diff --git a/component/admin/access.xml b/component/admin/access.xml index 641339d232c..b6712e3108b 100644 --- a/component/admin/access.xml +++ b/component/admin/access.xml @@ -5,54 +5,64 @@
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -69,18 +79,18 @@ - - - - - - - - - - - - + + + + + + + + + + + + \ No newline at end of file diff --git a/component/admin/layouts/component/full/header/menu.php b/component/admin/layouts/component/full/header/menu.php index 4b22cb50ca5..ba85b7da81b 100644 --- a/component/admin/layouts/component/full/header/menu.php +++ b/component/admin/layouts/component/full/header/menu.php @@ -11,32 +11,34 @@ extract($displayData); -$logoutUrl = JRoute::_('index.php?option=com_login&task=logout&' . JSession::getFormToken() . '=1'); -$user = JFactory::getUser(); +$logoutUrl = JRoute::_('index.php?option=com_login&task=logout&' . JSession::getFormToken() . '=1'); +$user = JFactory::getUser(); ?> diff --git a/component/admin/layouts/component/full/sidebar.php b/component/admin/layouts/component/full/sidebar.php index dc1c9a79f8f..0e9144c7f00 100644 --- a/component/admin/layouts/component/full/sidebar.php +++ b/component/admin/layouts/component/full/sidebar.php @@ -12,5 +12,5 @@ ?> diff --git a/component/admin/layouts/component/full/sidebar/link.php b/component/admin/layouts/component/full/sidebar/link.php index 8c37e2918b8..39234d05fb3 100644 --- a/component/admin/layouts/component/full/sidebar/link.php +++ b/component/admin/layouts/component/full/sidebar/link.php @@ -1,4 +1,5 @@ input->getCmd('view'); ?> - + diff --git a/component/admin/layouts/component/full/sidebar/menu.php b/component/admin/layouts/component/full/sidebar/menu.php index 7e6683311b8..03cc94dbb91 100644 --- a/component/admin/layouts/component/full/sidebar/menu.php +++ b/component/admin/layouts/component/full/sidebar/menu.php @@ -1,4 +1,5 @@ - + diff --git a/component/admin/layouts/component/full/tab/layout.php b/component/admin/layouts/component/full/tab/layout.php index dfd9ed15caa..842237ff4a5 100644 --- a/component/admin/layouts/component/full/tab/layout.php +++ b/component/admin/layouts/component/full/tab/layout.php @@ -1,4 +1,5 @@
- loadTemplate($row->param); ?> + loadTemplate($row->param); ?>
diff --git a/component/admin/layouts/component/full/tab/link.php b/component/admin/layouts/component/full/tab/link.php index 327e8dd272f..dc69632a834 100644 --- a/component/admin/layouts/component/full/tab/link.php +++ b/component/admin/layouts/component/full/tab/link.php @@ -1,4 +1,5 @@ diff --git a/component/admin/layouts/component/full/tab/main.php b/component/admin/layouts/component/full/tab/main.php index bad45ffb1c0..575eea1b68d 100644 --- a/component/admin/layouts/component/full/tab/main.php +++ b/component/admin/layouts/component/full/tab/main.php @@ -1,4 +1,5 @@
-
-
-
- -
-
-
+
+
+
+ +
+
+
-
-
- - $row, 'view' => $view)); ?> - -
-
+
+
+ + $row, 'view' => $view) + ); ?> + +
+
diff --git a/component/admin/layouts/component/image.php b/component/admin/layouts/component/image.php index 1717dfc4421..fbeadde7d6e 100644 --- a/component/admin/layouts/component/image.php +++ b/component/admin/layouts/component/image.php @@ -15,44 +15,44 @@ ?>
- +
-get('USE_IMAGE_SIZE_SWAPPING') - ); -?> -
- - - - -
+ get('USE_IMAGE_SIZE_SWAPPING') + ); + ?> +
+ + + + +
-
-
+
+
-
- -
+
+ +
diff --git a/component/admin/layouts/config/config.php b/component/admin/layouts/config/config.php index c6c6cbe9c0e..a9c975df8fb 100644 --- a/component/admin/layouts/config/config.php +++ b/component/admin/layouts/config/config.php @@ -25,11 +25,11 @@ $id = (isset($id)) ? $id : ''; ?> - +
- +
diff --git a/component/admin/layouts/config/group.php b/component/admin/layouts/config/group.php index 5acf7e8339f..59a8cf38dde 100644 --- a/component/admin/layouts/config/group.php +++ b/component/admin/layouts/config/group.php @@ -13,9 +13,9 @@ * Layout variables * ========================= * - * @var array $displayData List of data - * @var string $title Title of this config field - * @var string $content Description of this config field. + * @var array $displayData List of data + * @var string $title Title of this config field + * @var string $content Description of this config field. */ extract($displayData); ?> diff --git a/component/admin/layouts/fields/display.php b/component/admin/layouts/fields/display.php index 3ae978c61d4..e91318ad5ab 100644 --- a/component/admin/layouts/fields/display.php +++ b/component/admin/layouts/fields/display.php @@ -14,5 +14,5 @@ ?> - + diff --git a/component/admin/layouts/inline/text.php b/component/admin/layouts/inline/text.php index 9369dd91456..1a0a7b9519d 100644 --- a/component/admin/layouts/inline/text.php +++ b/component/admin/layouts/inline/text.php @@ -28,5 +28,5 @@ class="form-control edit-inline" data-original-value="" disabled="disabled" style="display: none;"/>
- +
diff --git a/component/admin/layouts/joomla/form/renderfield.php b/component/admin/layouts/joomla/form/renderfield.php index 4b426264a5f..782954a49e8 100644 --- a/component/admin/layouts/joomla/form/renderfield.php +++ b/component/admin/layouts/joomla/form/renderfield.php @@ -17,10 +17,9 @@ * $input : (string) The input field html code */ -if (!empty($displayData['options']['showonEnabled'])) -{ - JHtml::_('jquery.framework'); - JHtml::_('script', 'jui/cms.js', false, true); +if (!empty($displayData['options']['showonEnabled'])) { + JHtml::_('jquery.framework'); + JHtml::_('script', 'jui/cms.js', false, true); } $class = empty($displayData['options']['class']) ? "" : " " . $displayData['options']['class']; @@ -28,11 +27,11 @@ ?>
> - - - + + +
- +
diff --git a/component/admin/layouts/joomla/form/renderlabel.php b/component/admin/layouts/joomla/form/renderlabel.php index 3c78a38abcd..b5058300fc3 100644 --- a/component/admin/layouts/joomla/form/renderlabel.php +++ b/component/admin/layouts/joomla/form/renderlabel.php @@ -24,28 +24,26 @@ $desc = $displayData['description']; $for = $displayData['for']; $req = $displayData['required']; -$classes = array_filter((array) $displayData['classes']); +$classes = array_filter((array)$displayData['classes']); $position = $displayData['position']; $id = $for . '-lbl'; $title = ''; // If a description is specified, use it to build a tooltip. -if (!empty($desc)) -{ - JHtml::_('redshopjquery.popover'); - $classes[] = 'hasPopover'; - $title = ' title="' . trim($text) . '" data-content="' . trim($desc) . '"'; +if (!empty($desc)) { + JHtml::_('redshopjquery.popover'); + $classes[] = 'hasPopover'; + $title = ' title="' . trim($text) . '" data-content="' . trim($desc) . '"'; } // If required, there's a class for that. -if ($req) -{ - $classes[] = 'required'; +if ($req) { + $classes[] = 'required'; } ?> diff --git a/component/admin/layouts/joomla/system/message.php b/component/admin/layouts/joomla/system/message.php index 4c0b86d812a..2e4abc5f999 100644 --- a/component/admin/layouts/joomla/system/message.php +++ b/component/admin/layouts/joomla/system/message.php @@ -12,27 +12,26 @@ extract($displayData); // Nothing to show -if (!is_array($msgList) || empty($msgList)) -{ - return; +if (!is_array($msgList) || empty($msgList)) { + return; } $allowedTypes = array('error', 'message', 'notice', 'warning'); ?>
-
- $msgs): ?> - + $msgs): ?> + $type, - 'messages' => $msgs - ); + $layoutData = array( + 'type' => $type, + 'messages' => $msgs + ); - echo JLayoutHelper::render('joomla.system.message.' . strtolower($type), $layoutData); - ?> - -
+ echo JLayoutHelper::render('joomla.system.message.' . strtolower($type), $layoutData); + ?> + +
diff --git a/component/admin/layouts/joomla/system/message/error.php b/component/admin/layouts/joomla/system/message/error.php index e0cd7fd7cc4..1cd09a59540 100644 --- a/component/admin/layouts/joomla/system/message/error.php +++ b/component/admin/layouts/joomla/system/message/error.php @@ -12,20 +12,19 @@ extract($displayData); // Nothing to show -if (empty($messages)) -{ - return; +if (empty($messages)) { + return; } ?> diff --git a/component/admin/layouts/joomla/system/message/message.php b/component/admin/layouts/joomla/system/message/message.php index 9855d38768e..35214f2a4fa 100644 --- a/component/admin/layouts/joomla/system/message/message.php +++ b/component/admin/layouts/joomla/system/message/message.php @@ -12,20 +12,19 @@ extract($displayData); // Nothing to show -if (empty($messages)) -{ - return; +if (empty($messages)) { + return; } ?> diff --git a/component/admin/layouts/joomla/system/message/notice.php b/component/admin/layouts/joomla/system/message/notice.php index 303c8b6eb53..c8647ecc425 100644 --- a/component/admin/layouts/joomla/system/message/notice.php +++ b/component/admin/layouts/joomla/system/message/notice.php @@ -12,20 +12,19 @@ extract($displayData); // Nothing to show -if (empty($messages)) -{ - return; +if (empty($messages)) { + return; } ?> diff --git a/component/admin/layouts/joomla/system/message/warning.php b/component/admin/layouts/joomla/system/message/warning.php index 0c09fb1a41c..913330c3452 100644 --- a/component/admin/layouts/joomla/system/message/warning.php +++ b/component/admin/layouts/joomla/system/message/warning.php @@ -12,15 +12,15 @@ extract($displayData); ?> - + diff --git a/component/admin/layouts/pagination/link.php b/component/admin/layouts/pagination/link.php index df7ebda0889..49a35f6ef0e 100644 --- a/component/admin/layouts/pagination/link.php +++ b/component/admin/layouts/pagination/link.php @@ -1,4 +1,5 @@ text; -switch ((string) $item->text) -{ - // Check for "Start" item - case JText::_('JLIB_HTML_START') : - $icon = 'icon-fast-backward icon-first'; - break; - - // Check for "Prev" item - case $item->text === JText::_('JPREV') : - $item->text = JText::_('JPREVIOUS'); - $icon = 'icon-step-backward icon-previous'; - break; - - // Check for "Prev" item - case $item->text == JText::_('LIB_REDCORE_PREVIOUS_10') : - $icon = "icon-backward"; - break; - - // Check for "Next" item - case JText::_('JNEXT') : - $icon = 'icon-step-forward icon-next'; - break; - - // Check for "Next" item - case JText::_('LIB_REDCORE_NEXT_10') : - $icon = "icon-forward"; - break; - - // Check for "End" item - case JText::_('JLIB_HTML_END') : - $icon = 'icon-fast-forward icon-last'; - break; - - default: - $icon = null; - break; +switch ((string)$item->text) { + // Check for "Start" item + case JText::_('JLIB_HTML_START') : + $icon = 'icon-fast-backward icon-first'; + break; + + // Check for "Prev" item + case $item->text === JText::_('JPREV') : + $item->text = JText::_('JPREVIOUS'); + $icon = 'icon-step-backward icon-previous'; + break; + + // Check for "Prev" item + case $item->text == JText::_('LIB_REDCORE_PREVIOUS_10') : + $icon = "icon-backward"; + break; + + // Check for "Next" item + case JText::_('JNEXT') : + $icon = 'icon-step-forward icon-next'; + break; + + // Check for "Next" item + case JText::_('LIB_REDCORE_NEXT_10') : + $icon = "icon-forward"; + break; + + // Check for "End" item + case JText::_('JLIB_HTML_END') : + $icon = 'icon-fast-forward icon-last'; + break; + + default: + $icon = null; + break; } -if ($icon !== null) -{ - $display = ''; +if ($icon !== null) { + $display = ''; } -if ($displayData['active']) -{ - if ($item->base > 0) - { - $limit = 'limitstart.value=' . $item->base; - } - else - { - $limit = 'limitstart.value=0'; - } - - $cssClasses = array(); - - $title = ''; - - if (!is_numeric($item->text)) - { - JHtml::_('bootstrap.tooltip'); - $cssClasses[] = 'hasTooltip'; - $title = ' title="' . $item->text . '" '; - } - - $onClick = ''; - $href = trim($item->link); - - // Still using javascript approach in backend - if (JFactory::getApplication()->isAdmin()) - { - $onClick = 'onclick="document.adminForm.' . $item->prefix . $limit - . '; Joomla.submitform(document.forms[\'' . $item->formName . '\'].task.value, document.forms[\'' . $item->formName . '\']);return false;"'; - $href = '#'; - } -} -else -{ - $class = (property_exists($item, 'active') && $item->active) ? 'active' : 'disabled'; +if ($displayData['active']) { + if ($item->base > 0) { + $limit = 'limitstart.value=' . $item->base; + } else { + $limit = 'limitstart.value=0'; + } + + $cssClasses = array(); + + $title = ''; + + if (!is_numeric($item->text)) { + JHtml::_('bootstrap.tooltip'); + $cssClasses[] = 'hasTooltip'; + $title = ' title="' . $item->text . '" '; + } + + $onClick = ''; + $href = trim($item->link); + + // Still using javascript approach in backend + if (JFactory::getApplication()->isAdmin()) { + $onClick = 'onclick="document.adminForm.' . $item->prefix . $limit + . '; Joomla.submitform(document.forms[\'' . $item->formName . '\'].task.value, document.forms[\'' . $item->formName . '\']);return false;"'; + $href = '#'; + } +} else { + $class = (property_exists($item, 'active') && $item->active) ? 'active' : 'disabled'; } ?> -
  • - - - - href="" - > - - -
  • +
  • + + + + href="" + > + + +
  • -
  • - -
  • +
  • + +
  • $page) - { - if (!$page['active']) - { - $currentPage = $k; - } - } +if (!empty($pages['pages'])) { + foreach ($pages['pages'] as $k => $page) { + if (!$page['active']) { + $currentPage = $k; + } + } } -if ($currentPage >= $step) -{ - if ($currentPage % $step === 0) - { - $range = ceil($currentPage / $step) + 1; - } - else - { - $range = ceil($currentPage / $step); - } +if ($currentPage >= $step) { + if ($currentPage % $step === 0) { + $range = ceil($currentPage / $step) + 1; + } else { + $range = ceil($currentPage / $step); + } } ?> diff --git a/component/admin/layouts/product_detail/product_attribute.php b/component/admin/layouts/product_detail/product_attribute.php index 9c220bd8d9b..bfa5909a388 100644 --- a/component/admin/layouts/product_detail/product_attribute.php +++ b/component/admin/layouts/product_detail/product_attribute.php @@ -1,4 +1,5 @@ detail->product_id)) -{ - $productId = $data->detail->product_id; +if (isset($data->detail->product_id)) { + $productId = $data->detail->product_id; } -if (isset($data->detail->attribute_set_id)) -{ - $attributeSetId = $data->detail->attribute_set_id; +if (isset($data->detail->attribute_set_id)) { + $attributeSetId = $data->detail->attribute_set_id; } JText::script('COM_REDSHOP_ATTRIBUTE_NAME'); @@ -53,158 +52,166 @@ ?>
    - -lists['attributes']) -{ - foreach ($data->lists['attributes'] as $keyAttr => $attributeData) - { - $displayType = $attributeData['display_type']; - $attributeId = $attributeData['attribute_id']; - $checkedRequired = ($attributeData['attribute_required'] == 1) ? ' checked="checked"' : ''; - $multipleSelection = ($attributeData['allow_multiple_selection'] == 1) ? ' checked="checked"' : ''; - $hideAttributePrice = ($attributeData['hide_attribute_price'] == 1) ? ' checked="checked"' : ''; - $attributePublished = ($attributeData['attribute_published'] == 1) ? ' checked="checked"' : ''; - $attrPref = 'attribute[' . $keyAttr . ']'; - ?> - - - : - - - -
    - - - -
    -
    -
    -
    - - -
    - -
    - - -
    - -
    - - -
    -
    - - -
    -
    - - -
    -
    - -
    - -
    - value="1"/> - - -
    - -
    - /> - - -
    - -
    - /> - - -
    - -
    - value="1"/> - - -
    -
    -
    - - - -
    - -
    - - + - - $property) - { - $propPref = $attrPref . '[property][' . $keyProperty . ']'; - - echo RedshopLayoutHelper::render( - 'product_detail.product_property', - array( - 'keyAttr' => $keyAttr, - 'keyProperty' => $keyProperty, - 'property' => $property, - 'propPref' => $propPref, - 'productId' => $productId, - 'attributeId' => $attributeId, - 'data' => $data - ) - ); - } - ?> -
    -
    - -
    - - + + lists['attributes']) { + foreach ($data->lists['attributes'] as $keyAttr => $attributeData) { + $displayType = $attributeData['display_type']; + $attributeId = $attributeData['attribute_id']; + $checkedRequired = ($attributeData['attribute_required'] == 1) ? ' checked="checked"' : ''; + $multipleSelection = ($attributeData['allow_multiple_selection'] == 1) ? ' checked="checked"' : ''; + $hideAttributePrice = ($attributeData['hide_attribute_price'] == 1) ? ' checked="checked"' : ''; + $attributePublished = ($attributeData['attribute_published'] == 1) ? ' checked="checked"' : ''; + $attrPref = 'attribute[' . $keyAttr . ']'; + ?> + + + : + + + +
    + + + +
    +
    +
    +
    + + +
    + +
    + + +
    + +
    + + +
    +
    + + +
    +
    + + +
    +
    + +
    + +
    + + value="1"/> + + +
    + +
    + /> + + +
    + +
    + /> + + +
    + +
    + + value="1"/> + + +
    +
    +
    + + + +
    + +
    + + + + + $property) { + $propPref = $attrPref . '[property][' . $keyProperty . ']'; + + echo RedshopLayoutHelper::render( + 'product_detail.product_property', + array( + 'keyAttr' => $keyAttr, + 'keyProperty' => $keyProperty, + 'property' => $property, + 'propPref' => $propPref, + 'productId' => $productId, + 'attributeId' => $attributeId, + 'data' => $data + ) + ); + } + ?> +
    +
    + +
    + +
    diff --git a/component/admin/layouts/product_detail/product_property.php b/component/admin/layouts/product_detail/product_property.php index 11bced97456..e0aa9c92978 100644 --- a/component/admin/layouts/product_detail/product_property.php +++ b/component/admin/layouts/product_detail/product_property.php @@ -1,4 +1,5 @@ property_id; -$totalSubProp = (isset($property->subvalue)) ? count($property->subvalue) : 0; +$propertyId = $property->property_id; +$totalSubProp = (isset($property->subvalue)) ? count($property->subvalue) : 0; $propertyPublished = ($property->property_published == 1) ? 'checked="checked"' : ''; -$style = ($totalSubProp) ? 'style="display:block;"' : 'style="display:none;"'; +$style = ($totalSubProp) ? 'style="display:block;"' : 'style="display:none;"'; -$propertyImage = ''; +$propertyImage = ''; $propertyImageThumb = ''; -if ($property->property_image && JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . 'product_attributes/' . $property->property_image)) -{ - $propertyImage = REDSHOP_FRONT_IMAGES_ABSPATH . 'product_attributes/' . $property->property_image; - - $propertyImageThumb = RedshopHelperMedia::getImagePath( - $property->property_image, - '', - 'thumb', - 'product_attributes', - 100, - 0, - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') - ); +if ($property->property_image && JFile::exists( + REDSHOP_FRONT_IMAGES_RELPATH . 'product_attributes/' . $property->property_image + )) { + $propertyImage = REDSHOP_FRONT_IMAGES_ABSPATH . 'product_attributes/' . $property->property_image; + + $propertyImageThumb = RedshopHelperMedia::getImagePath( + $property->property_image, + '', + 'thumb', + 'product_attributes', + 100, + 0, + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') + ); } -$mainImage = ''; +$mainImage = ''; $mainImageThumb = ''; -if ($property->property_main_image && JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . 'property/' . $property->property_main_image)) -{ - $mainImage = REDSHOP_FRONT_IMAGES_ABSPATH . 'property/' . $property->property_main_image; - - $mainImageThumb = RedshopHelperMedia::getImagePath( - $property->property_main_image, - '', - 'thumb', - 'property', - 120, - 0, - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') - ); +if ($property->property_main_image && JFile::exists( + REDSHOP_FRONT_IMAGES_RELPATH . 'property/' . $property->property_main_image + )) { + $mainImage = REDSHOP_FRONT_IMAGES_ABSPATH . 'property/' . $property->property_main_image; + + $mainImageThumb = RedshopHelperMedia::getImagePath( + $property->property_main_image, + '', + 'thumb', + 'property', + 120, + 0, + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') + ); } ?> - : property_name; ?> - + : property_name; ?> + diff --git a/component/admin/layouts/product_detail/product_subproperty.php b/component/admin/layouts/product_detail/product_subproperty.php index 9b70c56c661..0a9a46c9026 100644 --- a/component/admin/layouts/product_detail/product_subproperty.php +++ b/component/admin/layouts/product_detail/product_subproperty.php @@ -1,4 +1,5 @@ subattribute_published == 1) ? 'checked="checked"' : ''; -$subPropertyImage = ''; +$subPropertyImage = ''; $subPropertyImageThumb = ''; -if ($subProperty->subattribute_color_image && JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . 'subcolor/' . $subProperty->subattribute_color_image)) -{ - $subPropertyImage = REDSHOP_FRONT_IMAGES_ABSPATH . 'subcolor/' . $subProperty->subattribute_color_image; - - $subPropertyImageThumb = RedshopHelperMedia::getImagePath( - $subProperty->subattribute_color_image, - '', - 'thumb', - 'subcolor', - 50, - 0, - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') - ); +if ($subProperty->subattribute_color_image && JFile::exists( + REDSHOP_FRONT_IMAGES_RELPATH . 'subcolor/' . $subProperty->subattribute_color_image + )) { + $subPropertyImage = REDSHOP_FRONT_IMAGES_ABSPATH . 'subcolor/' . $subProperty->subattribute_color_image; + + $subPropertyImageThumb = RedshopHelperMedia::getImagePath( + $subProperty->subattribute_color_image, + '', + 'thumb', + 'subcolor', + 50, + 0, + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') + ); } -$mainImage = ''; +$mainImage = ''; $mainImageThumb = ''; -if ($subProperty->subattribute_color_main_image && JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . 'subproperty/' . $subProperty->subattribute_color_main_image)) -{ - $mainImage = REDSHOP_FRONT_IMAGES_ABSPATH . 'subproperty/' . $subProperty->subattribute_color_main_image; - - $mainImageThumb = RedshopHelperMedia::getImagePath( - $subProperty->subattribute_color_main_image, - '', - 'thumb', - 'subproperty', - 100, - 0, - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') - ); +if ($subProperty->subattribute_color_main_image && JFile::exists( + REDSHOP_FRONT_IMAGES_RELPATH . 'subproperty/' . $subProperty->subattribute_color_main_image + )) { + $mainImage = REDSHOP_FRONT_IMAGES_ABSPATH . 'subproperty/' . $subProperty->subattribute_color_main_image; + + $mainImageThumb = RedshopHelperMedia::getImagePath( + $subProperty->subattribute_color_main_image, + '', + 'thumb', + 'subproperty', + 100, + 0, + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') + ); } ?>
    -
    -
    - - - - - -
    -
    - - - lists['prop_oprand'], $subPropPref . '[oprand]', 'text-center input-xmini', 'value', 'text', $subProperty->oprand); ?> - - -
    -
    - - -
    -
    - - -
    -
    - - - - - - - get('USE_STOCKROOM')): ?> - - - - -
    - -
    - - name="[published]" value="1"/> -
    - -
    - - setdefault_selected == 1) ? 'checked' : ''; ?> /> -
    - -
    - -
    - -
    - -
    - -
    - - - -
    -
    - - - - - - - - - - - -
    -
    -
    - -
    - - - -
    -
    - - - - - - - - - - - -
    -
    -
    -
    - -dispatcher. - * This is used for integration with other redSHOP extensions which can extend product type. - */ - - if ($productId && !empty($subProperty->subattribute_color_id)) - { - $data->dispatcher->trigger('productTypeSubPropertyValue', array($property, $subProperty)); - } -?> +
    +
    + + + + + +
    +
    + + + lists['prop_oprand'], + $subPropPref . '[oprand]', + 'text-center input-xmini', + 'value', + 'text', + $subProperty->oprand + ); ?> + + +
    +
    + + +
    +
    + + +
    +
    + + + + + + + get('USE_STOCKROOM')): ?> + + + + +
    + +
    + + name="[published]" + value="1"/> +
    + +
    + + setdefault_selected == 1) ? 'checked' : ''; ?> /> +
    + +
    + +
    + +
    + +
    + +
    + + + +
    +
    + + + + + + + + + + + +
    +
    +
    + +
    + + + +
    +
    + + + + + + + + + + + +
    +
    +
    +
    + + dispatcher. + * This is used for integration with other redSHOP extensions which can extend product type. + */ + + if ($productId && !empty($subProperty->subattribute_color_id)) { + $data->dispatcher->trigger('productTypeSubPropertyValue', array($property, $subProperty)); + } + ?>
    diff --git a/component/admin/layouts/searchtools/default.php b/component/admin/layouts/searchtools/default.php index 7c4afe6d219..907a066cd61 100755 --- a/component/admin/layouts/searchtools/default.php +++ b/component/admin/layouts/searchtools/default.php @@ -16,12 +16,15 @@ // Set some basic options $customOptions = array( - 'filtersHidden' => isset($data['options']['filtersHidden']) ? $data['options']['filtersHidden'] : empty($data['view']->activeFilters), - 'defaultLimit' => isset($data['options']['defaultLimit']) ? $data['options']['defaultLimit'] : JFactory::getApplication()->get('list_limit', 20), - 'searchFieldSelector' => '#filter_search', - 'orderFieldSelector' => '#list_fullordering', - 'totalResults' => isset($data['options']['totalResults']) ? $data['options']['totalResults'] : -1, - 'noResultsText' => isset($data['options']['noResultsText']) ? $data['options']['noResultsText'] : JText::_('JGLOBAL_NO_MATCHING_RESULTS'), + 'filtersHidden' => isset($data['options']['filtersHidden']) ? $data['options']['filtersHidden'] : empty($data['view']->activeFilters), + 'defaultLimit' => isset($data['options']['defaultLimit']) ? $data['options']['defaultLimit'] : JFactory::getApplication( + )->get('list_limit', 20), + 'searchFieldSelector' => '#filter_search', + 'orderFieldSelector' => '#list_fullordering', + 'totalResults' => isset($data['options']['totalResults']) ? $data['options']['totalResults'] : -1, + 'noResultsText' => isset($data['options']['noResultsText']) ? $data['options']['noResultsText'] : JText::_( + 'JGLOBAL_NO_MATCHING_RESULTS' + ), ); $data['options'] = array_merge($customOptions, $data['options']); @@ -32,24 +35,24 @@ JHtml::_('searchtools.form', $formSelector, $data['options']); $filtersClass = isset($data['view']->activeFilters) && $data['view']->activeFilters ? ' js-stools-container-filters-visible' : ''; -$showFilter = isset($data['options']['showFilter']) ? (boolean) $data['options']['showFilter'] : true; +$showFilter = isset($data['options']['showFilter']) ? (boolean)$data['options']['showFilter'] : true; ?>
    -
    -
    - -
    -
    - -
    -
    - - -
    - -
    - +
    +
    + +
    +
    + +
    +
    + + +
    + +
    +
    - + diff --git a/component/admin/layouts/searchtools/default/bar.php b/component/admin/layouts/searchtools/default/bar.php index 62fa53a2d9b..6cdfc939b09 100755 --- a/component/admin/layouts/searchtools/default/bar.php +++ b/component/admin/layouts/searchtools/default/bar.php @@ -16,9 +16,8 @@ // Receive overridable options $data['options'] = !empty($data['options']) ? $data['options'] : array(); -if (is_array($data['options'])) -{ - $data['options'] = new Registry($data['options']); +if (is_array($data['options'])) { + $data['options'] = new Registry($data['options']); } // Options @@ -29,20 +28,21 @@ ?> - -
    -
    - input; ?> - - -
    -
    - -
    - -
    - - + +
    +
    + input; ?> + + +
    +
    + +
    + +
    + + filterForm->getGroup('filter'); -foreach ($filters as $field) -{ - if ($showonstring = $field->getAttribute('showon')) - { - $showonarr = array(); +foreach ($filters as $field) { + if ($showonstring = $field->getAttribute('showon')) { + $showonarr = array(); - foreach (preg_split('%\[AND\]|\[OR\]%', $showonstring) as $showonfield) - { - $showon = explode(':', $showonfield, 2); - $showonarr[] = array( - 'field' => $showon[0], - 'values' => explode(',', $showon[1]), - 'op' => (preg_match('%\[(AND|OR)\]' . $showonfield . '%', $showonstring, $matches)) ? $matches[1] : '' - ); - } + foreach (preg_split('%\[AND\]|\[OR\]%', $showonstring) as $showonfield) { + $showon = explode(':', $showonfield, 2); + $showonarr[] = array( + 'field' => $showon[0], + 'values' => explode(',', $showon[1]), + 'op' => (preg_match( + '%\[(AND|OR)\]' . $showonfield . '%', + $showonstring, + $matches + )) ? $matches[1] : '' + ); + } - $data['view']->filterForm->setFieldAttribute($field->fieldname, 'dataShowOn', json_encode($showonarr), $field->group); - } + $data['view']->filterForm->setFieldAttribute( + $field->fieldname, + 'dataShowOn', + json_encode($showonarr), + $field->group + ); + } } // Load the form filters $filters = $data['view']->filterForm->getGroup('filter'); ?> - $field) : ?> - - getAttribute('dataShowOn')) - { - JHtml::_('jquery.framework'); - JHtml::_('script', 'jui/cms.js', false, true); - $showOn = " data-showon='" . $showOnData . "'"; - } - ?> -
    > - input; ?> -
    - - + $field) : ?> + + getAttribute('dataShowOn')) { + JHtml::_('jquery.framework'); + JHtml::_('script', 'jui/cms.js', false, true); + $showOn = " data-showon='" . $showOnData . "'"; + } + ?> +
    > + input; ?> +
    + + diff --git a/component/admin/layouts/searchtools/default/list.php b/component/admin/layouts/searchtools/default/list.php index ea777b3c333..57b0a78dac0 100755 --- a/component/admin/layouts/searchtools/default/list.php +++ b/component/admin/layouts/searchtools/default/list.php @@ -15,11 +15,11 @@ $list = $data['view']->filterForm->getGroup('list'); ?> -
    - $field) : ?> -
    - input ?> -
    - -
    +
    + $field) : ?> +
    + input ?> +
    + +
    diff --git a/component/admin/layouts/searchtools/default/noitems.php b/component/admin/layouts/searchtools/default/noitems.php index 1da23a91d89..007cef16efc 100755 --- a/component/admin/layouts/searchtools/default/noitems.php +++ b/component/admin/layouts/searchtools/default/noitems.php @@ -12,5 +12,5 @@ $data = $displayData; ?>
    - +
    diff --git a/component/admin/layouts/searchtools/grid/sort.php b/component/admin/layouts/searchtools/grid/sort.php index 686d76546bf..892b3b93e30 100755 --- a/component/admin/layouts/searchtools/grid/sort.php +++ b/component/admin/layouts/searchtools/grid/sort.php @@ -15,9 +15,11 @@ JHtml::_('bootstrap.popover'); ?> -icon)) : ?> -title)) : ?>title); ?> -order == $data->selected) : ?> + data-order="order; ?>" data-direction="direction); ?>" + data-name="title); ?>" + title="" + data-content="" data-placement="top"> + icon)) : ?> + title)) : ?>title); ?> + order == $data->selected) : ?> diff --git a/component/admin/layouts/templates/mail_template_tag.php b/component/admin/layouts/templates/mail_template_tag.php index f346ec7b421..094d471d123 100644 --- a/component/admin/layouts/templates/mail_template_tag.php +++ b/component/admin/layouts/templates/mail_template_tag.php @@ -1,4 +1,5 @@ -

    - {product_name} {product_link} {user_question} {answer} {user_telephone_lbl} {user_telephone} {user_address_lbl} {user_address} - -

    - {name} {discount} {coupon_code} - -

    - {name} {discount} - - {order_information_lbl} {order_id_lbl} {order_id} {order_number_lbl} {order_number} {order_date_lbl} {order_date}
    - {order_status_lbl} {order_status} {billing_address_information_lbl} {billing_address}
    - {shipping_address_information_lbl} {shipping_address} {order_detail_lbl} {product_name_lbl}
    - {note_lbl} {quantity_lbl} {product_loop_start} {product_name} {product_userfields} {product_wrapper} {product_quantity} {product_loop_end}
    - {order_payment_status} {shipping_method_lbl} {shipping_method} {shipping_rate_name} {order_detail_link} - -

    - {name} {discount} {days} {coupon_code} -

    - {name} - -

    - {name} - -

    - {name} {discount} {days} {coupon_code} - -

    - {name} {discount} {days} {coupon_code} - -

    - {name} - -

    - {fullname} {order_id} {order_number} {order_date} {product_serial_loop_start} {token} {product_serial_number} {product_name} {product_serial_loop_end} - -

    - {name} {order_id} {order_number} {order_date} {order_comment} - - {name} {url} {coupon_amount} {coupon_code} {coupon_duration} - - {giftcard_price_lbl} {giftcard_reciver_name_lbl} {giftcard_reciver_email_lbl} {giftcard_price} {giftcard_reciver_name} {giftcard_reciver_email} {giftcard_desc} {giftcard_price}
    - {giftcard_validity_from} {giftcard_validity_to} {giftcard_image} {giftcard_validity} {giftcard_code_lbl} {giftcard_code} - -

    - {invoice_number} - {order_information_lbl} {order_id_lbl} {order_id} {order_number_lbl} {order_number} {order_date_lbl} {order_date} {order_status_lbl} {order_status}
    - {billing_address_information_lbl} {billing_address} {shipping_address_information_lbl} {shipping_address} {order_detail_lbl} {product_name_lbl}
    - product_name} {product_number} {note_lbl} {product_wrapper} {price_lbl}
    - {product_price} {product_sku} {quantity_lbl} {product_quantity} {total_price_lbl}
    - {product_total_price} {order_subtotal_lbl} {order_subtotal} {if discount} {order_discount} {discount_in_percentage} {discount end if} {if vat} {order_tax} {vat end if}
    - {total_lbl} {order_total} {order_detail_link} {payment_lbl} {payment_method}
    - {shipping_lbl} {order_shipping} {shipping_method_lbl} {shipping_method} {customer_note_lbl} {customer_note} {requisition_number_lbl} {requisition_number} {if payment_discount} {payment_discount_lbl} {payment_order_discount} {payment_discount end if}
    - {discount_type_lbl} {discount_type} {product_userfields} {shipping} {shipping_excl_vat} {product_subtotal} {product_subtotal_excl_vat} {sub_total_vat} {discount_excl_vat} {total_excl_vat}
    - {denotation_label} {discount_denotation} {discount_excl_vat} {shipping_denotation} {shipping_excl_vat} {discount_excl_vat} {product_attribute_number} {order_detail_link_lbl}
    - {product_attribute} {product_accessory} {special_discount} {special_discount_amount} {download_token} {download_token_lbl} {referral_code}
    - {product_subtotal_lbl} {product_subtotal_excl_vat_lbl} {shipping_with_vat_lbl} {shipping_excl_vat_lbl} {product_price_excl_lbl} {shipping_rate_name}
    - {order_shipping_shop_location} {order_payment_status} {payment_extrainfo} {payment_extrafields_lbl} {payment_extrafields} {shipping_extrafields_lbl} {shipping_extrafields} - -

    - {username} {email} - - {shopname} {link} {name} - -

    - {order_mail_intro_text_title} {order_mail_intro_text} {order_information_lbl} {order_id_lbl} {order_id} {order_number_lbl} {order_number}
    - {order_date_lbl} {order_date} {order_status_lbl} {order_status} {billing_address_information_lbl}
    - {billing_address} {shipping_address_information_lbl} {shipping_address} {order_detail_lbl} {product_name_lbl} {stock_status} {tracking_number_lbl} {tracking_number} {tracking_url}
    - {product_name} {product_s_desc} {product_number} {note_lbl} {product_wrapper} {price_lbl}
    - {product_price} {product_sku} {quantity_lbl} {product_quantity} {total_price_lbl} {product_total_price} {order_subtotal_lbl} {order_subtotal} {if discount} {order_discount} {discount_in_percentage} {discount end if} {if vat} {order_tax} {vat end if} {total_lbl}
    - {order_total} {order_detail_link} {payment_lbl} {payment_method} {shipping_lbl}
    - {order_shipping} {shipping_method_lbl} {shipping_method} {customer_note_lbl} {customer_note} {requisition_number_lbl} {requisition_number} {if payment_discount} {payment_discount_lbl} {payment_order_discount} {payment_discount end if} {discount_type_lbl} {discount_type} {product_userfields}
    - {fullname} {firstname} {lastname} {shipping} {shipping_excl_vat} {product_subtotal} {product_subtotal_excl_vat} {sub_total_vat} {discount_excl_vat} {total_excl_vat}
    - {denotation_label} {discount_denotation} {discount_excl_vat} {shipping_denotation} {shipping_excl_vat} {discount_excl_vat} {payment_extrainfo} {product_attribute_number}
    - {order_detail_link_lbl} {product_attribute} {product_attribute_loop_start} {product_attribute_name} {product_attribute_value} {product_attribute_value_price} {product_attribute_calculated_price} {product_attribute_loop_end} {product_accessory} {special_discount} {special_discount_amount} {download_token} {download_token_lbl} {referral_code} {product_subtotal_lbl} {product_subtotal_excl_vat_lbl}
    - {shipping_with_vat_lbl} {shipping_excl_vat_lbl} {product_price_excl_lbl} {shipping_rate_name} {order_shipping_shop_location} {order_payment_status} {transaction_id_label} {transaction_id} {payment_extrafields_lbl} {payment_extrafields} {shipping_extrafields_lbl} {shipping_extrafields} {order_transfee_label} {order_transfee} {order_total_incl_transfee} - -

    - {fullname} {email} {order_id} {order_number} {order_date} {customer_note_lbl} {customer_note} {order_detail_link_lbl} {order_detail_link} {customer_id} {order_track_url} - - {firstname} {lastname} {product_name} {subsciption_enddate} {subscription_period} {subscription_price} {product_link} - -

    - {quotation_information_lbl} {quotation_id_lbl} {quotation_id} {quotation_number_lbl} {quotation_number} {quotation_date_lbl} {quotation_date}
    - {quotation_status_lbl} {quotation_status} {quotation_note_lbl} {quotation_note} {quotation_customer_note_lbl} {quotation_customer_note}
    - {billing_address_information_lbl} {billing_address} {quotation_detail_lbl} {product_name_lbl} {product_name} {product_number_lbl} {product_number} {product_s_desc}
    - {note_lbl} {product_wrapper} {price_lbl} {product_price} {quantity_lbl} {product_quantity} {total_price_lbl} {product_total_price} {quotation_subtotal_lbl} {quotation_subtotal}
    - {quotation_vat_lbl} {quotation_vat} {total_lbl} {quotation_total} {quotation_discount_lbl} {quotation_discount} {quotation_detail_link} - - {username} {password} {link} - -

    - {shopname} {fullname} {firstname} {lastname} {name} {username} {password} {email} {account_link} - - {vat_number} {username} {company_name} {country} {state} {phone} {zipcode} {address} {city} - -

    - {username} {product_name} {product_link} {title} {comment} - - {friend_name} {your_name} {product_name} {product_desc} {product_url} - - {username} {shopname} {name} {company_name} {address} {city} {zipcode} {country} {phone} - - {name} {product_loop_start} {product_thumb_image} {product_name} {product_price} {product_loop_end} {from_name} - - {discount_code} {discount_value} {discount_voucher_product} {discount_start_date} {discount_end_date} - +

    + {product_name} {product_link} {user_question} {answer} {user_telephone_lbl} {user_telephone} {user_address_lbl} {user_address} + +

    + {name} {discount} {coupon_code} + +

    + {name} {discount} + + {order_information_lbl} {order_id_lbl} {order_id} {order_number_lbl} {order_number} {order_date_lbl} {order_date} +
    + {order_status_lbl} {order_status} {billing_address_information_lbl} {billing_address}
    + {shipping_address_information_lbl} {shipping_address} {order_detail_lbl} {product_name_lbl}
    + {note_lbl} {quantity_lbl} {product_loop_start} {product_name} {product_userfields} {product_wrapper} {product_quantity} {product_loop_end} +
    + {order_payment_status} {shipping_method_lbl} {shipping_method} {shipping_rate_name} {order_detail_link} + +

    + {name} {discount} {days} {coupon_code} +

    + {name} + +

    + {name} + +

    + {name} {discount} {days} {coupon_code} + +

    + {name} {discount} {days} {coupon_code} + +

    + {name} + +

    + {fullname} {order_id} {order_number} {order_date} {product_serial_loop_start} {token} {product_serial_number} {product_name} {product_serial_loop_end} + +

    + {name} {order_id} {order_number} {order_date} {order_comment} + + {name} {url} {coupon_amount} {coupon_code} {coupon_duration} + + {giftcard_price_lbl} {giftcard_reciver_name_lbl} {giftcard_reciver_email_lbl} {giftcard_price} {giftcard_reciver_name} {giftcard_reciver_email} {giftcard_desc} {giftcard_price} +
    + {giftcard_validity_from} {giftcard_validity_to} {giftcard_image} {giftcard_validity} {giftcard_code_lbl} {giftcard_code} + +

    + {invoice_number} + {order_information_lbl} {order_id_lbl} {order_id} {order_number_lbl} {order_number} {order_date_lbl} {order_date} {order_status_lbl} {order_status} +
    + {billing_address_information_lbl} {billing_address} {shipping_address_information_lbl} {shipping_address} {order_detail_lbl} {product_name_lbl} +
    + product_name} {product_number} {note_lbl} {product_wrapper} {price_lbl}
    + {product_price} {product_sku} {quantity_lbl} {product_quantity} {total_price_lbl}
    + {product_total_price} {order_subtotal_lbl} {order_subtotal} {if discount} {order_discount} {discount_in_percentage} {discount end if} {if vat} {order_tax} {vat end if} +
    + {total_lbl} {order_total} {order_detail_link} {payment_lbl} {payment_method}
    + {shipping_lbl} {order_shipping} {shipping_method_lbl} {shipping_method} {customer_note_lbl} {customer_note} {requisition_number_lbl} {requisition_number} {if payment_discount} {payment_discount_lbl} {payment_order_discount} {payment_discount end if} +
    + {discount_type_lbl} {discount_type} {product_userfields} {shipping} {shipping_excl_vat} {product_subtotal} {product_subtotal_excl_vat} {sub_total_vat} {discount_excl_vat} {total_excl_vat} +
    + {denotation_label} {discount_denotation} {discount_excl_vat} {shipping_denotation} {shipping_excl_vat} {discount_excl_vat} {product_attribute_number} {order_detail_link_lbl} +
    + {product_attribute} {product_accessory} {special_discount} {special_discount_amount} {download_token} {download_token_lbl} {referral_code} +
    + {product_subtotal_lbl} {product_subtotal_excl_vat_lbl} {shipping_with_vat_lbl} {shipping_excl_vat_lbl} {product_price_excl_lbl} {shipping_rate_name} +
    + {order_shipping_shop_location} {order_payment_status} {payment_extrainfo} {payment_extrafields_lbl} {payment_extrafields} {shipping_extrafields_lbl} {shipping_extrafields} + +

    + {username} {email} + + {shopname} {link} {name} + +

    + {order_mail_intro_text_title} {order_mail_intro_text} {order_information_lbl} {order_id_lbl} {order_id} {order_number_lbl} {order_number} +
    + {order_date_lbl} {order_date} {order_status_lbl} {order_status} {billing_address_information_lbl}
    + {billing_address} {shipping_address_information_lbl} {shipping_address} {order_detail_lbl} {product_name_lbl} {stock_status} {tracking_number_lbl} {tracking_number} {tracking_url} +
    + {product_name} {product_s_desc} {product_number} {note_lbl} {product_wrapper} {price_lbl}
    + {product_price} {product_sku} {quantity_lbl} {product_quantity} {total_price_lbl} {product_total_price} {order_subtotal_lbl} {order_subtotal} {if discount} {order_discount} {discount_in_percentage} {discount end if} {if vat} {order_tax} {vat end if} {total_lbl} +
    + {order_total} {order_detail_link} {payment_lbl} {payment_method} {shipping_lbl}
    + {order_shipping} {shipping_method_lbl} {shipping_method} {customer_note_lbl} {customer_note} {requisition_number_lbl} {requisition_number} {if payment_discount} {payment_discount_lbl} {payment_order_discount} {payment_discount end if} {discount_type_lbl} {discount_type} {product_userfields} +
    + {fullname} {firstname} {lastname} {shipping} {shipping_excl_vat} {product_subtotal} {product_subtotal_excl_vat} {sub_total_vat} {discount_excl_vat} {total_excl_vat} +
    + {denotation_label} {discount_denotation} {discount_excl_vat} {shipping_denotation} {shipping_excl_vat} {discount_excl_vat} {payment_extrainfo} {product_attribute_number} +
    + {order_detail_link_lbl} {product_attribute} {product_attribute_loop_start} {product_attribute_name} {product_attribute_value} {product_attribute_value_price} {product_attribute_calculated_price} {product_attribute_loop_end} {product_accessory} {special_discount} {special_discount_amount} {download_token} {download_token_lbl} {referral_code} {product_subtotal_lbl} {product_subtotal_excl_vat_lbl} +
    + {shipping_with_vat_lbl} {shipping_excl_vat_lbl} {product_price_excl_lbl} {shipping_rate_name} {order_shipping_shop_location} {order_payment_status} {transaction_id_label} {transaction_id} {payment_extrafields_lbl} {payment_extrafields} {shipping_extrafields_lbl} {shipping_extrafields} {order_transfee_label} {order_transfee} {order_total_incl_transfee} + +

    + {fullname} {email} {order_id} {order_number} {order_date} {customer_note_lbl} {customer_note} {order_detail_link_lbl} {order_detail_link} {customer_id} {order_track_url} + + {firstname} {lastname} {product_name} {subsciption_enddate} {subscription_period} {subscription_price} {product_link} + +

    + {quotation_information_lbl} {quotation_id_lbl} {quotation_id} {quotation_number_lbl} {quotation_number} {quotation_date_lbl} {quotation_date} +
    + {quotation_status_lbl} {quotation_status} {quotation_note_lbl} {quotation_note} {quotation_customer_note_lbl} {quotation_customer_note} +
    + {billing_address_information_lbl} {billing_address} {quotation_detail_lbl} {product_name_lbl} {product_name} {product_number_lbl} {product_number} {product_s_desc} +
    + {note_lbl} {product_wrapper} {price_lbl} {product_price} {quantity_lbl} {product_quantity} {total_price_lbl} {product_total_price} {quotation_subtotal_lbl} {quotation_subtotal} +
    + {quotation_vat_lbl} {quotation_vat} {total_lbl} {quotation_total} {quotation_discount_lbl} {quotation_discount} {quotation_detail_link} + + {username} {password} {link} + +

    + {shopname} {fullname} {firstname} {lastname} {name} {username} {password} {email} {account_link} + + {vat_number} {username} {company_name} {country} {state} {phone} {zipcode} {address} {city} + +

    + {username} {product_name} {product_link} {title} {comment} + + {friend_name} {your_name} {product_name} {product_desc} {product_url} + + {username} {shopname} {name} {company_name} {address} {city} {zipcode} {country} {phone} + + {name} {product_loop_start} {product_thumb_image} {product_name} {product_price} {product_loop_end} {from_name} + + {discount_code} {discount_value} {discount_voucher_product} {discount_start_date} {discount_end_date} +
    -
    +

    - - - $desc): ?> - - - - - - -
    - {} - - -
    + + + $desc): ?> + + + + + + +
    + {} + + +
    diff --git a/component/admin/layouts/templates/template_tag.php b/component/admin/layouts/templates/template_tag.php index 4daae761d2f..6fb4d626293 100644 --- a/component/admin/layouts/templates/template_tag.php +++ b/component/admin/layouts/templates/template_tag.php @@ -1,4 +1,5 @@ -

    - {if accessory_main} {accessory_main end if} {accessory_mainproduct_price} {accessory_main_image} {accessory_main_title} {accessory_main_short_desc} {accessory_main_readmore} {accessory_main_image_3} {accessory_main_image_2}
    - {accessory_product_start} {accessory_product_end} {accessory_title} {accessory_image} {accessory_price} {accessory_price_saving} {accessory_main_price}
    - {accessory_short_desc} {accessory_quantity} {product_number} {accessory_readmore} {accessory_image_3} {accessory_image_2}
    - {manufacturer_name} {manufacturer_link} {without_vat} {accessory_readmore_link} {accessory_add_chkbox_lbl} {accessory_quantity_lbl} {accessory_preview_image}
    - {selected_accessory_price} {accessory_add_chkbox} {attribute_template:attributes} {stock_status} - -

    - {welcome_introtext} {account_image} {account_title} {billing_address_start} {billing_address_end} - {fullname_lbl} {fullname} {vatnumber_lbl} {vatnumber} {email_lbl} {email} {address_lbl} {address} {city_lbl} {city}
    - {zipcode_lbl} {zipcode} {state_lbl} {state} {country_lbl} {country} {phone_lbl} {phone}{phone_optional} {company_name_lbl} {company_name} {requesting_tax_exempt_lbl} {requesting_tax_exempt} {edit_account_link} {customer_custom_fields}
    - {more_orders} {order_image} {order_title} {order_loop_start} {order_index} {order_id} {order_detail_link} {order_loop_end}
    - {coupon_image} {coupon_title} {coupon_loop_start} {coupon_code_lbl} {coupon_code} {coupon_value_lbl} {coupon_value} {coupon_loop_end}
    - {shipping_image} {shipping_title} {edit_shipping_link}
    - {quotation_image} {quotation_title} {quotation_loop_start} {quotation_index} {quotation_id} {quotation_detail_link} {quotation_loop_end}
    - {tag_image} {tag_title} {edit_tag_link}
    - {wishlist_image} {wishlist_title} {edit_wishlist_link}
    - {compare_image} {compare_title} {edit_compare_link} {logout_link} {newsletter_signup_chk} {newsletter_signup_lbl} {reserve_discount} {reserve_discount_lbl}
    - {product_serial_loop_start} {product_serial_image} {product_serial_title} {product_name} {product_serial_number} {product_serial_loop_end} - -

    - {addtocart_quantity_increase_decrease} {addtocart_link} {addtocart_quantity} {addtocart_image} {addtocart_image_aslink} {addtocart_button} {addtocart_tooltip} {quantity_lbl} - -

    - {ajax_cart_box_title} {show_cart_text} {show_cart_button} {continue_shopping_button} - -

    - {product_name} {product_price} {product_image} {attribute_template:attributes} {accessory_template:templatename} {if product_userfield} {product_userfield end if} - -

    - {user_email_lbl} {user_email} {user_name_lbl} {user_name} {user_question_lbl} {user_question} {user_telephone_lbl} {user_telephone} {user_address_lbl} {user_address} {send_button} {captcha_lbl} {captcha} - -

    - {attribute_title} {attribute_tooltip} {property_dropdown} {property_image_without_scroller} {property_image_scroller}
    - {subproperty_start} {property_title} {subproperty_dropdown} {subproperty_image_without_scroller} {subproperty_image_scroller} {subproperty_end} - -

    - {attribute_title} {property_image_lbl} {virtual_number_lbl} {property_name_lbl} {property_price_lbl} {property_stock_lbl} {add_to_cart_lbl} {property_start} {property_image} {virtual_number} {property_name} {property_price} {without_vat} {property_stock} {property_end} - -

    -

    - {account_creation_start}
    - {username_lbl}{username} - {password_lbl}{password} - {confirm_password_lbl}{confirm_password}
    - {newsletter_signup_chk}{newsletter_signup_lbl}
    - {account_creation_end}
    - {required_lbl}
    - {shipping_same_as_billing_lbl} {shipping_same_as_billing} - -

    - {cart_lbl} {product_price} {product_loop_start} {product_total_price} {product_name} {product_number}
    - {product_attribute} {product_attribute_loop_start} {product_attribute_name} {product_attribute_value} {product_attribute_value_price} {product_attribute_calculated_price} {product_attribute_loop_end} {attribute_label} {attribute_change} {product_accessory} {product_old_price} {product_customfields_lbl} {product_customfields} {product_subscription_lbl} {product_subscription} {product_wrapper} {discount_rule}
    - {update} {discount_form_lbl} {discount_form} {product_userfields} {coupon_code_lbl} {shipping_lbl} {total_lbl} {product_name_lbl} {price_lbl} {quantity_lbl} {total_price_lbl} {print} {product_thumb_image} {product_price_excl_vat} {product_total_price_excl_vat} {product_loop_end} {attribute_price_with_vat} {attribute_price_without_vat} {shipping}
    - {vat_info} {vat_shipping} {shipping_lbl} {product_subtotal} {shipping_excl_vat} {sub_total_vat} {discount_excl_vat} {total_excl_vat} {denotation_label} {discount_denotation} {discount_excl_vat}
    - {shipping_denotation} {shipping_excl_vat} {product_subtotal_lbl} {product_subtotal_excl_vat_lbl} {shipping_with_vat_lbl} {shipping_excl_vat_lbl} {product_price_excl_lbl} {product_name_nolink} {product_attribute_number} {tax_with_shipping_lbl} {product_subtotal} {product_subtotal_excl_vat} {total}
    - {update_cart} {quantity_increase_decrease} {remove_product} {empty_cart} {if discount} {discount_lbl} {order_discount} {discount_in_percentage} {discount end if} {totalpurchase_lbl}
    - {if vat} {vat_lbl} {tax} {vat end if} {checkout_button} {shop_more} - -

    - {name_lbl} {name} {email_lbl} {email_address} {submit_button_catalog} {catalog_select} - -

    - {product_name_lbl} {quantity_lbl} {print} {product_loop_start} {product_name} {product_attribute} {product_accessory} {product_wrapper} {product_userfields} {product_thumb_image} {update_cart} {remove_product} {product_loop_end} {update} {empty_cart} {coupon_code_lbl} {discount_form} {checkout_button} {shop_more} - -

    - {discount_type_lbl} {discount_type} {order_information_lbl} {print} {order_id_lbl} {order_id} {order_number_lbl} {order_number} {order_date_lbl} {order_date} {order_status_lbl} {order_status} {billing_address_information_lbl} {billing_address} {shipping_address_info_lbl} {shipping_address} {order_detail_lbl} {product_name_lbl} {note_lbl} {quantity_lbl} {product_loop_start} {product_name} {product_userfields} {customer_note} {product_quantity} {product_loop_end} - -

    - {product_name_lbl} {print} {quantity_lbl} {product_loop_start} {product_name} {product_userfields} {product_thumb_image} {product_quantity} {product_loop_end} {order_number_lbl} {order_number} {delivery_time_lbl} {delivery_time} {order_id} {order_id_lbl} {print} - -

    - {if subcats} {category_main_description} {category_main_short_desc} {category_main_name} {category_main_thumb_image} {subproductlimit:X} {subcats end if}
    - {category_loop_start} {category_loop_end} {category_name} {category_description} {category_short_desc} {category_thumb_image} {category_back_thumb_image} {category_thumb_image}
    - {product_price_lbl} {product_price_slider} {include_product_in_sub_cat} {product_loop_start} {product_loop_end} {product_name} {product_price} {product_rating_summary} {product_s_desc}
    - {pagination} {perpagelimit:X} {product_display_limit} {show_all_products_in_category} {order_by} {if product_on_sale} {product_on_sale end if} {price_excluding_vat}
    - {more_documents} {product_id_lbl} {product_id} {product_number_lbl} {product_number} {product_discount_price} {product_old_price} {product_price_saving} {product_price_saving_percentage} {with_vat} {without_vat} {filter_by}
    - {template_selector_category_lbl} {template_selector_category} {manufacturer_link} {manufacturer_name} {stock_status:class for available stock : class for out of stock: class for pre order} {shopname} {read_more} {category_readmore} {category_main_thumb_image_2} {category_main_thumb_image_3} {category_thumb_image_2} {category_thumb_image_3}
    - {product_stock_amount_image} {product_price_table} {product_thumb_image_3} {product_thumb_image_2} {discount_start_date} {discount_end_date} {compare_products_button} {compare_product_div} {front_img_link} {back_img_link} {product_preview_img} {read_more_link} {product_name_nolink} {category_product_link}
    - {order_by_lbl} {filter_by_lbl} {returntocategory_link} {returntocategory_name} {returntocategory} {category_total_product_lbl} {category_total_product} {product_delivery_time} {delivery_time_lbl} {product_length} {product_width} {product_height} {front_preview_img_link} {back_preview_img_link} {if product_userfield} {product_userfield end if} - -

    - {print} {filter_by_lbl} {filter_by} {order_by_lbl} {order_by} {category_frontpage_introtext} {template_selector_category} {template_selector_category_lbl} {category_loop_start} {category_thumb_image} {category_back_thumb_image} {category_name} {category_description} {category_thumb_image_2} {category_thumb_image_3} {category_readmore} {category_short_desc} {category_total_product_lbl} {category_total_product} {product_loop_start} {product_thumb_image} {product_name} {product_price} {read_more} {attribute_template:attributes} {form_addtocart:add_to_cart1} {product_id_lbl} {product_id} {product_thumb_image_3} {product_thumb_image_2} {product_number_lbl} {product_number} {product_size} {product_length} {product_width} {product_height} {read_more_link} {product_s_desc} {product_desc} {product_rating_summary} {manufacturer_link} {manufacturer_name} {manufacturer_product_link} {if product_userfield} {product_userfield end if} {product_loop_end} {category_loop_end} {pagination} - -

    - {apply_button} {cancel_button} - -

    - {product_name} {product_number} {product_thumb_image} {checkout_button} {terms_and_conditions} {product_subtotal} {product_subtotal_excl_vat} {total} {shop_more} {shipping}
    - {product_price} {update_cart} {product_total_price} {product_loop_start} {product_attribute} {product_attribute_loop_start} {product_attribute_name} {product_attribute_value} {product_attribute_value_price} {product_attribute_loop_end} {attribute_label} {product_accessory} {product_wrapper} {product_userfields} {coupon_code_lbl} {if discount} {discount_lbl} {order_discount} {discount_in_percentage} {discount end if} {totalpurchase_lbl}
    - {if vat} {vat_lbl} {tax} {vat end if} {shipping_lbl} {total_lbl} {product_name_lbl} {price_lbl} {quantity_lbl} {total_price_lbl} {product_loop_end} {product_thumb_image} {product_price_excl_vat} {product_total_price_excl_vat}
    - {attribute_price_with_vat} {attribute_price_without_vat} {vat_shipping} {shipping_lbl} {customer_note_lbl} {customer_note} {requisition_number_lbl} {requisition_number} {shipping_excl_vat} {sub_total_vat} {discount_excl_vat} {total_excl_vat} {denotation_label} {discount_denotation} {discount_excl_vat} {shipping_denotation} {shipping_excl_vat} {checkout_back_button} {product_attribute_number} {thirdparty_email} {thirdparty_email_lbl} {quotation_request} - -

    - {order_id} {order_status} {customer_name} {payment_status} - -

    -

    - {email_lbl}{email} - {retype_email_lbl}{retype_email}
    - {company_name_lbl}{company_name} - {vat_number_lbl}{vat_number} - {firstname_lbl}{firstname} - {lastname_lbl}{lastname} - {address_lbl}{address} - {zipcode_lbl}{zipcode} - {city_lbl}{city} - {country_lbl}{country} - {state_lbl}{state} - {phone_lbl}{phone}{phone_optional} - {tax_exempt_lbl}{tax_exempt}

    -

    - {ean_number_lbl}{ean_number}
    - {company_extrafield} - -

    - {print} {compare_product_heading} {returntocategory_name} {returntocategory_link} {remove_all} {expand_collapse}
    - {product_name} {product_image} {manufacturer_name} {discount_start_date} {discount_end_date} {product_price}
    - {product_s_desc} {product_desc} {product_rating_summary} {product_delivery_time} {product_number}
    - {products_in_stock} {product_stock_amount_image} {product_weight} {product_length} {product_height} {product_width}
    - {product_availability_date} {product_volume} {product_category} {remove} {add_to_cart} {product_field} - -

    - {category_frontpage_introtext} {category_frontpage_loop_start} {category_thumb_image} {category_back_thumb_image} {category_name} {category_frontpage_loop_end} {pagination} {print} {category_thumb_image_2} {category_thumb_image_3} {category_readmore} {category_description} {category_short_desc} {category_total_product} {category_total_product_lbl} - -

    - {customer_quantity_lbl} {customer_quantity} {customer_amount_lbl} {customer_amount} {giftcard_name} {giftcard_desc} {giftcard_image}
    - {giftcard_price_lbl} {giftcard_price} {giftcard_value_lbl} {giftcard_value}
    - {giftcard_validity} {giftcard_validity_from} {giftcard_validity_to} {giftcard_reciver_name_lbl} {giftcard_reciver_name} {giftcard_reciver_email_lbl} {giftcard_reciver_email} {form_addtocart:cart_templatename}
    - {if giftcard_userfield} {giftcard_userfield end if} - -

    - {giftcard_loop_start} {giftcard_name} {giftcard_desc} {giftcard_readmore} {giftcard_value_lbl} {giftcard_value} {giftcard_price_lbl} {giftcard_price} {giftcard_validity} {giftcard_loop_end} - -

    - {order_by} {manufacturer_loop_start} {manufacturer_loop_end} {manufacturer_name} {manufacturer_image} {manufacturer_description} {manufacturer_link} {manufacturer_allproductslink} {print} {pagination} - -

    - {manufacturer_name} {manufacturer_image} {manufacturer_description} {category_name} {category_thumb_image} {category_desc} {category_name_with_link} {category_loop_start} {category_loop_end} {manufacturer_url} {manufacturer_allproductslink_lbl} {manufacturer_allproductslink} {manufacturer_extra_fields} - -

    - {order_by} {filter_by}
    - {product_loop_start} {category_heading_start} {category_name} {category_heading_end} {product_name} {product_thumb_image} {product_thumb_image_2} {product_thumb_image_3} {product_price} {product_s_desc}
    - {product_old_price} {product_price_saving} {product_price_saving_percentage} {product_loop_end} {manufacturer_product_link} {form_addtocart:add_to_cart1} {print} {product_id_lbl} {product_id} {product_number} {product_number_lbl} {product_desc} {read_more} {read_more_link} {manufacturer_image} {manufacturer_name} {manufacturer_description} {manufacturer_extra_fields} {manufacturer_link} {pagination} - -

    - {data} {username} {email} {unsubscribe_link} - -

    - {product_name} {product_price} {product_thumb_image} {product_s_desc} {product_desc} {unsubscribe_link} - -

    - {billing_template} {billing_address_information_lbl} {edit_billing_address} {billing_address} {shipping_address_information_lbl} {shipping_address} - -

    - {order_id} {order_number} {order_date} {order_status} {order_status_log} {order_status_order_only_lbl} {order_status_payment_only_lbl} {order_status_order_only} {order_status_payment_only} {tracking_number_lbl} {tracking_number} {tracking_url}
    - {billing_address} {shipping_address} {product_name} {product_number} {product_wrapper}
    - {product_price} {product_attribute_loop_start} {product_attribute_name} {product_attribute_value} {product_attribute_value_price} {product_attribute_calculated_price} {product_attribute_loop_end} {attribute_label} {product_quantity} {product_total_price} {order_subtotal} {order_total}
    - {order_information_lbl} {order_id_lbl} {order_number_lbl} {order_date_lbl} {order_status_lbl}
    - {billing_address_information_lbl} {shipping_address_information_lbl} {order_detail_lbl} {product_name_lbl} {note_lbl} {price_lbl}
    - {quantity_lbl} {total_price_lbl} {order_subtotal_lbl} {if discount} {discount_lbl} {order_discount} {discount_in_percentage} {discount end if} {if vat} {vat_lbl}
    - {order_tax} {vat end if} {shipping_lbl} {total_lbl} {payment_lbl} {payment_method} {customer_note_lbl} {customer_note} {requisition_number_lbl}
    - {requisition_number} {shipping_method_lbl} {shipping_method} {if payment_discount} {payment_discount_lbl} {payment_order_discount} {payment_discount end if} {product_userfields}
    - {print} {product_attribute} {product_accessory} {product_number_lbl} {product_subscription_lbl} {product_subscription}
    - {product_price_excl_vat} {product_total_price_excl_vat} {product_subtotal_excl_vat} {order_subtotal_excl_vat}
    - {tax} {reorder_button} {shipping} {vat_shipping} {shipping_lbl}
    - {download_date_list_lbl} {download_date_list} {download_counter_lbl} {download_counter} {download_date_lbl} {download_date} {download_token_lbl} {download_token}
    - {product_subtotal} {shipping_excl_vat} {product_subtotal} {sub_total_vat} {discount_excl_vat} {total_excl_vat} {denotation_label} {discount_denotation} {discount_excl_vat}
    - {shipping_denotation} {shipping_excl_vat} {product_s_desc} {product_thumb_image} {product_old_price} {special_discount} {special_discount_amount}
    - {payment_extrafields_lbl} {payment_extrafields} {shipping_extrafields_lbl} {shipping_extrafields} {product_gift} - -

    - {order_id} {order_number} {order_date} {order_status} {order_status_order_only_lbl}{order_status_payment_only_lbl} {order_status_order_only} {order_status_payment_only}
    - {billing_address} {shipping_address} {product_name} {product_number} {product_attribute_loop_start} {product_attribute_name} {product_attribute_value} {product_attribute_value_price} {product_attribute_loop_end} {attribute_label} {product_wrapper}
    - {product_price} {product_quantity} {product_total_price} {order_subtotal} {order_total}
    - {order_information_lbl} {order_id_lbl} {order_number_lbl} {order_date_lbl} {order_status_lbl} {billing_address_information_lbl} {shipping_address_information_lbl}
    - {order_detail_lbl} {product_name_lbl} {note_lbl} {price_lbl} {quantity_lbl} {total_price_lbl} {order_subtotal_lbl} {if discount} {discount_lbl} {order_discount} {discount_in_percentage} {discount end if} {if vat} {vat_lbl}
    - {order_tax} {vat end if} {shipping_lbl} {total_lbl} {payment_lbl} {payment_method} {customer_note_lbl} {customer_note} {requisition_number_lbl} {requisition_number}
    - {shipping_method_lbl} {shipping_method} {if payment_discount} {payment_discount_lbl} {payment_order_discount} {payment_discount end if}
    - {product_userfields} {print} {special_discount} {special_discount_amount} - -

    - {product_loop_start} {product_loop_end} {product_name} {product_number}
    - {product_attribute_loop_start} {product_attribute_name} {product_attribute_value} {product_attribute_value_price} {product_attribute_calculated_price} {product_attribute_loop_end} {attribute_label} {product_wrapper} {product_price} {product_quantity} {product_total_price} {order_subtotal} {tracking_number_lbl} {tracking_number} {tracking_url}
    - {order_id} {order_number} {order_shipping} {order_total} {delivery_time} {payment_status} {print}{delivery_time_lbl}
    - {if discount} {discount_lbl} {order_discount} {discount_in_percentage} {discount end if} {if vat} {vat_lbl} {order_tax} {vat end if} {shipping_lbl} {shipping_method_lbl} {shipping_method}
    - {if payment_discount} {payment_discount_lbl} {payment_order_discount} {payment_discount end if}
    - {product_userfields} {shipping} {vat_shipping} {shipping_lbl}
    - {download_date_list_lbl} {download_date_list} {download_counter_lbl} {download_counter} {download_date_lbl} {download_date} {download_token_lbl} {download_token}
    - {product_subtotal} {product_subtotal_excl_vat} {shipping_excl_vat} {product_subtotal} {sub_total_vat} {discount_excl_vat} {total_excl_vat} {denotation_label} {discount_denotation}
    - {discount_excl_vat} {shipping_denotation} {shipping_excl_vat} {payment_extrafields_lbl} {payment_extrafields} {shipping_extrafields_lbl} {shipping_extrafields} {product_gift} - -

    - {order_id_lbl} {product_name_lbl} {total_price_lbl} {order_date_lbl} {order_status_lbl} {order_detail_lbl} {product_loop_start} {order_id} {order_products} {order_total} {order_date} {order_status} {order_detail_link} {reorder_link} {product_loop_end} {pagination} {print} {order_number} {pagination_limit} - -

    -

    - {email_lbl}{email} - {firstname_lbl}{firstname} - {lastname_lbl}{lastname} - {address_lbl}{address} - {zipcode_lbl}{zipcode} - {city_lbl}{city} - {country_lbl}{country} - {state_lbl}{state} - {phone_lbl}{phone}{phone_optional} - {private_extrafield}
    - {retype_email_lbl}{retype_email} - -

    - {product_name} {manufacturer_name} {supplier_name} {publish_date} {update_date}
    - {discount_start_date} {discount_end_date} {product_discount_price} {product_old_price} {product_price_saving} {product_price_saving_percentage} {if product_on_sale}
    - {product_on_sale end if} {product_price_lbl} {if product_special} {product_special end if} {product_name} {product_price} {lowest_price} {highest_price}
    - {product_thumb_image} {product_thumb_image_2} {product_thumb_image_3} {product_s_desc} {product_rating} {more_images} {more_documents} {more_videos}
    - {product_desc} {bookmark} {send_to_friend} {ask_question_about_product} {ask_question_about_product_without_lightbox} {manufacturer_product_link} {product_rating_summary}
    - {product_delivery_time} {manufacturer_link} {form_rating} {form_rating_without_lightbox} {product_id_lbl} {product_id}
    - {product_number_lbl} {product_number} {product_price_table} {products_in_stock} {if product_userfield} {product_userfield end if}
    - {delivery_time_lbl} {with_vat} {without_vat} {discount_calculator} {facebook_like_button} {googleplus1}
    - {returntocategory_name} {returntocategory_link} {product_size}
    - {component_heading} {returntocategory} {navigation_link_right} {product_weight} {product_weight_lbl}
    - {child_products} {product_volume} {product_volume_lbl} {product_price_novat} {price_excluding_vat}
    - {more_images_3} {more_images_2} {product_stock_amount_image}
    - {wishlist_button} {wishlist_link} {compare_products_button} {compare_product_div} {my_tags_button} {subscription} {ajaxdetail_template:templatename} {accessory_template:templatename}
    - {question_loop_start} {question} {question_owner} {question_date} {answer_loop_start} {answer} {answer_owner} {answer_date} {answer_loop_end} {question_loop_end}
    - {product_length} {product_width} {product_height}
    - {front_img_link} {back_img_link} {category_product_img} {category_front_img_link} {category_back_img_link} {product_preview_img} {diameter} {product_diameter_lbl} {manufacturer_image}
    - {back_link} {product_length_lbl} {product_width_lbl} {product_height_lbl} {min_order_product_quantity} {print} {product_category_list} {stock_notify_flag} {product_availability_date}
    - {stock_status} {product_gift_table} - -

    - {product_thumb_image} {product_thumb_image_2} {product_thumb_image_3} {product_name} {product_desc} {product_price} {read_more} {attribute_template:attributes} {form_addtocart:add_to_cart1} - -

    - {name_lbl} {name} {email_lbl} {email_address} {address_fields} {submit_button_sample} {product_samples} - -

    - {cart_lbl} {print} {product_name_lbl} {quantity_lbl} {product_loop_start} {product_name} {product_attribute} {product_accessory} {product_wrapper} {product_userfields} {product_thumb_image} {update_cart} {remove_product} {product_loop_end} {update} {empty_cart} {checkout_button} {shop_more} - -

    - {print} {quotation_information_lbl} {quotation_id_lbl} {quotaion_id} {quotation_number_lbl} {quotation_number} {quotation_date_lbl} {quotation_date} {quotation_status_lbl} {quotation_status} {quotation_note_lbl} {quotation_note} {account_information_lbl} {account_information} {quotation_detail_lbl} {product_name_lbl} {note_lbl} {price_lbl} {quantity_lbl} {total_price_lbl} {product_loop_start} {product_name} {product_attribute} {product_accessory} {product_number_lbl} {product_number} {product_price} {product_quantity} {product_total_price} {product_loop_end} {product_userfields} {quotation_subtotal_lbl} {quotation_subtotal} {total_lbl} {quotation_total} {quotation_discount_lbl} {quotation_discount} {quotation_custom_field_list} - -

    - {order_detail_lbl} {product_name_lbl} {quantity_lbl} {product_loop_start} {product_name} {product_attribute} {product_accessory} {product_userfields} {update_cart} {product_wrapper} {product_loop_end} {customer_note_lbl} {customer_note} {billing_address_information_lbl} {billing_address} {cancel_btn} {request_quotation_btn} {quotation_custom_field_list} - -

    - {search_tag_display} {product_loop_start} {product_loop_end} {product_name} {product_price} {product_thumb_image}
    - {product_s_desc} {read_more} {product_id_lbl} {product_id} {product_number_lbl} {product_number} {manufacturer_link} {manufacturer_name} {order_by} {pagination}
    - {perpagelimit:X} {product_display_limit} {attribute_template:attributes} - -

    - {payment_heading} {payment_loop_start} {payment_method_name} {creditcard_information} {payment_extrafields} {payment_loop_end} - -

    - {shipping_heading} {shipping_method_loop_start} {shipping_method_title} {shipping_rate_loop_start} {shipping_rate_name} {shipping_rate} {shipping_location} {shipping_rate_loop_end} {shipping_method_loop_end} - -

    - {relproduct_link} {relproduct_image} {relproduct_name} {relproduct_price} {relproduct_number} {relproduct_number_lbl} {read_more} {relproduct_old_price} {relproduct_price_table} {relproduct_price_saving}
    - {related_product_start} {related_product_end} {relproduct_s_desc} {relproduct_rating_summary} {relproduct_price_novat} {relproduct_old_price_lbl} {relproduct_image_2} {relproduct_image_3}
    - {attribute_template:templatename} {form_addtocart:templatename} {producttag:rs_field}
    - {stock_status} {relproduct_attribute_pricelist} {manufacturer_name} {manufacturer_link} {read_more_link} - -

    - {show_all_images_rating} {rating_statistics} {product_loop_start} {product_title} {images}
    - {review_loop_start} {fullname} {title} {comment} {stars} {reviewdate} {review_loop_end} {product_loop_end} - -

    - {order_information_lbl} {order_id_lbl} {order_id} {order_number_lbl} {order_number} {order_date_lbl} {order_date} {order_status_lbl} {order_status} {customer_note_lbl} {customer_note} {billing_address_information_lbl} {billing_address} {shipping_address_information_lbl} {shipping_address} {order_detail_lbl}
    - {product_loop_start} {product_name_lbl} {note_lbl} {price_lbl} {quantity_lbl} {total_price_lbl} {product_name} {product_number} {product_userfields} {product_attribute} {product_accessory} {product_wrapper} {product_price} {product_quantity} {product_total_price} {product_loop_end}
    - {if vat} {vat_lbl} {order_tax} {vat end if}
    - {if discount} {discount_lbl} {order_discount} {discount end if}
    - {order_subtotal_lbl} {product_subtotal} {shipping_lbl} {shipping_excl_vat} {total_lbl} {order_total} {order_payment_status} {shipping_method_lbl} {shipping_method} {order_detail_link} - -

    -

    - {firstname_st_lbl}{firstname_st}
    - {lastname_st_lbl}{lastname_st}
    - {address_st_lbl}{address_st}
    - {zipcode_st_lbl}{zipcode_st}
    - {city_st_lbl}{city_st}
    - {country_st_lbl}{country_st}
    - {state_st_lbl}{state_st}
    - {phone_st_lbl}{phone_st}

    +switch ($name) { + case 'accessory': + ?> +

    + {if accessory_main} {accessory_main end if} {accessory_mainproduct_price} {accessory_main_image} {accessory_main_title} {accessory_main_short_desc} {accessory_main_readmore} {accessory_main_image_3} {accessory_main_image_2} +
    + {accessory_product_start} {accessory_product_end} {accessory_title} {accessory_image} {accessory_price} {accessory_price_saving} {accessory_main_price} +
    + {accessory_short_desc} {accessory_quantity} {product_number} {accessory_readmore} {accessory_image_3} {accessory_image_2} +
    + {manufacturer_name} {manufacturer_link} {without_vat} {accessory_readmore_link} {accessory_add_chkbox_lbl} {accessory_quantity_lbl} {accessory_preview_image} +
    + {selected_accessory_price} {accessory_add_chkbox} {attribute_template:attributes} {stock_status} + +

    + {welcome_introtext} {account_image} {account_title} {billing_address_start} {billing_address_end} + {fullname_lbl} {fullname} {vatnumber_lbl} {vatnumber} {email_lbl} {email} {address_lbl} {address} {city_lbl} {city} +
    + {zipcode_lbl} {zipcode} {state_lbl} {state} {country_lbl} {country} {phone_lbl} {phone}{phone_optional} {company_name_lbl} {company_name} {requesting_tax_exempt_lbl} {requesting_tax_exempt} {edit_account_link} {customer_custom_fields} +
    + {more_orders} {order_image} {order_title} {order_loop_start} {order_index} {order_id} {order_detail_link} {order_loop_end} +
    + {coupon_image} {coupon_title} {coupon_loop_start} {coupon_code_lbl} {coupon_code} {coupon_value_lbl} {coupon_value} {coupon_loop_end} +
    + {shipping_image} {shipping_title} {edit_shipping_link}
    + {quotation_image} {quotation_title} {quotation_loop_start} {quotation_index} {quotation_id} {quotation_detail_link} {quotation_loop_end} +
    + {tag_image} {tag_title} {edit_tag_link}
    + {wishlist_image} {wishlist_title} {edit_wishlist_link}
    + {compare_image} {compare_title} {edit_compare_link} {logout_link} {newsletter_signup_chk} {newsletter_signup_lbl} {reserve_discount} {reserve_discount_lbl} +
    + {product_serial_loop_start} {product_serial_image} {product_serial_title} {product_name} {product_serial_number} {product_serial_loop_end} + +

    + {addtocart_quantity_increase_decrease} {addtocart_link} {addtocart_quantity} {addtocart_image} {addtocart_image_aslink} {addtocart_button} {addtocart_tooltip} {quantity_lbl} + +

    + {ajax_cart_box_title} {show_cart_text} {show_cart_button} {continue_shopping_button} + +

    + {product_name} {product_price} {product_image} {attribute_template:attributes} {accessory_template:templatename} {if product_userfield} {product_userfield end if} + +

    + {user_email_lbl} {user_email} {user_name_lbl} {user_name} {user_question_lbl} {user_question} {user_telephone_lbl} {user_telephone} {user_address_lbl} {user_address} {send_button} {captcha_lbl} {captcha} + +

    + {attribute_title} {attribute_tooltip} {property_dropdown} {property_image_without_scroller} {property_image_scroller} +
    + {subproperty_start} {property_title} {subproperty_dropdown} {subproperty_image_without_scroller} {subproperty_image_scroller} {subproperty_end} + +

    + {attribute_title} {property_image_lbl} {virtual_number_lbl} {property_name_lbl} {property_price_lbl} {property_stock_lbl} {add_to_cart_lbl} {property_start} {property_image} {virtual_number} {property_name} {property_price} {without_vat} {property_stock} {property_end} + +

    +

    + {account_creation_start}
    + {username_lbl}{username} + {password_lbl}{password} + {confirm_password_lbl}{confirm_password}
    + {newsletter_signup_chk}{newsletter_signup_lbl}
    + {account_creation_end}
    + {required_lbl}
    + {shipping_same_as_billing_lbl} {shipping_same_as_billing} + +

    + {cart_lbl} {product_price} {product_loop_start} {product_total_price} {product_name} {product_number}
    + {product_attribute} {product_attribute_loop_start} {product_attribute_name} {product_attribute_value} {product_attribute_value_price} {product_attribute_calculated_price} {product_attribute_loop_end} {attribute_label} {attribute_change} {product_accessory} {product_old_price} {product_customfields_lbl} {product_customfields} {product_subscription_lbl} {product_subscription} {product_wrapper} {discount_rule} +
    + {update} {discount_form_lbl} {discount_form} {product_userfields} {coupon_code_lbl} {shipping_lbl} {total_lbl} {product_name_lbl} {price_lbl} {quantity_lbl} {total_price_lbl} {print} {product_thumb_image} {product_price_excl_vat} {product_total_price_excl_vat} {product_loop_end} {attribute_price_with_vat} {attribute_price_without_vat} {shipping} +
    + {vat_info} {vat_shipping} {shipping_lbl} {product_subtotal} {shipping_excl_vat} {sub_total_vat} {discount_excl_vat} {total_excl_vat} {denotation_label} {discount_denotation} {discount_excl_vat} +
    + {shipping_denotation} {shipping_excl_vat} {product_subtotal_lbl} {product_subtotal_excl_vat_lbl} {shipping_with_vat_lbl} {shipping_excl_vat_lbl} {product_price_excl_lbl} {product_name_nolink} {product_attribute_number} {tax_with_shipping_lbl} {product_subtotal} {product_subtotal_excl_vat} {total} +
    + {update_cart} {quantity_increase_decrease} {remove_product} {empty_cart} {if discount} {discount_lbl} {order_discount} {discount_in_percentage} {discount end if} {totalpurchase_lbl} +
    + {if vat} {vat_lbl} {tax} {vat end if} {checkout_button} {shop_more} + +

    + {name_lbl} {name} {email_lbl} {email_address} {submit_button_catalog} {catalog_select} + +

    + {product_name_lbl} {quantity_lbl} {print} {product_loop_start} {product_name} {product_attribute} {product_accessory} {product_wrapper} {product_userfields} {product_thumb_image} {update_cart} {remove_product} {product_loop_end} {update} {empty_cart} {coupon_code_lbl} {discount_form} {checkout_button} {shop_more} + +

    + {discount_type_lbl} {discount_type} {order_information_lbl} {print} {order_id_lbl} {order_id} {order_number_lbl} {order_number} {order_date_lbl} {order_date} {order_status_lbl} {order_status} {billing_address_information_lbl} {billing_address} {shipping_address_info_lbl} {shipping_address} {order_detail_lbl} {product_name_lbl} {note_lbl} {quantity_lbl} {product_loop_start} {product_name} {product_userfields} {customer_note} {product_quantity} {product_loop_end} + +

    + {product_name_lbl} {print} {quantity_lbl} {product_loop_start} {product_name} {product_userfields} {product_thumb_image} {product_quantity} {product_loop_end} {order_number_lbl} {order_number} {delivery_time_lbl} {delivery_time} {order_id} {order_id_lbl} {print} + +

    + {if subcats} {category_main_description} {category_main_short_desc} {category_main_name} {category_main_thumb_image} {subproductlimit:X} {subcats end if} +
    + {category_loop_start} {category_loop_end} {category_name} {category_description} {category_short_desc} {category_thumb_image} {category_back_thumb_image} {category_thumb_image} +
    + {product_price_lbl} {product_price_slider} {include_product_in_sub_cat} {product_loop_start} {product_loop_end} {product_name} {product_price} {product_rating_summary} {product_s_desc} +
    + {pagination} {perpagelimit:X} {product_display_limit} {show_all_products_in_category} {order_by} {if product_on_sale} {product_on_sale end if} {price_excluding_vat} +
    + {more_documents} {product_id_lbl} {product_id} {product_number_lbl} {product_number} {product_discount_price} {product_old_price} {product_price_saving} {product_price_saving_percentage} {with_vat} {without_vat} {filter_by} +
    + {template_selector_category_lbl} {template_selector_category} {manufacturer_link} {manufacturer_name} {stock_status:class for available stock : class for out of stock: class for pre order} {shopname} {read_more} {category_readmore} {category_main_thumb_image_2} {category_main_thumb_image_3} {category_thumb_image_2} {category_thumb_image_3} +
    + {product_stock_amount_image} {product_price_table} {product_thumb_image_3} {product_thumb_image_2} {discount_start_date} {discount_end_date} {compare_products_button} {compare_product_div} {front_img_link} {back_img_link} {product_preview_img} {read_more_link} {product_name_nolink} {category_product_link} +
    + {order_by_lbl} {filter_by_lbl} {returntocategory_link} {returntocategory_name} {returntocategory} {category_total_product_lbl} {category_total_product} {product_delivery_time} {delivery_time_lbl} {product_length} {product_width} {product_height} {front_preview_img_link} {back_preview_img_link} {if product_userfield} {product_userfield end if} + +

    + {print} {filter_by_lbl} {filter_by} {order_by_lbl} {order_by} {category_frontpage_introtext} {template_selector_category} {template_selector_category_lbl} {category_loop_start} {category_thumb_image} {category_back_thumb_image} {category_name} {category_description} {category_thumb_image_2} {category_thumb_image_3} {category_readmore} {category_short_desc} {category_total_product_lbl} {category_total_product} {product_loop_start} {product_thumb_image} {product_name} {product_price} {read_more} {attribute_template:attributes} {form_addtocart:add_to_cart1} {product_id_lbl} {product_id} {product_thumb_image_3} {product_thumb_image_2} {product_number_lbl} {product_number} {product_size} {product_length} {product_width} {product_height} {read_more_link} {product_s_desc} {product_desc} {product_rating_summary} {manufacturer_link} {manufacturer_name} {manufacturer_product_link} {if product_userfield} {product_userfield end if} {product_loop_end} {category_loop_end} {pagination} + +

    + {apply_button} {cancel_button} + +

    + {product_name} {product_number} {product_thumb_image} {checkout_button} {terms_and_conditions} {product_subtotal} {product_subtotal_excl_vat} {total} {shop_more} {shipping} +
    + {product_price} {update_cart} {product_total_price} {product_loop_start} {product_attribute} {product_attribute_loop_start} {product_attribute_name} {product_attribute_value} {product_attribute_value_price} {product_attribute_loop_end} {attribute_label} {product_accessory} {product_wrapper} {product_userfields} {coupon_code_lbl} {if discount} {discount_lbl} {order_discount} {discount_in_percentage} {discount end if} {totalpurchase_lbl} +
    + {if vat} {vat_lbl} {tax} {vat end if} {shipping_lbl} {total_lbl} {product_name_lbl} {price_lbl} {quantity_lbl} {total_price_lbl} {product_loop_end} {product_thumb_image} {product_price_excl_vat} {product_total_price_excl_vat} +
    + {attribute_price_with_vat} {attribute_price_without_vat} {vat_shipping} {shipping_lbl} {customer_note_lbl} {customer_note} {requisition_number_lbl} {requisition_number} {shipping_excl_vat} {sub_total_vat} {discount_excl_vat} {total_excl_vat} {denotation_label} {discount_denotation} {discount_excl_vat} {shipping_denotation} {shipping_excl_vat} {checkout_back_button} {product_attribute_number} {thirdparty_email} {thirdparty_email_lbl} {quotation_request} + +

    + {order_id} {order_status} {customer_name} {payment_status} + +

    +

    + {email_lbl}{email} + {retype_email_lbl}{retype_email}
    + {company_name_lbl}{company_name} + {vat_number_lbl}{vat_number} + {firstname_lbl}{firstname} + {lastname_lbl}{lastname} + {address_lbl}{address} + {zipcode_lbl}{zipcode} + {city_lbl}{city} + {country_lbl}{country} + {state_lbl}{state} + {phone_lbl}{phone}{phone_optional} + {tax_exempt_lbl}{tax_exempt}

    +

    + {ean_number_lbl}{ean_number}
    + {company_extrafield} + +

    + {print} {compare_product_heading} {returntocategory_name} {returntocategory_link} {remove_all} {expand_collapse} +
    + {product_name} {product_image} {manufacturer_name} {discount_start_date} {discount_end_date} {product_price} +
    + {product_s_desc} {product_desc} {product_rating_summary} {product_delivery_time} {product_number}
    + {products_in_stock} {product_stock_amount_image} {product_weight} {product_length} {product_height} {product_width} +
    + {product_availability_date} {product_volume} {product_category} {remove} {add_to_cart} {product_field} + +

    + {category_frontpage_introtext} {category_frontpage_loop_start} {category_thumb_image} {category_back_thumb_image} {category_name} {category_frontpage_loop_end} {pagination} {print} {category_thumb_image_2} {category_thumb_image_3} {category_readmore} {category_description} {category_short_desc} {category_total_product} {category_total_product_lbl} + +

    + {customer_quantity_lbl} {customer_quantity} {customer_amount_lbl} {customer_amount} {giftcard_name} {giftcard_desc} {giftcard_image} +
    + {giftcard_price_lbl} {giftcard_price} {giftcard_value_lbl} {giftcard_value}
    + {giftcard_validity} {giftcard_validity_from} {giftcard_validity_to} {giftcard_reciver_name_lbl} {giftcard_reciver_name} {giftcard_reciver_email_lbl} {giftcard_reciver_email} {form_addtocart:cart_templatename} +
    + {if giftcard_userfield} {giftcard_userfield end if} + +

    + {giftcard_loop_start} {giftcard_name} {giftcard_desc} {giftcard_readmore} {giftcard_value_lbl} {giftcard_value} {giftcard_price_lbl} {giftcard_price} {giftcard_validity} {giftcard_loop_end} + +

    + {order_by} {manufacturer_loop_start} {manufacturer_loop_end} {manufacturer_name} {manufacturer_image} {manufacturer_description} {manufacturer_link} {manufacturer_allproductslink} {print} {pagination} + +

    + {manufacturer_name} {manufacturer_image} {manufacturer_description} {category_name} {category_thumb_image} {category_desc} {category_name_with_link} {category_loop_start} {category_loop_end} {manufacturer_url} {manufacturer_allproductslink_lbl} {manufacturer_allproductslink} {manufacturer_extra_fields} + +

    + {order_by} {filter_by}
    + {product_loop_start} {category_heading_start} {category_name} {category_heading_end} {product_name} {product_thumb_image} {product_thumb_image_2} {product_thumb_image_3} {product_price} {product_s_desc} +
    + {product_old_price} {product_price_saving} {product_price_saving_percentage} {product_loop_end} {manufacturer_product_link} {form_addtocart:add_to_cart1} {print} {product_id_lbl} {product_id} {product_number} {product_number_lbl} {product_desc} {read_more} {read_more_link} {manufacturer_image} {manufacturer_name} {manufacturer_description} {manufacturer_extra_fields} {manufacturer_link} {pagination} + +

    + {data} {username} {email} {unsubscribe_link} + +

    + {product_name} {product_price} {product_thumb_image} {product_s_desc} {product_desc} {unsubscribe_link} + +

    + {billing_template} {billing_address_information_lbl} {edit_billing_address} {billing_address} {shipping_address_information_lbl} {shipping_address} + +

    + {order_id} {order_number} {order_date} {order_status} {order_status_log} {order_status_order_only_lbl} {order_status_payment_only_lbl} {order_status_order_only} {order_status_payment_only} {tracking_number_lbl} {tracking_number} {tracking_url} +
    + {billing_address} {shipping_address} {product_name} {product_number} {product_wrapper}
    + {product_price} {product_attribute_loop_start} {product_attribute_name} {product_attribute_value} {product_attribute_value_price} {product_attribute_calculated_price} {product_attribute_loop_end} {attribute_label} {product_quantity} {product_total_price} {order_subtotal} {order_total} +
    + {order_information_lbl} {order_id_lbl} {order_number_lbl} {order_date_lbl} {order_status_lbl}
    + {billing_address_information_lbl} {shipping_address_information_lbl} {order_detail_lbl} {product_name_lbl} {note_lbl} {price_lbl} +
    + {quantity_lbl} {total_price_lbl} {order_subtotal_lbl} {if discount} {discount_lbl} {order_discount} {discount_in_percentage} {discount end if} {if vat} {vat_lbl} +
    + {order_tax} {vat end if} {shipping_lbl} {total_lbl} {payment_lbl} {payment_method} {customer_note_lbl} {customer_note} {requisition_number_lbl} +
    + {requisition_number} {shipping_method_lbl} {shipping_method} {if payment_discount} {payment_discount_lbl} {payment_order_discount} {payment_discount end if} {product_userfields} +
    + {print} {product_attribute} {product_accessory} {product_number_lbl} {product_subscription_lbl} {product_subscription} +
    + {product_price_excl_vat} {product_total_price_excl_vat} {product_subtotal_excl_vat} {order_subtotal_excl_vat} +
    + {tax} {reorder_button} {shipping} {vat_shipping} {shipping_lbl}
    + {download_date_list_lbl} {download_date_list} {download_counter_lbl} {download_counter} {download_date_lbl} {download_date} {download_token_lbl} {download_token} +
    + {product_subtotal} {shipping_excl_vat} {product_subtotal} {sub_total_vat} {discount_excl_vat} {total_excl_vat} {denotation_label} {discount_denotation} {discount_excl_vat} +
    + {shipping_denotation} {shipping_excl_vat} {product_s_desc} {product_thumb_image} {product_old_price} {special_discount} {special_discount_amount} +
    + {payment_extrafields_lbl} {payment_extrafields} {shipping_extrafields_lbl} {shipping_extrafields} {product_gift} + +

    + {order_id} {order_number} {order_date} {order_status} {order_status_order_only_lbl}{order_status_payment_only_lbl} {order_status_order_only} {order_status_payment_only} +
    + {billing_address} {shipping_address} {product_name} {product_number} {product_attribute_loop_start} {product_attribute_name} {product_attribute_value} {product_attribute_value_price} {product_attribute_loop_end} {attribute_label} {product_wrapper} +
    + {product_price} {product_quantity} {product_total_price} {order_subtotal} {order_total}
    + {order_information_lbl} {order_id_lbl} {order_number_lbl} {order_date_lbl} {order_status_lbl} {billing_address_information_lbl} {shipping_address_information_lbl} +
    + {order_detail_lbl} {product_name_lbl} {note_lbl} {price_lbl} {quantity_lbl} {total_price_lbl} {order_subtotal_lbl} {if discount} {discount_lbl} {order_discount} {discount_in_percentage} {discount end if} {if vat} {vat_lbl} +
    + {order_tax} {vat end if} {shipping_lbl} {total_lbl} {payment_lbl} {payment_method} {customer_note_lbl} {customer_note} {requisition_number_lbl} {requisition_number} +
    + {shipping_method_lbl} {shipping_method} {if payment_discount} {payment_discount_lbl} {payment_order_discount} {payment_discount end if} +
    + {product_userfields} {print} {special_discount} {special_discount_amount} + +

    + {product_loop_start} {product_loop_end} {product_name} {product_number}
    + {product_attribute_loop_start} {product_attribute_name} {product_attribute_value} {product_attribute_value_price} {product_attribute_calculated_price} {product_attribute_loop_end} {attribute_label} {product_wrapper} {product_price} {product_quantity} {product_total_price} {order_subtotal} {tracking_number_lbl} {tracking_number} {tracking_url} +
    + {order_id} {order_number} {order_shipping} {order_total} {delivery_time} {payment_status} {print}{delivery_time_lbl} +
    + {if discount} {discount_lbl} {order_discount} {discount_in_percentage} {discount end if} {if vat} {vat_lbl} {order_tax} {vat end if} {shipping_lbl} {shipping_method_lbl} {shipping_method} +
    + {if payment_discount} {payment_discount_lbl} {payment_order_discount} {payment_discount end if}
    + {product_userfields} {shipping} {vat_shipping} {shipping_lbl}
    + {download_date_list_lbl} {download_date_list} {download_counter_lbl} {download_counter} {download_date_lbl} {download_date} {download_token_lbl} {download_token} +
    + {product_subtotal} {product_subtotal_excl_vat} {shipping_excl_vat} {product_subtotal} {sub_total_vat} {discount_excl_vat} {total_excl_vat} {denotation_label} {discount_denotation} +
    + {discount_excl_vat} {shipping_denotation} {shipping_excl_vat} {payment_extrafields_lbl} {payment_extrafields} {shipping_extrafields_lbl} {shipping_extrafields} {product_gift} + +

    + {order_id_lbl} {product_name_lbl} {total_price_lbl} {order_date_lbl} {order_status_lbl} {order_detail_lbl} {product_loop_start} {order_id} {order_products} {order_total} {order_date} {order_status} {order_detail_link} {reorder_link} {product_loop_end} {pagination} {print} {order_number} {pagination_limit} + +

    +

    + {email_lbl}{email} + {firstname_lbl}{firstname} + {lastname_lbl}{lastname} + {address_lbl}{address} + {zipcode_lbl}{zipcode} + {city_lbl}{city} + {country_lbl}{country} + {state_lbl}{state} + {phone_lbl}{phone}{phone_optional} + {private_extrafield}
    + {retype_email_lbl}{retype_email} + +

    + {product_name} {manufacturer_name} {supplier_name} {publish_date} {update_date}
    + {discount_start_date} {discount_end_date} {product_discount_price} {product_old_price} {product_price_saving} {product_price_saving_percentage} {if product_on_sale} +
    + {product_on_sale end if} {product_price_lbl} {if product_special} {product_special end if} {product_name} {product_price} {lowest_price} {highest_price} +
    + {product_thumb_image} {product_thumb_image_2} {product_thumb_image_3} {product_s_desc} {product_rating} {more_images} {more_documents} {more_videos} +
    + {product_desc} {bookmark} {send_to_friend} {ask_question_about_product} {ask_question_about_product_without_lightbox} {manufacturer_product_link} {product_rating_summary} +
    + {product_delivery_time} {manufacturer_link} {form_rating} {form_rating_without_lightbox} {product_id_lbl} {product_id} +
    + {product_number_lbl} {product_number} {product_price_table} {products_in_stock} {if product_userfield} {product_userfield end if} +
    + {delivery_time_lbl} {with_vat} {without_vat} {discount_calculator} {facebook_like_button} {googleplus1}
    + {returntocategory_name} {returntocategory_link} {product_size}
    + {component_heading} {returntocategory} {navigation_link_right} {product_weight} {product_weight_lbl}
    + {child_products} {product_volume} {product_volume_lbl} {product_price_novat} {price_excluding_vat}
    + {more_images_3} {more_images_2} {product_stock_amount_image}
    + {wishlist_button} {wishlist_link} {compare_products_button} {compare_product_div} {my_tags_button} {subscription} {ajaxdetail_template:templatename} {accessory_template:templatename} +
    + {question_loop_start} {question} {question_owner} {question_date} {answer_loop_start} {answer} {answer_owner} {answer_date} {answer_loop_end} {question_loop_end} +
    + {product_length} {product_width} {product_height}
    + {front_img_link} {back_img_link} {category_product_img} {category_front_img_link} {category_back_img_link} {product_preview_img} {diameter} {product_diameter_lbl} {manufacturer_image} +
    + {back_link} {product_length_lbl} {product_width_lbl} {product_height_lbl} {min_order_product_quantity} {print} {product_category_list} {stock_notify_flag} {product_availability_date} +
    + {stock_status} {product_gift_table} + +

    + {product_thumb_image} {product_thumb_image_2} {product_thumb_image_3} {product_name} {product_desc} {product_price} {read_more} {attribute_template:attributes} {form_addtocart:add_to_cart1} + +

    + {name_lbl} {name} {email_lbl} {email_address} {address_fields} {submit_button_sample} {product_samples} + +

    + {cart_lbl} {print} {product_name_lbl} {quantity_lbl} {product_loop_start} {product_name} {product_attribute} {product_accessory} {product_wrapper} {product_userfields} {product_thumb_image} {update_cart} {remove_product} {product_loop_end} {update} {empty_cart} {checkout_button} {shop_more} + +

    + {print} {quotation_information_lbl} {quotation_id_lbl} {quotaion_id} {quotation_number_lbl} {quotation_number} {quotation_date_lbl} {quotation_date} {quotation_status_lbl} {quotation_status} {quotation_note_lbl} {quotation_note} {account_information_lbl} {account_information} {quotation_detail_lbl} {product_name_lbl} {note_lbl} {price_lbl} {quantity_lbl} {total_price_lbl} {product_loop_start} {product_name} {product_attribute} {product_accessory} {product_number_lbl} {product_number} {product_price} {product_quantity} {product_total_price} {product_loop_end} {product_userfields} {quotation_subtotal_lbl} {quotation_subtotal} {total_lbl} {quotation_total} {quotation_discount_lbl} {quotation_discount} {quotation_custom_field_list} + +

    + {order_detail_lbl} {product_name_lbl} {quantity_lbl} {product_loop_start} {product_name} {product_attribute} {product_accessory} {product_userfields} {update_cart} {product_wrapper} {product_loop_end} {customer_note_lbl} {customer_note} {billing_address_information_lbl} {billing_address} {cancel_btn} {request_quotation_btn} {quotation_custom_field_list} + +

    + {search_tag_display} {product_loop_start} {product_loop_end} {product_name} {product_price} {product_thumb_image} +
    + {product_s_desc} {read_more} {product_id_lbl} {product_id} {product_number_lbl} {product_number} {manufacturer_link} {manufacturer_name} {order_by} {pagination} +
    + {perpagelimit:X} {product_display_limit} {attribute_template:attributes} + +

    + {payment_heading} {payment_loop_start} {payment_method_name} {creditcard_information} {payment_extrafields} {payment_loop_end} + +

    + {shipping_heading} {shipping_method_loop_start} {shipping_method_title} {shipping_rate_loop_start} {shipping_rate_name} {shipping_rate} {shipping_location} {shipping_rate_loop_end} {shipping_method_loop_end} + +

    + {relproduct_link} {relproduct_image} {relproduct_name} {relproduct_price} {relproduct_number} {relproduct_number_lbl} {read_more} {relproduct_old_price} {relproduct_price_table} {relproduct_price_saving} +
    + {related_product_start} {related_product_end} {relproduct_s_desc} {relproduct_rating_summary} {relproduct_price_novat} {relproduct_old_price_lbl} {relproduct_image_2} {relproduct_image_3} +
    + {attribute_template:templatename} {form_addtocart:templatename} {producttag:rs_field}
    + {stock_status} {relproduct_attribute_pricelist} {manufacturer_name} {manufacturer_link} {read_more_link} + +

    + {show_all_images_rating} {rating_statistics} {product_loop_start} {product_title} {images}
    + {review_loop_start} {fullname} {title} {comment} {stars} {reviewdate} {review_loop_end} {product_loop_end} + +

    + {order_information_lbl} {order_id_lbl} {order_id} {order_number_lbl} {order_number} {order_date_lbl} {order_date} {order_status_lbl} {order_status} {customer_note_lbl} {customer_note} {billing_address_information_lbl} {billing_address} {shipping_address_information_lbl} {shipping_address} {order_detail_lbl} +
    + {product_loop_start} {product_name_lbl} {note_lbl} {price_lbl} {quantity_lbl} {total_price_lbl} {product_name} {product_number} {product_userfields} {product_attribute} {product_accessory} {product_wrapper} {product_price} {product_quantity} {product_total_price} {product_loop_end} +
    + {if vat} {vat_lbl} {order_tax} {vat end if}
    + {if discount} {discount_lbl} {order_discount} {discount end if}
    + {order_subtotal_lbl} {product_subtotal} {shipping_lbl} {shipping_excl_vat} {total_lbl} {order_total} {order_payment_status} {shipping_method_lbl} {shipping_method} {order_detail_link} + +

    +

    + {firstname_st_lbl}{firstname_st}
    + {lastname_st_lbl}{lastname_st}
    + {address_st_lbl}{address_st}
    + {zipcode_st_lbl}{zipcode_st}
    + {city_st_lbl}{city_st}
    + {country_st_lbl}{country_st}
    + {state_st_lbl}{state_st}
    + {phone_st_lbl}{phone_st}

    -

    - {extra_field_st_start}{extra_field_st}{extra_field_st_end} - -

    - {shipping_box_heading} {shipping_box_list} - -

    - {order_information_lbl} {order_id_lbl} {order_id} {order_number_lbl} {order_number} {order_date_lbl} {order_date}
    - {order_status_lbl} {order_status} {shipping_address_information_lbl} {shipping_firstname_lbl} {shipping_firstname} {shipping_lastname_lbl} {shipping_lastname}
    - {shipping_address_lbl} {shipping_address} {shipping_zip_lbl} {shipping_zip} {shipping_city_lbl} {shipping_city} {shipping_country_lbl} {shipping_state_lbl}
    - {shipping_phone_lbl} {company_name_lbl} {company_name} {shipping_country} {shipping_phone} {shipping_state} - -

    - {order_id_lbl} {order_id} {order_date_lbl} {order_date} {product_name_lbl} {product_number_lbl} {product_quantity_lbl} {product_name}
    - {product_attribute} {product_number} {product_quantity} {requisition_number} {requisition_number_lbl} - -

    - {if product_userfield} {product_userfield end if} {all_cart} {product_loop_start} {product_loop_end} {mail_link} {product_price} {remove_product_link}
    - {product_thumb_image} {product_name} {back_link} {product_thumb_image_2} {product_thumb_image_3}
    - {price_excluding_vat} {product_price_table} {product_old_price} {product_price_saving} {product_price_saving_percentage} {product_s_desc} {read_more} {read_more_link} - -

    - {email_to_friend} {emailto_lbl} {emailto} {sender_lbl} {sender}
    - {mail_lbl} {mail} {subject_lbl} {subject} {cancel_button} {send_button} - -

    - {wrapper_dropdown} {wrapper_image} {wrapper_add_checkbox} {wrapper_price} -

    + {extra_field_st_start}{extra_field_st}{extra_field_st_end} + +

    + {shipping_box_heading} {shipping_box_list} + +

    + {order_information_lbl} {order_id_lbl} {order_id} {order_number_lbl} {order_number} {order_date_lbl} {order_date} +
    + {order_status_lbl} {order_status} {shipping_address_information_lbl} {shipping_firstname_lbl} {shipping_firstname} {shipping_lastname_lbl} {shipping_lastname} +
    + {shipping_address_lbl} {shipping_address} {shipping_zip_lbl} {shipping_zip} {shipping_city_lbl} {shipping_city} {shipping_country_lbl} {shipping_state_lbl} +
    + {shipping_phone_lbl} {company_name_lbl} {company_name} {shipping_country} {shipping_phone} {shipping_state} + +

    + {order_id_lbl} {order_id} {order_date_lbl} {order_date} {product_name_lbl} {product_number_lbl} {product_quantity_lbl} {product_name} +
    + {product_attribute} {product_number} {product_quantity} {requisition_number} {requisition_number_lbl} + +

    + {if product_userfield} {product_userfield end if} {all_cart} {product_loop_start} {product_loop_end} {mail_link} {product_price} {remove_product_link} +
    + {product_thumb_image} {product_name} {back_link} {product_thumb_image_2} {product_thumb_image_3}
    + {price_excluding_vat} {product_price_table} {product_old_price} {product_price_saving} {product_price_saving_percentage} {product_s_desc} {read_more} {read_more_link} + +

    + {email_to_friend} {emailto_lbl} {emailto} {sender_lbl} {sender}
    + {mail_lbl} {mail} {subject_lbl} {subject} {cancel_button} {send_button} + +

    + {wrapper_dropdown} {wrapper_image} {wrapper_add_checkbox} {wrapper_price} + getPrimaryKey(); $itemId = $data->item->{$primaryKey}; -$action = 'index.php?option=com_redshop&task=' . $data->getInstanceName() . '.edit&' . $primaryKey . '=' . $itemId; +$action = 'index.php?option=com_redshop&task=' . $data->getInstanceName( + ) . '.edit&' . $primaryKey . '=' . $itemId; $fieldSetClass = 'col-md-' . (12 / $data->formFieldsetsColumn); ?> -
    - fields as $fieldSet): ?> + fields as $fieldSet): ?>
    - JText::_('COM_REDSHOP_' . strtoupper($fieldSet->name)), 'content' => $fieldSet->html) - ) - ?> + JText::_('COM_REDSHOP_' . strtoupper($fieldSet->name)), + 'content' => $fieldSet->html + ) + ) + ?>
    - +
    diff --git a/component/admin/layouts/view/edit/tab.php b/component/admin/layouts/view/edit/tab.php index 3a63de1d33d..7e6995296d2 100644 --- a/component/admin/layouts/view/edit/tab.php +++ b/component/admin/layouts/view/edit/tab.php @@ -1,4 +1,5 @@ getInstanceName() . '.edit&' . $primaryKey . '=' . $itemId; ?> -
    +
    - - fields as $fieldSet): ?> -
    + + fields as $fieldSet): ?> +
    - html ?> + html ?>
    - - + +
    diff --git a/component/admin/layouts/view/list.php b/component/admin/layouts/view/list.php index 72185994969..4652392dd90 100644 --- a/component/admin/layouts/view/list.php +++ b/component/admin/layouts/view/list.php @@ -1,4 +1,5 @@ 'search', - 'searchFieldSelector' => '#filter_search', - 'limitFieldSelector' => '#list_' . $viewName . '_limit', - 'activeOrder' => $listOrder, - 'activeDirection' => $listDirn, - 'filterButton' => (count($data->filterForm->getGroup('filter')) > 1) + 'searchField' => 'search', + 'searchFieldSelector' => '#filter_search', + 'limitFieldSelector' => '#list_' . $viewName . '_limit', + 'activeOrder' => $listOrder, + 'activeDirection' => $listDirn, + 'filterButton' => (count($data->filterForm->getGroup('filter')) > 1) ); $filterOptions = array_merge($filterOptions, $data->filterFormOptions); -if ($data->hasOrdering) -{ - $saveOrderUrl = 'index.php?option=com_redshop&task=' . $viewName . '.saveOrderAjax&tmpl=component'; - $orderingColumn = true === $data->isNested ? 'lft' : 'ordering'; - $allowOrder = ($listOrder == $orderingColumn && strtolower($listDirn) == 'asc' && $data->canEdit && empty($search)); +if ($data->hasOrdering) { + $saveOrderUrl = 'index.php?option=com_redshop&task=' . $viewName . '.saveOrderAjax&tmpl=component'; + $orderingColumn = true === $data->isNested ? 'lft' : 'ordering'; + $allowOrder = ($listOrder == $orderingColumn && strtolower( + $listDirn + ) == 'asc' && $data->canEdit && empty($search)); - if ($allowOrder) - { - JHtml::_('sortablelist.sortable', 'table-' . $viewName, 'adminForm', strtolower($listDirn), $saveOrderUrl, false, true); - } + if ($allowOrder) { + JHtml::_( + 'sortablelist.sortable', + 'table-' . $viewName, + 'adminForm', + strtolower($listDirn), + $saveOrderUrl, + false, + true + ); + } } ?> - redirect(JURI::base() . "index.php?option=com_redshop", $msg); - } - - // Set some model state values - $app->enqueueMessage($msg); - $this->setState('name', $installer->get('name')); - $this->setState('result', $result); - $this->setState('message', $installer->message); - $this->setState('extension.message', $installer->get('extension.message')); - - // Cleanup the install files - if (!JFile::exists($package['packagefile'])) - { - $config = JFactory::getConfig(); - $package['packagefile'] = $config->get('tmp_path') . '/' . $package['packagefile']; - } - - JInstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']); - ?> - - - - - - get('tmp_path'); - - // Unpack the downloaded package file - $package = JInstallerHelper::unpack($tmp_dest . '/' . $p_file); - - ?> - - input->getString('install_directory'); - $p_dir = JPath::clean($p_dir); - - // Did you give us a valid directory? - if (!is_dir($p_dir)) - { - JError::raiseWarning('SOME_ERROR_CODE', JText::_('COM_REDSHOP_PLEASE_ENTER_A_PACKAGE_DIRECTORY')); - - return false; - } - - // Detect the package type - $type = JInstallerHelper::detectType($p_dir); - - // Did you give us a valid package? - if (!$type) - { - JError::raiseWarning('SOME_ERROR_CODE', JText::_('COM_REDSHOP_PATH_DOES_NOT_HAVE_A_VALID_PACKAGE')); - - return false; - } - - $package['packagefile'] = null; - $package['extractdir'] = null; - $package['dir'] = $p_dir; - $package['type'] = $type; - - return $package; - } + public $_data = null; + + public $_total = null; + + public $_pagination = null; + + public $_table_prefix = null; + + public $_table = null; + + /** @var object JTable object */ + public $_url = null; + + public function getData() + { + $app = JFactory::getApplication(); + + $this->getzipfilenames(); + + $this->install(); + session_unregister("filename"); + session_unregister("zipno"); + $msg = JText::_('COM_REDSHOP_REDSHOP_REMOTLY_UPDATED'); + $app->redirect(JURI::base() . 'index.php?option=com_redshop', $msg); + } + + public function getzipfilenames() + { + $user = JFactory::getUser(); + $url = Redshop::getConfig()->get( + 'REMOTE_UPDATE_DOMAIN_URL' + ) . "index.php?option=com_remoteupdate&view=getcomponent&redusername=" . + $user->username . "&reddomain=" . JURI::base() . ""; + + $ch = curl_init(); + + // Set curl to return the data instead of printing it to the browser. + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + + // Set the URL + curl_setopt($ch, CURLOPT_URL, $url); + + // Execute the fetch + $data = curl_exec($ch); + + // Close the connection + curl_close($ch); + ob_clean(); + $fp = fopen(JPATH_ROOT . '/tmp/com_jcomments_new.zip', 'w'); + fwrite($fp, $data); + fclose($fp); + + $filename = JURI::base() . '/tmp/com_jcomments_new.zip'; + $_SESSION['filename'][0] = $filename; + } + + public function install() + { + $app = JFactory::getApplication(); + $fileType = "url"; + + switch ($fileType) { + case 'url': + $package = $this->_getPackageFromUrl(); + break; + + default: + $this->setState('message', 'No Install Type Found'); + + return false; + break; + } + + // Was the package unpacked? + if (!$package) { + $this->setState('message', 'Unable to find install package'); + $msg = JText::_('COM_REDSHOP_REDSHOP_REMOTELY_UPDATED'); + $app->redirect(JURI::base() . "index.php?option=com_redshop", $msg); + } + + // Get an installer instance + $installer = JInstaller::getInstance(); + + // Install the package + if (!$installer->install($package['dir'])) { + ?> + + redirect(JURI::base() . "index.php?option=com_redshop", $msg); + } + + // Set some model state values + $app->enqueueMessage($msg); + $this->setState('name', $installer->get('name')); + $this->setState('result', $result); + $this->setState('message', $installer->message); + $this->setState('extension.message', $installer->get('extension.message')); + + // Cleanup the install files + if (!JFile::exists($package['packagefile'])) { + $config = JFactory::getConfig(); + $package['packagefile'] = $config->get('tmp_path') . '/' . $package['packagefile']; + } + + JInstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']); + ?> + + + + + + get('tmp_path'); + + // Unpack the downloaded package file + $package = JInstallerHelper::unpack($tmp_dest . '/' . $p_file); + + ?> + + get( + 'REMOTE_UPDATE_DOMAIN_URL' + ) . "index.php?option=com_reviews&domainname=" . JUri::getInstance()->toString(array('host')); + $ch = curl_init(); + curl_setopt( + $ch, + CURLOPT_USERAGENT, + "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" + ); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_ENCODING, ""); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_AUTOREFERER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + $content = curl_exec($ch); + preg_match_all("#(.*?)#is", $content, $out); + $content = trim($out[0][0]); + $response = curl_getinfo($ch); + print_r($response); + JFactory::getApplication()->close(); + curl_close($ch); + $x = count(explode(",", $content)); + + return $x; + } + + public function _getPackageFromFolder() + { + $p_dir = JFactory::getApplication()->input->getString('install_directory'); + $p_dir = JPath::clean($p_dir); + + // Did you give us a valid directory? + if (!is_dir($p_dir)) { + JError::raiseWarning('SOME_ERROR_CODE', JText::_('COM_REDSHOP_PLEASE_ENTER_A_PACKAGE_DIRECTORY')); + + return false; + } + + // Detect the package type + $type = JInstallerHelper::detectType($p_dir); + + // Did you give us a valid package? + if (!$type) { + JError::raiseWarning('SOME_ERROR_CODE', JText::_('COM_REDSHOP_PATH_DOES_NOT_HAVE_A_VALID_PACKAGE')); + + return false; + } + + $package['packagefile'] = null; + $package['extractdir'] = null; + $package['dir'] = $p_dir; + $package['type'] = $type; + + return $package; + } } diff --git a/component/admin/models/zipcode.php b/component/admin/models/zipcode.php index 86969b4ab49..631d70de176 100644 --- a/component/admin/models/zipcode.php +++ b/component/admin/models/zipcode.php @@ -18,45 +18,44 @@ */ class RedshopModelZipcode extends RedshopModelForm { - /** - * Method to save a record. - * - * @param array $data data - * @return boolean - * - * @since 2.1.3 - * @throws Exception - */ - public function save($data) - { - /** @var RedshopTableZipcode $table */ - $table = $this->getTable('Zipcode'); - - if ($data['zipcodeto'] && ($data['zipcode'] > $data['zipcodeto'])) - { - return false; - } - - if (!$data['zipcodeto']) - { - $data['zipcodeto'] = $data['zipcode']; - } - - for ($i = $data['zipcode']; $i <= $data['zipcodeto']; $i++) - { - $data['zipcode'] = is_numeric($data['zipcode']) ? $i : $data['zipcode']; - - if (!$table->bind($data) || !$table->docheck()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_ZIPCODE_ALREADY_EXISTS') . ": " . $data['zipcode']); - /** @scrutinizer ignore-deprecated */ JError::raiseWarning('', /** @scrutinizer ignore-deprecated */ $this->getError()); - - continue; - } - - parent::save($data); - } - - return true; - } + /** + * Method to save a record. + * + * @param array $data data + * + * @return boolean + * + * @throws Exception + * @since 2.1.3 + */ + public function save($data) + { + /** @var RedshopTableZipcode $table */ + $table = $this->getTable('Zipcode'); + + if ($data['zipcodeto'] && ($data['zipcode'] > $data['zipcodeto'])) { + return false; + } + + if (!$data['zipcodeto']) { + $data['zipcodeto'] = $data['zipcode']; + } + + for ($i = $data['zipcode']; $i <= $data['zipcodeto']; $i++) { + $data['zipcode'] = is_numeric($data['zipcode']) ? $i : $data['zipcode']; + + if (!$table->bind($data) || !$table->docheck()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_ZIPCODE_ALREADY_EXISTS') . ": " . $data['zipcode']); + /** @scrutinizer ignore-deprecated */ + JError::raiseWarning('', /** @scrutinizer ignore-deprecated */ $this->getError()); + + continue; + } + + parent::save($data); + } + + return true; + } } diff --git a/component/admin/models/zipcodes.php b/component/admin/models/zipcodes.php index 6a220bd86a9..37d8defd418 100644 --- a/component/admin/models/zipcodes.php +++ b/component/admin/models/zipcodes.php @@ -1,4 +1,5 @@ getUserStateFromRequest($this->context . '.filter.search', 'filter_search'); - $this->setState('filter.search', $search); - - $countryId = $this->getUserStateFromRequest($this->context . '.filter.country_id', 'filter_country_id'); - $this->setState('filter.country_id', $countryId); - - // List state information. - parent::populateState($ordering, $direction); - } - - /** - * Method to get a store id based on model configuration state. - * - * This is necessary because the model is used by the component and - * different modules that might need different sets of data or different - * ordering requirements. - * - * @param string $id A prefix for the store id. - * - * @return string A store id. - * - * @since 2.1.3 - */ - protected function getStoreId($id = '') - { - // Compile the store id. - $id .= ':' . $this->getState('filter.search'); - $id .= ':' . $this->getState('filter.country_id'); - - return parent::getStoreId($id); - } - - /** - * Method to build an SQL query to load the list data. - * - * @return string An SQL query - */ - protected function getListQuery() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query->select( - $db->qn( - [ - 'z.id', - 'z.country_code', - 'z.state_code', - 'z.city_name', - 'z.zipcode', - 'z.zipcodeto', - 'c.country_name', - 's.state_name', - ] - ) - ) - ->from($db->qn('#__redshop_zipcode', 'z')) - ->leftJoin($db->qn('#__redshop_country', 'c') . ' ON ' . $db->qn('z.country_code') . ' = ' . $db->qn('c.country_3_code')) - ->leftJoin( - $db->qn('#__redshop_state', 's') - . ' ON ' . $db->qn('z.state_code') . ' = ' . $db->qn('s.state_2_code') - . ' AND ' . $db->qn('c.id') . ' = ' . $db->qn('s.country_id') - ); - - $search = $this->getState('filter.search'); - - if (!empty($search)) - { - $query->where( - '(' . $db->qn('z.zipcode') . ' LIKE ' . $db->q($search) . - ' OR ' . $db->qn('z.city_name') . ' LIKE ' . $db->q('%' . $search . '%') . - ' OR ' . $db->qn('c.country_name') . 'LIKE' . $db->q('%' . $search . '%') - . ')' - ); - } - - $countryId = $this->getState('filter.country_id'); - - if (!empty($countryId)) - { - $query->where($db->qn('s.country_id') . ' = ' . $db->q($countryId)); - } - - // Add the list ordering clause. - $orderCol = $this->state->get('list.ordering', 'z.id'); - $orderDirn = $this->state->get('list.direction', 'asc'); - $query->order($db->escape($orderCol . ' ' . $orderDirn)); - - return $query; - } + /** + * Name of the filter form to load + * + * @var string + */ + protected $filterFormName = 'filter_zipcodes'; + + /** + * Construct class + * + * @since 2.1.3 + */ + public function __construct($config = array()) + { + if (empty($config['filter_fields'])) { + $config['filter_fields'] = array( + 'id', + 'z.id', + 'country_code', + 'z.country_code', + 'state_code', + 'z.state_code', + 'city_name', + 'z.city_name', + 'zipcode', + 'z.zipcode', + 'zipcodeto', + 'z.zipcodeto', + ); + } + + parent::__construct($config); + } + + /** + * Method to auto-populate the model state. + * + * This method should only be called once per instantiation and is designed + * to be called on the first call to the getState() method unless the model + * configuration flag to ignore the request is set. + * + * Note. Calling getState in this method will result in recursion. + * + * @param string $ordering An optional ordering field. + * @param string $direction An optional direction (asc|desc). + * + * @return void + * + * @since 2.1.3 + */ + protected function populateState($ordering = 'z.id', $direction = 'asc') + { + $search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search'); + $this->setState('filter.search', $search); + + $countryId = $this->getUserStateFromRequest($this->context . '.filter.country_id', 'filter_country_id'); + $this->setState('filter.country_id', $countryId); + + // List state information. + parent::populateState($ordering, $direction); + } + + /** + * Method to get a store id based on model configuration state. + * + * This is necessary because the model is used by the component and + * different modules that might need different sets of data or different + * ordering requirements. + * + * @param string $id A prefix for the store id. + * + * @return string A store id. + * + * @since 2.1.3 + */ + protected function getStoreId($id = '') + { + // Compile the store id. + $id .= ':' . $this->getState('filter.search'); + $id .= ':' . $this->getState('filter.country_id'); + + return parent::getStoreId($id); + } + + /** + * Method to build an SQL query to load the list data. + * + * @return string An SQL query + */ + protected function getListQuery() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->select( + $db->qn( + [ + 'z.id', + 'z.country_code', + 'z.state_code', + 'z.city_name', + 'z.zipcode', + 'z.zipcodeto', + 'c.country_name', + 's.state_name', + ] + ) + ) + ->from($db->qn('#__redshop_zipcode', 'z')) + ->leftJoin( + $db->qn('#__redshop_country', 'c') . ' ON ' . $db->qn('z.country_code') . ' = ' . $db->qn( + 'c.country_3_code' + ) + ) + ->leftJoin( + $db->qn('#__redshop_state', 's') + . ' ON ' . $db->qn('z.state_code') . ' = ' . $db->qn('s.state_2_code') + . ' AND ' . $db->qn('c.id') . ' = ' . $db->qn('s.country_id') + ); + + $search = $this->getState('filter.search'); + + if (!empty($search)) { + $query->where( + '(' . $db->qn('z.zipcode') . ' LIKE ' . $db->q($search) . + ' OR ' . $db->qn('z.city_name') . ' LIKE ' . $db->q('%' . $search . '%') . + ' OR ' . $db->qn('c.country_name') . 'LIKE' . $db->q('%' . $search . '%') + . ')' + ); + } + + $countryId = $this->getState('filter.country_id'); + + if (!empty($countryId)) { + $query->where($db->qn('s.country_id') . ' = ' . $db->q($countryId)); + } + + // Add the list ordering clause. + $orderCol = $this->state->get('list.ordering', 'z.id'); + $orderDirn = $this->state->get('list.direction', 'asc'); + $query->order($db->escape($orderCol . ' ' . $orderDirn)); + + return $query; + } } \ No newline at end of file diff --git a/component/admin/redshop.php b/component/admin/redshop.php index 1d50e174f60..053e8c6e5f0 100644 --- a/component/admin/redshop.php +++ b/component/admin/redshop.php @@ -1,4 +1,5 @@ isExists() && $app->input->getCmd('view') != 'install') -{ - $controller = 'redshop'; - \JFactory::getApplication()->input->set('view', 'redshop'); - \JFactory::getApplication()->input->set('layout', 'noconfig'); +if (!$config->isExists() && $app->input->getCmd('view') != 'install') { + $controller = 'redshop'; + \JFactory::getApplication()->input->set('view', 'redshop'); + \JFactory::getApplication()->input->set('layout', 'noconfig'); } \Redshop\Shipping\Rate::removeShippingRate(); @@ -40,31 +40,28 @@ $user->usertype = $userType[0]; $user->gid = $user->groups[$user->usertype]; -if (!$user->authorise('core.manage', 'com_redshop') && !$json) -{ - $app->enqueueMessage(JText::_('JERROR_ALERTNOAUTHOR'), 'error'); +if (!$user->authorise('core.manage', 'com_redshop') && !$json) { + $app->enqueueMessage(JText::_('JERROR_ALERTNOAUTHOR'), 'error'); - return false; + return false; } $isWizard = \JFactory::getApplication()->input->getInt('wizard', 0); $step = \JFactory::getApplication()->input->get('step', ''); // Initialize wizard -if ($isWizard || $step != '') -{ - if ($user->gid != 8 && !$user->authorise('core.manage', 'com_redshop')) - { - throw new Exception('COM_REDSHOP_DONT_HAVE_PERMISSION'); - } +if ($isWizard || $step != '') { + if ($user->gid != 8 && !$user->authorise('core.manage', 'com_redshop')) { + throw new Exception('COM_REDSHOP_DONT_HAVE_PERMISSION'); + } - \JFactory::getApplication()->input->set('view', 'wizard'); + \JFactory::getApplication()->input->set('view', 'wizard'); - require_once JPATH_COMPONENT . '/helpers/wizard/wizard.php'; - $redSHOPWizard = new \redSHOPWizard; - $redSHOPWizard->initialize(); + require_once JPATH_COMPONENT . '/helpers/wizard/wizard.php'; + $redSHOPWizard = new \redSHOPWizard; + $redSHOPWizard->initialize(); - return true; + return true; } $view = $app->input->get('view', 'redshop'); @@ -78,33 +75,26 @@ // Check for array format. $filter = \JFilterInput::getInstance(); -if (is_array($task)) -{ - $command = $filter->clean(array_pop(array_keys($task)), 'cmd'); -} -else -{ - $command = $filter->clean($task, 'cmd'); +if (is_array($task)) { + $command = $filter->clean(array_pop(array_keys($task)), 'cmd'); +} else { + $command = $filter->clean($task, 'cmd'); } // Check for a not controller.task command. -if ($command != '' && strpos($command, '.') === false) -{ - \JFactory::getApplication()->input->set('task', $view . '.' . $command); - $task = $command; -} -elseif ($command != '' && strpos($command, '.') !== false) -{ - $commands = explode('.', $command); - $view = $commands[0]; - $task = $commands[1]; +if ($command != '' && strpos($command, '.') === false) { + \JFactory::getApplication()->input->set('task', $view . '.' . $command); + $task = $command; +} elseif ($command != '' && strpos($command, '.') !== false) { + $commands = explode('.', $command); + $view = $commands[0]; + $task = $commands[1]; } // Set the controller page -if (!file_exists(JPATH_COMPONENT . '/controllers/' . $view . '.php')) -{ - $view = 'redshop'; - \JFactory::getApplication()->input->set('view', $view); +if (!file_exists(JPATH_COMPONENT . '/controllers/' . $view . '.php')) { + $view = 'redshop'; + \JFactory::getApplication()->input->set('view', $view); } \RedshopHelperConfig::script('SITE_URL', \JURI::root()); diff --git a/component/admin/sql/index.html b/component/admin/sql/index.html index 94906bce29b..af1d3c9d43e 100644 --- a/component/admin/sql/index.html +++ b/component/admin/sql/index.html @@ -1 +1,3 @@ - + + + diff --git a/component/admin/sql/install/index.html b/component/admin/sql/install/index.html index 94906bce29b..af1d3c9d43e 100644 --- a/component/admin/sql/install/index.html +++ b/component/admin/sql/install/index.html @@ -1 +1,3 @@ - + + + diff --git a/component/admin/sql/install/mysql/index.html b/component/admin/sql/install/mysql/index.html index 94906bce29b..af1d3c9d43e 100644 --- a/component/admin/sql/install/mysql/index.html +++ b/component/admin/sql/install/mysql/index.html @@ -1 +1,3 @@ - + + + diff --git a/component/admin/sql/updates/index.html b/component/admin/sql/updates/index.html index 94906bce29b..af1d3c9d43e 100644 --- a/component/admin/sql/updates/index.html +++ b/component/admin/sql/updates/index.html @@ -1 +1,3 @@ - + + + diff --git a/component/admin/sql/updates/mysql/index.html b/component/admin/sql/updates/mysql/index.html index 94906bce29b..af1d3c9d43e 100644 --- a/component/admin/sql/updates/mysql/index.html +++ b/component/admin/sql/updates/mysql/index.html @@ -1 +1,3 @@ - + + + diff --git a/component/admin/tables/accessory_detail.php b/component/admin/tables/accessory_detail.php index 68d0ee047ee..2e45c74b932 100644 --- a/component/admin/tables/accessory_detail.php +++ b/component/admin/tables/accessory_detail.php @@ -11,38 +11,37 @@ class Tableaccessory_detail extends JTable { - public $accessoryId = null; + public $accessoryId = null; - public $product_id = null; + public $product_id = null; - public $child_product_id = null; + public $child_product_id = null; - public $accessory_price = null; + public $accessory_price = null; - public $oprand = null; + public $oprand = null; - public $ordering = null; + public $ordering = null; - public $category_id = null; + public $category_id = null; - public $setdefault_selected = null; + public $setdefault_selected = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_accessory', 'accessory_id', $db); - } + parent::__construct($this->_table_prefix . 'product_accessory', 'accessory_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/accountgroup_detail.php b/component/admin/tables/accountgroup_detail.php index 2233719307d..710815ca4ec 100644 --- a/component/admin/tables/accountgroup_detail.php +++ b/component/admin/tables/accountgroup_detail.php @@ -11,43 +11,42 @@ class Tableaccountgroup_detail extends JTable { - public $accountgroup_id = null; + public $accountgroup_id = null; - public $accountgroup_name = null; + public $accountgroup_name = null; - public $economic_vat_account = null; + public $economic_vat_account = null; - public $economic_nonvat_account = null; + public $economic_nonvat_account = null; - public $economic_discount_vat_account = null; + public $economic_discount_vat_account = null; - public $economic_discount_nonvat_account = null; + public $economic_discount_nonvat_account = null; - public $economic_shipping_vat_account = null; + public $economic_shipping_vat_account = null; - public $economic_shipping_nonvat_account = null; + public $economic_shipping_nonvat_account = null; - public $economic_discount_product_number = null; + public $economic_discount_product_number = null; - public $published = 1; + public $published = 1; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'economic_accountgroup', 'accountgroup_id', $db); - } + parent::__construct($this->_table_prefix . 'economic_accountgroup', 'accountgroup_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/alert_detail.php b/component/admin/tables/alert_detail.php index aa8e6396c69..8ceeaa64d1a 100644 --- a/component/admin/tables/alert_detail.php +++ b/component/admin/tables/alert_detail.php @@ -11,18 +11,18 @@ class Tablealert_detail extends JTable { - public $id = 0; + public $id = 0; - public $message = null; + public $message = null; - public $sent_date = null; + public $sent_date = null; - public $read = 0; + public $read = 0; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'alert', 'id', $db); - } + parent::__construct($this->_table_prefix . 'alert', 'id', $db); + } } diff --git a/component/admin/tables/associations.php b/component/admin/tables/associations.php index 8f6528afe21..11a536994e2 100644 --- a/component/admin/tables/associations.php +++ b/component/admin/tables/associations.php @@ -13,29 +13,29 @@ */ class TableAssociations extends JTable { - /** @var int Primary key */ - public $id = null; + /** @var int Primary key */ + public $id = null; - /** @var string Whether or not a product is published */ - public $published = null; + /** @var string Whether or not a product is published */ + public $published = null; - /** @var string Whether or not a product is checked out */ - public $checked_out = null; + /** @var string Whether or not a product is checked out */ + public $checked_out = null; - /** @var string When a product is checked out */ - public $checked_out_time = null; + /** @var string When a product is checked out */ + public $checked_out_time = null; - /** @var integer The order of the product */ - public $ordering = 0; + /** @var integer The order of the product */ + public $ordering = 0; - /** @var integer The ID of the Redshop product */ - public $product_id = 0; + /** @var integer The ID of the Redshop product */ + public $product_id = 0; - /** - * @param database A database connector object - */ - public function __construct(&$db) - { - parent::__construct('#__redproductfinder_associations', 'id', $db); - } + /** + * @param database A database connector object + */ + public function __construct(&$db) + { + parent::__construct('#__redproductfinder_associations', 'id', $db); + } } diff --git a/component/admin/tables/attribute.php b/component/admin/tables/attribute.php index 5f83c03e274..f639b445b99 100644 --- a/component/admin/tables/attribute.php +++ b/component/admin/tables/attribute.php @@ -20,106 +20,93 @@ */ class RedshopTableAttribute extends JTable { - /** - * Constructor - * - * @param JDatabaseDriver $db Database driver object. - * - * @since 11.1 - */ - public function __construct($db) - { - parent::__construct('#__redshop_product_attribute', 'attribute_id', $db); - } - - /** - * Method to set the publishing state for a row or list of rows in the database - * table. The method respects checked out rows by other users and will attempt - * to checkin rows that it can after adjustments are made. - * - * @param mixed $pks An optional array of primary key values to update. If not set the instance property value is used. - * @param integer $state The publishing state. eg. [0 = unpublished, 1 = published, 2=archived, -2=trashed] - * @param integer $userId The user id of the user performing the operation. - * - * @return boolean True on success. - * - * @since 1.0.4 - */ - public function publish($pks = null, $state = 1, $userId = 0) - { - $k = $this->_tbl_key; - - // Sanitize input. - $pks = ArrayHelper::toInteger($pks); - $userId = (int) $userId; - $state = (int) $state; - - // If there are no primary keys set check to see if the instance key is set. - if (empty($pks)) - { - if ($this->$k) - { - $pks = array($this->$k); - } - // Nothing to set publishing state on, return false. - else - { - $this->setError(JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED')); - - return false; - } - } - - // Build the WHERE clause for the primary keys. - $where = $k . '=' . implode(' OR ' . $k . '=', $pks); - - // Determine if there is checkin support for the table. - if (!property_exists($this, 'checked_out') || !property_exists($this, 'checked_out_time')) - { - $checkin = ''; - } - else - { - $checkin = ' AND (checked_out = 0 OR checked_out = ' . (int) $userId . ')'; - } - - // Update the publishing state for rows with the given primary keys. - $this->_db->setQuery( - 'UPDATE ' . $this->_db->quoteName($this->_tbl) - . ' SET ' . $this->_db->quoteName('attribute_published') . ' = ' . (int) $state - . ' WHERE (' . $where . ')' - . $checkin - ); - - try - { - $this->_db->execute(); - } - catch (RuntimeException $e) - { - $this->setError($e->getMessage()); - - return false; - } - - // If checkin is supported and all rows were adjusted, check them in. - if ($checkin && (count($pks) == $this->_db->getAffectedRows())) - { - // Checkin the rows. - foreach ($pks as $pk) - { - $this->checkin($pk); - } - } - - // If the JTable instance value is in the list of primary keys that were set, set the instance. - if (in_array($this->$k, $pks)) - { - $this->state = $state; - } - - $this->setError(''); - - return true; - } + /** + * Constructor + * + * @param JDatabaseDriver $db Database driver object. + * + * @since 11.1 + */ + public function __construct($db) + { + parent::__construct('#__redshop_product_attribute', 'attribute_id', $db); + } + + /** + * Method to set the publishing state for a row or list of rows in the database + * table. The method respects checked out rows by other users and will attempt + * to checkin rows that it can after adjustments are made. + * + * @param mixed $pks An optional array of primary key values to update. If not set the instance property value is used. + * @param integer $state The publishing state. eg. [0 = unpublished, 1 = published, 2=archived, -2=trashed] + * @param integer $userId The user id of the user performing the operation. + * + * @return boolean True on success. + * + * @since 1.0.4 + */ + public function publish($pks = null, $state = 1, $userId = 0) + { + $k = $this->_tbl_key; + + // Sanitize input. + $pks = ArrayHelper::toInteger($pks); + $userId = (int)$userId; + $state = (int)$state; + + // If there are no primary keys set check to see if the instance key is set. + if (empty($pks)) { + if ($this->$k) { + $pks = array($this->$k); + } // Nothing to set publishing state on, return false. + else { + $this->setError(JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED')); + + return false; + } + } + + // Build the WHERE clause for the primary keys. + $where = $k . '=' . implode(' OR ' . $k . '=', $pks); + + // Determine if there is checkin support for the table. + if (!property_exists($this, 'checked_out') || !property_exists($this, 'checked_out_time')) { + $checkin = ''; + } else { + $checkin = ' AND (checked_out = 0 OR checked_out = ' . (int)$userId . ')'; + } + + // Update the publishing state for rows with the given primary keys. + $this->_db->setQuery( + 'UPDATE ' . $this->_db->quoteName($this->_tbl) + . ' SET ' . $this->_db->quoteName('attribute_published') . ' = ' . (int)$state + . ' WHERE (' . $where . ')' + . $checkin + ); + + try { + $this->_db->execute(); + } catch (RuntimeException $e) { + $this->setError($e->getMessage()); + + return false; + } + + // If checkin is supported and all rows were adjusted, check them in. + if ($checkin && (count($pks) == $this->_db->getAffectedRows())) { + // Checkin the rows. + foreach ($pks as $pk) { + $this->checkin($pk); + } + } + + // If the JTable instance value is in the list of primary keys that were set, set the instance. + if (in_array($this->$k, $pks)) { + $this->state = $state; + } + + $this->setError(''); + + return true; + } } diff --git a/component/admin/tables/attribute_property.php b/component/admin/tables/attribute_property.php index 1716c744e4e..6d1a07caa09 100644 --- a/component/admin/tables/attribute_property.php +++ b/component/admin/tables/attribute_property.php @@ -11,50 +11,49 @@ class Tableattribute_property extends JTable { - public $propertyId = null; + public $propertyId = null; - public $attributeId = null; + public $attributeId = null; - public $property_name = null; + public $property_name = null; - public $property_price = null; + public $property_price = null; - public $oprand = null; + public $oprand = null; - public $property_image = null; + public $property_image = null; - public $property_main_image = null; + public $property_main_image = null; - public $ordering = null; + public $ordering = null; - public $property_number = null; + public $property_number = null; - public $setdefault_selected = 0; + public $setdefault_selected = 0; - public $setrequire_selected = 0; + public $setrequire_selected = 0; - public $setmulti_selected = 0; + public $setmulti_selected = 0; - public $setdisplay_type = null; + public $setdisplay_type = null; - public $property_published = 1; + public $property_published = 1; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_attribute_property', 'property_id', $db); - } + parent::__construct($this->_table_prefix . 'product_attribute_property', 'property_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/attribute_set_detail.php b/component/admin/tables/attribute_set_detail.php index 3bd4ee0a4d9..e6f092784be 100644 --- a/component/admin/tables/attribute_set_detail.php +++ b/component/admin/tables/attribute_set_detail.php @@ -11,28 +11,27 @@ class Tableattribute_set_detail extends JTable { - public $attribute_set_id = null; + public $attribute_set_id = null; - public $attribute_set_name = 0; + public $attribute_set_name = 0; - public $published = null; + public $published = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'attribute_set', 'attribute_set_id', $db); - } + parent::__construct($this->_table_prefix . 'attribute_set', 'attribute_set_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/attributeprices_detail.php b/component/admin/tables/attributeprices_detail.php index 8de915b7bbf..87ccec2f3aa 100644 --- a/component/admin/tables/attributeprices_detail.php +++ b/component/admin/tables/attributeprices_detail.php @@ -61,9 +61,9 @@ public function __construct(&$db) */ public function check() { - $xid = \Redshop\Attribute\Helper::getAttributePriceStartId($this); + $xid = \Redshop\Attribute\Helper::getAttributePriceStartId($this); $xidEnd = \Redshop\Attribute\Helper::getAttributePriceStartId($this); - + if (($xid || $xidEnd) && (($xid != intval($this->price_id) @@ -73,7 +73,8 @@ public function check() ) { $this->_error = \Joomla\CMS\Language\Text::sprintf( 'WARNNAMETRYAGAIN', - \Joomla\CMS\Language\Text::_('COM_REDSHOP_PRICE_ALREADY_EXISTS')); + \Joomla\CMS\Language\Text::_('COM_REDSHOP_PRICE_ALREADY_EXISTS') + ); return false; } diff --git a/component/admin/tables/barcode.php b/component/admin/tables/barcode.php index c2f36309fcb..684493b8f3c 100644 --- a/component/admin/tables/barcode.php +++ b/component/admin/tables/barcode.php @@ -18,32 +18,32 @@ */ class TableBarcode extends JTable { - /** - * Primary Key - * - * @var integer - */ - public $log_id = null; + /** + * Primary Key + * + * @var integer + */ + public $log_id = null; - /** - * @var string - */ - public $order_id = null; + /** + * @var string + */ + public $order_id = null; - public $user_id = null; + public $user_id = null; - public $barcode = null; + public $barcode = null; - public $search_date = null; + public $search_date = null; - /** - * Constructor - * - * @param object Database connector object - */ - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'orderbarcode_log', 'log_id', $db); - } + /** + * Constructor + * + * @param object Database connector object + */ + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; + parent::__construct($this->_table_prefix . 'orderbarcode_log', 'log_id', $db); + } } diff --git a/component/admin/tables/catalog.php b/component/admin/tables/catalog.php index 95ff80e23e5..9ea0f4a236c 100644 --- a/component/admin/tables/catalog.php +++ b/component/admin/tables/catalog.php @@ -18,17 +18,17 @@ */ class RedshopTableCatalog extends RedshopTable { - /** - * The table name without prefix. - * - * @var string - */ - protected $_tableName = 'redshop_catalog'; + /** + * The table name without prefix. + * + * @var string + */ + protected $_tableName = 'redshop_catalog'; - /** - * The table key column - * - * @var string - */ - protected $_tableKey = 'catalog_id'; + /** + * The table key column + * + * @var string + */ + protected $_tableKey = 'catalog_id'; } diff --git a/component/admin/tables/catalog_request.php b/component/admin/tables/catalog_request.php index d2423582279..9c5deee9e57 100644 --- a/component/admin/tables/catalog_request.php +++ b/component/admin/tables/catalog_request.php @@ -11,34 +11,33 @@ class Tablecatalog_request extends JTable { - public $catalog_user_id = null; + public $catalog_user_id = null; - public $catalog_id = null; + public $catalog_id = null; - public $name = null; + public $name = null; - public $email = null; + public $email = null; - public $registerDate = null; + public $registerDate = null; - public $block = null; + public $block = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'catalog_request', 'catalog_user_id', $db); - } + parent::__construct($this->_table_prefix . 'catalog_request', 'catalog_user_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/category.php b/component/admin/tables/category.php index 630fb2dc4a2..a088a5ffdf7 100644 --- a/component/admin/tables/category.php +++ b/component/admin/tables/category.php @@ -18,195 +18,182 @@ */ class RedshopTableCategory extends RedshopTableNested { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_category'; - - /** - * @var integer - */ - public $id; - - /** - * @var string - */ - public $name; - - /** - * @var string - */ - public $category_thumb_image; - - /** - * @var string - */ - public $description; - - /** - * @var string - */ - public $category_full_image; - - /** - * @var string - */ - public $metakey; - - /** - * @var string - */ - public $metadesc; - - /** - * @var integer - */ - public $template; - - /** - * @var integer - */ - public $published; - - /** - * @var integer - */ - public $category_pdate; - - /** - * @var integer - */ - public $products_per_page; - - /** - * Event name to trigger after delete(). - * - * @var string - */ - protected $_eventAfterDelete = 'onAfterDeleteCategory'; - - /** - * @var integer - */ - public $ordering; - - /** - * Called delete(). - * - * @param integer $pk The primary key of the node to delete. - * @param boolean $children True to delete child nodes, false to move them up a level. - * - * @return boolean True on success. - */ - protected function doDelete($pk = null, $children = true) - { - $db = $this->getDbo(); - - // Check child category - $query = $db->getQuery(true) - ->select('COUNT(*) AS ctotal') - ->select($db->qn('name')) - ->from($db->qn('#__redshop_category')) - ->where($db->qn('parent_id') . ' = ' . (int)$this->id); - - $childCount = $db->setQuery($query)->loadResult(); - - if ($childCount > 0) { - $this->setError(JText::sprintf('COM_REDSHOP_CATEGORY_PARENT_ERROR_MSG', $this->name, $this->id)); - - return false; - } - - // Check products - $productCount = RedshopEntityCategory::getInstance($this->id)->productCount(); - - if ($productCount > 0) { - $this->setError(JText::sprintf('COM_REDSHOP_CATEGORY_EXIST_PRODUCT', $this->name, $this->id)); - - return false; - } - - // Remove thumb images. - if (!empty($this->category_thumb_image)) { - $thumbPath = REDSHOP_FRONT_IMAGES_RELPATH . 'category/thumb/' . $this->category_thumb_image; - - if (JFile::exists($thumbPath)) { - JFile::delete($thumbPath); - } - } - - // Remove full images. - if (!empty($this->category_full_image)) { - $fullImagePath = REDSHOP_FRONT_IMAGES_RELPATH . 'category/thumb/' . $this->category_full_image; - - if (JFile::exists($fullImagePath)) { - JFile::delete($fullImagePath); - } - } - - // Remove reference with products - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_product_category_xref')) - ->where($db->qn('category_id') . ' = ' . $this->id); - $db->setQuery($query)->execute(); - - // Force do not delete child categories - return parent::doDelete($pk, false); - } - - /** - * Do the database store. - * - * @param boolean $updateNulls True to update null values as well. - * - * @return boolean - * @since 2.1.0 - */ - protected function doStore($updateNulls = false) - { - if (!parent::doStore($updateNulls)) { - return false; - } - - // Prepare target folder. - \Redshop\Helper\Media::createFolder(REDSHOP_MEDIA_IMAGE_RELPATH . 'category/' . $this->id); - - // Prepare target folder. - \Redshop\Helper\Media::createFolder(REDSHOP_MEDIA_IMAGE_RELPATH . 'category/' . $this->id . '/thumb'); - - /** @var RedshopModelCategory $model */ - $model = RedshopModel::getInstance('Category', 'RedshopModel'); - $media = $this->getOption('media', array()); - - if (!empty($media['category_full_image'])) { - $model->storeMedia($this, $media['category_full_image'], 'full'); - } - - if (!empty($media['category_back_full_image'])) { - $model->storeMedia($this, $media['category_back_full_image'], 'back'); - } - - return true; - } - - /** - * Called check(). - * - * @return boolean True on success. - * @throws Exception - * - * @since 2.1.0 - */ - protected function doCheck() - { - if (empty(trim($this->name))) { - $this->setError(JText::_('COM_REDSHOP_TOOLTIP_CATEGORY_NAME')); - - return false; - } - - return parent::doCheck(); - } + /** + * @var integer + */ + public $id; + /** + * @var string + */ + public $name; + /** + * @var string + */ + public $category_thumb_image; + /** + * @var string + */ + public $description; + /** + * @var string + */ + public $category_full_image; + /** + * @var string + */ + public $metakey; + /** + * @var string + */ + public $metadesc; + /** + * @var integer + */ + public $template; + /** + * @var integer + */ + public $published; + /** + * @var integer + */ + public $category_pdate; + /** + * @var integer + */ + public $products_per_page; + /** + * @var integer + */ + public $ordering; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_category'; + /** + * Event name to trigger after delete(). + * + * @var string + */ + protected $_eventAfterDelete = 'onAfterDeleteCategory'; + + /** + * Called delete(). + * + * @param integer $pk The primary key of the node to delete. + * @param boolean $children True to delete child nodes, false to move them up a level. + * + * @return boolean True on success. + */ + protected function doDelete($pk = null, $children = true) + { + $db = $this->getDbo(); + + // Check child category + $query = $db->getQuery(true) + ->select('COUNT(*) AS ctotal') + ->select($db->qn('name')) + ->from($db->qn('#__redshop_category')) + ->where($db->qn('parent_id') . ' = ' . (int)$this->id); + + $childCount = $db->setQuery($query)->loadResult(); + + if ($childCount > 0) { + $this->setError(JText::sprintf('COM_REDSHOP_CATEGORY_PARENT_ERROR_MSG', $this->name, $this->id)); + + return false; + } + + // Check products + $productCount = RedshopEntityCategory::getInstance($this->id)->productCount(); + + if ($productCount > 0) { + $this->setError(JText::sprintf('COM_REDSHOP_CATEGORY_EXIST_PRODUCT', $this->name, $this->id)); + + return false; + } + + // Remove thumb images. + if (!empty($this->category_thumb_image)) { + $thumbPath = REDSHOP_FRONT_IMAGES_RELPATH . 'category/thumb/' . $this->category_thumb_image; + + if (JFile::exists($thumbPath)) { + JFile::delete($thumbPath); + } + } + + // Remove full images. + if (!empty($this->category_full_image)) { + $fullImagePath = REDSHOP_FRONT_IMAGES_RELPATH . 'category/thumb/' . $this->category_full_image; + + if (JFile::exists($fullImagePath)) { + JFile::delete($fullImagePath); + } + } + + // Remove reference with products + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_product_category_xref')) + ->where($db->qn('category_id') . ' = ' . $this->id); + $db->setQuery($query)->execute(); + + // Force do not delete child categories + return parent::doDelete($pk, false); + } + + /** + * Do the database store. + * + * @param boolean $updateNulls True to update null values as well. + * + * @return boolean + * @since 2.1.0 + */ + protected function doStore($updateNulls = false) + { + if (!parent::doStore($updateNulls)) { + return false; + } + + // Prepare target folder. + \Redshop\Helper\Media::createFolder(REDSHOP_MEDIA_IMAGE_RELPATH . 'category/' . $this->id); + + // Prepare target folder. + \Redshop\Helper\Media::createFolder(REDSHOP_MEDIA_IMAGE_RELPATH . 'category/' . $this->id . '/thumb'); + + /** @var RedshopModelCategory $model */ + $model = RedshopModel::getInstance('Category', 'RedshopModel'); + $media = $this->getOption('media', array()); + + if (!empty($media['category_full_image'])) { + $model->storeMedia($this, $media['category_full_image'], 'full'); + } + + if (!empty($media['category_back_full_image'])) { + $model->storeMedia($this, $media['category_back_full_image'], 'back'); + } + + return true; + } + + /** + * Called check(). + * + * @return boolean True on success. + * @throws Exception + * + * @since 2.1.0 + */ + protected function doCheck() + { + if (empty(trim($this->name))) { + $this->setError(JText::_('COM_REDSHOP_TOOLTIP_CATEGORY_NAME')); + + return false; + } + + return parent::doCheck(); + } } diff --git a/component/admin/tables/country.php b/component/admin/tables/country.php index 7bc81052854..d273307ee15 100644 --- a/component/admin/tables/country.php +++ b/component/admin/tables/country.php @@ -18,74 +18,74 @@ */ class RedshopTableCountry extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_country'; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_country'; - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (!parent::doCheck()) - { - return false; - } + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (!parent::doCheck()) { + return false; + } - if (empty($this->country_name)) - { - return false; - } + if (empty($this->country_name)) { + return false; + } - if (empty($this->country_3_code)) - { - return false; - } + if (empty($this->country_3_code)) { + return false; + } - if (empty($this->country_2_code)) - { - return false; - } + if (empty($this->country_2_code)) { + return false; + } - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query->select($db->qn(array('id', 'country_3_code'))) - ->from($db->qn('#__redshop_country')) - ->where($db->qn('country_3_code') . ' = ' . $db->quote($this->country_3_code) . ' AND ' . $db->qn('id') . ' != ' . $db->q($this->id)); + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->select($db->qn(array('id', 'country_3_code'))) + ->from($db->qn('#__redshop_country')) + ->where( + $db->qn('country_3_code') . ' = ' . $db->quote($this->country_3_code) . ' AND ' . $db->qn( + 'id' + ) . ' != ' . $db->q($this->id) + ); - $xid = $db->setQuery($query)->loadResult(); + $xid = $db->setQuery($query)->loadResult(); - if ($xid) - { - $this->setError(JText::_('COM_REDSHOP_COUNTRY_CODE_3_ALREADY_EXISTS')); + if ($xid) { + $this->setError(JText::_('COM_REDSHOP_COUNTRY_CODE_3_ALREADY_EXISTS')); - return false; - } - else - { - $query = $db->getQuery(true); - $query->select($db->qn(array('id', 'country_3_code', 'country_2_code'))) - ->from($db->qn('#__redshop_country')) - ->where($db->qn('country_2_code') . ' = ' . $db->q($this->country_2_code) . ' AND ' . $db->qn('id') . ' != ' . $db->q($this->id)); + return false; + } else { + $query = $db->getQuery(true); + $query->select($db->qn(array('id', 'country_3_code', 'country_2_code'))) + ->from($db->qn('#__redshop_country')) + ->where( + $db->qn('country_2_code') . ' = ' . $db->q($this->country_2_code) . ' AND ' . $db->qn( + 'id' + ) . ' != ' . $db->q($this->id) + ); - $xid = $db->setQuery($query)->loadResult(); + $xid = $db->setQuery($query)->loadResult(); - if ($xid) - { - $this->setError(JText::_('COM_REDSHOP_COUNTRY_CODE_2_ALREADY_EXISTS')); + if ($xid) { + $this->setError(JText::_('COM_REDSHOP_COUNTRY_CODE_2_ALREADY_EXISTS')); - return false; - } - } + return false; + } + } - return true; - } + return true; + } } diff --git a/component/admin/tables/coupon.php b/component/admin/tables/coupon.php index 97993bc47f3..59ea0526a23 100644 --- a/component/admin/tables/coupon.php +++ b/component/admin/tables/coupon.php @@ -13,170 +13,146 @@ * Table Coupon * * @package RedSHOP.Backend - * @subpackage Table + * @subpackage Table * @since 2.1.0 */ class RedshopTableCoupon extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_coupons'; - - /** - * @var integer - */ - public $id; - - /** - * @var string - */ - public $code; - - /** - * @var integer - */ - public $type = 0; - - /** - * @var float - */ - public $value = 0.00; - - /** - * @var string - */ - public $start_date = '0000-00-00 00:00:00'; - - /** - * @var string - */ - public $end_date = '0000-00-00 00:00:00'; - - /** - * @var integer - */ - public $effect = 0; - - /** - * @var integer - */ - public $userid; - - /** - * @var integer - */ - public $amount_left; - - /** - * @var integer - */ - public $published; - - /** - * @var integer - */ - public $subtotal; - - /** - * @var integer - */ - public $order_id; - - /** - * @var integer - */ - public $free_shipping; - - /** - * @var integer - */ - public $created_by; - - /** - * @var string - */ - public $created_date = '0000-00-00 00:00:00'; - - /** - * @var integer - */ - public $checked_out; - - /** - * @var string - */ - public $checked_out_time = '0000-00-00 00:00:00'; - - /** - * @var integer - */ - public $modified_by; - - /** - * @var string - */ - public $modified_date = '0000-00-00 00:00:00'; - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (!parent::doCheck()) - { - return false; - } - - if (empty($this->code)) - { - return false; - } - - if (empty($this->value)) - { - return false; - } - - $db = $this->getDbo(); - - // Check duplicate. - $code = $this->get('code'); - - $voucherQuery = $db->getQuery(true) - ->select($db->qn('code')) - ->from($db->qn('#__redshop_voucher')); - - $couponQuery = $db->getQuery(true) - ->select($db->qn('code')) - ->from($db->qn('#__redshop_coupons')); - - if ($this->hasPrimaryKey()) - { - $couponQuery->where($db->qn('id') . ' <> ' . $this->id); - } - - $couponQuery->union($voucherQuery); - - $query = $db->getQuery(true) - ->select('COUNT(*)') - ->from('(' . $couponQuery . ') AS ' . $db->qn('data')) - ->where($db->qn('data.code') . ' = ' . $db->quote($code)); - - if ($db->setQuery($query)->loadResult()) - { - $this->setError(JText::_('COM_REDSHOP_COUPON_ERROR_CODE_ALREADY_EXIST')); - - return false; - } - - return true; - } + /** + * @var integer + */ + public $id; + /** + * @var string + */ + public $code; + /** + * @var integer + */ + public $type = 0; + /** + * @var float + */ + public $value = 0.00; + /** + * @var string + */ + public $start_date = '0000-00-00 00:00:00'; + /** + * @var string + */ + public $end_date = '0000-00-00 00:00:00'; + /** + * @var integer + */ + public $effect = 0; + /** + * @var integer + */ + public $userid; + /** + * @var integer + */ + public $amount_left; + /** + * @var integer + */ + public $published; + /** + * @var integer + */ + public $subtotal; + /** + * @var integer + */ + public $order_id; + /** + * @var integer + */ + public $free_shipping; + /** + * @var integer + */ + public $created_by; + /** + * @var string + */ + public $created_date = '0000-00-00 00:00:00'; + /** + * @var integer + */ + public $checked_out; + /** + * @var string + */ + public $checked_out_time = '0000-00-00 00:00:00'; + /** + * @var integer + */ + public $modified_by; + /** + * @var string + */ + public $modified_date = '0000-00-00 00:00:00'; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_coupons'; + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (!parent::doCheck()) { + return false; + } + + if (empty($this->code)) { + return false; + } + + if (empty($this->value)) { + return false; + } + + $db = $this->getDbo(); + + // Check duplicate. + $code = $this->get('code'); + + $voucherQuery = $db->getQuery(true) + ->select($db->qn('code')) + ->from($db->qn('#__redshop_voucher')); + + $couponQuery = $db->getQuery(true) + ->select($db->qn('code')) + ->from($db->qn('#__redshop_coupons')); + + if ($this->hasPrimaryKey()) { + $couponQuery->where($db->qn('id') . ' <> ' . $this->id); + } + + $couponQuery->union($voucherQuery); + + $query = $db->getQuery(true) + ->select('COUNT(*)') + ->from('(' . $couponQuery . ') AS ' . $db->qn('data')) + ->where($db->qn('data.code') . ' = ' . $db->quote($code)); + + if ($db->setQuery($query)->loadResult()) { + $this->setError(JText::_('COM_REDSHOP_COUPON_ERROR_CODE_ALREADY_EXIST')); + + return false; + } + + return true; + } } diff --git a/component/admin/tables/currency.php b/component/admin/tables/currency.php index c0a73f13beb..d0c6fac4a93 100644 --- a/component/admin/tables/currency.php +++ b/component/admin/tables/currency.php @@ -18,126 +18,113 @@ */ class RedshopTableCurrency extends RedshopTable { - /** - * @var string - */ - protected $_tableName = 'redshop_currency'; - - /** - * @var integer - */ - public $id; - - /** - * @var string - */ - public $name; - - /** - * @var string - */ - public $code; - - /** - * @var integer - */ - public $created_by; - - /** - * @var string - */ - public $created_date = '0000-00-00 00:00:00'; - - /** - * @var integer - */ - public $checked_out; - - /** - * @var string - */ - public $checked_out_time = '0000-00-00 00:00:00'; - - /** - * @var integer - */ - public $modified_by; - - /** - * @var string - */ - public $modified_date = '0000-00-00 00:00:00'; - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (!parent::doCheck()) - { - return false; - } - - if (empty(trim($this->name))) - { - return false; - } - - if (empty(trim($this->code))) - { - return false; - } - - $db = $this->getDbo(); - - // Check duplicate. - $code = $this->get('code'); - - $codeQuery = $db->getQuery(true) - ->select($db->qn('code')) - ->from($db->qn('#__' . $this->_tableName)); - - if ($this->hasPrimaryKey()) - { - $codeQuery->where($db->qn('id') . ' <> ' . $this->id); - } - - $query = $db->getQuery(true) - ->select('COUNT(*)') - ->from('(' . $codeQuery . ') AS ' . $db->qn('data')) - ->where($db->qn('data.code') . ' = ' . $db->q($code)); - - if ($db->setQuery($query)->loadResult()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_CURRENCY_CODE_ALREADY_EXISTS')); - - return false; - } - - return true; - } - - /** - * Delete one or more registers - * - * @param mixed $pk Array of ids or ids comma separated - * - * @return boolean Deleted successfully? - */ - protected function doDelete($pk = null) - { - if (Redshop::getConfig()->get('CURRENCY_CODE') == $this->code) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_CURRENCY_ERROR_DELETE_CURRENCY_SET_IN_CONFIG')); - - return false; - } - - return parent::doDelete(); - } + /** + * @var integer + */ + public $id; + /** + * @var string + */ + public $name; + /** + * @var string + */ + public $code; + /** + * @var integer + */ + public $created_by; + /** + * @var string + */ + public $created_date = '0000-00-00 00:00:00'; + /** + * @var integer + */ + public $checked_out; + /** + * @var string + */ + public $checked_out_time = '0000-00-00 00:00:00'; + /** + * @var integer + */ + public $modified_by; + /** + * @var string + */ + public $modified_date = '0000-00-00 00:00:00'; + /** + * @var string + */ + protected $_tableName = 'redshop_currency'; + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (!parent::doCheck()) { + return false; + } + + if (empty(trim($this->name))) { + return false; + } + + if (empty(trim($this->code))) { + return false; + } + + $db = $this->getDbo(); + + // Check duplicate. + $code = $this->get('code'); + + $codeQuery = $db->getQuery(true) + ->select($db->qn('code')) + ->from($db->qn('#__' . $this->_tableName)); + + if ($this->hasPrimaryKey()) { + $codeQuery->where($db->qn('id') . ' <> ' . $this->id); + } + + $query = $db->getQuery(true) + ->select('COUNT(*)') + ->from('(' . $codeQuery . ') AS ' . $db->qn('data')) + ->where($db->qn('data.code') . ' = ' . $db->q($code)); + + if ($db->setQuery($query)->loadResult()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_CURRENCY_CODE_ALREADY_EXISTS')); + + return false; + } + + return true; + } + + /** + * Delete one or more registers + * + * @param mixed $pk Array of ids or ids comma separated + * + * @return boolean Deleted successfully? + */ + protected function doDelete($pk = null) + { + if (Redshop::getConfig()->get('CURRENCY_CODE') == $this->code) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_CURRENCY_ERROR_DELETE_CURRENCY_SET_IN_CONFIG')); + + return false; + } + + return parent::doDelete(); + } } diff --git a/component/admin/tables/discount.php b/component/admin/tables/discount.php index 0aa75500fd2..aa99f559b32 100644 --- a/component/admin/tables/discount.php +++ b/component/admin/tables/discount.php @@ -18,233 +18,218 @@ */ class RedshopTableDiscount extends RedshopTable { - /** - * The table name without the prefix. - * - * @var string - */ - protected $_tableName = 'redshop_discount'; - - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'discount_id'; - - /** - * @var integer - */ - public $discount_id; - - /** - * @var string - */ - public $name; - - /** - * @var integer - */ - public $amount = 0; - - /** - * @var integer - */ - public $condition = 1; - - /** - * @var float - */ - public $discount_amount = 0.0; - - /** - * @var integer - */ - public $discount_type = 0; - - /** - * @var string - */ - public $start_date; - - /** - * @var string - */ - public $end_date; - - /** - * @var integer - */ - public $published = 1; - - /** - * Do the database store. - * - * @param boolean $updateNulls True to update null values as well. - * - * @return boolean - */ - protected function doStore($updateNulls = false) - { - if (!parent::doStore($updateNulls)) - { - return false; - } - - if ($this->getOption('inlineMode', false) === true) - { - return true; - } - - return $this->updateShopperGroups(); - } - - /** - * Method for update shopper group xref. - * - * @return boolean - */ - protected function updateShopperGroups() - { - $db = $this->getDbo(); - - // Clear current reference products. - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_discount_shoppers')) - ->where($db->qn('discount_id') . ' = ' . $this->discount_id); - $db->setQuery($query)->execute(); - - $shopperGroupIds = $this->getOption('shopperGroups', null); - - if (empty($shopperGroupIds) || empty(array_filter($shopperGroupIds))) - { - return true; - } - - $query->clear() - ->insert($db->qn('#__redshop_discount_shoppers')) - ->columns($db->qn(array('discount_id', 'shopper_group_id'))); - - foreach ($shopperGroupIds as $shopperGroupId) - { - $query->values((int) $this->discount_id . ',' . (int) $shopperGroupId); - } - - return $db->setQuery($query)->execute(); - } - - /** - * Method to bind an associative array or object to the JTable instance.This - * method only binds properties that are publicly accessible and optionally - * takes an array of properties to ignore when binding. - * - * @param mixed $src An associative array or object to bind to the JTable instance. - * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. - * - * @return boolean True on success. - * - * @throws Exception - */ - protected function doBind(&$src, $ignore = array()) - { - if (isset($src['shopper_group']) && !empty($src['shopper_group'])) - { - $shopperGroups = is_string($src['shopper_group']) ? explode(',', $src['shopper_group']) : $src['shopper_group']; - $this->setOption('shopperGroups', array_filter($shopperGroups)); - unset($src['shopper_group']); - } - - return parent::doBind($src, $ignore); - } - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (empty($this->name)) - { - return false; - } - - // Check amount - if ((float) $this->amount <= 0.0) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_DISCOUNT_ERROR_AMOUNT_ZERO')); - - return false; - } - - // Check discount amount - if ((float) $this->discount_amount <= 0.0) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_DISCOUNT_ERROR_DISCOUNT_AMOUNT_ZERO')); - - return false; - } - - // Check amount and discount amount - if (((float) $this->amount) < (float) $this->discount_amount) - { - /** @scrutinizer ignore-deprecated */ - $this->setError(JText::_('COM_REDSHOP_DISCOUNT_ERROR_AMOUNT_HIGHT_DISCOUNT_AMOUNT')); - - return false; - } - - // If discount type is percent. Make sure discount amount not higher than 100. - if ($this->discount_type == 1 && $this->discount_amount > 100) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_DISCOUNT_ERROR_DISCOUNT_PERCENTAGE')); - - return false; - } - - // If discount type is percent. Make sure discount amount not higher than 100. - if (!empty($this->start_date) && !empty($this->end_date) && $this->start_date >= $this->end_date) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_DISCOUNT_ERROR_START_DATE_SAME_HIGH_END_DATE')); - - return false; - } - - // Check shopper groups - if (empty($this->getOption('shopperGroups', array()))) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_DISCOUNT_ERROR_MISSING_SHOPPER_GROUPS')); - - return false; - } - - return parent::doCheck(); - } - - /** - * Delete one or more registers - * - * @param mixed $pk Array of ids or ids comma separated - * - * @return boolean Deleted successfully? - */ - public function doDelete($pk = null) - { - $discountId = $this->discount_id; - - if (!parent::doDelete($pk)) - { - return false; - } - - $db = $this->getDbo(); - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_discount_shoppers')) - ->where($db->qn('discount_id') . ' = ' . $discountId); - - return $db->setQuery($query)->execute(); - } + /** + * @var integer + */ + public $discount_id; + /** + * @var string + */ + public $name; + /** + * @var integer + */ + public $amount = 0; + /** + * @var integer + */ + public $condition = 1; + /** + * @var float + */ + public $discount_amount = 0.0; + /** + * @var integer + */ + public $discount_type = 0; + /** + * @var string + */ + public $start_date; + /** + * @var string + */ + public $end_date; + /** + * @var integer + */ + public $published = 1; + /** + * The table name without the prefix. + * + * @var string + */ + protected $_tableName = 'redshop_discount'; + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'discount_id'; + + /** + * Delete one or more registers + * + * @param mixed $pk Array of ids or ids comma separated + * + * @return boolean Deleted successfully? + */ + public function doDelete($pk = null) + { + $discountId = $this->discount_id; + + if (!parent::doDelete($pk)) { + return false; + } + + $db = $this->getDbo(); + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_discount_shoppers')) + ->where($db->qn('discount_id') . ' = ' . $discountId); + + return $db->setQuery($query)->execute(); + } + + /** + * Do the database store. + * + * @param boolean $updateNulls True to update null values as well. + * + * @return boolean + */ + protected function doStore($updateNulls = false) + { + if (!parent::doStore($updateNulls)) { + return false; + } + + if ($this->getOption('inlineMode', false) === true) { + return true; + } + + return $this->updateShopperGroups(); + } + + /** + * Method for update shopper group xref. + * + * @return boolean + */ + protected function updateShopperGroups() + { + $db = $this->getDbo(); + + // Clear current reference products. + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_discount_shoppers')) + ->where($db->qn('discount_id') . ' = ' . $this->discount_id); + $db->setQuery($query)->execute(); + + $shopperGroupIds = $this->getOption('shopperGroups', null); + + if (empty($shopperGroupIds) || empty(array_filter($shopperGroupIds))) { + return true; + } + + $query->clear() + ->insert($db->qn('#__redshop_discount_shoppers')) + ->columns($db->qn(array('discount_id', 'shopper_group_id'))); + + foreach ($shopperGroupIds as $shopperGroupId) { + $query->values((int)$this->discount_id . ',' . (int)$shopperGroupId); + } + + return $db->setQuery($query)->execute(); + } + + /** + * Method to bind an associative array or object to the JTable instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param mixed $src An associative array or object to bind to the JTable instance. + * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + * + * @throws Exception + */ + protected function doBind(&$src, $ignore = array()) + { + if (isset($src['shopper_group']) && !empty($src['shopper_group'])) { + $shopperGroups = is_string($src['shopper_group']) ? explode( + ',', + $src['shopper_group'] + ) : $src['shopper_group']; + $this->setOption('shopperGroups', array_filter($shopperGroups)); + unset($src['shopper_group']); + } + + return parent::doBind($src, $ignore); + } + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (empty($this->name)) { + return false; + } + + // Check amount + if ((float)$this->amount <= 0.0) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_DISCOUNT_ERROR_AMOUNT_ZERO')); + + return false; + } + + // Check discount amount + if ((float)$this->discount_amount <= 0.0) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_DISCOUNT_ERROR_DISCOUNT_AMOUNT_ZERO')); + + return false; + } + + // Check amount and discount amount + if (((float)$this->amount) < (float)$this->discount_amount) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_DISCOUNT_ERROR_AMOUNT_HIGHT_DISCOUNT_AMOUNT')); + + return false; + } + + // If discount type is percent. Make sure discount amount not higher than 100. + if ($this->discount_type == 1 && $this->discount_amount > 100) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_DISCOUNT_ERROR_DISCOUNT_PERCENTAGE')); + + return false; + } + + // If discount type is percent. Make sure discount amount not higher than 100. + if (!empty($this->start_date) && !empty($this->end_date) && $this->start_date >= $this->end_date) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_DISCOUNT_ERROR_START_DATE_SAME_HIGH_END_DATE')); + + return false; + } + + // Check shopper groups + if (empty($this->getOption('shopperGroups', array()))) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_DISCOUNT_ERROR_MISSING_SHOPPER_GROUPS')); + + return false; + } + + return parent::doCheck(); + } } diff --git a/component/admin/tables/discount_product.php b/component/admin/tables/discount_product.php index 93f433df48b..c2969752b21 100644 --- a/component/admin/tables/discount_product.php +++ b/component/admin/tables/discount_product.php @@ -18,228 +18,214 @@ */ class RedshopTableDiscount_Product extends RedshopTable { - /** - * The table name without the prefix. - * - * @var string - */ - protected $_tableName = 'redshop_discount_product'; - - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'discount_product_id'; - - /** - * @var integer - */ - public $discount_product_id; - - /** - * @var integer - */ - public $amount = 0; - - /** - * @var integer - */ - public $condition = 1; - - /** - * @var float - */ - public $discount_amount = 0.0; - - /** - * @var integer - */ - public $discount_type = 0; - - /** - * @var integer - */ - public $start_date = 0; - - /** - * @var integer - */ - public $end_date = 0; - - /** - * @var integer - */ - public $published = 1; - - /** - * @var string - */ - public $category_ids = ''; - - /** - * Do the database store. - * - * @param boolean $updateNulls True to update null values as well. - * - * @return boolean - */ - protected function doStore($updateNulls = false) - { - if (!parent::doStore($updateNulls)) - { - return false; - } - - if ($this->getOption('inlineMode', false) === true) - { - return true; - } - - return $this->updateShopperGroups(); - } - - /** - * Method for update shopper group xref. - * - * @return boolean - */ - protected function updateShopperGroups() - { - $db = $this->getDbo(); - - // Clear current reference products. - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_discount_product_shoppers')) - ->where($db->qn('discount_product_id') . ' = ' . $this->discount_product_id); - $db->setQuery($query)->execute(); - - $shopperGroupIds = $this->getOption('shopperGroups', null); - - if (empty($shopperGroupIds) || empty(array_filter($shopperGroupIds))) - { - return true; - } - - $query->clear() - ->insert($db->qn('#__redshop_discount_product_shoppers')) - ->columns($db->qn(array('discount_product_id', 'shopper_group_id'))); - - foreach ($shopperGroupIds as $shopperGroupId) - { - $query->values((int) $this->discount_product_id . ',' . (int) $shopperGroupId); - } - - return $db->setQuery($query)->execute(); - } - - /** - * Method to bind an associative array or object to the JTable instance.This - * method only binds properties that are publicly accessible and optionally - * takes an array of properties to ignore when binding. - * - * @param mixed $src An associative array or object to bind to the JTable instance. - * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. - * - * @return boolean True on success. - * - * @throws Exception - */ - protected function doBind(&$src, $ignore = array()) - { - if (isset($src['shopper_group']) && !empty($src['shopper_group'])) - { - $shopperGroups = is_string($src['shopper_group']) ? explode(',', $src['shopper_group']) : $src['shopper_group']; - $this->setOption('shopperGroups', array_values(array_filter($shopperGroups))); - unset($src['shopper_group']); - } - - return parent::doBind($src, $ignore); - } - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - // Check amount - if ((float) $this->amount <= 0.0) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_DISCOUNT_PRODUCT_ERROR_AMOUNT_ZERO')); - - return false; - } - - // Check discount amount - if ((float) $this->discount_amount <= 0.0) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_DISCOUNT_PRODUCT_ERROR_DISCOUNT_AMOUNT_ZERO')); - - return false; - } - - // Check amount and discount amount - if (((float) $this->amount) < (float) $this->discount_amount) - { - /** @scrutinizer ignore-deprecated */ - $this->setError(JText::_('COM_REDSHOP_DISCOUNT_PRODUCT_ERROR_AMOUNT_HIGHT_DISCOUNT_AMOUNT')); - - return false; - } - - // If discount type is percent. Make sure discount amount not higher than 100. - if ($this->discount_type == 1 && $this->discount_amount > 100) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_DISCOUNT_PRODUCT_ERROR_DISCOUNT_PERCENTAGE')); - - return false; - } - - // Make sure start date always lower than end date. - if (!empty($this->start_date) && !empty($this->end_date) && $this->start_date > $this->end_date) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_DISCOUNT_PRODUCT_ERROR_START_DATE_SAME_HIGH_END_DATE')); - - return false; - } - - // Check shopper groups - if (empty($this->getOption('shopperGroups', array()))) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_DISCOUNT_PRODUCT_ERROR_MISSING_SHOPPER_GROUPS')); - - return false; - } - - return parent::doCheck(); - } - - /** - * Delete one or more registers - * - * @param mixed $pk Array of ids or ids comma separated - * - * @return boolean Deleted successfully? - */ - public function doDelete($pk = null) - { - $discountProductId = $this->discount_product_id; - - if (!parent::doDelete($pk)) - { - return false; - } - - $db = $this->getDbo(); - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_discount_product_shoppers')) - ->where($db->qn('discount_product_id') . ' = ' . $discountProductId); - - return $db->setQuery($query)->execute(); - } + /** + * @var integer + */ + public $discount_product_id; + /** + * @var integer + */ + public $amount = 0; + /** + * @var integer + */ + public $condition = 1; + /** + * @var float + */ + public $discount_amount = 0.0; + /** + * @var integer + */ + public $discount_type = 0; + /** + * @var integer + */ + public $start_date = 0; + /** + * @var integer + */ + public $end_date = 0; + /** + * @var integer + */ + public $published = 1; + /** + * @var string + */ + public $category_ids = ''; + /** + * The table name without the prefix. + * + * @var string + */ + protected $_tableName = 'redshop_discount_product'; + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'discount_product_id'; + + /** + * Delete one or more registers + * + * @param mixed $pk Array of ids or ids comma separated + * + * @return boolean Deleted successfully? + */ + public function doDelete($pk = null) + { + $discountProductId = $this->discount_product_id; + + if (!parent::doDelete($pk)) { + return false; + } + + $db = $this->getDbo(); + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_discount_product_shoppers')) + ->where($db->qn('discount_product_id') . ' = ' . $discountProductId); + + return $db->setQuery($query)->execute(); + } + + /** + * Do the database store. + * + * @param boolean $updateNulls True to update null values as well. + * + * @return boolean + */ + protected function doStore($updateNulls = false) + { + if (!parent::doStore($updateNulls)) { + return false; + } + + if ($this->getOption('inlineMode', false) === true) { + return true; + } + + return $this->updateShopperGroups(); + } + + /** + * Method for update shopper group xref. + * + * @return boolean + */ + protected function updateShopperGroups() + { + $db = $this->getDbo(); + + // Clear current reference products. + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_discount_product_shoppers')) + ->where($db->qn('discount_product_id') . ' = ' . $this->discount_product_id); + $db->setQuery($query)->execute(); + + $shopperGroupIds = $this->getOption('shopperGroups', null); + + if (empty($shopperGroupIds) || empty(array_filter($shopperGroupIds))) { + return true; + } + + $query->clear() + ->insert($db->qn('#__redshop_discount_product_shoppers')) + ->columns($db->qn(array('discount_product_id', 'shopper_group_id'))); + + foreach ($shopperGroupIds as $shopperGroupId) { + $query->values((int)$this->discount_product_id . ',' . (int)$shopperGroupId); + } + + return $db->setQuery($query)->execute(); + } + + /** + * Method to bind an associative array or object to the JTable instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param mixed $src An associative array or object to bind to the JTable instance. + * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + * + * @throws Exception + */ + protected function doBind(&$src, $ignore = array()) + { + if (isset($src['shopper_group']) && !empty($src['shopper_group'])) { + $shopperGroups = is_string($src['shopper_group']) ? explode( + ',', + $src['shopper_group'] + ) : $src['shopper_group']; + $this->setOption('shopperGroups', array_values(array_filter($shopperGroups))); + unset($src['shopper_group']); + } + + return parent::doBind($src, $ignore); + } + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + // Check amount + if ((float)$this->amount <= 0.0) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_DISCOUNT_PRODUCT_ERROR_AMOUNT_ZERO')); + + return false; + } + + // Check discount amount + if ((float)$this->discount_amount <= 0.0) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_DISCOUNT_PRODUCT_ERROR_DISCOUNT_AMOUNT_ZERO')); + + return false; + } + + // Check amount and discount amount + if (((float)$this->amount) < (float)$this->discount_amount) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_DISCOUNT_PRODUCT_ERROR_AMOUNT_HIGHT_DISCOUNT_AMOUNT')); + + return false; + } + + // If discount type is percent. Make sure discount amount not higher than 100. + if ($this->discount_type == 1 && $this->discount_amount > 100) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_DISCOUNT_PRODUCT_ERROR_DISCOUNT_PERCENTAGE')); + + return false; + } + + // Make sure start date always lower than end date. + if (!empty($this->start_date) && !empty($this->end_date) && $this->start_date > $this->end_date) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_DISCOUNT_PRODUCT_ERROR_START_DATE_SAME_HIGH_END_DATE')); + + return false; + } + + // Check shopper groups + if (empty($this->getOption('shopperGroups', array()))) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_DISCOUNT_PRODUCT_ERROR_MISSING_SHOPPER_GROUPS')); + + return false; + } + + return parent::doCheck(); + } } diff --git a/component/admin/tables/field.php b/component/admin/tables/field.php index f0d97e2eaaf..6a92e106adc 100755 --- a/component/admin/tables/field.php +++ b/component/admin/tables/field.php @@ -9,6 +9,7 @@ defined('_JEXEC') or die; JLoader::import('redshop.library'); + /** * Table Field * @@ -18,311 +19,274 @@ */ class RedshopTableField extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_fields'; - - /** - * @var integer - */ - public $id; - - /** - * @var string - */ - public $name; - - /** - * @var integer - */ - public $type; - - /** - * @var integer - */ - public $groupId; - - /** - * @var integer - */ - public $ordering; - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (empty($this->name)) - { - return false; - } - - if (empty($this->title)) - { - return false; - } - - if (!parent::doCheck()) - { - return false; - } - - $this->name = str_replace(" ", "_", $this->name); - - // Set 'rs' prefix to field name - list($prefix) = explode("_", $this->name); - - if ($prefix != 'rs') - { - $this->name = "rs_" . $this->name; - } - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('COUNT(*) AS cnt') - ->from($db->qn('#__redshop_fields')) - ->where($db->qn('name') . ' = ' . $db->quote($this->name)) - ->where($db->qn('id') . ' != ' . (int) $this->id); - - $db->setQuery($query); - $result = $db->loadResult(); - - if ((boolean) $result) - { - $this->setError(JText::_('COM_REDSHOP_FIELDS_ALLREADY_EXIST')); - - return false; - } - - if (!$this->id) - { - $query = $db->getQuery(true) - ->select('COUNT(*) + 1') - ->from($db->qn('#__redshop_fields')); - - $this->ordering = (int) $db->setQuery($query)->loadResult(); - } - - return true; - } - - /** - * Do the database store. - * - * @param boolean $updateNulls True to update null values as well. - * - * @return boolean - * @throws Exception - */ - protected function doStore($updateNulls = false) - { - if (!$this->groupId) - { - $this->groupId = null; - } - - if (!parent::doStore($updateNulls)) - { - return false; - } - - if ($this->type == 0 || $this->type == RedshopHelperExtrafields::TYPE_TEXT || $this->type == RedshopHelperExtrafields::TYPE_TEXT_AREA) - { - $id[] = (int) $this->id; - $this->deleteFieldValues($id, 'field_id'); - } - else - { - $this->saveFieldValues($this->id); - } - - return true; - } - - /** - * Delete one or more registers - * - * @param mixed $pk Array of ids or ids comma separated - * - * @return boolean Deleted successfully? - */ - protected function doDelete($pk = null) - { - $db = $this->getDbo(); - - if (!parent::doDelete($pk)) - { - return false; - } - - if (is_array($pk)) - { - $pk = implode(',', $pk); - } - - // Remove fields_data - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_fields_data')) - ->where($db->qn('fieldid') . ' IN (' . $pk . ')'); - - $db->setQuery($query); - - if (!$db->execute()) - { - $this->setError($db->getErrorMsg()); - } - - return true; - } - - /** - * Method to delete all values related to a field or array of fields - * - * @param array $ids An array of field ids. - * @param string $field The field column to check for deleting. - * - * @return boolean True if successful, false if an error occurs. - * - * @since 2.0.6 - */ - protected function deleteFieldValues($ids, $field) - { - $db = $this->getDbo(); - $ids = implode(',', $ids); - - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_fields_value')) - ->where($db->qn($field) . ' IN (' . $ids . ')'); - - if (!$db->setQuery($query)->execute()) - { - $this->setError($db->getErrorMsg()); - - return false; - } - - return true; - } - - /** - * Method to save all values related to a field - * - * @param int $id Id of field. - * - * @return boolean True if successful, false if an error occurs. - * @throws Exception - * - * @since 2.0.6 - */ - protected function saveFieldValues($id) - { - $db = JFactory::getDbo(); - $valueIds = array(); - $extraNames = array(); - $extraValues = array(); - - // Get input - $app = JFactory::getApplication(); - $post = $app->input->post; - $total = 0; - - if (is_array($post->get('value_id'))) - { - $extraValues = $post->getString('extra_value', ''); - $valueIds = $post->get('value_id', array(), 'array'); - - if ($this->type == RedshopHelperExtrafields::TYPE_IMAGE_SELECT || $this->type == RedshopHelperExtrafields::TYPE_IMAGE_WITH_LINK) - { - $extraNames = JFactory::getApplication()->input->files->get('extra_name_file', array(), 'array'); - $total = count((array)$extraNames); - } - else - { - $extraNames = $post->get('extra_name', '', 'raw'); - $total = count((array) $extraNames); - } - } - - // Do not reset values if we are ordering - $task = $app->input->get('task'); - - if ($task != 'fields.saveOrderAjax' && $task != 'saveOrderAjax') - { - $fieldDataIds = RedshopEntityField::getInstance($id)->getFieldValues(); - - if (count($fieldDataIds) > 0) - { - $fid = array(); - - foreach ($fieldDataIds as $fieldDataId) - { - $fid[] = $fieldDataId->value_id; - } - - $delFieldIds = array_diff($fid, $valueIds); - - if (count($delFieldIds) > 0) - { - $this->deleteFieldValues($delFieldIds, 'value_id'); - } - } - } - - for ($j = 0; $j < $total; $j++) - { - $filename = $extraNames[$j]; - - if ($this->type == RedshopHelperExtrafields::TYPE_IMAGE_SELECT || $this->type == RedshopHelperExtrafields::TYPE_IMAGE_WITH_LINK) - { - if ($extraValues[$j] != "" && $extraNames[$j]['name'] != "" && $extraNames[$j]['error'] == 0) - { - $filename = RedshopHelperMedia::cleanFileName($extraNames[$j]['name']); - - $source = $extraNames[$j]['tmp_name']; - $destination = REDSHOP_FRONT_IMAGES_RELPATH . 'extrafield/' . $filename; - - JFile::upload($source, $destination); - } - } - - if ($extraNames[$j]['error'] == 0 || !isset($extraNames[$j]['error'])) - { - if (empty($valueIds[$j])) - { - $obj = new stdClass; - $obj->field_id = (int)$id; - $obj->field_name = $filename; - $obj->field_value = $extraValues[$j]; - $db->insertObject('#__redshop_fields_value', $obj); - } - else - { - $obj = new stdClass; - $obj->value_id = $valueIds[$j]; - $obj->field_value = $extraValues[$j]; - $obj->field_name = $filename; - $db->updateObject('#__redshop_fields_value', $obj, array('value_id')); - } - } - else - { - $obj = new stdClass; - $obj->value_id = $valueIds[$j]; - $obj->field_value = $extraValues[$j]; - $obj->field_name = $filename; - $db->updateObject('#__redshop_fields_value', $obj,array('value_id')); - } - } - - return true; - } + /** + * @var integer + */ + public $id; + /** + * @var string + */ + public $name; + /** + * @var integer + */ + public $type; + /** + * @var integer + */ + public $groupId; + /** + * @var integer + */ + public $ordering; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_fields'; + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (empty($this->name)) { + return false; + } + + if (empty($this->title)) { + return false; + } + + if (!parent::doCheck()) { + return false; + } + + $this->name = str_replace(" ", "_", $this->name); + + // Set 'rs' prefix to field name + list($prefix) = explode("_", $this->name); + + if ($prefix != 'rs') { + $this->name = "rs_" . $this->name; + } + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('COUNT(*) AS cnt') + ->from($db->qn('#__redshop_fields')) + ->where($db->qn('name') . ' = ' . $db->quote($this->name)) + ->where($db->qn('id') . ' != ' . (int)$this->id); + + $db->setQuery($query); + $result = $db->loadResult(); + + if ((boolean)$result) { + $this->setError(JText::_('COM_REDSHOP_FIELDS_ALLREADY_EXIST')); + + return false; + } + + if (!$this->id) { + $query = $db->getQuery(true) + ->select('COUNT(*) + 1') + ->from($db->qn('#__redshop_fields')); + + $this->ordering = (int)$db->setQuery($query)->loadResult(); + } + + return true; + } + + /** + * Do the database store. + * + * @param boolean $updateNulls True to update null values as well. + * + * @return boolean + * @throws Exception + */ + protected function doStore($updateNulls = false) + { + if (!$this->groupId) { + $this->groupId = null; + } + + if (!parent::doStore($updateNulls)) { + return false; + } + + if ($this->type == 0 || $this->type == RedshopHelperExtrafields::TYPE_TEXT || $this->type == RedshopHelperExtrafields::TYPE_TEXT_AREA) { + $id[] = (int)$this->id; + $this->deleteFieldValues($id, 'field_id'); + } else { + $this->saveFieldValues($this->id); + } + + return true; + } + + /** + * Method to delete all values related to a field or array of fields + * + * @param array $ids An array of field ids. + * @param string $field The field column to check for deleting. + * + * @return boolean True if successful, false if an error occurs. + * + * @since 2.0.6 + */ + protected function deleteFieldValues($ids, $field) + { + $db = $this->getDbo(); + $ids = implode(',', $ids); + + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_fields_value')) + ->where($db->qn($field) . ' IN (' . $ids . ')'); + + if (!$db->setQuery($query)->execute()) { + $this->setError($db->getErrorMsg()); + + return false; + } + + return true; + } + + /** + * Method to save all values related to a field + * + * @param int $id Id of field. + * + * @return boolean True if successful, false if an error occurs. + * @throws Exception + * + * @since 2.0.6 + */ + protected function saveFieldValues($id) + { + $db = JFactory::getDbo(); + $valueIds = array(); + $extraNames = array(); + $extraValues = array(); + + // Get input + $app = JFactory::getApplication(); + $post = $app->input->post; + $total = 0; + + if (is_array($post->get('value_id'))) { + $extraValues = $post->getString('extra_value', ''); + $valueIds = $post->get('value_id', array(), 'array'); + + if ($this->type == RedshopHelperExtrafields::TYPE_IMAGE_SELECT || $this->type == RedshopHelperExtrafields::TYPE_IMAGE_WITH_LINK) { + $extraNames = JFactory::getApplication()->input->files->get('extra_name_file', array(), 'array'); + $total = count((array)$extraNames); + } else { + $extraNames = $post->get('extra_name', '', 'raw'); + $total = count((array)$extraNames); + } + } + + // Do not reset values if we are ordering + $task = $app->input->get('task'); + + if ($task != 'fields.saveOrderAjax' && $task != 'saveOrderAjax') { + $fieldDataIds = RedshopEntityField::getInstance($id)->getFieldValues(); + + if (count($fieldDataIds) > 0) { + $fid = array(); + + foreach ($fieldDataIds as $fieldDataId) { + $fid[] = $fieldDataId->value_id; + } + + $delFieldIds = array_diff($fid, $valueIds); + + if (count($delFieldIds) > 0) { + $this->deleteFieldValues($delFieldIds, 'value_id'); + } + } + } + + for ($j = 0; $j < $total; $j++) { + $filename = $extraNames[$j]; + + if ($this->type == RedshopHelperExtrafields::TYPE_IMAGE_SELECT || $this->type == RedshopHelperExtrafields::TYPE_IMAGE_WITH_LINK) { + if ($extraValues[$j] != "" && $extraNames[$j]['name'] != "" && $extraNames[$j]['error'] == 0) { + $filename = RedshopHelperMedia::cleanFileName($extraNames[$j]['name']); + + $source = $extraNames[$j]['tmp_name']; + $destination = REDSHOP_FRONT_IMAGES_RELPATH . 'extrafield/' . $filename; + + JFile::upload($source, $destination); + } + } + + if ($extraNames[$j]['error'] == 0 || !isset($extraNames[$j]['error'])) { + if (empty($valueIds[$j])) { + $obj = new stdClass; + $obj->field_id = (int)$id; + $obj->field_name = $filename; + $obj->field_value = $extraValues[$j]; + $db->insertObject('#__redshop_fields_value', $obj); + } else { + $obj = new stdClass; + $obj->value_id = $valueIds[$j]; + $obj->field_value = $extraValues[$j]; + $obj->field_name = $filename; + $db->updateObject('#__redshop_fields_value', $obj, array('value_id')); + } + } else { + $obj = new stdClass; + $obj->value_id = $valueIds[$j]; + $obj->field_value = $extraValues[$j]; + $obj->field_name = $filename; + $db->updateObject('#__redshop_fields_value', $obj, array('value_id')); + } + } + + return true; + } + + /** + * Delete one or more registers + * + * @param mixed $pk Array of ids or ids comma separated + * + * @return boolean Deleted successfully? + */ + protected function doDelete($pk = null) + { + $db = $this->getDbo(); + + if (!parent::doDelete($pk)) { + return false; + } + + if (is_array($pk)) { + $pk = implode(',', $pk); + } + + // Remove fields_data + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_fields_data')) + ->where($db->qn('fieldid') . ' IN (' . $pk . ')'); + + $db->setQuery($query); + + if (!$db->execute()) { + $this->setError($db->getErrorMsg()); + } + + return true; + } } diff --git a/component/admin/tables/field_data.php b/component/admin/tables/field_data.php index 668d3653b78..0061e3f433e 100644 --- a/component/admin/tables/field_data.php +++ b/component/admin/tables/field_data.php @@ -18,17 +18,17 @@ */ class RedshopTableField_Data extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_fields_data'; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_fields_data'; - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'data_id'; + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'data_id'; } diff --git a/component/admin/tables/field_group.php b/component/admin/tables/field_group.php index 863b06a5313..7f73b9ba24f 100644 --- a/component/admin/tables/field_group.php +++ b/component/admin/tables/field_group.php @@ -18,128 +18,115 @@ */ class RedshopTableField_Group extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - * - * @since 2.1.0 - */ - protected $_tableName = 'redshop_fields_group'; - - /** - * @var integer - * - * @since 2.1.0 - */ - public $id = null; - - /** - * @var string - * - * @since 2.1.0 - */ - public $name = null; - - /** - * @var string - * - * @since 2.1.0 - */ - public $description = null; - - /** - * @var string - * - * @since 2.1.0 - */ - public $section = null; - - /** - * @var integer - * - * @since 2.1.0 - */ - public $created_by = null; - - /** - * @var string - * - * @since 2.1.0 - */ - public $created_date = null; - - /** - * @var integer - * - * @since 2.1.0 - */ - public $checked_out = null; - - /** - * @var string - * - * @since 2.1.0 - */ - public $checked_out_time; - - /** - * @var string - * - * @since 2.1.0 - */ - public $modified_date = null; - - /** - * @var integer - * - * @since 2.1.0 - */ - public $modified_by = null; - - /** - * @var integer - * - * @since 2.1.0 - */ - public $ordering = null; - - /** - * @var integer - * - * @since 2.1.0 - */ - public $published = null; - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (!parent::doCheck()) - { - return false; - } - - if (empty($this->name)) - { - /** @scrutinizer ignore-deprecated */ $this->setError('COM_REDSHOP_FIELD_GROUP_ERROR_MISSING_NAME'); - - return false; - } - - if (empty($this->section)) - { - /** @scrutinizer ignore-deprecated */ $this->setError('COM_REDSHOP_FIELD_GROUP_ERROR_MISSING_SECTION'); - - return false; - } - - return true; - } + /** + * @var integer + * + * @since 2.1.0 + */ + public $id = null; + /** + * @var string + * + * @since 2.1.0 + */ + public $name = null; + /** + * @var string + * + * @since 2.1.0 + */ + public $description = null; + /** + * @var string + * + * @since 2.1.0 + */ + public $section = null; + /** + * @var integer + * + * @since 2.1.0 + */ + public $created_by = null; + /** + * @var string + * + * @since 2.1.0 + */ + public $created_date = null; + /** + * @var integer + * + * @since 2.1.0 + */ + public $checked_out = null; + /** + * @var string + * + * @since 2.1.0 + */ + public $checked_out_time; + /** + * @var string + * + * @since 2.1.0 + */ + public $modified_date = null; + /** + * @var integer + * + * @since 2.1.0 + */ + public $modified_by = null; + /** + * @var integer + * + * @since 2.1.0 + */ + public $ordering = null; + /** + * @var integer + * + * @since 2.1.0 + */ + public $published = null; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + * + * @since 2.1.0 + */ + protected $_tableName = 'redshop_fields_group'; + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (!parent::doCheck()) { + return false; + } + + if (empty($this->name)) { + /** @scrutinizer ignore-deprecated */ + $this->setError('COM_REDSHOP_FIELD_GROUP_ERROR_MISSING_NAME'); + + return false; + } + + if (empty($this->section)) { + /** @scrutinizer ignore-deprecated */ + $this->setError('COM_REDSHOP_FIELD_GROUP_ERROR_MISSING_SECTION'); + + return false; + } + + return true; + } } diff --git a/component/admin/tables/fields_value.php b/component/admin/tables/fields_value.php index ec4b7086202..5931c8d4dfb 100644 --- a/component/admin/tables/fields_value.php +++ b/component/admin/tables/fields_value.php @@ -11,30 +11,29 @@ class Tablefields_value extends JTable { - public $value_id = null; + public $value_id = null; - public $field_id = null; + public $field_id = null; - public $field_name = null; + public $field_name = null; - public $field_value = null; + public $field_value = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'fields_value', 'value_id', $db); - } + parent::__construct($this->_table_prefix . 'fields_value', 'value_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/giftcard.php b/component/admin/tables/giftcard.php index 22f0d1875d6..6011e2abfee 100644 --- a/component/admin/tables/giftcard.php +++ b/component/admin/tables/giftcard.php @@ -20,142 +20,131 @@ */ class RedshopTableGiftcard extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_giftcard'; - - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'giftcard_id'; - - /** - * Delete one or more registers - * - * @param string/array $pk Array of ids or ids comma separated - * - * @return boolean Deleted successfuly? - */ - protected function doDelete($pk = null) - { - if ($this->giftcard_image != '' && file(REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $this->giftcard_image)) - { - JFile::delete(REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $this->giftcard_image); - } - - if ($this->giftcard_bgimage != '' && file(REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $this->giftcard_bgimage)) - { - JFile::delete(REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $this->giftcard_bgimage); - } - - return parent::doDelete($pk); - } - - /** - * Do the database store. - * - * @param boolean $updateNulls True to update null values as well. - * - * @return boolean - */ - protected function doStore($updateNulls = false) - { - - // Get input - $app = JFactory::getApplication(); - $input = $app->input; - - $giftCardFile = $input->files->get('jform'); - $image = $giftCardFile['giftcard_image_file']; - - if ($image['name'] != '' && $this->giftcard_image != '') - { - JFile::delete(REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $this->giftcard_image); - $this->giftcard_image = ''; - } - - if ($image['name'] != '') - { - $image['name'] = RedshopHelperMedia::cleanFileName($image['name']); - $this->giftcard_image = $image['name']; - JFile::upload($image['tmp_name'], REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $image['name']); - } - - // Get background image file - $bgImage = $giftCardFile['giftcard_bgimage_file']; - - if (($bgImage['name'] != '' && $this->giftcard_bgimage != '')) - { - JFile::delete(REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $this->giftcard_bgimage); - $this->giftcard_bgimage = ''; - } - - if ($bgImage['name'] != '') - { - $bgImage['name'] = RedshopHelperMedia::cleanFileName($bgImage['name']); - $this->giftcard_bgimage = $bgImage['name']; - JFile::upload($bgImage['tmp_name'], REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $bgImage['name']); - } - - $this->giftcard_price = RedshopHelperProduct::redpriceDecimal($this->giftcard_price); - $this->giftcard_value = RedshopHelperProduct::redpriceDecimal($this->giftcard_value); - - if (!parent::doStore($updateNulls)) - { - return false; - } - - if (Redshop::getConfig()->get('ECONOMIC_INTEGRATION') == 1) - { - $giftData = new stdClass; - $giftData->product_id = $this->giftcard_id; - $giftData->product_number = "gift_" . $this->giftcard_id . "_" . $this->giftcard_name; - $giftData->product_name = $this->giftcard_name; - $giftData->product_price = $this->giftcard_price; - $giftData->accountgroup_id = $this->accountgroup_id; - $giftData->product_volume = 0; - - RedshopEconomic::createProductInEconomic($giftData); - } - - return true; - } - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (empty($this->giftcard_name)) - { - return false; - } - - if (empty($this->giftcard_price)) - { - return false; - } - - if (empty($this->giftcard_value)) - { - return false; - } - - if (empty($this->giftcard_validity)) - { - return false; - } - - return parent::doCheck(); - } + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_giftcard'; + + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'giftcard_id'; + + /** + * Delete one or more registers + * + * @param string/array $pk Array of ids or ids comma separated + * + * @return boolean Deleted successfuly? + */ + protected function doDelete($pk = null) + { + if ($this->giftcard_image != '' && file(REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $this->giftcard_image)) { + JFile::delete(REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $this->giftcard_image); + } + + if ($this->giftcard_bgimage != '' && file( + REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $this->giftcard_bgimage + )) { + JFile::delete(REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $this->giftcard_bgimage); + } + + return parent::doDelete($pk); + } + + /** + * Do the database store. + * + * @param boolean $updateNulls True to update null values as well. + * + * @return boolean + */ + protected function doStore($updateNulls = false) + { + // Get input + $app = JFactory::getApplication(); + $input = $app->input; + + $giftCardFile = $input->files->get('jform'); + $image = $giftCardFile['giftcard_image_file']; + + if ($image['name'] != '' && $this->giftcard_image != '') { + JFile::delete(REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $this->giftcard_image); + $this->giftcard_image = ''; + } + + if ($image['name'] != '') { + $image['name'] = RedshopHelperMedia::cleanFileName($image['name']); + $this->giftcard_image = $image['name']; + JFile::upload($image['tmp_name'], REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $image['name']); + } + + // Get background image file + $bgImage = $giftCardFile['giftcard_bgimage_file']; + + if (($bgImage['name'] != '' && $this->giftcard_bgimage != '')) { + JFile::delete(REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $this->giftcard_bgimage); + $this->giftcard_bgimage = ''; + } + + if ($bgImage['name'] != '') { + $bgImage['name'] = RedshopHelperMedia::cleanFileName($bgImage['name']); + $this->giftcard_bgimage = $bgImage['name']; + JFile::upload($bgImage['tmp_name'], REDSHOP_FRONT_IMAGES_RELPATH . 'giftcard/' . $bgImage['name']); + } + + $this->giftcard_price = RedshopHelperProduct::redpriceDecimal($this->giftcard_price); + $this->giftcard_value = RedshopHelperProduct::redpriceDecimal($this->giftcard_value); + + if (!parent::doStore($updateNulls)) { + return false; + } + + if (Redshop::getConfig()->get('ECONOMIC_INTEGRATION') == 1) { + $giftData = new stdClass; + $giftData->product_id = $this->giftcard_id; + $giftData->product_number = "gift_" . $this->giftcard_id . "_" . $this->giftcard_name; + $giftData->product_name = $this->giftcard_name; + $giftData->product_price = $this->giftcard_price; + $giftData->accountgroup_id = $this->accountgroup_id; + $giftData->product_volume = 0; + + RedshopEconomic::createProductInEconomic($giftData); + } + + return true; + } + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (empty($this->giftcard_name)) { + return false; + } + + if (empty($this->giftcard_price)) { + return false; + } + + if (empty($this->giftcard_value)) { + return false; + } + + if (empty($this->giftcard_validity)) { + return false; + } + + return parent::doCheck(); + } } diff --git a/component/admin/tables/index.html b/component/admin/tables/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/tables/index.html +++ b/component/admin/tables/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/tables/mail.php b/component/admin/tables/mail.php index b22564a9c88..15fd645419e 100644 --- a/component/admin/tables/mail.php +++ b/component/admin/tables/mail.php @@ -18,45 +18,42 @@ */ class RedshopTableMail extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_mail'; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_mail'; - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'mail_id'; + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'mail_id'; - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (empty($this->mail_name)) - { - return false; - } + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (empty($this->mail_name)) { + return false; + } - if (empty($this->mail_section)) - { - return false; - } + if (empty($this->mail_section)) { + return false; + } - if (empty($this->mail_subject)) - { - return false; - } + if (empty($this->mail_subject)) { + return false; + } - return parent::doCheck(); - } + return parent::doCheck(); + } } diff --git a/component/admin/tables/manufacturer.php b/component/admin/tables/manufacturer.php index 8f95bb02c95..bb90080912a 100644 --- a/component/admin/tables/manufacturer.php +++ b/component/admin/tables/manufacturer.php @@ -18,237 +18,223 @@ */ class RedshopTableManufacturer extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_manufacturer'; - - /** - * @var integer - */ - public $id; - - /** - * @var string - */ - public $name; - - /** - * @var integer - */ - public $published = 1; - - /** - * @var integer - */ - public $product_per_page; - - /** - * Delete one or more registers - * - * @param string/array $pk Array of ids or ids comma separated - * - * @return boolean Deleted successfully? - */ - protected function doDelete($pk = null) - { - $manufacturerId = $this->id; - $media = RedshopEntityManufacturer::getInstance($manufacturerId)->getMedia(); - - if (!parent::doDelete($pk)) - { - return false; - } - - // B/C for old plugin - JPluginHelper::importPlugin('redshop_product'); - RedshopHelperUtility::getDispatcher()->trigger('onAfterManufacturerDelete', array($manufacturerId)); - - // Delete associated media - if ($media->isValid()) - { - /** @var RedshopTableMedia $mediaTable */ - $mediaTable = RedshopTable::getInstance('Media', 'RedshopTable'); - - if ($mediaTable->load($media->get('media_id'))) - { - $mediaTable->delete(); - } - } - - // Delete media folder - JFolder::delete(REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer/' . $manufacturerId); - - return true; - } - - /** - * Do the database store. - * - * @param boolean $updateNulls True to update null values as well. - * - * @return boolean - * @throws Exception - * @since 2.1.0 - */ - protected function doStore($updateNulls = false) - { - JPluginHelper::importPlugin('redshop_product'); - - // B/C for old plugin - $isNew = $this->id > 0 ? false : true; - RedshopHelperUtility::getDispatcher()->trigger('onBeforeManufacturerSave', array(&$this, $isNew)); - - if (!parent::doStore($updateNulls)) - { - return false; - } - - // Store fields data. - $this->storeFields(); - - // Store media - $this->storeMedia(); - - // B/C for old plugin - RedshopHelperUtility::getDispatcher()->trigger('onAfterManufacturerSave', array(&$this, $isNew)); - - return true; - } - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (!parent::doCheck()) - { - return false; - } - - // Check product per page - if (!$this->product_per_page) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_MANUFACTURER_ERROR_PRODUCT_PER_PAGE')); - - return false; - } - - return true; - } - - /** - * Method for store fields data. - * - * @return void - * @throws Exception - * - * @since 2.1.0 - */ - protected function storeFields() - { - RedshopHelperExtrafields::extraFieldSave( - JFactory::getApplication()->input->post->getArray(), RedshopHelperExtrafields::SECTION_MANUFACTURER, $this->id - ); - } - - /** - * Method for store fields data. - * - * @return void - * @throws Exception - * - * @since 2.1.0 - */ - protected function storeMedia() - { - $mediaField = 'manufacturer_image'; - - // Prepare target folder. - \Redshop\Helper\Media::createFolder(REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer/' . $this->id); - - // Prepare target folder. - \Redshop\Helper\Media::createFolder(REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer/' . $this->id . '/thumb'); - - $input = JFactory::getApplication()->input; - - $dropzone = $input->post->get('dropzone', array(), ''); - $dropzone = isset($dropzone[$mediaField]) ? $dropzone[$mediaField] : null; - - $dropzoneAlternateText = $input->post->get('dropzone_alternate_text', array(), ''); - $dropzoneAlternateText = isset($dropzoneAlternateText[$mediaField]) ? $dropzoneAlternateText[$mediaField] : null; - - if (null === $dropzone) - { - return; - } - - foreach ($dropzone as $key => $value) - { - /** @var RedshopTableMedia $mediaTable */ - $mediaTable = JTable::getInstance('Media', 'RedshopTable'); - - if (strpos($key, 'media-') !== false) - { - $mediaTable->load(str_replace('media-', '', $key)); - - // Delete old image. - $oldMediaFile = JPath::clean(REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer/' - . $this->id . '/' . $mediaTable->media_name - ); - - if (JFile::exists($oldMediaFile)) - { - JFile::delete($oldMediaFile); - } - - if (empty($value)) - { - $mediaTable->delete(); - - continue; - } - } - else - { - $mediaTable->set('section_id', $this->id); - $mediaTable->set('media_section', 'manufacturer'); - } - - if (!JFile::exists(JPATH_ROOT . '/' . $value)) - { - continue; - } - - $alternateText = isset($dropzoneAlternateText[$key]) ? $dropzoneAlternateText[$key] : $this->name; - - $mediaTable->set('media_alternate_text', $alternateText); - $mediaTable->set('media_type', 'images'); - $mediaTable->set('published', 1); - - // Copy new image for this media - $fileName = md5($this->name) . '.' . JFile::getExt($value); - $file = REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer/' . $this->id . '/' . $fileName; - - JFile::move(JPATH_ROOT . '/' . $value, $file); - - $mediaTable->set('media_name', $fileName); - $mediaTable->store(); - - // Optimize image - $factory = new \ImageOptimizer\OptimizerFactory; - $optimizer = $factory->get(); - $optimizer->optimize($file); - } - - // Clear thumbnail folder - \Redshop\Helper\Media::createFolder(REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer/' . $this->id . '/thumb', true); - } + /** + * @var integer + */ + public $id; + /** + * @var string + */ + public $name; + /** + * @var integer + */ + public $published = 1; + /** + * @var integer + */ + public $product_per_page; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_manufacturer'; + + /** + * Delete one or more registers + * + * @param string/array $pk Array of ids or ids comma separated + * + * @return boolean Deleted successfully? + */ + protected function doDelete($pk = null) + { + $manufacturerId = $this->id; + $media = RedshopEntityManufacturer::getInstance($manufacturerId)->getMedia(); + + if (!parent::doDelete($pk)) { + return false; + } + + // B/C for old plugin + JPluginHelper::importPlugin('redshop_product'); + RedshopHelperUtility::getDispatcher()->trigger('onAfterManufacturerDelete', array($manufacturerId)); + + // Delete associated media + if ($media->isValid()) { + /** @var RedshopTableMedia $mediaTable */ + $mediaTable = RedshopTable::getInstance('Media', 'RedshopTable'); + + if ($mediaTable->load($media->get('media_id'))) { + $mediaTable->delete(); + } + } + + // Delete media folder + JFolder::delete(REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer/' . $manufacturerId); + + return true; + } + + /** + * Do the database store. + * + * @param boolean $updateNulls True to update null values as well. + * + * @return boolean + * @throws Exception + * @since 2.1.0 + */ + protected function doStore($updateNulls = false) + { + JPluginHelper::importPlugin('redshop_product'); + + // B/C for old plugin + $isNew = $this->id > 0 ? false : true; + RedshopHelperUtility::getDispatcher()->trigger('onBeforeManufacturerSave', array(&$this, $isNew)); + + if (!parent::doStore($updateNulls)) { + return false; + } + + // Store fields data. + $this->storeFields(); + + // Store media + $this->storeMedia(); + + // B/C for old plugin + RedshopHelperUtility::getDispatcher()->trigger('onAfterManufacturerSave', array(&$this, $isNew)); + + return true; + } + + /** + * Method for store fields data. + * + * @return void + * @throws Exception + * + * @since 2.1.0 + */ + protected function storeFields() + { + RedshopHelperExtrafields::extraFieldSave( + JFactory::getApplication()->input->post->getArray(), + RedshopHelperExtrafields::SECTION_MANUFACTURER, + $this->id + ); + } + + /** + * Method for store fields data. + * + * @return void + * @throws Exception + * + * @since 2.1.0 + */ + protected function storeMedia() + { + $mediaField = 'manufacturer_image'; + + // Prepare target folder. + \Redshop\Helper\Media::createFolder(REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer/' . $this->id); + + // Prepare target folder. + \Redshop\Helper\Media::createFolder(REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer/' . $this->id . '/thumb'); + + $input = JFactory::getApplication()->input; + + $dropzone = $input->post->get('dropzone', array(), ''); + $dropzone = isset($dropzone[$mediaField]) ? $dropzone[$mediaField] : null; + + $dropzoneAlternateText = $input->post->get('dropzone_alternate_text', array(), ''); + $dropzoneAlternateText = isset($dropzoneAlternateText[$mediaField]) ? $dropzoneAlternateText[$mediaField] : null; + + if (null === $dropzone) { + return; + } + + foreach ($dropzone as $key => $value) { + /** @var RedshopTableMedia $mediaTable */ + $mediaTable = JTable::getInstance('Media', 'RedshopTable'); + + if (strpos($key, 'media-') !== false) { + $mediaTable->load(str_replace('media-', '', $key)); + + // Delete old image. + $oldMediaFile = JPath::clean( + REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer/' + . $this->id . '/' . $mediaTable->media_name + ); + + if (JFile::exists($oldMediaFile)) { + JFile::delete($oldMediaFile); + } + + if (empty($value)) { + $mediaTable->delete(); + + continue; + } + } else { + $mediaTable->set('section_id', $this->id); + $mediaTable->set('media_section', 'manufacturer'); + } + + if (!JFile::exists(JPATH_ROOT . '/' . $value)) { + continue; + } + + $alternateText = isset($dropzoneAlternateText[$key]) ? $dropzoneAlternateText[$key] : $this->name; + + $mediaTable->set('media_alternate_text', $alternateText); + $mediaTable->set('media_type', 'images'); + $mediaTable->set('published', 1); + + // Copy new image for this media + $fileName = md5($this->name) . '.' . JFile::getExt($value); + $file = REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer/' . $this->id . '/' . $fileName; + + JFile::move(JPATH_ROOT . '/' . $value, $file); + + $mediaTable->set('media_name', $fileName); + $mediaTable->store(); + + // Optimize image + $factory = new \ImageOptimizer\OptimizerFactory; + $optimizer = $factory->get(); + $optimizer->optimize($file); + } + + // Clear thumbnail folder + \Redshop\Helper\Media::createFolder(REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer/' . $this->id . '/thumb', true); + } + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (!parent::doCheck()) { + return false; + } + + // Check product per page + if (!$this->product_per_page) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_MANUFACTURER_ERROR_PRODUCT_PER_PAGE')); + + return false; + } + + return true; + } } diff --git a/component/admin/tables/mass_discount.php b/component/admin/tables/mass_discount.php index ce86b382ff5..9c069c76a86 100644 --- a/component/admin/tables/mass_discount.php +++ b/component/admin/tables/mass_discount.php @@ -20,636 +20,575 @@ */ class RedshopTableMass_Discount extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_mass_discount'; - - /** - * @var string - */ - public $end_date; - - /** - * @var integer - */ - public $amount; - - /** - * @var integer - */ - public $type; - - /** - * Called before bind(). - * - * Method to bind an associative array or object to the JTable instance.This - * method only binds properties that are publicly accessible and optionally - * takes an array of properties to ignore when binding. - * - * @param mixed $src An associative array or object to bind to the JTable instance. - * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. - * - * @return boolean True on success. - */ - public function beforeBind(&$src, $ignore = array()) - { - // Bind: Start Date unix - if (isset($src['start_date']) && !empty($src['start_date']) && !is_numeric($src['start_date'])) - { - $date = JFactory::getDate($src['start_date']); - $src['start_date'] = $date->toUnix(); - } - - // Bind: End Date unix - if (isset($src['end_date']) && !empty($src['end_date']) && !is_numeric($src['end_date'])) - { - $date = JFactory::getDate($src['end_date']); - $src['end_date'] = $date->toUnix(); - } - - // Bind: Discount products - if (isset($src['discount_product']) && !empty($src['discount_product']) && is_array($src['discount_product'])) - { - $src['discount_product'] = ArrayHelper::toInteger($src['discount_product']); - $src['discount_product'] = array_unique(array_filter($src['discount_product'])); - $src['discount_product'] = implode(',', $src['discount_product']); - } - - // Bind: Categories - if (isset($src['category_id']) && !empty($src['category_id']) && is_array($src['category_id'])) - { - $src['category_id'] = ArrayHelper::toInteger($src['category_id']); - $src['category_id'] = array_unique(array_filter($src['category_id'])); - $src['category_id'] = implode(',', $src['category_id']); - } - - // Bind: Manufacturers - if (isset($src['manufacturer_id']) && !empty($src['manufacturer_id']) && is_array($src['manufacturer_id'])) - { - $src['manufacturer_id'] = ArrayHelper::toInteger($src['manufacturer_id']); - $src['manufacturer_id'] = array_unique(array_filter($src['manufacturer_id'])); - $src['manufacturer_id'] = implode(',', $src['manufacturer_id']); - } - - return parent::beforeBind($src, $ignore); - } - - /** - * Method to bind an associative array or object to the JTable instance.This - * method only binds properties that are publicly accessible and optionally - * takes an array of properties to ignore when binding. - * - * @param mixed $src An associative array or object to bind to the JTable instance. - * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. - * - * @return boolean True on success. - * - * @throws \InvalidArgumentException - */ - protected function doBind(&$src, $ignore = array()) - { - if (empty($src['discount_product']) && empty($this->discount_product)) - { - $this->discount_product = null; - unset($src['discount_product']); - } - - if (empty($src['category_id']) && empty($this->category_id)) - { - $this->category_id = null; - unset($src['category_id']); - } - - return parent::doBind($src, $ignore); - } - - /** - * Delete one or more registers - * - * @param string|array $pk Array of ids or ids comma separated - * - * @return boolean Deleted successfuly? - */ - protected function doDelete($pk = null) - { - $massDiscountIds = $pk; - - if (!is_array($massDiscountIds)) - { - $massDiscountIds = array($massDiscountIds); - } - - $massDiscountIds = ArrayHelper::toInteger($massDiscountIds); - $productIds = array(); - - $table = clone $this; - - foreach ($massDiscountIds as $massDiscountId) - { - if (!$table->load($massDiscountId)) - { - continue; - } - - if (!empty($table->get('discount_product'))) - { - $this->updateProduct($table->get('discount_product')); - } - - $categories = explode(',', $table->category_id); - $categories = array_filter(ArrayHelper::toInteger($categories)); - - foreach ($categories as $category) - { - $products = RedshopHelperProduct::getProductCategory($category); - - if (empty($products)) - { - continue; - } - - foreach ($products as $product) - { - $productIds[] = $product->product_id; - } - } - - $manufacturers = explode(',', $table->manufacturer_id); - $manufacturers = array_filter(ArrayHelper::toInteger($manufacturers)); - - foreach ($manufacturers as $manufacturer) - { - $products = $this->getProductsFromManufacturer($manufacturer); - - if (empty($products)) - { - continue; - } - - foreach ($products as $product) - { - $productIds[] = $product->product_id; - } - } - } - - if (!empty($productIds)) - { - $this->updateProduct($productIds); - } - - return parent::doDelete($pk); - } - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass - * @throws Exception - */ - protected function doCheck() - { - if (!parent::doCheck()) - { - return false; - } - - if (empty($this->name)) - { - /** @scrutinizer ignore-deprecated */ $this->/** @scrutinizer ignore-call */ - setError(JText::_('COM_REDSHOP_MASS_DISCOUNT_MISSING_DISCOUNT_NAME'), 'error'); - - return false; - } - - if (empty($this->amount)) - { - /** @scrutinizer ignore-deprecated */ $this->/** @scrutinizer ignore-call */ setError(JText::_('COM_REDSHOP_MASS_DISCOUNT_DISCOUNT_AMOUNT_MUST_BE_LARGER_THAN_ZERO'), 'error'); - - return false; - } - - if (empty($this->discount_product) && empty($this->category_id) && empty($this->manufacturer_id)) - { - /** @scrutinizer ignore-deprecated */ $this->/** @scrutinizer ignore-call */ setError(JText::_('COM_REDSHOP_MASS_DISCOUNT_DETAIL_NO_PRODUCTS_SELECTED'), 'error'); - - return false; - } - - if ($this->start_date > $this->end_date) - { - /** @scrutinizer ignore-deprecated */ $this->/** @scrutinizer ignore-call */ setError(JText::_('COM_REDSHOP_MASS_DISCOUNT_ENDDATE_LOWER_STARTDATE'), 'error'); - - return false; - } - - return true; - } - - /** - * Called before store(). Overriden to send isNew to plugins. - * - * @param boolean $updateNulls True to update null values as well. - * @param boolean $isNew True if we are adding a new item. - * @param mixed $oldItem null for new items | JTable otherwise - * - * @return boolean True on success. - * @throws Exception - */ - protected function beforeStore($updateNulls = false, $isNew = false, $oldItem = null) - { - if (!parent::beforeStore($updateNulls, $isNew, $oldItem)) - { - return false; - } - - $db = $this->_db; - $query = $db->getQuery(true); - - $this->updateProductsBaseDiscountProduct($this, $isNew, $oldItem); - - /* - * Update products for "category_id" - */ - $categories = $isNew ? array() : explode(',', $oldItem->category_id); - $newCategories = explode(',', $this->category_id); - $isChangeCategory = false; - $isNewChangeCategory = false; - - $diffCategories = array_diff($categories, $newCategories); - - if (count($diffCategories)) - { - sort($diffCategories); - } - else - { - $isChangeCategory = true; - } - - $diffCategories = array_filter(array_values($diffCategories)); - - foreach ($diffCategories as $diffCategory) - { - $products = RedshopHelperProduct::getProductCategory($diffCategory); - $productIds = array(); - - foreach ($products as $product) - { - $productIds[] = $product->product_id; - } - - if (empty($productIds)) - { - continue; - } - - $query->clear() - ->update($db->qn('#__redshop_product')) - ->set($db->qn('product_on_sale') . ' = 0') - ->where($db->qn('product_id') . ' IN (' . implode(',', $productIds) . ')'); - - if (!$db->setQuery($query)->execute()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); - - return false; - } - } - - $newDiffCategories = array_diff($newCategories, $categories); - - if (count($newDiffCategories)) - { - sort($newDiffCategories); - } - else - { - $isNewChangeCategory = true; - } - - if ($isChangeCategory && $isNewChangeCategory) - { - $newDiffCategories = $categories; - } - - foreach ($newDiffCategories as $newDiffCategory) - { - $products = RedshopHelperProduct::getProductCategory($newDiffCategory); - - foreach ($products as $product) - { - $productData = Redshop::product((int) $product->product_id); - - if ($this->type == 1) - { - $price = $productData->product_price - ($productData->product_price * $this->amount / 100); - } - else - { - $price = $productData->product_price - $this->amount; - } - - $price = RedshopHelperProductPrice::priceRound($price); - - $query->clear() - ->update($db->qn('#__redshop_product')) - ->set($db->qn('product_on_sale') . ' = 1') - ->set($db->qn('discount_price') . ' = ' . $price) - ->set($db->qn('discount_stratdate') . ' = ' . $this->start_date) - ->set($db->qn('discount_enddate') . ' = ' . $this->end_date) - ->where($db->qn('product_id') . ' = ' . $product->product_id); - - if (!$db->setQuery($query)->execute()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); - - return false; - } - } - } - - /* - * Update products for "manufacturer_id" - */ - $isChangeManufacturer = false; - $isNewChangeManufacturer = false; - $manufacturers = $isNew ? array() : explode(',', $oldItem->manufacturer_id); - $newManufacturers = explode(',', $this->manufacturer_id); - - $diffManufacturers = array_diff($manufacturers, $newManufacturers); - - if (count($diffManufacturers)) - { - sort($diffManufacturers); - } - else - { - $isChangeManufacturer = true; - } - - $diffManufacturers = array_filter(array_values($diffManufacturers)); - - if (!empty($diffManufacturers)) - { - $query->clear() - ->update($db->qn('#__redshop_product')) - ->set($db->qn('product_on_sale') . ' = 0') - ->where($db->qn('manufacturer_id') . ' IN (' . implode(',', $diffManufacturers) . ')'); - - if (!$db->setQuery($query)->execute()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); - - return false; - } - } - - $newDiffManufacturers = array_diff($newManufacturers, $manufacturers); - - if (count($newDiffManufacturers)) - { - sort($newDiffManufacturers); - } - else - { - $isNewChangeManufacturer = true; - } - - if ($isNewChangeManufacturer && $isChangeManufacturer) - { - $newDiffManufacturers = $manufacturers; - } - - $newDiffManufacturers = array_filter(array_values($newDiffManufacturers)); - - if (!empty($newDiffManufacturers)) - { - $query->clear() - ->select($db->qn('product_id')) - ->from($db->qn('#__redshop_product')) - ->where($db->qn('manufacturer_id') . ' IN (' . implode(',', $newDiffManufacturers) . ')'); - $productIds = $db->setQuery($query)->loadColumn(); - - foreach ($productIds as $productId) - { - $productData = Redshop::product((int) $productId); - - if ($this->type == 1) - { - $price = $productData->product_price - ($productData->product_price * $this->amount / 100); - } - else - { - $price = $productData->product_price - $this->amount; - } - - $price = RedshopHelperProductPrice::priceRound($price); - - $query->clear() - ->update($db->qn('#__redshop_product')) - ->set($db->qn('product_on_sale') . ' = 1') - ->set($db->qn('discount_price') . ' = ' . $price) - ->set($db->qn('discount_stratdate') . ' = ' . $this->start_date) - ->set($db->qn('discount_enddate') . ' = ' . $this->end_date) - ->where($db->qn('product_id') . ' = ' . $productData->product_id); - - if (!$db->setQuery($query)->execute()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); - - return false; - } - } - } - - return true; - } - - /** - * Update Product On Sale status - * - * @param array|string $productIds List of products. - * - * @return boolean - */ - public function updateProduct($productIds) - { - if (empty($productIds)) - { - return true; - } - - if (is_string($productIds)) - { - $productIds = explode(',', $productIds); - } - - $productIds = ArrayHelper::toInteger($productIds); - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_product')) - ->set($db->qn('product_on_sale') . ' = 0') - ->set($db->qn('discount_stratdate') . ' = 0') - ->set($db->qn('discount_enddate') . ' = 0') - ->set($db->qn('discount_price') . ' = 0') - ->where($db->qn('product_id') . ' IN (' . implode(',', $productIds) . ')'); - - return $db->setQuery($query)->execute(); - } - - /** - * Method for get product of manufacturer. - * - * @param int $id ID of manufacturer - * - * @return mixed - * - * @since 2.0.3 - */ - public function getProductsFromManufacturer($id) - { - if (!$id) - { - return array(); - } - - $db = $this->_db; - - $query = $db->getQuery(true) - ->select($db->qn('product_id')) - ->from($db->qn('#__redshop_product')) - ->where($db->qn('manufacturer_id') . ' = ' . (int) $id); - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * Method for update product base on "discount_product" - * - * @param self $data New data - * @param boolean $isNew Is new or not. - * @param mixed $oldItem Old data - * - * @return boolean - * @throws Exception - * - * @since 2.0.3 - */ - protected function updateProductsBaseDiscountProduct($data, $isNew = false, $oldItem = null) - { - $db = $this->_db; - $query = $db->getQuery(true); - $isChangeProduct = false; - $isNewChangeProduct = false; - - $discountProducts = $isNew ? array() : explode(',', $oldItem->discount_product); - $newDiscountProducts = explode(',', $this->discount_product); - - $diffProducts = array_filter(array_diff($discountProducts, $newDiscountProducts)); - - if (count($diffProducts)) - { - sort($diffProducts); - } - else - { - $isChangeProduct = true; - } - - if (!empty($diffProducts)) - { - $query->clear() - ->update($db->qn('#__redshop_product')) - ->set($db->qn('product_on_sale') . ' = 0') - ->where($db->qn('product_id') . ' IN (' . implode(',', $diffProducts) . ')'); - - if (!$db->setQuery($query)->execute()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); - - return false; - } - } - - $newDiffProducts = array_diff($newDiscountProducts, $discountProducts); - - if (count($newDiffProducts)) - { - sort($newDiffProducts); - } - else - { - $isNewChangeProduct = true; - } - - if ($isChangeProduct && $isNewChangeProduct) - { - $newDiffProducts = $discountProducts; - } - - $newDiffProducts = array_filter(array_values($newDiffProducts)); - - if (empty($newDiffProducts)) - { - return true; - } - - foreach ($newDiffProducts as $newDiffProduct) - { - try - { - $productData = Redshop::product($newDiffProduct); - - // Ticket ONKELP-161: Temporary comment these code to by pass product_on_sale check before apply another mass discount - if ($this->type == 1) - { - $price = $productData->product_price - ($productData->product_price * $this->amount / 100); - } - else - { - $price = $productData->product_price - $this->amount; - } - - $price = RedshopHelperProductPrice::priceRound($price); - $query->clear(); - - // Update fields - $update = array( - $db->qn('product_on_sale') . ' = 1', - $db->qn('discount_price') . ' = ' . (float) $price, - $db->qn('discount_stratdate') . ' = ' . (int) $this->start_date, - $db->qn('discount_enddate') . ' = ' . (int) $this->end_date - ); - - // By condition - $conditions = array ( - $db->qn('product_id') . ' = ' . (int) $newDiffProduct - ); - $query->update($db->qn('#__redshop_product'))->set($update)->where($conditions); - $db->setQuery($query); - - if (!$db->execute()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - } - catch (Exception $e) - { - /** @scrutinizer ignore-deprecated */ - $this->/** @scrutinizer ignore-call */ setError($e->getMessage(), 'error'); - } - } - - return true; - } + /** + * @var string + */ + public $end_date; + /** + * @var integer + */ + public $amount; + /** + * @var integer + */ + public $type; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_mass_discount'; + + /** + * Called before bind(). + * + * Method to bind an associative array or object to the JTable instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param mixed $src An associative array or object to bind to the JTable instance. + * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + */ + public function beforeBind(&$src, $ignore = array()) + { + // Bind: Start Date unix + if (isset($src['start_date']) && !empty($src['start_date']) && !is_numeric($src['start_date'])) { + $date = JFactory::getDate($src['start_date']); + $src['start_date'] = $date->toUnix(); + } + + // Bind: End Date unix + if (isset($src['end_date']) && !empty($src['end_date']) && !is_numeric($src['end_date'])) { + $date = JFactory::getDate($src['end_date']); + $src['end_date'] = $date->toUnix(); + } + + // Bind: Discount products + if (isset($src['discount_product']) && !empty($src['discount_product']) && is_array($src['discount_product'])) { + $src['discount_product'] = ArrayHelper::toInteger($src['discount_product']); + $src['discount_product'] = array_unique(array_filter($src['discount_product'])); + $src['discount_product'] = implode(',', $src['discount_product']); + } + + // Bind: Categories + if (isset($src['category_id']) && !empty($src['category_id']) && is_array($src['category_id'])) { + $src['category_id'] = ArrayHelper::toInteger($src['category_id']); + $src['category_id'] = array_unique(array_filter($src['category_id'])); + $src['category_id'] = implode(',', $src['category_id']); + } + + // Bind: Manufacturers + if (isset($src['manufacturer_id']) && !empty($src['manufacturer_id']) && is_array($src['manufacturer_id'])) { + $src['manufacturer_id'] = ArrayHelper::toInteger($src['manufacturer_id']); + $src['manufacturer_id'] = array_unique(array_filter($src['manufacturer_id'])); + $src['manufacturer_id'] = implode(',', $src['manufacturer_id']); + } + + return parent::beforeBind($src, $ignore); + } + + /** + * Method to bind an associative array or object to the JTable instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param mixed $src An associative array or object to bind to the JTable instance. + * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + * + * @throws \InvalidArgumentException + */ + protected function doBind(&$src, $ignore = array()) + { + if (empty($src['discount_product']) && empty($this->discount_product)) { + $this->discount_product = null; + unset($src['discount_product']); + } + + if (empty($src['category_id']) && empty($this->category_id)) { + $this->category_id = null; + unset($src['category_id']); + } + + return parent::doBind($src, $ignore); + } + + /** + * Delete one or more registers + * + * @param string|array $pk Array of ids or ids comma separated + * + * @return boolean Deleted successfuly? + */ + protected function doDelete($pk = null) + { + $massDiscountIds = $pk; + + if (!is_array($massDiscountIds)) { + $massDiscountIds = array($massDiscountIds); + } + + $massDiscountIds = ArrayHelper::toInteger($massDiscountIds); + $productIds = array(); + + $table = clone $this; + + foreach ($massDiscountIds as $massDiscountId) { + if (!$table->load($massDiscountId)) { + continue; + } + + if (!empty($table->get('discount_product'))) { + $this->updateProduct($table->get('discount_product')); + } + + $categories = explode(',', $table->category_id); + $categories = array_filter(ArrayHelper::toInteger($categories)); + + foreach ($categories as $category) { + $products = RedshopHelperProduct::getProductCategory($category); + + if (empty($products)) { + continue; + } + + foreach ($products as $product) { + $productIds[] = $product->product_id; + } + } + + $manufacturers = explode(',', $table->manufacturer_id); + $manufacturers = array_filter(ArrayHelper::toInteger($manufacturers)); + + foreach ($manufacturers as $manufacturer) { + $products = $this->getProductsFromManufacturer($manufacturer); + + if (empty($products)) { + continue; + } + + foreach ($products as $product) { + $productIds[] = $product->product_id; + } + } + } + + if (!empty($productIds)) { + $this->updateProduct($productIds); + } + + return parent::doDelete($pk); + } + + /** + * Update Product On Sale status + * + * @param array|string $productIds List of products. + * + * @return boolean + */ + public function updateProduct($productIds) + { + if (empty($productIds)) { + return true; + } + + if (is_string($productIds)) { + $productIds = explode(',', $productIds); + } + + $productIds = ArrayHelper::toInteger($productIds); + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_product')) + ->set($db->qn('product_on_sale') . ' = 0') + ->set($db->qn('discount_stratdate') . ' = 0') + ->set($db->qn('discount_enddate') . ' = 0') + ->set($db->qn('discount_price') . ' = 0') + ->where($db->qn('product_id') . ' IN (' . implode(',', $productIds) . ')'); + + return $db->setQuery($query)->execute(); + } + + /** + * Method for get product of manufacturer. + * + * @param int $id ID of manufacturer + * + * @return mixed + * + * @since 2.0.3 + */ + public function getProductsFromManufacturer($id) + { + if (!$id) { + return array(); + } + + $db = $this->_db; + + $query = $db->getQuery(true) + ->select($db->qn('product_id')) + ->from($db->qn('#__redshop_product')) + ->where($db->qn('manufacturer_id') . ' = ' . (int)$id); + + return $db->setQuery($query)->loadObjectList(); + } + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass + * @throws Exception + */ + protected function doCheck() + { + if (!parent::doCheck()) { + return false; + } + + if (empty($this->name)) { + /** @scrutinizer ignore-deprecated */ + $this->/** @scrutinizer ignore-call */ + setError(JText::_('COM_REDSHOP_MASS_DISCOUNT_MISSING_DISCOUNT_NAME'), 'error'); + + return false; + } + + if (empty($this->amount)) { + /** @scrutinizer ignore-deprecated */ + $this->/** @scrutinizer ignore-call */ setError( + JText::_('COM_REDSHOP_MASS_DISCOUNT_DISCOUNT_AMOUNT_MUST_BE_LARGER_THAN_ZERO'), + 'error' + ); + + return false; + } + + if (empty($this->discount_product) && empty($this->category_id) && empty($this->manufacturer_id)) { + /** @scrutinizer ignore-deprecated */ + $this->/** @scrutinizer ignore-call */ setError( + JText::_('COM_REDSHOP_MASS_DISCOUNT_DETAIL_NO_PRODUCTS_SELECTED'), + 'error' + ); + + return false; + } + + if ($this->start_date > $this->end_date) { + /** @scrutinizer ignore-deprecated */ + $this->/** @scrutinizer ignore-call */ setError( + JText::_('COM_REDSHOP_MASS_DISCOUNT_ENDDATE_LOWER_STARTDATE'), + 'error' + ); + + return false; + } + + return true; + } + + /** + * Called before store(). Overriden to send isNew to plugins. + * + * @param boolean $updateNulls True to update null values as well. + * @param boolean $isNew True if we are adding a new item. + * @param mixed $oldItem null for new items | JTable otherwise + * + * @return boolean True on success. + * @throws Exception + */ + protected function beforeStore($updateNulls = false, $isNew = false, $oldItem = null) + { + if (!parent::beforeStore($updateNulls, $isNew, $oldItem)) { + return false; + } + + $db = $this->_db; + $query = $db->getQuery(true); + + $this->updateProductsBaseDiscountProduct($this, $isNew, $oldItem); + + /* + * Update products for "category_id" + */ + $categories = $isNew ? array() : explode(',', $oldItem->category_id); + $newCategories = explode(',', $this->category_id); + $isChangeCategory = false; + $isNewChangeCategory = false; + + $diffCategories = array_diff($categories, $newCategories); + + if (count($diffCategories)) { + sort($diffCategories); + } else { + $isChangeCategory = true; + } + + $diffCategories = array_filter(array_values($diffCategories)); + + foreach ($diffCategories as $diffCategory) { + $products = RedshopHelperProduct::getProductCategory($diffCategory); + $productIds = array(); + + foreach ($products as $product) { + $productIds[] = $product->product_id; + } + + if (empty($productIds)) { + continue; + } + + $query->clear() + ->update($db->qn('#__redshop_product')) + ->set($db->qn('product_on_sale') . ' = 0') + ->where($db->qn('product_id') . ' IN (' . implode(',', $productIds) . ')'); + + if (!$db->setQuery($query)->execute()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); + + return false; + } + } + + $newDiffCategories = array_diff($newCategories, $categories); + + if (count($newDiffCategories)) { + sort($newDiffCategories); + } else { + $isNewChangeCategory = true; + } + + if ($isChangeCategory && $isNewChangeCategory) { + $newDiffCategories = $categories; + } + + foreach ($newDiffCategories as $newDiffCategory) { + $products = RedshopHelperProduct::getProductCategory($newDiffCategory); + + foreach ($products as $product) { + $productData = Redshop::product((int)$product->product_id); + + if ($this->type == 1) { + $price = $productData->product_price - ($productData->product_price * $this->amount / 100); + } else { + $price = $productData->product_price - $this->amount; + } + + $price = RedshopHelperProductPrice::priceRound($price); + + $query->clear() + ->update($db->qn('#__redshop_product')) + ->set($db->qn('product_on_sale') . ' = 1') + ->set($db->qn('discount_price') . ' = ' . $price) + ->set($db->qn('discount_stratdate') . ' = ' . $this->start_date) + ->set($db->qn('discount_enddate') . ' = ' . $this->end_date) + ->where($db->qn('product_id') . ' = ' . $product->product_id); + + if (!$db->setQuery($query)->execute()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); + + return false; + } + } + } + + /* + * Update products for "manufacturer_id" + */ + $isChangeManufacturer = false; + $isNewChangeManufacturer = false; + $manufacturers = $isNew ? array() : explode(',', $oldItem->manufacturer_id); + $newManufacturers = explode(',', $this->manufacturer_id); + + $diffManufacturers = array_diff($manufacturers, $newManufacturers); + + if (count($diffManufacturers)) { + sort($diffManufacturers); + } else { + $isChangeManufacturer = true; + } + + $diffManufacturers = array_filter(array_values($diffManufacturers)); + + if (!empty($diffManufacturers)) { + $query->clear() + ->update($db->qn('#__redshop_product')) + ->set($db->qn('product_on_sale') . ' = 0') + ->where($db->qn('manufacturer_id') . ' IN (' . implode(',', $diffManufacturers) . ')'); + + if (!$db->setQuery($query)->execute()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); + + return false; + } + } + + $newDiffManufacturers = array_diff($newManufacturers, $manufacturers); + + if (count($newDiffManufacturers)) { + sort($newDiffManufacturers); + } else { + $isNewChangeManufacturer = true; + } + + if ($isNewChangeManufacturer && $isChangeManufacturer) { + $newDiffManufacturers = $manufacturers; + } + + $newDiffManufacturers = array_filter(array_values($newDiffManufacturers)); + + if (!empty($newDiffManufacturers)) { + $query->clear() + ->select($db->qn('product_id')) + ->from($db->qn('#__redshop_product')) + ->where($db->qn('manufacturer_id') . ' IN (' . implode(',', $newDiffManufacturers) . ')'); + $productIds = $db->setQuery($query)->loadColumn(); + + foreach ($productIds as $productId) { + $productData = Redshop::product((int)$productId); + + if ($this->type == 1) { + $price = $productData->product_price - ($productData->product_price * $this->amount / 100); + } else { + $price = $productData->product_price - $this->amount; + } + + $price = RedshopHelperProductPrice::priceRound($price); + + $query->clear() + ->update($db->qn('#__redshop_product')) + ->set($db->qn('product_on_sale') . ' = 1') + ->set($db->qn('discount_price') . ' = ' . $price) + ->set($db->qn('discount_stratdate') . ' = ' . $this->start_date) + ->set($db->qn('discount_enddate') . ' = ' . $this->end_date) + ->where($db->qn('product_id') . ' = ' . $productData->product_id); + + if (!$db->setQuery($query)->execute()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); + + return false; + } + } + } + + return true; + } + + /** + * Method for update product base on "discount_product" + * + * @param self $data New data + * @param boolean $isNew Is new or not. + * @param mixed $oldItem Old data + * + * @return boolean + * @throws Exception + * + * @since 2.0.3 + */ + protected function updateProductsBaseDiscountProduct($data, $isNew = false, $oldItem = null) + { + $db = $this->_db; + $query = $db->getQuery(true); + $isChangeProduct = false; + $isNewChangeProduct = false; + + $discountProducts = $isNew ? array() : explode(',', $oldItem->discount_product); + $newDiscountProducts = explode(',', $this->discount_product); + + $diffProducts = array_filter(array_diff($discountProducts, $newDiscountProducts)); + + if (count($diffProducts)) { + sort($diffProducts); + } else { + $isChangeProduct = true; + } + + if (!empty($diffProducts)) { + $query->clear() + ->update($db->qn('#__redshop_product')) + ->set($db->qn('product_on_sale') . ' = 0') + ->where($db->qn('product_id') . ' IN (' . implode(',', $diffProducts) . ')'); + + if (!$db->setQuery($query)->execute()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); + + return false; + } + } + + $newDiffProducts = array_diff($newDiscountProducts, $discountProducts); + + if (count($newDiffProducts)) { + sort($newDiffProducts); + } else { + $isNewChangeProduct = true; + } + + if ($isChangeProduct && $isNewChangeProduct) { + $newDiffProducts = $discountProducts; + } + + $newDiffProducts = array_filter(array_values($newDiffProducts)); + + if (empty($newDiffProducts)) { + return true; + } + + foreach ($newDiffProducts as $newDiffProduct) { + try { + $productData = Redshop::product($newDiffProduct); + + // Ticket ONKELP-161: Temporary comment these code to by pass product_on_sale check before apply another mass discount + if ($this->type == 1) { + $price = $productData->product_price - ($productData->product_price * $this->amount / 100); + } else { + $price = $productData->product_price - $this->amount; + } + + $price = RedshopHelperProductPrice::priceRound($price); + $query->clear(); + + // Update fields + $update = array( + $db->qn('product_on_sale') . ' = 1', + $db->qn('discount_price') . ' = ' . (float)$price, + $db->qn('discount_stratdate') . ' = ' . (int)$this->start_date, + $db->qn('discount_enddate') . ' = ' . (int)$this->end_date + ); + + // By condition + $conditions = array( + $db->qn('product_id') . ' = ' . (int)$newDiffProduct + ); + $query->update($db->qn('#__redshop_product'))->set($update)->where($conditions); + $db->setQuery($query); + + if (!$db->execute()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + } catch (Exception $e) { + /** @scrutinizer ignore-deprecated */ + $this->/** @scrutinizer ignore-call */ setError($e->getMessage(), 'error'); + } + } + + return true; + } } diff --git a/component/admin/tables/media.php b/component/admin/tables/media.php index 89664bcd89b..00de20f0e14 100644 --- a/component/admin/tables/media.php +++ b/component/admin/tables/media.php @@ -18,98 +18,88 @@ */ class RedshopTableMedia extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_media'; - - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'media_id'; - - /** - * @var integer - */ - public $media_id; - - /** - * @var string - */ - public $media_name = ''; - - /** - * @var string - */ - public $media_alternate_text = ''; - - /** - * @var string - */ - public $media_section = ''; - - /** - * @var integer - */ - public $section_id = ''; - - /** - * @var string - */ - public $media_type = ''; - - /** - * @var string - */ - public $media_mimetype = ''; - - /** - * @var integer - */ - public $published = ''; - - /** - * @var integer - */ - public $ordering = ''; - - /** - * @var string - */ - public $scope = ''; - - /** - * Delete one or more registers - * - * @param string/array $pk Array of ids or ids comma separated - * - * @return boolean Deleted successfuly? - */ - protected function doDelete($pk = null) - { - if ($this->media_section == 'images' - && ($this->media_section == 'manufacturer' || $this->media_section == 'category')) - { - // New folder structure - $folder = JPath::clean(REDSHOP_MEDIA_IMAGE_RELPATH . $this->media_section . '/' . $this->section_id . '/thumb'); - - if (JFolder::exists($folder)) - { - JFolder::delete($folder); - } - - $file = JPath::clean(REDSHOP_MEDIA_IMAGE_RELPATH . $this->media_section . '/' . $this->section_id . '/' . $this->media_name); - - if (JFile::exists($file)) - { - JFile::delete($file); - } - } - - return parent::doDelete($pk); - } + /** + * @var integer + */ + public $media_id; + /** + * @var string + */ + public $media_name = ''; + /** + * @var string + */ + public $media_alternate_text = ''; + /** + * @var string + */ + public $media_section = ''; + /** + * @var integer + */ + public $section_id = ''; + /** + * @var string + */ + public $media_type = ''; + /** + * @var string + */ + public $media_mimetype = ''; + /** + * @var integer + */ + public $published = ''; + /** + * @var integer + */ + public $ordering = ''; + /** + * @var string + */ + public $scope = ''; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_media'; + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'media_id'; + + /** + * Delete one or more registers + * + * @param string/array $pk Array of ids or ids comma separated + * + * @return boolean Deleted successfuly? + */ + protected function doDelete($pk = null) + { + if ($this->media_section == 'images' + && ($this->media_section == 'manufacturer' || $this->media_section == 'category')) { + // New folder structure + $folder = JPath::clean( + REDSHOP_MEDIA_IMAGE_RELPATH . $this->media_section . '/' . $this->section_id . '/thumb' + ); + + if (JFolder::exists($folder)) { + JFolder::delete($folder); + } + + $file = JPath::clean( + REDSHOP_MEDIA_IMAGE_RELPATH . $this->media_section . '/' . $this->section_id . '/' . $this->media_name + ); + + if (JFile::exists($file)) { + JFile::delete($file); + } + } + + return parent::doDelete($pk); + } } diff --git a/component/admin/tables/media_detail.php b/component/admin/tables/media_detail.php index 138d771b3a1..7bf2f0c29d9 100644 --- a/component/admin/tables/media_detail.php +++ b/component/admin/tables/media_detail.php @@ -11,40 +11,39 @@ class Tablemedia_detail extends JTable { - public $media_id = null; + public $media_id = null; - public $media_name = null; + public $media_name = null; - public $media_alternate_text = null; + public $media_alternate_text = null; - public $media_section = null; + public $media_section = null; - public $section_id = null; + public $section_id = null; - public $media_type = null; + public $media_type = null; - public $media_mimetype = null; + public $media_mimetype = null; - public $published = null; + public $published = null; - public $ordering = null; + public $ordering = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'media', 'media_id', $db); - } + parent::__construct($this->_table_prefix . 'media', 'media_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/media_download.php b/component/admin/tables/media_download.php index 7ecc5317b0e..cb1decb522f 100644 --- a/component/admin/tables/media_download.php +++ b/component/admin/tables/media_download.php @@ -11,28 +11,27 @@ class Tablemedia_download extends JTable { - public $id = null; + public $id = null; - public $name = null; + public $name = null; - public $media_id = null; + public $media_id = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'media_download', 'id', $db); - } + parent::__construct($this->_table_prefix . 'media_download', 'id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/newsletter_detail.php b/component/admin/tables/newsletter_detail.php index 40bda0ea9b1..9298267863e 100644 --- a/component/admin/tables/newsletter_detail.php +++ b/component/admin/tables/newsletter_detail.php @@ -11,34 +11,33 @@ class Tablenewsletter_detail extends JTable { - public $newsletter_id = null; + public $newsletter_id = null; - public $name = null; + public $name = null; - public $body = null; + public $body = null; - public $subject = null; + public $subject = null; - public $template_id = null; + public $template_id = null; - public $published = null; + public $published = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'newsletter', 'newsletter_id', $db); - } + parent::__construct($this->_table_prefix . 'newsletter', 'newsletter_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/newslettersubscr_detail.php b/component/admin/tables/newslettersubscr_detail.php index ef52776a7ae..c45a185e998 100644 --- a/component/admin/tables/newslettersubscr_detail.php +++ b/component/admin/tables/newslettersubscr_detail.php @@ -11,88 +11,88 @@ class Tablenewslettersubscr_detail extends JTable { - public $subscription_id = null; - - public $user_id = null; - - public $date = null; - - public $newsletter_id = null; - - public $name = null; - - public $email = null; - - public $published = null; - - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; - - parent::__construct($this->_table_prefix . 'newsletter_subscription', 'subscription_id', $db); - } - - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } - - return parent::bind($array, $ignore); - } - - /** - * Method to store a row in the database from the JTable instance properties. - * - * If a primary key value is set the row with that primary key value will be updated with the instance property values. - * If no primary key value is set a new row will be inserted into the database with the properties from the JTable instance. - * - * @param boolean $updateNulls True to update fields even if they are null. - * - * @return boolean True on success. - * - * @since 11.1 - */ - public function store($updateNulls = false) - { - $isNew = empty($this->subscription_id) ? true : false; - - if (!parent::store($updateNulls)) - { - return false; - } - - JPluginHelper::importPlugin('redshop_user'); - RedshopHelperUtility::getDispatcher()->trigger('addNewsLetterSubscription', array($isNew, $this->getProperties())); - - return true; - } - - /** - * Method to delete a row from the database table by primary key value. - * - * @param mixed $pk An optional primary key value to delete. If not set the instance property value is used. - * - * @return boolean True on success. - * - * @since 11.1 - * @throws UnexpectedValueException - */ - public function delete($pk = null) - { - $data = $this->getProperties(); - - if (!parent::delete($pk)) - { - return false; - } - - JPluginHelper::importPlugin('redshop_user'); - RedshopHelperUtility::getDispatcher()->trigger('removeNewsLetterSubscription', array($data)); - - return true; - } + public $subscription_id = null; + + public $user_id = null; + + public $date = null; + + public $newsletter_id = null; + + public $name = null; + + public $email = null; + + public $published = null; + + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; + + parent::__construct($this->_table_prefix . 'newsletter_subscription', 'subscription_id', $db); + } + + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } + + return parent::bind($array, $ignore); + } + + /** + * Method to store a row in the database from the JTable instance properties. + * + * If a primary key value is set the row with that primary key value will be updated with the instance property values. + * If no primary key value is set a new row will be inserted into the database with the properties from the JTable instance. + * + * @param boolean $updateNulls True to update fields even if they are null. + * + * @return boolean True on success. + * + * @since 11.1 + */ + public function store($updateNulls = false) + { + $isNew = empty($this->subscription_id) ? true : false; + + if (!parent::store($updateNulls)) { + return false; + } + + JPluginHelper::importPlugin('redshop_user'); + RedshopHelperUtility::getDispatcher()->trigger( + 'addNewsLetterSubscription', + array($isNew, $this->getProperties()) + ); + + return true; + } + + /** + * Method to delete a row from the database table by primary key value. + * + * @param mixed $pk An optional primary key value to delete. If not set the instance property value is used. + * + * @return boolean True on success. + * + * @throws UnexpectedValueException + * @since 11.1 + */ + public function delete($pk = null) + { + $data = $this->getProperties(); + + if (!parent::delete($pk)) { + return false; + } + + JPluginHelper::importPlugin('redshop_user'); + RedshopHelperUtility::getDispatcher()->trigger('removeNewsLetterSubscription', array($data)); + + return true; + } } diff --git a/component/admin/tables/notifystock_user.php b/component/admin/tables/notifystock_user.php index 74c36729102..6cb72141699 100644 --- a/component/admin/tables/notifystock_user.php +++ b/component/admin/tables/notifystock_user.php @@ -11,33 +11,32 @@ class Tablenotifystock_user extends JTable { - public $id = null; + public $id = null; - public $product_id = null; + public $product_id = null; - public $propertyId = null; + public $propertyId = null; - public $subPropertyId = null; + public $subPropertyId = null; - public $user_id = null; + public $user_id = null; - public $notification_status = null; + public $notification_status = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'notifystock_users', 'id', $db); - } + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; + parent::__construct($this->_table_prefix . 'notifystock_users', 'id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/order_acc_item.php b/component/admin/tables/order_acc_item.php index 56a790b75ae..3f0e060819e 100644 --- a/component/admin/tables/order_acc_item.php +++ b/component/admin/tables/order_acc_item.php @@ -11,44 +11,43 @@ class Tableorder_acc_item extends JTable { - public $order_item_acc_id = null; + public $order_item_acc_id = null; - public $order_item_id = null; + public $order_item_id = null; - public $product_id = null; + public $product_id = null; - public $order_acc_item_sku = null; + public $order_acc_item_sku = null; - public $order_acc_item_name = null; + public $order_acc_item_name = null; - public $order_acc_price = null; + public $order_acc_price = null; - public $order_acc_vat = null; + public $order_acc_vat = null; - public $product_quantity = null; + public $product_quantity = null; - public $product_acc_item_price = null; + public $product_acc_item_price = null; - public $product_acc_final_price = null; + public $product_acc_final_price = null; - public $product_attribute = null; + public $product_attribute = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'order_acc_item', 'order_item_acc_id', $db); - } + parent::__construct($this->_table_prefix . 'order_acc_item', 'order_item_acc_id', $db); + } - function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/order_attribute_item.php b/component/admin/tables/order_attribute_item.php index 2a621c152b2..b93460815ea 100644 --- a/component/admin/tables/order_attribute_item.php +++ b/component/admin/tables/order_attribute_item.php @@ -11,46 +11,45 @@ class Tableorder_attribute_item extends JTable { - public $order_att_item_id = null; + public $order_att_item_id = null; - public $order_item_id = null; + public $order_item_id = null; - public $section_id = null; + public $section_id = null; - public $section = null; + public $section = null; - public $parent_section_id = null; + public $parent_section_id = null; - public $section_name = null; + public $section_name = null; - public $section_vat = null; + public $section_vat = null; - public $section_price = null; + public $section_price = null; - public $section_oprand = null; + public $section_oprand = null; - public $is_accessory_att = null; + public $is_accessory_att = null; - public $stockroom_id = null; + public $stockroom_id = null; - public $stockroom_quantity = null; + public $stockroom_quantity = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'order_attribute_item', 'order_att_item_id', $db); - } + parent::__construct($this->_table_prefix . 'order_attribute_item', 'order_att_item_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/order_detail.php b/component/admin/tables/order_detail.php index 5850e52b50b..2f1fa705757 100644 --- a/component/admin/tables/order_detail.php +++ b/component/admin/tables/order_detail.php @@ -11,119 +11,120 @@ class Tableorder_detail extends JTable { - public $order_id = null; + public $order_id = null; - public $user_id = null; + public $user_id = null; - public $order_number = null; + public $order_number = null; - public $barcode = null; + public $barcode = null; - public $is_booked = 0; + public $is_booked = 0; - public $user_info_id = null; + public $user_info_id = null; - public $order_total = null; + public $order_total = null; - public $order_subtotal = null; + public $order_subtotal = null; - public $order_tax = null; + public $order_tax = null; - public $order_tax_details = null; + public $order_tax_details = null; - public $order_shipping = null; + public $order_shipping = null; - public $order_shipping_tax = null; + public $order_shipping_tax = null; - public $coupon_discount = null; + public $coupon_discount = null; - public $order_discount = null; + public $order_discount = null; - public $order_discount_vat = null; + public $order_discount_vat = null; - public $payment_discount = null; + public $payment_discount = null; - public $special_discount = null; + public $special_discount = null; - public $special_discount_amount = null; + public $special_discount_amount = null; - public $order_status = null; + public $order_status = null; - public $order_payment_status = null; + public $order_payment_status = null; - public $cdate = null; + public $cdate = null; - public $mdate = null; + public $mdate = null; - public $ship_method_id = null; + public $ship_method_id = null; - public $customer_note = null; + public $customer_note = null; - public $ip_address = null; + public $ip_address = null; - public $encr_key = null; + public $encr_key = null; - public $invoice_no = null; + public $invoice_no = null; - public $discount_type = null; + public $discount_type = null; - public $payment_oprand = null; + public $payment_oprand = null; - public $order_label_create = 0; + public $order_label_create = 0; - public $analytics_status = 0; + public $analytics_status = 0; - public $requisition_number = null; + public $requisition_number = null; - public $bookinvoice_number = 0; + public $bookinvoice_number = 0; - public $bookinvoice_date = 0; + public $bookinvoice_date = 0; - public $track_no = null; + public $track_no = null; - public $shop_id = null; + public $shop_id = null; - public $customer_message = null; + public $customer_message = null; - public $referral_code = null; + public $referral_code = null; - public $tax_after_discount; + public $tax_after_discount; - public function __construct(& $db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'orders', 'order_id', $db); - } + parent::__construct($this->_table_prefix . 'orders', 'order_id', $db); + } - /** - * Validate all table fields before saving - * - * @return boolean - * - * @since 2.0.0.4 - */ - public function check() - { - if (empty($this->order_status) || $this->order_status === 0) - { - JFactory::getApplication()->enqueueMessage(JText::_('COM_REDSHOP_TABLE_ORDER_REDSHOP_INVALID_ORDER_STATUS'), 'warning'); + /** + * Validate all table fields before saving + * + * @return boolean + * + * @since 2.0.0.4 + */ + public function check() + { + if (empty($this->order_status) || $this->order_status === 0) { + JFactory::getApplication()->enqueueMessage( + JText::_('COM_REDSHOP_TABLE_ORDER_REDSHOP_INVALID_ORDER_STATUS'), + 'warning' + ); - return false; - } + return false; + } - return parent::check(); - } + return parent::check(); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/order_item_detail.php b/component/admin/tables/order_item_detail.php index 2ebf60a74cf..359dbb2157f 100644 --- a/component/admin/tables/order_item_detail.php +++ b/component/admin/tables/order_item_detail.php @@ -11,82 +11,81 @@ class Tableorder_item_detail extends JTable { - public $order_item_id = null; + public $order_item_id = null; - public $order_id = null; + public $order_id = null; - public $user_info_id = null; + public $user_info_id = null; - public $supplier_id = null; + public $supplier_id = null; - public $product_id = null; + public $product_id = null; - public $order_item_sku = null; + public $order_item_sku = null; - public $order_item_name = null; + public $order_item_name = null; - public $product_quantity = null; + public $product_quantity = null; - public $product_item_price = null; + public $product_item_price = null; - public $product_item_old_price = null; + public $product_item_old_price = null; - public $product_item_price_excl_vat = null; + public $product_item_price_excl_vat = null; - public $product_final_price = null; + public $product_final_price = null; - public $order_item_currency = null; + public $order_item_currency = null; - public $order_status = null; + public $order_status = null; - public $customer_note = null; + public $customer_note = null; - public $cdate = null; + public $cdate = null; - public $mdate = null; + public $mdate = null; - public $product_attribute = null; + public $product_attribute = null; - public $discount_calc_data = null; + public $discount_calc_data = null; - public $product_accessory = null; + public $product_accessory = null; - public $delivery_time = null; + public $delivery_time = null; - public $stockroom_id = null; + public $stockroom_id = null; - public $stockroom_quantity = null; + public $stockroom_quantity = null; - public $wrapper_id = null; + public $wrapper_id = null; - public $wrapper_price = null; + public $wrapper_price = null; - public $is_giftcard = 0; + public $is_giftcard = 0; - public $product_purchase_price = 0; + public $product_purchase_price = 0; - public $attribute_image = null; + public $attribute_image = null; - public $giftcard_user_email; + public $giftcard_user_email; - public $giftcard_user_name; + public $giftcard_user_name; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'order_item', 'order_item_id', $db); - } + parent::__construct($this->_table_prefix . 'order_item', 'order_item_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/order_payment.php b/component/admin/tables/order_payment.php index 3671a8180a8..cc06e234738 100644 --- a/component/admin/tables/order_payment.php +++ b/component/admin/tables/order_payment.php @@ -11,48 +11,47 @@ class Tableorder_payment extends JTable { - public $payment_order_id = null; + public $payment_order_id = null; - public $order_id = null; + public $order_id = null; - public $payment_method_id = null; + public $payment_method_id = null; - public $order_payment_code = null; + public $order_payment_code = null; - public $order_payment_cardname = null; + public $order_payment_cardname = null; - public $order_payment_number = null; + public $order_payment_number = null; - public $order_payment_ccv = null; + public $order_payment_ccv = null; - public $order_payment_expire = null; + public $order_payment_expire = null; - public $order_payment_name = null; + public $order_payment_name = null; - public $order_payment_trans_id = null; + public $order_payment_trans_id = null; - public $order_payment_amount = null; + public $order_payment_amount = null; - public $authorize_status = null; + public $authorize_status = null; - public $payment_method_class; + public $payment_method_class; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'order_payment', 'payment_order_id', $db); - } + parent::__construct($this->_table_prefix . 'order_payment', 'payment_order_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/order_status.php b/component/admin/tables/order_status.php index 73f6342a20c..6f59fe4a1c8 100644 --- a/component/admin/tables/order_status.php +++ b/component/admin/tables/order_status.php @@ -16,117 +16,109 @@ * @subpackage Table * @since 2.0.3 */ - class RedshopTableOrder_Status extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_order_status'; - - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'order_status_id'; - - /** - * @var integer - */ - public $order_status_id; - - /** - * @var string - */ - public $order_status_name; - - /** - * @var string - */ - public $order_status_code; - - /** - * @var integer - */ - public $published; - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (empty($this->order_status_name)) - { - return false; - } - - if (empty($this->order_status_code)) - { - return false; - } - - if (!parent::doCheck()) - { - return false; - } - - // Check status code. - $db = $this->getDbo(); - $query = $db->getQuery(true) - ->select('COUNT(' . $db->qn('order_status_code') . ') AS ' . $db->qn('count')) - ->from($db->qn('#__' . $this->_tableName)) - ->where($db->qn('order_status_code') . ' = ' . $db->quote($this->order_status_code)); - - if ($this->order_status_id) - { - $query->where($db->qn('order_status_id') . ' != ' . $this->order_status_id); - } - - if ($db->setQuery($query)->loadResult()) - { - $this->setError(JText::_('COM_REDSHOP_ORDER_STATUS_ERROR_STATUS_EXIST')); - - return false; - } - - return true; - } - - /** - * Delete one or more registers - * - * @param string/array $pk Array of ids or ids comma separated - * - * @return boolean Deleted successfuly? - */ - protected function doDelete($pk = null) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select($db->qn(['s.order_status_id', 's.order_status_code'])) - ->from($db->qn('#__redshop_order_status', 's')) - ->innerJoin($db->qn('#__redshop_orders', 'o') . ' ON ' . $db->qn('s.order_status_code') . ' = ' . $db->qn('o.order_status')) - ->where($db->qn('order_status_id') . ' = ' . $db->q($pk)); - $db->setQuery($query); - - $check = $db->loadObjectList(); - - if (count($check) > 0) - { - JFactory::getApplication()->enqueueMessage(JText::_('COM_REDSHOP_ORDER_STAUS_FAIL_DELETE'), 'error'); - - return false; - } - - return parent::doDelete($pk); - } + /** + * @var integer + */ + public $order_status_id; + /** + * @var string + */ + public $order_status_name; + /** + * @var string + */ + public $order_status_code; + /** + * @var integer + */ + public $published; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_order_status'; + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'order_status_id'; + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (empty($this->order_status_name)) { + return false; + } + + if (empty($this->order_status_code)) { + return false; + } + + if (!parent::doCheck()) { + return false; + } + + // Check status code. + $db = $this->getDbo(); + $query = $db->getQuery(true) + ->select('COUNT(' . $db->qn('order_status_code') . ') AS ' . $db->qn('count')) + ->from($db->qn('#__' . $this->_tableName)) + ->where($db->qn('order_status_code') . ' = ' . $db->quote($this->order_status_code)); + + if ($this->order_status_id) { + $query->where($db->qn('order_status_id') . ' != ' . $this->order_status_id); + } + + if ($db->setQuery($query)->loadResult()) { + $this->setError(JText::_('COM_REDSHOP_ORDER_STATUS_ERROR_STATUS_EXIST')); + + return false; + } + + return true; + } + + /** + * Delete one or more registers + * + * @param string/array $pk Array of ids or ids comma separated + * + * @return boolean Deleted successfuly? + */ + protected function doDelete($pk = null) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select($db->qn(['s.order_status_id', 's.order_status_code'])) + ->from($db->qn('#__redshop_order_status', 's')) + ->innerJoin( + $db->qn('#__redshop_orders', 'o') . ' ON ' . $db->qn('s.order_status_code') . ' = ' . $db->qn( + 'o.order_status' + ) + ) + ->where($db->qn('order_status_id') . ' = ' . $db->q($pk)); + $db->setQuery($query); + + $check = $db->loadObjectList(); + + if (count($check) > 0) { + JFactory::getApplication()->enqueueMessage(JText::_('COM_REDSHOP_ORDER_STAUS_FAIL_DELETE'), 'error'); + + return false; + } + + return parent::doDelete($pk); + } } diff --git a/component/admin/tables/order_status_log.php b/component/admin/tables/order_status_log.php index 5860192468d..320a821d0b0 100644 --- a/component/admin/tables/order_status_log.php +++ b/component/admin/tables/order_status_log.php @@ -11,34 +11,33 @@ class Tableorder_status_log extends JTable { - public $order_status_log_id = null; + public $order_status_log_id = null; - public $order_id = null; + public $order_id = null; - public $order_status = null; + public $order_status = null; - public $order_payment_status = null; + public $order_payment_status = null; - public $date_changed = null; + public $date_changed = null; - public $customer_note = null; + public $customer_note = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'order_status_log', 'order_status_log_id', $db); - } + parent::__construct($this->_table_prefix . 'order_status_log', 'order_status_log_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/order_user_detail.php b/component/admin/tables/order_user_detail.php index b3c091a201b..83640f8f140 100644 --- a/component/admin/tables/order_user_detail.php +++ b/component/admin/tables/order_user_detail.php @@ -11,72 +11,71 @@ class Tableorder_user_detail extends JTable { - public $order_info_id = null; + public $order_info_id = null; - public $users_info_id = null; + public $users_info_id = null; - public $order_id = null; + public $order_id = null; - public $user_id = null; + public $user_id = null; - public $firstname = null; + public $firstname = null; - public $address_type = null; + public $address_type = null; - public $lastname = null; + public $lastname = null; - public $vat_number = null; + public $vat_number = null; - public $tax_exempt = 0; + public $tax_exempt = 0; - public $requesting_tax_exempt = 0; + public $requesting_tax_exempt = 0; - public $shopper_group_id = null; + public $shopper_group_id = null; - public $published = null; + public $published = null; - public $isCompany = null; + public $isCompany = null; - public $country_code = null; + public $country_code = null; - public $state_code = null; + public $state_code = null; - public $zipcode = 0; + public $zipcode = 0; - public $phone = 0; + public $phone = 0; - public $city = 0; + public $city = 0; - public $address = 0; + public $address = 0; - public $tax_exempt_approved = 0; + public $tax_exempt_approved = 0; - public $approved = 0; + public $approved = 0; - public $user_email = null; + public $user_email = null; - public $company_name = null; + public $company_name = null; - public $thirdparty_email = null; + public $thirdparty_email = null; - public $ean_number = null; + public $ean_number = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'order_users_info', 'order_info_id', $db); - } + parent::__construct($this->_table_prefix . 'order_users_info', 'order_info_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/page_viewer.php b/component/admin/tables/page_viewer.php index babbe41e735..3ec5e23047b 100644 --- a/component/admin/tables/page_viewer.php +++ b/component/admin/tables/page_viewer.php @@ -18,17 +18,17 @@ */ class RedshopTablePage_Viewer extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_pageviewer'; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_pageviewer'; - /** - * Format for audit date fields (created_date, modified_date) - * - * @var string - */ - protected $_auditDateFormat = 'U'; + /** + * Format for audit date fields (created_date, modified_date) + * + * @var string + */ + protected $_auditDateFormat = 'U'; } diff --git a/component/admin/tables/prices_detail.php b/component/admin/tables/prices_detail.php index dee6c106a5e..9813c36897b 100644 --- a/component/admin/tables/prices_detail.php +++ b/component/admin/tables/prices_detail.php @@ -11,73 +11,73 @@ class Tableprices_detail extends JTable { - public $price_id = 0; + public $price_id = 0; - public $product_id = null; + public $product_id = null; - public $product_price = null; + public $product_price = null; - public $product_currency = null; + public $product_currency = null; - public $shopper_group_id = null; + public $shopper_group_id = null; - public $price_quantity_start = 0; + public $price_quantity_start = 0; - public $price_quantity_end = 0; + public $price_quantity_end = 0; - public $cdate = null; + public $cdate = null; - public $discount_price = 0; + public $discount_price = 0; - public $discount_start_date = 0; + public $discount_start_date = 0; - public $discount_end_date = 0; + public $discount_end_date = 0; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_price', 'price_id', $db); - } + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; + parent::__construct($this->_table_prefix . 'product_price', 'price_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } - public function check() - { - // Check for valid name + public function check() + { + // Check for valid name - $query = 'SELECT price_id FROM ' . $this->_table_prefix . 'product_price WHERE shopper_group_id = "' - . $this->shopper_group_id . '" AND product_id = ' . (int) $this->product_id - . ' AND price_quantity_start <= ' . $this->_db->quote($this->price_quantity_start) - . ' AND price_quantity_end >= ' . $this->_db->quote($this->price_quantity_start) . ''; + $query = 'SELECT price_id FROM ' . $this->_table_prefix . 'product_price WHERE shopper_group_id = "' + . $this->shopper_group_id . '" AND product_id = ' . (int)$this->product_id + . ' AND price_quantity_start <= ' . $this->_db->quote($this->price_quantity_start) + . ' AND price_quantity_end >= ' . $this->_db->quote($this->price_quantity_start) . ''; - $this->_db->setQuery($query); - $xid = intval($this->_db->loadResult()); + $this->_db->setQuery($query); + $xid = intval($this->_db->loadResult()); - $query_end = 'SELECT price_id FROM ' . $this->_table_prefix . 'product_price WHERE shopper_group_id = "' - . $this->shopper_group_id . '" AND product_id = ' . (int) $this->product_id - . ' AND price_quantity_start <= ' . $this->_db->quote($this->price_quantity_end) - . ' AND price_quantity_end >= ' . $this->_db->quote($this->price_quantity_end) . ''; + $query_end = 'SELECT price_id FROM ' . $this->_table_prefix . 'product_price WHERE shopper_group_id = "' + . $this->shopper_group_id . '" AND product_id = ' . (int)$this->product_id + . ' AND price_quantity_start <= ' . $this->_db->quote($this->price_quantity_end) + . ' AND price_quantity_end >= ' . $this->_db->quote($this->price_quantity_end) . ''; - $this->_db->setQuery($query_end); - $xid_end = intval($this->_db->loadResult()); + $this->_db->setQuery($query_end); + $xid_end = intval($this->_db->loadResult()); - if (($xid || $xid_end) && (($xid != intval($this->price_id) && $xid != 0) || ($xid_end != intval($this->price_id) && $xid_end != 0))) - { - $this->_error = JText::sprintf('WARNNAMETRYAGAIN', JText::_('COM_REDSHOP_PRICE_ALREADY_EXISTS')); + if (($xid || $xid_end) && (($xid != intval($this->price_id) && $xid != 0) || ($xid_end != intval( + $this->price_id + ) && $xid_end != 0))) { + $this->_error = JText::sprintf('WARNNAMETRYAGAIN', JText::_('COM_REDSHOP_PRICE_ALREADY_EXISTS')); - return false; - } + return false; + } - return true; - } + return true; + } } diff --git a/component/admin/tables/product_attribute.php b/component/admin/tables/product_attribute.php index 147ace32cd2..5aebc6901b2 100755 --- a/component/admin/tables/product_attribute.php +++ b/component/admin/tables/product_attribute.php @@ -11,46 +11,45 @@ class Tableproduct_attribute extends JTable { - public $attributeId = null; + public $attributeId = null; - public $attribute_set_id = 0; + public $attribute_set_id = 0; - public $attribute_name = null; + public $attribute_name = null; - public $attribute_description = null; + public $attribute_description = null; - public $attribute_required = null; + public $attribute_required = null; - public $allow_multiple_selection = 0; + public $allow_multiple_selection = 0; - public $hide_attribute_price = 0; + public $hide_attribute_price = 0; - public $product_id = null; + public $product_id = null; - public $ordering = null; + public $ordering = null; - public $attribute_published = 1; + public $attribute_published = 1; - public $display_type = null; + public $display_type = null; - public $extra_field = null; + public $extra_field = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_attribute', 'attribute_id', $db); - } + parent::__construct($this->_table_prefix . 'product_attribute', 'attribute_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/product_attribute_price_detail.php b/component/admin/tables/product_attribute_price_detail.php index 6d5b03abae8..751f3d1da6e 100644 --- a/component/admin/tables/product_attribute_price_detail.php +++ b/component/admin/tables/product_attribute_price_detail.php @@ -11,46 +11,45 @@ class Tableproduct_attribute_price_detail extends JTable { - public $price_id = null; + public $price_id = null; - public $section_id = 0; + public $section_id = 0; - public $section = null; + public $section = null; - public $product_price = 0; + public $product_price = 0; - public $product_currency = null; + public $product_currency = null; - public $cdate = 0; + public $cdate = 0; - public $shopper_group_id = 0; + public $shopper_group_id = 0; - public $price_quantity_start = 0; + public $price_quantity_start = 0; - public $price_quantity_end = 0; + public $price_quantity_end = 0; - public $discount_price = 0; + public $discount_price = 0; - public $discount_start_date = 0; + public $discount_start_date = 0; - public $discount_end_date = 0; + public $discount_end_date = 0; - public function __construct(& $db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_attribute_price', 'price_id', $db); - } + parent::__construct($this->_table_prefix . 'product_attribute_price', 'price_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/product_compare.php b/component/admin/tables/product_compare.php index da9561f7baf..97e4e58a6e3 100644 --- a/component/admin/tables/product_compare.php +++ b/component/admin/tables/product_compare.php @@ -11,28 +11,27 @@ class Tableproduct_compare extends JTable { - public $compare_id = 0; + public $compare_id = 0; - public $product_id = null; + public $product_id = null; - public $user_id = 0; + public $user_id = 0; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_compare', 'compare_id', $db); - } + parent::__construct($this->_table_prefix . 'product_compare', 'compare_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/product_detail.php b/component/admin/tables/product_detail.php index 16260e8574f..18f0222c48f 100644 --- a/component/admin/tables/product_detail.php +++ b/component/admin/tables/product_detail.php @@ -18,210 +18,209 @@ */ class TableProduct_Detail extends JTable { - /** - * @var integer - */ - public $attribute_set_id; - - /** - * @var integer - */ - public $not_for_sale; - - /** - * @var integer - */ - public $manufacturer_id; - - /** - * @var string - */ - public $product_name; - - /** - * @var string - */ - public $product_number; - - /** - * @var string - */ - public $product_thumb_image; - - /** - * @var string - */ - public $product_back_thumb_image; - - /** - * @var string - */ - public $product_full_image; - - /** - * @var string - */ - public $product_back_full_image; - - /** - * @var string - */ - public $product_preview_image; - - /** - * @var string - */ - public $product_preview_back_image; - - /** - * @var integer - */ - public $product_id; - - /** - * @var float - */ - public $weight; - - /** - * @var float - */ - public $product_length; - - /** - * @var float - */ - public $product_height; - - /** - * @var float - */ - public $product_width; - - /** - * @var float - */ - public $product_price; - - /** - * @var integer - */ - public $min_order_product_quantity; - - /** - * @var integer - */ - public $max_order_product_quantity; - - /** - * @var integer - */ - public $product_special; - - /** - * @var integer - */ - public $expired; - - /** - * @var integer - */ - public $product_on_sale; - - /** - * @var integer - */ - public $visited; - - /** - * @var integer - */ - public $published; - - /** - * @var integer - */ - public $product_template; - - /** - * @var integer - */ - public $product_parent_id; - - /** - * @var string - */ - public $sef_url; - - /** - * @var string - */ - public $metarobot_info; - - /** - * @var string - */ - public $product_s_desc; - - /** - * @var string - */ - public $product_desc; - - /** - * @var string - */ - public $metadesc; - - /** - * @var string - */ - public $metakey; - - /** - * @var string - */ - public $pagetitle; - - /** - * Constructor - * - * @param JDatabaseDriver $db Database driver object. - * - * @since 11.1 - */ - public function __construct($db) - { - parent::__construct('#__redshop_product', 'product_id', $db); - } - - /** - * Method to check duplicate product number - * - * @return boolean True on success - */ - public function check() - { - // Initialiase variables. - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('product_id') - ->from($db->qn('#__redshop_product')) - ->where($db->qn('product_number') . ' = ' . $db->q($this->product_number)); - - // Set the query and load the result. - $db->setQuery($query); - - $duplicateProductId = intval($db->loadResult()); - - // Make sure we are not checking it's own product number - if ($duplicateProductId && $duplicateProductId != intval($this->product_id)) - { - $this->setError(JText::_('COM_REDSHOP_PRODUCT_NUMBER_ALREADY_EXISTS')); - - return false; - } - - return true; - } + /** + * @var integer + */ + public $attribute_set_id; + + /** + * @var integer + */ + public $not_for_sale; + + /** + * @var integer + */ + public $manufacturer_id; + + /** + * @var string + */ + public $product_name; + + /** + * @var string + */ + public $product_number; + + /** + * @var string + */ + public $product_thumb_image; + + /** + * @var string + */ + public $product_back_thumb_image; + + /** + * @var string + */ + public $product_full_image; + + /** + * @var string + */ + public $product_back_full_image; + + /** + * @var string + */ + public $product_preview_image; + + /** + * @var string + */ + public $product_preview_back_image; + + /** + * @var integer + */ + public $product_id; + + /** + * @var float + */ + public $weight; + + /** + * @var float + */ + public $product_length; + + /** + * @var float + */ + public $product_height; + + /** + * @var float + */ + public $product_width; + + /** + * @var float + */ + public $product_price; + + /** + * @var integer + */ + public $min_order_product_quantity; + + /** + * @var integer + */ + public $max_order_product_quantity; + + /** + * @var integer + */ + public $product_special; + + /** + * @var integer + */ + public $expired; + + /** + * @var integer + */ + public $product_on_sale; + + /** + * @var integer + */ + public $visited; + + /** + * @var integer + */ + public $published; + + /** + * @var integer + */ + public $product_template; + + /** + * @var integer + */ + public $product_parent_id; + + /** + * @var string + */ + public $sef_url; + + /** + * @var string + */ + public $metarobot_info; + + /** + * @var string + */ + public $product_s_desc; + + /** + * @var string + */ + public $product_desc; + + /** + * @var string + */ + public $metadesc; + + /** + * @var string + */ + public $metakey; + + /** + * @var string + */ + public $pagetitle; + + /** + * Constructor + * + * @param JDatabaseDriver $db Database driver object. + * + * @since 11.1 + */ + public function __construct($db) + { + parent::__construct('#__redshop_product', 'product_id', $db); + } + + /** + * Method to check duplicate product number + * + * @return boolean True on success + */ + public function check() + { + // Initialiase variables. + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('product_id') + ->from($db->qn('#__redshop_product')) + ->where($db->qn('product_number') . ' = ' . $db->q($this->product_number)); + + // Set the query and load the result. + $db->setQuery($query); + + $duplicateProductId = intval($db->loadResult()); + + // Make sure we are not checking it's own product number + if ($duplicateProductId && $duplicateProductId != intval($this->product_id)) { + $this->setError(JText::_('COM_REDSHOP_PRODUCT_NUMBER_ALREADY_EXISTS')); + + return false; + } + + return true; + } } diff --git a/component/admin/tables/product_discount_calc.php b/component/admin/tables/product_discount_calc.php index 33090c03b2d..706a8061bf3 100644 --- a/component/admin/tables/product_discount_calc.php +++ b/component/admin/tables/product_discount_calc.php @@ -11,75 +11,77 @@ class Tableproduct_discount_calc extends JTable { - public $id = 0; + public $id = 0; - public $product_id = 0; + public $product_id = 0; - public $area_start = 0; + public $area_start = 0; - public $area_end = 0; + public $area_end = 0; - public $area_price = 0; + public $area_price = 0; - public $discount_calc_unit = null; + public $discount_calc_unit = null; - public $area_start_converted = 0; + public $area_start_converted = 0; - public $area_end_converted = 0; + public $area_end_converted = 0; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_discount_calc', 'id', $db); - } + parent::__construct($this->_table_prefix . 'product_discount_calc', 'id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } - /** - * Check for the product ID - * - * @return boolean - */ - public function check() - { - $unit = \Redshop\Helper\Utility::getUnitConversation("m", $this->discount_calc_unit); + /** + * Check for the product ID + * + * @return boolean + */ + public function check() + { + $unit = \Redshop\Helper\Utility::getUnitConversation("m", $this->discount_calc_unit); - $convertedAreaStart = $this->area_start * $unit * $unit; - $convertedAreaEnd = $this->area_end * $unit * $unit; + $convertedAreaStart = $this->area_start * $unit * $unit; + $convertedAreaEnd = $this->area_end * $unit * $unit; - $db = $this->_db; + $db = $this->_db; - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_product_discount_calc')) - ->where($db->qn('product_id') . ' = ' . (int) $this->product_id) - ->where( - '(' - . $convertedAreaStart . ' BETWEEN ' . $db->qn('area_start_converted') . ' AND ' . $db->qn('area_end_converted') - . ' || ' . $convertedAreaEnd . ' BETWEEN ' . $db->qn('area_start_converted') . ' AND ' . $db->qn('area_end_converted') - . ')' - ); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_product_discount_calc')) + ->where($db->qn('product_id') . ' = ' . (int)$this->product_id) + ->where( + '(' + . $convertedAreaStart . ' BETWEEN ' . $db->qn('area_start_converted') . ' AND ' . $db->qn( + 'area_end_converted' + ) + . ' || ' . $convertedAreaEnd . ' BETWEEN ' . $db->qn('area_start_converted') . ' AND ' . $db->qn( + 'area_end_converted' + ) + . ')' + ); - $xid = $db->setQuery($query)->loadResult(); + $xid = $db->setQuery($query)->loadResult(); - if ($xid) - { - $this->_error = JText::_('COM_REDSHOP_SAME_RANGE'); + if ($xid) { + $this->_error = JText::_('COM_REDSHOP_SAME_RANGE'); - return false; - } + return false; + } - return true; - } + return true; + } } diff --git a/component/admin/tables/product_discount_calc_extra.php b/component/admin/tables/product_discount_calc_extra.php index 543b5c9cf7c..ca875855d0d 100644 --- a/component/admin/tables/product_discount_calc_extra.php +++ b/component/admin/tables/product_discount_calc_extra.php @@ -11,32 +11,31 @@ class Tableproduct_discount_calc_extra extends JTable { - public $pdcextra_id = 0; + public $pdcextra_id = 0; - public $product_id = 0; + public $product_id = 0; - public $option_name = 0; + public $option_name = 0; - public $oprand = 0; + public $oprand = 0; - public $price = 0; + public $price = 0; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_discount_calc_extra', 'pdcextra_id', $db); - } + parent::__construct($this->_table_prefix . 'product_discount_calc_extra', 'pdcextra_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/product_download.php b/component/admin/tables/product_download.php index 5b6a65ea6ce..312d565e30f 100644 --- a/component/admin/tables/product_download.php +++ b/component/admin/tables/product_download.php @@ -11,38 +11,37 @@ class Tableproduct_download extends JTable { - public $product_id = 0; + public $product_id = 0; - public $user_id = 0; + public $user_id = 0; - public $order_id = 0; + public $order_id = 0; - public $end_date = 0; + public $end_date = 0; - public $download_max = 0; + public $download_max = 0; - public $download_id = null; + public $download_id = null; - public $file_name = null; + public $file_name = null; - public $product_serial_number = null; + public $product_serial_number = null; - public function __construct(& $db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_download', '', $db); - } + parent::__construct($this->_table_prefix . 'product_download', '', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/product_serial_number.php b/component/admin/tables/product_serial_number.php index 5383bbcd329..0d2b9904a1b 100644 --- a/component/admin/tables/product_serial_number.php +++ b/component/admin/tables/product_serial_number.php @@ -11,30 +11,29 @@ class Tableproduct_serial_number extends JTable { - public $serial_id = null; + public $serial_id = null; - public $product_id = null; + public $product_id = null; - public $serial_number = ""; + public $serial_number = ""; - public $is_used = 0; + public $is_used = 0; - public function __construct(& $db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_serial_number', 'serial_id', $db); - } + parent::__construct($this->_table_prefix . 'product_serial_number', 'serial_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/product_subscribe_detail.php b/component/admin/tables/product_subscribe_detail.php index 3dc3393da38..8d8b5688909 100644 --- a/component/admin/tables/product_subscribe_detail.php +++ b/component/admin/tables/product_subscribe_detail.php @@ -11,38 +11,37 @@ class Tableproduct_subscribe_detail extends JTable { - public $product_subscribe_id = 0; + public $product_subscribe_id = 0; - public $order_id = 0; + public $order_id = 0; - public $order_item_id = 0; + public $order_item_id = 0; - public $product_id = 0; + public $product_id = 0; - public $subscription_id = 0; + public $subscription_id = 0; - public $user_id = 0; + public $user_id = 0; - public $start_date = 0; + public $start_date = 0; - public $end_date = 0; + public $end_date = 0; - public function __construct(& $db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_subscribe_detail', 'product_subscribe_id', $db); - } + parent::__construct($this->_table_prefix . 'product_subscribe_detail', 'product_subscribe_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/product_subscription.php b/component/admin/tables/product_subscription.php index 5001f0eaf07..54c0e10c421 100644 --- a/component/admin/tables/product_subscription.php +++ b/component/admin/tables/product_subscription.php @@ -11,32 +11,31 @@ class Tableproduct_subscription extends JTable { - public $subscription_id = 0; + public $subscription_id = 0; - public $product_id = 0; + public $product_id = 0; - public $subscription_period = 0; + public $subscription_period = 0; - public $period_type = null; + public $period_type = null; - public $subscription_price = null; + public $subscription_price = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_subscription', 'subscription_id', $db); - } + parent::__construct($this->_table_prefix . 'product_subscription', 'subscription_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/product_subscription_renewal.php b/component/admin/tables/product_subscription_renewal.php index 4fd3b6f5d51..8d2ef28c841 100644 --- a/component/admin/tables/product_subscription_renewal.php +++ b/component/admin/tables/product_subscription_renewal.php @@ -11,28 +11,27 @@ class Tableproduct_subscription_renewal extends JTable { - public $renewal_id = 0; + public $renewal_id = 0; - public $product_id = 0; + public $product_id = 0; - public $before_no_days = 0; + public $before_no_days = 0; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'subscription_renewal', 'renewal_id', $db); - } + parent::__construct($this->_table_prefix . 'subscription_renewal', 'renewal_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/product_tags.php b/component/admin/tables/product_tags.php index 257e3617c82..739ec18a30d 100644 --- a/component/admin/tables/product_tags.php +++ b/component/admin/tables/product_tags.php @@ -11,30 +11,29 @@ class Tableproduct_tags extends JTable { - public $tags_id = 0; + public $tags_id = 0; - public $tags_name = null; + public $tags_name = null; - public $tags_counter = 0; + public $tags_counter = 0; - public $published = 0; + public $published = 0; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_tags', 'tags_id', $db); - } + parent::__construct($this->_table_prefix . 'product_tags', 'tags_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/question.php b/component/admin/tables/question.php index c6002c95e36..c3950104be2 100644 --- a/component/admin/tables/question.php +++ b/component/admin/tables/question.php @@ -18,33 +18,31 @@ */ class RedshopTableQuestion extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_customer_question'; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_customer_question'; - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (!parent::doCheck()) - { - return false; - } + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (!parent::doCheck()) { + return false; + } - if (isset($this->question_date) || empty($this->question_date)) - { - $this->question_date = time(); - } + if (isset($this->question_date) || empty($this->question_date)) { + $this->question_date = time(); + } - return true; - } + return true; + } } diff --git a/component/admin/tables/quotation_accessory_item.php b/component/admin/tables/quotation_accessory_item.php index 52eb8b1f5ef..420ec9f1a74 100644 --- a/component/admin/tables/quotation_accessory_item.php +++ b/component/admin/tables/quotation_accessory_item.php @@ -11,44 +11,43 @@ class Tablequotation_accessory_item extends JTable { - public $quotation_item_acc_id = null; + public $quotation_item_acc_id = null; - public $quotation_item_id = null; + public $quotation_item_id = null; - public $accessoryId = null; + public $accessoryId = null; - public $accessory_item_sku = null; + public $accessory_item_sku = null; - public $accessory_item_name = null; + public $accessory_item_name = null; - public $accessory_price = null; + public $accessory_price = null; - public $accessory_vat = null; + public $accessory_vat = null; - public $accessory_quantity = null; + public $accessory_quantity = null; - public $accessory_item_price = null; + public $accessory_item_price = null; - public $accessory_final_price = null; + public $accessory_final_price = null; - public $accessory_attribute = null; + public $accessory_attribute = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'quotation_accessory_item', 'quotation_item_acc_id', $db); - } + parent::__construct($this->_table_prefix . 'quotation_accessory_item', 'quotation_item_acc_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/quotation_attribute_item.php b/component/admin/tables/quotation_attribute_item.php index afbeced6e0a..2ef96fc61bc 100644 --- a/component/admin/tables/quotation_attribute_item.php +++ b/component/admin/tables/quotation_attribute_item.php @@ -11,42 +11,41 @@ class Tablequotation_attribute_item extends JTable { - public $quotation_att_item_id = null; + public $quotation_att_item_id = null; - public $quotation_item_id = null; + public $quotation_item_id = null; - public $section_id = null; + public $section_id = null; - public $section = null; + public $section = null; - public $parent_section_id = null; + public $parent_section_id = null; - public $section_name = null; + public $section_name = null; - public $section_vat = null; + public $section_vat = null; - public $section_price = null; + public $section_price = null; - public $section_oprand = null; + public $section_oprand = null; - public $is_accessory_att = null; + public $is_accessory_att = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'quotation_attribute_item', 'quotation_att_item_id', $db); - } + parent::__construct($this->_table_prefix . 'quotation_attribute_item', 'quotation_att_item_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/quotation_detail.php b/component/admin/tables/quotation_detail.php index 5b5b8ba215c..84fcdac4463 100644 --- a/component/admin/tables/quotation_detail.php +++ b/component/admin/tables/quotation_detail.php @@ -11,58 +11,57 @@ class Tablequotation_detail extends JTable { - public $quotation_id = null; + public $quotation_id = null; - public $quotation_number = null; + public $quotation_number = null; - public $user_id = null; + public $user_id = null; - public $user_info_id = null; + public $user_info_id = null; - public $user_email = null; + public $user_email = null; - public $order_id = null; + public $order_id = null; - public $quotation_total = null; + public $quotation_total = null; - public $quotation_subtotal = null; + public $quotation_subtotal = null; - public $quotation_tax = null; + public $quotation_tax = null; - public $quotation_discount = 0; + public $quotation_discount = 0; - public $quotation_special_discount = 0; + public $quotation_special_discount = 0; - public $quotation_status = null; + public $quotation_status = null; - public $quotation_cdate = null; + public $quotation_cdate = null; - public $quotation_mdate = null; + public $quotation_mdate = null; - public $quotation_note = null; + public $quotation_note = null; - public $quotation_customer_note = null; + public $quotation_customer_note = null; - public $quotation_ipaddress = null; + public $quotation_ipaddress = null; - public $quotation_encrkey = null; + public $quotation_encrkey = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'quotation', 'quotation_id', $db); - } + parent::__construct($this->_table_prefix . 'quotation', 'quotation_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/quotation_item_detail.php b/component/admin/tables/quotation_item_detail.php index a32da844be6..56b39d72da6 100644 --- a/component/admin/tables/quotation_item_detail.php +++ b/component/admin/tables/quotation_item_detail.php @@ -11,51 +11,50 @@ class Tablequotation_item_detail extends JTable { - public $quotation_item_id = null; + public $quotation_item_id = null; - public $quotation_id = null; + public $quotation_id = null; - public $product_id = null; + public $product_id = null; - public $product_name = null; + public $product_name = null; - public $product_price = null; + public $product_price = null; - public $actualitem_price = null; + public $actualitem_price = null; - public $product_excl_price = null; + public $product_excl_price = null; - public $product_final_price = null; + public $product_final_price = null; - public $product_quantity = null; + public $product_quantity = null; - public $product_attribute = null; + public $product_attribute = null; - public $product_accessory = null; + public $product_accessory = null; - public $mycart_accessory = null; + public $mycart_accessory = null; - public $product_wrapperid = null; + public $product_wrapperid = null; - public $wrapper_price = null; + public $wrapper_price = null; - public $is_giftcard = null; + public $is_giftcard = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'quotation_item', 'quotation_item_id', $db); - } + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; + parent::__construct($this->_table_prefix . 'quotation_item', 'quotation_item_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/rating_detail.php b/component/admin/tables/rating_detail.php index 2602c989eaf..42025b347f5 100644 --- a/component/admin/tables/rating_detail.php +++ b/component/admin/tables/rating_detail.php @@ -11,27 +11,26 @@ class RedshopTableRating_detail extends JTable { - /** - * Constructor - * - * @param JDatabaseDriver $db Database driver object. - * - * @since 11.1 - */ - public function __construct($db) - { - parent::__construct('#__redshop_product_rating', 'rating_id', $db); - } + /** + * Constructor + * + * @param JDatabaseDriver $db Database driver object. + * + * @since 11.1 + */ + public function __construct($db) + { + parent::__construct('#__redshop_product_rating', 'rating_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/related_product.php b/component/admin/tables/related_product.php index e36e0e06fd2..0d149416381 100644 --- a/component/admin/tables/related_product.php +++ b/component/admin/tables/related_product.php @@ -11,26 +11,25 @@ class Tablerelated_product extends JTable { - public $related_id = null; + public $related_id = null; - public $product_id = null; + public $product_id = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_related', 'related_id', $db); - } + parent::__construct($this->_table_prefix . 'product_related', 'related_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/sample_detail.php b/component/admin/tables/sample_detail.php index 818826d873e..fffc684a5fb 100644 --- a/component/admin/tables/sample_detail.php +++ b/component/admin/tables/sample_detail.php @@ -11,28 +11,27 @@ class Tablesample_detail extends JTable { - public $sample_id = null; + public $sample_id = null; - public $sample_name = null; + public $sample_name = null; - public $published = null; + public $published = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'catalog_sample', 'sample_id', $db); - } + parent::__construct($this->_table_prefix . 'catalog_sample', 'sample_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/sample_request.php b/component/admin/tables/sample_request.php index d8fce837d29..556cb004a92 100644 --- a/component/admin/tables/sample_request.php +++ b/component/admin/tables/sample_request.php @@ -11,34 +11,33 @@ class Tablesample_request extends JTable { - public $request_id = null; + public $request_id = null; - public $colour_id = null; + public $colour_id = null; - public $name = null; + public $name = null; - public $email = null; + public $email = null; - public $registerdate = null; + public $registerdate = null; - public $block = null; + public $block = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'sample_request', 'request_id', $db); - } + parent::__construct($this->_table_prefix . 'sample_request', 'request_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/shipping_box.php b/component/admin/tables/shipping_box.php index 7d3c8d0db1e..bf7bc301072 100644 --- a/component/admin/tables/shipping_box.php +++ b/component/admin/tables/shipping_box.php @@ -18,90 +18,82 @@ */ class RedshopTableShipping_Box extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_shipping_boxes'; - - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'shipping_box_id'; - - /** - * @var integer - */ - public $shipping_box_id = null; - - /** - * @var float - */ - public $shipping_box_name = null; - - /** - * @var float - */ - public $shipping_box_length = null; - - /** - * @var float - */ - public $shipping_box_width = null; - - /** - * @var float - */ - public $shipping_box_height = null; - - /** - * @var integer - */ - public $shipping_box_priority = null; - - /** - * @var integer - */ - public $published = null; - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - $this->shipping_box_length = floatval($this->shipping_box_length); - $this->shipping_box_width = floatval($this->shipping_box_width); - $this->shipping_box_height = floatval($this->shipping_box_height); - - if ($this->shipping_box_length <= 0.0) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_SHIPPING_BOX_ERROR_LENGTH_INVALID')); - - return false; - } - - if ($this->shipping_box_width <= 0.0) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_SHIPPING_BOX_ERROR_WIDTH_INVALID')); - - return false; - } - - if ($this->shipping_box_height <= 0.0) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_SHIPPING_BOX_ERROR_HEIGHT_INVALID')); - - return false; - } - - return parent::doCheck(); - } + /** + * @var integer + */ + public $shipping_box_id = null; + /** + * @var float + */ + public $shipping_box_name = null; + /** + * @var float + */ + public $shipping_box_length = null; + /** + * @var float + */ + public $shipping_box_width = null; + /** + * @var float + */ + public $shipping_box_height = null; + /** + * @var integer + */ + public $shipping_box_priority = null; + /** + * @var integer + */ + public $published = null; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_shipping_boxes'; + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'shipping_box_id'; + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + $this->shipping_box_length = floatval($this->shipping_box_length); + $this->shipping_box_width = floatval($this->shipping_box_width); + $this->shipping_box_height = floatval($this->shipping_box_height); + + if ($this->shipping_box_length <= 0.0) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_SHIPPING_BOX_ERROR_LENGTH_INVALID')); + + return false; + } + + if ($this->shipping_box_width <= 0.0) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_SHIPPING_BOX_ERROR_WIDTH_INVALID')); + + return false; + } + + if ($this->shipping_box_height <= 0.0) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_SHIPPING_BOX_ERROR_HEIGHT_INVALID')); + + return false; + } + + return parent::doCheck(); + } } diff --git a/component/admin/tables/shipping_detail.php b/component/admin/tables/shipping_detail.php index 7df83de60be..cff6a23edbc 100644 --- a/component/admin/tables/shipping_detail.php +++ b/component/admin/tables/shipping_detail.php @@ -11,40 +11,39 @@ class Tableshipping_detail extends JTable { - public $shipping_id = null; + public $shipping_id = null; - public $shipping_name = null; + public $shipping_name = null; - public $shipping_class = null; + public $shipping_class = null; - public $shipping_method_code = null; + public $shipping_method_code = null; - public $published = null; + public $published = null; - public $shipping_details = null; + public $shipping_details = null; - public $params = null; + public $params = null; - public $plugin = null; + public $plugin = null; - public $ordering = null; + public $ordering = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__extensions'; + public function __construct(&$db) + { + $this->_table_prefix = '#__extensions'; - parent::__construct($this->_table_prefix, 'extension_id', $db); - } + parent::__construct($this->_table_prefix, 'extension_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/shipping_rate_detail.php b/component/admin/tables/shipping_rate_detail.php index c82dc2787a2..b5eded575bb 100644 --- a/component/admin/tables/shipping_rate_detail.php +++ b/component/admin/tables/shipping_rate_detail.php @@ -11,86 +11,85 @@ class Tableshipping_rate_detail extends JTable { - public $shipping_rate_id = null; + public $shipping_rate_id = null; - public $shipping_rate_name = null; + public $shipping_rate_name = null; - public $shipping_class = null; + public $shipping_class = null; - public $shipping_rate_country = null; + public $shipping_rate_country = null; - public $shipping_rate_volume_start = null; + public $shipping_rate_volume_start = null; - public $shipping_rate_volume_end = null; + public $shipping_rate_volume_end = null; - public $shipping_rate_weight_start = null; + public $shipping_rate_weight_start = null; - public $shipping_rate_weight_end = null; + public $shipping_rate_weight_end = null; - public $shipping_rate_ordertotal_start = null; + public $shipping_rate_ordertotal_start = null; - public $shipping_rate_ordertotal_end = null; + public $shipping_rate_ordertotal_end = null; - public $shipping_rate_zip_start = null; + public $shipping_rate_zip_start = null; - public $shipping_rate_zip_end = null; + public $shipping_rate_zip_end = null; - public $shipping_rate_value = null; + public $shipping_rate_value = null; - public $shipping_rate_priority = null; + public $shipping_rate_priority = null; - public $shipping_rate_package_fee = null; + public $shipping_rate_package_fee = null; - public $shipping_rate_on_product = null; + public $shipping_rate_on_product = null; - public $shipping_rate_on_category = null; + public $shipping_rate_on_category = null; - public $company_only = null; + public $company_only = null; - public $apply_vat = 0; + public $apply_vat = 0; - public $shipping_location_info = null; + public $shipping_location_info = null; - public $shipping_rate_length_start = 0; + public $shipping_rate_length_start = 0; - public $shipping_rate_length_end = 0; + public $shipping_rate_length_end = 0; - public $shipping_rate_width_start = 0; + public $shipping_rate_width_start = 0; - public $shipping_rate_width_end = 0; + public $shipping_rate_width_end = 0; - public $shipping_rate_height_start = 0; + public $shipping_rate_height_start = 0; - public $shipping_rate_height_end = 0; + public $shipping_rate_height_end = 0; - public $shipping_tax_group_id = null; + public $shipping_tax_group_id = null; - public $shipping_rate_state = null; + public $shipping_rate_state = null; - public $shipping_rate_on_shopper_group = null; + public $shipping_rate_on_shopper_group = null; - public $consignor_carrier_code = null; + public $consignor_carrier_code = null; - public $economic_displaynumber = null; + public $economic_displaynumber = null; - public $deliver_type = null; + public $deliver_type = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'shipping_rate', 'shipping_rate_id', $db); - } + parent::__construct($this->_table_prefix . 'shipping_rate', 'shipping_rate_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/shopper_group_detail.php b/component/admin/tables/shopper_group_detail.php index d9635a40fb1..7ab7007dc8c 100644 --- a/component/admin/tables/shopper_group_detail.php +++ b/component/admin/tables/shopper_group_detail.php @@ -11,66 +11,65 @@ class Tableshopper_group_detail extends JTable { - public $shopper_group_id = null; + public $shopper_group_id = null; - public $shopper_group_name = null; + public $shopper_group_name = null; - public $shopper_group_customer_type = null; + public $shopper_group_customer_type = null; - public $shopper_group_portal = null; + public $shopper_group_portal = null; - public $shopper_group_categories = null; + public $shopper_group_categories = null; - public $shopper_group_url = null; + public $shopper_group_url = null; - public $shopper_group_logo = null; + public $shopper_group_logo = null; - public $shopper_group_introtext = null; + public $shopper_group_introtext = null; - public $shopper_group_desc = null; + public $shopper_group_desc = null; - public $parent_id = null; + public $parent_id = null; - public $default_shipping = 0; + public $default_shipping = 0; - public $default_shipping_rate = null; + public $default_shipping_rate = null; - public $show_price_without_vat = 0; + public $show_price_without_vat = 0; - public $show_price = 'global'; + public $show_price = 'global'; - public $use_as_catalog = 'global'; + public $use_as_catalog = 'global'; - public $published = null; + public $published = null; - public $shopper_group_cart_checkout_itemid = 0; + public $shopper_group_cart_checkout_itemid = 0; - public $tax_group_id = 0; + public $tax_group_id = 0; - public $apply_product_price_vat = 0; + public $apply_product_price_vat = 0; - public $shopper_group_cart_itemid = 0; + public $shopper_group_cart_itemid = 0; - public $shopper_group_quotation_mode = 0; + public $shopper_group_quotation_mode = 0; - public $shopper_group_manufactures = null; + public $shopper_group_manufactures = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'shopper_group', 'shopper_group_id', $db); - } + parent::__construct($this->_table_prefix . 'shopper_group', 'shopper_group_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/site_viewer.php b/component/admin/tables/site_viewer.php index f773fafab01..390dca7f2b5 100644 --- a/component/admin/tables/site_viewer.php +++ b/component/admin/tables/site_viewer.php @@ -18,17 +18,17 @@ */ class RedshopTableSite_Viewer extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_siteviewer'; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_siteviewer'; - /** - * Format for audit date fields (created_date, modified_date) - * - * @var string - */ - protected $_auditDateFormat = 'U'; + /** + * Format for audit date fields (created_date, modified_date) + * + * @var string + */ + protected $_auditDateFormat = 'U'; } diff --git a/component/admin/tables/state.php b/component/admin/tables/state.php index f8ab6bb87f8..5b8cc830e1e 100644 --- a/component/admin/tables/state.php +++ b/component/admin/tables/state.php @@ -18,94 +18,85 @@ */ class RedshopTableState extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_state'; - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (empty($this->country_id)) - { - return false; - } - - if (empty($this->state_name)) - { - return false; - } - - if (empty($this->state_3_code)) - { - return false; - } - - if (empty($this->state_2_code)) - { - return false; - } - - if (!parent::doCheck()) - { - return false; - } - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true); - $query->select([$db->qn('id'), $db->qn('state_3_code')]) - ->from($db->qn('#__redshop_state')) - ->where( - $db->qn('state_3_code') . ' = ' . $db->q($this->state_3_code) - . ' AND ' . $db->qn('id') . ' != ' . $db->q($this->id) - . ' AND ' . $db->qn('country_id') . ' = ' . $db->q($this->country_id) - ); - - $db->setQuery($query); - - $xid = intval($db->loadResult()); - - if ($xid) - { - $this->_error = JText::_('COM_REDSHOP_STATE_CODE3_ALREADY_EXISTS'); - JError::raiseWarning('', $this->_error); - - return false; - } - else - { - $query = $db->getQuery(true); - - $query->select([$db->qn('id'), $db->qn('state_3_code'), $db->qn('state_2_code')]) - ->from($db->qn('#__redshop_state')) - ->where( - $db->qn('state_2_code') . ' = ' . $db->q($this->state_2_code) - . ' AND ' . $db->qn('id') . ' != ' . $db->q($this->id) - . ' AND ' . $db->qn('country_id') . ' = ' . $db->q($this->country_id) - ); - - $db->setQuery($query); - $xid = intval($db->loadResult()); - - if ($xid) - { - $this->_error = JText::_('COM_REDSHOP_STATE_CODE2_ALREADY_EXISTS'); - JError::raiseWarning('', $this->_error); - - return false; - } - } - - return true; - } + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_state'; + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (empty($this->country_id)) { + return false; + } + + if (empty($this->state_name)) { + return false; + } + + if (empty($this->state_3_code)) { + return false; + } + + if (empty($this->state_2_code)) { + return false; + } + + if (!parent::doCheck()) { + return false; + } + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true); + $query->select([$db->qn('id'), $db->qn('state_3_code')]) + ->from($db->qn('#__redshop_state')) + ->where( + $db->qn('state_3_code') . ' = ' . $db->q($this->state_3_code) + . ' AND ' . $db->qn('id') . ' != ' . $db->q($this->id) + . ' AND ' . $db->qn('country_id') . ' = ' . $db->q($this->country_id) + ); + + $db->setQuery($query); + + $xid = intval($db->loadResult()); + + if ($xid) { + $this->_error = JText::_('COM_REDSHOP_STATE_CODE3_ALREADY_EXISTS'); + JError::raiseWarning('', $this->_error); + + return false; + } else { + $query = $db->getQuery(true); + + $query->select([$db->qn('id'), $db->qn('state_3_code'), $db->qn('state_2_code')]) + ->from($db->qn('#__redshop_state')) + ->where( + $db->qn('state_2_code') . ' = ' . $db->q($this->state_2_code) + . ' AND ' . $db->qn('id') . ' != ' . $db->q($this->id) + . ' AND ' . $db->qn('country_id') . ' = ' . $db->q($this->country_id) + ); + + $db->setQuery($query); + $xid = intval($db->loadResult()); + + if ($xid) { + $this->_error = JText::_('COM_REDSHOP_STATE_CODE2_ALREADY_EXISTS'); + JError::raiseWarning('', $this->_error); + + return false; + } + } + + return true; + } } diff --git a/component/admin/tables/stockimage_detail.php b/component/admin/tables/stockimage_detail.php index ca24d9f6c56..27bdecd4cf1 100644 --- a/component/admin/tables/stockimage_detail.php +++ b/component/admin/tables/stockimage_detail.php @@ -11,33 +11,32 @@ class Tablestockimage_detail extends JTable { - public $stock_amount_id = null; + public $stock_amount_id = null; - public $stockroom_id = null; + public $stockroom_id = null; - public $stock_option = null; + public $stock_option = null; - public $stock_quantity = null; + public $stock_quantity = null; - public $stock_amount_image = null; + public $stock_amount_image = null; - public $stock_amount_image_tooltip = null; + public $stock_amount_image_tooltip = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'stockroom_amount_image', 'stock_amount_id', $db); - } + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; + parent::__construct($this->_table_prefix . 'stockroom_amount_image', 'stock_amount_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/stockroom_detail.php b/component/admin/tables/stockroom_detail.php index 86afe88ad3a..e1a47ab4499 100644 --- a/component/admin/tables/stockroom_detail.php +++ b/component/admin/tables/stockroom_detail.php @@ -11,42 +11,41 @@ class Tablestockroom_detail extends JTable { - public $stockroom_id = null; + public $stockroom_id = null; - public $stockroom_name = null; + public $stockroom_name = null; - public $min_stock_amount = 0; + public $min_stock_amount = 0; - public $stockroom_desc = null; + public $stockroom_desc = null; - public $creation_date = null; + public $creation_date = null; - public $min_del_time = null; + public $min_del_time = null; - public $max_del_time = null; + public $max_del_time = null; - public $show_in_front = 0; + public $show_in_front = 0; - public $delivery_time = 'Days'; + public $delivery_time = 'Days'; - public $published = null; + public $published = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'stockroom', 'stockroom_id', $db); - } + parent::__construct($this->_table_prefix . 'stockroom', 'stockroom_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/subattribute_property.php b/component/admin/tables/subattribute_property.php index 4367e268335..02e793f9a3b 100755 --- a/component/admin/tables/subattribute_property.php +++ b/component/admin/tables/subattribute_property.php @@ -11,48 +11,47 @@ class Tablesubattribute_property extends JTable { - public $subattribute_color_id = null; + public $subattribute_color_id = null; - public $subattribute_color_name = null; + public $subattribute_color_name = null; - public $subattribute_color_title = null; + public $subattribute_color_title = null; - public $subattribute_color_price = null; + public $subattribute_color_price = null; - public $oprand = null; + public $oprand = null; - public $subattribute_color_image = null; + public $subattribute_color_image = null; - public $subattribute_id = null; + public $subattribute_id = null; - public $ordering = null; + public $ordering = null; - public $subattribute_color_number = null; + public $subattribute_color_number = null; - public $setdefault_selected = 0; + public $setdefault_selected = 0; - public $subattribute_color_main_image = null; + public $subattribute_color_main_image = null; - public $subattribute_published = 1; + public $subattribute_published = 1; - public $extra_field = null; + public $extra_field = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_subattribute_color', 'subattribute_color_id', $db); - } + parent::__construct($this->_table_prefix . 'product_subattribute_color', 'subattribute_color_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/supplier.php b/component/admin/tables/supplier.php index 437f0df1e77..a49228b88f5 100644 --- a/component/admin/tables/supplier.php +++ b/component/admin/tables/supplier.php @@ -18,28 +18,27 @@ */ class RedshopTableSupplier extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_supplier'; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_supplier'; - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (empty($this->name)) - { - return false; - } + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (empty($this->name)) { + return false; + } - return parent::doCheck(); - } + return parent::doCheck(); + } } diff --git a/component/admin/tables/tax_group.php b/component/admin/tables/tax_group.php index 7d01b511c30..87e55960fc1 100644 --- a/component/admin/tables/tax_group.php +++ b/component/admin/tables/tax_group.php @@ -18,48 +18,46 @@ */ class RedshopTableTax_Group extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_tax_group'; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_tax_group'; - /** - * Delete one or more registers - * - * @param string/array $pk Array of ids or ids comma separated - * - * @return boolean Deleted successful? - */ - protected function doDelete($pk = null) - { - // Check tax rates - if (RedshopEntityTax_Group::getInstance($this->id)->getTaxRates()->count() > 0) - { - $this->setError(JText::sprintf('COM_REDSHOP_TAX_GROUP_ERROR_DELETE_HAVE_TAX_RATE', $this->name)); + /** + * Delete one or more registers + * + * @param string/array $pk Array of ids or ids comma separated + * + * @return boolean Deleted successful? + */ + protected function doDelete($pk = null) + { + // Check tax rates + if (RedshopEntityTax_Group::getInstance($this->id)->getTaxRates()->count() > 0) { + $this->setError(JText::sprintf('COM_REDSHOP_TAX_GROUP_ERROR_DELETE_HAVE_TAX_RATE', $this->name)); - return false; - } + return false; + } - return parent::doDelete($pk); - } + return parent::doDelete($pk); + } - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (empty($this->name)) - { - return false; - } + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (empty($this->name)) { + return false; + } - return parent::doCheck(); - } + return parent::doCheck(); + } } diff --git a/component/admin/tables/tax_rate.php b/component/admin/tables/tax_rate.php index 494066f1bed..571e8a38c10 100644 --- a/component/admin/tables/tax_rate.php +++ b/component/admin/tables/tax_rate.php @@ -18,45 +18,41 @@ */ class RedshopTableTax_Rate extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_tax_rate'; - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (empty($this->name)) - { - return false; - } - - if (empty($this->tax_group_id)) - { - return false; - } - - if (!parent::doCheck()) - { - return false; - } - - if ($this->tax_rate < 0) - { - $this->setError(JText::_('COM_REDSHOP_TAX_RATE_INVALID_INPUT_MSG')); - - return false; - } - - return true; - } + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_tax_rate'; + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (empty($this->name)) { + return false; + } + + if (empty($this->tax_group_id)) { + return false; + } + + if (!parent::doCheck()) { + return false; + } + + if ($this->tax_rate < 0) { + $this->setError(JText::_('COM_REDSHOP_TAX_RATE_INVALID_INPUT_MSG')); + + return false; + } + + return true; + } } diff --git a/component/admin/tables/template.php b/component/admin/tables/template.php index 2d8e2dbaebd..f038a4a816c 100644 --- a/component/admin/tables/template.php +++ b/component/admin/tables/template.php @@ -18,238 +18,212 @@ */ class RedshopTableTemplate extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_template'; - - /** - * Temporary variable for store/load template content; - * - * @var string - */ - public $templateDesc; - - /** - * @var integer - */ - public $id; - - /** - * @var string - */ - public $file_name; - - /** - * @var string - */ - public $name; - - /** - * @var string - */ - public $section; - - /** - * Method to load a row from the database by primary key and bind the fields - * to the JTable instance properties. - * - * @param mixed $keys An optional primary key value to load the row by, or an array of fields to match. If not - * set the instance property value is used. - * @param boolean $reset True to reset the default values before loading the new row. - * - * @return boolean True if successful. False if row not found. - */ - protected function doLoad($keys = null, $reset = true) - { - if (!parent::doLoad($keys, $reset)) - { - return false; - } - - if ($this->id && !empty($this->file_name)) - { - $file = JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $this->section . '/' . $this->file_name . '.php'); - - if (JFile::exists($file)) - { - $this->templateDesc = (string) file_get_contents($file); - } - } - - return true; - } - - /** - * Method to bind an associative array or object to the JTable instance.This - * method only binds properties that are publicly accessible and optionally - * takes an array of properties to ignore when binding. - * - * @param mixed $src An associative array or object to bind to the JTable instance. - * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. - * - * @return boolean True on success. - * - * @throws InvalidArgumentException - */ - protected function doBind(&$src, $ignore = array()) - { - if (!empty($src['order_status']) && !is_array($src['order_status'])) - { - $src['order_status'] = explode(',', $src['order_status']); - } - else - { - unset($src['order_status']); - $this->order_status = ''; - } - - if (!empty($src['payment_methods']) && !is_array($src['payment_methods'])) - { - $src['payment_methods'] = explode(',', $src['payment_methods']); - } - else - { - unset($src['payment_methods']); - $this->payment_methods = ''; - } - - if (!empty($src['shipping_methods']) && !is_array($src['shipping_methods'])) - { - $src['shipping_methods'] = explode(',', $src['shipping_methods']); - } - else - { - unset($src['shipping_methods']); - $this->shipping_methods = ''; - } - - return parent::doBind($src, $ignore); - } - - /** - * Do the database store. - * - * @param boolean $updateNulls True to update null values as well. - * - * @return boolean - * - * @throws Exception - */ - protected function doStore($updateNulls = false) - { - if (!empty($this->payment_methods) && is_array($this->payment_methods)) - { - $this->payment_methods = implode(',', $this->payment_methods); - } - - if (!empty($this->shipping_methods) && is_array($this->shipping_methods)) - { - $this->shipping_methods = implode(',', $this->shipping_methods); - } - - if (!empty($this->order_status) && is_array($this->order_status)) - { - $this->order_status = implode(',', $this->order_status); - } - - $isNew = !$this->id; - - $this->setOption('content', $this->templateDesc); - unset($this->templateDesc); - - if (!parent::doStore($updateNulls)) - { - return false; - } - - if ($isNew || empty($this->file_name)) - { - $fileName = $this->generateTemplateFileName($this->id, $this->name); - - $db = $this->getDbo(); - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_template')) - ->where($db->qn('id') . ' = ' . $this->id) - ->set($db->qn('file_name') . ' = ' . $db->quote($fileName)); - $db->setQuery($query)->execute(); - } - else - { - $fileName = $this->file_name; - } - - // Write template file - JFile::write( - JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $this->section . '/' . $fileName . '.php'), - $this->getOption('content', '') - ); - - return true; - } - - /** - * Delete one or more registers - * - * @param string /array $pk Array of ids or ids comma separated - * - * @return boolean Deleted successfully? - */ - protected function doDelete($pk = null) - { - if (!parent::doDelete($pk)) - { - return false; - } - - $templatePath = JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $this->section . '/' . $this->file_name . '.php'); - - if (JFile::exists($templatePath)) - { - return JFile::delete($templatePath); - } - - return true; - } - - /** - * Method for make template name safe - * - * @param integer $id Template ID - * @param string $name Template name - * - * @return string - * - * @since 2.0.7 - */ - public function generateTemplateFileName($id = 0, $name = '') - { - return str_replace('-', '_', JFilterOutput::stringURLSafe($id . ' - ' . strtolower($name))); - } - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (empty($this->name)) - { - return false; - } - - if (empty($this->section)) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('COM_REDSHOP_TEMPLATE_ERROR_SELECT_SECTION')); - return false; - } - - return parent::doCheck(); - } + /** + * Temporary variable for store/load template content; + * + * @var string + */ + public $templateDesc; + /** + * @var integer + */ + public $id; + /** + * @var string + */ + public $file_name; + /** + * @var string + */ + public $name; + /** + * @var string + */ + public $section; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_template'; + + /** + * Method to load a row from the database by primary key and bind the fields + * to the JTable instance properties. + * + * @param mixed $keys An optional primary key value to load the row by, or an array of fields to match. If not + * set the instance property value is used. + * @param boolean $reset True to reset the default values before loading the new row. + * + * @return boolean True if successful. False if row not found. + */ + protected function doLoad($keys = null, $reset = true) + { + if (!parent::doLoad($keys, $reset)) { + return false; + } + + if ($this->id && !empty($this->file_name)) { + $file = JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $this->section . '/' . $this->file_name . '.php'); + + if (JFile::exists($file)) { + $this->templateDesc = (string)file_get_contents($file); + } + } + + return true; + } + + /** + * Method to bind an associative array or object to the JTable instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param mixed $src An associative array or object to bind to the JTable instance. + * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + * + * @throws InvalidArgumentException + */ + protected function doBind(&$src, $ignore = array()) + { + if (!empty($src['order_status']) && !is_array($src['order_status'])) { + $src['order_status'] = explode(',', $src['order_status']); + } else { + unset($src['order_status']); + $this->order_status = ''; + } + + if (!empty($src['payment_methods']) && !is_array($src['payment_methods'])) { + $src['payment_methods'] = explode(',', $src['payment_methods']); + } else { + unset($src['payment_methods']); + $this->payment_methods = ''; + } + + if (!empty($src['shipping_methods']) && !is_array($src['shipping_methods'])) { + $src['shipping_methods'] = explode(',', $src['shipping_methods']); + } else { + unset($src['shipping_methods']); + $this->shipping_methods = ''; + } + + return parent::doBind($src, $ignore); + } + + /** + * Do the database store. + * + * @param boolean $updateNulls True to update null values as well. + * + * @return boolean + * + * @throws Exception + */ + protected function doStore($updateNulls = false) + { + if (!empty($this->payment_methods) && is_array($this->payment_methods)) { + $this->payment_methods = implode(',', $this->payment_methods); + } + + if (!empty($this->shipping_methods) && is_array($this->shipping_methods)) { + $this->shipping_methods = implode(',', $this->shipping_methods); + } + + if (!empty($this->order_status) && is_array($this->order_status)) { + $this->order_status = implode(',', $this->order_status); + } + + $isNew = !$this->id; + + $this->setOption('content', $this->templateDesc); + unset($this->templateDesc); + + if (!parent::doStore($updateNulls)) { + return false; + } + + if ($isNew || empty($this->file_name)) { + $fileName = $this->generateTemplateFileName($this->id, $this->name); + + $db = $this->getDbo(); + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_template')) + ->where($db->qn('id') . ' = ' . $this->id) + ->set($db->qn('file_name') . ' = ' . $db->quote($fileName)); + $db->setQuery($query)->execute(); + } else { + $fileName = $this->file_name; + } + + // Write template file + JFile::write( + JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $this->section . '/' . $fileName . '.php'), + $this->getOption('content', '') + ); + + return true; + } + + /** + * Method for make template name safe + * + * @param integer $id Template ID + * @param string $name Template name + * + * @return string + * + * @since 2.0.7 + */ + public function generateTemplateFileName($id = 0, $name = '') + { + return str_replace('-', '_', JFilterOutput::stringURLSafe($id . ' - ' . strtolower($name))); + } + + /** + * Delete one or more registers + * + * @param string /array $pk Array of ids or ids comma separated + * + * @return boolean Deleted successfully? + */ + protected function doDelete($pk = null) + { + if (!parent::doDelete($pk)) { + return false; + } + + $templatePath = JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $this->section . '/' . $this->file_name . '.php'); + + if (JFile::exists($templatePath)) { + return JFile::delete($templatePath); + } + + return true; + } + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (empty($this->name)) { + return false; + } + + if (empty($this->section)) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('COM_REDSHOP_TEMPLATE_ERROR_SELECT_SECTION')); + + return false; + } + + return parent::doCheck(); + } } diff --git a/component/admin/tables/text.php b/component/admin/tables/text.php index ccba85d8ffa..178c256d10d 100644 --- a/component/admin/tables/text.php +++ b/component/admin/tables/text.php @@ -18,51 +18,45 @@ */ class RedshopTableText extends RedshopTable { - /** - * @var string - */ - protected $_tableName = 'redshop_textlibrary'; - - /** - * @var string - */ - public $name; - - /** - * @var string - */ - public $desc; - - /** - * @var string - */ - public $section = 'product'; - - /** - * @var integer - */ - public $published = 1; - - /** - * @var string - */ - public $content; - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (empty($this->name)) - { - return false; - } - - return parent::doCheck(); - } + /** + * @var string + */ + public $name; + /** + * @var string + */ + public $desc; + /** + * @var string + */ + public $section = 'product'; + /** + * @var integer + */ + public $published = 1; + /** + * @var string + */ + public $content; + /** + * @var string + */ + protected $_tableName = 'redshop_textlibrary'; + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (empty($this->name)) { + return false; + } + + return parent::doCheck(); + } } diff --git a/component/admin/tables/transaction_coupon_detail.php b/component/admin/tables/transaction_coupon_detail.php index 0c2eda0369f..4bcf9a90e3a 100644 --- a/component/admin/tables/transaction_coupon_detail.php +++ b/component/admin/tables/transaction_coupon_detail.php @@ -11,36 +11,35 @@ class Tabletransaction_coupon_detail extends JTable { - public $transaction_coupon_id = null; + public $transaction_coupon_id = null; - public $coupon_id = null; + public $coupon_id = null; - public $coupon_code = null; + public $coupon_code = null; - public $coupon_value = null; + public $coupon_value = null; - public $userid = null; + public $userid = null; - public $trancation_date = null; + public $trancation_date = null; - public $published = null; + public $published = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'coupons_transaction', 'transaction_coupon_id', $db); - } + parent::__construct($this->_table_prefix . 'coupons_transaction', 'transaction_coupon_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/transaction_voucher_detail.php b/component/admin/tables/transaction_voucher_detail.php index 9d9633b167b..4e921cc2049 100644 --- a/component/admin/tables/transaction_voucher_detail.php +++ b/component/admin/tables/transaction_voucher_detail.php @@ -11,40 +11,39 @@ class Tabletransaction_voucher_detail extends JTable { - public $transaction_voucher_id = null; + public $transaction_voucher_id = null; - public $voucher_id = null; + public $voucher_id = null; - public $voucher_code = null; + public $voucher_code = null; - public $amount = null; + public $amount = null; - public $user_id = null; + public $user_id = null; - public $order_id = null; + public $order_id = null; - public $trancation_date = null; + public $trancation_date = null; - public $product_id = null; + public $product_id = null; - public $published = null; + public $published = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'product_voucher_transaction', 'transaction_voucher_id', $db); - } + parent::__construct($this->_table_prefix . 'product_voucher_transaction', 'transaction_voucher_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/user_detail.php b/component/admin/tables/user_detail.php index f1ad18ab601..13254939ef3 100644 --- a/component/admin/tables/user_detail.php +++ b/component/admin/tables/user_detail.php @@ -11,70 +11,69 @@ class Tableuser_detail extends JTable { - public $users_info_id = null; + public $users_info_id = null; - public $user_email = null; + public $user_email = null; - public $user_id = null; + public $user_id = null; - public $firstname = null; + public $firstname = null; - public $address_type = null; + public $address_type = null; - public $lastname = null; + public $lastname = null; - public $company_name = null; + public $company_name = null; - public $vat_number = null; + public $vat_number = null; - public $requesting_tax_exempt = null; + public $requesting_tax_exempt = null; - public $tax_exempt = 0; + public $tax_exempt = 0; - public $shopper_group_id = null; + public $shopper_group_id = null; - public $isCompany = null; + public $isCompany = null; - public $address = 0; + public $address = 0; - public $city = 0; + public $city = 0; - public $country_code = null; + public $country_code = null; - public $state_code = null; + public $state_code = null; - public $zipcode = 0; + public $zipcode = 0; - public $phone = 0; + public $phone = 0; - public $tax_exempt_approved = 0; + public $tax_exempt_approved = 0; - public $approved = 0; + public $approved = 0; - public $ean_number = null; + public $ean_number = null; - public $accept_terms_conditions = 0; + public $accept_terms_conditions = 0; - public $veis_vat_number = null; + public $veis_vat_number = null; - public $veis_status = null; + public $veis_status = null; - public function __construct(& $db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'users_info', 'users_info_id', $db); - } + parent::__construct($this->_table_prefix . 'users_info', 'users_info_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/usercart.php b/component/admin/tables/usercart.php index a41145f637c..98a21ac7878 100644 --- a/component/admin/tables/usercart.php +++ b/component/admin/tables/usercart.php @@ -18,37 +18,32 @@ */ class RedshopTableUsercart extends \Redshop\Table\AbstractTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_usercart'; - - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'cart_id'; - - /** - * @var integer - */ - public $cart_id = 0; - - /** - * @var integer - */ - public $user_id = 0; - - /** - * @var integer - */ - public $cdate = 0; - - /** - * @var integer - */ - public $mdate = 0; + /** + * @var integer + */ + public $cart_id = 0; + /** + * @var integer + */ + public $user_id = 0; + /** + * @var integer + */ + public $cdate = 0; + /** + * @var integer + */ + public $mdate = 0; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_usercart'; + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'cart_id'; } diff --git a/component/admin/tables/usercart_accessory_item.php b/component/admin/tables/usercart_accessory_item.php index 98ea01d7a70..8e589206c72 100644 --- a/component/admin/tables/usercart_accessory_item.php +++ b/component/admin/tables/usercart_accessory_item.php @@ -18,37 +18,32 @@ */ class RedshopTableUsercart_Accessory_Item extends \Redshop\Table\AbstractTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_usercart_accessory_item'; - - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'cart_acc_item_id'; - - /** - * @var integer - */ - public $cart_acc_item_id = 0; - - /** - * @var integer - */ - public $cart_item_id = 0; - - /** - * @var integer - */ - public $accessoryId = 0; - - /** - * @var integer - */ - public $accessory_quantity = 0; + /** + * @var integer + */ + public $cart_acc_item_id = 0; + /** + * @var integer + */ + public $cart_item_id = 0; + /** + * @var integer + */ + public $accessoryId = 0; + /** + * @var integer + */ + public $accessory_quantity = 0; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_usercart_accessory_item'; + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'cart_acc_item_id'; } diff --git a/component/admin/tables/usercart_attribute_item.php b/component/admin/tables/usercart_attribute_item.php index 0a3dc3720d7..6b178b0544a 100644 --- a/component/admin/tables/usercart_attribute_item.php +++ b/component/admin/tables/usercart_attribute_item.php @@ -18,47 +18,40 @@ */ class RedshopTableUsercart_Attribute_Item extends \Redshop\Table\AbstractTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_usercart_attribute_item'; - - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'cart_att_item_id'; - - /** - * @var integer - */ - public $cart_att_item_id = 0; - - /** - * @var integer - */ - public $cart_item_id = 0; - - /** - * @var integer - */ - public $section_id = 0; - - /** - * @var string - */ - public $section = null; - - /** - * @var integer - */ - public $parent_section_id = 0; - - /** - * @var integer - */ - public $is_accessory_att = 0; + /** + * @var integer + */ + public $cart_att_item_id = 0; + /** + * @var integer + */ + public $cart_item_id = 0; + /** + * @var integer + */ + public $section_id = 0; + /** + * @var string + */ + public $section = null; + /** + * @var integer + */ + public $parent_section_id = 0; + /** + * @var integer + */ + public $is_accessory_att = 0; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_usercart_attribute_item'; + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'cart_att_item_id'; } diff --git a/component/admin/tables/usercart_item.php b/component/admin/tables/usercart_item.php index a771f6ff125..21b26dd0b5f 100644 --- a/component/admin/tables/usercart_item.php +++ b/component/admin/tables/usercart_item.php @@ -18,62 +18,52 @@ */ class RedshopTableUsercart_Item extends \Redshop\Table\AbstractTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_usercart_item'; - - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'cart_item_id'; - - /** - * @var integer - */ - public $cart_item_id = 0; - - /** - * @var integer - */ - public $cart_idx = 0; - - /** - * @var integer - */ - public $cart_id = 0; - - /** - * @var integer - */ - public $product_id = 0; - - /** - * @var integer - */ - public $product_quantity = 0; - - /** - * @var integer - */ - public $product_wrapper_id = 0; - - /** - * @var integer - */ - public $product_subscription_id = 0; - - /** - * @var integer - */ - public $giftcard_id = 0; - - /** - * @var string - */ - public $attribs = ''; + /** + * @var integer + */ + public $cart_item_id = 0; + /** + * @var integer + */ + public $cart_idx = 0; + /** + * @var integer + */ + public $cart_id = 0; + /** + * @var integer + */ + public $product_id = 0; + /** + * @var integer + */ + public $product_quantity = 0; + /** + * @var integer + */ + public $product_wrapper_id = 0; + /** + * @var integer + */ + public $product_subscription_id = 0; + /** + * @var integer + */ + public $giftcard_id = 0; + /** + * @var string + */ + public $attribs = ''; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_usercart_item'; + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'cart_item_id'; } diff --git a/component/admin/tables/voucher.php b/component/admin/tables/voucher.php index 6e19be3a8ec..cfcfe41099b 100644 --- a/component/admin/tables/voucher.php +++ b/component/admin/tables/voucher.php @@ -18,184 +18,170 @@ */ class RedshopTableVoucher extends RedshopTable { - /** - * The table name without the prefix. Ex: cursos_courses - * - * @var string - */ - protected $_tableName = 'redshop_voucher'; - - /** - * @var integer - */ - public $id; - - /** - * @var string - */ - public $code; - - /** - * @var float - */ - public $amount; - - /** - * @var string - */ - public $type; - - /** - * @var string - */ - public $start_date = '0000-00-00 00:00:00'; - - /** - * @var string - */ - public $end_date = '0000-00-00 00:00:00'; - - /** - * @var integer - */ - public $free_ship; - - /** - * @var integer - */ - public $voucher_left; - - /** - * @var integer - */ - public $published; - - /** - * Checks that the object is valid and able to be stored. - * - * This method checks that the parent_id is non-zero and exists in the database. - * Note that the root node (parent_id = 0) cannot be manipulated with this class. - * - * @return boolean True if all checks pass. - */ - protected function doCheck() - { - if (!parent::doCheck()) - { - return false; - } - - $db = $this->getDbo(); - - // Check duplicate. - $code = $this->get('code'); - - $voucherQuery = $db->getQuery(true) - ->select($db->qn('code')) - ->from($db->qn('#__redshop_voucher')); - - if ($this->hasPrimaryKey()) - { - $voucherQuery->where($db->qn('id') . ' <> ' . $this->id); - } - - $couponQuery = $db->getQuery(true) - ->select($db->qn('code')) - ->from($db->qn('#__redshop_coupons')); - $couponQuery->union($voucherQuery); - - $query = $db->getQuery(true) - ->select('COUNT(*)') - ->from('(' . $couponQuery . ') AS ' . $db->qn('data')) - ->where($db->qn('data.code') . ' = ' . $db->quote($code)); - - if ($db->setQuery($query)->loadResult()) - { - $this->setError(JText::_('COM_REDSHOP_VOUCHER_ERROR_CODE_ALREADY_EXIST')); - - return false; - } - - return true; - } - - /** - * Method to bind an associative array or object to the JTable instance.This - * method only binds properties that are publicly accessible and optionally - * takes an array of properties to ignore when binding. - * - * @param mixed $src An associative array or object to bind to the JTable instance. - * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. - * - * @return boolean True on success. - * - * @throws Exception - */ - protected function doBind(&$src, $ignore = array()) - { - if (isset($src['voucher_products']) && !empty($src['voucher_products'])) - { - $products = is_string($src['voucher_products']) ? explode(',', $src['voucher_products']) : $src['voucher_products']; - $this->setOption('products', $products); - unset($src['shopper_group']); - } - - return parent::doBind($src, $ignore); - } - - /** - * Do the database store. - * - * @param boolean $updateNulls True to update null values as well. - * - * @return boolean - */ - protected function doStore($updateNulls = false) - { - if (!parent::doStore($updateNulls)) - { - return false; - } - - if ($this->getOption('skip.updateProducts', false) === true || $this->getOption('inlineMode', false) === true) - { - return true; - } - - return $this->updateProduct(); - } - - /** - * Method for update product xref. - * - * @return boolean - */ - protected function updateProduct() - { - $db = $this->getDbo(); - - // Clear current reference products. - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_product_voucher_xref')) - ->where($db->qn('voucher_id') . ' = ' . $this->id); - $db->setQuery($query)->execute(); - - $products = $this->getOption('products', null); - - if (empty(array_filter($products))) - { - return true; - } - - $query->clear() - ->insert($db->qn('#__redshop_product_voucher_xref')) - ->columns($db->qn(array('voucher_id', 'product_id'))); - - foreach ($products as $productId) - { - $query->values((int) $this->id . ',' . (int) $productId); - } - - return $db->setQuery($query)->execute(); - } + /** + * @var integer + */ + public $id; + /** + * @var string + */ + public $code; + /** + * @var float + */ + public $amount; + /** + * @var string + */ + public $type; + /** + * @var string + */ + public $start_date = '0000-00-00 00:00:00'; + /** + * @var string + */ + public $end_date = '0000-00-00 00:00:00'; + /** + * @var integer + */ + public $free_ship; + /** + * @var integer + */ + public $voucher_left; + /** + * @var integer + */ + public $published; + /** + * The table name without the prefix. Ex: cursos_courses + * + * @var string + */ + protected $_tableName = 'redshop_voucher'; + + /** + * Checks that the object is valid and able to be stored. + * + * This method checks that the parent_id is non-zero and exists in the database. + * Note that the root node (parent_id = 0) cannot be manipulated with this class. + * + * @return boolean True if all checks pass. + */ + protected function doCheck() + { + if (!parent::doCheck()) { + return false; + } + + $db = $this->getDbo(); + + // Check duplicate. + $code = $this->get('code'); + + $voucherQuery = $db->getQuery(true) + ->select($db->qn('code')) + ->from($db->qn('#__redshop_voucher')); + + if ($this->hasPrimaryKey()) { + $voucherQuery->where($db->qn('id') . ' <> ' . $this->id); + } + + $couponQuery = $db->getQuery(true) + ->select($db->qn('code')) + ->from($db->qn('#__redshop_coupons')); + $couponQuery->union($voucherQuery); + + $query = $db->getQuery(true) + ->select('COUNT(*)') + ->from('(' . $couponQuery . ') AS ' . $db->qn('data')) + ->where($db->qn('data.code') . ' = ' . $db->quote($code)); + + if ($db->setQuery($query)->loadResult()) { + $this->setError(JText::_('COM_REDSHOP_VOUCHER_ERROR_CODE_ALREADY_EXIST')); + + return false; + } + + return true; + } + + /** + * Method to bind an associative array or object to the JTable instance.This + * method only binds properties that are publicly accessible and optionally + * takes an array of properties to ignore when binding. + * + * @param mixed $src An associative array or object to bind to the JTable instance. + * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. + * + * @return boolean True on success. + * + * @throws Exception + */ + protected function doBind(&$src, $ignore = array()) + { + if (isset($src['voucher_products']) && !empty($src['voucher_products'])) { + $products = is_string($src['voucher_products']) ? explode( + ',', + $src['voucher_products'] + ) : $src['voucher_products']; + $this->setOption('products', $products); + unset($src['shopper_group']); + } + + return parent::doBind($src, $ignore); + } + + /** + * Do the database store. + * + * @param boolean $updateNulls True to update null values as well. + * + * @return boolean + */ + protected function doStore($updateNulls = false) + { + if (!parent::doStore($updateNulls)) { + return false; + } + + if ($this->getOption('skip.updateProducts', false) === true || $this->getOption('inlineMode', false) === true) { + return true; + } + + return $this->updateProduct(); + } + + /** + * Method for update product xref. + * + * @return boolean + */ + protected function updateProduct() + { + $db = $this->getDbo(); + + // Clear current reference products. + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_product_voucher_xref')) + ->where($db->qn('voucher_id') . ' = ' . $this->id); + $db->setQuery($query)->execute(); + + $products = $this->getOption('products', null); + + if (empty(array_filter($products))) { + return true; + } + + $query->clear() + ->insert($db->qn('#__redshop_product_voucher_xref')) + ->columns($db->qn(array('voucher_id', 'product_id'))); + + foreach ($products as $productId) { + $query->values((int)$this->id . ',' . (int)$productId); + } + + return $db->setQuery($query)->execute(); + } } diff --git a/component/admin/tables/wishlist.php b/component/admin/tables/wishlist.php index 97aa32ab93a..618477cf9b6 100644 --- a/component/admin/tables/wishlist.php +++ b/component/admin/tables/wishlist.php @@ -11,32 +11,31 @@ class Tablewishlist extends JTable { - public $wishlist_id = 0; + public $wishlist_id = 0; - public $wishlist_name = null; + public $wishlist_name = null; - public $user_id = null; + public $user_id = null; - public $comment = null; + public $comment = null; - public $cdate = null; + public $cdate = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'wishlist', 'wishlist_id', $db); - } + parent::__construct($this->_table_prefix . 'wishlist', 'wishlist_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/wishlist_product.php b/component/admin/tables/wishlist_product.php index 77dad61c9f5..f6ee424f202 100644 --- a/component/admin/tables/wishlist_product.php +++ b/component/admin/tables/wishlist_product.php @@ -18,17 +18,17 @@ */ class RedshopTableWishlist_Product extends RedshopTable { - /** - * The table name without the prefix. - * - * @var string - */ - protected $_tableName = 'redshop_wishlist_product'; + /** + * The table name without the prefix. + * + * @var string + */ + protected $_tableName = 'redshop_wishlist_product'; - /** - * The table key column. Usually: id - * - * @var string - */ - protected $_tableKey = 'wishlist_product_id'; + /** + * The table key column. Usually: id + * + * @var string + */ + protected $_tableKey = 'wishlist_product_id'; } diff --git a/component/admin/tables/wishlist_product_item.php b/component/admin/tables/wishlist_product_item.php index 0efc5ac6568..5ba3ee7585e 100644 --- a/component/admin/tables/wishlist_product_item.php +++ b/component/admin/tables/wishlist_product_item.php @@ -18,10 +18,10 @@ */ class RedshopTableWishlist_Product_Item extends RedshopTable { - /** - * The table name without the prefix. - * - * @var string - */ - protected $_tableName = 'redshop_wishlist_product_item'; + /** + * The table name without the prefix. + * + * @var string + */ + protected $_tableName = 'redshop_wishlist_product_item'; } diff --git a/component/admin/tables/wrapper_detail.php b/component/admin/tables/wrapper_detail.php index 82f8c4b3be6..e359acbb517 100644 --- a/component/admin/tables/wrapper_detail.php +++ b/component/admin/tables/wrapper_detail.php @@ -11,39 +11,38 @@ class Tablewrapper_detail extends JTable { - public $wrapper_id = 0; + public $wrapper_id = 0; - public $product_id = null; + public $product_id = null; - public $category_id = null; + public $category_id = null; - public $wrapper_price = null; + public $wrapper_price = null; - public $wrapper_name = null; + public $wrapper_name = null; - public $wrapper_image = null; + public $wrapper_image = null; - public $wrapper_use_to_all = 0; + public $wrapper_use_to_all = 0; - public $published = 1; + public $published = 1; - public $createdate = 0; + public $createdate = 0; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'wrapper', 'wrapper_id', $db); - } + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; + parent::__construct($this->_table_prefix . 'wrapper', 'wrapper_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/xmlexport_detail.php b/component/admin/tables/xmlexport_detail.php index 5155608226d..fa48473ae57 100644 --- a/component/admin/tables/xmlexport_detail.php +++ b/component/admin/tables/xmlexport_detail.php @@ -11,70 +11,69 @@ class Tablexmlexport_detail extends JTable { - public $xmlexport_id = null; + public $xmlexport_id = null; - public $filename = null; + public $filename = null; - public $display_filename = null; + public $display_filename = null; - public $parent_name = null; + public $parent_name = null; - public $element_name = null; + public $element_name = null; - public $section_type = null; + public $section_type = null; - public $sync_on_request = 0; + public $sync_on_request = 0; - public $auto_sync = 0; + public $auto_sync = 0; - public $auto_sync_interval = 0; + public $auto_sync_interval = 0; - public $xmlexport_date = null; + public $xmlexport_date = null; - public $xmlexport_filetag = null; + public $xmlexport_filetag = null; - public $xmlexport_billingtag = null; + public $xmlexport_billingtag = null; - public $billing_element_name = null; + public $billing_element_name = null; - public $xmlexport_shippingtag = null; + public $xmlexport_shippingtag = null; - public $shipping_element_name = null; + public $shipping_element_name = null; - public $xmlexport_orderitemtag = null; + public $xmlexport_orderitemtag = null; - public $orderitem_element_name = null; + public $orderitem_element_name = null; - public $xmlexport_stocktag = null; + public $xmlexport_stocktag = null; - public $stock_element_name = null; + public $stock_element_name = null; - public $xmlexport_prdextrafieldtag = null; + public $xmlexport_prdextrafieldtag = null; - public $prdextrafield_element_name = null; + public $prdextrafield_element_name = null; - public $published = 0; + public $published = 0; - public $use_to_all_users = 1; + public $use_to_all_users = 1; - public $xmlexport_on_category = null; + public $xmlexport_on_category = null; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'xml_export', 'xmlexport_id', $db); - } + parent::__construct($this->_table_prefix . 'xml_export', 'xmlexport_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/xmlimport_detail.php b/component/admin/tables/xmlimport_detail.php index 121346bc0bc..84fa62b0ec5 100644 --- a/component/admin/tables/xmlimport_detail.php +++ b/component/admin/tables/xmlimport_detail.php @@ -11,70 +11,69 @@ class Tablexmlimport_detail extends JTable { - public $xmlimport_id = null; + public $xmlimport_id = null; - public $filename = null; + public $filename = null; - public $display_filename = null; + public $display_filename = null; - public $xmlimport_url = null; + public $xmlimport_url = null; - public $section_type = null; + public $section_type = null; - public $sync_on_request = 0; + public $sync_on_request = 0; - public $auto_sync = 0; + public $auto_sync = 0; - public $auto_sync_interval = 0; + public $auto_sync_interval = 0; - public $override_existing = 0; + public $override_existing = 0; - public $add_prefix_for_existing = null; + public $add_prefix_for_existing = null; - public $xmlimport_date = null; + public $xmlimport_date = null; - public $xmlimport_filetag = null; + public $xmlimport_filetag = null; - public $xmlimport_billingtag = null; + public $xmlimport_billingtag = null; - public $xmlimport_shippingtag = null; + public $xmlimport_shippingtag = null; - public $xmlimport_orderitemtag = null; + public $xmlimport_orderitemtag = null; - public $xmlimport_stocktag = null; + public $xmlimport_stocktag = null; - public $xmlimport_prdextrafieldtag = null; + public $xmlimport_prdextrafieldtag = null; - public $element_name = null; + public $element_name = null; - public $billing_element_name = null; + public $billing_element_name = null; - public $shipping_element_name = null; + public $shipping_element_name = null; - public $orderitem_element_name = null; + public $orderitem_element_name = null; - public $stock_element_name = null; + public $stock_element_name = null; - public $prdextrafield_element_name = null; + public $prdextrafield_element_name = null; - public $published = 0; + public $published = 0; - public function __construct(&$db) - { - $this->_table_prefix = '#__redshop_'; + public function __construct(&$db) + { + $this->_table_prefix = '#__redshop_'; - parent::__construct($this->_table_prefix . 'xml_import', 'xmlimport_id', $db); - } + parent::__construct($this->_table_prefix . 'xml_import', 'xmlimport_id', $db); + } - public function bind($array, $ignore = '') - { - if (array_key_exists('params', $array) && is_array($array['params'])) - { - $registry = new JRegistry; - $registry->loadArray($array['params']); - $array['params'] = $registry->toString(); - } + public function bind($array, $ignore = '') + { + if (array_key_exists('params', $array) && is_array($array['params'])) { + $registry = new JRegistry; + $registry->loadArray($array['params']); + $array['params'] = $registry->toString(); + } - return parent::bind($array, $ignore); - } + return parent::bind($array, $ignore); + } } diff --git a/component/admin/tables/zipcode.php b/component/admin/tables/zipcode.php index 49dbba3c489..15f3a09d46b 100644 --- a/component/admin/tables/zipcode.php +++ b/component/admin/tables/zipcode.php @@ -18,53 +18,46 @@ */ class RedshopTableZipcode extends RedshopTable { - /** - * The table name without prefix. - * - * @var string - */ - protected $_tableName = 'redshop_zipcode'; - - /** - * The table key column - * - * @var string - */ - protected $_tableKey = 'id'; - - public $id = null; - - public $state_code = null; - - public $city_name = null; - - public $zipcode = null; - - public $country_code = null; - - /** - * Check zipcode - * - * @return boolean - */ - public function docheck() - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('id') - ->from($db->qn("#__redshop_zipcode")) - ->where($db->qn('zipcode') . ' = ' . $db->q((int) $this->zipcode)) - ->where($db->qn('id') . ' != ' . $db->q((int) $this->id)) - ->where($db->qn('country_code') . ' = ' . $db->q((string) $this->country_code)); - - $xid = intval($db->setQuery($query)->loadResult()); - - if ($xid) - { - return false; - } - - return parent::doCheck(); - } + public $id = null; + public $state_code = null; + public $city_name = null; + public $zipcode = null; + public $country_code = null; + /** + * The table name without prefix. + * + * @var string + */ + protected $_tableName = 'redshop_zipcode'; + /** + * The table key column + * + * @var string + */ + protected $_tableKey = 'id'; + + /** + * Check zipcode + * + * @return boolean + */ + public function docheck() + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('id') + ->from($db->qn("#__redshop_zipcode")) + ->where($db->qn('zipcode') . ' = ' . $db->q((int)$this->zipcode)) + ->where($db->qn('id') . ' != ' . $db->q((int)$this->id)) + ->where($db->qn('country_code') . ' = ' . $db->q((string)$this->country_code)); + + $xid = intval($db->setQuery($query)->loadResult()); + + if ($xid) { + return false; + } + + return parent::doCheck(); + } } diff --git a/component/admin/updates/1.3.3.1.php b/component/admin/updates/1.3.3.1.php index e69423f94f6..eb741b59f8a 100644 --- a/component/admin/updates/1.3.3.1.php +++ b/component/admin/updates/1.3.3.1.php @@ -18,46 +18,44 @@ */ class RedshopUpdate1331 extends RedshopInstallUpdate { - /** - * Method to update schema table if necessary. - * - * @return void - * - * @since 1.3.3.1 - */ - public function updateDatabaseSchema() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('extension_id')) - ->from($db->qn('#__extensions')) - ->where($db->qn('element') . ' = ' . $db->quote('com_redshop')) - ->where($db->qn('type') . ' = ' . $db->quote('component')); - $componentId = $db->setQuery($query)->loadResult(); + /** + * Method to update schema table if necessary. + * + * @return void + * + * @since 1.3.3.1 + */ + public function updateDatabaseSchema() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('extension_id')) + ->from($db->qn('#__extensions')) + ->where($db->qn('element') . ' = ' . $db->quote('com_redshop')) + ->where($db->qn('type') . ' = ' . $db->quote('component')); + $componentId = $db->setQuery($query)->loadResult(); - // Skip if there are no redshop install - if (!$componentId) - { - return; - } + // Skip if there are no redshop install + if (!$componentId) { + return; + } - $query->clear() - ->select($db->qn('version_id')) - ->from($db->qn('#__schemas')) - ->where($db->qn('extension_id') . ' = ' . $componentId); - $result = $db->setQuery($query)->loadResult(); + $query->clear() + ->select($db->qn('version_id')) + ->from($db->qn('#__schemas')) + ->where($db->qn('extension_id') . ' = ' . $componentId); + $result = $db->setQuery($query)->loadResult(); - // Skip if there are already schema - if ($result) - { - return; - } + // Skip if there are already schema + if ($result) { + return; + } - $query->clear() - ->insert($db->qn('#__schemas')) - ->columns($db->qn(array('extension_id', 'version_id'))) - ->values($componentId . ',' . $db->quote('1.1.10')); + $query->clear() + ->insert($db->qn('#__schemas')) + ->columns($db->qn(array('extension_id', 'version_id'))) + ->values($componentId . ',' . $db->quote('1.1.10')); - $db->setQuery($query)->execute(); - } + $db->setQuery($query)->execute(); + } } diff --git a/component/admin/updates/1.6.0.php b/component/admin/updates/1.6.0.php index e170c6baf02..07325bbfdd5 100644 --- a/component/admin/updates/1.6.0.php +++ b/component/admin/updates/1.6.0.php @@ -18,88 +18,88 @@ */ class RedshopUpdate160 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 1.6.0 - */ - protected function getOldFiles() - { - return array( - JPATH_SITE . '/components/com_redshop/assets/download/product/.htaccess', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/navigator_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/product_detail/tmpl/default_product_dropdown.php', - JPATH_SITE . '/components/com_redshop/views/category/tmpl/searchletter.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/container.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/container_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/customprint.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/delivery.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/order_container.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/payment.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/payment_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/product_container.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/subinstall.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/container.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/container_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/order_container.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/payment.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/payment_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/product_container.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/container_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/payment_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/accessmanager/tmpl/noaccess.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/order/tmpl/multiprint_order.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/order/tmpl/previewlog.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/stockroom_detail/tmpl/default_product.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/assets/js/select_sort.js', - JPATH_ADMINISTRATOR . '/components/com_redshop/assets/js/related.js', - JPATH_ADMINISTRATOR . '/components/com_redshop/assets/js/container_search.js', - JPATH_ADMINISTRATOR . '/components/com_redshop/assets/js/mootools.js', - JPATH_ADMINISTRATOR . '/components/com_redshop/assets/images/redshop_white.png', - JPATH_ADMINISTRATOR . '/components/com_redshop/assets/images/j_arrow.png', - JPATH_ADMINISTRATOR . '/components/com_redshop/assets/images/j_arrow_down.png', - JPATH_ADMINISTRATOR . '/components/com_redshop/assets/images/ui-icons_222222_256x240.png', - JPATH_ADMINISTRATOR . '/components/com_redshop/assets/images/ui-icons_228ef1_256x240.png', - JPATH_SITE . '/components/com_redshop/controllers/password.php', - JPATH_SITE . '/components/com_redshop/controllers/price_filter.php', - JPATH_SITE . '/components/com_redshop/helpers/class.img2thumb.php', - JPATH_SITE . '/components/com_redshop/helpers/graph.php', - JPATH_SITE . '/components/com_redshop/helpers/pagination.php', - JPATH_SITE . '/components/com_redshop/helpers/thumb.php', - JPATH_SITE . '/components/com_redshop/models/password.php', - JPATH_SITE . '/components/com_redshop/views/price_filter/view.html.php', - JPATH_SITE . '/components/com_redshop/views/product/tmpl/default_askquestion.php', - JPATH_LIBRARIES . '/redshop/form/fields/rstext.php' - ); - } + /** + * Return list of old files for clean + * + * @return array + * + * @since 1.6.0 + */ + protected function getOldFiles() + { + return array( + JPATH_SITE . '/components/com_redshop/assets/download/product/.htaccess', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/navigator_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/product_detail/tmpl/default_product_dropdown.php', + JPATH_SITE . '/components/com_redshop/views/category/tmpl/searchletter.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/container.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/container_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/customprint.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/delivery.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/order_container.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/payment.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/payment_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/product_container.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/subinstall.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/container.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/container_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/order_container.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/payment.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/payment_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/product_container.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/container_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/payment_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/accessmanager/tmpl/noaccess.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/order/tmpl/multiprint_order.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/order/tmpl/previewlog.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/stockroom_detail/tmpl/default_product.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/assets/js/select_sort.js', + JPATH_ADMINISTRATOR . '/components/com_redshop/assets/js/related.js', + JPATH_ADMINISTRATOR . '/components/com_redshop/assets/js/container_search.js', + JPATH_ADMINISTRATOR . '/components/com_redshop/assets/js/mootools.js', + JPATH_ADMINISTRATOR . '/components/com_redshop/assets/images/redshop_white.png', + JPATH_ADMINISTRATOR . '/components/com_redshop/assets/images/j_arrow.png', + JPATH_ADMINISTRATOR . '/components/com_redshop/assets/images/j_arrow_down.png', + JPATH_ADMINISTRATOR . '/components/com_redshop/assets/images/ui-icons_222222_256x240.png', + JPATH_ADMINISTRATOR . '/components/com_redshop/assets/images/ui-icons_228ef1_256x240.png', + JPATH_SITE . '/components/com_redshop/controllers/password.php', + JPATH_SITE . '/components/com_redshop/controllers/price_filter.php', + JPATH_SITE . '/components/com_redshop/helpers/class.img2thumb.php', + JPATH_SITE . '/components/com_redshop/helpers/graph.php', + JPATH_SITE . '/components/com_redshop/helpers/pagination.php', + JPATH_SITE . '/components/com_redshop/helpers/thumb.php', + JPATH_SITE . '/components/com_redshop/models/password.php', + JPATH_SITE . '/components/com_redshop/views/price_filter/view.html.php', + JPATH_SITE . '/components/com_redshop/views/product/tmpl/default_askquestion.php', + JPATH_LIBRARIES . '/redshop/form/fields/rstext.php' + ); + } - /** - * Return list of old folders for clean - * - * @return array - * - * @since 1.6.0 - */ - protected function getOldFolders() - { - return array( - JPATH_SITE . '/components/com_redshop/assets/js', - JPATH_SITE . '/components/com_redshop/assets/css', - JPATH_SITE . '/components/com_redshop/helpers/fonts', - JPATH_SITE . '/components/com_redshop/helpers/tcpdf', - JPATH_SITE . '/components/com_redshop/views/epayrelay', - JPATH_SITE . '/components/com_redshop/views/password', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/adapters', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/container', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/container_detail', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/customprint', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/delivery', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/payment', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/payment_detail', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/product_container', - JPATH_ADMINISTRATOR . '/components/com_redshop/layouts/system' - ); - } + /** + * Return list of old folders for clean + * + * @return array + * + * @since 1.6.0 + */ + protected function getOldFolders() + { + return array( + JPATH_SITE . '/components/com_redshop/assets/js', + JPATH_SITE . '/components/com_redshop/assets/css', + JPATH_SITE . '/components/com_redshop/helpers/fonts', + JPATH_SITE . '/components/com_redshop/helpers/tcpdf', + JPATH_SITE . '/components/com_redshop/views/epayrelay', + JPATH_SITE . '/components/com_redshop/views/password', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/adapters', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/container', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/container_detail', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/customprint', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/delivery', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/payment', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/payment_detail', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/product_container', + JPATH_ADMINISTRATOR . '/components/com_redshop/layouts/system' + ); + } } diff --git a/component/admin/updates/2.0.0.2.php b/component/admin/updates/2.0.0.2.php index 0830d3776ef..04cd7878c44 100644 --- a/component/admin/updates/2.0.0.2.php +++ b/component/admin/updates/2.0.0.2.php @@ -18,64 +18,64 @@ */ class RedshopUpdate2002 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.0.0.2 - */ - protected function getOldFiles() - { - return array( - JPATH_SITE . '/components/com_redshop/helpers/helper.php', - JPATH_SITE . '/components/com_redshop/helpers/currency.php', - JPATH_SITE . '/components/com_redshop/helpers/product.php', - JPATH_SITE . '/components/com_redshop/helpers/cart.php', - JPATH_SITE . '/components/com_redshop/helpers/user.php', - JPATH_SITE . '/components/com_redshop/views/search/tmpl/default.xml', - JPATH_SITE . '/components/com_redshop/helpers/extra_field.php', - JPATH_SITE . '/components/com_redshop/helpers/google_analytics.php', - JPATH_SITE . '/components/com_redshop/helpers/googleanalytics.php', - JPATH_SITE . '/components/com_redshop/helpers/zip.php', - JPATH_SITE . '/components/com_redshop/helpers/cron.php', - JPATH_SITE . '/components/com_redshop/helpers/redshop.js.php', - JPATH_SITE . '/components/com_redshop/helpers/zipfile.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/answer.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/answer_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/answer.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/answer_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/access_level.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/category.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/configuration.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/images.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/mail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/media.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/order.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/quotation.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/stockroom.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/template.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/update.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/shopper.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/xmlcron.php', - JPATH_LIBRARIES . '/redshop/form/fields/stockroom.php' - ); - } + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.0.0.2 + */ + protected function getOldFiles() + { + return array( + JPATH_SITE . '/components/com_redshop/helpers/helper.php', + JPATH_SITE . '/components/com_redshop/helpers/currency.php', + JPATH_SITE . '/components/com_redshop/helpers/product.php', + JPATH_SITE . '/components/com_redshop/helpers/cart.php', + JPATH_SITE . '/components/com_redshop/helpers/user.php', + JPATH_SITE . '/components/com_redshop/views/search/tmpl/default.xml', + JPATH_SITE . '/components/com_redshop/helpers/extra_field.php', + JPATH_SITE . '/components/com_redshop/helpers/google_analytics.php', + JPATH_SITE . '/components/com_redshop/helpers/googleanalytics.php', + JPATH_SITE . '/components/com_redshop/helpers/zip.php', + JPATH_SITE . '/components/com_redshop/helpers/cron.php', + JPATH_SITE . '/components/com_redshop/helpers/redshop.js.php', + JPATH_SITE . '/components/com_redshop/helpers/zipfile.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/answer.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/answer_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/answer.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/answer_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/access_level.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/category.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/configuration.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/images.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/mail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/media.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/order.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/quotation.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/stockroom.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/template.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/update.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/shopper.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/xmlcron.php', + JPATH_LIBRARIES . '/redshop/form/fields/stockroom.php' + ); + } - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.0.0.2 - */ - protected function getOldFolders() - { - return array( - JPATH_LIBRARIES . '/redshop/config', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/answer', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/answer_detail', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/barcode' - ); - } + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.0.0.2 + */ + protected function getOldFolders() + { + return array( + JPATH_LIBRARIES . '/redshop/config', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/answer', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/answer_detail', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/barcode' + ); + } } diff --git a/component/admin/updates/2.0.0.5.php b/component/admin/updates/2.0.0.5.php index 9a083e732fd..adec89c8301 100644 --- a/component/admin/updates/2.0.0.5.php +++ b/component/admin/updates/2.0.0.5.php @@ -18,34 +18,34 @@ */ class RedshopUpdate2005 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.0.0.5 - */ - protected function getOldFiles() - { - return array( - JPATH_ADMINISTRATOR . '/component/admin/controllers/question_detail.php', - JPATH_ADMINISTRATOR . '/component/admin/models/question_detail.php', - JPATH_ADMINISTRATOR . '/component/admin/tables/question_detail.php', - JPATH_ADMINISTRATOR . '/component/admin/views/question/tmpl/default.php' - ); - } + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.0.0.5 + */ + protected function getOldFiles() + { + return array( + JPATH_ADMINISTRATOR . '/component/admin/controllers/question_detail.php', + JPATH_ADMINISTRATOR . '/component/admin/models/question_detail.php', + JPATH_ADMINISTRATOR . '/component/admin/tables/question_detail.php', + JPATH_ADMINISTRATOR . '/component/admin/views/question/tmpl/default.php' + ); + } - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.0.0.5 - */ - protected function getOldFolders() - { - return array( - JPATH_ADMINISTRATOR . '/component/admin/views/question_detail' - ); - } + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.0.0.5 + */ + protected function getOldFolders() + { + return array( + JPATH_ADMINISTRATOR . '/component/admin/views/question_detail' + ); + } } diff --git a/component/admin/updates/2.0.10.php b/component/admin/updates/2.0.10.php index 6e1de757748..2ace83761b8 100644 --- a/component/admin/updates/2.0.10.php +++ b/component/admin/updates/2.0.10.php @@ -18,36 +18,36 @@ */ class RedshopUpdate2010 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.0.10 - */ - protected function getOldFiles() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/discount_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/discount_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/discount_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/discount/tmpl/product.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/mass_discount/tmpl/product.php', - JPATH_LIBRARIES . '/redshop/entity/product_discount.php' - ); - } + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.0.10 + */ + protected function getOldFiles() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/discount_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/discount_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/discount_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/discount/tmpl/product.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/mass_discount/tmpl/product.php', + JPATH_LIBRARIES . '/redshop/entity/product_discount.php' + ); + } - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.0.10 - */ - protected function getOldFolders() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/views/discount_detail' - ); - } + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.0.10 + */ + protected function getOldFolders() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/views/discount_detail' + ); + } } diff --git a/component/admin/updates/2.0.11.php b/component/admin/updates/2.0.11.php index b425c97b880..c9e21f7d57a 100644 --- a/component/admin/updates/2.0.11.php +++ b/component/admin/updates/2.0.11.php @@ -18,34 +18,34 @@ */ class RedshopUpdate2011 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.0.11 - */ - protected function getOldFiles() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/currency_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/currency_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/currency_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/currency/tmpl/default.php' - ); - } + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.0.11 + */ + protected function getOldFiles() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/currency_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/currency_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/currency_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/currency/tmpl/default.php' + ); + } - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.0.11 - */ - protected function getOldFolders() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/views/currency_detail' - ); - } + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.0.11 + */ + protected function getOldFolders() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/views/currency_detail' + ); + } } diff --git a/component/admin/updates/2.0.12.php b/component/admin/updates/2.0.12.php index b065a77fa7c..a9d99421fa6 100644 --- a/component/admin/updates/2.0.12.php +++ b/component/admin/updates/2.0.12.php @@ -18,36 +18,36 @@ */ class RedshopUpdate2012 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.0.11 - */ - protected function getOldFiles() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/textlibrary.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/textlibrary_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/textlibrary.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/textlibrary_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/textlibrary_detail.php' - ); - } + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.0.11 + */ + protected function getOldFiles() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/textlibrary.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/textlibrary_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/textlibrary.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/textlibrary_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/textlibrary_detail.php' + ); + } - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.0.11 - */ - protected function getOldFolders() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/views/textlibrary', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/textlibrary_detail' - ); - } + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.0.11 + */ + protected function getOldFolders() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/views/textlibrary', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/textlibrary_detail' + ); + } } diff --git a/component/admin/updates/2.0.13.php b/component/admin/updates/2.0.13.php index b6139c93ee7..4b05aad6898 100644 --- a/component/admin/updates/2.0.13.php +++ b/component/admin/updates/2.0.13.php @@ -18,85 +18,78 @@ */ class RedshopUpdate2013 extends RedshopInstallUpdate { - /** - * Method for migrate manufacturer images. - * - * @return void - * @throws Exception - * - * @since 2.0.13 - */ - public function migrateManufacturerImages() - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_media')) - ->where($db->qn('media_section') . ' = ' . $db->quote('manufacturer')) - ->order($db->qn('section_id')); - - $medias = $db->setQuery($query)->loadObjectList(); - - if (empty($medias)) - { - return; - } - - $newBasePath = REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer'; - $oldBasePath = REDSHOP_FRONT_IMAGES_RELPATH . 'manufacturer'; - - foreach ($medias as $media) - { - /** @var RedshopTableMedia $table */ - $table = RedshopTable::getAdminInstance('Media', array('ignore_request' => true), 'com_redshop'); - - $table->bind((array) $media); - - // In case this media don't have media file. Delete this. - if (empty($table->media_name)) - { - $table->delete(); - - continue; - } - - // Prepare target folder. - $path = $newBasePath . '/' . $table->section_id; - - if (!JFolder::exists($path)) - { - JFolder::create($path); - } - - // Copy index.html to this folder. - if (!JFile::exists($path . '/index.html')) - { - JFile::copy(REDSHOP_MEDIA_IMAGE_RELPATH . 'index.html', $path . '/index.html'); - } - - // Check old image exist. - $oldImagePath = $oldBasePath . '/' . $table->media_name; - - if (!JFile::exists($oldImagePath)) - { - continue; - } - - // Generate new image using MD5 - $newFileName = md5(basename($table->media_name)) . '.' . JFile::getExt($table->media_name); - - if (!JFile::copy($oldImagePath, $path . '/' . $newFileName)) - { - continue; - } - - // Update media data with new file name. - $table->media_name = $newFileName; - $table->store(); - } - - // Remove old folders - JFolder::delete($oldBasePath); - } + /** + * Method for migrate manufacturer images. + * + * @return void + * @throws Exception + * + * @since 2.0.13 + */ + public function migrateManufacturerImages() + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_media')) + ->where($db->qn('media_section') . ' = ' . $db->quote('manufacturer')) + ->order($db->qn('section_id')); + + $medias = $db->setQuery($query)->loadObjectList(); + + if (empty($medias)) { + return; + } + + $newBasePath = REDSHOP_MEDIA_IMAGE_RELPATH . 'manufacturer'; + $oldBasePath = REDSHOP_FRONT_IMAGES_RELPATH . 'manufacturer'; + + foreach ($medias as $media) { + /** @var RedshopTableMedia $table */ + $table = RedshopTable::getAdminInstance('Media', array('ignore_request' => true), 'com_redshop'); + + $table->bind((array)$media); + + // In case this media don't have media file. Delete this. + if (empty($table->media_name)) { + $table->delete(); + + continue; + } + + // Prepare target folder. + $path = $newBasePath . '/' . $table->section_id; + + if (!JFolder::exists($path)) { + JFolder::create($path); + } + + // Copy index.html to this folder. + if (!JFile::exists($path . '/index.html')) { + JFile::copy(REDSHOP_MEDIA_IMAGE_RELPATH . 'index.html', $path . '/index.html'); + } + + // Check old image exist. + $oldImagePath = $oldBasePath . '/' . $table->media_name; + + if (!JFile::exists($oldImagePath)) { + continue; + } + + // Generate new image using MD5 + $newFileName = md5(basename($table->media_name)) . '.' . JFile::getExt($table->media_name); + + if (!JFile::copy($oldImagePath, $path . '/' . $newFileName)) { + continue; + } + + // Update media data with new file name. + $table->media_name = $newFileName; + $table->store(); + } + + // Remove old folders + JFolder::delete($oldBasePath); + } } diff --git a/component/admin/updates/2.0.14.php b/component/admin/updates/2.0.14.php index cf8dffbcdc0..0b403eba708 100644 --- a/component/admin/updates/2.0.14.php +++ b/component/admin/updates/2.0.14.php @@ -18,125 +18,120 @@ */ class RedshopUpdate2014 extends RedshopInstallUpdate { - /** - * Method for migrate category images. - * - * @return void - * - * @since 2.0.14 - */ - public function migrateCategoryImages() - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->qn(array('id', 'name', 'category_full_image', 'category_back_full_image'))) - ->from($db->qn('#__redshop_category')) - ->where( - '(' - . $db->qn('category_full_image') . ' IS NOT NULL OR ' . $db->qn('category_full_image') . ' <> ' . $db->quote('') - . ') OR (' - . $db->qn('category_back_full_image') . ' IS NOT NULL OR ' . $db->qn('category_back_full_image') . ' <> ' . $db->quote('') - . ')' - ) - ->order($db->qn('lft')); - - $medias = $db->setQuery($query)->loadObjectList(); - - if (empty($medias)) - { - return; - } - - $newBasePath = REDSHOP_MEDIA_IMAGE_RELPATH . 'category'; - $oldBasePath = REDSHOP_FRONT_IMAGES_RELPATH . 'category'; - - foreach ($medias as $media) - { - // Prepare target folder. - $path = $newBasePath . '/' . $media->id; - - if (!JFolder::exists($path)) - { - JFolder::create($path); - } - - // Copy index.html to this folder. - if (!JFile::exists($path . '/index.html')) - { - JFile::copy(REDSHOP_MEDIA_IMAGE_RELPATH . 'index.html', $path . '/index.html'); - } - - if (!empty($media->category_full_image)) - { - $this->storeMedia($media, $media->category_full_image, 'full', $oldBasePath, $newBasePath); - } - - if (!empty($media->category_full_image)) - { - $this->storeMedia($media, $media->category_back_full_image, 'back', $oldBasePath, $newBasePath); - } - } - - // Remove old folders - JFolder::delete($oldBasePath); - } - - /** - * Method for store media - * - * @param object $category Category data - * @param string $fileName File name - * @param string $scope Scope of media. - * @param string $oldBasePath Scope of media. - * @param string $newBasePath Scope of media. - * - * @return void - * - * @since 2.0.14 - */ - private function storeMedia($category, $fileName, $scope, $oldBasePath, $newBasePath) - { - /** @var RedshopTableMedia $table */ - $table = RedshopTable::getAdminInstance('Media', array('ignore_request' => true), 'com_redshop'); - - // Generate new image using MD5 - $newFileName = md5(basename($fileName)) . '.' . JFile::getExt($fileName); - - if (!$table->load( - array( - 'media_name' => $fileName, - 'media_section' => 'category', - 'section_id' => $category->id, - 'media_type' => 'images' - ) - )) - { - $table->section_id = $category->id; - $table->media_section = 'category'; - $table->media_type = 'images'; - } - - $table->media_alternate_text = $category->name; - $table->published = 1; - $table->ordering = 0; - $table->scope = $scope; - - // Check old image exist. - $oldImagePath = $oldBasePath . '/' . $fileName; - - if (!JFile::exists($oldImagePath)) - { - return; - } - - if (!JFile::copy($oldImagePath, $newBasePath . '/' . $category->id . '/' . $newFileName)) - { - return; - } - - // Update media data with new file name. - $table->media_name = $newFileName; - $table->store(); - } + /** + * Method for migrate category images. + * + * @return void + * + * @since 2.0.14 + */ + public function migrateCategoryImages() + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->qn(array('id', 'name', 'category_full_image', 'category_back_full_image'))) + ->from($db->qn('#__redshop_category')) + ->where( + '(' + . $db->qn('category_full_image') . ' IS NOT NULL OR ' . $db->qn( + 'category_full_image' + ) . ' <> ' . $db->quote('') + . ') OR (' + . $db->qn('category_back_full_image') . ' IS NOT NULL OR ' . $db->qn( + 'category_back_full_image' + ) . ' <> ' . $db->quote('') + . ')' + ) + ->order($db->qn('lft')); + + $medias = $db->setQuery($query)->loadObjectList(); + + if (empty($medias)) { + return; + } + + $newBasePath = REDSHOP_MEDIA_IMAGE_RELPATH . 'category'; + $oldBasePath = REDSHOP_FRONT_IMAGES_RELPATH . 'category'; + + foreach ($medias as $media) { + // Prepare target folder. + $path = $newBasePath . '/' . $media->id; + + if (!JFolder::exists($path)) { + JFolder::create($path); + } + + // Copy index.html to this folder. + if (!JFile::exists($path . '/index.html')) { + JFile::copy(REDSHOP_MEDIA_IMAGE_RELPATH . 'index.html', $path . '/index.html'); + } + + if (!empty($media->category_full_image)) { + $this->storeMedia($media, $media->category_full_image, 'full', $oldBasePath, $newBasePath); + } + + if (!empty($media->category_full_image)) { + $this->storeMedia($media, $media->category_back_full_image, 'back', $oldBasePath, $newBasePath); + } + } + + // Remove old folders + JFolder::delete($oldBasePath); + } + + /** + * Method for store media + * + * @param object $category Category data + * @param string $fileName File name + * @param string $scope Scope of media. + * @param string $oldBasePath Scope of media. + * @param string $newBasePath Scope of media. + * + * @return void + * + * @since 2.0.14 + */ + private function storeMedia($category, $fileName, $scope, $oldBasePath, $newBasePath) + { + /** @var RedshopTableMedia $table */ + $table = RedshopTable::getAdminInstance('Media', array('ignore_request' => true), 'com_redshop'); + + // Generate new image using MD5 + $newFileName = md5(basename($fileName)) . '.' . JFile::getExt($fileName); + + if (!$table->load( + array( + 'media_name' => $fileName, + 'media_section' => 'category', + 'section_id' => $category->id, + 'media_type' => 'images' + ) + )) { + $table->section_id = $category->id; + $table->media_section = 'category'; + $table->media_type = 'images'; + } + + $table->media_alternate_text = $category->name; + $table->published = 1; + $table->ordering = 0; + $table->scope = $scope; + + // Check old image exist. + $oldImagePath = $oldBasePath . '/' . $fileName; + + if (!JFile::exists($oldImagePath)) { + return; + } + + if (!JFile::copy($oldImagePath, $newBasePath . '/' . $category->id . '/' . $newFileName)) { + return; + } + + // Update media data with new file name. + $table->media_name = $newFileName; + $table->store(); + } } diff --git a/component/admin/updates/2.0.15.php b/component/admin/updates/2.0.15.php index 754c4c3f6fa..3f34d1c9074 100644 --- a/component/admin/updates/2.0.15.php +++ b/component/admin/updates/2.0.15.php @@ -18,34 +18,34 @@ */ class RedshopUpdate2015 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.0.15 - */ - protected function getOldFiles() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/manufacturer_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/manufacturer_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/manufacturer_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/manufacturer/tmpl/default.php' - ); - } + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.0.15 + */ + protected function getOldFiles() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/manufacturer_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/manufacturer_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/manufacturer_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/manufacturer/tmpl/default.php' + ); + } - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.0.15 - */ - protected function getOldFolders() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/views/manufacturer_detail' - ); - } + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.0.15 + */ + protected function getOldFolders() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/views/manufacturer_detail' + ); + } } diff --git a/component/admin/updates/2.0.3.php b/component/admin/updates/2.0.3.php index e0f4cc1492c..27d38a15531 100644 --- a/component/admin/updates/2.0.3.php +++ b/component/admin/updates/2.0.3.php @@ -20,494 +20,455 @@ */ class RedshopUpdate203 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.0.3 - */ - protected function getOldFiles() - { - return array( - JPATH_ADMINISTRATOR . '/component/admin/controllers/supplier_detail.php', - JPATH_ADMINISTRATOR . '/component/admin/controllers/tax.php', - JPATH_ADMINISTRATOR . '/component/admin/controllers/tax_detail.php', - JPATH_ADMINISTRATOR . '/component/admin/controllers/mass_discount_detail.php', - JPATH_ADMINISTRATOR . '/component/admin/models/supplier_detail.php', - JPATH_ADMINISTRATOR . '/component/admin/models/mass_discount_detail.php', - JPATH_ADMINISTRATOR . '/component/admin/models/tax.php', - JPATH_ADMINISTRATOR . '/component/admin/models/tax_detail.php', - JPATH_ADMINISTRATOR . '/component/admin/tables/supplier_detail.php', - JPATH_ADMINISTRATOR . '/component/admin/tables/mass_discount_detail.php', - JPATH_ADMINISTRATOR . '/component/admin/tables/tax_detail.php', - JPATH_ADMINISTRATOR . '/component/admin/views/supplier/tmpl/default.php', - JPATH_ADMINISTRATOR . '/component/admin/views/mass_discount/tmpl/default.php', - JPATH_SITE . '/media/com_redshop/css/media.css', - JPATH_SITE . '/media/com_redshop/css/media-uncompressed.css', - JPATH_SITE . '/media/com_redshop/js/media.js', - JPATH_SITE . '/media/com_redshop/js/media-uncompressed.js', - JPATH_ADMINISTRATOR . '/component/admin/views/order_detail/view.tcpdf.php', - JPATH_LIBRARIES . '/redshop/helper/tcpdf.php' - ); - } - - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.0.3 - */ - protected function getOldFolders() - { - return array( - JPATH_ADMINISTRATOR . '/component/admin/views/supplier_detail', - JPATH_ADMINISTRATOR . '/component/admin/views/tax', - JPATH_ADMINISTRATOR . '/component/admin/views/mass_discount_detail', - JPATH_ADMINISTRATOR . '/component/admin/views/tax_detail' - ); - } - - /** - * Method for update override template when update. - * - * @return void - * - * @since 2.0.4 - */ - public static function updateOverrideTemplate() - { - $dir = JPATH_SITE . '/templates/'; - $codeDir = JPATH_SITE . '/code/'; - $files = JFolder::folders($dir); - $templates = array(); - $adminHelpers = array(); - $adminTemplateHelpers = array(); - - if (JFolder::exists($codeDir)) - { - $codeFiles = JFolder::folders($codeDir); - - foreach ($codeFiles as $key => $value) - { - if (JFolder::exists($codeDir . 'administrator/components')) - { - $templates[$codeDir . 'administrator/components'] = JFolder::folders($codeDir . 'administrator/components'); - } - - if (JFolder::exists($codeDir . 'administrator')) - { - $templates[$codeDir . 'administrator'] = JFolder::folders($codeDir . 'administrator'); - } - - if (JFolder::exists($codeDir . 'components')) - { - $templates[$codeDir . 'components'] = JFolder::folders($codeDir . 'components'); - } - - if (JFolder::exists($codeDir)) - { - $templates[$codeDir] = JFolder::folders($codeDir); - } - - if (JFolder::exists($codeDir . 'com_redshop/helpers')) - { - $adminHelpers[$codeDir . 'com_redshop/helpers'] = JFolder::files($codeDir . 'com_redshop/helpers'); - } - } - } - - foreach ($files as $key => $value) - { - if (!JFile::exists($dir . $value)) - { - $templates[$dir . $value] = JFolder::folders($dir . $value); - } - } - - $override = array(); - $jsOverride = array(); - - self::getOverrideFromTemplates($templates, $override, $jsOverride, $adminTemplateHelpers); - - $overrideFiles = self::getOverrideFiles($override); - - $app = JFactory::getApplication(); - $data = Redshop::getConfig()->toArray(); - $temp = $app->getUserState('com_redshop.config.global.data'); - - if (!empty($temp)) - { - $data = array_merge($data, $temp); - } - - $data['BACKWARD_COMPATIBLE_PHP'] = 0; - $data['BACKWARD_COMPATIBLE_JS'] = 0; - $config = Redshop::getConfig(); - - if (!empty($overrideFiles)) - { - self::replaceCode($overrideFiles); - - // Check site used MVC && Templates Override - $data['BACKWARD_COMPATIBLE_PHP'] = 1; - } - - if (!empty($jsOverride)) - { - // Check site used JS Override - $data['BACKWARD_COMPATIBLE_JS'] = 1; - } - - $app->setUserState('com_redshop.config.global.data', $data); - $data = new Registry($data); - $config->save($data); - - self::moveAdminHelper($adminHelpers, $codeDir); - self::moveAdminTemplateHelper($adminTemplateHelpers); - } - - /** - * Method for get override files - * - * @param array $override Override - * - * @return array - * - * @since 2.0.3 - */ - private static function getOverrideFiles($override) - { - if (empty($override)) - { - return array(); - } - - $overrideFolders = array(); - $overrideLayoutFolders = array(); - $overrideLayoutFiles = array(); - $overrideFiles = array(); - - foreach ($override as $key => $value) - { - foreach ($value as $name) - { - if ($name === 'layouts') - { - $overrideLayoutFolders[$key . '/' . $name] = JFolder::folders($key . '/' . $name); - } - elseif (!JFile::exists($key . '/' . $name) && ($name === 'com_redshop' || strpos($name, 'mod_redshop') !== false)) - { - // Read all files and folders in parent folder - $overrideFolders[$key . '/' . $name] = array_diff(scandir($key . '/' . $name), array('.', '..')); - } - } - } - - foreach ($overrideFolders as $key => $value) - { - foreach ($value as $name) - { - $target = !JFile::exists($key . '/' . $name) ? $key . '/' . $name : $key; - $overrideFiles[$target] = JFolder::files($target); - } - } - - foreach ($overrideLayoutFolders as $key => $value) - { - foreach ($value as $name) - { - if ($name !== 'com_redshop' || JFile::exists($key . '/' . $name)) - { - continue; - } - - $overrideLayoutFiles[$key . '/' . $name] = JFolder::files($key . '/' . $name); - } - } - - if (!empty($overrideLayoutFiles)) - { - foreach ($overrideLayoutFiles as $key => $value) - { - foreach ($value as $name) - { - if (JFile::exists($key . '/' . $name)) - { - continue; - } - - $overrideFiles[$key . '/' . $name] = JFolder::files($key . '/' . $name); - } - } - } - - return $overrideFiles; - } - - /** - * Method for replace helper override. - * - * @param array $overrideFiles Override Files - * - * @return void - * @since 2.0.3 - */ - private static function replaceCode($overrideFiles) - { - if (empty($overrideFiles)) - { - return; - } - - $replaceString = array( - 'new quotationHelper()' => 'quotationHelper::getInstance()', - 'new order_functions()' => 'order_functions::getInstance()', - 'new Redconfiguration()' => 'Redconfiguration::getInstance()', - 'new Redconfiguration' => 'Redconfiguration::getInstance()', - 'new Redtemplate()' => 'Redtemplate::getInstance()', - 'new Redtemplate' => 'Redtemplate::getInstance()', - 'new extra_field()' => 'extra_field::getInstance()', - 'new rsstockroomhelper()' => 'rsstockroomhelper::getInstance()', - 'new rsstockroomhelper' => 'rsstockroomhelper::getInstance()', - 'new shipping()' => 'shipping::getInstance()', - 'new CurrencyHelper()' => 'CurrencyHelper::getInstance()', - 'new economic()' => 'economic::getInstance()', - 'new rsUserhelper()' => 'rsUserHelper::getInstance()', - 'new rsUserhelper' => 'rsUserHelper::getInstance()', - 'GoogleAnalytics' => 'RedshopHelperGoogleanalytics', - 'new quotationHelper' => 'quotationHelper::getInstance()', - 'new order_functions' => 'order_functions::getInstance()', - 'new extra_field' => 'extra_field::getInstance()', - 'new shipping' => 'shipping::getInstance()', - 'new CurrencyHelper' => 'CurrencyHelper::getInstance()', - 'new economic' => 'economic::getInstance()', - 'RedshopConfig::scriptDeclaration();' => '', - '$redConfiguration' => '$Redconfiguration', - 'require_once JPATH_SITE . \'/components/com_redshop/helpers/redshop.js.php\'' => '', - ); - - foreach ($overrideFiles as $path => $files) - { - foreach ($files as $file) - { - $content = file_get_contents($path . '/' . $file); - - foreach ($replaceString as $old => $new) - { - if (strpos($content, $old) === false) - { - continue; - } - - $content = str_replace($old, $new, $content); - JFile::write($path . '/' . $file, $content); - } - } - } - } - - /** - * Method for replace helper override. - * - * @param array $adminHelpers Admin helpers - * @param string $codeDir Code directory - * - * @return void - * @since 2.0.3 - */ - private static function moveAdminHelper($adminHelpers, $codeDir) - { - if (empty($adminHelpers)) - { - return; - } - - $replaceAdminHelper = array( - 'adminorder.php' => 'order_functions.php', - 'admincategory.php' => 'product_category.php', - 'adminquotation.php' => 'quotationhelper.php', - 'adminaccess_level.php' => 'redaccesslevel.php', - 'adminconfiguration.php' => 'redconfiguration.php', - 'adminmedia.php' => 'redmediahelper.php', - 'adminimages.php' => 'redshophelperimages.php', - 'adminmail.php' => 'redshopmail.php', - 'adminupdate.php' => 'redshopupdate.php', - 'admintemplate.php' => 'redtemplate.php', - 'adminstockroom.php' => 'rsstockroom.php', - 'adminshopper.php' => 'shoppergroup.php' - ); - - $replaceSiteHelper = array( - 'currency.php' => 'currencyhelper.php', - 'extra_field.php' => 'extrafield.php', - 'google_analytics.php' => 'googleanalytics.php', - ); - - foreach ($adminHelpers as $path => $files) - { - foreach ($replaceAdminHelper as $old => $new) - { - if (!JFile::exists($path . '/' . $old)) - { - continue; - } - - if (!JFolder::exists($codeDir . 'administrator/components/com_redshop/helpers')) - { - JFolder::create($codeDir . 'administrator/components/com_redshop/helpers'); - } - - JFile::move($codeDir . 'com_redshop/helpers/' . $old, $codeDir . 'administrator/components/com_redshop/helpers/' . $new); - } - - foreach ($replaceSiteHelper as $old => $new) - { - if (!JFile::exists($path . '/' . $old)) - { - continue; - } - - if (!JFolder::exists($codeDir . 'components/com_redshop/helpers')) - { - JFolder::create($codeDir . 'components/com_redshop/helpers'); - } - - JFile::move($codeDir . 'com_redshop/helpers/' . $old, $codeDir . 'components/com_redshop/helpers/' . $new); - } - } - } - - /** - * Method for replace helper override. - * - * @param array $adminTemplateHelpers Admin template helpers - * - * @return void - * @since 2.0.3 - */ - private static function moveAdminTemplateHelper($adminTemplateHelpers) - { - if (empty($adminTemplateHelpers)) - { - return; - } - - $replaceAdminHelper = array( - 'adminorder.php' => 'order_functions.php', - 'admincategory.php' => 'product_category.php', - 'adminquotation.php' => 'quotationhelper.php', - 'adminaccess_level.php' => 'redaccesslevel.php', - 'adminconfiguration.php' => 'redconfiguration.php', - 'adminmedia.php' => 'redmediahelper.php', - 'adminimages.php' => 'redshophelperimages.php', - 'adminmail.php' => 'redshopmail.php', - 'adminupdate.php' => 'redshopupdate.php', - 'admintemplate.php' => 'redtemplate.php', - 'adminstockroom.php' => 'rsstockroom.php', - 'adminshopper.php' => 'shoppergroup.php' - ); - - $replaceSiteHelper = array( - 'currency.php' => 'currencyhelper.php', - 'extra_field.php' => 'extrafield.php', - 'google_analytics.php' => 'googleanalytics.php', - 'product.php' => 'producthelper.php', - ); - - foreach ($adminTemplateHelpers as $path => $files) - { - foreach ($replaceAdminHelper as $old => $new) - { - if (!JFile::exists($path . '/code/com_redshop/helpers/' . $old)) - { - continue; - } - - if (!JFolder::exists($path . '/code/administrator/components/com_redshop/helpers')) - { - JFolder::create($path . '/code/administrator/components/com_redshop/helpers'); - } - - JFile::move($path . '/code/com_redshop/helpers/' . $old, $path . '/code/administrator/components/com_redshop/helpers/' . $new); - } - - foreach ($replaceSiteHelper as $old => $new) - { - if (!JFile::exists($path . '/code/com_redshop/helpers/' . $old)) - { - continue; - } - - if (!JFolder::exists($path . '/code/components/com_redshop/helpers')) - { - JFolder::create($path . '/code/components/com_redshop/helpers'); - } - - JFile::move($path . '/code/com_redshop/helpers/' . $old, $path . '/code/components/com_redshop/helpers/' . $new); - } - } - } - - /** - * Get override template from templates. - * - * @param array $templates Templates - * @param array $override Overrides - * @param array $jsOverride Javascript overrides - * @param array $adminTemplateHelpers Admin template overrides. - * - * - * @return void - * @since 2.0.3 - */ - private static function getOverrideFromTemplates($templates, &$override, &$jsOverride, &$adminTemplateHelpers) - { - if (empty($templates)) - { - return; - } - - foreach ($templates as $key => $value) - { - foreach ($value as $name) - { - if (JFile::exists($key . '/' . $name)) - { - continue; - } - - if (JFolder::exists($key . '/com_redshop')) - { - $override[$key . '/com_redshop'] = JFolder::folders($key . '/com_redshop'); - } - - if (JFolder::exists($key . '/html')) - { - $override[$key . '/html'] = JFolder::folders($key . '/html'); - } - - if (JFolder::exists($key . '/js/com_redshop')) - { - $jsOverride[$key . '/js/com_redshop'] = JFolder::files($key . '/js/com_redshop'); - } - - if (JFolder::exists($key . '/code/com_redshop')) - { - $override[$key . '/code/com_redshop'] = JFolder::folders($key . '/code/com_redshop'); - } - - if (JFolder::exists($key . '/code/components/com_redshop')) - { - $override[$key . '/code/components/com_redshop'] = JFolder::folders($key . '/code/components/com_redshop'); - } - - if (JFolder::exists($key . '/code/com_redshop/helpers')) - { - $adminTemplateHelpers[$key] = JFolder::files($key . '/code/com_redshop/helpers'); - } - } - } - } + /** + * Method for update override template when update. + * + * @return void + * + * @since 2.0.4 + */ + public static function updateOverrideTemplate() + { + $dir = JPATH_SITE . '/templates/'; + $codeDir = JPATH_SITE . '/code/'; + $files = JFolder::folders($dir); + $templates = array(); + $adminHelpers = array(); + $adminTemplateHelpers = array(); + + if (JFolder::exists($codeDir)) { + $codeFiles = JFolder::folders($codeDir); + + foreach ($codeFiles as $key => $value) { + if (JFolder::exists($codeDir . 'administrator/components')) { + $templates[$codeDir . 'administrator/components'] = JFolder::folders( + $codeDir . 'administrator/components' + ); + } + + if (JFolder::exists($codeDir . 'administrator')) { + $templates[$codeDir . 'administrator'] = JFolder::folders($codeDir . 'administrator'); + } + + if (JFolder::exists($codeDir . 'components')) { + $templates[$codeDir . 'components'] = JFolder::folders($codeDir . 'components'); + } + + if (JFolder::exists($codeDir)) { + $templates[$codeDir] = JFolder::folders($codeDir); + } + + if (JFolder::exists($codeDir . 'com_redshop/helpers')) { + $adminHelpers[$codeDir . 'com_redshop/helpers'] = JFolder::files($codeDir . 'com_redshop/helpers'); + } + } + } + + foreach ($files as $key => $value) { + if (!JFile::exists($dir . $value)) { + $templates[$dir . $value] = JFolder::folders($dir . $value); + } + } + + $override = array(); + $jsOverride = array(); + + self::getOverrideFromTemplates($templates, $override, $jsOverride, $adminTemplateHelpers); + + $overrideFiles = self::getOverrideFiles($override); + + $app = JFactory::getApplication(); + $data = Redshop::getConfig()->toArray(); + $temp = $app->getUserState('com_redshop.config.global.data'); + + if (!empty($temp)) { + $data = array_merge($data, $temp); + } + + $data['BACKWARD_COMPATIBLE_PHP'] = 0; + $data['BACKWARD_COMPATIBLE_JS'] = 0; + $config = Redshop::getConfig(); + + if (!empty($overrideFiles)) { + self::replaceCode($overrideFiles); + + // Check site used MVC && Templates Override + $data['BACKWARD_COMPATIBLE_PHP'] = 1; + } + + if (!empty($jsOverride)) { + // Check site used JS Override + $data['BACKWARD_COMPATIBLE_JS'] = 1; + } + + $app->setUserState('com_redshop.config.global.data', $data); + $data = new Registry($data); + $config->save($data); + + self::moveAdminHelper($adminHelpers, $codeDir); + self::moveAdminTemplateHelper($adminTemplateHelpers); + } + + /** + * Get override template from templates. + * + * @param array $templates Templates + * @param array $override Overrides + * @param array $jsOverride Javascript overrides + * @param array $adminTemplateHelpers Admin template overrides. + * + * + * @return void + * @since 2.0.3 + */ + private static function getOverrideFromTemplates($templates, &$override, &$jsOverride, &$adminTemplateHelpers) + { + if (empty($templates)) { + return; + } + + foreach ($templates as $key => $value) { + foreach ($value as $name) { + if (JFile::exists($key . '/' . $name)) { + continue; + } + + if (JFolder::exists($key . '/com_redshop')) { + $override[$key . '/com_redshop'] = JFolder::folders($key . '/com_redshop'); + } + + if (JFolder::exists($key . '/html')) { + $override[$key . '/html'] = JFolder::folders($key . '/html'); + } + + if (JFolder::exists($key . '/js/com_redshop')) { + $jsOverride[$key . '/js/com_redshop'] = JFolder::files($key . '/js/com_redshop'); + } + + if (JFolder::exists($key . '/code/com_redshop')) { + $override[$key . '/code/com_redshop'] = JFolder::folders($key . '/code/com_redshop'); + } + + if (JFolder::exists($key . '/code/components/com_redshop')) { + $override[$key . '/code/components/com_redshop'] = JFolder::folders( + $key . '/code/components/com_redshop' + ); + } + + if (JFolder::exists($key . '/code/com_redshop/helpers')) { + $adminTemplateHelpers[$key] = JFolder::files($key . '/code/com_redshop/helpers'); + } + } + } + } + + /** + * Method for get override files + * + * @param array $override Override + * + * @return array + * + * @since 2.0.3 + */ + private static function getOverrideFiles($override) + { + if (empty($override)) { + return array(); + } + + $overrideFolders = array(); + $overrideLayoutFolders = array(); + $overrideLayoutFiles = array(); + $overrideFiles = array(); + + foreach ($override as $key => $value) { + foreach ($value as $name) { + if ($name === 'layouts') { + $overrideLayoutFolders[$key . '/' . $name] = JFolder::folders($key . '/' . $name); + } elseif (!JFile::exists($key . '/' . $name) && ($name === 'com_redshop' || strpos( + $name, + 'mod_redshop' + ) !== false)) { + // Read all files and folders in parent folder + $overrideFolders[$key . '/' . $name] = array_diff(scandir($key . '/' . $name), array('.', '..')); + } + } + } + + foreach ($overrideFolders as $key => $value) { + foreach ($value as $name) { + $target = !JFile::exists($key . '/' . $name) ? $key . '/' . $name : $key; + $overrideFiles[$target] = JFolder::files($target); + } + } + + foreach ($overrideLayoutFolders as $key => $value) { + foreach ($value as $name) { + if ($name !== 'com_redshop' || JFile::exists($key . '/' . $name)) { + continue; + } + + $overrideLayoutFiles[$key . '/' . $name] = JFolder::files($key . '/' . $name); + } + } + + if (!empty($overrideLayoutFiles)) { + foreach ($overrideLayoutFiles as $key => $value) { + foreach ($value as $name) { + if (JFile::exists($key . '/' . $name)) { + continue; + } + + $overrideFiles[$key . '/' . $name] = JFolder::files($key . '/' . $name); + } + } + } + + return $overrideFiles; + } + + /** + * Method for replace helper override. + * + * @param array $overrideFiles Override Files + * + * @return void + * @since 2.0.3 + */ + private static function replaceCode($overrideFiles) + { + if (empty($overrideFiles)) { + return; + } + + $replaceString = array( + 'new quotationHelper()' => 'quotationHelper::getInstance()', + 'new order_functions()' => 'order_functions::getInstance()', + 'new Redconfiguration()' => 'Redconfiguration::getInstance()', + 'new Redconfiguration' => 'Redconfiguration::getInstance()', + 'new Redtemplate()' => 'Redtemplate::getInstance()', + 'new Redtemplate' => 'Redtemplate::getInstance()', + 'new extra_field()' => 'extra_field::getInstance()', + 'new rsstockroomhelper()' => 'rsstockroomhelper::getInstance()', + 'new rsstockroomhelper' => 'rsstockroomhelper::getInstance()', + 'new shipping()' => 'shipping::getInstance()', + 'new CurrencyHelper()' => 'CurrencyHelper::getInstance()', + 'new economic()' => 'economic::getInstance()', + 'new rsUserhelper()' => 'rsUserHelper::getInstance()', + 'new rsUserhelper' => 'rsUserHelper::getInstance()', + 'GoogleAnalytics' => 'RedshopHelperGoogleanalytics', + 'new quotationHelper' => 'quotationHelper::getInstance()', + 'new order_functions' => 'order_functions::getInstance()', + 'new extra_field' => 'extra_field::getInstance()', + 'new shipping' => 'shipping::getInstance()', + 'new CurrencyHelper' => 'CurrencyHelper::getInstance()', + 'new economic' => 'economic::getInstance()', + 'RedshopConfig::scriptDeclaration();' => '', + '$redConfiguration' => '$Redconfiguration', + 'require_once JPATH_SITE . \'/components/com_redshop/helpers/redshop.js.php\'' => '', + ); + + foreach ($overrideFiles as $path => $files) { + foreach ($files as $file) { + $content = file_get_contents($path . '/' . $file); + + foreach ($replaceString as $old => $new) { + if (strpos($content, $old) === false) { + continue; + } + + $content = str_replace($old, $new, $content); + JFile::write($path . '/' . $file, $content); + } + } + } + } + + /** + * Method for replace helper override. + * + * @param array $adminHelpers Admin helpers + * @param string $codeDir Code directory + * + * @return void + * @since 2.0.3 + */ + private static function moveAdminHelper($adminHelpers, $codeDir) + { + if (empty($adminHelpers)) { + return; + } + + $replaceAdminHelper = array( + 'adminorder.php' => 'order_functions.php', + 'admincategory.php' => 'product_category.php', + 'adminquotation.php' => 'quotationhelper.php', + 'adminaccess_level.php' => 'redaccesslevel.php', + 'adminconfiguration.php' => 'redconfiguration.php', + 'adminmedia.php' => 'redmediahelper.php', + 'adminimages.php' => 'redshophelperimages.php', + 'adminmail.php' => 'redshopmail.php', + 'adminupdate.php' => 'redshopupdate.php', + 'admintemplate.php' => 'redtemplate.php', + 'adminstockroom.php' => 'rsstockroom.php', + 'adminshopper.php' => 'shoppergroup.php' + ); + + $replaceSiteHelper = array( + 'currency.php' => 'currencyhelper.php', + 'extra_field.php' => 'extrafield.php', + 'google_analytics.php' => 'googleanalytics.php', + ); + + foreach ($adminHelpers as $path => $files) { + foreach ($replaceAdminHelper as $old => $new) { + if (!JFile::exists($path . '/' . $old)) { + continue; + } + + if (!JFolder::exists($codeDir . 'administrator/components/com_redshop/helpers')) { + JFolder::create($codeDir . 'administrator/components/com_redshop/helpers'); + } + + JFile::move( + $codeDir . 'com_redshop/helpers/' . $old, + $codeDir . 'administrator/components/com_redshop/helpers/' . $new + ); + } + + foreach ($replaceSiteHelper as $old => $new) { + if (!JFile::exists($path . '/' . $old)) { + continue; + } + + if (!JFolder::exists($codeDir . 'components/com_redshop/helpers')) { + JFolder::create($codeDir . 'components/com_redshop/helpers'); + } + + JFile::move( + $codeDir . 'com_redshop/helpers/' . $old, + $codeDir . 'components/com_redshop/helpers/' . $new + ); + } + } + } + + /** + * Method for replace helper override. + * + * @param array $adminTemplateHelpers Admin template helpers + * + * @return void + * @since 2.0.3 + */ + private static function moveAdminTemplateHelper($adminTemplateHelpers) + { + if (empty($adminTemplateHelpers)) { + return; + } + + $replaceAdminHelper = array( + 'adminorder.php' => 'order_functions.php', + 'admincategory.php' => 'product_category.php', + 'adminquotation.php' => 'quotationhelper.php', + 'adminaccess_level.php' => 'redaccesslevel.php', + 'adminconfiguration.php' => 'redconfiguration.php', + 'adminmedia.php' => 'redmediahelper.php', + 'adminimages.php' => 'redshophelperimages.php', + 'adminmail.php' => 'redshopmail.php', + 'adminupdate.php' => 'redshopupdate.php', + 'admintemplate.php' => 'redtemplate.php', + 'adminstockroom.php' => 'rsstockroom.php', + 'adminshopper.php' => 'shoppergroup.php' + ); + + $replaceSiteHelper = array( + 'currency.php' => 'currencyhelper.php', + 'extra_field.php' => 'extrafield.php', + 'google_analytics.php' => 'googleanalytics.php', + 'product.php' => 'producthelper.php', + ); + + foreach ($adminTemplateHelpers as $path => $files) { + foreach ($replaceAdminHelper as $old => $new) { + if (!JFile::exists($path . '/code/com_redshop/helpers/' . $old)) { + continue; + } + + if (!JFolder::exists($path . '/code/administrator/components/com_redshop/helpers')) { + JFolder::create($path . '/code/administrator/components/com_redshop/helpers'); + } + + JFile::move( + $path . '/code/com_redshop/helpers/' . $old, + $path . '/code/administrator/components/com_redshop/helpers/' . $new + ); + } + + foreach ($replaceSiteHelper as $old => $new) { + if (!JFile::exists($path . '/code/com_redshop/helpers/' . $old)) { + continue; + } + + if (!JFolder::exists($path . '/code/components/com_redshop/helpers')) { + JFolder::create($path . '/code/components/com_redshop/helpers'); + } + + JFile::move( + $path . '/code/com_redshop/helpers/' . $old, + $path . '/code/components/com_redshop/helpers/' . $new + ); + } + } + } + + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.0.3 + */ + protected function getOldFiles() + { + return array( + JPATH_ADMINISTRATOR . '/component/admin/controllers/supplier_detail.php', + JPATH_ADMINISTRATOR . '/component/admin/controllers/tax.php', + JPATH_ADMINISTRATOR . '/component/admin/controllers/tax_detail.php', + JPATH_ADMINISTRATOR . '/component/admin/controllers/mass_discount_detail.php', + JPATH_ADMINISTRATOR . '/component/admin/models/supplier_detail.php', + JPATH_ADMINISTRATOR . '/component/admin/models/mass_discount_detail.php', + JPATH_ADMINISTRATOR . '/component/admin/models/tax.php', + JPATH_ADMINISTRATOR . '/component/admin/models/tax_detail.php', + JPATH_ADMINISTRATOR . '/component/admin/tables/supplier_detail.php', + JPATH_ADMINISTRATOR . '/component/admin/tables/mass_discount_detail.php', + JPATH_ADMINISTRATOR . '/component/admin/tables/tax_detail.php', + JPATH_ADMINISTRATOR . '/component/admin/views/supplier/tmpl/default.php', + JPATH_ADMINISTRATOR . '/component/admin/views/mass_discount/tmpl/default.php', + JPATH_SITE . '/media/com_redshop/css/media.css', + JPATH_SITE . '/media/com_redshop/css/media-uncompressed.css', + JPATH_SITE . '/media/com_redshop/js/media.js', + JPATH_SITE . '/media/com_redshop/js/media-uncompressed.js', + JPATH_ADMINISTRATOR . '/component/admin/views/order_detail/view.tcpdf.php', + JPATH_LIBRARIES . '/redshop/helper/tcpdf.php' + ); + } + + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.0.3 + */ + protected function getOldFolders() + { + return array( + JPATH_ADMINISTRATOR . '/component/admin/views/supplier_detail', + JPATH_ADMINISTRATOR . '/component/admin/views/tax', + JPATH_ADMINISTRATOR . '/component/admin/views/mass_discount_detail', + JPATH_ADMINISTRATOR . '/component/admin/views/tax_detail' + ); + } } diff --git a/component/admin/updates/2.0.4.php b/component/admin/updates/2.0.4.php index 71366377a1f..212c1d7e323 100644 --- a/component/admin/updates/2.0.4.php +++ b/component/admin/updates/2.0.4.php @@ -18,147 +18,144 @@ */ class RedshopUpdate204 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.0.4 - */ - protected function getOldFiles() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/update.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/redshopupdate.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/update.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/tax_group_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/tax_group_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/tax_group_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/tax_group/tmpl/default.php', - JPATH_SITE . '/libraries/redshop/install/database.php' - ); - } - - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.0.4 - */ - protected function getOldFolders() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/views/update', - JPATH_ADMINISTRATOR . '/components/com_redshop/extras/sh404sef/sef_ext', - JPATH_ADMINISTRATOR . '/components/com_redshop/extras/sh404sef/meta_ext', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/barcode', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/tax_group_detail' - ); - } - - /** - * Change images file name - * - * @param array $files List files in image folder - * @param string $path Path to folder - * - * @return void - */ - protected function changeImageFileName(&$files, &$path) - { - if (empty($files)) - { - return; - } - - foreach ($files as $file) - { - $fileName = str_replace(array('%20', ' '), '-', $file); - - JFile::move($path . $file, $path . $fileName); - } - } - - /** - * Method for rename image files name to correct format. - * - * @return void - * - * @since 2.0.4 - */ - public function updateImageFileNames() - { - $db = JFactory::getDbo(); - - /** Update DB */ - $fields = array( - $db->qn('product_full_image') . ' = REPLACE(' . $db->qn('product_full_image') . ", '%20', '-')", - $db->qn('product_full_image') . ' = REPLACE(' . $db->qn('product_full_image') . ", ' ', '-')", - $db->qn('product_thumb_image') . ' = REPLACE(' . $db->qn('product_thumb_image') . ", '%20', '-')", - $db->qn('product_thumb_image') . ' = REPLACE(' . $db->qn('product_thumb_image') . ", ' ', '-')" - ); - - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_product')) - ->set($fields); - $db->setQuery($query)->execute(); - - /** Update Image Name */ - $files = JFolder::files(JPATH_SITE . '/components/com_redshop/assets/images/product/'); - $this->changeImageFileName($files, $path); - - $files = JFolder::files(JPATH_SITE . '/components/com_redshop/assets/images/product/thumb/'); - $this->changeImageFileName($files, $path); - } - - /** - * Method for update menu item id if necessary. - * - * @return void - * - * @since 2.0.4 - */ - public function updateMenuItem() - { - $db = JFactory::getDbo(); - - // For Blank component id in menu table-admin menu error solution - Get redSHOP extension id from the table - $query = $db->getQuery(true) - ->select('extension_id') - ->from($db->qn('#__extensions')) - ->where($db->qn('name') . ' LIKE ' . $db->quote('%redshop')) - ->where($db->qn('element') . ' = ' . $db->quote('com_redshop')) - ->where($db->qn('type') . ' = ' . $db->quote('component')); - - $extensionId = $db->setQuery($query)->loadResult(); - - // Check for component menu item entry - $query->clear() - ->select('id,component_id') - ->from($db->qn('#__menu')) - ->where($db->qn('menutype') . ' = ' . $db->quote('main')) - ->where($db->qn('path') . ' LIKE ' . $db->quote('%redshop')) - ->where($db->qn('type') . ' = ' . $db->quote('component')); - - $menuItem = $db->setQuery($query)->loadObject(); - - // If component Entry found and component_id is same as extension id - no need to update menu item - $isUpdate = ($menuItem && $menuItem->component_id == $extensionId) ? false : true; - - if (!$isUpdate) - { - return; - } - - $query->clear() - ->update($db->qn('#__menu')) - ->set($db->qn('component_id') . ' = ' . (int) $extensionId) - ->where($db->qn('menutype') . ' = ' . $db->quote('main')) - ->where($db->qn('path') . ' LIKE ' . $db->quote('%redshop')) - ->where($db->qn('type') . ' = ' . $db->quote('component')); - - // Set the query and execute the update. - $db->setQuery($query)->execute(); - } + /** + * Method for rename image files name to correct format. + * + * @return void + * + * @since 2.0.4 + */ + public function updateImageFileNames() + { + $db = JFactory::getDbo(); + + /** Update DB */ + $fields = array( + $db->qn('product_full_image') . ' = REPLACE(' . $db->qn('product_full_image') . ", '%20', '-')", + $db->qn('product_full_image') . ' = REPLACE(' . $db->qn('product_full_image') . ", ' ', '-')", + $db->qn('product_thumb_image') . ' = REPLACE(' . $db->qn('product_thumb_image') . ", '%20', '-')", + $db->qn('product_thumb_image') . ' = REPLACE(' . $db->qn('product_thumb_image') . ", ' ', '-')" + ); + + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_product')) + ->set($fields); + $db->setQuery($query)->execute(); + + /** Update Image Name */ + $files = JFolder::files(JPATH_SITE . '/components/com_redshop/assets/images/product/'); + $this->changeImageFileName($files, $path); + + $files = JFolder::files(JPATH_SITE . '/components/com_redshop/assets/images/product/thumb/'); + $this->changeImageFileName($files, $path); + } + + /** + * Change images file name + * + * @param array $files List files in image folder + * @param string $path Path to folder + * + * @return void + */ + protected function changeImageFileName(&$files, &$path) + { + if (empty($files)) { + return; + } + + foreach ($files as $file) { + $fileName = str_replace(array('%20', ' '), '-', $file); + + JFile::move($path . $file, $path . $fileName); + } + } + + /** + * Method for update menu item id if necessary. + * + * @return void + * + * @since 2.0.4 + */ + public function updateMenuItem() + { + $db = JFactory::getDbo(); + + // For Blank component id in menu table-admin menu error solution - Get redSHOP extension id from the table + $query = $db->getQuery(true) + ->select('extension_id') + ->from($db->qn('#__extensions')) + ->where($db->qn('name') . ' LIKE ' . $db->quote('%redshop')) + ->where($db->qn('element') . ' = ' . $db->quote('com_redshop')) + ->where($db->qn('type') . ' = ' . $db->quote('component')); + + $extensionId = $db->setQuery($query)->loadResult(); + + // Check for component menu item entry + $query->clear() + ->select('id,component_id') + ->from($db->qn('#__menu')) + ->where($db->qn('menutype') . ' = ' . $db->quote('main')) + ->where($db->qn('path') . ' LIKE ' . $db->quote('%redshop')) + ->where($db->qn('type') . ' = ' . $db->quote('component')); + + $menuItem = $db->setQuery($query)->loadObject(); + + // If component Entry found and component_id is same as extension id - no need to update menu item + $isUpdate = ($menuItem && $menuItem->component_id == $extensionId) ? false : true; + + if (!$isUpdate) { + return; + } + + $query->clear() + ->update($db->qn('#__menu')) + ->set($db->qn('component_id') . ' = ' . (int)$extensionId) + ->where($db->qn('menutype') . ' = ' . $db->quote('main')) + ->where($db->qn('path') . ' LIKE ' . $db->quote('%redshop')) + ->where($db->qn('type') . ' = ' . $db->quote('component')); + + // Set the query and execute the update. + $db->setQuery($query)->execute(); + } + + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.0.4 + */ + protected function getOldFiles() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/update.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/redshopupdate.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/update.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/tax_group_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/tax_group_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/tax_group_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/tax_group/tmpl/default.php', + JPATH_SITE . '/libraries/redshop/install/database.php' + ); + } + + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.0.4 + */ + protected function getOldFolders() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/views/update', + JPATH_ADMINISTRATOR . '/components/com_redshop/extras/sh404sef/sef_ext', + JPATH_ADMINISTRATOR . '/components/com_redshop/extras/sh404sef/meta_ext', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/barcode', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/tax_group_detail' + ); + } } diff --git a/component/admin/updates/2.0.6.php b/component/admin/updates/2.0.6.php index a1662f5124d..d23ca44fc1e 100644 --- a/component/admin/updates/2.0.6.php +++ b/component/admin/updates/2.0.6.php @@ -18,147 +18,147 @@ */ class RedshopUpdate206 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.0.6 - */ - protected function getOldFiles() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/accessmanager.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/accessmanager_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/redaccesslevel.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/thumbnail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/accessmanager.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/accessmanager_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/accessmanager_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/category_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/category_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/fields_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/fields_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/fields_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/configuration/tmpl/default_analytics.php' - ); - } - - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.0.6 - */ - protected function getOldFolders() - { - return array( - JPATH_LIBRARIES . '/redshop/economic', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/accessmanager', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/accessmanager_detail', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/category_detail', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/fields_detail' - ); - } - - /** - * Method to update new structure for Category - * - * @return void - * - * @since 2.0.6 - */ - public function updateCategory() - { - $db = JFactory::getDbo(); - $check = RedshopHelperCategory::getRootId(); - - if (!empty($check)) - { - return; - } - - $root = new stdClass; - $root->name = 'ROOT'; - $root->parent_id = 0; - $root->level = 0; - $root->lft = 0; - $root->rgt = 1; - $root->published = 1; - $db->insertObject('#__redshop_category', $root); - - $rootId = $db->insertid(); - - $query = $db->getQuery(true) - ->select('c.*') - ->select($db->qn('cx.category_parent_id', 'parent_id')) - ->from($db->qn('#__redshop_category', 'c')) - ->leftJoin($db->qn('#__redshop_category_xref', 'cx') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('cx.category_child_id')); - $categories = $db->setQuery($query)->loadObjectList(); - - foreach ($categories as $key => $category) - { - if ($category->name == 'ROOT') - { - continue; - } - - $parentId = ($category->parent_id == 0) ? $rootId : $category->parent_id; - $alias = JFilterOutput::stringUrlUnicodeSlug($category->name); - - $fields = array( - $db->qn('parent_id') . ' = ' . $db->q((int) $parentId), - $db->qn('alias') . ' = ' . $db->q($alias) - ); - - $conditions = array( - $db->qn('id') . ' = ' . $db->q((int) $category->id) - ); - - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_category')) - ->set($fields) - ->where($conditions); - - $db->setQuery($query)->execute(); - } - - if ($this->processRebuildCategory($rootId)) - { - $this->processDeleteCategoryXrefTable(); - } - } - - /** - * Method to update new structure for Category - * - * @param int $rootId Root ID - * - * @return mixed - * - * @since 2.0.6 - */ - protected function processRebuildCategory($rootId) - { - /** @var RedshopTableCategory $table */ - $table = RedshopTable::getInstance('Category', 'RedshopTable'); - - return $table->rebuild($rootId); - } - - /** - * Method to update new structure for Category - * - * @return mixed - * - * @since 2.0.6 - */ - protected function processDeleteCategoryXrefTable() - { - $db = JFactory::getDbo(); - - return $db->setQuery('DROP TABLE IF EXISTS ' . $db->qn('#__redshop_category_xref')) - ->execute(); - } + /** + * Method to update new structure for Category + * + * @return void + * + * @since 2.0.6 + */ + public function updateCategory() + { + $db = JFactory::getDbo(); + $check = RedshopHelperCategory::getRootId(); + + if (!empty($check)) { + return; + } + + $root = new stdClass; + $root->name = 'ROOT'; + $root->parent_id = 0; + $root->level = 0; + $root->lft = 0; + $root->rgt = 1; + $root->published = 1; + $db->insertObject('#__redshop_category', $root); + + $rootId = $db->insertid(); + + $query = $db->getQuery(true) + ->select('c.*') + ->select($db->qn('cx.category_parent_id', 'parent_id')) + ->from($db->qn('#__redshop_category', 'c')) + ->leftJoin( + $db->qn('#__redshop_category_xref', 'cx') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn( + 'cx.category_child_id' + ) + ); + $categories = $db->setQuery($query)->loadObjectList(); + + foreach ($categories as $key => $category) { + if ($category->name == 'ROOT') { + continue; + } + + $parentId = ($category->parent_id == 0) ? $rootId : $category->parent_id; + $alias = JFilterOutput::stringUrlUnicodeSlug($category->name); + + $fields = array( + $db->qn('parent_id') . ' = ' . $db->q((int)$parentId), + $db->qn('alias') . ' = ' . $db->q($alias) + ); + + $conditions = array( + $db->qn('id') . ' = ' . $db->q((int)$category->id) + ); + + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_category')) + ->set($fields) + ->where($conditions); + + $db->setQuery($query)->execute(); + } + + if ($this->processRebuildCategory($rootId)) { + $this->processDeleteCategoryXrefTable(); + } + } + + /** + * Method to update new structure for Category + * + * @param int $rootId Root ID + * + * @return mixed + * + * @since 2.0.6 + */ + protected function processRebuildCategory($rootId) + { + /** @var RedshopTableCategory $table */ + $table = RedshopTable::getInstance('Category', 'RedshopTable'); + + return $table->rebuild($rootId); + } + + /** + * Method to update new structure for Category + * + * @return mixed + * + * @since 2.0.6 + */ + protected function processDeleteCategoryXrefTable() + { + $db = JFactory::getDbo(); + + return $db->setQuery('DROP TABLE IF EXISTS ' . $db->qn('#__redshop_category_xref')) + ->execute(); + } + + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.0.6 + */ + protected function getOldFiles() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/accessmanager.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/accessmanager_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/redaccesslevel.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/thumbnail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/accessmanager.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/accessmanager_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/accessmanager_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/category_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/category_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/fields_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/fields_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/fields_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/configuration/tmpl/default_analytics.php' + ); + } + + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.0.6 + */ + protected function getOldFolders() + { + return array( + JPATH_LIBRARIES . '/redshop/economic', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/accessmanager', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/accessmanager_detail', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/category_detail', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/fields_detail' + ); + } } diff --git a/component/admin/updates/2.0.7.php b/component/admin/updates/2.0.7.php index 4bee460afc6..73669a318b5 100644 --- a/component/admin/updates/2.0.7.php +++ b/component/admin/updates/2.0.7.php @@ -18,122 +18,122 @@ */ class RedshopUpdate207 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.0.7 - */ - protected function getOldFiles() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/voucher_detail.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/views/voucher/tmpl/default.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/models/voucher_detail.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/controllers/voucher_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/mail_detail.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/views/mail/tmpl/default.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/models/mail_detail.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/controllers/mail_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/template_detail.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/views/template/tmpl/default.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/models/template_detail.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/controllers/template_detail.php', - JPATH_LIBRARIES . '/redshop/helper/route.php' - ); - } - - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.0.7 - */ - protected function getOldFolders() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/views/voucher_detail', - JPATH_SITE . '/components/com_redshop/layouts/tags', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/mail_detail', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/template_detail' - ); - } - - /** - * Method for migrate voucher data to new table - * - * @return void - * - * @since 2.0.7 - */ - public function migrateVoucher() - { - $db = JFactory::getDbo(); - - // Check table exist. - $result = $db->setQuery("SHOW TABLES LIKE " . $db->quote('#__redshop_product_voucher'))->loadResult(); - - if (empty($result)) - { - return; - } - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_product_voucher')) - ->order($db->qn('voucher_id')); - - $vouchers = $db->setQuery($query)->loadObjectList(); - - if (empty($vouchers)) - { - $this->dropOldTable(); - - return; - } - - $table = RedshopTable::getAdminInstance('Voucher'); - $table->setOption('skip.checkPrimary', true); - $table->setOption('skip.updateProducts', true); - - foreach ($vouchers as $voucher) - { - $data = (array) $voucher; - - $data['id'] = $data['voucher_id']; - $data['code'] = $data['voucher_code']; - $data['type'] = $data['voucher_type']; - $data['free_ship'] = $data['free_shipping']; - $data['start_date'] = !$data['start_date'] ? '0000-00-00 00:00:00' : JFactory::getDate($data['start_date'])->format('Y-m-d H:i:s'); - $data['end_date'] = !$data['end_date'] ? '0000-00-00 00:00:00' : JFactory::getDate($data['end_date'])->format('Y-m-d H:i:s'); - - unset($data['voucher_id']); - unset($data['voucher_code']); - unset($data['voucher_type']); - unset($data['free_shipping']); - - if (!$table->save($data)) - { - JFactory::getApplication()->enqueueMessage($table->getError(), 'error'); - } - } - - $this->dropOldTable(); - } - - /** - * Method for drop old `#__redshop_product_voucher` table. - * - * @return void - * - * @since 2.0.7 - */ - protected function dropOldTable() - { - $db = JFactory::getDbo(); - - $db->setQuery('DROP TABLE IF EXISTS ' . $db->qn('#__redshop_product_voucher'))->execute(); - } + /** + * Method for migrate voucher data to new table + * + * @return void + * + * @since 2.0.7 + */ + public function migrateVoucher() + { + $db = JFactory::getDbo(); + + // Check table exist. + $result = $db->setQuery("SHOW TABLES LIKE " . $db->quote('#__redshop_product_voucher'))->loadResult(); + + if (empty($result)) { + return; + } + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_product_voucher')) + ->order($db->qn('voucher_id')); + + $vouchers = $db->setQuery($query)->loadObjectList(); + + if (empty($vouchers)) { + $this->dropOldTable(); + + return; + } + + $table = RedshopTable::getAdminInstance('Voucher'); + $table->setOption('skip.checkPrimary', true); + $table->setOption('skip.updateProducts', true); + + foreach ($vouchers as $voucher) { + $data = (array)$voucher; + + $data['id'] = $data['voucher_id']; + $data['code'] = $data['voucher_code']; + $data['type'] = $data['voucher_type']; + $data['free_ship'] = $data['free_shipping']; + $data['start_date'] = !$data['start_date'] ? '0000-00-00 00:00:00' : JFactory::getDate( + $data['start_date'] + )->format('Y-m-d H:i:s'); + $data['end_date'] = !$data['end_date'] ? '0000-00-00 00:00:00' : JFactory::getDate( + $data['end_date'] + )->format('Y-m-d H:i:s'); + + unset($data['voucher_id']); + unset($data['voucher_code']); + unset($data['voucher_type']); + unset($data['free_shipping']); + + if (!$table->save($data)) { + JFactory::getApplication()->enqueueMessage($table->getError(), 'error'); + } + } + + $this->dropOldTable(); + } + + /** + * Method for drop old `#__redshop_product_voucher` table. + * + * @return void + * + * @since 2.0.7 + */ + protected function dropOldTable() + { + $db = JFactory::getDbo(); + + $db->setQuery('DROP TABLE IF EXISTS ' . $db->qn('#__redshop_product_voucher'))->execute(); + } + + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.0.7 + */ + protected function getOldFiles() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/voucher_detail.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/views/voucher/tmpl/default.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/models/voucher_detail.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/controllers/voucher_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/mail_detail.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/views/mail/tmpl/default.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/models/mail_detail.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/controllers/mail_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/template_detail.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/views/template/tmpl/default.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/models/template_detail.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/controllers/template_detail.php', + JPATH_LIBRARIES . '/redshop/helper/route.php' + ); + } + + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.0.7 + */ + protected function getOldFolders() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/views/voucher_detail', + JPATH_SITE . '/components/com_redshop/layouts/tags', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/mail_detail', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/template_detail' + ); + } } diff --git a/component/admin/updates/2.0.9.php b/component/admin/updates/2.0.9.php index 209cfb79eec..c7078867ea5 100644 --- a/component/admin/updates/2.0.9.php +++ b/component/admin/updates/2.0.9.php @@ -18,303 +18,292 @@ */ class RedshopUpdate209 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.0.9 - */ - protected function getOldFiles() - { - return array(); - } - - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.0.9 - */ - protected function getOldFolders() - { - return array( - JPATH_SITE . '/components/com_redshop/templates' - ); - } - - /** - * Method for migrate voucher data to new table - * - * @return void - * @throws Exception - * - * @since 2.0.9 - */ - public function migrateTemplateFiles() - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_template')) - ->order($db->qn('section')); - - $templates = $db->setQuery($query)->loadObjectList(); - - if (empty($templates)) - { - return; - } - - $templates = $this->migrateOldTemplate($templates); - - if (empty($templates)) - { - return; - } - - $this->migrateOverrideTemplate($templates); - } - - /** - * Template View selector - * - * @param array $templates Templates - * - * @return array List of template table which already migrate correct data. - * - * @since 2.0.9 - */ - protected function migrateOldTemplate($templates = array()) - { - $oldPaths = array(); - $tables = array(); - - // Copy old template files to new structure. - foreach ($templates as $template) - { - /** @var RedshopTableTemplate $table */ - $table = RedshopTable::getAdminInstance('Template', array('ignore_request' => true), 'com_redshop'); - $table->bind((array) $template); - - // Skip if template already migrate - if (!empty($template->file_name)) - { - $tables[] = $table; - - continue; - } - - $table->file_name = $table->generateTemplateFileName($table->id, $table->name); - - if (!$table->store()) - { - continue; - } - - $view = $this->getTemplateView($template->section); - $oldPaths[] = JPath::clean(JPATH_SITE . '/components/com_redshop/views/' . $view . '/tmpl/' . $template->section); - $sourceFile = JPATH_SITE . '/components/com_redshop/views/' . $view . '/tmpl/' . $template->section . '/' . $template->name . '.php'; - $sourceFile = JPath::clean($sourceFile); - - if (!JFile::exists($sourceFile)) - { - $sourceFile = JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $table->section . '/default.php'); - } - - $targetFile = JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $table->section . '/' . $table->file_name . '.php'); - - if (JFile::exists($sourceFile)) - { - if (JFile::exists($targetFile)) - { - JFile::delete($targetFile); - } - - JFile::copy($sourceFile, $targetFile); - } - - $tables[] = $table; - } - - // Delete old folders. - $oldPaths = array_unique($oldPaths); - - foreach ($oldPaths as $path) - { - if (JFolder::exists($path)) - { - JFolder::delete($path); - } - } - - return $tables; - } - - /** - * Template View selector - * - * @param array $templates Templates - * - * @return void - * @throws Exception - * - * @since 2.0.9 - */ - protected function migrateOverrideTemplate($templates = array()) - { - $joomlaTemplate = $this->getActiveSiteTemplate(); - - foreach ($templates as $template) - { - /** @var RedshopTableTemplate $template */ - $view = $this->getTemplateView($template->section); - $overrideFile = JPATH_SITE . '/templates/' . $joomlaTemplate . '/html/com_redshop/'; - - if ($template->section != 'categoryproduct') - { - $overrideFile .= $view . '/' . $template->section . '/' . $template->name . '.php'; - } - else - { - $overrideFile .= $template->section . '/' . $template->name . '.php'; - } - - $overrideFile = JPath::clean($overrideFile); - - if (!JFile::exists($overrideFile)) - { - continue; - } - - $target = JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $template->section . '/' . $template->file_name . '.php'); - - if (JFile::exists($target)) - { - JFile::delete($target); - } - - JFile::move($overrideFile, $target); - } - } - - /** - * Template View selector - * - * @param string $section Template section - * - * @return string Template Joomla view name - * - * @since 2.0.9 - */ - protected function getTemplateView($section) - { - $section = strtolower($section); - - switch ($section) - { - case 'product': - case 'related_product': - case 'product_sample': - case 'accessory_template': - case 'attribute_template': - case 'attributewithcart_template': - case 'review': - case 'wrapper_template': - case 'compare_product': - $view = "product"; - break; - - case 'categoryproduct': - case 'category': - case 'frontpage_category': - $view = "category"; - break; - - case 'catalog': - case 'catalog_sample': - $view = "catalog"; - break; - - case 'manufacturer': - case 'manufacturer_detail': - case 'manufacturer_products': - - $view = "manufacturers"; - break; - case 'cart': - case 'add_to_cart': - case 'ajax_cart_detail_box': - case 'ajax_cart_box': - case 'empty_cart': - $view = "cart"; - break; - - case 'account_template': - $view = "account"; - break; - - case 'private_billing_template': - case 'company_billing_template': - case 'billing_template': - case 'shipping_template': - $view = "registration"; - break; - - case 'wishlist_template': - case 'wishlist_mail_template': - $view = "wishlist"; - break; - - case 'newsletter': - case 'newsletter_product': - $view = "newsletter"; - break; - - case 'order_list': - case 'order_detail': - case 'order_receipt': - $view = "orders"; - break; - - case 'giftcard': - $view = "giftcard"; - break; - - case 'checkout': - case 'onestep_checkout': - $view = "checkout"; - break; - - case 'ask_question_template': - $view = "ask_question"; - break; - - default: - return ''; - } - - return $view; - } - - /** - * Method for get "default" template use on Front-end - * - * @return string - * - * @since 2.0.9 - */ - protected function getActiveSiteTemplate() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('template')) - ->from($db->qn('#__template_styles')) - ->where($db->qn('client_id') . ' = 0') - ->where($db->qn('home') . ' = 1'); - - return $db->setQuery($query)->loadResult(); - } + /** + * Method for migrate voucher data to new table + * + * @return void + * @throws Exception + * + * @since 2.0.9 + */ + public function migrateTemplateFiles() + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_template')) + ->order($db->qn('section')); + + $templates = $db->setQuery($query)->loadObjectList(); + + if (empty($templates)) { + return; + } + + $templates = $this->migrateOldTemplate($templates); + + if (empty($templates)) { + return; + } + + $this->migrateOverrideTemplate($templates); + } + + /** + * Template View selector + * + * @param array $templates Templates + * + * @return array List of template table which already migrate correct data. + * + * @since 2.0.9 + */ + protected function migrateOldTemplate($templates = array()) + { + $oldPaths = array(); + $tables = array(); + + // Copy old template files to new structure. + foreach ($templates as $template) { + /** @var RedshopTableTemplate $table */ + $table = RedshopTable::getAdminInstance('Template', array('ignore_request' => true), 'com_redshop'); + $table->bind((array)$template); + + // Skip if template already migrate + if (!empty($template->file_name)) { + $tables[] = $table; + + continue; + } + + $table->file_name = $table->generateTemplateFileName($table->id, $table->name); + + if (!$table->store()) { + continue; + } + + $view = $this->getTemplateView($template->section); + $oldPaths[] = JPath::clean( + JPATH_SITE . '/components/com_redshop/views/' . $view . '/tmpl/' . $template->section + ); + $sourceFile = JPATH_SITE . '/components/com_redshop/views/' . $view . '/tmpl/' . $template->section . '/' . $template->name . '.php'; + $sourceFile = JPath::clean($sourceFile); + + if (!JFile::exists($sourceFile)) { + $sourceFile = JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $table->section . '/default.php'); + } + + $targetFile = JPath::clean( + JPATH_REDSHOP_TEMPLATE . '/' . $table->section . '/' . $table->file_name . '.php' + ); + + if (JFile::exists($sourceFile)) { + if (JFile::exists($targetFile)) { + JFile::delete($targetFile); + } + + JFile::copy($sourceFile, $targetFile); + } + + $tables[] = $table; + } + + // Delete old folders. + $oldPaths = array_unique($oldPaths); + + foreach ($oldPaths as $path) { + if (JFolder::exists($path)) { + JFolder::delete($path); + } + } + + return $tables; + } + + /** + * Template View selector + * + * @param string $section Template section + * + * @return string Template Joomla view name + * + * @since 2.0.9 + */ + protected function getTemplateView($section) + { + $section = strtolower($section); + + switch ($section) { + case 'product': + case 'related_product': + case 'product_sample': + case 'accessory_template': + case 'attribute_template': + case 'attributewithcart_template': + case 'review': + case 'wrapper_template': + case 'compare_product': + $view = "product"; + break; + + case 'categoryproduct': + case 'category': + case 'frontpage_category': + $view = "category"; + break; + + case 'catalog': + case 'catalog_sample': + $view = "catalog"; + break; + + case 'manufacturer': + case 'manufacturer_detail': + case 'manufacturer_products': + + $view = "manufacturers"; + break; + case 'cart': + case 'add_to_cart': + case 'ajax_cart_detail_box': + case 'ajax_cart_box': + case 'empty_cart': + $view = "cart"; + break; + + case 'account_template': + $view = "account"; + break; + + case 'private_billing_template': + case 'company_billing_template': + case 'billing_template': + case 'shipping_template': + $view = "registration"; + break; + + case 'wishlist_template': + case 'wishlist_mail_template': + $view = "wishlist"; + break; + + case 'newsletter': + case 'newsletter_product': + $view = "newsletter"; + break; + + case 'order_list': + case 'order_detail': + case 'order_receipt': + $view = "orders"; + break; + + case 'giftcard': + $view = "giftcard"; + break; + + case 'checkout': + case 'onestep_checkout': + $view = "checkout"; + break; + + case 'ask_question_template': + $view = "ask_question"; + break; + + default: + return ''; + } + + return $view; + } + + /** + * Template View selector + * + * @param array $templates Templates + * + * @return void + * @throws Exception + * + * @since 2.0.9 + */ + protected function migrateOverrideTemplate($templates = array()) + { + $joomlaTemplate = $this->getActiveSiteTemplate(); + + foreach ($templates as $template) { + /** @var RedshopTableTemplate $template */ + $view = $this->getTemplateView($template->section); + $overrideFile = JPATH_SITE . '/templates/' . $joomlaTemplate . '/html/com_redshop/'; + + if ($template->section != 'categoryproduct') { + $overrideFile .= $view . '/' . $template->section . '/' . $template->name . '.php'; + } else { + $overrideFile .= $template->section . '/' . $template->name . '.php'; + } + + $overrideFile = JPath::clean($overrideFile); + + if (!JFile::exists($overrideFile)) { + continue; + } + + $target = JPath::clean( + JPATH_REDSHOP_TEMPLATE . '/' . $template->section . '/' . $template->file_name . '.php' + ); + + if (JFile::exists($target)) { + JFile::delete($target); + } + + JFile::move($overrideFile, $target); + } + } + + /** + * Method for get "default" template use on Front-end + * + * @return string + * + * @since 2.0.9 + */ + protected function getActiveSiteTemplate() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('template')) + ->from($db->qn('#__template_styles')) + ->where($db->qn('client_id') . ' = 0') + ->where($db->qn('home') . ' = 1'); + + return $db->setQuery($query)->loadResult(); + } + + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.0.9 + */ + protected function getOldFiles() + { + return array(); + } + + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.0.9 + */ + protected function getOldFolders() + { + return array( + JPATH_SITE . '/components/com_redshop/templates' + ); + } } diff --git a/component/admin/updates/2.1.0.php b/component/admin/updates/2.1.0.php index 414c79fa4b5..917ae9b1c06 100644 --- a/component/admin/updates/2.1.0.php +++ b/component/admin/updates/2.1.0.php @@ -18,117 +18,114 @@ */ class RedshopUpdate210 extends RedshopInstallUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.1.0 - */ - protected function getOldFiles() - { - return array( - // Old coupon files - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/coupon_detail.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/views/coupon/tmpl/default.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/models/coupon_detail.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/controllers/coupon_detail.php', - // Old shipping box files - JPATH_ADMINISTRATOR . '/component/com_redshop/controllers/shipping_box_detail.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/tables/shipping_box_detail.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/views/shipping_box/tmpl/default.php', - JPATH_ADMINISTRATOR . '/component/com_redshop/models/shipping_box_detail.php', - // Old address field files - JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/addressfields_listing.php', - JPATH_ADMINISTRATOR . '/components/com_redshop/models/addressfields_listing.php', - JPATH_LIBRARIES . '/redshop/src/Economic/Economic.php' - ); - } - - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.1.0 - */ - protected function getOldFolders() - { - return array( - JPATH_ADMINISTRATOR . '/components/com_redshop/views/addressfields_listing', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/coupon_detail', - JPATH_ADMINISTRATOR . '/components/com_redshop/views/shipping_box_detail', - JPATH_ADMINISTRATOR . '/components/com_redshop/assets/js', - JPATH_ADMINISTRATOR . '/components/com_redshop/assets/css', - JPATH_ADMINISTRATOR . '/components/com_redshop/assets/images' - ); - } - - /** - * Method for migrate voucher data to new table - * - * @return void - * - * @since 2.1.0 - * - * @throws Exception - */ - public function migrateCoupons() - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_coupons')) - ->order($db->qn('id')); - - $coupons = $db->setQuery($query)->loadObjectList(); - - if (empty($coupons)) - { - return; - } - - $nullDate = $db->getNullDate(); - - foreach ($coupons as $coupon) - { - /** @var RedshopTableCoupon $table */ - $table = RedshopTable::getAdminInstance('Coupon'); - - if (!$table->load($coupon->id)) - { - continue; - } - - $needUpdate = false; - - if ($table->start_date == $nullDate && !empty($coupon->start_date_old)) - { - $table->start_date = JFactory::getDate($coupon->start_date_old)->toSql(); - $needUpdate = true; - } - - if ($table->end_date == $nullDate && !empty($coupon->end_date_old)) - { - $table->end_date = JFactory::getDate($coupon->end_date_old)->toSql(); - $needUpdate = true; - } - - if (!$needUpdate) - { - continue; - } - - if (!$table->store()) - { - JFactory::getApplication()->enqueueMessage($table->getError(), 'error'); - } - } - - $query = 'CALL redSHOP_Column_Remove(' . $db->quote('#__redshop_coupons') . ',' . $db->quote('start_date_old') . ');'; - $db->setQuery($query)->execute(); - $query = 'CALL redSHOP_Column_Remove(' . $db->quote('#__redshop_coupons') . ',' . $db->quote('end_date_old') . ');'; - $db->setQuery($query)->execute(); - } + /** + * Method for migrate voucher data to new table + * + * @return void + * + * @throws Exception + * @since 2.1.0 + * + */ + public function migrateCoupons() + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_coupons')) + ->order($db->qn('id')); + + $coupons = $db->setQuery($query)->loadObjectList(); + + if (empty($coupons)) { + return; + } + + $nullDate = $db->getNullDate(); + + foreach ($coupons as $coupon) { + /** @var RedshopTableCoupon $table */ + $table = RedshopTable::getAdminInstance('Coupon'); + + if (!$table->load($coupon->id)) { + continue; + } + + $needUpdate = false; + + if ($table->start_date == $nullDate && !empty($coupon->start_date_old)) { + $table->start_date = JFactory::getDate($coupon->start_date_old)->toSql(); + $needUpdate = true; + } + + if ($table->end_date == $nullDate && !empty($coupon->end_date_old)) { + $table->end_date = JFactory::getDate($coupon->end_date_old)->toSql(); + $needUpdate = true; + } + + if (!$needUpdate) { + continue; + } + + if (!$table->store()) { + JFactory::getApplication()->enqueueMessage($table->getError(), 'error'); + } + } + + $query = 'CALL redSHOP_Column_Remove(' . $db->quote('#__redshop_coupons') . ',' . $db->quote( + 'start_date_old' + ) . ');'; + $db->setQuery($query)->execute(); + $query = 'CALL redSHOP_Column_Remove(' . $db->quote('#__redshop_coupons') . ',' . $db->quote( + 'end_date_old' + ) . ');'; + $db->setQuery($query)->execute(); + } + + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.1.0 + */ + protected function getOldFiles() + { + return array( + // Old coupon files + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/coupon_detail.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/views/coupon/tmpl/default.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/models/coupon_detail.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/controllers/coupon_detail.php', + // Old shipping box files + JPATH_ADMINISTRATOR . '/component/com_redshop/controllers/shipping_box_detail.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/tables/shipping_box_detail.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/views/shipping_box/tmpl/default.php', + JPATH_ADMINISTRATOR . '/component/com_redshop/models/shipping_box_detail.php', + // Old address field files + JPATH_ADMINISTRATOR . '/components/com_redshop/controllers/addressfields_listing.php', + JPATH_ADMINISTRATOR . '/components/com_redshop/models/addressfields_listing.php', + JPATH_LIBRARIES . '/redshop/src/Economic/Economic.php' + ); + } + + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.1.0 + */ + protected function getOldFolders() + { + return array( + JPATH_ADMINISTRATOR . '/components/com_redshop/views/addressfields_listing', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/coupon_detail', + JPATH_ADMINISTRATOR . '/components/com_redshop/views/shipping_box_detail', + JPATH_ADMINISTRATOR . '/components/com_redshop/assets/js', + JPATH_ADMINISTRATOR . '/components/com_redshop/assets/css', + JPATH_ADMINISTRATOR . '/components/com_redshop/assets/images' + ); + } } diff --git a/component/admin/updates/2.1.1.php b/component/admin/updates/2.1.1.php index 28f3d11c2ac..7ceddd23e36 100644 --- a/component/admin/updates/2.1.1.php +++ b/component/admin/updates/2.1.1.php @@ -10,6 +10,7 @@ defined('_JEXEC') or die; use Joomla\Registry\Registry; + /** * Update class * @@ -19,35 +20,33 @@ */ class RedshopUpdate211 extends RedshopInstallUpdate { - /** - * Method for fixing Calendar field not displaying properly when upgrade redshop - * (happen when the DEFAULT_DATEFORMAT of old version is not assigned a format) - * - * @return void - * - * @since 2.1.1 - * @throws Exception - */ - public function fixCalendarFormField() - { - $app = JFactory::getApplication(); - $currentConfig = Redshop::getConfig()->toArray(); + /** + * Method for fixing Calendar field not displaying properly when upgrade redshop + * (happen when the DEFAULT_DATEFORMAT of old version is not assigned a format) + * + * @return void + * + * @throws Exception + * @since 2.1.1 + */ + public function fixCalendarFormField() + { + $app = JFactory::getApplication(); + $currentConfig = Redshop::getConfig()->toArray(); - $temp = $app->getUserState('com_redshop.config.global.data'); + $temp = $app->getUserState('com_redshop.config.global.data'); - if (!empty($temp)) - { - $currentConfig = array_merge($currentConfig, $temp); - } + if (!empty($temp)) { + $currentConfig = array_merge($currentConfig, $temp); + } - if ($currentConfig['DEFAULT_DATEFORMAT'] === '0') - { - $currentConfig['DEFAULT_DATEFORMAT'] = 'Y-m-d'; - } + if ($currentConfig['DEFAULT_DATEFORMAT'] === '0') { + $currentConfig['DEFAULT_DATEFORMAT'] = 'Y-m-d'; + } - $config = Redshop::getConfig(); - $app->setUserState('com_redshop.config.global.data', $currentConfig); - $data = new Registry($currentConfig); - $config->save($data); - } + $config = Redshop::getConfig(); + $app->setUserState('com_redshop.config.global.data', $currentConfig); + $data = new Registry($currentConfig); + $config->save($data); + } } diff --git a/component/admin/updates/index.html b/component/admin/updates/index.html index 94906bce29b..af1d3c9d43e 100644 --- a/component/admin/updates/index.html +++ b/component/admin/updates/index.html @@ -1 +1,3 @@ - + + + diff --git a/component/admin/views/access/index.html b/component/admin/views/access/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/access/index.html +++ b/component/admin/views/access/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/access/tmpl/default.php b/component/admin/views/access/tmpl/default.php index ec0e920f422..5b7939782fa 100644 --- a/component/admin/views/access/tmpl/default.php +++ b/component/admin/views/access/tmpl/default.php @@ -1,4 +1,5 @@
    -

    -

    +

    +

    -
    - form->getInput('rules') ?> - - - form->getInput('title') ?> - form->getInput('id') ?> - + + form->getInput('rules') ?> + + + form->getInput('title') ?> + form->getInput('id') ?> +
    \ No newline at end of file diff --git a/component/admin/views/access/tmpl/index.html b/component/admin/views/access/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/access/tmpl/index.html +++ b/component/admin/views/access/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/access/view.html.php b/component/admin/views/access/view.html.php index caaa21bd1cc..4a52575231f 100644 --- a/component/admin/views/access/view.html.php +++ b/component/admin/views/access/view.html.php @@ -17,62 +17,61 @@ * @subpackage View * @since 2.0.6 */ - class RedshopViewAccess extends RedshopViewAdmin { - /** - * @var JForm - */ - protected $form; + /** + * @var JForm + */ + protected $form; - /** - * @var object - */ - protected $item; + /** + * @var object + */ + protected $item; - /** - * @var array - */ - protected $state; + /** + * @var array + */ + protected $state; - /** - * Function display template - * - * @param string $tpl name of template - * - * @return void - * - * @since 2.0.6 - */ - public function display($tpl = null) - { - JToolBarHelper::title(JText::_('COM_REDSHOP_ACCESS_MANAGER'), 'redshop_country_48'); + /** + * Function display template + * + * @param string $tpl name of template + * + * @return void + * + * @since 2.0.6 + */ + public function display($tpl = null) + { + JToolBarHelper::title(JText::_('COM_REDSHOP_ACCESS_MANAGER'), 'redshop_country_48'); - /** @var RedshopModelAccess $model */ - $model = $this->getModel(); + /** @var RedshopModelAccess $model */ + $model = $this->getModel(); - $this->item = $model->getItem(); - $this->form = $model->getForm(); - $this->state = $model->getState(); + $this->item = $model->getItem(); + $this->form = $model->getForm(); + $this->state = $model->getState(); - $this->addToolBar(); + $this->addToolBar(); - parent::display($tpl); - } + parent::display($tpl); + } - /** - * Add the page title and toolbar. - * - * @return void - * - * @since 2.0.6 - */ - protected function addToolbar() - { - JFactory::getApplication()->input->set('hidemainmenu', true); + /** + * Add the page title and toolbar. + * + * @return void + * + * @since 2.0.6 + */ + protected function addToolbar() + { + JFactory::getApplication()->input->set('hidemainmenu', true); - // Prepare text for title - JToolBarHelper::title(JText::_('COM_REDSHOP_ACCESS_MANAGER')); - JToolBarHelper::apply('access.save'); - } + // Prepare text for title + JToolBarHelper::title(JText::_('COM_REDSHOP_ACCESS_MANAGER')); + JToolBarHelper::apply('access.save'); + } } diff --git a/component/admin/views/accountgroup/index.html b/component/admin/views/accountgroup/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/accountgroup/index.html +++ b/component/admin/views/accountgroup/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/accountgroup/tmpl/default.php b/component/admin/views/accountgroup/tmpl/default.php index 097b27e3f13..541741932e1 100644 --- a/component/admin/views/accountgroup/tmpl/default.php +++ b/component/admin/views/accountgroup/tmpl/default.php @@ -1,4 +1,5 @@
    - - - - - - - - - - - - - - - - - - detail); $i < $n; $i++) - { - $row = $this->detail[$i]; - $row->id = $row->accountgroup_id; - $link = JRoute::_('index.php?option=com_redshop&view=accountgroup_detail&task=edit&cid[]=' . $row->id); - $published = JHtml::_('jgrid.published', $row->published, $i, '', 1); ?> - "> - - - - - - - - - - - - - - - - - -
    - - lists['order_Dir'], $this->lists['order']);?>lists['order_Dir'], $this->lists['order']);?>lists['order_Dir'], $this->lists['order']);?>lists['order_Dir'], $this->lists['order']);?>lists['order_Dir'], $this->lists['order']);?>lists['order_Dir'], $this->lists['order']);?>lists['order_Dir'], $this->lists['order']);?>lists['order_Dir'], $this->lists['order']);?>lists['order_Dir'], $this->lists['order']);?>lists['order_Dir'], $this->lists['order']); ?>
    pagination->getRowOffset($i); ?>id); ?>accountgroup_name; ?> - economic_vat_account;?>economic_nonvat_account;?>economic_discount_product_number;?>economic_discount_vat_account;?>economic_discount_nonvat_account;?>economic_shipping_vat_account;?>economic_shipping_nonvat_account;?>id;?>
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter(); ?>
    - - - - - + + + + + + + + + + + + + + + + + + detail); $i < $n; $i++) { + $row = $this->detail[$i]; + $row->id = $row->accountgroup_id; + $link = JRoute::_('index.php?option=com_redshop&view=accountgroup_detail&task=edit&cid[]=' . $row->id); + $published = JHtml::_('jgrid.published', $row->published, $i, '', 1); ?> + "> + + + + + + + + + + + + + + + + + +
    + + lists['order_Dir'], + $this->lists['order'] + ); ?>lists['order_Dir'], + $this->lists['order'] + ); ?>lists['order_Dir'], + $this->lists['order'] + ); ?>lists['order_Dir'], + $this->lists['order'] + ); ?>lists['order_Dir'], + $this->lists['order'] + ); ?>lists['order_Dir'], + $this->lists['order'] + ); ?>lists['order_Dir'], + $this->lists['order'] + ); ?>lists['order_Dir'], + $this->lists['order'] + ); ?>lists['order_Dir'], + $this->lists['order'] + ); ?>lists['order_Dir'], + $this->lists['order'] + ); ?>
    pagination->getRowOffset($i); ?>id); ?>accountgroup_name; ?> + economic_vat_account; ?>economic_nonvat_account; ?>economic_discount_product_number; ?>economic_discount_vat_account; ?>economic_discount_nonvat_account; ?>economic_shipping_vat_account; ?>economic_shipping_nonvat_account; ?>id; ?>
    + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?>
    + + + + +
    diff --git a/component/admin/views/accountgroup/tmpl/index.html b/component/admin/views/accountgroup/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/accountgroup/tmpl/index.html +++ b/component/admin/views/accountgroup/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/accountgroup/view.html.php b/component/admin/views/accountgroup/view.html.php index cae5c3dcaf2..4bbf5cb71c8 100644 --- a/component/admin/views/accountgroup/view.html.php +++ b/component/admin/views/accountgroup/view.html.php @@ -13,37 +13,41 @@ class RedshopViewAccountgroup extends RedshopViewAdmin { - public function display($tpl = null) - { - global $context; - - $app = JFactory::getApplication(); - - $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_ECONOMIC_ACCOUNT_GROUP')); - - JToolBarHelper::title(JText::_('COM_REDSHOP_ECONOMIC_ACCOUNT_GROUP'), 'redshop_accountgroup48'); - JToolbarHelper::addNew(); - JToolbarHelper::EditList(); - JToolbarHelper::deleteList(); - JToolBarHelper::publishList(); - JToolBarHelper::unpublishList(); - - $uri = JFactory::getURI(); - - $filter_order = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'accountgroup_id'); - $filter_order_Dir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', ''); - $lists['order'] = $filter_order; - $lists['order_Dir'] = $filter_order_Dir; - - $detail = $this->get('Data'); - $pagination = $this->get('Pagination'); - - $this->pagination = $pagination; - $this->detail = $detail; - $this->lists = $lists; - $this->request_url = $uri->toString(); - - parent::display($tpl); - } + public function display($tpl = null) + { + global $context; + + $app = JFactory::getApplication(); + + $document = JFactory::getDocument(); + $document->setTitle(JText::_('COM_REDSHOP_ECONOMIC_ACCOUNT_GROUP')); + + JToolBarHelper::title(JText::_('COM_REDSHOP_ECONOMIC_ACCOUNT_GROUP'), 'redshop_accountgroup48'); + JToolbarHelper::addNew(); + JToolbarHelper::EditList(); + JToolbarHelper::deleteList(); + JToolBarHelper::publishList(); + JToolBarHelper::unpublishList(); + + $uri = JFactory::getURI(); + + $filter_order = $app->getUserStateFromRequest( + $context . 'filter_order', + 'filter_order', + 'accountgroup_id' + ); + $filter_order_Dir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', ''); + $lists['order'] = $filter_order; + $lists['order_Dir'] = $filter_order_Dir; + + $detail = $this->get('Data'); + $pagination = $this->get('Pagination'); + + $this->pagination = $pagination; + $this->detail = $detail; + $this->lists = $lists; + $this->request_url = $uri->toString(); + + parent::display($tpl); + } } diff --git a/component/admin/views/accountgroup_detail/index.html b/component/admin/views/accountgroup_detail/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/accountgroup_detail/index.html +++ b/component/admin/views/accountgroup_detail/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/accountgroup_detail/tmpl/default.php b/component/admin/views/accountgroup_detail/tmpl/default.php index dea94115943..ac63a3b05a2 100644 --- a/component/admin/views/accountgroup_detail/tmpl/default.php +++ b/component/admin/views/accountgroup_detail/tmpl/default.php @@ -1,4 +1,5 @@ +defined('_JEXEC') or die; ?>
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    : -
    : -
    : -
    : -
    : -
    : -
    : -
    :lists['published']; ?>
    -
    -
    - - - +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    : +
    : +
    : +
    : +
    : +
    : +
    : +
    :lists['published']; ?>
    +
    +
    + + +
    diff --git a/component/admin/views/accountgroup_detail/tmpl/index.html b/component/admin/views/accountgroup_detail/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/accountgroup_detail/tmpl/index.html +++ b/component/admin/views/accountgroup_detail/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/accountgroup_detail/view.html.php b/component/admin/views/accountgroup_detail/view.html.php index c34cce2c55c..dc6eb75c8d7 100644 --- a/component/admin/views/accountgroup_detail/view.html.php +++ b/component/admin/views/accountgroup_detail/view.html.php @@ -20,7 +20,8 @@ class RedshopViewAccountgroup_detail extends RedshopViewAdmin protected $displaySidebar = false; /** - * @param null $tpl + * @param null $tpl + * * @return mixed|void */ public function display($tpl = null) @@ -30,9 +31,9 @@ public function display($tpl = null) JToolBarHelper::save(); JToolBarHelper::apply(); - $lists = array(); + $lists = array(); $detail = $this->get('data'); - $isNew = ($detail->accountgroup_id < 1); + $isNew = ($detail->accountgroup_id < 1); $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); @@ -42,12 +43,15 @@ public function display($tpl = null) \JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); } - \JToolBarHelper::title(JText::_('COM_REDSHOP_ECONOMIC_ACCOUNT_GROUP') . ': [ ' . $text . ' ]', 'redshop_accountgroup48'); + \JToolBarHelper::title( + JText::_('COM_REDSHOP_ECONOMIC_ACCOUNT_GROUP') . ': [ ' . $text . ' ]', + 'redshop_accountgroup48' + ); $lists['published'] = \JHTML::_('select.booleanlist', 'published', 'class="inputbox"', $detail->published); - $this->detail = $detail; - $this->lists = $lists; + $this->detail = $detail; + $this->lists = $lists; $this->requestUrl = $uri->toString(); parent::display($tpl); diff --git a/component/admin/views/addorder_detail/index.html b/component/admin/views/addorder_detail/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/addorder_detail/index.html +++ b/component/admin/views/addorder_detail/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/addorder_detail/tmpl/default.php b/component/admin/views/addorder_detail/tmpl/default.php index 139ad20cbeb..09bec6ac72c 100644 --- a/component/admin/views/addorder_detail/tmpl/default.php +++ b/component/admin/views/addorder_detail/tmpl/default.php @@ -1,4 +1,5 @@ getModel('addorder_detail'); -$billing = $this->billing; -$shipping = $this->shipping; +$billing = $this->billing; +$shipping = $this->shipping; $isCompany = $billing->is_company; -if (!empty ($_SERVER['REMOTE_ADDR'])) -{ - $ip = $_SERVER['REMOTE_ADDR']; -} -else -{ - $ip = 'unknown'; +if (!empty ($_SERVER['REMOTE_ADDR'])) { + $ip = $_SERVER['REMOTE_ADDR']; +} else { + $ip = 'unknown'; } $session = JFactory::getSession(); $session->set('ordertotal', 0); $billisshipcheck = ($this->shipping->billisship) ? "checked" : ""; -$shippingblock = ($this->shipping->billisship) ? "none" : ""; - -if ($this->detail->user_id < 0) -{ - $style = "none"; - $create_account = 0; -} -else -{ - $style = "block"; - $create_account = 1; +$shippingblock = ($this->shipping->billisship) ? "none" : ""; + +if ($this->detail->user_id < 0) { + $style = "none"; + $create_account = 0; +} else { + $style = "block"; + $create_account = 1; } $allowCustomer = ''; -$allowCompany = ''; -if ($isCompany == 1) -{ - $allowCustomer = 'style="display:none;"'; -} -else -{ - $allowCompany = 'style="display:none;"'; +$allowCompany = ''; +if ($isCompany == 1) { + $allowCustomer = 'style="display:none;"'; +} else { + $allowCompany = 'style="display:none;"'; } $err = JFactory::getApplication()->input->get('err', ''); @@ -62,782 +54,877 @@ $app->setUserState('com_redshop.addorder_detail.guestuser.username', null); ?> input->getCmd('ajaxtask', '')): ?> -
    -
    -
    - : -
    -
    - value = $this->detail->user_id; - $userDetail->text = $billing->firstname . ' ' . $billing->lastname; - echo JHTML::_('redshopselect.search', $userDetail, 'user_id', - array( - 'select2.ajaxOptions' => array('typeField' => ', addreduser:1'), - 'select2.options' => array( - 'events' => array('select2-selecting' => 'function(e) { + +
    +
    + : +
    +
    + value = $this->detail->user_id; + $userDetail->text = $billing->firstname . ' ' . $billing->lastname; + echo JHTML::_( + 'redshopselect.search', + $userDetail, + 'user_id', + array( + 'select2.ajaxOptions' => array('typeField' => ', addreduser:1'), + 'select2.options' => array( + 'events' => array( + 'select2-selecting' => 'function(e) { document.getElementById(\'user_id\').value = e.object.id; showUserDetail(); if (e.object.id){ document.getElementById(\'trCreateAccount\').style.display = \'none\'; - }}') - ) - ) - ); - ?> -
    -
    -
    -
    -
    -
    - : -
    -
    - -
    -
    -
    - - - - - - users_info_id): ?> - - + + + + + + +
    - - - - - - - - - - - - -
    - - - - - - > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > - - - - > - - - - get('USE_TAX_EXEMPT') == 1) - { - ?> - > - - - - > - - - - > - - - - - - - - -
    :lists['is_company'];?>
    :
    - : -
    :
    :
    :
    :
    :lists['country_code'];?>
    :lists['state_code']; ?>
    :
    :detail->user_id <= 0 && $style == "block") - { ?>onblur="validate(2);" /> -
    :
    :
    :tax_exempt); ?>
    : - requesting_tax_exempt); ?>
    - : - tax_exempt_approved); ?> -
    -
    >lists['customer_field'];?>
    -
    >lists['company_field'];?>
    -
    -
    - - - - - - - - - -
    - : - - - onclick="javascript:getShippinginfo('users_info_id ?>')" /> -
    :lists['shippinginfo_list'] ?>
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    :
    :
    :
    :
    :
    :lists['country_code_ST']; ?>
    :lists['state_code_ST']; ?>
    :
    -
    >lists['shipping_customer_field'];?>
    -
    >lists['shipping_company_field'];?>
    -
    -
    -
    - - detail->user_id <= 0): ?> - - - - - -
    - - - - - - - - - - - - - -
    :
    :
    :
    -
    - - - input->getCmd('ajaxtask') == "getuser"): ?> - - -
    - - - - - - - + + + + + + + + +
    - - - - - - - + + + + + + + +
    - - - - - - -
    array('typeField' => ', isproduct:1'), - 'select2.options' => array( - 'events' => array('select2-selecting' => 'function(e) { + }}' + ) + ) + ) + ); + ?> + + +
    +
    +
    +
    + : +
    +
    + +
    +
    +
    + + + + + + users_info_id): ?> + + - - - - - - -
    + + + + + + + + + + + + +
    + + + + + + > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + > + + + + > + + + + get('USE_TAX_EXEMPT') == 1) { + ?> + > + + + + > + + + + > + + + + + + + + +
    : + lists['is_company']; ?>
    :
    + : +
    :
    :
    :
    :
    :lists['country_code']; ?>
    :lists['state_code']; ?>
    :
    :detail->user_id <= 0 && $style == "block") + { ?>onblur="validate(2);" /> +
    :
    :
    :tax_exempt + ); ?>
    : + requesting_tax_exempt + ); ?>
    + : + tax_exempt_approved + ); ?> +
    +
    >lists['customer_field']; ?>
    +
    >lists['company_field']; ?>
    +
    +
    + + + + + + + + + +
    + : + + + onclick="javascript:getShippinginfo('users_info_id ?>')"/> +
    + : + lists['shippinginfo_list'] ?>
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + : +
    : +
    : +
    :
    :
    : + lists['country_code_ST']; ?>
    :lists['state_code_ST']; ?>
    :
    +
    >lists['shipping_customer_field']; ?>
    +
    >lists['shipping_company_field']; ?>
    +
    +
    +
    + + detail->user_id <= 0): ?> + + + + + +
    + + + + + + + + + + + + + +
    : +
    :
    + : +
    +
    + + + input->getCmd('ajaxtask') == "getuser"): ?> + + +
    + + + + + + + - - - - - - - - -
    + + + + + + + - - - - - - - -
    + + + + + + + + + + + + + +
    array('typeField' => ', isproduct:1'), + 'select2.options' => array( + 'events' => array( + 'select2-selecting' => 'function(e) { document.getElementById(\'product1\').value = e.object.id; displayProductDetailInfo(\'product1\', 0);}' - ) - ) - ) - ); - ?> -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - : -
    -
    - : -
    -
    - : -
    - -
    - : -
    - % -
    - : -
    -
    -
    -
    - : -
    -
    -
    -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    convertDateFormat(time());?>
    -
    -
    -
    -
    - input->getCmd('ajaxtask')): ?> - - - - - - - - - - -
    + ) + ) + ) + ); + ?> +
    +
    +
    +
    + +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + : +
    + +
    + : +
    +
    + : + +
    + +
    + : + +
    + % +
    + : +
    + +
    +
    +
    + : +
    +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    convertDateFormat(time()); ?>
    +
    +
    +
    +
    + input->getCmd('ajaxtask')): ?> + + + + + + + + + + +
    input; @@ -227,315 +203,325 @@ function validateProductQuantity() { ?>
    - - - - - - - - - - - - -
    - - - - - - - -
    : - array('typeField' => ', addreduser:1'), - 'select2.options' => array( - 'events' => array('select2-selecting' => 'function(e) {document.getElementById(\'user_id\').value = e.object.id;showquotationUserDetail()}') - ) - ) - ); - ?> -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    :
    : -
    : -
    : -
    :
    :lists['country_code']; ?>
    :lists['state_code']; ?>
    :
    :
    lists['quotation_extrafield'];?>
    - detail->user_id <= 0) - { - ?> - - - - - - - - - - - - - -
    : - -
    :
    - : -
    - get('ajaxtask') == "getuser") - { - die(); - } - - if (!$jinput->get('ajaxtask')) - { - ?> -
    - - - - - - - - - - - - - - - -
    -
    - - - - - - - - - - - - - - - - - - - - -
    - -
    - array('typeField' => ', isproduct:1'), - 'select2.options' => array( - 'events' => array('select2-selecting' => 'function(e) {document.getElementById(\'product1\').value = e.object.id;displayProductDetailInfo(\'product1\', 0);}') - ) - ) - ); - ?> -
    -
    -
    -
    -
    - -
    -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - -
    -
    - - - - - - - - - - - - - - - - - - - - - - -
    - : -
    -
    - : -
    -
    -
    -
    - : -
    -
    -
    -
    -
    -
    - - - + + + + + + + + + + + + +
    + + + + + + + +
    : + array('typeField' => ', addreduser:1'), + 'select2.options' => array( + 'events' => array('select2-selecting' => 'function(e) {document.getElementById(\'user_id\').value = e.object.id;showquotationUserDetail()}') + ) + ) + ); + ?> +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    :
    : +
    : +
    : +
    :
    :lists['country_code']; ?>
    :lists['state_code']; ?>
    :
    :
    lists['quotation_extrafield']; ?>
    + detail->user_id <= 0) { + ?> + + + + + + + + + + + + + +
    : + +
    :
    + : +
    + get('ajaxtask') == "getuser") { + die(); + } + + if (!$jinput->get('ajaxtask')) + { + ?> +
    + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + + + + + + + + + +
    + + + +
    + array('typeField' => ', isproduct:1'), + 'select2.options' => array( + 'events' => array('select2-selecting' => 'function(e) {document.getElementById(\'product1\').value = e.object.id;displayProductDetailInfo(\'product1\', 0);}') + ) + ) + ); + ?> +
    +
    +
    +
    +
    + +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + : +
    +
    + : +
    +
    +
    +
    + : +
    +
    +
    +
    +
    +
    + + +
    -
    - +
    + diff --git a/component/admin/views/addquotation_detail/tmpl/index.html b/component/admin/views/addquotation_detail/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/addquotation_detail/tmpl/index.html +++ b/component/admin/views/addquotation_detail/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/addquotation_detail/view.html.php b/component/admin/views/addquotation_detail/view.html.php index 44039572267..8df07830c50 100644 --- a/component/admin/views/addquotation_detail/view.html.php +++ b/component/admin/views/addquotation_detail/view.html.php @@ -10,78 +10,83 @@ defined('_JEXEC') or die; - class RedshopViewAddquotation_detail extends RedshopViewAdmin { - /** - * The request url. - * - * @var string - */ - public $request_url; - - /** - * Do we have to display a sidebar ? - * - * @var boolean - */ - protected $displaySidebar = false; - - public function display($tpl = null) - { - $document = JFactory::getDocument(); - - $document->setTitle(JText::_('COM_REDSHOP_QUOTATION_MANAGEMENT')); - - /** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/json.min.js', false, true); - /** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/redshop.validation.min.js', false, true); - /** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/redshop.order.min.js', false, true); - /** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/redshop.admin.common.min.js', false, true); - /** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/ajaxupload.min.js', false, true); - $session = JFactory::getSession(); - $uri = JUri::getInstance(); - - $lists = array(); - $model = $this->getModel(); - $user_id = JFactory::getApplication()->input->getInt('user_id', 0); - - if ($user_id != 0) - { - $billing = RedshopHelperOrder::getBillingAddress($user_id); - } - else - { - $billing = $model->setBilling(); - } - - $detail = new stdClass; - $detail->user_id = $user_id; - - $session->set('offlineuser_id', $user_id); - - JToolBarHelper::title( - JText::_('COM_REDSHOP_QUOTATION_MANAGEMENT') . ': [ ' - . JText::_('COM_REDSHOP_NEW') . ' ]', 'redshop_order48' - ); - - JToolBarHelper::apply(); - JToolBarHelper::save(); - JToolBarHelper::custom('send', 'send.png', 'send.png', JText::_('COM_REDSHOP_SEND'), false); - JToolBarHelper::cancel(); - - $countryarray = RedshopHelperWorld::getCountryList((array) $billing); - $billing->country_code = $countryarray['country_code']; - $lists['country_code'] = $countryarray['country_dropdown']; - - $statearray = RedshopHelperWorld::getStateList((array) $billing); - $lists['state_code'] = $statearray['state_dropdown']; - $lists['quotation_extrafield'] = RedshopHelperExtrafields::listAllField(RedshopHelperExtrafields::SECTION_QUOTATION, $billing->users_info_id); - - $this->lists = $lists; - $this->detail = $detail; - $this->billing = $billing; - $this->request_url = $uri->toString(); - - parent::display($tpl); - } + /** + * The request url. + * + * @var string + */ + public $request_url; + + /** + * Do we have to display a sidebar ? + * + * @var boolean + */ + protected $displaySidebar = false; + + public function display($tpl = null) + { + $document = JFactory::getDocument(); + + $document->setTitle(JText::_('COM_REDSHOP_QUOTATION_MANAGEMENT')); + + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/json.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.validation.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.order.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.admin.common.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/ajaxupload.min.js', false, true); + $session = JFactory::getSession(); + $uri = JUri::getInstance(); + + $lists = array(); + $model = $this->getModel(); + $user_id = JFactory::getApplication()->input->getInt('user_id', 0); + + if ($user_id != 0) { + $billing = RedshopHelperOrder::getBillingAddress($user_id); + } else { + $billing = $model->setBilling(); + } + + $detail = new stdClass; + $detail->user_id = $user_id; + + $session->set('offlineuser_id', $user_id); + + JToolBarHelper::title( + JText::_('COM_REDSHOP_QUOTATION_MANAGEMENT') . ': [ ' + . JText::_('COM_REDSHOP_NEW') . ' ]', + 'redshop_order48' + ); + + JToolBarHelper::apply(); + JToolBarHelper::save(); + JToolBarHelper::custom('send', 'send.png', 'send.png', JText::_('COM_REDSHOP_SEND'), false); + JToolBarHelper::cancel(); + + $countryarray = RedshopHelperWorld::getCountryList((array)$billing); + $billing->country_code = $countryarray['country_code']; + $lists['country_code'] = $countryarray['country_dropdown']; + + $statearray = RedshopHelperWorld::getStateList((array)$billing); + $lists['state_code'] = $statearray['state_dropdown']; + $lists['quotation_extrafield'] = RedshopHelperExtrafields::listAllField( + RedshopHelperExtrafields::SECTION_QUOTATION, + $billing->users_info_id + ); + + $this->lists = $lists; + $this->detail = $detail; + $this->billing = $billing; + $this->request_url = $uri->toString(); + + parent::display($tpl); + } } diff --git a/component/admin/views/alert/tmpl/default.php b/component/admin/views/alert/tmpl/default.php index 97a0cf2c98a..372c5bb9215 100644 --- a/component/admin/views/alert/tmpl/default.php +++ b/component/admin/views/alert/tmpl/default.php @@ -1,4 +1,5 @@
    -
    -
    -
    -
    - - "> - -
    -
    -
    - : - lists['read_filter']; ?> -
    -
    - - - - - - - - - +
    +
    +
    +
    + + "> + +
    +
    +
    + : + lists['read_filter']; ?> +
    +
    +
    - - - - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> -
    + + + + + + + + - - - + + alerts); $i < $n; $i++) - { - $row = $this->alerts[$i]; - $row->id = $row->id; + for ($i = 0, $n = count($this->alerts); $i < $n; $i++) { + $row = $this->alerts[$i]; + $row->id = $row->id; - $read = JHtml::_('jgrid.published', $row->read, $i, '', 1); - ?> - "> - - - - - - - - + $read = JHtml::_('jgrid.published', $row->read, $i, '', 1); + ?> + "> + + + + + + + + - - - -
    + + + + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> +
    - pagination->getRowOffset($i); ?> - - id); ?> - message; ?>sent_date; ?>id; ?>
    + pagination->getRowOffset($i); ?> + + id); ?> + message; ?>sent_date; ?>id; ?>
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter(); ?> -
    -
    + + + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?> + + + +
    - - - - - - + + + + + + diff --git a/component/admin/views/alert/view.html.php b/component/admin/views/alert/view.html.php index c1c57c8dbb7..4b138f7041c 100644 --- a/component/admin/views/alert/view.html.php +++ b/component/admin/views/alert/view.html.php @@ -12,54 +12,66 @@ class RedshopViewAlert extends RedshopViewAdmin { - /** - * The current user. - * - * @var JUser - */ - public $user; + /** + * The current user. + * + * @var JUser + */ + public $user; - /** - * The request url. - * - * @var string - */ - public $request_url; + /** + * The request url. + * + * @var string + */ + public $request_url; - public function display($tpl = null) - { - $document = JFactory::getDocument(); + public function display($tpl = null) + { + $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_ALERT')); + $document->setTitle(JText::_('COM_REDSHOP_ALERT')); - JToolBarHelper::title(JText::_('COM_REDSHOP_ALERT_MANAGEMENT'), 'redshop_mailcenter48'); - JToolBarHelper::deleteList(); - JToolBarHelper::custom('publish', 'publish.png', 'publish.png', JText::_('COM_REDSHOP_ALERT_READ'), true); - JToolBarHelper::custom('unpublish', 'unpublish.png', 'unpublish.png', JText::_('COM_REDSHOP_ALERT_UNREAD'), true); + JToolBarHelper::title(JText::_('COM_REDSHOP_ALERT_MANAGEMENT'), 'redshop_mailcenter48'); + JToolBarHelper::deleteList(); + JToolBarHelper::custom('publish', 'publish.png', 'publish.png', JText::_('COM_REDSHOP_ALERT_READ'), true); + JToolBarHelper::custom( + 'unpublish', + 'unpublish.png', + 'unpublish.png', + JText::_('COM_REDSHOP_ALERT_UNREAD'), + true + ); - $uri = JFactory::getURI(); - $this->state = $this->get('State'); + $uri = JFactory::getURI(); + $this->state = $this->get('State'); - $optiontype = array(); - $optiontype[] = JHTML::_('select.option', 'select', JText::_('COM_REDSHOP_SELECT')); - $optiontype[] = JHTML::_('select.option', '1', JText::_('COM_REDSHOP_ALERT_READ')); - $optiontype[] = JHTML::_('select.option', '0', JText::_('COM_REDSHOP_ALERT_UNREAD')); + $optiontype = array(); + $optiontype[] = JHTML::_('select.option', 'select', JText::_('COM_REDSHOP_SELECT')); + $optiontype[] = JHTML::_('select.option', '1', JText::_('COM_REDSHOP_ALERT_READ')); + $optiontype[] = JHTML::_('select.option', '0', JText::_('COM_REDSHOP_ALERT_UNREAD')); - $lists['read_filter'] = JHTML::_('select.genericlist', $optiontype, 'read_filter', - 'class="inputbox" size="1" onchange="document.adminForm.submit();" ', 'value', 'text', $this->state->get('read_filter') - ); + $lists['read_filter'] = JHTML::_( + 'select.genericlist', + $optiontype, + 'read_filter', + 'class="inputbox" size="1" onchange="document.adminForm.submit();" ', + 'value', + 'text', + $this->state->get('read_filter') + ); - $lists['order'] = $this->state->get('list.ordering'); - $lists['order_Dir'] = $this->state->get('list.direction'); - $alerts = $this->get('Data'); - $pagination = $this->get('Pagination'); + $lists['order'] = $this->state->get('list.ordering'); + $lists['order_Dir'] = $this->state->get('list.direction'); + $alerts = $this->get('Data'); + $pagination = $this->get('Pagination'); - $this->user = JFactory::getUser(); - $this->lists = $lists; - $this->alerts = $alerts; - $this->pagination = $pagination; - $this->request_url = $uri->toString(); + $this->user = JFactory::getUser(); + $this->lists = $lists; + $this->alerts = $alerts; + $this->pagination = $pagination; + $this->request_url = $uri->toString(); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/attribute/index.html b/component/admin/views/attribute/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/attribute/index.html +++ b/component/admin/views/attribute/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/attribute/tmpl/edit.php b/component/admin/views/attribute/tmpl/edit.php index d1cf904833a..965c2f5615d 100644 --- a/component/admin/views/attribute/tmpl/edit.php +++ b/component/admin/views/attribute/tmpl/edit.php @@ -1,4 +1,5 @@
    -
    -
    -
    -
    - - form->getFieldset('details') as $field): ?> - hidden) : ?> - input;?> - -
    -
    - label; ?> -
    -
    - input; ?> -
    -
    - -
    -
    -
    -
    - - - +
    +
    +
    +
    + + form->getFieldset('details') as $field): ?> + hidden) : ?> + input; ?> + +
    +
    + label; ?> +
    +
    + input; ?> +
    +
    + +
    +
    +
    +
    + + +
    diff --git a/component/admin/views/attribute/tmpl/index.html b/component/admin/views/attribute/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/attribute/tmpl/index.html +++ b/component/admin/views/attribute/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/attribute/view.html.php b/component/admin/views/attribute/view.html.php index 79cb37d93fe..bc098eccdfe 100644 --- a/component/admin/views/attribute/view.html.php +++ b/component/admin/views/attribute/view.html.php @@ -18,65 +18,63 @@ */ class RedshopViewAttribute extends RedshopViewAdmin { - protected $form; + protected $form; - protected $item; + protected $item; - protected $state; + protected $state; - /** - * Display the view. - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return mixed A string if successful, otherwise an Error object. - */ - public function display($tpl = null) - { - // Initialise variables. - $this->form = $this->get('Form'); - $this->item = $this->get('Item'); - $this->state = $this->get('State'); + /** + * Display the view. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise an Error object. + */ + public function display($tpl = null) + { + // Initialise variables. + $this->form = $this->get('Form'); + $this->item = $this->get('Item'); + $this->state = $this->get('State'); - // Check for errors. - if (count($errors = $this->get('Errors'))) - { - throw new Exception(implode("\n", $errors)); + // Check for errors. + if (count($errors = $this->get('Errors'))) { + throw new Exception(implode("\n", $errors)); - return false; - } + return false; + } - $this->addToolbar(); - parent::display($tpl); - } + $this->addToolbar(); + parent::display($tpl); + } - /** - * Add the page title and toolbar. - * - * @return void - * - * @since 1.6 - */ - protected function addToolbar() - { - JFactory::getApplication()->input->set('hidemainmenu', true); + /** + * Add the page title and toolbar. + * + * @return void + * + * @since 1.6 + */ + protected function addToolbar() + { + JFactory::getApplication()->input->set('hidemainmenu', true); - $isNew = ($this->item->attribute_id < 1); + $isNew = ($this->item->attribute_id < 1); - // Prepare text for title - $title = JText::_('COM_REDSHOP_ATTRIBUTE_MANAGEMENT') . ': [ ' . JText::_('COM_REDSHOP_EDIT') . ' ]'; + // Prepare text for title + $title = JText::_('COM_REDSHOP_ATTRIBUTE_MANAGEMENT') . ': [ ' . JText::_( + 'COM_REDSHOP_EDIT' + ) . ' ]'; - JToolBarHelper::title($title, 'redshop_giftcard_48'); - JToolBarHelper::apply('attribute.apply'); - JToolBarHelper::save('attribute.save'); + JToolBarHelper::title($title, 'redshop_giftcard_48'); + JToolBarHelper::apply('attribute.apply'); + JToolBarHelper::save('attribute.save'); - if ($isNew) - { - JToolBarHelper::cancel('attribute.cancel'); - } - else - { - JToolBarHelper::cancel('attribute.cancel', JText::_('JTOOLBAR_CLOSE')); - } - } + if ($isNew) { + JToolBarHelper::cancel('attribute.cancel'); + } else { + JToolBarHelper::cancel('attribute.cancel', JText::_('JTOOLBAR_CLOSE')); + } + } } diff --git a/component/admin/views/attribute_set/index.html b/component/admin/views/attribute_set/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/attribute_set/index.html +++ b/component/admin/views/attribute_set/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/attribute_set/tmpl/default.php b/component/admin/views/attribute_set/tmpl/default.php index 468fe1278ab..a0457bc48b3 100644 --- a/component/admin/views/attribute_set/tmpl/default.php +++ b/component/admin/views/attribute_set/tmpl/default.php @@ -1,4 +1,5 @@
    -
    - - - - - - - - - - - products); $i < $n; $i++) - { - $row = $this->products[$i]; - $row->id = $row->attribute_set_id; - $link = JRoute::_('index.php?option=com_redshop&view=attribute_set_detail&task=edit&cid[]=' . $row->id); +
    +
    - - - - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> -
    + + + + + + + + + + products); $i < $n; $i++) { + $row = $this->products[$i]; + $row->id = $row->attribute_set_id; + $link = JRoute::_( + 'index.php?option=com_redshop&view=attribute_set_detail&task=edit&cid[]=' . $row->id + ); - $published = JHtml::_('jgrid.published', $row->published, $i, '', 1);?> - "> - - - - - - - - - -
    + + + + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> +
    pagination->getRowOffset($i); ?>id); ?>attribute_set_name; ?> - id; ?>
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter(); ?>
    -
    - - - - - + $published = JHtml::_('jgrid.published', $row->published, $i, '', 1); ?> + "> + pagination->getRowOffset($i); ?> + id); ?> + attribute_set_name; ?> + + + id; ?> + + + + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?> + + +
    + + + + + diff --git a/component/admin/views/attribute_set/tmpl/index.html b/component/admin/views/attribute_set/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/attribute_set/tmpl/index.html +++ b/component/admin/views/attribute_set/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/attribute_set/view.html.php b/component/admin/views/attribute_set/view.html.php index df16768a6f5..389c71c6577 100644 --- a/component/admin/views/attribute_set/view.html.php +++ b/component/admin/views/attribute_set/view.html.php @@ -12,41 +12,45 @@ class RedshopViewAttribute_set extends RedshopViewAdmin { - public function display($tpl = null) - { - global $context; + public function display($tpl = null) + { + global $context; - $app = JFactory::getApplication(); + $app = JFactory::getApplication(); - $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_ATTRIBUTE_SET')); + $document = JFactory::getDocument(); + $document->setTitle(JText::_('COM_REDSHOP_ATTRIBUTE_SET')); - JToolBarHelper::title(JText::_('COM_REDSHOP_ATTRIBUTE_SET'), 'redshop_attribute_bank48'); + JToolBarHelper::title(JText::_('COM_REDSHOP_ATTRIBUTE_SET'), 'redshop_attribute_bank48'); - JToolbarHelper::addNew(); - JToolbarHelper::EditList(); - JToolBarHelper::custom('copy', 'copy.png', 'copy_f2.png', JText::_('COM_REDSHOP_TOOLBAR_COPY'), true); - JToolBarHelper::deleteList(); - JToolBarHelper::publishList(); - JToolBarHelper::unpublishList(); + JToolbarHelper::addNew(); + JToolbarHelper::EditList(); + JToolBarHelper::custom('copy', 'copy.png', 'copy_f2.png', JText::_('COM_REDSHOP_TOOLBAR_COPY'), true); + JToolBarHelper::deleteList(); + JToolBarHelper::publishList(); + JToolBarHelper::unpublishList(); - $uri = JFactory::getURI(); + $uri = JFactory::getURI(); - $filter_order = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'attribute_set_id'); - $filter_order_Dir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', ''); + $filter_order = $app->getUserStateFromRequest( + $context . 'filter_order', + 'filter_order', + 'attribute_set_id' + ); + $filter_order_Dir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', ''); - $lists = array(); - $lists['order'] = $filter_order; - $lists['order_Dir'] = $filter_order_Dir; + $lists = array(); + $lists['order'] = $filter_order; + $lists['order_Dir'] = $filter_order_Dir; - $products = $this->get('Data'); - $pagination = $this->get('Pagination'); + $products = $this->get('Data'); + $pagination = $this->get('Pagination'); - $this->lists = $lists; - $this->products = $products; - $this->pagination = $pagination; - $this->request_url = $uri->toString(); + $this->lists = $lists; + $this->products = $products; + $this->pagination = $pagination; + $this->request_url = $uri->toString(); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/attribute_set_detail/index.html b/component/admin/views/attribute_set_detail/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/attribute_set_detail/index.html +++ b/component/admin/views/attribute_set_detail/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/attribute_set_detail/tmpl/default.php b/component/admin/views/attribute_set_detail/tmpl/default.php index dff185c3c1f..c9eb0b87712 100644 --- a/component/admin/views/attribute_set_detail/tmpl/default.php +++ b/component/admin/views/attribute_set_detail/tmpl/default.php @@ -1,4 +1,5 @@ root(); ?>
    request_url) ?>" method="post" name="adminForm" id="adminForm" enctype="multipart/form-data"> -
    -
    - - - - - -
    - - - - - - - - - -
    - - - -
    - : - - lists ['published'];?> -
    -
    -
    -
    - -
    - - - - - - - - - - - -
    -
    -
    - -
    -
    - $this)); ?> - - - - - +
    +
    + + + + + +
    + + + + + + + + + +
    + + + +
    + : + + lists ['published']; ?> +
    +
    +
    +
    + +
    + + + + + + + + + + + +
    +
    +
    + +
    +
    + $this)); ?> + + + + +
    diff --git a/component/admin/views/attribute_set_detail/tmpl/index.html b/component/admin/views/attribute_set_detail/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/attribute_set_detail/tmpl/index.html +++ b/component/admin/views/attribute_set_detail/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/attribute_set_detail/view.html.php b/component/admin/views/attribute_set_detail/view.html.php index d534d31fd86..5669ee9978c 100644 --- a/component/admin/views/attribute_set_detail/view.html.php +++ b/component/admin/views/attribute_set_detail/view.html.php @@ -12,78 +12,82 @@ class RedshopViewAttribute_set_detail extends RedshopViewAdmin { - /** - * Do we have to display a sidebar ? - * - * @var boolean - */ - protected $displaySidebar = false; + /** + * Do we have to display a sidebar ? + * + * @var boolean + */ + protected $displaySidebar = false; - public function display($tpl = null) - { - $lists = array(); + public function display($tpl = null) + { + $lists = array(); - $model = $this->getModel('attribute_set_detail'); + $model = $this->getModel('attribute_set_detail'); - $attributes = $model->getattributes(); + $attributes = $model->getattributes(); - JToolBarHelper::title(JText::_('COM_REDSHOP_ATTRIBUTE_SET_DETAIL'), 'redshop_attribute_bank48'); - $document = JFactory::getDocument(); + JToolBarHelper::title(JText::_('COM_REDSHOP_ATTRIBUTE_SET_DETAIL'), 'redshop_attribute_bank48'); + $document = JFactory::getDocument(); - $document->addScriptDeclaration(" + $document->addScriptDeclaration( + " var WANT_TO_DELETE = '" . JText::_('COM_REDSHOP_DO_WANT_TO_DELETE') . "'; " - ); + ); - if (version_compare(JVERSION, '3.0', '<')) - { - /** @scrutinizer ignore-deprecated */ JHtml::stylesheet('com_redshop/redshop.update.min.css', array(), true); - } + if (version_compare(JVERSION, '3.0', '<')) { + /** @scrutinizer ignore-deprecated */ + JHtml::stylesheet('com_redshop/redshop.update.min.css', array(), true); + } - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/redshop.attribute-manipulation.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/redshop.fields.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/redshop.validation.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.attribute-manipulation.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.fields.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.validation.min.js', false, true); - $uri = JUri::getInstance(); + $uri = JUri::getInstance(); - $detail = $this->get('data'); + $detail = $this->get('data'); - $isNew = ($detail->attribute_set_id < 1); + $isNew = ($detail->attribute_set_id < 1); - $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); + $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); - JToolBarHelper::title(JText::_('COM_REDSHOP_ATTRIBUTE_SET') . ': [ ' . $text . ' ]', 'redshop_attribute_bank48'); + JToolBarHelper::title( + JText::_('COM_REDSHOP_ATTRIBUTE_SET') . ': [ ' . $text . ' ]', + 'redshop_attribute_bank48' + ); - JToolBarHelper::apply(); + JToolBarHelper::apply(); - JToolBarHelper::save(); + JToolBarHelper::save(); - if ($isNew) - { - JToolBarHelper::cancel(); - } - else - { - JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); - } + if ($isNew) { + JToolBarHelper::cancel(); + } else { + JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); + } - $lists['published'] = JHTML::_('select.booleanlist', 'published', 'class="inputbox"', $detail->published); - $lists['attributes'] = $attributes; + $lists['published'] = JHTML::_('select.booleanlist', 'published', 'class="inputbox"', $detail->published); + $lists['attributes'] = $attributes; - $propOprand = array(); - $propOprand[] = JHtml::_('select.option', '+', '+'); - $propOprand[] = JHtml::_('select.option', '-', '-'); - $propOprand[] = JHtml::_('select.option', '=', '='); - $propOprand[] = JHtml::_('select.option', '*', '*'); - $propOprand[] = JHtml::_('select.option', '/', '/'); + $propOprand = array(); + $propOprand[] = JHtml::_('select.option', '+', '+'); + $propOprand[] = JHtml::_('select.option', '-', '-'); + $propOprand[] = JHtml::_('select.option', '=', '='); + $propOprand[] = JHtml::_('select.option', '*', '*'); + $propOprand[] = JHtml::_('select.option', '/', '/'); - $lists['prop_oprand'] = $propOprand; + $lists['prop_oprand'] = $propOprand; - $this->model = $model; - $this->lists = $lists; - $this->detail = $detail; - $this->request_url = $uri->toString(); + $this->model = $model; + $this->lists = $lists; + $this->detail = $detail; + $this->request_url = $uri->toString(); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/attributeprices/index.html b/component/admin/views/attributeprices/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/attributeprices/index.html +++ b/component/admin/views/attributeprices/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/attributeprices/tmpl/default.php b/component/admin/views/attributeprices/tmpl/default.php index 1c8576c0d54..656f3c0e6e9 100644 --- a/component/admin/views/attributeprices/tmpl/default.php +++ b/component/admin/views/attributeprices/tmpl/default.php @@ -17,74 +17,79 @@ };
    -
    - - - - -
    -
    +
    + + + + +
    +
    -
    - - - - - - - - - - - - - - data); $i++) - { - $row = $this->data[$i]; - $row->id = $row->price_id; - $link = JRoute::_('index.php?tmpl=component&option=com_redshop&view=attributeprices_detail&task=edit§ion=' . $this->section . '§ion_id=' . $row->section_id . '&cid[]=' . $row->price_id);?> - "> - - - - - - - - - - - - - -
    pagination->getRowOffset($i); ?>id); ?>property_name;?> - shopper_group_name;?>price_quantity_start;?>price_quantity_end;?>product_price); ?>discount_price); ?>
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter(); ?>
    -
    - - - - - +
    + + + + + + + + + + + + + + data); $i++) { + $row = $this->data[$i]; + $row->id = $row->price_id; + $link = JRoute::_( + 'index.php?tmpl=component&option=com_redshop&view=attributeprices_detail&task=edit§ion=' . $this->section . '§ion_id=' . $row->section_id . '&cid[]=' . $row->price_id + ); ?> + "> + + + + + + + + + + + + + +
    pagination->getRowOffset($i); ?>id); ?>property_name; ?> + shopper_group_name; ?>price_quantity_start; ?>price_quantity_end; ?>product_price); ?>discount_price); ?>
    + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?>
    +
    + + + + +
    diff --git a/component/admin/views/attributeprices/tmpl/index.html b/component/admin/views/attributeprices/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/attributeprices/tmpl/index.html +++ b/component/admin/views/attributeprices/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/attributeprices/view.html.php b/component/admin/views/attributeprices/view.html.php index 53e7391814f..34721bdba2c 100644 --- a/component/admin/views/attributeprices/view.html.php +++ b/component/admin/views/attributeprices/view.html.php @@ -13,39 +13,39 @@ class RedshopViewAttributeprices extends RedshopViewAdmin { - public function display($tpl = null) - { - global $context; + public function display($tpl = null) + { + global $context; - $app = JFactory::getApplication(); + $app = JFactory::getApplication(); - $section_id = $app->input->get('section_id'); - $section = $app->input->get('section'); + $section_id = $app->input->get('section_id'); + $section = $app->input->get('section'); - $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_ATTRIBUTE_PRICE')); + $document = JFactory::getDocument(); + $document->setTitle(JText::_('COM_REDSHOP_ATTRIBUTE_PRICE')); - JToolBarHelper::title(JText::_('COM_REDSHOP_ATTRIBUTE_PRICE'), 'redshop_vatrates48'); + JToolBarHelper::title(JText::_('COM_REDSHOP_ATTRIBUTE_PRICE'), 'redshop_vatrates48'); - JToolbarHelper::addNew(); - JToolbarHelper::EditList(); - JToolBarHelper::deleteList(); - $uri = JFactory::getURI(); + JToolbarHelper::addNew(); + JToolbarHelper::EditList(); + JToolBarHelper::deleteList(); + $uri = JFactory::getURI(); - $limitstart = $app->getUserStateFromRequest($context . 'limitstart', 'limitstart', '0'); - $limit = $app->getUserStateFromRequest($context . 'limit', 'limit', '10'); + $limitstart = $app->getUserStateFromRequest($context . 'limitstart', 'limitstart', '0'); + $limit = $app->getUserStateFromRequest($context . 'limit', 'limit', '10'); - $total = $this->get('Total'); - $data = $this->get('Data'); - $pagination = new JPagination($total, $limitstart, $limit); + $total = $this->get('Total'); + $data = $this->get('Data'); + $pagination = new JPagination($total, $limitstart, $limit); - $this->user = JFactory::getUser(); - $this->data = $data; - $this->section_id = $section_id; - $this->section = $section; - $this->pagination = $pagination; - $this->request_url = $uri->toString(); + $this->user = JFactory::getUser(); + $this->data = $data; + $this->section_id = $section_id; + $this->section = $section; + $this->pagination = $pagination; + $this->request_url = $uri->toString(); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/attributeprices_detail/index.html b/component/admin/views/attributeprices_detail/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/attributeprices_detail/index.html +++ b/component/admin/views/attributeprices_detail/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/attributeprices_detail/tmpl/default.php b/component/admin/views/attributeprices_detail/tmpl/default.php index 70e4ded0c7c..a55c7349e10 100644 --- a/component/admin/views/attributeprices_detail/tmpl/default.php +++ b/component/admin/views/attributeprices_detail/tmpl/default.php @@ -1,4 +1,5 @@ -input->get('section'); ?>
    -
    - - -
    -
    +
    + + +
    +
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
    :property->property_name;?>
    - : - lists['shopper_group_name'];?>
    - : - -
    - : - -
    : -
    : - -
    - : - - +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - -
    :property->property_name; ?>
    + : + lists['shopper_group_name']; ?>
    + : + +
    + : + +
    : +
    : + +
    + : + + detail->discount_start_date) : - $sdate = date(Redshop::getConfig()->getString('DEFAULT_DATEFORMAT', 'Y-m-d'), $this->detail->discount_start_date); - endif; + if ($this->detail->discount_start_date) : + $sdate = date( + Redshop::getConfig()->getString('DEFAULT_DATEFORMAT', 'Y-m-d'), + $this->detail->discount_start_date + ); + endif; - echo JHtml::_( - 'redshopcalendar.calendar', - $sdate, - 'discount_start_date', - 'discount_start_date', - null, - array('class' => 'form-control', 'size' => '15', 'maxlength' => '19') - ); + echo JHtml::_( + 'redshopcalendar.calendar', + $sdate, + 'discount_start_date', + 'discount_start_date', + null, + array('class' => 'form-control', 'size' => '15', 'maxlength' => '19') + ); - ?> + ?> +
    + :
    - : - - + detail->discount_end_date) : - $sdate = date(Redshop::getConfig()->getString('DEFAULT_DATEFORMAT', 'Y-m-d'), $this->detail->discount_end_date); - endif; + if ($this->detail->discount_end_date) : + $sdate = date( + Redshop::getConfig()->getString('DEFAULT_DATEFORMAT', 'Y-m-d'), + $this->detail->discount_end_date + ); + endif; echo JHtml::_( 'redshopcalendar.calendar', @@ -137,16 +148,16 @@ array('class' => 'form-control', 'size' => '15', 'maxlength' => '19') ); - ?> + ?>
    -
    - -
    - - - - - +
    +
    +
    +
    + + + + +
    diff --git a/component/admin/views/attributeprices_detail/tmpl/index.html b/component/admin/views/attributeprices_detail/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/attributeprices_detail/tmpl/index.html +++ b/component/admin/views/attributeprices_detail/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/attributeprices_detail/view.html.php b/component/admin/views/attributeprices_detail/view.html.php index 4bcca5b45eb..775c8a471f7 100644 --- a/component/admin/views/attributeprices_detail/view.html.php +++ b/component/admin/views/attributeprices_detail/view.html.php @@ -12,30 +12,30 @@ class RedshopViewAttributeprices_detail extends RedshopViewAdmin { - /** - * Do we have to display a sidebar ? - * - * @var boolean - */ - protected $displaySidebar = false; + /** + * Do we have to display a sidebar ? + * + * @var boolean + */ + protected $displaySidebar = false; - public function display($tpl = null) - { - $this->lists = array(); - $this->detail = $this->get('data'); - $model = $this->getModel('attributeprices_detail'); - $this->property = $model->getPropertyName(); - $this->request_url = JFactory::getURI()->toString(); + public function display($tpl = null) + { + $this->lists = array(); + $this->detail = $this->get('data'); + $model = $this->getModel('attributeprices_detail'); + $this->property = $model->getPropertyName(); + $this->request_url = JFactory::getURI()->toString(); - $this->lists['shopper_group_name'] = RedshopHelperShopper_Group::listAll( - "shopper_group_id", - 0, - array($this->detail->shopper_group_id), - 1, - true, - false - ); + $this->lists['shopper_group_name'] = RedshopHelperShopper_Group::listAll( + "shopper_group_id", + 0, + array($this->detail->shopper_group_id), + 1, + true, + false + ); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/attributes/index.html b/component/admin/views/attributes/index.html index 94906bce29b..af1d3c9d43e 100644 --- a/component/admin/views/attributes/index.html +++ b/component/admin/views/attributes/index.html @@ -1 +1,3 @@ - + + + diff --git a/component/admin/views/attributes/tmpl/default.php b/component/admin/views/attributes/tmpl/default.php index cb9873f8d62..5f371342307 100644 --- a/component/admin/views/attributes/tmpl/default.php +++ b/component/admin/views/attributes/tmpl/default.php @@ -1,4 +1,5 @@ escape($this->state->get('list.direction')); ?>
    -
    - $this, - 'options' => array( - 'searchField' => 'search', - 'filtersHidden' => false, - 'searchFieldSelector' => '#filter_search', - 'limitFieldSelector' => '#list_users_limit', - 'activeOrder' => $listOrder, - 'activeDirection' => $listDirn, - ) - ) - ); - ?> -
    +
    + $this, + 'options' => array( + 'searchField' => 'search', + 'filtersHidden' => false, + 'searchFieldSelector' => '#filter_search', + 'limitFieldSelector' => '#list_users_limit', + 'activeOrder' => $listOrder, + 'activeDirection' => $listDirn, + ) + ) + ); + ?> +
    - items)) : ?> -
    - -
    - - - - - - - - - - - - - - items as $i => $item) : ?> - - - - + + + + + + + + + +
    - - - - - - - - - - - -
    - attribute_id); ?> - -
    - attribute_published, $i, 'attributes.', true, 'cb'); ?> -
    -
    -
    - - escape($item->attribute_name); ?> - + items)) : ?> +
    + +
    + + + + + + + + + + + + + + items as $i => $item) : ?> + + + + - - - - - - - - - -
    + + + + + + + + + + + +
    + attribute_id); ?> + +
    + attribute_published, + $i, + 'attributes.', + true, + 'cb' + ); ?> +
    +
    + - - product_name;?> - - display_type;?> - - attribute_id; ?> -
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter(); ?> -
    - - - - +
    +
    + product_name; ?> + + display_type; ?> + + attribute_id; ?> +
    + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?> +
    + + + +
    diff --git a/component/admin/views/attributes/tmpl/index.html b/component/admin/views/attributes/tmpl/index.html index 94906bce29b..af1d3c9d43e 100644 --- a/component/admin/views/attributes/tmpl/index.html +++ b/component/admin/views/attributes/tmpl/index.html @@ -1 +1,3 @@ - + + + diff --git a/component/admin/views/attributes/view.html.php b/component/admin/views/attributes/view.html.php index 2523561fc8c..3722085dad7 100644 --- a/component/admin/views/attributes/view.html.php +++ b/component/admin/views/attributes/view.html.php @@ -18,60 +18,58 @@ */ class RedshopViewAttributes extends RedshopViewAdmin { - /** - * Display the Attributes view - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return void - */ - public function display($tpl = null) - { - $model = $this->getModel(); + /** + * Display the Attributes view + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + */ + public function display($tpl = null) + { + $model = $this->getModel(); - // Get data from the model - $this->items = $model->getItems(); - $this->pagination = $model->getPagination(); - $this->state = $model->getState(); - $this->activeFilters = $model->getActiveFilters(); - $this->filterForm = $model->getForm(); + // Get data from the model + $this->items = $model->getItems(); + $this->pagination = $model->getPagination(); + $this->state = $model->getState(); + $this->activeFilters = $model->getActiveFilters(); + $this->filterForm = $model->getForm(); - // Check for errors. - if (count($errors = $this->get('Errors'))) - { - throw new Exception(implode('
    ', $errors)); + // Check for errors. + if (count($errors = $this->get('Errors'))) { + throw new Exception(implode('
    ', $errors)); - return false; - } + return false; + } - // Set the tool-bar and number of found items - $this->addToolBar(); + // Set the tool-bar and number of found items + $this->addToolBar(); - // Display the template - parent::display($tpl); - } + // Display the template + parent::display($tpl); + } - /** - * Add the page title and toolbar. - * - * @return void - * - * @since 1.6 - */ - protected function addToolBar() - { - $title = JText::_('COM_REDSHOP_ATTRIBUTE_MANAGEMENT'); + /** + * Add the page title and toolbar. + * + * @return void + * + * @since 1.6 + */ + protected function addToolBar() + { + $title = JText::_('COM_REDSHOP_ATTRIBUTE_MANAGEMENT'); - if ($this->pagination->total) - { - $title .= "(" . $this->pagination->total . ")"; - } + if ($this->pagination->total) { + $title .= "(" . $this->pagination->total . ")"; + } - JToolBarHelper::title($title, 'redshop_giftcard_48'); - JToolBarHelper::addNew('attribute.add'); - JToolBarHelper::editList('attribute.edit'); - JToolBarHelper::deleteList('', 'attributes.delete'); - JToolbarHelper::publish('attributes.publish', 'JTOOLBAR_PUBLISH', true); - JToolbarHelper::unpublish('attributes.unpublish', 'JTOOLBAR_UNPUBLISH', true); - } + JToolBarHelper::title($title, 'redshop_giftcard_48'); + JToolBarHelper::addNew('attribute.add'); + JToolBarHelper::editList('attribute.edit'); + JToolBarHelper::deleteList('', 'attributes.delete'); + JToolbarHelper::publish('attributes.publish', 'JTOOLBAR_PUBLISH', true); + JToolbarHelper::unpublish('attributes.unpublish', 'JTOOLBAR_UNPUBLISH', true); + } } diff --git a/component/admin/views/catalog/index.html b/component/admin/views/catalog/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/catalog/index.html +++ b/component/admin/views/catalog/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/catalog/tmpl/edit.php b/component/admin/views/catalog/tmpl/edit.php index c71283b54fb..3c4211ecd99 100644 --- a/component/admin/views/catalog/tmpl/edit.php +++ b/component/admin/views/catalog/tmpl/edit.php @@ -1,4 +1,5 @@ \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/catalog/view.html.php b/component/admin/views/catalog/view.html.php index fcaa25bcffd..3e2d526a9e8 100644 --- a/component/admin/views/catalog/view.html.php +++ b/component/admin/views/catalog/view.html.php @@ -18,22 +18,21 @@ */ class RedshopViewCatalog extends RedshopViewForm { - /** - * Method for prepare field HTML - * - * @param object $field Group object - * - * @return boolean|string False if keep. String for HTML content if success. - * - * @since 2.1.2 - */ - public function prepareField($field) - { - if ($field->getAttribute('name') == 'media') - { - return false; - } + /** + * Method for prepare field HTML + * + * @param object $field Group object + * + * @return boolean|string False if keep. String for HTML content if success. + * + * @since 2.1.2 + */ + public function prepareField($field) + { + if ($field->getAttribute('name') == 'media') { + return false; + } - return parent::/** @scrutinizer ignore-call */ prepareField($field); - } + return parent::/** @scrutinizer ignore-call */ prepareField($field); + } } diff --git a/component/admin/views/catalog_request/index.html b/component/admin/views/catalog_request/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/catalog_request/index.html +++ b/component/admin/views/catalog_request/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/catalog_request/tmpl/default.php b/component/admin/views/catalog_request/tmpl/default.php index 67f27c60a2c..91e5a4a7bf6 100644 --- a/component/admin/views/catalog_request/tmpl/default.php +++ b/component/admin/views/catalog_request/tmpl/default.php @@ -7,109 +7,150 @@ * @license GNU General Public License version 2 or later; see LICENSE */ -$Redconfiguration = Redconfiguration::getInstance();?> +$Redconfiguration = Redconfiguration::getInstance(); ?>
    -
    - - - - - - - - - - - - - - - catalog); $i < $n; $i++) - { - $row = $this->catalog[$i]; - $row->id = $row->catalog_user_id; - $row->published = $row->block; - $published = JHtml::_('jgrid.published', $row->published, $i, '', 1); +
    +
    - - - - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> -
    + + + + + + + + + + + + + + catalog); $i < $n; $i++) { + $row = $this->catalog[$i]; + $row->id = $row->catalog_user_id; + $row->published = $row->block; + $published = JHtml::_('jgrid.published', $row->published, $i, '', 1); - $reminder1 = JHtml::_('jgrid.published', $row->reminder_1, $i, '', 1); - $reminder2 = JHtml::_('jgrid.published', $row->reminder_2, $i, '', 1); - $reminder3 = JHtml::_('jgrid.published', $row->reminder_3, $i, '', 1);?> - "> - - - - - - - - - - - - - -
    + + + + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> +
    pagination->getRowOffset($i); ?>id); ?>name; ?>email; ?>convertDateFormat($row->registerDate); ?>
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter(); ?> -
    -
    + $reminder1 = JHtml::_('jgrid.published', $row->reminder_1, $i, '', 1); + $reminder2 = JHtml::_('jgrid.published', $row->reminder_2, $i, '', 1); + $reminder3 = JHtml::_('jgrid.published', $row->reminder_3, $i, '', 1); ?> + "> + pagination->getRowOffset($i); ?> + id); ?> + name; ?> + email; ?> + convertDateFormat($row->registerDate); ?> + + + + + + + + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?> + + + +
    - - - - - + + + + + diff --git a/component/admin/views/catalog_request/tmpl/index.html b/component/admin/views/catalog_request/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/catalog_request/tmpl/index.html +++ b/component/admin/views/catalog_request/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/catalog_request/view.html.php b/component/admin/views/catalog_request/view.html.php index af062109b89..2bdaa7991d2 100644 --- a/component/admin/views/catalog_request/view.html.php +++ b/component/admin/views/catalog_request/view.html.php @@ -12,36 +12,36 @@ class RedshopViewCatalog_request extends RedshopViewAdmin { - public function display($tpl = null) - { - $context = "rating"; + public function display($tpl = null) + { + $context = "rating"; - $app = JFactory::getApplication(); + $app = JFactory::getApplication(); - $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_CATALOG_REQUEST')); + $document = JFactory::getDocument(); + $document->setTitle(JText::_('COM_REDSHOP_CATALOG_REQUEST')); - JToolBarHelper::title(JText::_('COM_REDSHOP_CATALOG_REQUEST_MANAGEMENT'), 'redshop_catalogmanagement48'); - JToolBarHelper::deleteList(); - JToolBarHelper::publishList(); - JToolBarHelper::unpublishList(); + JToolBarHelper::title(JText::_('COM_REDSHOP_CATALOG_REQUEST_MANAGEMENT'), 'redshop_catalogmanagement48'); + JToolBarHelper::deleteList(); + JToolBarHelper::publishList(); + JToolBarHelper::unpublishList(); - $uri = JFactory::getURI(); + $uri = JFactory::getURI(); - $filter_order = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'catalog_user_id'); - $filter_order_Dir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', ''); + $filter_order = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'catalog_user_id'); + $filter_order_Dir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', ''); - $lists['order'] = $filter_order; - $lists['order_Dir'] = $filter_order_Dir; - $catalog = $this->get('Data'); - $pagination = $this->get('Pagination'); + $lists['order'] = $filter_order; + $lists['order_Dir'] = $filter_order_Dir; + $catalog = $this->get('Data'); + $pagination = $this->get('Pagination'); - $this->user = JFactory::getUser(); - $this->lists = $lists; - $this->catalog = $catalog; - $this->pagination = $pagination; - $this->request_url = $uri->toString(); + $this->user = JFactory::getUser(); + $this->lists = $lists; + $this->catalog = $catalog; + $this->pagination = $pagination; + $this->request_url = $uri->toString(); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/catalogs/index.html b/component/admin/views/catalogs/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/catalogs/index.html +++ b/component/admin/views/catalogs/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/catalogs/tmpl/default.php b/component/admin/views/catalogs/tmpl/default.php index ad7c091f89e..436659d236e 100644 --- a/component/admin/views/catalogs/tmpl/default.php +++ b/component/admin/views/catalogs/tmpl/default.php @@ -1,4 +1,5 @@ \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/catalogs/view.html.php b/component/admin/views/catalogs/view.html.php index 04bdbba355a..c3b6793944b 100644 --- a/component/admin/views/catalogs/view.html.php +++ b/component/admin/views/catalogs/view.html.php @@ -18,31 +18,32 @@ */ class RedshopViewCatalogs extends RedshopViewList { - /** - * Method for render 'Media' column - * - * @param array $config Row config. - * @param int $index Row index. - * @param object $row Row data. - * - * @return string - * @throws Exception - * - * @since 2.1.2 - */ - public function onRenderColumn($config, $index, $row) - { - if ($config['dataCol'] == 'media') - { - $model = $this->getModel('catalogs'); - $mediaDetail = $model->mediaDetail($row->catalog_id); - echo 'getModel('catalogs'); + $mediaDetail = $model->mediaDetail($row->catalog_id); + echo 'catalog_id . '&showbuttons=1&media_section=catalog§ion_name=' . $row->catalog_name . '" rel="{handler: \'iframe\', size: {x: 1050, y: 450}}" title=""> - media(' . count($mediaDetail) . ')'; - } + media(' . count( + $mediaDetail + ) . ')'; + } - return parent::onRenderColumn($config, $index, $row); - } + return parent::onRenderColumn($config, $index, $row); + } } diff --git a/component/admin/views/categories/index.html b/component/admin/views/categories/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/categories/index.html +++ b/component/admin/views/categories/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/categories/tmpl/default.php b/component/admin/views/categories/tmpl/default.php index b565843ded3..a76f0f53726 100644 --- a/component/admin/views/categories/tmpl/default.php +++ b/component/admin/views/categories/tmpl/default.php @@ -1,4 +1,5 @@ $this)); ?> diff --git a/component/admin/views/categories/tmpl/index.html b/component/admin/views/categories/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/categories/tmpl/index.html +++ b/component/admin/views/categories/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/categories/view.html.php b/component/admin/views/categories/view.html.php index bc1937f246a..ecee22127ac 100644 --- a/component/admin/views/categories/view.html.php +++ b/component/admin/views/categories/view.html.php @@ -18,130 +18,128 @@ */ class RedshopViewCategories extends RedshopViewList { - /** - * @var boolean - * - * @since 2.0.6 - */ - public $hasOrdering = true; + /** + * @var boolean + * + * @since 2.0.6 + */ + public $hasOrdering = true; - /** - * @var boolean - * - * @since 2.0.6 - */ - public $isNested = true; + /** + * @var boolean + * + * @since 2.0.6 + */ + public $isNested = true; - /** - * Method for add toolbar. - * - * @return void - * - * @since 2.0.6 - */ - protected function addToolbar() - { - // Add common button - if ($this->canCreate) - { - JToolbarHelper::addNew($this->getInstanceName() . '.add'); - JToolbarHelper::custom('category.copy', 'copy.png', 'copy_f2.png', JText::_('COM_REDSHOP_TOOLBAR_COPY'), true); - } + /** + * Method for render 'Published' column + * + * @param array $config Row config. + * @param int $index Row index. + * @param object $row Row data. + * + * @return string + * + * @since 2.0.6 + */ + public function onRenderColumn($config, $index, $row) + { + $isCheckedOut = $row->checked_out && JFactory::getUser()->id != $row->checked_out; + $inlineEditEnable = Redshop::getConfig()->getBool('INLINE_EDITING'); - if ($this->canDelete) - { - JToolbarHelper::deleteList('', $this->getInstancesName() . '.delete'); - } + if ($config['dataCol'] == 'name') { + if ($config['inline'] === true && !$isCheckedOut && $inlineEditEnable && $this->canEdit) { + $value = $row->{$config['dataCol']}; + $display = $value; - if ($this->canEdit) - { - JToolbarHelper::publish($this->getInstancesName() . '.publish', 'JTOOLBAR_PUBLISH', true); - JToolbarHelper::unpublish($this->getInstancesName() . '.unpublish', 'JTOOLBAR_UNPUBLISH', true); - JToolbarHelper::checkin($this->getInstancesName() . '.checkin', 'JTOOLBAR_CHECKIN', true); - } - } + if ($config['edit_link']) { + $display = str_repeat('| — ', $row->level - 1) + . '' . $value . ''; + } - /** - * Method for prepare table. - * - * @return void - * - * @since 2.0.6 - */ - protected function prepareTable() - { - parent::prepareTable(); + return JHtml::_('redshopgrid.inline', $config['dataCol'], $value, $display, $row->id, $config['type']); + } else { + if ($this->canEdit) { + return str_repeat('| — ', $row->level - 1) + . '' + . $row->{$config['dataCol']} . ''; + } else { + return str_repeat( + '| — ', + $row->level - 1 + ) . $row->{$config['dataCol']}; + } + } + } elseif ($config['dataCol'] == 'description') { + return JHtml::_('redshopgrid.slidetext', strip_tags($row->description)); + } - $this->columns[] = array( - // This column is sortable? - 'sortable' => false, - // Text for column - 'text' => JText::_('COM_REDSHOP_PRODUCTS'), - // Name of property for get data. - 'dataCol' => 'product', - // Width of column - 'width' => 'auto', - // Enable edit inline? - 'inline' => false, - // Display with edit link or not? - 'edit_link' => false, - // Type of column - 'type' => 'text', - ); - } + $row->product = RedshopEntityCategory::getInstance($row->id)->productCount(); - /** - * Method for render 'Published' column - * - * @param array $config Row config. - * @param int $index Row index. - * @param object $row Row data. - * - * @return string - * - * @since 2.0.6 - */ - public function onRenderColumn($config, $index, $row) - { - $isCheckedOut = $row->checked_out && JFactory::getUser()->id != $row->checked_out; - $inlineEditEnable = Redshop::getConfig()->getBool('INLINE_EDITING'); + return parent::onRenderColumn($config, $index, $row); + } - if ($config['dataCol'] == 'name') - { - if ($config['inline'] === true && !$isCheckedOut && $inlineEditEnable && $this->canEdit) - { - $value = $row->{$config['dataCol']}; - $display = $value; + /** + * Method for add toolbar. + * + * @return void + * + * @since 2.0.6 + */ + protected function addToolbar() + { + // Add common button + if ($this->canCreate) { + JToolbarHelper::addNew($this->getInstanceName() . '.add'); + JToolbarHelper::custom( + 'category.copy', + 'copy.png', + 'copy_f2.png', + JText::_('COM_REDSHOP_TOOLBAR_COPY'), + true + ); + } - if ($config['edit_link']) - { - $display = str_repeat('| — ', $row->level - 1) - . '' . $value . ''; - } + if ($this->canDelete) { + JToolbarHelper::deleteList('', $this->getInstancesName() . '.delete'); + } - return JHtml::_('redshopgrid.inline', $config['dataCol'], $value, $display, $row->id, $config['type']); - } - else - { - if ($this->canEdit) - { - return str_repeat('| — ', $row->level - 1) - . '' - . $row->{$config['dataCol']} . ''; - } - else - { - return str_repeat('| — ', $row->level - 1) . $row->{$config['dataCol']}; - } - } - } - elseif ($config['dataCol'] == 'description') - { - return JHtml::_('redshopgrid.slidetext', strip_tags($row->description)); - } + if ($this->canEdit) { + JToolbarHelper::publish($this->getInstancesName() . '.publish', 'JTOOLBAR_PUBLISH', true); + JToolbarHelper::unpublish($this->getInstancesName() . '.unpublish', 'JTOOLBAR_UNPUBLISH', true); + JToolbarHelper::checkin($this->getInstancesName() . '.checkin', 'JTOOLBAR_CHECKIN', true); + } + } - $row->product = RedshopEntityCategory::getInstance($row->id)->productCount(); + /** + * Method for prepare table. + * + * @return void + * + * @since 2.0.6 + */ + protected function prepareTable() + { + parent::prepareTable(); - return parent::onRenderColumn($config, $index, $row); - } + $this->columns[] = array( + // This column is sortable? + 'sortable' => false, + // Text for column + 'text' => JText::_('COM_REDSHOP_PRODUCTS'), + // Name of property for get data. + 'dataCol' => 'product', + // Width of column + 'width' => 'auto', + // Enable edit inline? + 'inline' => false, + // Display with edit link or not? + 'edit_link' => false, + // Type of column + 'type' => 'text', + ); + } } diff --git a/component/admin/views/category/index.html b/component/admin/views/category/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/category/index.html +++ b/component/admin/views/category/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/category/tmpl/edit.php b/component/admin/views/category/tmpl/edit.php index 89e08228e37..ed57c54dc61 100644 --- a/component/admin/views/category/tmpl/edit.php +++ b/component/admin/views/category/tmpl/edit.php @@ -1,4 +1,5 @@ - $this, - 'tabMenu' => $this->tabmenu->getData('tab')->items, - ) - ); - ?> - form->getInput('id'); ?> + $this, + 'tabMenu' => $this->tabmenu->getData('tab')->items, + ) + ); + ?> + form->getInput('id'); ?> - + diff --git a/component/admin/views/category/tmpl/edit_accessory.php b/component/admin/views/category/tmpl/edit_accessory.php index 582a2024aee..096094d96f3 100644 --- a/component/admin/views/category/tmpl/edit_accessory.php +++ b/component/admin/views/category/tmpl/edit_accessory.php @@ -1,4 +1,5 @@
    - array( - 'info' => array( - JText::_('COM_REDSHOP_CATEGORY_ACCESSORY_PRODUCT_INFO') - ) - ), - 'showHeading' => false, - 'allowClose' => false - ) - ); - ?> + array( + 'info' => array( + JText::_('COM_REDSHOP_CATEGORY_ACCESSORY_PRODUCT_INFO') + ) + ), + 'showHeading' => false, + 'allowClose' => false + ) + ); + ?> - @@ -70,31 +77,39 @@ - lists['categroy_accessory_product']; + $accessoryProduct = $this->lists['categroy_accessory_product']; - for ($f = 0, $fn = count($accessoryProduct); $f < $fn; $f++) : - $accessoryMainPrice = 0; + for ($f = 0, $fn = count($accessoryProduct); $f < $fn; $f++) : + $accessoryMainPrice = 0; - if ($accessoryProduct[$f]->product_id && $accessoryProduct[$f]->accessory_id) : - $accessoryMainPrice = \Redshop\Product\Accessory::getPrice($accessoryProduct[$f]->product_id, $accessoryProduct[$f]->newaccessory_price, $accessoryProduct[$f]->accessory_main_price, 1); - endif; + if ($accessoryProduct[$f]->product_id && $accessoryProduct[$f]->accessory_id) : + $accessoryMainPrice = \Redshop\Product\Accessory::getPrice( + $accessoryProduct[$f]->product_id, + $accessoryProduct[$f]->newaccessory_price, + $accessoryProduct[$f]->accessory_main_price, + 1 + ); + endif; - //$checked = ($accessoryProduct[$f]->setdefault_selected) ? "checked" : ""; - ?> + //$checked = ($accessoryProduct[$f]->setdefault_selected) ? "checked" : ""; + ?> @@ -116,7 +133,7 @@ class="childProductAccessory" class="button btn btn-danger" type="button"> - +

    +


    - array( - 'events' => array( - 'select2-selecting' => 'function(e) {create_table_accessory(e.object.text, e.object.id, e.object.price)}', - 'select2-close' => 'function(e) {$(this).select2("val", "")}' - ) - ), - 'select2.ajaxOptions' => array('typeField' => ', accessoryList: function(){ + array( + 'events' => array( + 'select2-selecting' => 'function(e) {create_table_accessory(e.object.text, e.object.id, e.object.price)}', + 'select2-close' => 'function(e) {$(this).select2("val", "")}' + ) + ), + 'select2.ajaxOptions' => array( + 'typeField' => ', accessoryList: function(){ var listAcc = []; jQuery(\'input.childProductAccessory\').each(function(){ listAcc[listAcc.length] = jQuery(this).val(); }); return listAcc.join(","); - }'), - ) - ); - ?> + }' + ), + ) + ); + ?>
    - product_name; ?> - product_name; ?> + - - @@ -105,8 +120,10 @@ class="childProductAccessory" name="product_accessory[][accessory_price]"> -
    diff --git a/component/admin/views/category/tmpl/edit_extrafield.php b/component/admin/views/category/tmpl/edit_extrafield.php index 6d7e5015c6c..24240d1f07f 100644 --- a/component/admin/views/category/tmpl/edit_extrafield.php +++ b/component/admin/views/category/tmpl/edit_extrafield.php @@ -1,4 +1,5 @@ - extraFields) : ?> - extraFields; ?> - + extraFields) : ?> + extraFields; ?> + diff --git a/component/admin/views/category/tmpl/edit_information.php b/component/admin/views/category/tmpl/edit_information.php index ae14d1dfe62..9a0b2ef4f15 100644 --- a/component/admin/views/category/tmpl/edit_information.php +++ b/component/admin/views/category/tmpl/edit_information.php @@ -1,4 +1,5 @@ item->id)->getMedia(); -foreach ($media->getAll() as $mediaItem) -{ - if ($mediaItem->get('scope') == 'full') - { - $fullImage = $mediaItem->get('media_name'); - $fullMediaId = $mediaItem->getId(); - } - elseif ($mediaItem->get('scope') == 'back') - { - $backImage = $mediaItem->get('media_name'); - $backMediaId = $mediaItem->getId(); - } +foreach ($media->getAll() as $mediaItem) { + if ($mediaItem->get('scope') == 'full') { + $fullImage = $mediaItem->get('media_name'); + $fullMediaId = $mediaItem->getId(); + } elseif ($mediaItem->get('scope') == 'back') { + $backImage = $mediaItem->get('media_name'); + $backMediaId = $mediaItem->getId(); + } } ?> @@ -37,15 +34,15 @@

    - form->renderField('name') ?> - form->renderField('parent_id') ?> - form->renderField('published') ?> - form->renderField('products_per_page') ?> - form->renderField('template') ?> - form->renderField('more_template') ?> - form->renderField('compare_template_id') ?> - form->renderField('short_description') ?> - form->renderField('description') ?> + form->renderField('name') ?> + form->renderField('parent_id') ?> + form->renderField('published') ?> + form->renderField('products_per_page') ?> + form->renderField('template') ?> + form->renderField('more_template') ?> + form->renderField('compare_template_id') ?> + form->renderField('short_description') ?> + form->renderField('description') ?>
    @@ -56,18 +53,18 @@
    - item->id, - 'category', - $fullImage, - false, - true, - $fullMediaId - ); - ?> + item->id, + 'category', + $fullImage, + false, + true, + $fullMediaId + ); + ?>
    @@ -78,34 +75,34 @@
    - item->id, - 'category', - $backImage, - false, - true, - $backMediaId - ); - ?> + item->id, + 'category', + $backImage, + false, + true, + $backMediaId + ); + ?>
    - form->renderField('created_by') ?> - form->renderField('created_date') ?> - form->renderField('modified_by') ?> - form->renderField('modified_date') ?> + form->renderField('created_by') ?> + form->renderField('created_date') ?> + form->renderField('modified_by') ?> + form->renderField('modified_date') ?>
    - form->getInput('checked_out'); ?> - form->getInput('checked_out_time'); ?> - form->getInput('level'); ?> - form->getInput('lft'); ?> - form->getInput('rgt'); ?> + form->getInput('checked_out'); ?> + form->getInput('checked_out_time'); ?> + form->getInput('level'); ?> + form->getInput('lft'); ?> + form->getInput('rgt'); ?> diff --git a/component/admin/views/category/tmpl/edit_product_filter.php b/component/admin/views/category/tmpl/edit_product_filter.php index 139ff6edba5..991dd5e16b4 100644 --- a/component/admin/views/category/tmpl/edit_product_filter.php +++ b/component/admin/views/category/tmpl/edit_product_filter.php @@ -1,4 +1,5 @@ item->id)->getProducts(true); -if (!empty($productList)) -{ - foreach ($productList as $product) - { - $productsFilter[] = $product->product_id; - } +if (!empty($productList)) { + foreach ($productList as $product) { + $productsFilter[] = $product->product_id; + } } $registry = new JRegistry; @@ -31,28 +30,26 @@

    - form->getFieldset('filters') as $field) : ?> -
    - fieldname == 'product_attributes') - { - $options['product_ids'] = $productsFilter; - } - - $value = $filterParams->get($field->fieldname); - - if ($field->type === 'Radio' && empty($value)) - { - $value = 0; - } - - $field->setValue($value, true); - ?> - renderField($options); ?> -
    - + form->getFieldset('filters') as $field) : ?> +
    + fieldname == 'product_attributes') { + $options['product_ids'] = $productsFilter; + } + + $value = $filterParams->get($field->fieldname); + + if ($field->type === 'Radio' && empty($value)) { + $value = 0; + } + + $field->setValue($value, true); + ?> + renderField($options); ?> +
    +
    diff --git a/component/admin/views/category/tmpl/edit_seo.php b/component/admin/views/category/tmpl/edit_seo.php index 5fdff9a5dab..5623fece0a5 100644 --- a/component/admin/views/category/tmpl/edit_seo.php +++ b/component/admin/views/category/tmpl/edit_seo.php @@ -1,4 +1,5 @@
    - form->getFieldset('seo') as $field) : ?> - hidden) : ?> - input ?> - + form->getFieldset('seo') as $field) : ?> + hidden) : ?> + input ?> +
    - form->renderField($field->fieldname) ?> + form->renderField($field->fieldname) ?>
    - +
    diff --git a/component/admin/views/category/tmpl/index.html b/component/admin/views/category/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/category/tmpl/index.html +++ b/component/admin/views/category/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/category/view.html.php b/component/admin/views/category/view.html.php index 6e0d772e392..6c374a19c3f 100644 --- a/component/admin/views/category/view.html.php +++ b/component/admin/views/category/view.html.php @@ -20,152 +20,147 @@ */ class RedshopViewCategory extends RedshopViewForm { - /** - * @var integer - * - * @since 2.1.2 - */ - protected $is_new = 0; - - /** - * Execute and display a template script. - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return mixed A string if successful, otherwise an Error object. - * - * @see JViewLegacy::loadTemplate() - * @since 12.2 - * - * @throws Exception - */ - public function display($tpl = null) - { - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/redshop.validation.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/redshop.fields.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/json.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/json.min.js', false, true); - - $model = $this->getModel('category'); - - // Initialise variables. - $this->item = $this->get('Item'); - $this->state = $this->get('State'); - - // Accessory of Category - $categoryAccessoryProduct = array(); - - if ($this->item->id) - { - $categoryAccessoryProduct = RedshopHelperAccessory::getProductAccessories(0, 0, 0, $this->item->id); - } - else - { - $this->is_new = 1; - } - - $this->lists['categroy_accessory_product'] = $categoryAccessoryProduct; - $this->extraFields = $model->getExtraFields($this->item); - $this->tabmenu = $this->getTabMenu(); - - // Check for errors. - if (count($errors = $this->get('Errors'))) - { - throw new Exception(implode("\n", $errors)); - } - - parent::display($tpl); - } - - /** - * Tab Menu - * - * @return object Tab menu - * - * @since 1.7 - * @throws Exception - */ - private function getTabMenu() - { - $tabMenu = new RedshopMenu(); - - $tabMenu->section('tab') - ->title('COM_REDSHOP_CATEGORY_INFORMATION') - ->addItem( - '#information', - 'COM_REDSHOP_CATEGORY_INFORMATION', - true, - 'information' - )->addItem( - '#seo', - 'COM_REDSHOP_META_DATA_TAB', - false, - 'seo' - )->addItem( - '#extrafield', - 'COM_REDSHOP_FIELDS', - false, - 'extrafield' - )->addItem( - '#accessory', - 'COM_REDSHOP_ACCESSORY_PRODUCT', - false, - 'accessory' - )->addItem( - '#product_filter', - 'COM_REDSHOP_PRODUCT_FILTERS', - false, - 'product_filter' - ); - - return $tabMenu; - } - - /** - * Add the page title and toolbar. - * - * @return void - * - * @since 1.6 - * @throws Exception - */ - protected function addToolbar() - { - JFactory::getApplication()->input->set('hidemainmenu', true); - $user = JFactory::getUser(); - - if ($this->is_new && (!empty($user->authorise('com_redshop', 'core.create')))) - { - JToolbarHelper::apply('category.apply'); - JToolbarHelper::save('category.save'); - JToolbarHelper::save2new('category.save2new'); - JToolbarHelper::cancel('category.cancel'); - } - else - { - // Since it's an existing record, check the edit permission, or fall back to edit own if the owner. - if ((!empty($user->authorise('com_redshop', 'core.edit')))) - { - JToolbarHelper::apply('category.apply'); - JToolbarHelper::save('category.save'); - - // We can save this record, but check the create permission to see if we can return to make a new one. - if ((!empty($user->authorise('com_redshop', 'core.create')))) - { - JToolbarHelper::save2new('category.save2new'); - } - } - - JToolbarHelper::cancel('category.cancel', JText::_('JTOOLBAR_CLOSE')); - - $itemId = (int) RedshopHelperRouter::getCategoryItemid($this->item->id); - - $link = JURI::root() . 'index.php?option=com_redshop' - . '&view=&view=category&layout=detail' - . '&cid=' . $this->item->id - . '&Itemid=' . $itemId; - - RedshopToolbarHelper::link($link, 'preview', 'JGLOBAL_PREVIEW', '_blank'); - } - } + /** + * @var integer + * + * @since 2.1.2 + */ + protected $is_new = 0; + + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise an Error object. + * + * @throws Exception + * @since 12.2 + * + * @see JViewLegacy::loadTemplate() + */ + public function display($tpl = null) + { + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.validation.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.fields.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/json.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/json.min.js', false, true); + + $model = $this->getModel('category'); + + // Initialise variables. + $this->item = $this->get('Item'); + $this->state = $this->get('State'); + + // Accessory of Category + $categoryAccessoryProduct = array(); + + if ($this->item->id) { + $categoryAccessoryProduct = RedshopHelperAccessory::getProductAccessories(0, 0, 0, $this->item->id); + } else { + $this->is_new = 1; + } + + $this->lists['categroy_accessory_product'] = $categoryAccessoryProduct; + $this->extraFields = $model->getExtraFields($this->item); + $this->tabmenu = $this->getTabMenu(); + + // Check for errors. + if (count($errors = $this->get('Errors'))) { + throw new Exception(implode("\n", $errors)); + } + + parent::display($tpl); + } + + /** + * Tab Menu + * + * @return object Tab menu + * + * @throws Exception + * @since 1.7 + */ + private function getTabMenu() + { + $tabMenu = new RedshopMenu(); + + $tabMenu->section('tab') + ->title('COM_REDSHOP_CATEGORY_INFORMATION') + ->addItem( + '#information', + 'COM_REDSHOP_CATEGORY_INFORMATION', + true, + 'information' + )->addItem( + '#seo', + 'COM_REDSHOP_META_DATA_TAB', + false, + 'seo' + )->addItem( + '#extrafield', + 'COM_REDSHOP_FIELDS', + false, + 'extrafield' + )->addItem( + '#accessory', + 'COM_REDSHOP_ACCESSORY_PRODUCT', + false, + 'accessory' + )->addItem( + '#product_filter', + 'COM_REDSHOP_PRODUCT_FILTERS', + false, + 'product_filter' + ); + + return $tabMenu; + } + + /** + * Add the page title and toolbar. + * + * @return void + * + * @throws Exception + * @since 1.6 + */ + protected function addToolbar() + { + JFactory::getApplication()->input->set('hidemainmenu', true); + $user = JFactory::getUser(); + + if ($this->is_new && (!empty($user->authorise('com_redshop', 'core.create')))) { + JToolbarHelper::apply('category.apply'); + JToolbarHelper::save('category.save'); + JToolbarHelper::save2new('category.save2new'); + JToolbarHelper::cancel('category.cancel'); + } else { + // Since it's an existing record, check the edit permission, or fall back to edit own if the owner. + if ((!empty($user->authorise('com_redshop', 'core.edit')))) { + JToolbarHelper::apply('category.apply'); + JToolbarHelper::save('category.save'); + + // We can save this record, but check the create permission to see if we can return to make a new one. + if ((!empty($user->authorise('com_redshop', 'core.create')))) { + JToolbarHelper::save2new('category.save2new'); + } + } + + JToolbarHelper::cancel('category.cancel', JText::_('JTOOLBAR_CLOSE')); + + $itemId = (int)RedshopHelperRouter::getCategoryItemid($this->item->id); + + $link = JURI::root() . 'index.php?option=com_redshop' + . '&view=&view=category&layout=detail' + . '&cid=' . $this->item->id + . '&Itemid=' . $itemId; + + RedshopToolbarHelper::link($link, 'preview', 'JGLOBAL_PREVIEW', '_blank'); + } + } } diff --git a/component/admin/views/configuration/index.html b/component/admin/views/configuration/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/configuration/index.html +++ b/component/admin/views/configuration/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/configuration/tmpl/default.php b/component/admin/views/configuration/tmpl/default.php index 1260f8157bc..aadfe2c9f4c 100644 --- a/component/admin/views/configuration/tmpl/default.php +++ b/component/admin/views/configuration/tmpl/default.php @@ -1,4 +1,5 @@ getUserState('com_redshop.configuration.selectedTabPosition', 'general'); -if ($app->input->getInt('dashboard', 0)) -{ - $selectedTabPosition = 'dashboard'; +if ($app->input->getInt('dashboard', 0)) { + $selectedTabPosition = 'dashboard'; } ?>
    - $this, - 'tabMenu' => $this->tabmenu->getData('tab')->items, - ) - ); - ?> - - - - - - - + enctype="multipart/form-data"> + $this, + 'tabMenu' => $this->tabmenu->getData('tab')->items, + ) + ); + ?> + + + + + + +
    diff --git a/component/admin/views/configuration/tmpl/default_accessory_product.php b/component/admin/views/configuration/tmpl/default_accessory_product.php index 301d08e6dcf..2a1c065bc88 100644 --- a/component/admin/views/configuration/tmpl/default_accessory_product.php +++ b/component/admin/views/configuration/tmpl/default_accessory_product.php @@ -1,4 +1,5 @@
    - JText::_('COM_REDSHOP_ACCESSORY_AS_PRODUCT_IN_CART_ENABLE_LBL'), - 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_AS_PRODUCT_IN_CART_ENABLE_LBL'), - 'field' => $this->lists['accessory_as_product_in_cart_enable'] - ) - ); - echo RedshopLayoutHelper::render( - 'config.config', - array( - 'title' => JText::_('COM_REDSHOP_ACCESSORY_PRODUCT_IN_LIGHTBOX_LBL'), - 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_PRODUCT_IN_LIGHTBOX_LBL'), - 'field' => $this->lists['accessory_product_in_lightbox'] - ) - ); - echo RedshopLayoutHelper::render( - 'config.config', - array( - 'title' => JText::_('COM_REDSHOP_ACCESSORY_PRODUCT_ORDERING_METHOD_LBL'), - 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_PRODUCT_ORDERING_METHOD_LBL'), - 'field' => $this->lists['default_accessory_ordering_method'] - ) - ); - echo RedshopLayoutHelper::render( - 'config.config', - array( - 'title' => JText::_('COM_REDSHOP_ACCESSORY_PRODUCT_DESC_MAX_CHARS_LBL'), - 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_PRODUCT_DESC_MAX_CHARS_LBL'), - 'field' => '' - ) - ); - echo RedshopLayoutHelper::render( - 'config.config', - array( - 'title' => JText::_('COM_REDSHOP_ACCESSORY_PRODUCT_DESC_END_SUFFIX_LBL'), - 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_PRODUCT_DESC_END_SUFFIX_LBL'), - 'field' => '' - ) - ); - echo RedshopLayoutHelper::render( - 'config.config', - array( - 'title' => JText::_('COM_REDSHOP_ACCESSORY_PRODUCT_TITLE_MAX_CHARS_LBL'), - 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_PRODUCT_TITLE_MAX_CHARS_LBL'), - 'field' => '' - ) - ); - echo RedshopLayoutHelper::render( - 'config.config', - array( - 'title' => JText::_('COM_REDSHOP_ACCESSORY_PRODUCT_TITLE_END_SUFFIX_LBL'), - 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_PRODUCT_TITLE_END_SUFFIX_LBL'), - 'line' => false, - 'field' => '' - ) - ); - ?> + JText::_('COM_REDSHOP_ACCESSORY_AS_PRODUCT_IN_CART_ENABLE_LBL'), + 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_AS_PRODUCT_IN_CART_ENABLE_LBL'), + 'field' => $this->lists['accessory_as_product_in_cart_enable'] + ) + ); + echo RedshopLayoutHelper::render( + 'config.config', + array( + 'title' => JText::_('COM_REDSHOP_ACCESSORY_PRODUCT_IN_LIGHTBOX_LBL'), + 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_PRODUCT_IN_LIGHTBOX_LBL'), + 'field' => $this->lists['accessory_product_in_lightbox'] + ) + ); + echo RedshopLayoutHelper::render( + 'config.config', + array( + 'title' => JText::_('COM_REDSHOP_ACCESSORY_PRODUCT_ORDERING_METHOD_LBL'), + 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_PRODUCT_ORDERING_METHOD_LBL'), + 'field' => $this->lists['default_accessory_ordering_method'] + ) + ); + echo RedshopLayoutHelper::render( + 'config.config', + array( + 'title' => JText::_('COM_REDSHOP_ACCESSORY_PRODUCT_DESC_MAX_CHARS_LBL'), + 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_PRODUCT_DESC_MAX_CHARS_LBL'), + 'field' => '' + ) + ); + echo RedshopLayoutHelper::render( + 'config.config', + array( + 'title' => JText::_('COM_REDSHOP_ACCESSORY_PRODUCT_DESC_END_SUFFIX_LBL'), + 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_PRODUCT_DESC_END_SUFFIX_LBL'), + 'field' => '' + ) + ); + echo RedshopLayoutHelper::render( + 'config.config', + array( + 'title' => JText::_('COM_REDSHOP_ACCESSORY_PRODUCT_TITLE_MAX_CHARS_LBL'), + 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_PRODUCT_TITLE_MAX_CHARS_LBL'), + 'field' => '' + ) + ); + echo RedshopLayoutHelper::render( + 'config.config', + array( + 'title' => JText::_('COM_REDSHOP_ACCESSORY_PRODUCT_TITLE_END_SUFFIX_LBL'), + 'desc' => JText::_('COM_REDSHOP_TOOLTIP_ACCESSORY_PRODUCT_TITLE_END_SUFFIX_LBL'), + 'line' => false, + 'field' => '' + ) + ); + ?>
    @@ -86,21 +95,26 @@
    -

    +

    -
    + + + diff --git a/component/admin/views/statistic/view.html.php b/component/admin/views/statistic/view.html.php index 0832233e99c..4ed20eef38e 100644 --- a/component/admin/views/statistic/view.html.php +++ b/component/admin/views/statistic/view.html.php @@ -15,196 +15,187 @@ * The Statistic view * * @package RedSHOP.Backend - * @subpackage Statistic.View + * @subpackage Statistic.View * @since 2.0.6 */ class RedshopViewStatistic extends RedshopViewAdmin { - /** - * @var JPagination - */ - public $pagination; - - /** - * Execute and display a template script. - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return mixed A string if successful, otherwise a Error object. - * - * @throws Exception - */ - public function display($tpl = null) - { - global $context; - - $uri = JUri::getInstance(); - $app = JFactory::getApplication(); - $document = JFactory::getDocument(); - - $layout = $app->input->getCmd('layout', ''); - - $startdate = $app->input->getInt('startdate', 0); - $enddate = $app->input->getInt('enddate', 0); - - $filteroption = $app->input->getInt('filteroption', 0); - $typeoption = $app->input->getInt('typeoption', 2); - - $lists = array(); - $option = array(); - - $option[] = JHtml::_('select.option', '0', JText::_('COM_REDSHOP_Select')); - $option[] = JHtml::_('select.option', '1', JText::_('COM_REDSHOP_DAILY')); - $option[] = JHtml::_('select.option', '2', JText::_('COM_REDSHOP_WEEKLY')); - $option[] = JHtml::_('select.option', '3', JText::_('COM_REDSHOP_MONTHLY')); - $option[] = JHtml::_('select.option', '4', JText::_('COM_REDSHOP_YEARLY')); - - $type[] = JHtml::_('select.option', '1', JText::_('COM_REDSHOP_NUMBER_OF_TIMES_SOLD')); - $type[] = JHtml::_('select.option', '2', JText::_('COM_REDSHOP_NUMBER_OF_ITEMS_SOLD')); - - $lists['filteroption'] = JHtml::_('select.genericlist', $option, 'filteroption', - 'class="inputbox" size="1" onchange="document.adminForm.submit();" ', 'value', 'text', $filteroption - ); - - $lists['typeoption'] = JHtml::_('select.genericlist', $type, 'typeoption', - 'class="inputbox" size="1" onchange="document.adminForm.submit();" ', 'value', 'text', $typeoption - ); - - $redshopviewer = array(); - $pageviewer = array(); - $avgorderamount = array(); - $popularsell = array(); - $bestsell = array(); - $newprod = array(); - $neworder = array(); - $totalturnover = array(); - $amountorder = array(); - $amountprice = array(); - $amountspentintotal = array(); - - $limitstart = $app->getUserStateFromRequest($context . 'limitstart', 'limitstart', '0'); - $limit = $app->getUserStateFromRequest($context . 'limit', 'limit', '10'); - - if ($layout == 'turnover') - { - $this->setLayout('turnover'); - $title = JText::_('COM_REDSHOP_TOTAL_TURNOVER'); - $totalturnover = $this->get('TotalTurnover'); - $total = count($totalturnover); - } - elseif ($layout == 'pageview') - { - $this->setLayout('pageview'); - $title = JText::_('COM_REDSHOP_TOTAL_PAGEVIEWERS'); - $pageviewer = $this->get('PageViewer'); - $total = count($pageviewer); - } - elseif ($layout == 'amountorder') - { - $this->setLayout('amountorder'); - $title = JText::_('COM_REDSHOP_TOP_CUSTOMER_AMOUNT_OF_ORDER'); - $amountorder = $this->get('AmountOrder'); - $total = count($amountorder); - } - elseif ($layout == 'avrgorder') - { - $this->setLayout('avrgorder'); - $title = JText::_('COM_REDSHOP_AVG_ORDER_AMOUNT_CUSTOMER'); - $avgorderamount = $this->get('AvgOrderAmount'); - $total = count($avgorderamount); - } - elseif ($layout == 'amountprice') - { - $this->setLayout('amountprice'); - $title = JText::_('COM_REDSHOP_TOP_CUSTOMER_AMOUNT_OF_PRICE_PER_ORDER'); - $amountprice = $this->get('AmountPrice'); - $total = count($amountprice); - } - elseif ($layout == 'amountspent') - { - $this->setLayout('amountspent'); - $title = JText::_('COM_REDSHOP_TOP_CUSTOMER_AMOUNT_SPENT_IN_TOTAL'); - $amountspentintotal = $this->get('AmountSpentInTotal'); - $total = count($amountspentintotal); - } - elseif ($layout == 'bestsell') - { - $this->setLayout('bestsell'); - $title = JText::_('COM_REDSHOP_BEST_SELLERS'); - $bestsell = $this->get('BestSellers'); - $total = count($bestsell); - } - elseif ($layout == 'popularsell') - { - $this->setLayout('popularsell'); - $title = JText::_('COM_REDSHOP_MOST_VISITED_PRODUCTS'); - $popularsell = $this->get('MostPopular'); - $total = count($popularsell); - } - elseif ($layout == 'newprod') - { - $this->setLayout('newprod'); - $title = JText::_('COM_REDSHOP_NEWEST_PRODUCTS'); - $newprod = $this->get('NewProducts'); - $total = count($newprod); - } - elseif ($layout == 'neworder') - { - $this->setLayout('neworder'); - $title = JText::_('COM_REDSHOP_NEWEST_ORDERS'); - $neworder = $this->get('NewOrders'); - $total = count($neworder); - } - else - { - $this->setLayout('default'); - $title = JText::_('COM_REDSHOP_TOTAL_VISITORS'); - $redshopviewer = $this->get('RedshopViewer'); - $total = count($redshopviewer); - } - - $document->setTitle(JText::_('COM_REDSHOP_STATISTIC')); - - $pagination = new JPagination($total, $limitstart, $limit); - $this->pagination = $pagination; - - $this->startdate = $startdate; - $this->enddate = $enddate; - - $this->popularsell = $popularsell; - $this->bestsell = $bestsell; - $this->avgorderamount = $avgorderamount; - $this->newprod = $newprod; - $this->neworder = $neworder; - $this->totalturnover = $totalturnover; - $this->amountorder = $amountorder; - $this->amountprice = $amountprice; - $this->amountspentintotal = $amountspentintotal; - $this->redshopviewer = $redshopviewer; - $this->pageviewer = $pageviewer; - $this->lists = $lists; - $this->filteroption = $filteroption; - $this->typeoption = $typeoption; - $this->layout = $layout; - $this->request_url = $uri->toString(); - $this->title = $title; - - $this->addToolbar(); - parent::display($tpl); - } - - /** - * Add the page title and toolbar. - * - * @return void - * - * @since 1.6 - * - * @throws Exception - */ - protected function addToolbar() - { - JFactory::getApplication()->input->set('hidemainmenu', true); - JToolBarHelper::title($this->title, 'statistic redshop_statistic48'); - } + /** + * @var JPagination + */ + public $pagination; + + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise a Error object. + * + * @throws Exception + */ + public function display($tpl = null) + { + global $context; + + $uri = JUri::getInstance(); + $app = JFactory::getApplication(); + $document = JFactory::getDocument(); + + $layout = $app->input->getCmd('layout', ''); + + $startdate = $app->input->getInt('startdate', 0); + $enddate = $app->input->getInt('enddate', 0); + + $filteroption = $app->input->getInt('filteroption', 0); + $typeoption = $app->input->getInt('typeoption', 2); + + $lists = array(); + $option = array(); + + $option[] = JHtml::_('select.option', '0', JText::_('COM_REDSHOP_Select')); + $option[] = JHtml::_('select.option', '1', JText::_('COM_REDSHOP_DAILY')); + $option[] = JHtml::_('select.option', '2', JText::_('COM_REDSHOP_WEEKLY')); + $option[] = JHtml::_('select.option', '3', JText::_('COM_REDSHOP_MONTHLY')); + $option[] = JHtml::_('select.option', '4', JText::_('COM_REDSHOP_YEARLY')); + + $type[] = JHtml::_('select.option', '1', JText::_('COM_REDSHOP_NUMBER_OF_TIMES_SOLD')); + $type[] = JHtml::_('select.option', '2', JText::_('COM_REDSHOP_NUMBER_OF_ITEMS_SOLD')); + + $lists['filteroption'] = JHtml::_( + 'select.genericlist', + $option, + 'filteroption', + 'class="inputbox" size="1" onchange="document.adminForm.submit();" ', + 'value', + 'text', + $filteroption + ); + + $lists['typeoption'] = JHtml::_( + 'select.genericlist', + $type, + 'typeoption', + 'class="inputbox" size="1" onchange="document.adminForm.submit();" ', + 'value', + 'text', + $typeoption + ); + + $redshopviewer = array(); + $pageviewer = array(); + $avgorderamount = array(); + $popularsell = array(); + $bestsell = array(); + $newprod = array(); + $neworder = array(); + $totalturnover = array(); + $amountorder = array(); + $amountprice = array(); + $amountspentintotal = array(); + + $limitstart = $app->getUserStateFromRequest($context . 'limitstart', 'limitstart', '0'); + $limit = $app->getUserStateFromRequest($context . 'limit', 'limit', '10'); + + if ($layout == 'turnover') { + $this->setLayout('turnover'); + $title = JText::_('COM_REDSHOP_TOTAL_TURNOVER'); + $totalturnover = $this->get('TotalTurnover'); + $total = count($totalturnover); + } elseif ($layout == 'pageview') { + $this->setLayout('pageview'); + $title = JText::_('COM_REDSHOP_TOTAL_PAGEVIEWERS'); + $pageviewer = $this->get('PageViewer'); + $total = count($pageviewer); + } elseif ($layout == 'amountorder') { + $this->setLayout('amountorder'); + $title = JText::_('COM_REDSHOP_TOP_CUSTOMER_AMOUNT_OF_ORDER'); + $amountorder = $this->get('AmountOrder'); + $total = count($amountorder); + } elseif ($layout == 'avrgorder') { + $this->setLayout('avrgorder'); + $title = JText::_('COM_REDSHOP_AVG_ORDER_AMOUNT_CUSTOMER'); + $avgorderamount = $this->get('AvgOrderAmount'); + $total = count($avgorderamount); + } elseif ($layout == 'amountprice') { + $this->setLayout('amountprice'); + $title = JText::_('COM_REDSHOP_TOP_CUSTOMER_AMOUNT_OF_PRICE_PER_ORDER'); + $amountprice = $this->get('AmountPrice'); + $total = count($amountprice); + } elseif ($layout == 'amountspent') { + $this->setLayout('amountspent'); + $title = JText::_('COM_REDSHOP_TOP_CUSTOMER_AMOUNT_SPENT_IN_TOTAL'); + $amountspentintotal = $this->get('AmountSpentInTotal'); + $total = count($amountspentintotal); + } elseif ($layout == 'bestsell') { + $this->setLayout('bestsell'); + $title = JText::_('COM_REDSHOP_BEST_SELLERS'); + $bestsell = $this->get('BestSellers'); + $total = count($bestsell); + } elseif ($layout == 'popularsell') { + $this->setLayout('popularsell'); + $title = JText::_('COM_REDSHOP_MOST_VISITED_PRODUCTS'); + $popularsell = $this->get('MostPopular'); + $total = count($popularsell); + } elseif ($layout == 'newprod') { + $this->setLayout('newprod'); + $title = JText::_('COM_REDSHOP_NEWEST_PRODUCTS'); + $newprod = $this->get('NewProducts'); + $total = count($newprod); + } elseif ($layout == 'neworder') { + $this->setLayout('neworder'); + $title = JText::_('COM_REDSHOP_NEWEST_ORDERS'); + $neworder = $this->get('NewOrders'); + $total = count($neworder); + } else { + $this->setLayout('default'); + $title = JText::_('COM_REDSHOP_TOTAL_VISITORS'); + $redshopviewer = $this->get('RedshopViewer'); + $total = count($redshopviewer); + } + + $document->setTitle(JText::_('COM_REDSHOP_STATISTIC')); + + $pagination = new JPagination($total, $limitstart, $limit); + $this->pagination = $pagination; + + $this->startdate = $startdate; + $this->enddate = $enddate; + + $this->popularsell = $popularsell; + $this->bestsell = $bestsell; + $this->avgorderamount = $avgorderamount; + $this->newprod = $newprod; + $this->neworder = $neworder; + $this->totalturnover = $totalturnover; + $this->amountorder = $amountorder; + $this->amountprice = $amountprice; + $this->amountspentintotal = $amountspentintotal; + $this->redshopviewer = $redshopviewer; + $this->pageviewer = $pageviewer; + $this->lists = $lists; + $this->filteroption = $filteroption; + $this->typeoption = $typeoption; + $this->layout = $layout; + $this->request_url = $uri->toString(); + $this->title = $title; + + $this->addToolbar(); + parent::display($tpl); + } + + /** + * Add the page title and toolbar. + * + * @return void + * + * @throws Exception + * @since 1.6 + * + */ + protected function addToolbar() + { + JFactory::getApplication()->input->set('hidemainmenu', true); + JToolBarHelper::title($this->title, 'statistic redshop_statistic48'); + } } diff --git a/component/admin/views/statistic_customer/index.html b/component/admin/views/statistic_customer/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/statistic_customer/index.html +++ b/component/admin/views/statistic_customer/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/statistic_customer/tmpl/default.php b/component/admin/views/statistic_customer/tmpl/default.php index 65876069863..3b15cb348a6 100644 --- a/component/admin/views/statistic_customer/tmpl/default.php +++ b/component/admin/views/statistic_customer/tmpl/default.php @@ -1,4 +1,5 @@
    -
    -
    -
    - filterForm->getInput('date_range', 'filter') ?> -
    -
    -
    -
    - filterForm->getInput('limit', 'list') ?> -
    -
    -
    - customers)): ?> -
    -
    -

    -
    - -

    -
    -
    - - - - - - - - - - - customers as $i => $row) : ?> - - - - - - - - - - - -
    - - - - - - - -
    - - firstname . ' ' . $row->lastname; ?> - - user_email ?>count ?>total_sale) ?>
    - pagination->getListFooter(); ?> -
    - - - - - - - +
    +
    +
    + filterForm->getInput('date_range', 'filter') ?> +
    +
    +
    +
    + filterForm->getInput('limit', 'list') ?> +
    +
    +
    + customers)): ?> +
    +
    +

    +
    + +

    +
    +
    + + + + + + + + + + + customers as $i => $row) : ?> + + + + + + + + + + + +
    + + + + + + + +
    + + firstname . ' ' . $row->lastname; ?> + + user_email ?>count ?>total_sale) ?>
    + pagination->getListFooter(); ?> +
    + + + + + + +
    diff --git a/component/admin/views/statistic_customer/view.html.php b/component/admin/views/statistic_customer/view.html.php index 248e34a2101..90fb82a0006 100644 --- a/component/admin/views/statistic_customer/view.html.php +++ b/component/admin/views/statistic_customer/view.html.php @@ -18,64 +18,62 @@ */ class RedshopViewStatistic_Customer extends RedshopViewAdmin { - protected $state = array(); + public $customers = array(); + /** + * @var JForm + */ + public $filterForm = null; + protected $state = array(); - public $customers = array(); + /** + * Display the Statistic Customer view + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + */ + public function display($tpl = null) + { + $document = JFactory::getDocument(); + $document->setTitle(JText::_('COM_REDSHOP_STATISTIC_CUSTOMER')); - /** - * @var JForm - */ - public $filterForm = null; + /** @var RedshopModelStatistic_Customer $model */ + $model = $this->getModel(); - /** - * Display the Statistic Customer view - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return void - */ - public function display($tpl = null) - { - $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_STATISTIC_CUSTOMER')); + $this->customers = $model->getItems(); + $this->pagination = $model->getPagination(); + $this->state = $model->getState(); + $this->filterForm = $model->getForm(); - /** @var RedshopModelStatistic_Customer $model */ - $model = $this->getModel(); + $this->addToolbar(); - $this->customers = $model->getItems(); - $this->pagination = $model->getPagination(); - $this->state = $model->getState(); - $this->filterForm = $model->getForm(); + parent::display($tpl); + } - $this->addToolbar(); + /** + * Add the page title and toolbar. + * + * @return void + * + * @since 1.6 + */ + protected function addToolbar() + { + JFactory::getApplication()->input->set('hidemainmenu', true); + JToolBarHelper::title(JText::_('COM_REDSHOP_STATISTIC_CUSTOMER'), 'statistic redshop_statistic48'); - parent::display($tpl); - } - - /** - * Add the page title and toolbar. - * - * @return void - * - * @since 1.6 - */ - protected function addToolbar() - { - JFactory::getApplication()->input->set('hidemainmenu', true); - JToolBarHelper::title(JText::_('COM_REDSHOP_STATISTIC_CUSTOMER'), 'statistic redshop_statistic48'); - - RedshopToolbarHelper::custom( - 'exportCustomer', - 'save.png', - 'save_f2.png', - 'COM_REDSHOP_EXPORT_DATA_LBL', - false - ); - RedshopToolbarHelper::link( - 'index.php?tmpl=component&option=com_redshop&view=statistic_customer', - 'print', - 'COM_REDSHOP_PRINT', - '_blank' - ); - } + RedshopToolbarHelper::custom( + 'exportCustomer', + 'save.png', + 'save_f2.png', + 'COM_REDSHOP_EXPORT_DATA_LBL', + false + ); + RedshopToolbarHelper::link( + 'index.php?tmpl=component&option=com_redshop&view=statistic_customer', + 'print', + 'COM_REDSHOP_PRINT', + '_blank' + ); + } } diff --git a/component/admin/views/statistic_order/index.html b/component/admin/views/statistic_order/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/statistic_order/index.html +++ b/component/admin/views/statistic_order/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/statistic_order/tmpl/default.php b/component/admin/views/statistic_order/tmpl/default.php index 2cb388fcc14..3b288fe569b 100644 --- a/component/admin/views/statistic_order/tmpl/default.php +++ b/component/admin/views/statistic_order/tmpl/default.php @@ -1,4 +1,5 @@ escape($this->state->get('list.direction')); ?>
    -
    -
    -
    - filterForm->getInput('date_range', 'filter') ?> -
    -
    -
    -
    - filterForm->getInput('date_group', 'filter') ?> -
    -
    -
    -
    - filterForm->getInput('limit', 'list') ?> -
    -
    -
    - orders)): ?> -
    -
    -

    -
    - -
    -
    -
    - - - - - - - - - - orders as $i => $row) : ?> - - - - - - - - - - -
    - - - - - -
    viewdate; ?>count; ?>order_total) ?>
    - pagination->getListFooter(); ?> -
    - - - - - - - +
    +
    +
    + filterForm->getInput('date_range', 'filter') ?> +
    +
    +
    +
    + filterForm->getInput('date_group', 'filter') ?> +
    +
    +
    +
    + filterForm->getInput('limit', 'list') ?> +
    +
    +
    + orders)): ?> +
    +
    +

    +
    + +
    +
    +
    + + + + + + + + + + orders as $i => $row) : ?> + + + + + + + + + + +
    + + + + + +
    viewdate; ?>count; ?>order_total + ) ?>
    + pagination->getListFooter(); ?> +
    + + + + + + +
    diff --git a/component/admin/views/statistic_order/view.html.php b/component/admin/views/statistic_order/view.html.php index ca1759558a7..2032565cde3 100644 --- a/component/admin/views/statistic_order/view.html.php +++ b/component/admin/views/statistic_order/view.html.php @@ -18,52 +18,54 @@ */ class RedshopViewStatistic_Order extends RedshopViewAdmin { - /** - * Display the Statistic Customer view - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return void - */ - public function display($tpl = null) - { - $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_STATISTIC_ORDER')); + /** + * Display the Statistic Customer view + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + */ + public function display($tpl = null) + { + $document = JFactory::getDocument(); + $document->setTitle(JText::_('COM_REDSHOP_STATISTIC_ORDER')); - $model = $this->getModel(); + $model = $this->getModel(); - $this->orders = $model->getItems(); - $this->pagination = $model->getPagination(); - $this->state = $model->getState(); - $this->filterForm = $model->getForm(); + $this->orders = $model->getItems(); + $this->pagination = $model->getPagination(); + $this->state = $model->getState(); + $this->filterForm = $model->getForm(); - $this->addToolbar(); + $this->addToolbar(); - parent::display($tpl); - } + parent::display($tpl); + } - /** - * Add the page title and toolbar. - * - * @return void - * - * @since 1.6 - */ - protected function addToolbar() - { - JFactory::getApplication()->input->set('hidemainmenu', true); - JToolBarHelper::title(JText::_('COM_REDSHOP_STATISTIC_ORDER'), 'statistic redshop_statistic48'); - RedshopToolbarHelper::link( - 'index.php?tmpl=component&option=com_redshop&task=statistic_order.exportOrder&date_range=' . $this->state->get('filter.date_range'), - 'save.png', - 'COM_REDSHOP_EXPORT_DATA_LBL', - '_blank' - ); - RedshopToolbarHelper::link( - 'index.php?tmpl=component&option=com_redshop&view=statistic_order', - 'print', - 'COM_REDSHOP_PRINT', - '_blank' - ); - } + /** + * Add the page title and toolbar. + * + * @return void + * + * @since 1.6 + */ + protected function addToolbar() + { + JFactory::getApplication()->input->set('hidemainmenu', true); + JToolBarHelper::title(JText::_('COM_REDSHOP_STATISTIC_ORDER'), 'statistic redshop_statistic48'); + RedshopToolbarHelper::link( + 'index.php?tmpl=component&option=com_redshop&task=statistic_order.exportOrder&date_range=' . $this->state->get( + 'filter.date_range' + ), + 'save.png', + 'COM_REDSHOP_EXPORT_DATA_LBL', + '_blank' + ); + RedshopToolbarHelper::link( + 'index.php?tmpl=component&option=com_redshop&view=statistic_order', + 'print', + 'COM_REDSHOP_PRINT', + '_blank' + ); + } } diff --git a/component/admin/views/statistic_product/index.html b/component/admin/views/statistic_product/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/statistic_product/index.html +++ b/component/admin/views/statistic_product/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/statistic_product/tmpl/default.php b/component/admin/views/statistic_product/tmpl/default.php index 0f2ab986d26..2fe7af3f223 100644 --- a/component/admin/views/statistic_product/tmpl/default.php +++ b/component/admin/views/statistic_product/tmpl/default.php @@ -15,108 +15,145 @@ $listDirn = $this->escape($this->state->get('list.direction')); ?>
    -
    -
    -
    - filterForm->getInput('date_range', 'filter') ?> -
    -
    -
    -
    - filterForm->getInput('limit', 'list') ?> -
    -
    -
    - products)): ?> -
    -
    -

    -
    - -
    -
    - - - - - - - - - - - - - products as $i => $row) : ?> - - - - - - - - - - - - - -
    - product_name; ?> - product_number ?>manufacturer_name ?>order_count ?>unit_sold ?>total_sale); ?>
    - pagination->getListFooter(); ?> -
    - - - - - - - +
    +
    +
    + filterForm->getInput('date_range', 'filter') ?> +
    +
    +
    +
    + filterForm->getInput('limit', 'list') ?> +
    +
    +
    + products)): ?> +
    +
    +

    +
    + +
    +
    + + + + + + + + + + + + + products as $i => $row) : ?> + + + + + + + + + + + + + +
    + product_name; ?> + product_number ?>manufacturer_name ?>order_count ?>unit_sold ?>total_sale); ?>
    + pagination->getListFooter(); ?> +
    + + + + + + +
    diff --git a/component/admin/views/statistic_product/view.html.php b/component/admin/views/statistic_product/view.html.php index bdde6848c44..060b88b5f45 100644 --- a/component/admin/views/statistic_product/view.html.php +++ b/component/admin/views/statistic_product/view.html.php @@ -18,54 +18,54 @@ */ class RedshopViewStatistic_Product extends RedshopViewAdmin { - /** - * Display the Statistic Customer view - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return void - */ - public function display($tpl = null) - { - $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_STATISTIC_PRODUCT')); + /** + * Display the Statistic Customer view + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + */ + public function display($tpl = null) + { + $document = JFactory::getDocument(); + $document->setTitle(JText::_('COM_REDSHOP_STATISTIC_PRODUCT')); - $model = $this->getModel(); + $model = $this->getModel(); - $this->products = $model->getItems(); - $this->pagination = $model->getPagination(); - $this->state = $model->getState(); - $this->filterForm = $model->getForm(); + $this->products = $model->getItems(); + $this->pagination = $model->getPagination(); + $this->state = $model->getState(); + $this->filterForm = $model->getForm(); - $this->addToolbar(); + $this->addToolbar(); - parent::display($tpl); - } + parent::display($tpl); + } - /** - * Add the page title and toolbar. - * - * @return void - * - * @since 1.6 - */ - protected function addToolbar() - { - JFactory::getApplication()->input->set('hidemainmenu', true); - JToolBarHelper::title(JText::_('COM_REDSHOP_STATISTIC_PRODUCT'), 'statistic redshop_statistic48'); + /** + * Add the page title and toolbar. + * + * @return void + * + * @since 1.6 + */ + protected function addToolbar() + { + JFactory::getApplication()->input->set('hidemainmenu', true); + JToolBarHelper::title(JText::_('COM_REDSHOP_STATISTIC_PRODUCT'), 'statistic redshop_statistic48'); - RedshopToolbarHelper::custom( - 'exportProduct', - 'save.png', - 'save_f2.png', - 'COM_REDSHOP_EXPORT_DATA_LBL', - false - ); - RedshopToolbarHelper::link( - 'index.php?tmpl=component&option=com_redshop&view=statistic_product', - 'print', - 'COM_REDSHOP_PRINT', - '_blank' - ); - } + RedshopToolbarHelper::custom( + 'exportProduct', + 'save.png', + 'save_f2.png', + 'COM_REDSHOP_EXPORT_DATA_LBL', + false + ); + RedshopToolbarHelper::link( + 'index.php?tmpl=component&option=com_redshop&view=statistic_product', + 'print', + 'COM_REDSHOP_PRINT', + '_blank' + ); + } } diff --git a/component/admin/views/statistic_quotation/index.html b/component/admin/views/statistic_quotation/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/statistic_quotation/index.html +++ b/component/admin/views/statistic_quotation/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/statistic_quotation/tmpl/default.php b/component/admin/views/statistic_quotation/tmpl/default.php index ecad707a44b..230f85423bf 100644 --- a/component/admin/views/statistic_quotation/tmpl/default.php +++ b/component/admin/views/statistic_quotation/tmpl/default.php @@ -1,4 +1,5 @@ addScript('//www.gstatic.com/charts/loader.js'); ?>
    -
    - - - - -
    -
    - - - - - -
    -
    -
    - - - - - - - - - quotations as $i => $row) : ?> - - - - - - -
    viewdate; ?>count; ?>quotation_total);?>
    -
    - - +
    + + + + +
    +
    + + + + + +
    +
    +
    + + + + + + + + + quotations as $i => $row) : ?> + + + + + + +
    viewdate; ?>count; ?>quotation_total + ); ?>
    +
    + +
    diff --git a/component/admin/views/statistic_quotation/view.html.php b/component/admin/views/statistic_quotation/view.html.php index 33e3e9bb49f..c92123bae16 100644 --- a/component/admin/views/statistic_quotation/view.html.php +++ b/component/admin/views/statistic_quotation/view.html.php @@ -18,59 +18,65 @@ */ class RedshopViewStatistic_Quotation extends RedshopViewAdmin { - /** - * Display the Statistic Customer view - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return void - */ - public function display($tpl = null) - { - global $context; + /** + * Display the Statistic Customer view + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + */ + public function display($tpl = null) + { + global $context; - $uri = JFactory::getURI(); - $app = JFactory::getApplication(); - $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_STATISTIC_QUOTATION')); - /** @scrutinizer ignore-deprecated */JHtml::stylesheet('com_redshop/daterangepicker.min.css', array(), true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/moment.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/daterangepicker.min.js', false, true); + $uri = JFactory::getURI(); + $app = JFactory::getApplication(); + $document = JFactory::getDocument(); + $document->setTitle(JText::_('COM_REDSHOP_STATISTIC_QUOTATION')); + /** @scrutinizer ignore-deprecated */ + JHtml::stylesheet('com_redshop/daterangepicker.min.css', array(), true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/moment.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/daterangepicker.min.js', false, true); - $this->quotations = $this->get('Quotations'); - $this->filterStartDate = $app->input->getString('filter_start_date', ''); - $this->filterEndDate = $app->input->getString('filter_end_date', ''); - $this->filterDateLabel = $app->input->getString('filter_date_label', ''); + $this->quotations = $this->get('Quotations'); + $this->filterStartDate = $app->input->getString('filter_start_date', ''); + $this->filterEndDate = $app->input->getString('filter_end_date', ''); + $this->filterDateLabel = $app->input->getString('filter_date_label', ''); - $this->addToolbar(); - parent::display($tpl); - } + $this->addToolbar(); + parent::display($tpl); + } - /** - * Add the page title and toolbar. - * - * @return void - * - * @since 1.6 - */ - protected function addToolbar() - { - $title = JText::_('COM_REDSHOP_STATISTIC_QUOTATION'); - JFactory::getApplication()->input->set('hidemainmenu', true); - JToolBarHelper::title(JText::_('COM_REDSHOP_STATISTIC_QUOTATION') . " :: " . $title, 'statistic redshop_statistic48'); + /** + * Add the page title and toolbar. + * + * @return void + * + * @since 1.6 + */ + protected function addToolbar() + { + $title = JText::_('COM_REDSHOP_STATISTIC_QUOTATION'); + JFactory::getApplication()->input->set('hidemainmenu', true); + JToolBarHelper::title( + JText::_('COM_REDSHOP_STATISTIC_QUOTATION') . " :: " . $title, + 'statistic redshop_statistic48' + ); - RedshopToolbarHelper::custom( - 'exportQuotation', - 'save.png', - 'save_f2.png', - 'COM_REDSHOP_EXPORT_DATA_LBL', - false - ); - RedshopToolbarHelper::link( - 'index.php?tmpl=component&option=com_redshop&view=statistic_quotation', - 'print', - 'COM_REDSHOP_PRINT', - '_blank' - ); - } + RedshopToolbarHelper::custom( + 'exportQuotation', + 'save.png', + 'save_f2.png', + 'COM_REDSHOP_EXPORT_DATA_LBL', + false + ); + RedshopToolbarHelper::link( + 'index.php?tmpl=component&option=com_redshop&view=statistic_quotation', + 'print', + 'COM_REDSHOP_PRINT', + '_blank' + ); + } } diff --git a/component/admin/views/statistic_variant/index.html b/component/admin/views/statistic_variant/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/statistic_variant/index.html +++ b/component/admin/views/statistic_variant/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/statistic_variant/tmpl/default.php b/component/admin/views/statistic_variant/tmpl/default.php index 412038f5eb0..9eb18edd2ea 100644 --- a/component/admin/views/statistic_variant/tmpl/default.php +++ b/component/admin/views/statistic_variant/tmpl/default.php @@ -1,4 +1,5 @@ addScript('//www.gstatic.com/charts/loader.js'); $total = 0; -foreach ($this->productVariants as $itemId => $data) -{ - $total += $data['total_sale']; +foreach ($this->productVariants as $itemId => $data) { + $total += $data['total_sale']; } ?>
    -
    - - - - -
    -
    - - - - - -
    -
    -
    - - - - - - - - - - - - 0) :?> - productVariants as $itemId => $data) : - $row = (object) $data; - ?> - total_sale)) : ?> - - - - - - - - - - - -
    viewdate; ?>product_name; ?>product_attribute; ?>product_attribute_sku; ?>unit_sold; ?>total_sale); ?>
    -
    - - +
    + + + + +
    +
    + + + + + +
    +
    +
    + + + + + + + + + + + + 0) : ?> + productVariants as $itemId => $data) : + $row = (object)$data; + ?> + total_sale)) : ?> + + + + + + + + + + + +
    viewdate; ?>product_name; ?> + product_attribute; ?>product_attribute_sku; ?>unit_sold; ?>total_sale + ); ?>
    +
    + +
    diff --git a/component/admin/views/statistic_variant/view.html.php b/component/admin/views/statistic_variant/view.html.php index afaac36f732..0dcc872386e 100644 --- a/component/admin/views/statistic_variant/view.html.php +++ b/component/admin/views/statistic_variant/view.html.php @@ -18,61 +18,65 @@ */ class RedshopViewStatistic_Variant extends RedshopViewAdmin { - /** - * Display the Statistic Customer view - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return void - */ - public function display($tpl = null) - { - global $context; + /** + * Display the Statistic Customer view + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void + */ + public function display($tpl = null) + { + global $context; - $uri = JFactory::getURI(); - $app = JFactory::getApplication(); - $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_STATISTIC_PRODUCT_VARIANT')); - /** @scrutinizer ignore-deprecated */JHtml::stylesheet('com_redshop/daterangepicker.min.css', array(), true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/moment.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/daterangepicker.min.js', false, true); + $uri = JFactory::getURI(); + $app = JFactory::getApplication(); + $document = JFactory::getDocument(); + $document->setTitle(JText::_('COM_REDSHOP_STATISTIC_PRODUCT_VARIANT')); + /** @scrutinizer ignore-deprecated */ + JHtml::stylesheet('com_redshop/daterangepicker.min.css', array(), true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/moment.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/daterangepicker.min.js', false, true); - $this->productVariants = $this->get('ProductVariants'); - $this->filterStartDate = $app->input->getString('filter_start_date', ''); - $this->filterEndDate = $app->input->getString('filter_end_date', ''); - $this->filterDateLabel = $app->input->getString('filter_date_label', ''); + $this->productVariants = $this->get('ProductVariants'); + $this->filterStartDate = $app->input->getString('filter_start_date', ''); + $this->filterEndDate = $app->input->getString('filter_end_date', ''); + $this->filterDateLabel = $app->input->getString('filter_date_label', ''); - $this->addToolbar(); - parent::display($tpl); - } + $this->addToolbar(); + parent::display($tpl); + } - /** - * Add the page title and toolbar. - * - * @return void - * - * @since 1.6 - */ - protected function addToolbar() - { - $title = JText::_('COM_REDSHOP_STATISTIC_PRODUCT_VARIANT'); - JFactory::getApplication()->input->set('hidemainmenu', true); - JToolBarHelper::title( - JText::_('COM_REDSHOP_STATISTIC_PRODUCT_VARIANT') . " :: " . $title, 'statistic redshop_statistic48' - ); + /** + * Add the page title and toolbar. + * + * @return void + * + * @since 1.6 + */ + protected function addToolbar() + { + $title = JText::_('COM_REDSHOP_STATISTIC_PRODUCT_VARIANT'); + JFactory::getApplication()->input->set('hidemainmenu', true); + JToolBarHelper::title( + JText::_('COM_REDSHOP_STATISTIC_PRODUCT_VARIANT') . " :: " . $title, + 'statistic redshop_statistic48' + ); - RedshopToolbarHelper::custom( - 'exportProductVariant', - 'save.png', - 'save_f2.png', - 'COM_REDSHOP_EXPORT_DATA_LBL', - false - ); - RedshopToolbarHelper::link( - 'index.php?tmpl=component&option=com_redshop&view=statistic_variant', - 'print', - 'COM_REDSHOP_PRINT', - '_blank' - ); - } + RedshopToolbarHelper::custom( + 'exportProductVariant', + 'save.png', + 'save_f2.png', + 'COM_REDSHOP_EXPORT_DATA_LBL', + false + ); + RedshopToolbarHelper::link( + 'index.php?tmpl=component&option=com_redshop&view=statistic_variant', + 'print', + 'COM_REDSHOP_PRINT', + '_blank' + ); + } } diff --git a/component/admin/views/stockimage/tmpl/default.php b/component/admin/views/stockimage/tmpl/default.php index 2276c46aadb..226473cf024 100644 --- a/component/admin/views/stockimage/tmpl/default.php +++ b/component/admin/views/stockimage/tmpl/default.php @@ -21,79 +21,112 @@
    -
    -
    -
    -
    - - " /> - -
    -
    -
    +
    +
    +
    +
    + + "/> + +
    +
    +
    - - - - - - - - - - - - - - data); $i < $n; $i++) - { - $row = $this->data[$i]; - $row->id = $row->stock_amount_id; +
    lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']);?>
    + + + + + + + + + + + + + data); $i < $n; $i++) { + $row = $this->data[$i]; + $row->id = $row->stock_amount_id; - $thumbUrl = RedshopHelperMedia::getImagePath( - $row->stock_amount_image, - '', - 'thumb', - 'stockroom', - Redshop::getConfig()->get('DEFAULT_STOCKAMOUNT_THUMB_WIDTH'), - Redshop::getConfig()->get('DEFAULT_STOCKAMOUNT_THUMB_HEIGHT'), - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') - ); + $thumbUrl = RedshopHelperMedia::getImagePath( + $row->stock_amount_image, + '', + 'thumb', + 'stockroom', + Redshop::getConfig()->get('DEFAULT_STOCKAMOUNT_THUMB_WIDTH'), + Redshop::getConfig()->get('DEFAULT_STOCKAMOUNT_THUMB_HEIGHT'), + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') + ); - $link = JRoute::_('index.php?option=com_redshop&view=stockimage_detail&task=edit&cid[]=' . $row->id); ?> - "> - - - - - - - - - - - - - -
    lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>
    pagination->getRowOffset($i);?>id);?>stock_amount_image_tooltip;?> - stock_quantity;?>getStockAmountOption($row->stock_option);?>stockroom_name;?>stock_amount_id;?>
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter();?>
    -
    + $link = JRoute::_('index.php?option=com_redshop&view=stockimage_detail&task=edit&cid[]=' . $row->id); ?> + "> + pagination->getRowOffset($i); ?> + id); ?> + stock_amount_image_tooltip; ?> + + + stock_quantity; ?> + getStockAmountOption($row->stock_option); ?> + stockroom_name; ?> + stock_amount_id; ?> + + + + + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?> + + +
    - - - - - + + + + +
    diff --git a/component/admin/views/stockimage/view.html.php b/component/admin/views/stockimage/view.html.php index 8480a190d63..e7f1c630640 100644 --- a/component/admin/views/stockimage/view.html.php +++ b/component/admin/views/stockimage/view.html.php @@ -12,37 +12,37 @@ class RedshopViewStockimage extends RedshopViewAdmin { - public function display($tpl = null) - { - global $context; + public function display($tpl = null) + { + global $context; - $uri = JFactory::getURI(); - $app = JFactory::getApplication(); - $document = JFactory::getDocument(); + $uri = JFactory::getURI(); + $app = JFactory::getApplication(); + $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_STOCKIMAGE')); + $document->setTitle(JText::_('COM_REDSHOP_STOCKIMAGE')); - JToolBarHelper::title(JText::_('COM_REDSHOP_STOCKIMAGE_MANAGEMENT'), 'redshop_stockroom48'); - JToolbarHelper::addNew(); - JToolbarHelper::EditList(); - JToolBarHelper::deleteList(); + JToolBarHelper::title(JText::_('COM_REDSHOP_STOCKIMAGE_MANAGEMENT'), 'redshop_stockroom48'); + JToolbarHelper::addNew(); + JToolbarHelper::EditList(); + JToolBarHelper::deleteList(); - $state = $this->get('State'); - $filter_order = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'stock_amount_id'); - $filter_order_Dir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', ''); + $state = $this->get('State'); + $filter_order = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'stock_amount_id'); + $filter_order_Dir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', ''); - $lists ['order'] = $filter_order; - $lists ['order_Dir'] = $filter_order_Dir; - $this->filter = $state->get('filter'); + $lists ['order'] = $filter_order; + $lists ['order_Dir'] = $filter_order_Dir; + $this->filter = $state->get('filter'); - $data = $this->get('Data'); - $pagination = $this->get('Pagination'); + $data = $this->get('Data'); + $pagination = $this->get('Pagination'); - $this->lists = $lists; - $this->data = $data; - $this->pagination = $pagination; - $this->request_url = $uri->toString(); + $this->lists = $lists; + $this->data = $data; + $this->pagination = $pagination; + $this->request_url = $uri->toString(); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/stockimage_detail/index.html b/component/admin/views/stockimage_detail/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/stockimage_detail/index.html +++ b/component/admin/views/stockimage_detail/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/stockimage_detail/tmpl/default.php b/component/admin/views/stockimage_detail/tmpl/default.php index a2909893afa..9401a344b9c 100644 --- a/component/admin/views/stockimage_detail/tmpl/default.php +++ b/component/admin/views/stockimage_detail/tmpl/default.php @@ -1,4 +1,5 @@ root(); $thumbUrl = RedshopHelperMedia::getImagePath( - $this->detail->stock_amount_image, - '', - 'thumb', - 'stockroom', - Redshop::getConfig()->get('DEFAULT_STOCKAMOUNT_THUMB_WIDTH'), - Redshop::getConfig()->get('DEFAULT_STOCKAMOUNT_THUMB_HEIGHT'), - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') - ); + $this->detail->stock_amount_image, + '', + 'thumb', + 'stockroom', + Redshop::getConfig()->get('DEFAULT_STOCKAMOUNT_THUMB_WIDTH'), + Redshop::getConfig()->get('DEFAULT_STOCKAMOUNT_THUMB_HEIGHT'), + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') +); ?>
    -
    -
    - +
    +
    + - - - - - - - - - - - - - - - - - - - - - -
    : -
    : - lists['stockroom_id'];?>
    : - lists['stock_option'];?>
    : -
    : - -
    -
    -
    -
    -
    - - - - + + + + + + + + + + + + + + + + + + + + + +
    : +
    : + lists['stockroom_id']; ?>
    : + lists['stock_option']; ?>
    : +
    : + +
    +
    +
    +
    +
    + + + +
    diff --git a/component/admin/views/stockimage_detail/tmpl/index.html b/component/admin/views/stockimage_detail/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/stockimage_detail/tmpl/index.html +++ b/component/admin/views/stockimage_detail/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/stockimage_detail/view.html.php b/component/admin/views/stockimage_detail/view.html.php index e784b9bfd09..417e07fb9e9 100644 --- a/component/admin/views/stockimage_detail/view.html.php +++ b/component/admin/views/stockimage_detail/view.html.php @@ -12,60 +12,72 @@ class RedshopViewStockimage_detail extends RedshopViewAdmin { - /** - * Do we have to display a sidebar ? - * - * @var boolean - */ - protected $displaySidebar = false; + /** + * Do we have to display a sidebar ? + * + * @var boolean + */ + protected $displaySidebar = false; - public function display($tpl = null) - { - JToolBarHelper::title(JText::_('COM_REDSHOP_STOCKIMAGE_MANAGEMENT_DETAIL'), 'redshop_stockroom48'); - $uri = JFactory::getURI(); - $this->setLayout('default'); + public function display($tpl = null) + { + JToolBarHelper::title(JText::_('COM_REDSHOP_STOCKIMAGE_MANAGEMENT_DETAIL'), 'redshop_stockroom48'); + $uri = JFactory::getURI(); + $this->setLayout('default'); - $lists = array(); + $lists = array(); - $detail = $this->get('data'); - $isNew = ($detail->stock_amount_id < 1); - $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); - JToolBarHelper::title(JText::_('COM_REDSHOP_STOCKIMAGE') . ': [ ' . $text . ' ]', 'redshop_stockroom48'); + $detail = $this->get('data'); + $isNew = ($detail->stock_amount_id < 1); + $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); + JToolBarHelper::title( + JText::_('COM_REDSHOP_STOCKIMAGE') . ': [ ' . $text . ' ]', + 'redshop_stockroom48' + ); - // Create the toolbar - JToolBarHelper::save(); + // Create the toolbar + JToolBarHelper::save(); - if ($isNew) - { - JToolBarHelper::cancel(); - } - else - { - JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); - } + if ($isNew) { + JToolBarHelper::cancel(); + } else { + JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); + } - $model = $this->getModel('stockimage_detail'); + $model = $this->getModel('stockimage_detail'); - $stock_option = $model->getStockAmountOption(); - $stockroom_name = $model->getStockRoomList(); - $op = array(); - $op[0] = new stdClass; - $op[0]->value = 0; - $op[0]->text = JText::_('COM_REDSHOP_SELECT'); - $stockroom_name = array_merge($op, $stockroom_name); + $stock_option = $model->getStockAmountOption(); + $stockroom_name = $model->getStockRoomList(); + $op = array(); + $op[0] = new stdClass; + $op[0]->value = 0; + $op[0]->text = JText::_('COM_REDSHOP_SELECT'); + $stockroom_name = array_merge($op, $stockroom_name); - $lists['stock_option'] = JHTML::_('select.genericlist', $stock_option, 'stock_option', - 'class="inputbox" size="1" ', 'value', 'text', $detail->stock_option - ); + $lists['stock_option'] = JHTML::_( + 'select.genericlist', + $stock_option, + 'stock_option', + 'class="inputbox" size="1" ', + 'value', + 'text', + $detail->stock_option + ); - $lists['stockroom_id'] = JHTML::_('select.genericlist', $stockroom_name, 'stockroom_id', - 'class="inputbox" size="1" ', 'value', 'text', $detail->stockroom_id - ); + $lists['stockroom_id'] = JHTML::_( + 'select.genericlist', + $stockroom_name, + 'stockroom_id', + 'class="inputbox" size="1" ', + 'value', + 'text', + $detail->stockroom_id + ); - $this->lists = $lists; - $this->detail = $detail; - $this->request_url = $uri->toString(); + $this->lists = $lists; + $this->detail = $detail; + $this->request_url = $uri->toString(); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/stockroom/tmpl/default.php b/component/admin/views/stockroom/tmpl/default.php index 2c0f93c1c84..589d5c92cb5 100644 --- a/component/admin/views/stockroom/tmpl/default.php +++ b/component/admin/views/stockroom/tmpl/default.php @@ -1,4 +1,5 @@
    -
    -
    -
    -
    - - " /> - -
    -
    -
    - - - - - - - - - - - - - - stockroom); $i < $n; $i++) - { - $row = $this->stockroom [$i]; - $row->id = $row->stockroom_id; - $link = JRoute::_('index.php?option=com_redshop&view=stockroom_detail&task=edit&cid[]=' . $row->stockroom_id);?> - "> - - - - - - - - - - - - - -
    lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']);?>
    pagination->getRowOffset($i);?>id);?> - stockroom_name;?>min_del_time;?>max_del_time;?>published = $row->show_in_front; - echo $show_in_front = JHTML::_('grid.published', $row, $i, 'tick.png', 'publish_x.png', 'front');?>stockroom_id;?>
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter();?>
    -
    +
    +
    +
    +
    + + "/> + +
    +
    +
    + + + + + + + + + + + + + + stockroom); $i < $n; $i++) { + $row = $this->stockroom [$i]; + $row->id = $row->stockroom_id; + $link = JRoute::_( + 'index.php?option=com_redshop&view=stockroom_detail&task=edit&cid[]=' . $row->stockroom_id + ); ?> + "> + + + + + + + + + + + + + +
    lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>
    pagination->getRowOffset($i); ?>id); ?> + stockroom_name; ?>min_del_time; ?>max_del_time; ?>published = $row->show_in_front; + echo $show_in_front = JHTML::_( + 'grid.published', + $row, + $i, + 'tick.png', + 'publish_x.png', + 'front' + ); ?>stockroom_id; ?>
    + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?>
    +
    - - - - - + + + + +
    diff --git a/component/admin/views/stockroom/view.html.php b/component/admin/views/stockroom/view.html.php index 923a5042b1c..03306beafbc 100644 --- a/component/admin/views/stockroom/view.html.php +++ b/component/admin/views/stockroom/view.html.php @@ -12,43 +12,43 @@ class RedshopViewStockroom extends RedshopViewAdmin { - /** - * The request url. - * - * @var string - */ - public $request_url; - - public $state; - - public function display($tpl = null) - { - $uri = JFactory::getURI(); - $document = JFactory::getDocument(); - - $document->setTitle(JText::_('COM_REDSHOP_STOCKROOM')); - - JToolBarHelper::title(JText::_('COM_REDSHOP_STOCKROOM_MANAGEMENT'), 'redshop_stockroom48'); - JToolBarHelper::custom('listing', 'copy.png', 'copy_f2.png', JText::_('COM_REDSHOP_LISTING'), false); - JToolbarHelper::addNew(); - JToolbarHelper::EditList(); - JToolBarHelper::custom('copy', 'copy.png', 'copy_f2.png', JText::_('COM_REDSHOP_TOOLBAR_COPY'), true); - JToolBarHelper::deleteList(); - JToolBarHelper::publishList(); - JToolBarHelper::unpublishList(); - - $this->state = $this->get('State'); - $lists ['order'] = $this->state->get('list.ordering', 'stockroom_id'); - $lists ['order_Dir'] = $this->state->get('list.direction'); - - $stockroom = $this->get('Data'); - $pagination = $this->get('Pagination'); - - $this->lists = $lists; - $this->stockroom = $stockroom; - $this->pagination = $pagination; - $this->request_url = $uri->toString(); - - parent::display($tpl); - } + /** + * The request url. + * + * @var string + */ + public $request_url; + + public $state; + + public function display($tpl = null) + { + $uri = JFactory::getURI(); + $document = JFactory::getDocument(); + + $document->setTitle(JText::_('COM_REDSHOP_STOCKROOM')); + + JToolBarHelper::title(JText::_('COM_REDSHOP_STOCKROOM_MANAGEMENT'), 'redshop_stockroom48'); + JToolBarHelper::custom('listing', 'copy.png', 'copy_f2.png', JText::_('COM_REDSHOP_LISTING'), false); + JToolbarHelper::addNew(); + JToolbarHelper::EditList(); + JToolBarHelper::custom('copy', 'copy.png', 'copy_f2.png', JText::_('COM_REDSHOP_TOOLBAR_COPY'), true); + JToolBarHelper::deleteList(); + JToolBarHelper::publishList(); + JToolBarHelper::unpublishList(); + + $this->state = $this->get('State'); + $lists ['order'] = $this->state->get('list.ordering', 'stockroom_id'); + $lists ['order_Dir'] = $this->state->get('list.direction'); + + $stockroom = $this->get('Data'); + $pagination = $this->get('Pagination'); + + $this->lists = $lists; + $this->stockroom = $stockroom; + $this->pagination = $pagination; + $this->request_url = $uri->toString(); + + parent::display($tpl); + } } diff --git a/component/admin/views/stockroom_detail/index.html b/component/admin/views/stockroom_detail/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/stockroom_detail/index.html +++ b/component/admin/views/stockroom_detail/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/stockroom_detail/tmpl/default.php b/component/admin/views/stockroom_detail/tmpl/default.php index 135cced9307..34e8e546626 100644 --- a/component/admin/views/stockroom_detail/tmpl/default.php +++ b/component/admin/views/stockroom_detail/tmpl/default.php @@ -14,145 +14,168 @@ ?>
    -
    -
    - - - - - - - - - - - - - - - - - detail->delivery_time == 'Weeks') - { - $this->detail->min_del_time = (int) $this->detail->min_del_time / 7; - $this->detail->max_del_time = (int) $this->detail->max_del_time / 7; - } - - ?> - - - - - - - - - - - - - - - - - - -
    - - - -
    - - - -
    - - - booleanlist; ?> -
    - - - - -
    - - - - -
    - : - - lists['show_in_front']; ?> -
    - : - - lists['published']; ?> -
    -
    -
    -
    - -
    - -
    -
    - - - - - - -
    - display("stockroom_desc", $this->detail->stockroom_desc, '$widthPx', '$heightPx', '100', '20', '1'); ?> -
    -
    -
    -
    - - - - + id="adminForm"> +
    +
    + + + + + + + + + + + + + + + + + detail->delivery_time == 'Weeks') { + $this->detail->min_del_time = (int)$this->detail->min_del_time / 7; + $this->detail->max_del_time = (int)$this->detail->max_del_time / 7; + } + + ?> + + + + + + + + + + + + + + + + + + +
    + + + +
    + + + +
    + + + booleanlist; ?> +
    + + + + +
    + + + + +
    + : + + lists['show_in_front']; ?> +
    + : + + lists['published']; ?> +
    +
    +
    +
    + +
    + +
    +
    + + + + + + +
    + display( + "stockroom_desc", + $this->detail->stockroom_desc, + '$widthPx', + '$heightPx', + '100', + '20', + '1' + ); ?> +
    +
    +
    +
    + + + +
    diff --git a/component/admin/views/stockroom_detail/tmpl/importstock.php b/component/admin/views/stockroom_detail/tmpl/importstock.php index 2138f2b4fe2..69416368979 100644 --- a/component/admin/views/stockroom_detail/tmpl/importstock.php +++ b/component/admin/views/stockroom_detail/tmpl/importstock.php @@ -10,116 +10,119 @@ defined('_JEXEC') or die; ?>
    -
    -
    - - - - - - -
    lists['stockroom_id'];?>    -
    -
    -
    - - - - - - - - -
    -
    -
    - -
    -
    -
    - - - - +
    +
    + + + + + + +
    lists['stockroom_id']; ?>    +
    +
    +
    + + + + + + + + +
    +
    +
    + +
    +
    +
    + + + +
    diff --git a/component/admin/views/stockroom_detail/tmpl/index.html b/component/admin/views/stockroom_detail/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/stockroom_detail/tmpl/index.html +++ b/component/admin/views/stockroom_detail/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/stockroom_detail/view.html.php b/component/admin/views/stockroom_detail/view.html.php index d9a9d029dd1..f78cf5326b7 100644 --- a/component/admin/views/stockroom_detail/view.html.php +++ b/component/admin/views/stockroom_detail/view.html.php @@ -12,76 +12,94 @@ class RedshopViewStockroom_detail extends RedshopViewAdmin { - /** - * Do we have to display a sidebar ? - * - * @var boolean - */ - protected $displaySidebar = false; - - public function display($tpl = null) - { - $layout = JFactory::getApplication()->input->getCmd('layout', ''); - - $lists = array(); - $uri = JFactory::getURI(); - - /** @var RedshopModelStockroom_detail $model */ - $model = $this->getModel('stockroom_detail'); - - if ($layout == 'importstock') - { - $stockroom_name = $model->getStockRoomList(); - $op = array(); - $op[0]->value = 0; - $op[0]->text = JText::_('COM_REDSHOP_SELECT'); - $stockroom_name = array_merge($op, $stockroom_name); - $lists['stockroom_id'] = JHTML::_('select.genericlist', $stockroom_name, 'stockroom_id', 'class="inputbox" size="1" ', 'value', 'text'); - - JToolBarHelper::title(JText::_('COM_REDSHOP_IMPORT_STOCK_FROM_ECONOMIC'), 'redshop_stockroom48'); - JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); - $this->setLayout($layout); - } - else - { - $this->setLayout('default'); - $detail = $this->get('data'); - - $isNew = ($detail->stockroom_id < 1); - $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); - JToolBarHelper::title(JText::_('COM_REDSHOP_STOCKROOM') . ': [ ' . $text . ' ]', 'redshop_stockroom48'); - - // Create the toolbar - JToolBarHelper::apply(); - JToolBarHelper::save(); - - if ($isNew) - { - JToolBarHelper::cancel(); - } - else - { - JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); - } - - $lists['show_in_front'] = JHtml::_('select.booleanlist', 'show_in_front', 'class="inputbox"', $detail->show_in_front); - $lists['published'] = JHtml::_('select.booleanlist', 'published', 'class="inputbox"', $detail->published); - - $delivery_time = array(); - $delivery_time['value'] = "days"; - $delivery_time['value'] .= "weeks"; - - $booleanlist = RedshopHelperExtrafields::booleanList('delivery_time', 'class="inputbox"', $detail->delivery_time, - JText::_('COM_REDSHOP_DAYS'), JText::_('COM_REDSHOP_WEEKS') - ); - - $this->booleanlist = $booleanlist; - $this->detail = $detail; - } - - $this->lists = $lists; - $this->request_url = $uri->toString(); - - parent::display($tpl); - } + /** + * Do we have to display a sidebar ? + * + * @var boolean + */ + protected $displaySidebar = false; + + public function display($tpl = null) + { + $layout = JFactory::getApplication()->input->getCmd('layout', ''); + + $lists = array(); + $uri = JFactory::getURI(); + + /** @var RedshopModelStockroom_detail $model */ + $model = $this->getModel('stockroom_detail'); + + if ($layout == 'importstock') { + $stockroom_name = $model->getStockRoomList(); + $op = array(); + $op[0]->value = 0; + $op[0]->text = JText::_('COM_REDSHOP_SELECT'); + $stockroom_name = array_merge($op, $stockroom_name); + $lists['stockroom_id'] = JHTML::_( + 'select.genericlist', + $stockroom_name, + 'stockroom_id', + 'class="inputbox" size="1" ', + 'value', + 'text' + ); + + JToolBarHelper::title(JText::_('COM_REDSHOP_IMPORT_STOCK_FROM_ECONOMIC'), 'redshop_stockroom48'); + JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); + $this->setLayout($layout); + } else { + $this->setLayout('default'); + $detail = $this->get('data'); + + $isNew = ($detail->stockroom_id < 1); + $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); + JToolBarHelper::title( + JText::_('COM_REDSHOP_STOCKROOM') . ': [ ' . $text . ' ]', + 'redshop_stockroom48' + ); + + // Create the toolbar + JToolBarHelper::apply(); + JToolBarHelper::save(); + + if ($isNew) { + JToolBarHelper::cancel(); + } else { + JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); + } + + $lists['show_in_front'] = JHtml::_( + 'select.booleanlist', + 'show_in_front', + 'class="inputbox"', + $detail->show_in_front + ); + $lists['published'] = JHtml::_( + 'select.booleanlist', + 'published', + 'class="inputbox"', + $detail->published + ); + + $delivery_time = array(); + $delivery_time['value'] = "days"; + $delivery_time['value'] .= "weeks"; + + $booleanlist = RedshopHelperExtrafields::booleanList( + 'delivery_time', + 'class="inputbox"', + $detail->delivery_time, + JText::_('COM_REDSHOP_DAYS'), + JText::_('COM_REDSHOP_WEEKS') + ); + + $this->booleanlist = $booleanlist; + $this->detail = $detail; + } + + $this->lists = $lists; + $this->request_url = $uri->toString(); + + parent::display($tpl); + } } diff --git a/component/admin/views/stockroom_listing/tmpl/default.php b/component/admin/views/stockroom_listing/tmpl/default.php index 79d516cb1bf..d709909a844 100644 --- a/component/admin/views/stockroom_listing/tmpl/default.php +++ b/component/admin/views/stockroom_listing/tmpl/default.php @@ -1,4 +1,5 @@ getmodel('stockroom_listing'); -$showbuttons = JFactory::getApplication()->input->getInt('showbuttons', 0); +$model = $this->getmodel('stockroom_listing'); +$showbuttons = JFactory::getApplication()->input->getInt('showbuttons', 0); ?> -
    - - - -
    +
    + + + +
    -
    +
    - - " > - " onclick="clearForm();" > + + "> + " + onclick="clearForm();">
    - state->get('search_field') - ); - ?> + echo JHtml::_( + 'select.genericlist', + $filterOptions, + 'search_field', + 'class="inputbox" onchange="document.adminForm.submit();" ', + 'value', + 'text', + $this->state->get('search_field') + ); + ?> +
    +
    + lists['category']; ?> +
    +
    + lists['stockroom_type']; ?>
    -
    - lists['category'];?> -
    -
    - lists['stockroom_type']; ?> -
    -
    -
    - - - - - - - stockroom_type != 'product') : ?> - - - - stockroom);$j++) : ?> - - - - - - - resultlisting); $i < $n; $i++) : ?> - resultlisting [$i]; - $link1 = JRoute::_('index.php?option=com_redshop&view=product_detail&task=edit&cid[]=' . $row->product_id); - ?> - "> - - - - stockroom_type != 'product') : ?> - - - + +
    +
    - - - lists ['order_Dir'], - $this->lists ['order'] - ); - ?> - - lists ['order_Dir'], - $this->lists ['order'] - ); - ?> - - - - stockroom_type == 'property') : ?> - - stockroom_type == 'subproperty') : ?> - - - - stockroom[$j]->stockroom_name; ?> - - -
    - stockroom[$j]->stockroom_name;?> - -
    - pagination->getRowOffset($i); ?> - - - product_number; ?> - - - - product_name; ?> - - - stockroom_type == 'property') : ?> - property_number; ?> - stockroom_type == 'subproperty') : ?> - subattribute_color_number; ?> - - - stockroom_type == 'property') : ?> - property_name; ?> - stockroom_type == 'subproperty') : ?> - subattribute_color_name; ?> - -
    + + + + + + stockroom_type != 'product') : ?> + + + + stockroom); $j++) : ?> + + + + + + + resultlisting); $i < $n; $i++) : ?> + resultlisting [$i]; + $link1 = JRoute::_( + 'index.php?option=com_redshop&view=product_detail&task=edit&cid[]=' . $row->product_id + ); + ?> + "> + + + + stockroom_type != 'product') : ?> + + + - stockroom); $j < $countStockRoom; $j++) : ?> + stockroom); $j < $countStockRoom; $j++) : ?> - stockroom_type != 'product') ? $row->section_id : $row->product_id; + stockroom_type != 'product') ? $row->section_id : $row->product_id; - if (isset($this->quantities[$section_id . '.' . $this->stockroom[$j]->stockroom_id])) - { - $secrow = $this->quantities[$section_id . '.' . $this->stockroom[$j]->stockroom_id]; - $quantity = $secrow->quantity; - $preorder_stock = $secrow->preorder_stock; - $ordered_preorder = $secrow->ordered_preorder; - } + if (isset($this->quantities[$section_id . '.' . $this->stockroom[$j]->stockroom_id])) { + $secrow = $this->quantities[$section_id . '.' . $this->stockroom[$j]->stockroom_id]; + $quantity = $secrow->quantity; + $preorder_stock = $secrow->preorder_stock; + $ordered_preorder = $secrow->ordered_preorder; + } - $quntotal[$i][$j] = $quantity; - $preorder_stocktotal[$i][$j] = $preorder_stock; - ?> - - - - - - - + + + + + + + stockroom); $j < $nj; $j++) - { - $qungrandtotal[$j] = 0; - $preorder_stockalltotal[$j] = 0; + for ($j = 0, $nj = count($this->stockroom); $j < $nj; $j++) { + $qungrandtotal[$j] = 0; + $preorder_stockalltotal[$j] = 0; - for ($i = 0, $ni = count($this->resultlisting); $i < $ni; $i++) - { - $qungrandtotal[$j] = $qungrandtotal[$j] + $quntotal[$i][$j]; - $preorder_stockalltotal[$j] = $preorder_stockalltotal[$j] + $preorder_stocktotal[$i][$j]; - } - } + for ($i = 0, $ni = count($this->resultlisting); $i < $ni; $i++) { + $qungrandtotal[$j] = $qungrandtotal[$j] + $quntotal[$i][$j]; + $preorder_stockalltotal[$j] = $preorder_stockalltotal[$j] + $preorder_stocktotal[$i][$j]; + } + } - $colspan = ($this->stockroom_type == 'product') ? 3 : 5; - ?> + $colspan = ($this->stockroom_type == 'product') ? 3 : 5; + ?> - - - stockroom); $j++) : ?> - - - - + + + stockroom); $j++) : ?> + + + + - - - - - -
    + + + lists ['order_Dir'], + $this->lists ['order'] + ); + ?> + + lists ['order_Dir'], + $this->lists ['order'] + ); + ?> + + + + stockroom_type == 'property') : ?> + + stockroom_type == 'subproperty') : ?> + + + + stockroom[$j]->stockroom_name; ?> + + +
    + stockroom[$j]->stockroom_name; ?> + +
    + pagination->getRowOffset($i); ?> + + + product_number; ?> + + + + product_name; ?> + + + stockroom_type == 'property') : ?> + property_number; ?> + stockroom_type == 'subproperty') : ?> + subattribute_color_number; ?> + + + stockroom_type == 'property') : ?> + property_name; ?> + stockroom_type == 'subproperty') : ?> + subattribute_color_name; ?> + + - - - - - - - 0) : ?> - ( ) - - -
    + + + + + + + 0) : ?> + ( ) + + +
    - - - - - -
    + + + + + +
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter(); ?> -
    -
    - - - - - + + + + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?> + + + + +
    + + + + +
    diff --git a/component/admin/views/stockroom_listing/view.csv.php b/component/admin/views/stockroom_listing/view.csv.php index 5b6fbc5df41..c43536f1147 100644 --- a/component/admin/views/stockroom_listing/view.csv.php +++ b/component/admin/views/stockroom_listing/view.csv.php @@ -18,140 +18,122 @@ */ class RedshopViewStockroom_Listing extends RedshopViewCsv { - /** - * Delimiter character for CSV columns - * - * @var string - */ - public $delimiter = ';'; - - /** - * Get the columns for the csv file. - * - * @return array An associative array of column names as key and the title as value. - */ - protected function getColumns() - { - $model = $this->getModel(); - - return $model->getCsvColumns(); - } - - /** - * Execute and display a template script. - * - * @param string $tpl The name of the template file to parse. - * - * @return mixed A string if successful, otherwise a Error object. - * - * @throws RuntimeException - */ - public function display($tpl = null) - { - // Get the columns - $columns = $this->getColumns(); - - if (empty($columns)) - { - throw new RuntimeException( - sprintf( - 'Empty columns not allowed for the csv view %s', - get_class($this) - ) - ); - } - - $model = $this->getModel(); - - // For additional filtering and formating if needed - $model->setState('streamOutput', 'csv'); - - // Prepare the items - $items = $model->getItems(); - $state = $this->get('State'); - $stockroom_type = $state->get('stockroom_type'); - $stockrooms = $this->get('Stockroom'); - $ids = array(); - - if ($stockroom_type != 'product') - { - $nameId = 'section_id'; - } - else - { - $nameId = 'product_id'; - unset($columns['section_id'], $columns['stockroom_type']); - } - - foreach ($items as $item) - { - $ids[] = $item->$nameId; - } - - $quantities = $model->getQuantity($stockroom_type, '', $ids); - - $csvLines[0] = $columns; - $i = 1; - - if ($stockrooms) - { - foreach ($stockrooms as $stockroom) - { - foreach ($items as $item) - { - if (!isset($quantities[$item->$nameId . '.' . $stockroom->stockroom_id])) - { - continue; - } - - $value = $quantities[$item->$nameId . '.' . $stockroom->stockroom_id]; - - foreach ($columns as $name => $title) - { - if (property_exists($value, $name)) - { - $csvLines[$i][$name] = $value->$name; - } - } - - $csvLines[$i]['stockroom_type'] = $state->get('stockroom_type'); - - foreach ($columns as $name => $title) - { - if (property_exists($item, $name)) - { - $csvLines[$i][$name] = $item->$name; - } - } - - $i++; - } - } - } - - $stream = $this->initFIle(); - - foreach ($csvLines as $line) - { - $orderLine = array(); - - foreach ($columns as $name => $title) - { - if (array_key_exists($name, $line)) - { - $orderLine[$name] = $line[$name]; - } - else - { - $orderLine[$name] = ''; - } - } - - fputcsv($stream, $orderLine, $this->delimiter, $this->enclosure); - } - - fclose($stream); - - JFactory::getApplication()->close(); - } + /** + * Delimiter character for CSV columns + * + * @var string + */ + public $delimiter = ';'; + + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse. + * + * @return mixed A string if successful, otherwise a Error object. + * + * @throws RuntimeException + */ + public function display($tpl = null) + { + // Get the columns + $columns = $this->getColumns(); + + if (empty($columns)) { + throw new RuntimeException( + sprintf( + 'Empty columns not allowed for the csv view %s', + get_class($this) + ) + ); + } + + $model = $this->getModel(); + + // For additional filtering and formating if needed + $model->setState('streamOutput', 'csv'); + + // Prepare the items + $items = $model->getItems(); + $state = $this->get('State'); + $stockroom_type = $state->get('stockroom_type'); + $stockrooms = $this->get('Stockroom'); + $ids = array(); + + if ($stockroom_type != 'product') { + $nameId = 'section_id'; + } else { + $nameId = 'product_id'; + unset($columns['section_id'], $columns['stockroom_type']); + } + + foreach ($items as $item) { + $ids[] = $item->$nameId; + } + + $quantities = $model->getQuantity($stockroom_type, '', $ids); + + $csvLines[0] = $columns; + $i = 1; + + if ($stockrooms) { + foreach ($stockrooms as $stockroom) { + foreach ($items as $item) { + if (!isset($quantities[$item->$nameId . '.' . $stockroom->stockroom_id])) { + continue; + } + + $value = $quantities[$item->$nameId . '.' . $stockroom->stockroom_id]; + + foreach ($columns as $name => $title) { + if (property_exists($value, $name)) { + $csvLines[$i][$name] = $value->$name; + } + } + + $csvLines[$i]['stockroom_type'] = $state->get('stockroom_type'); + + foreach ($columns as $name => $title) { + if (property_exists($item, $name)) { + $csvLines[$i][$name] = $item->$name; + } + } + + $i++; + } + } + } + + $stream = $this->initFIle(); + + foreach ($csvLines as $line) { + $orderLine = array(); + + foreach ($columns as $name => $title) { + if (array_key_exists($name, $line)) { + $orderLine[$name] = $line[$name]; + } else { + $orderLine[$name] = ''; + } + } + + fputcsv($stream, $orderLine, $this->delimiter, $this->enclosure); + } + + fclose($stream); + + JFactory::getApplication()->close(); + } + + /** + * Get the columns for the csv file. + * + * @return array An associative array of column names as key and the title as value. + */ + protected function getColumns() + { + $model = $this->getModel(); + + return $model->getCsvColumns(); + } } diff --git a/component/admin/views/stockroom_listing/view.html.php b/component/admin/views/stockroom_listing/view.html.php index ef2673163f5..699f5c84ea5 100644 --- a/component/admin/views/stockroom_listing/view.html.php +++ b/component/admin/views/stockroom_listing/view.html.php @@ -12,94 +12,103 @@ class RedshopViewStockroom_listing extends RedshopViewAdmin { - public $state; - - /** - * The request url. - * - * @var string - */ - public $request_url; - - public function display($tpl = null) - { - $uri = JFactory::getURI(); - $document = JFactory::getDocument(); - - $document->setTitle(JText::_('COM_REDSHOP_STOCKROOM_LISTING')); - - JToolBarHelper::title(JText::_('COM_REDSHOP_STOCKROOM_LISTING_MANAGEMENT'), 'redshop_stockroom48'); - RedshopToolbarHelper::link('index.php?option=com_redshop&view=stockroom_listing&format=csv', 'save', JText::_('COM_REDSHOP_EXPORT_DATA_LBL')); - JToolBarHelper::custom('print_data', 'save.png', 'save_f2.png', 'Print Data', false); - - $this->state = $this->get('State'); - $stockroom_type = $this->state->get('stockroom_type'); - $category_id = $this->state->get('category_id'); - - // Stockroom type and attribute type - $optiontype = array(); - - $optiontype[] = JHTML::_('select.option', 'product', JText::_('COM_REDSHOP_PRODUCT')); - $optiontype[] = JHTML::_('select.option', 'property', JText::_('COM_REDSHOP_PROPERTY')); - $optiontype[] = JHTML::_('select.option', 'subproperty', JText::_('COM_REDSHOP_SUBPROPERTY')); - - $lists['stockroom_type'] = JHTML::_('select.genericlist', $optiontype, 'stockroom_type', - 'class="inputbox" size="1" onchange="document.adminForm.submit();" ', 'value', 'text', $stockroom_type - ); - - $categories = RedshopHelperCategory::getCategoryListArray(); - - if (is_null($categories)) - { - $categories = array(); - } - - $temps = array(); - $temps[0] = new stdClass; - $temps[0]->id = "0"; - $temps[0]->name = JText::_('COM_REDSHOP_SELECT_CATEGORY'); - $categories = @array_merge($temps, $categories); - $lists['category'] = JHTML::_('select.genericlist', $categories, 'category_id', - 'class="inputbox" onchange="getTaskChange();document.adminForm.submit();" ', - 'id', 'name', $category_id - ); - - $lists ['order'] = $this->state->get('list.ordering', 'p.product_id'); - $lists ['order_Dir'] = $this->state->get('list.direction'); - - $resultlisting = $this->get('Items'); - $stockroom = $this->get('Stockroom'); - $pagination = $this->get('Pagination'); - $model = $this->getModel('stockroom_listing'); - $ids = array(); - - if ($resultlisting) - { - if ($stockroom_type != 'product') - { - $nameId = 'section_id'; - } - else - { - $nameId = 'product_id'; - } - - foreach ($resultlisting as $item) - { - $ids[] = $item->$nameId; - } - } - - $this->quantities = $model->getQuantity($stockroom_type, '', $ids); - - $this->lists = $lists; - $this->resultlisting = $resultlisting; - $this->stockroom = $stockroom; - $this->stockroom_type = $stockroom_type; - - $this->pagination = $pagination; - $this->request_url = $uri->toString(); - - parent::display($tpl); - } + public $state; + + /** + * The request url. + * + * @var string + */ + public $request_url; + + public function display($tpl = null) + { + $uri = JFactory::getURI(); + $document = JFactory::getDocument(); + + $document->setTitle(JText::_('COM_REDSHOP_STOCKROOM_LISTING')); + + JToolBarHelper::title(JText::_('COM_REDSHOP_STOCKROOM_LISTING_MANAGEMENT'), 'redshop_stockroom48'); + RedshopToolbarHelper::link( + 'index.php?option=com_redshop&view=stockroom_listing&format=csv', + 'save', + JText::_('COM_REDSHOP_EXPORT_DATA_LBL') + ); + JToolBarHelper::custom('print_data', 'save.png', 'save_f2.png', 'Print Data', false); + + $this->state = $this->get('State'); + $stockroom_type = $this->state->get('stockroom_type'); + $category_id = $this->state->get('category_id'); + + // Stockroom type and attribute type + $optiontype = array(); + + $optiontype[] = JHTML::_('select.option', 'product', JText::_('COM_REDSHOP_PRODUCT')); + $optiontype[] = JHTML::_('select.option', 'property', JText::_('COM_REDSHOP_PROPERTY')); + $optiontype[] = JHTML::_('select.option', 'subproperty', JText::_('COM_REDSHOP_SUBPROPERTY')); + + $lists['stockroom_type'] = JHTML::_( + 'select.genericlist', + $optiontype, + 'stockroom_type', + 'class="inputbox" size="1" onchange="document.adminForm.submit();" ', + 'value', + 'text', + $stockroom_type + ); + + $categories = RedshopHelperCategory::getCategoryListArray(); + + if (is_null($categories)) { + $categories = array(); + } + + $temps = array(); + $temps[0] = new stdClass; + $temps[0]->id = "0"; + $temps[0]->name = JText::_('COM_REDSHOP_SELECT_CATEGORY'); + $categories = @array_merge($temps, $categories); + $lists['category'] = JHTML::_( + 'select.genericlist', + $categories, + 'category_id', + 'class="inputbox" onchange="getTaskChange();document.adminForm.submit();" ', + 'id', + 'name', + $category_id + ); + + $lists ['order'] = $this->state->get('list.ordering', 'p.product_id'); + $lists ['order_Dir'] = $this->state->get('list.direction'); + + $resultlisting = $this->get('Items'); + $stockroom = $this->get('Stockroom'); + $pagination = $this->get('Pagination'); + $model = $this->getModel('stockroom_listing'); + $ids = array(); + + if ($resultlisting) { + if ($stockroom_type != 'product') { + $nameId = 'section_id'; + } else { + $nameId = 'product_id'; + } + + foreach ($resultlisting as $item) { + $ids[] = $item->$nameId; + } + } + + $this->quantities = $model->getQuantity($stockroom_type, '', $ids); + + $this->lists = $lists; + $this->resultlisting = $resultlisting; + $this->stockroom = $stockroom; + $this->stockroom_type = $stockroom_type; + + $this->pagination = $pagination; + $this->request_url = $uri->toString(); + + parent::display($tpl); + } } diff --git a/component/admin/views/supplier/index.html b/component/admin/views/supplier/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/supplier/index.html +++ b/component/admin/views/supplier/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/supplier/tmpl/index.html b/component/admin/views/supplier/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/supplier/tmpl/index.html +++ b/component/admin/views/supplier/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/suppliers/tmpl/default.php b/component/admin/views/suppliers/tmpl/default.php index 450631c17b3..6970c2f0667 100644 --- a/component/admin/views/suppliers/tmpl/default.php +++ b/component/admin/views/suppliers/tmpl/default.php @@ -1,4 +1,5 @@ \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/tax_group/tmpl/index.html b/component/admin/views/tax_group/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/tax_group/tmpl/index.html +++ b/component/admin/views/tax_group/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/tax_groups/tmpl/default.php b/component/admin/views/tax_groups/tmpl/default.php index 450631c17b3..6970c2f0667 100644 --- a/component/admin/views/tax_groups/tmpl/default.php +++ b/component/admin/views/tax_groups/tmpl/default.php @@ -1,4 +1,5 @@ columns[] = array( - // This column is sortable? - 'sortable' => false, - // Text for column - 'text' => JText::_('COM_REDSHOP_TAX_RATE'), - // Name of property for get data. - 'dataCol' => 'tax_rates', - // Width of column - 'width' => '10%', - // Enable edit inline? - 'inline' => false, - // Display with edit link or not? - 'edit_link' => false, - // Type of column - 'type' => 'text', - ); - } + $taxRates = RedshopEntityTax_Group::getInstance($row->id)->getTaxRates()->count(); - /** - * Method for render 'Published' column - * - * @param array $config Row config. - * @param int $index Row index. - * @param object $row Row data. - * - * @return string - * - * @since 2.0.6 - */ - public function onRenderColumn($config, $index, $row) - { - if ($config['dataCol'] !== 'tax_rates') - { - return parent::onRenderColumn($config, $index, $row); - } + return '' . $taxRates . ''; + } - $taxRates = RedshopEntityTax_Group::getInstance($row->id)->getTaxRates()->count(); + /** + * Method for prepare table. + * + * @return void + * + * @since 2.0.6 + */ + protected function prepareTable() + { + parent::prepareTable(); - return '' . $taxRates . ''; - } + $this->columns[] = array( + // This column is sortable? + 'sortable' => false, + // Text for column + 'text' => JText::_('COM_REDSHOP_TAX_RATE'), + // Name of property for get data. + 'dataCol' => 'tax_rates', + // Width of column + 'width' => '10%', + // Enable edit inline? + 'inline' => false, + // Display with edit link or not? + 'edit_link' => false, + // Type of column + 'type' => 'text', + ); + } } diff --git a/component/admin/views/tax_rate/index.html b/component/admin/views/tax_rate/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/tax_rate/index.html +++ b/component/admin/views/tax_rate/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/tax_rate/tmpl/edit.php b/component/admin/views/tax_rate/tmpl/edit.php index c74e2bd2b3c..4c065353cc2 100644 --- a/component/admin/views/tax_rate/tmpl/edit.php +++ b/component/admin/views/tax_rate/tmpl/edit.php @@ -1,4 +1,5 @@ ": 1 }, method: "POST", - cache : false + cache: false }).success(function (data) { if ($("#jform_tax_state").length) { $("#jform_tax_state").parent().html(data); - } - else if ($("#rs_state_jformtax_state").length) { + } else if ($("#rs_state_jformtax_state").length) { $("#rs_state_jformtax_state").parent().html(data); } diff --git a/component/admin/views/tax_rate/tmpl/index.html b/component/admin/views/tax_rate/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/tax_rate/tmpl/index.html +++ b/component/admin/views/tax_rate/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/tax_rates/tmpl/default.php b/component/admin/views/tax_rates/tmpl/default.php index 450631c17b3..6970c2f0667 100644 --- a/component/admin/views/tax_rates/tmpl/default.php +++ b/component/admin/views/tax_rates/tmpl/default.php @@ -1,4 +1,5 @@ {$config['dataCol']}; + /** + * Method for render 'Published' column + * + * @param array $config Row config. + * @param int $index Row index. + * @param object $row Row data. + * + * @return string + * + * @since 2.0.6 + */ + public function onRenderColumn($config, $index, $row) + { + $value = $row->{$config['dataCol']}; - switch ($config['dataCol']) - { - case 'tax_group_id': - return '' - . $row->tax_group_name . ''; + switch ($config['dataCol']) { + case 'tax_group_id': + return '' + . $row->tax_group_name . ''; - case 'tax_country': - return $row->country_name; + case 'tax_country': + return $row->country_name; - case 'tax_state': - return $row->state_name; + case 'tax_state': + return $row->state_name; - case 'tax_rate': - return number_format( - $value * 100, - 2, - Redshop::getConfig()->get('PRICE_SEPERATOR'), - Redshop::getConfig()->get('THOUSAND_SEPERATOR') - ) . ' %'; + case 'tax_rate': + return number_format( + $value * 100, + 2, + Redshop::getConfig()->get('PRICE_SEPERATOR'), + Redshop::getConfig()->get('THOUSAND_SEPERATOR') + ) . ' %'; - default: - return parent::onRenderColumn($config, $index, $row); - } - } + default: + return parent::onRenderColumn($config, $index, $row); + } + } } diff --git a/component/admin/views/template/index.html b/component/admin/views/template/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/template/index.html +++ b/component/admin/views/template/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/template/tmpl/edit.php b/component/admin/views/template/tmpl/edit.php index 19c10d88cec..361bf2c2b78 100644 --- a/component/admin/views/template/tmpl/edit.php +++ b/component/admin/views/template/tmpl/edit.php @@ -11,11 +11,11 @@ ?>
    - formLayout, array('data' => $this)) ?> + formLayout, array('data' => $this)) ?>
    - item->section): ?> - loadTemplate('hints') ?> - + item->section): ?> + loadTemplate('hints') ?> +
    diff --git a/component/admin/views/template/tmpl/edit_hints.php b/component/admin/views/template/tmpl/edit_hints.php index 7b62fed58fa..d3726b4b073 100644 --- a/component/admin/views/template/tmpl/edit_hints.php +++ b/component/admin/views/template/tmpl/edit_hints.php @@ -1,4 +1,5 @@ RedshopHelperText::getTextLibraryData('category'), - 'newsletter' => RedshopHelperText::getTextLibraryData('newsletter'), - 'product' => RedshopHelperText::getTextLibraryData('product') + 'category' => RedshopHelperText::getTextLibraryData('category'), + 'newsletter' => RedshopHelperText::getTextLibraryData('newsletter'), + 'product' => RedshopHelperText::getTextLibraryData('product') ); $newBillingTags = array( - 'billing_address_start' => '', - 'companyname_lbl' => '', - 'companyname' => '', - 'firstname_lbl' => '', - 'firstname' => '', - 'lastname_lbl' => '', - 'lastname' => '', - 'address_lbl' => '', - 'address' => '', - 'city_lbl' => '', - 'city' => '', - 'zip_lbl' => '', - 'zip' => '', - 'country_lbl' => '', - 'country' => '', - 'state_lbl' => '', - 'state' => '', - 'phone_lbl' => '', - 'phone' => '', - 'email_lbl' => '', - 'email' => '', - 'vatnumber_lbl' => '', - 'vatnumber' => '', - 'taxexempt_lbl' => '', - 'taxexempt' => '', - 'user_taxexempt_request_lbl' => '', - 'user_taxexempt_request' => '', - 'billing_extrafield' => '', - 'billing_address_end' => '' + 'billing_address_start' => '', + 'companyname_lbl' => '', + 'companyname' => '', + 'firstname_lbl' => '', + 'firstname' => '', + 'lastname_lbl' => '', + 'lastname' => '', + 'address_lbl' => '', + 'address' => '', + 'city_lbl' => '', + 'city' => '', + 'zip_lbl' => '', + 'zip' => '', + 'country_lbl' => '', + 'country' => '', + 'state_lbl' => '', + 'state' => '', + 'phone_lbl' => '', + 'phone' => '', + 'email_lbl' => '', + 'email' => '', + 'vatnumber_lbl' => '', + 'vatnumber' => '', + 'taxexempt_lbl' => '', + 'taxexempt' => '', + 'user_taxexempt_request_lbl' => '', + 'user_taxexempt_request' => '', + 'billing_extrafield' => '', + 'billing_address_end' => '' ); $newShippingTags = array( - 'shipping_address_start' => '', - 'companyname_lbl' => '', - 'companyname' => '', - 'firstname_lbl' => '', - 'firstname' => '', - 'lastname_lbl' => '', - 'lastname' => '', - 'address_lbl' => '', - 'address' => '', - 'city_lbl' => '', - 'city' => '', - 'zip_lbl' => '', - 'zip' => '', - 'country_lbl' => '', - 'country' => '', - 'state_lbl' => '', - 'state' => '', - 'phone_lbl' => '', - 'phone' => '', - 'shipping_extrafield' => '', - 'shipping_address_end' => '' + 'shipping_address_start' => '', + 'companyname_lbl' => '', + 'companyname' => '', + 'firstname_lbl' => '', + 'firstname' => '', + 'lastname_lbl' => '', + 'lastname' => '', + 'address_lbl' => '', + 'address' => '', + 'city_lbl' => '', + 'city' => '', + 'zip_lbl' => '', + 'zip' => '', + 'country_lbl' => '', + 'country' => '', + 'state_lbl' => '', + 'state' => '', + 'phone_lbl' => '', + 'phone' => '', + 'shipping_extrafield' => '', + 'shipping_address_end' => '' ) ?>
    @@ -80,519 +81,691 @@
    - item->section) - { - case 'category': - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_CATEGORY, JText::_("COM_REDSHOP_FIELDS") - ); - - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_PRODUCT, JText::_("COM_REDSHOP_TEMPLATE_PRODUCT_FIELDS_TITLE") - ); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array( - 'tags' => RedshopHelperTemplate::getTemplateTags($this->item->section), - 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_CATEGORY_HINT') - ) - ); - - $addToCartAvailable = RedshopHelperTemplate::getTemplate('add_to_cart'); - $tags = array(); - foreach ($addToCartAvailable as $tag): - $tags['form_addtocart:' . $tag->name] = JText::_('COM_REDSHOP_ADD_TO_CART_TEMPLATE_AVAILABLE_HINT'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', - array( - 'tags' => $tags, - 'header' => JText::_('COM_REDSHOP_ADD_TO_CART') - ) - ); - - $availableTags = RedshopHelperTemplate::getTemplate('related_product'); - $tags = array(); - foreach ($availableTags as $tag): - $key = 'related_product_lightbox:' . $tag->name . '[:lightboxwidth][:lightboxheight]'; - $tags[$key] = JText::_("COM_REDSHOP_EXAMPLE_TEMPLATE") . ': {related_product_lightbox:' . $tag->name . ':600:300}'; - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags, 'header' => JText::_('COM_REDSHOP_RELATED_PRODUCT_LIGHTBOX_TEMPLATE_AVAILABLE_HINT'))); - ?> + item->section) { + case 'category': + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_CATEGORY, + JText::_("COM_REDSHOP_FIELDS") + ); + + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_PRODUCT, + JText::_("COM_REDSHOP_TEMPLATE_PRODUCT_FIELDS_TITLE") + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => RedshopHelperTemplate::getTemplateTags($this->item->section), + 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_CATEGORY_HINT') + ) + ); + + $addToCartAvailable = RedshopHelperTemplate::getTemplate('add_to_cart'); + $tags = array(); + foreach ($addToCartAvailable as $tag): + $tags['form_addtocart:' . $tag->name] = JText::_( + 'COM_REDSHOP_ADD_TO_CART_TEMPLATE_AVAILABLE_HINT' + ); + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_('COM_REDSHOP_ADD_TO_CART') + ) + ); + + $availableTags = RedshopHelperTemplate::getTemplate('related_product'); + $tags = array(); + foreach ($availableTags as $tag): + $key = 'related_product_lightbox:' . $tag->name . '[:lightboxwidth][:lightboxheight]'; + $tags[$key] = JText::_( + "COM_REDSHOP_EXAMPLE_TEMPLATE" + ) . ': {related_product_lightbox:' . $tag->name . ':600:300}'; + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_( + 'COM_REDSHOP_RELATED_PRODUCT_LIGHTBOX_TEMPLATE_AVAILABLE_HINT' + ) + ) + ); + ?>

    :

    - RedshopHelperTemplate::getTemplateTags($this->item->section), - 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_GIFTCARD_HINT') - ) - ); - - break; - case 'product': - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_PRODUCT, JText::_("COM_REDSHOP_PRODUCT_FIELDS") - ); - - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_PRODUCT_USERFIELD, JText::_("COM_REDSHOP_PRODUCT_USERFIELD") - ); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array( - 'tags' => RedshopHelperTemplate::getTemplateTags($this->item->section), - 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_PRODUCT_HINT') - ) - ); - - $addToCartAvailable = RedshopHelperTemplate::getTemplate('add_to_cart'); - $tags = array(); - foreach ($addToCartAvailable as $tag): - $tags['form_addtocart:' . $tag->name] = JText::_('COM_REDSHOP_ADD_TO_CART_TEMPLATE_AVAILABLE_HINT'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags, 'header' => JText::_('COM_REDSHOP_ADD_TO_CART'))); - - $availableTags = RedshopHelperTemplate::getTemplate('attribute_template'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['attribute_template:' . $tag->name] = JText::_('COM_REDSHOP_ATTRIBUTE_TEMPLATE'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_ATTRIBUTE_HINT'))); - - $availableTags = RedshopHelperTemplate::getTemplate('attributewithcart_template'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['attributewithcart_template:' . $tag->name] = JText::_('COM_REDSHOP_ATTRIBUTE_WITH_CART_TEMPLATE'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_ATTRIBUTE_WITH_CART_HINT'))); - - $availableTags = RedshopHelperTemplate::getTemplate('related_product'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['related_product:' . $tag->name] = JText::_('COM_REDSHOP_RELATED_PRODUCT_TEMPLATE'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_RELATED_PRODUCT_HINT'))); - - $availableTags = RedshopHelperTemplate::getTemplate('wrapper_template'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['wrapper_template:' . $tag->name] = JText::_('COM_REDSHOP_WRAPPER_TEMPLATE'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_WRAPPER_HINT'))); - - break; - case 'product_sample': - echo RedshopHelperTemplate::renderFieldTagHints(RedshopHelperExtrafields::SECTION_COLOR_SAMPLE); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags($this->item->section)) - ); - - break; - case 'manufacturer': - echo RedshopHelperTemplate::renderFieldTagHints(RedshopHelperExtrafields::SECTION_MANUFACTURER); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags($this->item->section)) - ); - - break; - case 'manufacturer_products': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags($this->item->section)) - ); - - $addToCartAvailable = RedshopHelperTemplate::getTemplate('add_to_cart'); - $tags = array(); - foreach ($addToCartAvailable as $tag): - $tags['form_addtocart:' . $tag->name] = JText::_('COM_REDSHOP_ADD_TO_CART_TEMPLATE_AVAILABLE_HINT'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags, 'header' => JText::_('COM_REDSHOP_ADD_TO_CART'))); - - break; - case 'categoryproduct': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('category_product')) - ); - - break; - case 'catalog': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('catalogue')) - ); - - break; - case 'order_detail': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('order_detail')) - ); - - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS, JText::_("COM_REDSHOP_CUSTOMER_SHIPPING_ADDRESS") - ); - - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS, JText::_("COM_REDSHOP_COMPANY_SHIPPING_ADDRESS") - ); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => $newBillingTags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_BILLING_HINT')) - ); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => $newShippingTags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_SHIPPING_HINT')) - ); - - break; - case 'order_receipt': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('order_receipt')) - ); - - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS, JText::_("COM_REDSHOP_CUSTOMER_SHIPPING_ADDRESS") - ); - - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS, JText::_("COM_REDSHOP_COMPANY_SHIPPING_ADDRESS") - ); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => $newBillingTags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_BILLING_HINT')) - ); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => $newShippingTags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_SHIPPING_HINT')) - ); - - break; - case 'order_print': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('order_print')) - ); - - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS, JText::_("COM_REDSHOP_CUSTOMER_SHIPPING_ADDRESS") - ); - - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS, JText::_("COM_REDSHOP_COMPANY_SHIPPING_ADDRESS") - ); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => $newBillingTags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_BILLING_HINT')) - ); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => $newShippingTags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_SHIPPING_HINT')) - ); - - break; - case 'order_list': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('orderlist')) - ); - - break; - case 'related_product': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('related_product')) - ); - - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_PRODUCT, JText::_("COM_REDSHOP_PRODUCT_FIELDS") - ); - - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_PRODUCT_USERFIELD, JText::_("COM_REDSHOP_PRODUCT_USERFIELD") - ); - - break; - case 'attribute_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('attribute')) - ); - - break; - case 'attributewithcart_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('attribute_with_cart')) - ); - - $availableTags = RedshopHelperTemplate::getTemplate('add_to_cart'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['form_addtocart:' . $tag->name] = JText::_('COM_REDSHOP_ADD_TO_CART_TEMPLATE_AVAILABLE_HINT'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags, 'header' => JText::_('COM_REDSHOP_ADD_TO_CART'))); - break; - case 'accessory_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('accessory')) - ); - break; - case 'wrapper_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('wrapper')) - ); - - break; - case 'wishlist_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('wishlist')) - ); - - break; - case 'wishlist_mail_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('wishlist_mail')) - ); - - break; - case 'ask_question_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('ask_question')) - ); - - break; - case 'ajax_cart_detail_box': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array( - 'tags' => RedshopHelperTemplate::getTemplateTags('ajax_product'), - 'header' => JText::_('COM_REDSHOP_AJAX_CART_BOX_DETAIL_TEMPLATE_HINT') - ) - ); - - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_USER_INFORMATIONS - ); - - $availableTags = RedshopHelperTemplate::getTemplate('add_to_cart'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['form_addtocart:' . $tag->name] = JText::_('COM_REDSHOP_ADD_TO_CART_TEMPLATE_AVAILABLE_HINT'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags, 'header' => JText::_('COM_REDSHOP_ADD_TO_CART'))); - - break; - case 'redproductfinder': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('redproductfinder')) - ); - - $availableTags = RedshopHelperTemplate::getTemplate('add_to_cart'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['form_addtocart:' . $tag->name] = JText::_('COM_REDSHOP_ADD_TO_CART_TEMPLATE_AVAILABLE_HINT'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags, 'header' => JText::_('COM_REDSHOP_ADD_TO_CART'))); - - break; - case 'account_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('account')) - ); - break; - case 'shippingbox': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('shipping_box')) - ); - break; - case 'onestep_checkout': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('onestep_checkout')) - ); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => $newBillingTags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_BILLING_HINT')) - ); - - $availableTags = RedshopHelperTemplate::getTemplate('checkout'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['checkout_template:' . $tag->name] = JText::_('COM_REDSHOP_CHECKOUT_TEMPLATE'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags)); - - $availableTags = RedshopHelperTemplate::getTemplate('shippingbox'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['shippingbox_template:' . $tag->name] = JText::_('COM_REDSHOP_SHIPPING_BOX_TEMPLATE'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags)); - - $availableTags = RedshopHelperTemplate::getTemplate('redshop_shipping'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['shipping_template:' . $tag->name] = JText::_('COM_REDSHOP_SHIPPING_METHOD_TEMPLATE'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags)); - - $availableTags = RedshopHelperTemplate::getTemplate('redshop_payment'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['payment_template:' . $tag->name] = JText::_('COM_REDSHOP_PAYMENT_METHOD_TEMPLATE'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags)); - - break; - case 'change_cart_attribute': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('change_cart_attribute')) - ); - - $availableTags = RedshopHelperTemplate::getTemplate('attribute_template'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['attribute_template:' . $tag->name] = JText::_('COM_REDSHOP_ATTRIBUTE_TEMPLATE'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags)); - - $availableTags = RedshopHelperTemplate::getTemplate('attributewithcart_template'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['attributewithcart_template:' . $tag->name] = JText::_('COM_REDSHOP_ATTRIBUTE_WITH_CART_TEMPLATE'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags)); - - break; - case 'product_content_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('product_content')) - ); - - break; - case 'billing_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('billing')) - ); - - $availableTags = RedshopHelperTemplate::getTemplate('private_billing_template'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['private_billing_template:' . $tag->name] = JText::_('COM_REDSHOP_PRIVATE_BILLING_TEMPLATE'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags, 'header' => JText::_('COM_REDSHOP_PRIVATE_BILLING_TEMPLATE'))); - - $availableTags = RedshopHelperTemplate::getTemplate('company_billing_template'); - $tags = array(); - foreach ($availableTags as $tag): - $tags['company_billing_template:' . $tag->name] = JText::_('COM_REDSHOP_COMPANY_BILLING_TEMPLATE'); - endforeach; - echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags, 'header' => JText::_('COM_REDSHOP_COMPANY_BILLING_TEMPLATE'))); - - break; - case 'private_billing_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('private_billing')) - ); - - break; - case 'company_billing_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('company_billing')) - ); - echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS, JText::_("COM_REDSHOP_FIELDS") - ); - - break; - case 'shipping_template': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('shipping')) - ); - - break; - case 'stock_note': - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags('stock_note')) - ); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => $newBillingTags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_BILLING_HINT')) - ); - - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => $newShippingTags, 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_SHIPPING_HINT')) - ); - - break; + RedshopHelperTemplate::getTemplateTags($this->item->section), + 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_GIFTCARD_HINT') + ) + ); + + break; + case 'product': + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_PRODUCT, + JText::_("COM_REDSHOP_PRODUCT_FIELDS") + ); + + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_PRODUCT_USERFIELD, + JText::_("COM_REDSHOP_PRODUCT_USERFIELD") + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => RedshopHelperTemplate::getTemplateTags($this->item->section), + 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_PRODUCT_HINT') + ) + ); + + $addToCartAvailable = RedshopHelperTemplate::getTemplate('add_to_cart'); + $tags = array(); + foreach ($addToCartAvailable as $tag): + $tags['form_addtocart:' . $tag->name] = JText::_( + 'COM_REDSHOP_ADD_TO_CART_TEMPLATE_AVAILABLE_HINT' + ); + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_('COM_REDSHOP_ADD_TO_CART') + ) + ); + + $availableTags = RedshopHelperTemplate::getTemplate('attribute_template'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['attribute_template:' . $tag->name] = JText::_( + 'COM_REDSHOP_ATTRIBUTE_TEMPLATE' + ); + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_( + 'COM_REDSHOP_TEMPLATE_TAG_ATTRIBUTE_HINT' + ) + ) + ); + + $availableTags = RedshopHelperTemplate::getTemplate('attributewithcart_template'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['attributewithcart_template:' . $tag->name] = JText::_( + 'COM_REDSHOP_ATTRIBUTE_WITH_CART_TEMPLATE' + ); + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_( + 'COM_REDSHOP_TEMPLATE_TAG_ATTRIBUTE_WITH_CART_HINT' + ) + ) + ); + + $availableTags = RedshopHelperTemplate::getTemplate('related_product'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['related_product:' . $tag->name] = JText::_( + 'COM_REDSHOP_RELATED_PRODUCT_TEMPLATE' + ); + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_( + 'COM_REDSHOP_TEMPLATE_TAG_RELATED_PRODUCT_HINT' + ) + ) + ); + + $availableTags = RedshopHelperTemplate::getTemplate('wrapper_template'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['wrapper_template:' . $tag->name] = JText::_( + 'COM_REDSHOP_WRAPPER_TEMPLATE' + ); + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_( + 'COM_REDSHOP_TEMPLATE_TAG_WRAPPER_HINT' + ) + ) + ); + + break; + case 'product_sample': + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_COLOR_SAMPLE + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags($this->item->section)) + ); + + break; + case 'manufacturer': + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_MANUFACTURER + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags($this->item->section)) + ); + + break; + case 'manufacturer_products': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags($this->item->section)) + ); + + $addToCartAvailable = RedshopHelperTemplate::getTemplate('add_to_cart'); + $tags = array(); + foreach ($addToCartAvailable as $tag): + $tags['form_addtocart:' . $tag->name] = JText::_( + 'COM_REDSHOP_ADD_TO_CART_TEMPLATE_AVAILABLE_HINT' + ); + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_('COM_REDSHOP_ADD_TO_CART') + ) + ); + + break; + case 'categoryproduct': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('category_product')) + ); + + break; + case 'catalog': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('catalogue')) + ); + + break; + case 'order_detail': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('order_detail')) + ); + + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS, + JText::_("COM_REDSHOP_CUSTOMER_SHIPPING_ADDRESS") + ); + + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS, + JText::_("COM_REDSHOP_COMPANY_SHIPPING_ADDRESS") + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $newBillingTags, + 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_BILLING_HINT') + ) + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $newShippingTags, + 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_SHIPPING_HINT') + ) + ); + + break; + case 'order_receipt': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('order_receipt')) + ); + + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS, + JText::_("COM_REDSHOP_CUSTOMER_SHIPPING_ADDRESS") + ); + + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS, + JText::_("COM_REDSHOP_COMPANY_SHIPPING_ADDRESS") + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $newBillingTags, + 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_BILLING_HINT') + ) + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $newShippingTags, + 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_SHIPPING_HINT') + ) + ); + + break; + case 'order_print': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('order_print')) + ); + + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS, + JText::_("COM_REDSHOP_CUSTOMER_SHIPPING_ADDRESS") + ); + + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS, + JText::_("COM_REDSHOP_COMPANY_SHIPPING_ADDRESS") + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $newBillingTags, + 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_BILLING_HINT') + ) + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $newShippingTags, + 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_SHIPPING_HINT') + ) + ); + + break; + case 'order_list': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('orderlist')) + ); + + break; + case 'related_product': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('related_product')) + ); + + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_PRODUCT, + JText::_("COM_REDSHOP_PRODUCT_FIELDS") + ); + + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_PRODUCT_USERFIELD, + JText::_("COM_REDSHOP_PRODUCT_USERFIELD") + ); + + break; + case 'attribute_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('attribute')) + ); + + break; + case 'attributewithcart_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('attribute_with_cart')) + ); + + $availableTags = RedshopHelperTemplate::getTemplate('add_to_cart'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['form_addtocart:' . $tag->name] = JText::_( + 'COM_REDSHOP_ADD_TO_CART_TEMPLATE_AVAILABLE_HINT' + ); + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_('COM_REDSHOP_ADD_TO_CART') + ) + ); + break; + case 'accessory_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('accessory')) + ); + break; + case 'wrapper_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('wrapper')) + ); + + break; + case 'wishlist_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('wishlist')) + ); + + break; + case 'wishlist_mail_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('wishlist_mail')) + ); + + break; + case 'ask_question_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('ask_question')) + ); + + break; + case 'ajax_cart_detail_box': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => RedshopHelperTemplate::getTemplateTags('ajax_product'), + 'header' => JText::_('COM_REDSHOP_AJAX_CART_BOX_DETAIL_TEMPLATE_HINT') + ) + ); + + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_USER_INFORMATIONS + ); + + $availableTags = RedshopHelperTemplate::getTemplate('add_to_cart'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['form_addtocart:' . $tag->name] = JText::_( + 'COM_REDSHOP_ADD_TO_CART_TEMPLATE_AVAILABLE_HINT' + ); + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_('COM_REDSHOP_ADD_TO_CART') + ) + ); + + break; + case 'redproductfinder': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('redproductfinder')) + ); + + $availableTags = RedshopHelperTemplate::getTemplate('add_to_cart'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['form_addtocart:' . $tag->name] = JText::_( + 'COM_REDSHOP_ADD_TO_CART_TEMPLATE_AVAILABLE_HINT' + ); + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_('COM_REDSHOP_ADD_TO_CART') + ) + ); + + break; + case 'account_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('account')) + ); + break; + case 'shippingbox': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('shipping_box')) + ); + break; + case 'onestep_checkout': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('onestep_checkout')) + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $newBillingTags, + 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_BILLING_HINT') + ) + ); + + $availableTags = RedshopHelperTemplate::getTemplate('checkout'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['checkout_template:' . $tag->name] = JText::_( + 'COM_REDSHOP_CHECKOUT_TEMPLATE' + ); + endforeach; + echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags)); + + $availableTags = RedshopHelperTemplate::getTemplate('shippingbox'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['shippingbox_template:' . $tag->name] = JText::_( + 'COM_REDSHOP_SHIPPING_BOX_TEMPLATE' + ); + endforeach; + echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags)); + + $availableTags = RedshopHelperTemplate::getTemplate('redshop_shipping'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['shipping_template:' . $tag->name] = JText::_( + 'COM_REDSHOP_SHIPPING_METHOD_TEMPLATE' + ); + endforeach; + echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags)); + + $availableTags = RedshopHelperTemplate::getTemplate('redshop_payment'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['payment_template:' . $tag->name] = JText::_( + 'COM_REDSHOP_PAYMENT_METHOD_TEMPLATE' + ); + endforeach; + echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags)); + + break; + case 'change_cart_attribute': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('change_cart_attribute')) + ); + + $availableTags = RedshopHelperTemplate::getTemplate('attribute_template'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['attribute_template:' . $tag->name] = JText::_( + 'COM_REDSHOP_ATTRIBUTE_TEMPLATE' + ); + endforeach; + echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags)); + + $availableTags = RedshopHelperTemplate::getTemplate('attributewithcart_template'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['attributewithcart_template:' . $tag->name] = JText::_( + 'COM_REDSHOP_ATTRIBUTE_WITH_CART_TEMPLATE' + ); + endforeach; + echo RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $tags)); + + break; + case 'product_content_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('product_content')) + ); + + break; + case 'billing_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('billing')) + ); + + $availableTags = RedshopHelperTemplate::getTemplate('private_billing_template'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['private_billing_template:' . $tag->name] = JText::_( + 'COM_REDSHOP_PRIVATE_BILLING_TEMPLATE' + ); + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_( + 'COM_REDSHOP_PRIVATE_BILLING_TEMPLATE' + ) + ) + ); + + $availableTags = RedshopHelperTemplate::getTemplate('company_billing_template'); + $tags = array(); + foreach ($availableTags as $tag): + $tags['company_billing_template:' . $tag->name] = JText::_( + 'COM_REDSHOP_COMPANY_BILLING_TEMPLATE' + ); + endforeach; + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $tags, + 'header' => JText::_( + 'COM_REDSHOP_COMPANY_BILLING_TEMPLATE' + ) + ) + ); + + break; + case 'private_billing_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('private_billing')) + ); + + break; + case 'company_billing_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('company_billing')) + ); + echo RedshopHelperTemplate::renderFieldTagHints( + RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS, + JText::_("COM_REDSHOP_FIELDS") + ); + + break; + case 'shipping_template': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('shipping')) + ); + + break; + case 'stock_note': + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags('stock_note')) + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $newBillingTags, + 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_BILLING_HINT') + ) + ); + + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array( + 'tags' => $newShippingTags, + 'header' => JText::_('COM_REDSHOP_TEMPLATE_TAG_SHIPPING_HINT') + ) + ); + + break; case 'quotation_cart': echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_QUOTATION, JText::_("COM_REDSHOP_FIELDS") + RedshopHelperExtrafields::SECTION_QUOTATION, + JText::_("COM_REDSHOP_FIELDS") ); echo RedshopLayoutHelper::render( @@ -604,7 +777,8 @@ case 'redshop_payment': echo RedshopHelperTemplate::renderFieldTagHints( - RedshopHelperExtrafields::SECTION_PAYMENT_GATEWAY, JText::_("COM_REDSHOP_FIELDS") + RedshopHelperExtrafields::SECTION_PAYMENT_GATEWAY, + JText::_("COM_REDSHOP_FIELDS") ); echo RedshopLayoutHelper::render( @@ -614,40 +788,44 @@ break; - default: - echo RedshopLayoutHelper::render( - 'templates.tags_hint', - array('tags' => RedshopHelperTemplate::getTemplateTags($this->item->section)) - ); + default: + echo RedshopLayoutHelper::render( + 'templates.tags_hint', + array('tags' => RedshopHelperTemplate::getTemplateTags($this->item->section)) + ); - break; - } - ?> + break; + } + ?>
    - item->section, true); - ?> - - - + item->section, + true + ); + ?> + + +
    - $texts): ?> - + $texts): ?> +
    - + - + - +
    {name ?>}{name ?> + } desc ?>
    - - + +
    diff --git a/component/admin/views/template/tmpl/index.html b/component/admin/views/template/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/template/tmpl/index.html +++ b/component/admin/views/template/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/template/view.html.php b/component/admin/views/template/view.html.php index 865a6c45ed7..1b307a80d6e 100644 --- a/component/admin/views/template/view.html.php +++ b/component/admin/views/template/view.html.php @@ -18,11 +18,11 @@ */ class RedshopViewTemplate extends RedshopViewForm { - /** - * Split fieldset in form into column - * - * @var integer - * @since 2.0.7 - */ - public $formFieldsetsColumn = 1; + /** + * Split fieldset in form into column + * + * @var integer + * @since 2.0.7 + */ + public $formFieldsetsColumn = 1; } diff --git a/component/admin/views/templates/tmpl/default.php b/component/admin/views/templates/tmpl/default.php index 1c7ac1b8cd2..9502fcbb72c 100644 --- a/component/admin/views/templates/tmpl/default.php +++ b/component/admin/views/templates/tmpl/default.php @@ -1,4 +1,5 @@ section); + /** + * Method for render 'Published' column + * + * @param array $config Row config. + * @param int $index Row index. + * @param object $row Row data. + * + * @return string + * + * @since 2.0.7 + */ + public function onRenderColumn($config, $index, $row) + { + if ($config['dataCol'] === 'section') { + $return = RedshopHelperTemplate::getTemplateSections($row->section); - return is_string($return) ? $return : ''; - } + return is_string($return) ? $return : ''; + } - return parent::onRenderColumn($config, $index, $row); - } + return parent::onRenderColumn($config, $index, $row); + } } diff --git a/component/admin/views/text/index.html b/component/admin/views/text/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/text/index.html +++ b/component/admin/views/text/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/text/tmpl/index.html b/component/admin/views/text/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/text/tmpl/index.html +++ b/component/admin/views/text/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/texts/tmpl/default.php b/component/admin/views/texts/tmpl/default.php index 450631c17b3..6970c2f0667 100644 --- a/component/admin/views/texts/tmpl/default.php +++ b/component/admin/views/texts/tmpl/default.php @@ -1,4 +1,5 @@ {$config['dataCol']}; + $value = $row->{$config['dataCol']}; - if ($value == 'category') - { - return '' . JText::_('COM_REDSHOP_TEXT_SECTION_OPTION_CATEGORY') . ''; - } - elseif ($value == 'newsletter') - { - return '' . JText::_('COM_REDSHOP_TEXT_SECTION_OPTION_NEWSLETTER') . ''; - } + if ($value == 'category') { + return '' . JText::_( + 'COM_REDSHOP_TEXT_SECTION_OPTION_CATEGORY' + ) . ''; + } elseif ($value == 'newsletter') { + return '' . JText::_( + 'COM_REDSHOP_TEXT_SECTION_OPTION_NEWSLETTER' + ) . ''; + } - return '' . JText::_('COM_REDSHOP_TEXT_SECTION_OPTION_PRODUCT') . ''; - } + return '' . JText::_('COM_REDSHOP_TEXT_SECTION_OPTION_PRODUCT') . ''; + } } diff --git a/component/admin/views/tool_image/index.html b/component/admin/views/tool_image/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/tool_image/index.html +++ b/component/admin/views/tool_image/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/tool_image/tmpl/default.php b/component/admin/views/tool_image/tmpl/default.php index ed5d392bc30..3ee8f2bf4be 100644 --- a/component/admin/views/tool_image/tmpl/default.php +++ b/component/admin/views/tool_image/tmpl/default.php @@ -1,4 +1,5 @@ ": 1 }, - function(response){ + function (response) { $("a").removeClass("disabled").prop("disabled", false); $(".images-loading").hide(); $(".images-status-log").html(''); - for (i = 0; i < response.length; i++) - { + for (i = 0; i < response.length; i++) { $(".images-status-log").append('

    ' + response[i] + '

    '); } }, @@ -38,7 +38,7 @@ function(response){ }); // Image size check - $("#images-size-check").click(function(event){ + $("#images-size-check").click(function (event) { event.preventDefault(); $("a").addClass("disabled").prop("disabled", true); @@ -50,7 +50,7 @@ function(response){ { "": 1 }, - function(response){ + function (response) { $(".images-status-log").html('

    ' + response + '

    '); processImageCheck(); } @@ -60,15 +60,14 @@ function(response){ })(jQuery);
    - availableVersions)): ?> + availableVersions)): ?>
    @@ -146,7 +147,7 @@ function (response) { - + @@ -155,9 +156,10 @@ function (response) { - availableVersions as $availableVersion): ?> + availableVersions as $availableVersion): ?> - version ?> + version ?> - + - +
    diff --git a/component/admin/views/tool_update/tmpl/index.html b/component/admin/views/tool_update/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/tool_update/tmpl/index.html +++ b/component/admin/views/tool_update/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/tool_update/view.html.php b/component/admin/views/tool_update/view.html.php index a1b4b71502f..6393e4d9df5 100644 --- a/component/admin/views/tool_update/view.html.php +++ b/component/admin/views/tool_update/view.html.php @@ -18,32 +18,32 @@ */ class RedshopViewTool_Update extends RedshopViewAdmin { - /** - * @var array - */ - public $availableVersions; + /** + * @var array + */ + public $availableVersions; - /** - * Display template function - * - * @param string $tpl template variable - * - * @return mixed - * @throws Exception - * - * @since 2.1.0 - */ - public function display($tpl = null) - { - /** @var RedshopModelTool $model */ - $model = $this->getModel(); + /** + * Display template function + * + * @param string $tpl template variable + * + * @return mixed + * @throws Exception + * + * @since 2.1.0 + */ + public function display($tpl = null) + { + /** @var RedshopModelTool $model */ + $model = $this->getModel(); - $this->availableVersions = $model->getAvailableUpdate(); + $this->availableVersions = $model->getAvailableUpdate(); - JFactory::getDocument()->setTitle(JText::_('COM_REDSHOP_TOOL')); - JToolbarHelper::title(JText::_('COM_REDSHOP_TOOL')); + JFactory::getDocument()->setTitle(JText::_('COM_REDSHOP_TOOL')); + JToolbarHelper::title(JText::_('COM_REDSHOP_TOOL')); - // Display the template - parent::display($tpl); - } + // Display the template + parent::display($tpl); + } } diff --git a/component/admin/views/user/tmpl/default.php b/component/admin/views/user/tmpl/default.php index fdf3f0457af..83cf6c07c5c 100644 --- a/component/admin/views/user/tmpl/default.php +++ b/component/admin/views/user/tmpl/default.php @@ -1,4 +1,5 @@ input->get('filter'); -$model = $this->getModel('user'); +$filter = JFactory::getApplication()->input->get('filter'); +$model = $this->getModel('user'); ?>
    -
    -
    -
    - - "> - +
    +
    +
    + + "> + -
    -
    +
    +
    -
    - - lists ['shopper_group'];?> -
    -
    - - lists ['tax_exempt_request'];?> -
    -
    -
    - - - - - - - - - - - - - - - + + lists ['shopper_group']; ?> + +
    + + lists ['tax_exempt_request']; ?> +
    + +
    +
    lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']); ?>lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']);?>lists ['order_Dir'], $this->lists ['order']);?>
    + + + + + + + + + + + + + + user); $i < $n; $i++) - { - $row = $this->user [$i]; - $row->id = $row->user_id; + for ($i = 0, $n = count($this->user); $i < $n; $i++) { + $row = $this->user [$i]; + $row->id = $row->user_id; - $link = RedshopHelperUtility::getSSLLink( - 'index.php?option=com_redshop&view=user_detail&task=edit&user_id=' . $row->id . '&cid[]=' . $row->users_info_id - ); + $link = RedshopHelperUtility::getSSLLink( + 'index.php?option=com_redshop&view=user_detail&task=edit&user_id=' . $row->id . '&cid[]=' . $row->users_info_id + ); - $iscompany = JText::_('COM_REDSHOP_USER_CUSTOMER'); + $iscompany = JText::_('COM_REDSHOP_USER_CUSTOMER'); - if ($row->is_company) - { - $iscompany = JText::_('COM_REDSHOP_USER_COMPANY'); - } + if ($row->is_company) { + $iscompany = JText::_('COM_REDSHOP_USER_COMPANY'); + } - $fisrt_name = '' . $row->firstname . ''; - $last_name = $row->lastname; - ?> - "> - - - - - - - "> + + + + + + + - - - - - - - -
    lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>lists ['order_Dir'], + $this->lists ['order'] + ); ?>
    pagination->getRowOffset($i);?>users_info_id);?> username;?> - shopper_group_id); + $fisrt_name = '' . $row->firstname . ''; + $last_name = $row->lastname; + ?> +
    pagination->getRowOffset($i); ?>users_info_id); ?> username; ?> + shopper_group_id); - if (count($shoppergroup) > 0) - { - echo $shoppergroup[0]->text; - } - ?> - - users_info_id); - echo RedshopHelperProductPrice::formattedPrice($totalsales); - ?> - users_info_id;?>
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter(); ?> -
    -
    - - - - - - + if (count($shoppergroup) > 0) { + echo $shoppergroup[0]->text; + } + ?> + + + users_info_id); + echo RedshopHelperProductPrice::formattedPrice($totalsales); + ?> + + users_info_id; ?> + + + + + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?> + + + +
    + + + + + +
    diff --git a/component/admin/views/user/tmpl/user_sync.php b/component/admin/views/user/tmpl/user_sync.php index 6140c4d65cc..c838cf9012b 100644 --- a/component/admin/views/user/tmpl/user_sync.php +++ b/component/admin/views/user/tmpl/user_sync.php @@ -1,4 +1,5 @@
    -
    -
    -
    -
    +
    +
    +
    +
    -
    -
    -
    -
    -
    - sync_user) - { - echo ''; - echo JText::_("COM_REDSHOP_ADDED"); - echo ' ' . $this->sync_user . ' '; - echo JText::_("COM_REDSHOP_YES_SYNC"); - echo '.'; - } - else - { - echo ''; - echo JText::_('COM_REDSHOP_NO_SYNC'); - echo '!'; - } - ?> -
    -
    -
    -
    -
    -
    -
    -
    +
    +
    +
    +
    +
    + sync_user) { + echo ''; + echo JText::_("COM_REDSHOP_ADDED"); + echo ' ' . $this->sync_user . ' '; + echo JText::_("COM_REDSHOP_YES_SYNC"); + echo '.'; + } else { + echo ''; + echo JText::_('COM_REDSHOP_NO_SYNC'); + echo '!'; + } + ?> +
    +
    +
    +
    +
    +
    +
    +
    -
    -
    +
    +
    diff --git a/component/admin/views/user/view.html.php b/component/admin/views/user/view.html.php index c39e9e418fa..6b700dd46ce 100644 --- a/component/admin/views/user/view.html.php +++ b/component/admin/views/user/view.html.php @@ -1,4 +1,5 @@ setTitle(JText::_('COM_REDSHOP_USER')); + $document->setTitle(JText::_('COM_REDSHOP_USER')); - $this->state = $this->get('State'); - $sync = JFactory::getApplication()->input->get('sync'); - $spgrp_filter = $this->state->get('spgrp_filter'); - $tax_exempt_request_filter = $this->state->get('tax_exempt_request_filter'); + $this->state = $this->get('State'); + $sync = JFactory::getApplication()->input->get('sync'); + $spgrp_filter = $this->state->get('spgrp_filter'); + $tax_exempt_request_filter = $this->state->get('tax_exempt_request_filter'); - if ($sync) - { - $this->setLayout('user_sync'); - $sync_user = RedshopInstall::synchronizeUser(); - $this->sync_user = $sync_user; - } - else - { - $this->setLayout('default'); - JToolBarHelper::title(JText::_('COM_REDSHOP_USER_MANAGEMENT'), 'users redshop_user48'); - JToolbarHelper::addNew(); - JToolbarHelper::EditList(); - JToolBarHelper::deleteList(); - } + if ($sync) { + $this->setLayout('user_sync'); + $sync_user = RedshopInstall::synchronizeUser(); + $this->sync_user = $sync_user; + } else { + $this->setLayout('default'); + JToolBarHelper::title(JText::_('COM_REDSHOP_USER_MANAGEMENT'), 'users redshop_user48'); + JToolbarHelper::addNew(); + JToolbarHelper::EditList(); + JToolBarHelper::deleteList(); + } - $lists ['order'] = $this->state->get('list.ordering', 'users_info_id'); - $lists ['order_Dir'] = $this->state->get('list.direction'); + $lists ['order'] = $this->state->get('list.ordering', 'users_info_id'); + $lists ['order_Dir'] = $this->state->get('list.direction'); - $user = $this->get('Data'); - $pagination = $this->get('Pagination'); + $user = $this->get('Data'); + $pagination = $this->get('Pagination'); - $shopper_groups = Redshop\Helper\ShopperGroup::generateList(); + $shopper_groups = Redshop\Helper\ShopperGroup::generateList(); - $temps = array(); - $temps[0] = new stdClass; - $temps[0]->value = 0; - $temps[0]->text = JText::_('COM_REDSHOP_SELECT'); - $shopper_groups = array_merge($temps, $shopper_groups); + $temps = array(); + $temps[0] = new stdClass; + $temps[0]->value = 0; + $temps[0]->text = JText::_('COM_REDSHOP_SELECT'); + $shopper_groups = array_merge($temps, $shopper_groups); - $lists['shopper_group'] = JHTML::_('select.genericlist', $shopper_groups, 'spgrp_filter', - 'class="inputbox" size="1" onchange="document.adminForm.submit()"', 'value', 'text', $spgrp_filter - ); + $lists['shopper_group'] = JHTML::_( + 'select.genericlist', + $shopper_groups, + 'spgrp_filter', + 'class="inputbox" size="1" onchange="document.adminForm.submit()"', + 'value', + 'text', + $spgrp_filter + ); - $optiontax_req = array(); - $optiontax_req[] = JHTML::_('select.option', 'select', JText::_('COM_REDSHOP_SELECT')); - $optiontax_req[] = JHTML::_('select.option', '1', JText::_('COM_REDSHOP_yes')); - $optiontax_req[] = JHTML::_('select.option', '0', JText::_('COM_REDSHOP_no')); - $lists['tax_exempt_request'] = JHTML::_('select.genericlist', $optiontax_req, 'tax_exempt_request_filter', - 'class="inputbox" size="1" onchange="document.adminForm.submit()"', 'value', 'text', $tax_exempt_request_filter - ); + $optiontax_req = array(); + $optiontax_req[] = JHTML::_('select.option', 'select', JText::_('COM_REDSHOP_SELECT')); + $optiontax_req[] = JHTML::_('select.option', '1', JText::_('COM_REDSHOP_yes')); + $optiontax_req[] = JHTML::_('select.option', '0', JText::_('COM_REDSHOP_no')); + $lists['tax_exempt_request'] = JHTML::_( + 'select.genericlist', + $optiontax_req, + 'tax_exempt_request_filter', + 'class="inputbox" size="1" onchange="document.adminForm.submit()"', + 'value', + 'text', + $tax_exempt_request_filter + ); - $this->lists = $lists; - $this->user = $user; - $this->pagination = $pagination; - $this->request_url = $uri->toString(); + $this->lists = $lists; + $this->user = $user; + $this->pagination = $pagination; + $this->request_url = $uri->toString(); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/user_detail/index.html b/component/admin/views/user_detail/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/user_detail/index.html +++ b/component/admin/views/user_detail/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/user_detail/tmpl/default.php b/component/admin/views/user_detail/tmpl/default.php index 2986125b205..ff70ea97c5f 100644 --- a/component/admin/views/user_detail/tmpl/default.php +++ b/component/admin/views/user_detail/tmpl/default.php @@ -1,4 +1,5 @@ input; +$jinput = JFactory::getApplication()->input; $this->order_functions = order_functions::getInstance(); -$this->config = Redconfiguration::getInstance(); -$this->model = $this->getModel('user_detail'); -$this->flag = $jinput->getString('flag', ''); -$this->shipping = $jinput->getString('shipping', ''); -$cancel = $jinput->getString('cancel', ''); -$this->silerntuser = ($this->detail->users_info_id) ? true : false; - -if ($this->detail->users_info_id && $this->detail->user_id && $this->detail->username) -{ - $this->silerntuser = false; +$this->config = Redconfiguration::getInstance(); +$this->model = $this->getModel('user_detail'); +$this->flag = $jinput->getString('flag', ''); +$this->shipping = $jinput->getString('shipping', ''); +$cancel = $jinput->getString('cancel', ''); +$this->silerntuser = ($this->detail->users_info_id) ? true : false; + +if ($this->detail->users_info_id && $this->detail->user_id && $this->detail->username) { + $this->silerntuser = false; } /* @@ -30,173 +30,161 @@ */ $tab = 0; -if ($cancel) -{ - $tab = 2; +if ($cancel) { + $tab = 2; } -if ($this->pagination->limitstart > 0) -{ - $tab = 3; +if ($this->pagination->limitstart > 0) { + $tab = 3; } ?>
    - $tab)); - - if (!$this->shipping) - { - // Create 1st Tab - echo JHtml::_('tabs.panel', JText::_('COM_REDSHOP_GENERAL_USER_INFO'), 'tab1'); - echo $this->loadTemplate('user'); - } - - $title = ($this->shipping == 1) ? JText::_('COM_REDSHOP_SHIPPING_INFORMATION') : JText::_('COM_REDSHOP_BILLING_INFORMATION'); - echo JHtml::_('tabs.panel', $title, 'tab2'); - echo $this->loadTemplate('billing'); - - if (!$this->shipping && $this->detail->user_id != 0 || $cancel == 1) - { - echo JHtml::_('tabs.panel', JText::_('COM_REDSHOP_SHIPPING_INFORMATION'), 'tab3'); - echo $this->loadTemplate('shipping'); - } - - $this->userorders = $this->model->userOrders(); - - if ($this->detail->user_id && count($this->userorders) > 0) - { - echo JHtml::_('tabs.panel', JText::_('COM_REDSHOP_ORDER_INFORMATION'), 'tab4'); - echo $this->loadTemplate('order'); - } - - if ($this->lists['extra_field'] != "") - { - echo JHtml::_('tabs.panel', JText::_('COM_REDSHOP_EXTRA_FIELD'), 'tab5'); ?> -
    lists ['extra_field']; ?>
    '; - echo ''; - } - - // Echo plugin tabs. - $this->dispatcher->trigger('onDisplayUserTabs', array($this->detail)); - - echo JHtml::_('tabs.end'); - - if ($this->shipping) - { - $info_id = $jinput->getString('info_id', ''); - echo ' + $tab)); + + if (!$this->shipping) { + // Create 1st Tab + echo JHtml::_('tabs.panel', JText::_('COM_REDSHOP_GENERAL_USER_INFO'), 'tab1'); + echo $this->loadTemplate('user'); + } + + $title = ($this->shipping == 1) ? JText::_('COM_REDSHOP_SHIPPING_INFORMATION') : JText::_( + 'COM_REDSHOP_BILLING_INFORMATION' + ); + echo JHtml::_('tabs.panel', $title, 'tab2'); + echo $this->loadTemplate('billing'); + + if (!$this->shipping && $this->detail->user_id != 0 || $cancel == 1) { + echo JHtml::_('tabs.panel', JText::_('COM_REDSHOP_SHIPPING_INFORMATION'), 'tab3'); + echo $this->loadTemplate('shipping'); + } + + $this->userorders = $this->model->userOrders(); + + if ($this->detail->user_id && count($this->userorders) > 0) { + echo JHtml::_('tabs.panel', JText::_('COM_REDSHOP_ORDER_INFORMATION'), 'tab4'); + echo $this->loadTemplate('order'); + } + + if ($this->lists['extra_field'] != "") { + echo JHtml::_('tabs.panel', JText::_('COM_REDSHOP_EXTRA_FIELD'), 'tab5'); ?> +
    lists ['extra_field']; ?>
    '; + echo ''; + } + + // Echo plugin tabs. + $this->dispatcher->trigger('onDisplayUserTabs', array($this->detail)); + + echo JHtml::_('tabs.end'); + + if ($this->shipping) { + $info_id = $jinput->getString('info_id', ''); + echo ' '; - } - else - { - echo ''; - } -?> -
    - - - - + } else { + echo ''; + } + ?> +
    + + + +
    diff --git a/component/admin/views/user_detail/tmpl/default_billing.php b/component/admin/views/user_detail/tmpl/default_billing.php index eb122570194..e28552c1047 100644 --- a/component/admin/views/user_detail/tmpl/default_billing.php +++ b/component/admin/views/user_detail/tmpl/default_billing.php @@ -1,4 +1,5 @@ shipping && $this->detail->is_company == 1) -{ - $allowCustomer = 'style="display:none;"'; -} -else -{ - $allowCompany = 'style="display:none;"'; +if (!$this->shipping && $this->detail->is_company == 1) { + $allowCustomer = 'style="display:none;"'; +} else { + $allowCompany = 'style="display:none;"'; } $countryStyle = (isset($this->showcountry) && $this->showcountry == 0) ? ' style="display:none;" ' : ''; @@ -38,7 +36,14 @@ : - + > @@ -50,20 +55,41 @@ : - + : - + > : lists['country_code']; ?> - + > @@ -71,14 +97,28 @@
    >lists['state_code']; ?> -
    +
    : - + @@ -91,69 +131,95 @@ - get('USE_TAX_EXEMPT') == 1) - { - ?> + get('USE_TAX_EXEMPT') == 1) { + ?> > : - + > : lists['tax_exempt']; - echo JHTML::tooltip(JText::_('COM_REDSHOP_TOOLTIP_TAX_EXEMPT'), JText::_('COM_REDSHOP_TAX_EXEMPT'), 'tooltip.png', '', '', false); ?> + echo JHTML::tooltip( + JText::_('COM_REDSHOP_TOOLTIP_TAX_EXEMPT'), + JText::_('COM_REDSHOP_TAX_EXEMPT'), + 'tooltip.png', + '', + '', + false + ); ?> > : lists['requesting_tax_exempt']; ?> - + > : lists['tax_exempt_approved']; ?> - + - + - shipping)): ?> - detail->is_company == 1): ?> - lists['shipping_company_field'] != ""): ?> + shipping)): ?> + detail->is_company == 1): ?> + lists['shipping_company_field'] != ""): ?>
    lists['shipping_company_field'] ?>
    - - - lists['shipping_customer_field'] != ""): ?> + + + lists['shipping_customer_field'] != ""): ?>
    lists['shipping_customer_field'] ?>
    - - - - lists['company_field'] != ""): ?> + + + + lists['company_field'] != ""): ?>
    > - lists['company_field'] ?> + lists['company_field'] ?>
    - - lists['customer_field'] != ""): ?> + + lists['customer_field'] != ""): ?>
    > - lists['customer_field'] ?> + lists['customer_field'] ?>
    - - + + - shipping) - { - $userInfoId = \JFactory::getApplication()->input->getInt('info_id', 0); - $user = \Redshop\User\Helper::getUsers([], ['ui.users_info_id' => ['=' => $userInfoId]])[0]; - ?> + shipping) { + $userInfoId = \JFactory::getApplication()->input->getInt('info_id', 0); + $user = \Redshop\User\Helper::getUsers([], ['ui.users_info_id' => ['=' => $userInfoId]])[0]; + ?> @@ -166,7 +232,7 @@ - +
    diff --git a/component/admin/views/user_detail/tmpl/default_order.php b/component/admin/views/user_detail/tmpl/default_order.php index d9a8981d706..81ba045cb52 100644 --- a/component/admin/views/user_detail/tmpl/default_order.php +++ b/component/admin/views/user_detail/tmpl/default_order.php @@ -1,4 +1,5 @@ +?>
    - - - - - - - - - - - - userorders); $i++) - { - $row = $this->userorders[$i]; - $row->id = $row->order_id; - $link = JRoute::_('index.php?option=com_redshop&view=order_detail&task=edit&cid[]=' . $row->order_id); ?> - - - - - - - - - - - - -
    pagination->getRowOffset($i);?> - order_id;?>order_number; ?>config->convertDateFormat($row->cdate); ?>order_total);?>
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter(); ?>
    + + + + + + + + + + + + userorders); $i++) { + $row = $this->userorders[$i]; + $row->id = $row->order_id; + $link = JRoute::_('index.php?option=com_redshop&view=order_detail&task=edit&cid[]=' . $row->order_id); ?> + + + + + + + + + + + + +
    pagination->getRowOffset($i); ?> + order_id; ?>order_number; ?>config->convertDateFormat($row->cdate); ?>order_total); ?>
    + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?>
    diff --git a/component/admin/views/user_detail/tmpl/default_user.php b/component/admin/views/user_detail/tmpl/default_user.php index b8e439164a2..2843a8b4708 100644 --- a/component/admin/views/user_detail/tmpl/default_user.php +++ b/component/admin/views/user_detail/tmpl/default_user.php @@ -1,4 +1,5 @@ +defined('_JEXEC') or die; ?>
    -
    - +
    + - - silerntuser) - { - ?> - - - - - - - - - - - - - - - - - - - - - - silerntuser) - { - ?> - - - - - - - - - - - - - - - - - -
    : - - *
    -
    : - - *
    lists['shopper_group']; ?> -
    detail->user_groups, true); ?> -
    lists['block']; ?>
    lists['is_company']; ?>
    lists['sendEmail']; ?>
    -
    + + silerntuser) { + ?> + + + + + + + + + + + + + + + + + + + + + + silerntuser) { + ?> + + + + + + + + + + + + + + + + + +
    : + + *
    +
    : + + *
    lists['shopper_group']; ?> +
    detail->user_groups, true); ?> +
    lists['block']; ?>
    lists['is_company']; ?>
    lists['sendEmail']; ?>
    +
    diff --git a/component/admin/views/user_detail/tmpl/index.html b/component/admin/views/user_detail/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/user_detail/tmpl/index.html +++ b/component/admin/views/user_detail/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/user_detail/view.html.php b/component/admin/views/user_detail/view.html.php index 48f081a10fb..f097c94fe33 100644 --- a/component/admin/views/user_detail/view.html.php +++ b/component/admin/views/user_detail/view.html.php @@ -115,8 +115,12 @@ public function display($tpl = null) ); - $this->lists['block'] = JHtml::_('select.booleanlist', 'block', 'class="inputbox"', - $this->detail->block ?? 0); + $this->lists['block'] = JHtml::_( + 'select.booleanlist', + 'block', + 'class="inputbox"', + $this->detail->block ?? 0 + ); $this->lists['tax_exempt_approved'] = JHtml::_( @@ -142,12 +146,12 @@ public function display($tpl = null) JText::_('COM_REDSHOP_USER_CUSTOMER') ); - $this->lists['sendEmail'] = JHtml::_( - 'select.booleanlist', - 'sendEmail', - 'class="inputbox"', - $this->detail->sendEmail ?? 0 - ); + $this->lists['sendEmail'] = JHtml::_( + 'select.booleanlist', + 'sendEmail', + 'class="inputbox"', + $this->detail->sendEmail ?? 0 + ); $this->lists['extra_field'] = RedshopHelperExtrafields::listAllField( RedshopHelperExtrafields::SECTION_USER_INFORMATIONS, diff --git a/component/admin/views/voucher/index.html b/component/admin/views/voucher/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/voucher/index.html +++ b/component/admin/views/voucher/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/voucher/tmpl/index.html b/component/admin/views/voucher/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/voucher/tmpl/index.html +++ b/component/admin/views/voucher/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/voucher/view.html.php b/component/admin/views/voucher/view.html.php index 4498df7e787..b7f76b5c4d0 100644 --- a/component/admin/views/voucher/view.html.php +++ b/component/admin/views/voucher/view.html.php @@ -13,7 +13,7 @@ * View Voucher * * @package RedSHOP.Backend - * @subpackage View + * @subpackage View * @since 2.0.7 */ class RedshopViewVoucher extends RedshopViewForm diff --git a/component/admin/views/vouchers/tmpl/default.php b/component/admin/views/vouchers/tmpl/default.php index 450631c17b3..6970c2f0667 100644 --- a/component/admin/views/vouchers/tmpl/default.php +++ b/component/admin/views/vouchers/tmpl/default.php @@ -1,4 +1,5 @@ checked_out && JFactory::getUser()->id != $row->checked_out; - $isInline = Redshop::getConfig()->getBool('INLINE_EDITING'); - $value = $row->{$config['dataCol']}; + /** + * Method for render columns + * + * @param array $config Row config. + * @param int $index Row index. + * @param object $row Row data. + * + * @return string + * + * @throws Exception + * @since 2.0.7 + * + */ + public function onRenderColumn($config, $index, $row) + { + $isCheckedOut = $row->checked_out && JFactory::getUser()->id != $row->checked_out; + $isInline = Redshop::getConfig()->getBool('INLINE_EDITING'); + $value = $row->{$config['dataCol']}; - switch ($config['dataCol']) - { - case 'amount': - if (!$isCheckedOut && $isInline && $this->canEdit && $config['inline'] === true) - { - $display = RedshopHelperProductPrice::formattedPrice($value); + switch ($config['dataCol']) { + case 'amount': + if (!$isCheckedOut && $isInline && $this->canEdit && $config['inline'] === true) { + $display = RedshopHelperProductPrice::formattedPrice($value); - return JHtml::_('redshopgrid.inline', $config['dataCol'], $value, $display, $row->id, 'number'); - } + return JHtml::_('redshopgrid.inline', $config['dataCol'], $value, $display, $row->id, 'number'); + } - return RedshopHelperProductPrice::formattedPrice($value); + return RedshopHelperProductPrice::formattedPrice($value); - case 'free_ship': - if ($value) - { - return ''; - } + case 'free_ship': + if ($value) { + return ''; + } - return ''; + return ''; - case 'start_date': - case 'end_date': - if ($value === '0000-00-00 00:00:00') - { - return ''; - } + case 'start_date': + case 'end_date': + if ($value === '0000-00-00 00:00:00') { + return ''; + } - $tz = new \DateTimeZone(\JFactory::getConfig()->get('offset')); - $date = date_create_from_format('Y-m-d H:i:s', $value, new \DateTimeZone('UTC')); + $tz = new \DateTimeZone(\JFactory::getConfig()->get('offset')); + $date = date_create_from_format('Y-m-d H:i:s', $value, new \DateTimeZone('UTC')); - return $date->setTimezone($tz)->format(Redshop::getConfig()->get('DEFAULT_DATEFORMAT', 'd-m-Y')); + return $date->setTimezone($tz)->format(Redshop::getConfig()->get('DEFAULT_DATEFORMAT', 'd-m-Y')); - default: - return parent::onRenderColumn($config, $index, $row); - } - } + default: + return parent::onRenderColumn($config, $index, $row); + } + } } diff --git a/component/admin/views/wizard/index.html b/component/admin/views/wizard/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/wizard/index.html +++ b/component/admin/views/wizard/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/wizard/tmpl/finish.php b/component/admin/views/wizard/tmpl/finish.php index 5b1051b9f4c..8878a03492c 100644 --- a/component/admin/views/wizard/tmpl/finish.php +++ b/component/admin/views/wizard/tmpl/finish.php @@ -10,26 +10,28 @@ $params = JFactory::getApplication()->input->get('params', '', 'raw'); ?>
    -
    - - - - - - - - - - -
    -
    -
    - - - - -
    -
    +
    + + + + + + + + + + +
    +
    +
    + + + + +
    +
    diff --git a/component/admin/views/wizard/tmpl/general.php b/component/admin/views/wizard/tmpl/general.php index 57dd3c1ab72..4b8198c6d94 100644 --- a/component/admin/views/wizard/tmpl/general.php +++ b/component/admin/views/wizard/tmpl/general.php @@ -1,4 +1,5 @@ input->get('params', '', 'raw'); ?>
    -
    -
     
    -
    -
     
    -
    -
    -
    - - - - - - + + + + + +
    - -
    +
    +
     
    +
    +
     
    +
    +
    + + + + + + + - - - - + + + + - - - - - - - - - - + + + + + + + + + + - - - - - - - - - - + + + + + + + + + + - - - - + + + + - - - - - - - - - - + + + + + + + + + + - - - - - - - - - - + + + + + + + + + + - - - - - - - - - - + + + + + + + + + + - - - - + + + + - - - - - -
    + +
    - - - -
    + title="::"> + + + +
    - - - -
     
    - -
    + title="::"> + + + +
     
    + +
    + title="::"> - - -
     
    - -
    + + +
     
    + +
    + title="::"> - - lists ['shop_country'];?> -
    + + lists ['shop_country']; ?> +
    - - - lists ['default_shipping_country']; ?> -
     
    - -
    + title="::"> + + + lists ['default_shipping_country']; ?> +
     
    + +
    - - lists ['country_list'];?>
     
    - -
    + title="::"> + + lists ['country_list']; ?>
     
    + +
    - - - lists ['default_dateformat']; ?> -
     
    - -
    + title="::"> + + + lists ['default_dateformat']; ?> +
     
    + +
    - - lists ['invoice_mail_enable'];?>
    + title="::"> + + lists ['invoice_mail_enable']; ?>
    - - lists ['invoice_mail_send_option'];?>
    - - - - -
    - -
    + title="::"> + +
    lists ['invoice_mail_send_option']; ?>
    + + + + +
    + +
    diff --git a/component/admin/views/wizard/tmpl/index.html b/component/admin/views/wizard/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/wizard/tmpl/index.html +++ b/component/admin/views/wizard/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/wizard/tmpl/price.php b/component/admin/views/wizard/tmpl/price.php index 167f2818839..5ab183199a0 100644 --- a/component/admin/views/wizard/tmpl/price.php +++ b/component/admin/views/wizard/tmpl/price.php @@ -17,17 +17,17 @@
    - loadTemplate('price'); ?> + loadTemplate('price'); ?>
    - loadTemplate('vat'); ?> + loadTemplate('vat'); ?>
    - loadTemplate('discount'); ?> + loadTemplate('discount'); ?>
    diff --git a/component/admin/views/wizard/tmpl/price_discount.php b/component/admin/views/wizard/tmpl/price_discount.php index 419fc599a09..2582ae938c3 100644 --- a/component/admin/views/wizard/tmpl/price_discount.php +++ b/component/admin/views/wizard/tmpl/price_discount.php @@ -1,4 +1,5 @@
    - +
     
    - - - - - - + + +
    - -
    + + + + + + - - -
    + +
    - + title="::"> + - lists ['discount_enable']; ?>
    +
    lists ['discount_enable']; ?>
    - - - - - - + + +
    - -
    + + + + + + - - -
    + +
    - - lists ['coupons_enable'];?>
    + title="::"> + +
    lists ['coupons_enable']; ?>
    - - - - - - + + +
    - -
    + + + + + + - - -
    + +
    - - lists ['vouchers_enable'];?>
    + title="::"> + +
    lists ['vouchers_enable']; ?>
    - - - - - - + + +
    - -
    + + + + + + - - -
    + +
    - + title="::"> + - lists ['discount_type'];?>
    +
    lists ['discount_type']; ?>
    - - - - - - + + +
    - -
    + + + + + + - - -
    + +
    - - lists['shipping_after'];?>
    + title="::"> + +
    lists['shipping_after']; ?>
    diff --git a/component/admin/views/wizard/tmpl/price_price.php b/component/admin/views/wizard/tmpl/price_price.php index 5337be5e099..a293ec295df 100644 --- a/component/admin/views/wizard/tmpl/price_price.php +++ b/component/admin/views/wizard/tmpl/price_price.php @@ -1,4 +1,5 @@ - - - - - - - - + + + + + + + - - - - + + + + - - - - - - - - - - + + + + + + + + + + - - + title="::"> + + + + - - + - - - - + + + + - - + title="::"> + + + +
     
    - -
    +
     
    + +
    - - - lists ['currency_data'];?> -
    + title="::"> + + + lists ['currency_data']; ?> +
    - - - -
     
    - -
    + title="::"> + + + +
     
    + +
    - - - -
    + +
    +
    - - - -
    + title="::"> + + + +
    - - - -
    + +
    diff --git a/component/admin/views/wizard/tmpl/price_vat.php b/component/admin/views/wizard/tmpl/price_vat.php index 824385a4221..4605aac97e0 100644 --- a/component/admin/views/wizard/tmpl/price_vat.php +++ b/component/admin/views/wizard/tmpl/price_vat.php @@ -1,4 +1,5 @@ - + + echo JText::_('COM_REDSHOP_TOOLTIP_DEFAULT_VAT_COUNTRY'); + ?>::"> + echo JText::_('COM_REDSHOP_DEFAULT_VAT_COUNTRY_LBL'); + ?> lists ['default_vat_country']; - ?> + echo $this->lists ['default_vat_country']; + ?> + echo JText::_('COM_REDSHOP_TOOLTIP_DEFAULT_VAT_STATE'); + ?>::"> + echo JText::_('COM_REDSHOP_DEFAULT_VAT_STATE_LBL'); + ?> lists ['default_vat_state']; - ?> + echo $this->lists ['default_vat_state']; + ?> + echo JText::_('COM_REDSHOP_CALCULATE_VAT_BASED_ON_LBL'); + ?> lists ['calculate_vat_on']; - ?> + echo $this->lists ['calculate_vat_on']; + ?> @@ -70,54 +71,54 @@ class="editlinktip hasTip" - + + echo JText::_('COM_REDSHOP_ADD_VAT_RATES_LBL'); + ?>::"> + echo JText::_('COM_REDSHOP_ADD_VAT_RATES_LBL'); + ?> + echo JText::_('COM_REDSHOP_ADD_RATES'); + ?>  
      - taxrates); $i++) - { - $tax = $this->taxrates [$i]; + taxrates); $i++) { + $tax = $this->taxrates [$i]; - $tax_rate_id = $tax->id; - $tax_country = $tax->tax_country; - $tax_rate = $tax->tax_rate; - $tax_group_id = $tax->tax_group_id; + $tax_rate_id = $tax->id; + $tax_country = $tax->tax_country; + $tax_rate = $tax->tax_rate; + $tax_group_id = $tax->tax_group_id; - $rate_html = $tax_country . " (" . $tax_rate . ")"; - ?> + $rate_html = $tax_country . " (" . $tax_rate . ")"; + ?>
    1. - - + + Remove
    2. - +
    @@ -128,23 +129,23 @@ class="editlinktip hasTip" - + + echo JText::_('COM_REDSHOP_APPLY_VAT_ON_DISCOUNT_LBL'); + ?> lists ['apply_vat_on_discount']; - ?> + echo $this->lists ['apply_vat_on_discount']; + ?> diff --git a/component/admin/views/wizard/tmpl/terms.php b/component/admin/views/wizard/tmpl/terms.php index a8c602e3597..eb64867a12e 100644 --- a/component/admin/views/wizard/tmpl/terms.php +++ b/component/admin/views/wizard/tmpl/terms.php @@ -10,71 +10,81 @@ $params = JFactory::getApplication()->input->get('params', '', 'raw'); ?>
    -
    - - - - - - + + + + + + + + +
    - -
    + + + + + + + - + - - - - - - - - -
    + +
    - - - ::"> + + + temparray['TERMS_ARTICLE_ID']; - if ($article_id) - { - $article->load($article_id); - } - else - { - $article->title = JText::_('COM_REDSHOP_SELECT_AN_ARTICLE'); - } - $js = " + $article = JTable::getInstance('content'); + $article_id = $this->temparray['TERMS_ARTICLE_ID']; + if ($article_id) { + $article->load($article_id); + } else { + $article->title = JText::_('COM_REDSHOP_SELECT_AN_ARTICLE'); + } + $js = " function jSelectArticle_terms_article_id(id, title, catid) { document.getElementById('terms_article_id_id').value = id; document.getElementById('terms_article_id_name').value = title; SqueezeBox.close(); }"; - $doc->addScriptDeclaration($js); + $doc->addScriptDeclaration($js); - $link = 'index.php?option=com_content&view=articles&layout=modal&tmpl=component&function=jSelectArticle_terms_article_id'; - JHtml::_('behavior.modal', 'a.joom-box'); - $html = "\n" . '
    '; - $html .= '
    '; + $html .= '' . "\n"; - $html .= "\n" . ''; + $html .= "\n" . ''; - echo $html; - ?> -
    - - - -
    - - - - -
    - + echo $html; + ?> +
    + + + +
    + + + + +
    +
    diff --git a/component/admin/views/wizard/tmpl/user.php b/component/admin/views/wizard/tmpl/user.php index 9f51f83791e..cf76bab63fc 100644 --- a/component/admin/views/wizard/tmpl/user.php +++ b/component/admin/views/wizard/tmpl/user.php @@ -10,24 +10,24 @@ $params = JFactory::getApplication()->input->get('params', '', 'raw'); ?>
    -
    - - - - - - - -
    -
    - - loadTemplate('registration');?> -
    -
    - - - - -
    -
    +
    + + + + + + + +
    +
    + + loadTemplate('registration'); ?> +
    +
    + + + + +
    +
    diff --git a/component/admin/views/wizard/tmpl/user_registration.php b/component/admin/views/wizard/tmpl/user_registration.php index 472268ed08d..c6c0058edc2 100644 --- a/component/admin/views/wizard/tmpl/user_registration.php +++ b/component/admin/views/wizard/tmpl/user_registration.php @@ -1,4 +1,5 @@ -
     
    -
    - - - - - - + +
    - -
    +
     
    +
    + + + + + + - - -
    + +
    - - - lists ['register_method']; ?> -
    -
    -
     
    -
    - - - - - - + + +
    - -
    + title="::"> + + + lists ['register_method']; ?> +
    +
    +
     
    +
    + + + + + + - + - -
    + +
    - : - + title="::"> + : + -
    -
    + rows="4" cols="40"/>temparray['WELCOMEPAGE_INTROTEXT']; ?> +
    +
    get('ALLOW_CUSTOMER_REGISTER_TYPE') != 2) -{ - ?> -
     
    -
    - - - - - - + +
    - -
    +if (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') != 2) { + ?> +
     
    +
    + + + + + + - + - -
    + +
    - : - + title="::"> + : + -
    -
    -temparray['REGISTRATION_INTROTEXT']; ?> +
    +
    + get('ALLOW_CUSTOMER_REGISTER_TYPE') != 1) -{ - ?> -
     
    -
    - - - - - - + +
    - -
    +if (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') != 1) { + ?> +
     
    +
    + + + + + + - + - -
    + +
    - : - + title="::"> + : + -
    -
    -temparray['REGISTRATION_COMPANY_INTROTEXT']; ?> +
    +
    + diff --git a/component/admin/views/wizard/tmpl/user_shopper_group.php b/component/admin/views/wizard/tmpl/user_shopper_group.php index eb6aa814ff2..d32e0a892e2 100644 --- a/component/admin/views/wizard/tmpl/user_shopper_group.php +++ b/component/admin/views/wizard/tmpl/user_shopper_group.php @@ -1,4 +1,5 @@ root(); ?> - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - - - - + + + + - - - get('DEFAULT_PORTAL_LOGO'); ?> - - - + ?> + + + get('DEFAULT_PORTAL_LOGO'); ?> + + +
    - lists ['portalshop']; - ?>
    - lists ['url_after_portal_login']; - ?>
    - lists ['url_after_portal_logout']; - ?>
    - -
    - lists ['shopper_group_default_private']; +
    + lists ['portalshop']; + ?>
    + lists ['url_after_portal_login']; + ?>
    + lists ['url_after_portal_logout']; + ?>
    + +
    + lists ['shopper_group_default_private']; - ?>
    - lists ['shopper_group_default_company']; + ?>
    + lists ['shopper_group_default_company']; - ?>
    - -
    - - -
    + +
    + + +
    diff --git a/component/admin/views/wizard/tmpl/welcome.php b/component/admin/views/wizard/tmpl/welcome.php index 5cc52ed5249..0a0f3c4fc50 100644 --- a/component/admin/views/wizard/tmpl/welcome.php +++ b/component/admin/views/wizard/tmpl/welcome.php @@ -6,19 +6,26 @@ * @copyright Copyright (C) 2008 - 2019 redCOMPONENT.com. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ + ?>
    - website'; - $forum_link = 'redSHOP - redCOMPONENT Forum'; - $contact_link = 'redCOMPONENT'; - $learn_more_link = 'redcomponent.com'; + website'; + $forum_link = 'redSHOP - redCOMPONENT Forum'; + $contact_link = 'redCOMPONENT'; + $learn_more_link = 'redcomponent.com'; - ?> + ?>
    + class="wizard_redshop_features">
     
     
    diff --git a/component/admin/views/wizard/view.html.php b/component/admin/views/wizard/view.html.php index 805325db4f4..0e16da8c179 100644 --- a/component/admin/views/wizard/view.html.php +++ b/component/admin/views/wizard/view.html.php @@ -1,4 +1,5 @@ get('redshop.wizard', false); - - // If it's not created than use distribute config file - if ($wizardConfig === false) - { - $config = JPATH_BASE . '/components/com_redshop/config/config.dist.php'; - - if (JFile::exists($config)) - { - // Only load this file if this class is not declared - if (!class_exists('RedshopConfig')) - { - require_once $config; - } - - $distConfig = new RedshopConfig; - $wizardConfig = get_object_vars($distConfig); - } - else - { - $wizardConfig = array(); - } - - // Save back to session - $session->set('redshop.wizard', $wizardConfig); - } - - // Set to view variable to use in tmpl files - $this->temparray = $wizardConfig; - - $uri = JUri::getInstance(); - $db = JFactory::getDbo(); - $config = Redconfiguration::getInstance(); - $model = $this->getModel(); - $document = JFactory::getDocument(); - - $document->setTitle(JText::_('COM_REDSHOP_CONFIG')); - /** @scrutinizer ignore-deprecated */ - JHtml::script('com_redshop/redshop.validation.min.js', false, true); - /** @scrutinizer ignore-deprecated */ - JHtml::stylesheet('com_redshop/redshop.min.css', array(), true); - /** @scrutinizer ignore-deprecated */ - JHtml::stylesheet('com_redshop/redshop.wizard.min.css', array(), true); - - // Shop country - $q = "SELECT country_3_code as value,country_name as text,country_jtext from #__redshop_country ORDER BY country_name ASC"; - $db->setQuery($q); - $countries = $db->loadObjectList(); - $countries = RedshopHelperUtility::convertLanguageString($countries); - - $lists['shop_country'] = JHtml::_('select.genericlist', $countries, 'shop_country', - 'class="inputbox" size="1" ', 'value', 'text', $this->temparray['SHOP_COUNTRY'] - ); - - // Shipping Country Start - $lists['default_shipping_country'] = JHtml::_('select.genericlist', $countries, 'default_shipping_country', - 'class="inputbox" size="1" ', 'value', 'text', $this->temparray['DEFAULT_SHIPPING_COUNTRY'] - ); - - // Date Formats - $default_dateformat = $config->getDateFormat(); - $lists['default_dateformat'] = JHtml::_('select.genericlist', $default_dateformat, 'default_dateformat', - 'class="inputbox" ', 'value', 'text', $this->temparray['DEFAULT_DATEFORMAT'] - ); - - // Country lists - $country_list = explode(',', $this->temparray['COUNTRY_LIST']); - $lists['country_list'] = JHtml::_('select.genericlist', $countries, 'country_list[]', - 'class="inputbox disableBootstrapChosen" multiple="multiple" size="5"', 'value', 'text', $country_list - ); - - // Invoice mail enable - $lists['invoice_mail_enable'] = JHtml::_('redshopselect.booleanlist', 'invoice_mail_enable', - 'class="inputbox" onchange="enableInvoice(this.value);"', $this->temparray['INVOICE_MAIL_ENABLE'] - ); - - // Invoice mail send type - $invoice_mail_send_option = array(); - $invoice_mail_send_option[0] = new stdClass; - $invoice_mail_send_option[0]->value = 0; - $invoice_mail_send_option[0]->text = JText::_('COM_REDSHOP_SELECT'); - - $invoice_mail_send_option[1] = new stdClass; - $invoice_mail_send_option[1]->value = 1; - $invoice_mail_send_option[1]->text = JText::_('COM_REDSHOP_ADMINISTRATOR'); - - $invoice_mail_send_option[2] = new stdClass; - $invoice_mail_send_option[2]->value = 2; - $invoice_mail_send_option[2]->text = JText::_('COM_REDSHOP_CUSTOMER'); - - $invoice_mail_send_option[3] = new stdClass; - $invoice_mail_send_option[3]->value = 3; - $invoice_mail_send_option[3]->text = JText::_('COM_REDSHOP_BOTH'); - - $lists['invoice_mail_send_option'] = JHtml::_('select.genericlist', $invoice_mail_send_option, 'invoice_mail_send_option', - 'class="inputbox" ', 'value', 'text', $this->temparray['INVOICE_MAIL_SEND_OPTION'] - ); - - // Registration methods - $register_methods = array(); - $register_methods[] = JHtml::_('select.option', '0', JText::_('COM_REDSHOP_REGISTER_WITH_ACCOUNT_CREATION')); - $register_methods[] = JHtml::_('select.option', '1', JText::_('COM_REDSHOP_REGISTER_WITHOUT_ACCOUNT_CREATION')); - $register_methods[] = JHtml::_('select.option', '2', JText::_('COM_REDSHOP_REGISTER_ACCOUNT_OPTIONAL')); - $register_methods[] = JHtml::_('select.option', '3', JText::_('COM_REDSHOP_REGISTER_ACCOUNT_SILENT')); - $lists['register_method'] = JHtml::_('select.genericlist', $register_methods, 'register_method', - 'class="inputbox" id="register_method"', 'value', 'text', $this->temparray['REGISTER_METHOD'] - ); - unset($register_methods); - - // Currency data - $currency_data = $model->getCurrency(); - $lists['currency_data'] = JHtml::_('select.genericlist', $currency_data, 'currency_code', - 'class="inputbox" size="1" ', 'value', 'text', $this->temparray['CURRENCY_CODE'] - ); - - // Discount - $discount_type = array(); - - $discount_type[0] = new stdClass; - $discount_type[0]->value = 0; - $discount_type[0]->text = JText::_('COM_REDSHOP_SELECT'); - - $discount_type[1] = new stdClass; - $discount_type[1]->value = 1; - $discount_type[1]->text = JText::_('COM_REDSHOP_DISCOUNT_OR_VOUCHER_OR_COUPON'); - - $discount_type[2] = new stdClass; - $discount_type[2]->value = 2; - $discount_type[2]->text = JText::_('COM_REDSHOP_DISCOUNT_VOUCHER_OR_COUPON'); - - $discount_type[3] = new stdClass; - $discount_type[3]->value = 3; - $discount_type[3]->text = JText::_('COM_REDSHOP_DISCOUNT_VOUCHER_COUPON'); - - $discount_type[4] = new stdClass; - $discount_type[4]->value = 4; - $discount_type[4]->text = JText::_('COM_REDSHOP_DISCOUNT_VOUCHER_COUPON_MULTIPLE'); - - $lists['discount_type'] = JHtml::_('select.genericlist', $discount_type, 'discount_type', - 'class="inputbox" ', 'value', 'text', $this->temparray['DISCOUNT_TYPE'] - ); - $lists['discount_enable'] = JHtml::_('redshopselect.booleanlist', 'discount_enable', 'class="inputbox" ', $this->temparray['DISCOUNT_ENABLE']); - $lists['coupons_enable'] = JHtml::_('redshopselect.booleanlist', 'coupons_enable', 'class="inputbox" ', $this->temparray['COUPONS_ENABLE']); - $lists['vouchers_enable'] = JHtml::_('redshopselect.booleanlist', 'vouchers_enable', 'class="inputbox" ', $this->temparray['VOUCHERS_ENABLE']); - - // Discount after Shipping - $shipping_after = $this->temparray['SHIPPING_AFTER']; - $lists['shipping_after'] = RedshopHelperExtrafields::rsBooleanList('shipping_after', 'class="inputbox"', $shipping_after, - $yes = JText::_('COM_REDSHOP_TOTAL'), $no = JText::_('COM_REDSHOP_SUBTOTAL_LBL'), '', 'total', 'subtotal' - ); - - // Vat Country - $tmp = array(); - $tmp[] = JHtml::_('select.option', '', JText::_('COM_REDSHOP_SELECT')); - $default_vat_country = @array_merge($tmp, $countries); - $lists['default_vat_country'] = JHtml::_('select.genericlist', $default_vat_country, 'default_vat_country', - 'class="inputbox" onchange="changeStateList();"', 'value', 'text', $this->temparray['DEFAULT_VAT_COUNTRY'] - ); - - // VAT States - $country_list_name = 'default_vat_country'; - $state_list_name = 'default_vat_state'; - $selected_country_code = $this->temparray['DEFAULT_VAT_COUNTRY']; - $selected_state_code = $this->temparray['DEFAULT_VAT_STATE']; - - if (empty($selected_state_code)) - { - $selected_state_code = "originalPos"; - } - else - { - $selected_state_code = "'" . $selected_state_code . "'"; - } - - $db->setQuery("SELECT c.id, c.country_3_code, s.state_name, s.state_2_code + public function display($tpl = null) + { + // Try to get temporary wizard config from config + $session = JFactory::getSession(); + $wizardConfig = $session->get('redshop.wizard', false); + + // If it's not created than use distribute config file + if ($wizardConfig === false) { + $config = JPATH_BASE . '/components/com_redshop/config/config.dist.php'; + + if (JFile::exists($config)) { + // Only load this file if this class is not declared + if (!class_exists('RedshopConfig')) { + require_once $config; + } + + $distConfig = new RedshopConfig; + $wizardConfig = get_object_vars($distConfig); + } else { + $wizardConfig = array(); + } + + // Save back to session + $session->set('redshop.wizard', $wizardConfig); + } + + // Set to view variable to use in tmpl files + $this->temparray = $wizardConfig; + + $uri = JUri::getInstance(); + $db = JFactory::getDbo(); + $config = Redconfiguration::getInstance(); + $model = $this->getModel(); + $document = JFactory::getDocument(); + + $document->setTitle(JText::_('COM_REDSHOP_CONFIG')); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.validation.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::stylesheet('com_redshop/redshop.min.css', array(), true); + /** @scrutinizer ignore-deprecated */ + JHtml::stylesheet('com_redshop/redshop.wizard.min.css', array(), true); + + // Shop country + $q = "SELECT country_3_code as value,country_name as text,country_jtext from #__redshop_country ORDER BY country_name ASC"; + $db->setQuery($q); + $countries = $db->loadObjectList(); + $countries = RedshopHelperUtility::convertLanguageString($countries); + + $lists['shop_country'] = JHtml::_( + 'select.genericlist', + $countries, + 'shop_country', + 'class="inputbox" size="1" ', + 'value', + 'text', + $this->temparray['SHOP_COUNTRY'] + ); + + // Shipping Country Start + $lists['default_shipping_country'] = JHtml::_( + 'select.genericlist', + $countries, + 'default_shipping_country', + 'class="inputbox" size="1" ', + 'value', + 'text', + $this->temparray['DEFAULT_SHIPPING_COUNTRY'] + ); + + // Date Formats + $default_dateformat = $config->getDateFormat(); + $lists['default_dateformat'] = JHtml::_( + 'select.genericlist', + $default_dateformat, + 'default_dateformat', + 'class="inputbox" ', + 'value', + 'text', + $this->temparray['DEFAULT_DATEFORMAT'] + ); + + // Country lists + $country_list = explode(',', $this->temparray['COUNTRY_LIST']); + $lists['country_list'] = JHtml::_( + 'select.genericlist', + $countries, + 'country_list[]', + 'class="inputbox disableBootstrapChosen" multiple="multiple" size="5"', + 'value', + 'text', + $country_list + ); + + // Invoice mail enable + $lists['invoice_mail_enable'] = JHtml::_( + 'redshopselect.booleanlist', + 'invoice_mail_enable', + 'class="inputbox" onchange="enableInvoice(this.value);"', + $this->temparray['INVOICE_MAIL_ENABLE'] + ); + + // Invoice mail send type + $invoice_mail_send_option = array(); + $invoice_mail_send_option[0] = new stdClass; + $invoice_mail_send_option[0]->value = 0; + $invoice_mail_send_option[0]->text = JText::_('COM_REDSHOP_SELECT'); + + $invoice_mail_send_option[1] = new stdClass; + $invoice_mail_send_option[1]->value = 1; + $invoice_mail_send_option[1]->text = JText::_('COM_REDSHOP_ADMINISTRATOR'); + + $invoice_mail_send_option[2] = new stdClass; + $invoice_mail_send_option[2]->value = 2; + $invoice_mail_send_option[2]->text = JText::_('COM_REDSHOP_CUSTOMER'); + + $invoice_mail_send_option[3] = new stdClass; + $invoice_mail_send_option[3]->value = 3; + $invoice_mail_send_option[3]->text = JText::_('COM_REDSHOP_BOTH'); + + $lists['invoice_mail_send_option'] = JHtml::_( + 'select.genericlist', + $invoice_mail_send_option, + 'invoice_mail_send_option', + 'class="inputbox" ', + 'value', + 'text', + $this->temparray['INVOICE_MAIL_SEND_OPTION'] + ); + + // Registration methods + $register_methods = array(); + $register_methods[] = JHtml::_( + 'select.option', + '0', + JText::_('COM_REDSHOP_REGISTER_WITH_ACCOUNT_CREATION') + ); + $register_methods[] = JHtml::_( + 'select.option', + '1', + JText::_('COM_REDSHOP_REGISTER_WITHOUT_ACCOUNT_CREATION') + ); + $register_methods[] = JHtml::_('select.option', '2', JText::_('COM_REDSHOP_REGISTER_ACCOUNT_OPTIONAL')); + $register_methods[] = JHtml::_('select.option', '3', JText::_('COM_REDSHOP_REGISTER_ACCOUNT_SILENT')); + $lists['register_method'] = JHtml::_( + 'select.genericlist', + $register_methods, + 'register_method', + 'class="inputbox" id="register_method"', + 'value', + 'text', + $this->temparray['REGISTER_METHOD'] + ); + unset($register_methods); + + // Currency data + $currency_data = $model->getCurrency(); + $lists['currency_data'] = JHtml::_( + 'select.genericlist', + $currency_data, + 'currency_code', + 'class="inputbox" size="1" ', + 'value', + 'text', + $this->temparray['CURRENCY_CODE'] + ); + + // Discount + $discount_type = array(); + + $discount_type[0] = new stdClass; + $discount_type[0]->value = 0; + $discount_type[0]->text = JText::_('COM_REDSHOP_SELECT'); + + $discount_type[1] = new stdClass; + $discount_type[1]->value = 1; + $discount_type[1]->text = JText::_('COM_REDSHOP_DISCOUNT_OR_VOUCHER_OR_COUPON'); + + $discount_type[2] = new stdClass; + $discount_type[2]->value = 2; + $discount_type[2]->text = JText::_('COM_REDSHOP_DISCOUNT_VOUCHER_OR_COUPON'); + + $discount_type[3] = new stdClass; + $discount_type[3]->value = 3; + $discount_type[3]->text = JText::_('COM_REDSHOP_DISCOUNT_VOUCHER_COUPON'); + + $discount_type[4] = new stdClass; + $discount_type[4]->value = 4; + $discount_type[4]->text = JText::_('COM_REDSHOP_DISCOUNT_VOUCHER_COUPON_MULTIPLE'); + + $lists['discount_type'] = JHtml::_( + 'select.genericlist', + $discount_type, + 'discount_type', + 'class="inputbox" ', + 'value', + 'text', + $this->temparray['DISCOUNT_TYPE'] + ); + $lists['discount_enable'] = JHtml::_( + 'redshopselect.booleanlist', + 'discount_enable', + 'class="inputbox" ', + $this->temparray['DISCOUNT_ENABLE'] + ); + $lists['coupons_enable'] = JHtml::_( + 'redshopselect.booleanlist', + 'coupons_enable', + 'class="inputbox" ', + $this->temparray['COUPONS_ENABLE'] + ); + $lists['vouchers_enable'] = JHtml::_( + 'redshopselect.booleanlist', + 'vouchers_enable', + 'class="inputbox" ', + $this->temparray['VOUCHERS_ENABLE'] + ); + + // Discount after Shipping + $shipping_after = $this->temparray['SHIPPING_AFTER']; + $lists['shipping_after'] = RedshopHelperExtrafields::rsBooleanList( + 'shipping_after', + 'class="inputbox"', + $shipping_after, + $yes = JText::_('COM_REDSHOP_TOTAL'), + $no = JText::_('COM_REDSHOP_SUBTOTAL_LBL'), + '', + 'total', + 'subtotal' + ); + + // Vat Country + $tmp = array(); + $tmp[] = JHtml::_('select.option', '', JText::_('COM_REDSHOP_SELECT')); + $default_vat_country = @array_merge($tmp, $countries); + $lists['default_vat_country'] = JHtml::_( + 'select.genericlist', + $default_vat_country, + 'default_vat_country', + 'class="inputbox" onchange="changeStateList();"', + 'value', + 'text', + $this->temparray['DEFAULT_VAT_COUNTRY'] + ); + + // VAT States + $country_list_name = 'default_vat_country'; + $state_list_name = 'default_vat_state'; + $selected_country_code = $this->temparray['DEFAULT_VAT_COUNTRY']; + $selected_state_code = $this->temparray['DEFAULT_VAT_STATE']; + + if (empty($selected_state_code)) { + $selected_state_code = "originalPos"; + } else { + $selected_state_code = "'" . $selected_state_code . "'"; + } + + $db->setQuery( + "SELECT c.id, c.country_3_code, s.state_name, s.state_2_code FROM #__redshop_country c LEFT JOIN #__redshop_state s ON c.id=s.country_id OR s.country_id IS NULL ORDER BY c.id, s.state_name" - ); - - $states = $db->loadObjectList(); - - // Build the State lists for each Country - $script = ""; - $lists['default_vat_state'] = $script; - - $lists['apply_vat_on_discount'] = JHtml::_('redshopselect.booleanlist', 'apply_vat_on_discount', - 'class="inputbox" size="1"', $this->temparray['APPLY_VAT_ON_DISCOUNT'] - ); - - $calculate_vat_on = $this->temparray['CALCULATE_VAT_ON']; - $lists['calculate_vat_on'] = RedshopHelperExtrafields::rsBooleanList('calculate_vat_on', - 'class="inputbox"', $calculate_vat_on, - $yes = JText::_('COM_REDSHOP_BILLING_ADDRESS_LBL'), - $no = JText::_('COM_REDSHOP_SHIPPING_ADDRESS_LBL'), '', 'BT', 'ST' - ); - - $this->taxrates = $this->get('TaxRates'); - - $this->lists = $lists; - $this->request_url = $uri->toString(); - - parent::display($tpl); - } + $lists['default_vat_state'] = $script; + + $lists['apply_vat_on_discount'] = JHtml::_( + 'redshopselect.booleanlist', + 'apply_vat_on_discount', + 'class="inputbox" size="1"', + $this->temparray['APPLY_VAT_ON_DISCOUNT'] + ); + + $calculate_vat_on = $this->temparray['CALCULATE_VAT_ON']; + $lists['calculate_vat_on'] = RedshopHelperExtrafields::rsBooleanList( + 'calculate_vat_on', + 'class="inputbox"', + $calculate_vat_on, + $yes = JText::_('COM_REDSHOP_BILLING_ADDRESS_LBL'), + $no = JText::_('COM_REDSHOP_SHIPPING_ADDRESS_LBL'), + '', + 'BT', + 'ST' + ); + + $this->taxrates = $this->get('TaxRates'); + + $this->lists = $lists; + $this->request_url = $uri->toString(); + + parent::display($tpl); + } } diff --git a/component/admin/views/wrapper/index.html b/component/admin/views/wrapper/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/wrapper/index.html +++ b/component/admin/views/wrapper/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/wrapper/tmpl/default.php b/component/admin/views/wrapper/tmpl/default.php index 5198c157669..3a01879f87f 100644 --- a/component/admin/views/wrapper/tmpl/default.php +++ b/component/admin/views/wrapper/tmpl/default.php @@ -1,4 +1,5 @@ input->get('showall', '0'); -$tmpl = ''; +$tmpl = ''; $uri = JURI::getInstance(); $url = $uri->root(); ?> @@ -20,116 +21,149 @@ checkSubmit(pressbutton, viewForm); }; - -
    -
    - - - - -
    -
    -
    + +
    +
    + + + + +
    +
    +
    -
    -
    -
    -
    - - "> - -
    -
    -
    +
    +
    +
    +
    + + "> + +
    +
    +
    - - - - - - - - - - - - - - data); $i++) - { - $row = $this->data[$i]; - $row->id = $row->wrapper_id; - $published = JHtml::_('jgrid.published', $row->published, $i, '', 1); - $row->published = $row->wrapper_use_to_all; - $enable_default = JHTML::_('grid.published', $row, $i, 'tick.png', 'publish_x.png', 'enable_default'); +
    - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> - - lists['order_Dir'], $this->lists['order']); ?> -
    + + + + + + + + + + + + + data); $i++) { + $row = $this->data[$i]; + $row->id = $row->wrapper_id; + $published = JHtml::_('jgrid.published', $row->published, $i, '', 1); + $row->published = $row->wrapper_use_to_all; + $enable_default = JHTML::_('grid.published', $row, $i, 'tick.png', 'publish_x.png', 'enable_default'); - $link = JRoute::_('index.php?option=com_redshop&view=wrapper_detail&task=edit&product_id=' . $this->product_id . '&cid[]=' . $row->wrapper_id . $tmpl . '&showall=' . $showall); ?> - "> - - - - - - - - - - - - - -
    + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> + + lists['order_Dir'], + $this->lists['order'] + ); ?> +
    pagination->getRowOffset($i); ?>id); ?>wrapper_name; ?> - - wrapper_image; - if (JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . $wimage_path)) - { - ?> - - wrapper_image; ?> - - wrapper_price);//CURRENCY_SYMBOL.number_format($row->wrapper_price,2,PRICE_SEPERATOR,THOUSAND_SEPERATOR); - ?>id; ?>
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter(); ?>
    -
    - - - - - - - + $link = JRoute::_( + 'index.php?option=com_redshop&view=wrapper_detail&task=edit&product_id=' . $this->product_id . '&cid[]=' . $row->wrapper_id . $tmpl . '&showall=' . $showall + ); ?> + "> + pagination->getRowOffset($i); ?> + id); ?> + wrapper_name; ?> + + + wrapper_image; + if (JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . $wimage_path)) { + ?> + + wrapper_image; ?> + + + wrapper_price + );//CURRENCY_SYMBOL.number_format($row->wrapper_price,2,PRICE_SEPERATOR,THOUSAND_SEPERATOR); + ?> + + + id; ?> + + + + + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?> + + +
    + + + + + + +
    diff --git a/component/admin/views/wrapper/tmpl/index.html b/component/admin/views/wrapper/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/wrapper/tmpl/index.html +++ b/component/admin/views/wrapper/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/wrapper/view.html.php b/component/admin/views/wrapper/view.html.php index 24cb86d5235..78cd73f89d0 100644 --- a/component/admin/views/wrapper/view.html.php +++ b/component/admin/views/wrapper/view.html.php @@ -13,53 +13,61 @@ class RedshopViewWrapper extends RedshopViewAdmin { - /** - * The current user. - * - * @var JUser - */ - public $user; + /** + * The current user. + * + * @var JUser + */ + public $user; - public $lists = array(); + public $lists = array(); - /** - * The request url. - * - * @var string - */ - public $request_url; + /** + * The request url. + * + * @var string + */ + public $request_url; - public function display($tpl = null) - { - $uri = JFactory::getURI(); - $app = JFactory::getApplication(); - $document = JFactory::getDocument(); - $productId = $app->input->get('product_id'); + public function display($tpl = null) + { + $uri = JFactory::getURI(); + $app = JFactory::getApplication(); + $document = JFactory::getDocument(); + $productId = $app->input->get('product_id'); - $document->setTitle(JText::_('COM_REDSHOP_WRAPPER')); + $document->setTitle(JText::_('COM_REDSHOP_WRAPPER')); - $data = $this->get('Data'); - $pagination = $this->get('Pagination'); + $data = $this->get('Data'); + $pagination = $this->get('Pagination'); - JToolBarHelper::title(JText::_('COM_REDSHOP_WRAPPER'), 'redshop_wrapper48'); - JToolbarHelper::addNew(); - JToolbarHelper::EditList(); - JToolBarHelper::deleteList(); - JToolBarHelper::publishList(); - JToolBarHelper::unpublishList(); + JToolBarHelper::title(JText::_('COM_REDSHOP_WRAPPER'), 'redshop_wrapper48'); + JToolbarHelper::addNew(); + JToolbarHelper::EditList(); + JToolBarHelper::deleteList(); + JToolBarHelper::publishList(); + JToolBarHelper::unpublishList(); - $context = 'wrapper_id'; - $state = $this->get('State'); - $this->lists['order'] = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'wrapper_id'); - $this->lists['order_Dir'] = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', ''); - $this->filter = $state->get('filter'); + $context = 'wrapper_id'; + $state = $this->get('State'); + $this->lists['order'] = $app->getUserStateFromRequest( + $context . 'filter_order', + 'filter_order', + 'wrapper_id' + ); + $this->lists['order_Dir'] = $app->getUserStateFromRequest( + $context . 'filter_order_Dir', + 'filter_order_Dir', + '' + ); + $this->filter = $state->get('filter'); - $this->user = JFactory::getUser(); - $this->data = $data; - $this->product_id = $productId; - $this->pagination = $pagination; - $this->request_url = $uri->toString(); + $this->user = JFactory::getUser(); + $this->data = $data; + $this->product_id = $productId; + $this->pagination = $pagination; + $this->request_url = $uri->toString(); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/wrapper_detail/index.html b/component/admin/views/wrapper_detail/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/wrapper_detail/index.html +++ b/component/admin/views/wrapper_detail/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/wrapper_detail/tmpl/default.php b/component/admin/views/wrapper_detail/tmpl/default.php index fe3272ae712..88a8373c721 100644 --- a/component/admin/views/wrapper_detail/tmpl/default.php +++ b/component/admin/views/wrapper_detail/tmpl/default.php @@ -1,4 +1,5 @@ input->get('showall', '0'); ?> - -
    -
    - - -
    -
    -
    + +
    +
    + + +
    +
    +
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - * - -
    - -
    lists['category_name']; ?>
    lists['product_name'];?> -
    - 'wrapper_image', - 'deleteid' => 'thumb_image_delete', - 'displayid' => 'thumb_image_display', - 'type' => 'wrapper', - 'image' => $this->detail->wrapper_image ?? '' - ) - ); - ?> -
    : - lists['use_to_all']; ?>
    : - lists['published']; ?>
    -
    -
    -
    - - - - - - +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + * + +
    + +
    lists['category_name']; ?>
    lists['product_name']; ?> +
    + 'wrapper_image', + 'deleteid' => 'thumb_image_delete', + 'displayid' => 'thumb_image_display', + 'type' => 'wrapper', + 'image' => $this->detail->wrapper_image ?? '' + ) + ); + ?> +
    : + lists['use_to_all']; ?>
    : + lists['published']; ?>
    +
    +
    +
    + + + + + +
    diff --git a/component/admin/views/wrapper_detail/tmpl/index.html b/component/admin/views/wrapper_detail/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/wrapper_detail/tmpl/index.html +++ b/component/admin/views/wrapper_detail/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/wrapper_detail/view.html.php b/component/admin/views/wrapper_detail/view.html.php index d8d67f49b41..84687f5fde8 100644 --- a/component/admin/views/wrapper_detail/view.html.php +++ b/component/admin/views/wrapper_detail/view.html.php @@ -33,7 +33,8 @@ class RedshopViewWrapper_Detail extends RedshopViewAdmin protected $displaySidebar = false; /** - * @param null $tpl + * @param null $tpl + * * @return mixed|void * @throws Exception */ @@ -42,15 +43,18 @@ public function display($tpl = null) global $context; $context = "wrapper"; - $uri = JFactory::getURI(); - $lists = array(); - $detail = $this->get('data'); - $model = $this->getModel('wrapper_detail'); + $uri = JFactory::getURI(); + $lists = array(); + $detail = $this->get('data'); + $model = $this->getModel('wrapper_detail'); $isNew = ($detail->wrapper_id ?? 0) < 1; - $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); + $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); - JToolBarHelper::title(JText::_('COM_REDSHOP_WRAPPER') . ': [ ' . $text . ' ]', 'redshop_wrapper48'); + JToolBarHelper::title( + JText::_('COM_REDSHOP_WRAPPER') . ': [ ' . $text . ' ]', + 'redshop_wrapper48' + ); JToolBarHelper::apply(); JToolBarHelper::save(); @@ -61,13 +65,17 @@ public function display($tpl = null) JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); } - $lists['published'] = JHTML::_('select.booleanlist', 'published', 'class="inputbox"', $detail->published); - $lists['use_to_all'] = JHTML::_('select.booleanlist', 'wrapper_use_to_all', 'class="inputbox"', - $detail->wrapper_use_to_all ?? 0); - + $lists['published'] = JHTML::_('select.booleanlist', 'published', 'class="inputbox"', $detail->published); + $lists['use_to_all'] = JHTML::_( + 'select.booleanlist', + 'wrapper_use_to_all', + 'class="inputbox"', + $detail->wrapper_use_to_all ?? 0 + ); + $productId = 0; - $input = JFactory::getApplication()->input; - $showAll = $input->get('showall', '0'); + $input = JFactory::getApplication()->input; + $showAll = $input->get('showall', '0'); if ($showAll) { $productId = $input->get('product_id'); @@ -79,7 +87,14 @@ public function display($tpl = null) $categoryId = explode(",", $detail->category_id); } - $lists['category_name'] = $model->getMultiselectBox("categoryid[]", $category, ($categoryId ?? []), "id", "name", true); + $lists['category_name'] = $model->getMultiselectBox( + "categoryid[]", + $category, + ($categoryId ?? []), + "id", + "name", + true + ); $product = $model->getProductInfo($productId); @@ -91,18 +106,21 @@ public function display($tpl = null) $resultContainer = []; } - $lists['product_name'] = JHTML::_('redshopselect.search', $resultContainer, 'container_product', + $lists['product_name'] = JHTML::_( + 'redshopselect.search', + $resultContainer, + 'container_product', array( 'select2.ajaxOptions' => array('typeField' => ', alert:"wrapper"'), - 'select2.options' => array('multiple' => true) + 'select2.options' => array('multiple' => true) ) ); - $this->lists = $lists; - $this->detail = $detail; - $this->product = $product; - $this->productId = $productId; - $this->category = $category; + $this->lists = $lists; + $this->detail = $detail; + $this->product = $product; + $this->productId = $productId; + $this->category = $category; $this->requestUrl = $uri->toString(); parent::display($tpl); diff --git a/component/admin/views/xmlexport/index.html b/component/admin/views/xmlexport/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/xmlexport/index.html +++ b/component/admin/views/xmlexport/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/xmlexport/tmpl/default.php b/component/admin/views/xmlexport/tmpl/default.php index e2639bda50d..3ef97047428 100644 --- a/component/admin/views/xmlexport/tmpl/default.php +++ b/component/admin/views/xmlexport/tmpl/default.php @@ -1,4 +1,5 @@ lists;?> +$lists = $this->lists; ?>
    -
    - - - - - - - - - - - - - - - - data); $i < $n; $i++) - { - $row = $this->data[$i]; - $row->id = $row->xmlexport_id; - $link = JRoute::_('index.php?option=com_redshop&view=xmlexport_detail&task=edit&cid[]=' . $row->id); +
    +
    - - - lists['order_Dir'], $this->lists['order']); ?> - lists['order_Dir'], $this->lists['order']); ?> - lists['order_Dir'], $this->lists['order']); ?> - lists['order_Dir'], $this->lists['order']); ?> - lists['order_Dir'], $this->lists['order']); ?> - lists['order_Dir'], $this->lists['order']); ?>
    + + + + + + + + + + + + + + + data); $i < $n; $i++) { + $row = $this->data[$i]; + $row->id = $row->xmlexport_id; + $link = JRoute::_('index.php?option=com_redshop&view=xmlexport_detail&task=edit&cid[]=' . $row->id); - $published = JHtml::_('jgrid.published', $row->published, $i, '', 1); ?> - "> - - - - - - - - - - - - - - - -
    + + + lists['order_Dir'], + $this->lists['order'] + ); ?> + lists['order_Dir'], + $this->lists['order'] + ); ?> + lists['order_Dir'], + $this->lists['order'] + ); ?> + lists['order_Dir'], + $this->lists['order'] + ); ?> + lists['order_Dir'], + $this->lists['order'] + ); ?> + lists['order_Dir'], + $this->lists['order'] + ); ?>
    pagination->getRowOffset($i); ?>id); ?>display_filename; ?> - filename != "") - { - echo '' . $row->filename . ''; - }?>section_type;?>published = $row->auto_sync; - echo $auto_sync = JHTML::_('grid.published', $row, $i, 'tick.png', 'publish_x.png', 'auto_sync');?>published = $row->use_to_all_users; - echo $usetoall = JHTML::_('grid.published', $row, $i, 'tick.png', 'publish_x.png', 'usetoall');?>id; ?>
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter(); ?>
    -
    + $published = JHtml::_('jgrid.published', $row->published, $i, '', 1); ?> + "> + pagination->getRowOffset($i); ?> + id); ?> + display_filename; ?> + + filename != "") { + echo '' . $row->filename . ''; + } ?> + section_type; ?> + published = $row->auto_sync; + echo $auto_sync = JHTML::_( + 'grid.published', + $row, + $i, + 'tick.png', + 'publish_x.png', + 'auto_sync' + ); ?> + published = $row->use_to_all_users; + echo $usetoall = JHTML::_( + 'grid.published', + $row, + $i, + 'tick.png', + 'publish_x.png', + 'usetoall' + ); ?> + + + id; ?> + + + + + + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?> + + - - - - - + + + + +
    diff --git a/component/admin/views/xmlexport/tmpl/index.html b/component/admin/views/xmlexport/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/xmlexport/tmpl/index.html +++ b/component/admin/views/xmlexport/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/xmlexport/view.html.php b/component/admin/views/xmlexport/view.html.php index 5d2acf4387d..3c72d0c0bce 100644 --- a/component/admin/views/xmlexport/view.html.php +++ b/component/admin/views/xmlexport/view.html.php @@ -12,37 +12,37 @@ class RedshopViewXmlexport extends RedshopViewAdmin { - function display($tpl = null) - { - global $context; + function display($tpl = null) + { + global $context; - $uri = JFactory::getURI(); - $app = JFactory::getApplication(); - $document = JFactory::getDocument(); + $uri = JFactory::getURI(); + $app = JFactory::getApplication(); + $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_xmlexport')); + $document->setTitle(JText::_('COM_REDSHOP_xmlexport')); - JToolBarHelper::title(JText::_('COM_REDSHOP_XML_EXPORT_MANAGEMENT'), 'redshop_export48'); - JToolbarHelper::addNew(); - JToolbarHelper::EditList(); - JToolBarHelper::deleteList(); - JToolBarHelper::publishList(); - JToolBarHelper::unpublishList(); + JToolBarHelper::title(JText::_('COM_REDSHOP_XML_EXPORT_MANAGEMENT'), 'redshop_export48'); + JToolbarHelper::addNew(); + JToolbarHelper::EditList(); + JToolBarHelper::deleteList(); + JToolBarHelper::publishList(); + JToolBarHelper::unpublishList(); - $filter_order = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'xmlexport_date'); - $filter_order_Dir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', 'DESC'); + $filter_order = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'xmlexport_date'); + $filter_order_Dir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', 'DESC'); - $lists['order'] = $filter_order; - $lists['order_Dir'] = $filter_order_Dir; + $lists['order'] = $filter_order; + $lists['order_Dir'] = $filter_order_Dir; - $data = $this->get('Data'); - $pagination = $this->get('Pagination'); + $data = $this->get('Data'); + $pagination = $this->get('Pagination'); - $this->lists = $lists; - $this->data = $data; - $this->pagination = $pagination; - $this->request_url = $uri->toString(); + $this->lists = $lists; + $this->data = $data; + $this->pagination = $pagination; + $this->request_url = $uri->toString(); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/xmlexport_detail/index.html b/component/admin/views/xmlexport_detail/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/xmlexport_detail/index.html +++ b/component/admin/views/xmlexport_detail/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/xmlexport_detail/tmpl/default.php b/component/admin/views/xmlexport_detail/tmpl/default.php index 49903a61f2c..e4c2900e7a8 100644 --- a/component/admin/views/xmlexport_detail/tmpl/default.php +++ b/component/admin/views/xmlexport_detail/tmpl/default.php @@ -1,4 +1,5 @@ getModel('xmlexport_detail'); -$orderstyle = "none"; +$orderstyle = "none"; $productstyle = "none"; -switch ($this->detail->section_type) -{ - case "product": - $orderstyle = "none"; - $productstyle = ""; - break; - case "order": - $orderstyle = ""; - $productstyle = "none"; - break; +switch ($this->detail->section_type) { + case "product": + $orderstyle = "none"; + $productstyle = ""; + break; + case "order": + $orderstyle = ""; + $productstyle = "none"; + break; } ?>
    -
    -
    - +
    +
    + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    : -
    : -
    :lists['section_type'];?>
    : - lists['auto_sync'];?>
    : - lists['sync_on_request'];?>
    : - lists['auto_sync_interval'];?>
    :lists['published']; ?>
    :detail->filename != "") - { - echo '' . JURI::root() . 'index.php?option=com_redshop&view=category&tmpl=component&task=download&file=' . $this->detail->filename . ''; - } ?> -
    : - detail->xmlexport_id . '" target="_black">' . JURI::root() . 'index.php?option=com_redshop&view=category&tmpl=component&task=generateXMLExportFile&xmlexport_id=' . $this->detail->xmlexport_id . ''; ?>
    -
    -
    -
    -
    - - - - - - - - - - iparray) > 0) - { - for ($i = 0; $i < count($this->iparray); $i++) - { - ?> - - - - - - - - - - -
    : - lists['use_to_all_users']; ?>
    -
    : - -
    : -
    -
    -
    -
    -
    - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    : +
    : +
    :lists['section_type']; ?>
    : + lists['auto_sync']; ?>
    : + lists['sync_on_request']; ?>
    : + lists['auto_sync_interval']; ?>
    :lists['published']; ?>
    :detail->filename != "") { + echo '' . JURI::root( + ) . 'index.php?option=com_redshop&view=category&tmpl=component&task=download&file=' . $this->detail->filename . ''; + } ?> +
    : + detail->xmlexport_id . '" target="_black">' . JURI::root( + ) . 'index.php?option=com_redshop&view=category&tmpl=component&task=generateXMLExportFile&xmlexport_id=' . $this->detail->xmlexport_id . ''; ?>
    +
    +
    +
    +
    + + + + + + + + + + iparray) > 0) { + for ($i = 0; $i < count($this->iparray); $i++) { + ?> + + + + + + + + + + +
    : + lists['use_to_all_users']; ?>
    +
    : + +
    : +
    +
    +
    +
    +
    + - - - - - - - - - - - - - - - - - -
    - <?php echo JText::_('COM_REDSHOP_ADD_ORDER_DETAIL'); ?> -
    - <?php echo JText::_('COM_REDSHOP_ADD_ORDER_USER_BILLING_INFORMATION'); ?> -
    - <?php echo JText::_('COM_REDSHOP_ADD_ORDER_USER_SHIPPING_INFORMATION'); ?> -
    - <?php echo JText::_('COM_REDSHOP_ADD_ORDERITEMDETAIL'); ?> -
    + + + + + + + + + + + + + + + + + +
    + <?php echo JText::_('COM_REDSHOP_ADD_ORDER_DETAIL'); ?> +
    + <?php echo JText::_('COM_REDSHOP_ADD_ORDER_USER_BILLING_INFORMATION'); ?> +
    + <?php echo JText::_('COM_REDSHOP_ADD_ORDER_USER_SHIPPING_INFORMATION'); ?> +
    + <?php echo JText::_('COM_REDSHOP_ADD_ORDERITEMDETAIL'); ?> +
    - - - - - - - - - - - - - - - - - - +
    lists['xmlexport_on_category'];?>
    - <?php echo JText::_('COM_REDSHOP_ADD_PRODUCT_DETAIL'); ?> -
    - <?php echo JText::_('COM_REDSHOP_ADD_PRODUCT_STOCK_DETAIL'); ?> -
    - <?php echo JText::_('COM_REDSHOP_ADD_PRODUCT_FIELD_DETAIL'); ?> -
    + + + + + + + + + + + + + + + + + columns);$i++) { ?> - -
    lists['xmlexport_on_category']; ?>
    + <?php echo JText::_('COM_REDSHOP_ADD_PRODUCT_DETAIL'); ?> +
    + <?php echo JText::_('COM_REDSHOP_ADD_PRODUCT_STOCK_DETAIL'); ?> +
    + <?php echo JText::_('COM_REDSHOP_ADD_PRODUCT_FIELD_DETAIL'); ?> +
    columns[$i]->Field ?>:
    -
    -
    -
    - - - - - - + + +
    +
    +
    + + + + + +
    diff --git a/component/admin/views/xmlexport_detail/tmpl/elementdetail.php b/component/admin/views/xmlexport_detail/tmpl/elementdetail.php index cad7bc44313..90bb189756c 100644 --- a/component/admin/views/xmlexport_detail/tmpl/elementdetail.php +++ b/component/admin/views/xmlexport_detail/tmpl/elementdetail.php @@ -1,4 +1,5 @@ root(); ?>
    -
    - - - - - - - - - - columns); $i++) - { - ?> - - - - - - - - - -
    - : - -
    columns[$i]->Field; ?>:
     
    -
    +
    + + + + + + + + + + columns); $i++) { + ?> + + + + + + + + + +
    + : + +
    columns[$i]->Field; ?>:
     
    +
    -
    - - - - - - +
    + + + + + +
    diff --git a/component/admin/views/xmlexport_detail/tmpl/index.html b/component/admin/views/xmlexport_detail/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/xmlexport_detail/tmpl/index.html +++ b/component/admin/views/xmlexport_detail/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/xmlexport_detail/view.html.php b/component/admin/views/xmlexport_detail/view.html.php index a4345418c6b..839aded649e 100644 --- a/component/admin/views/xmlexport_detail/view.html.php +++ b/component/admin/views/xmlexport_detail/view.html.php @@ -1,4 +1,5 @@ input; - $context = 'xmlexport_id'; - $layout = $jinput->getCmd('layout', ''); - $xmlhelper = new xmlHelper; - $session = JFactory::getSession(); - $childelement = $session->get('childelement'); - $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_xmlexport')); - /** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/redshop.xmlfunc.min.js', false, true); - - $uri = JUri::getInstance(); - $lists = array(); - $colvalue = array(); - $model = $this->getModel(); - $detail = $this->get('data'); - $parentsection = $jinput->get('parentsection', ''); - $detail->section_type = $jinput->get('section_type', $detail->section_type); - $isNew = ($detail->xmlexport_id < 1); - $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); - - JToolBarHelper::title(JText::_('COM_REDSHOP_XML_EXPORT_MANAGEMENT') . ': [ ' . $text . ' ]', 'redshop_export48'); - JToolBarHelper::custom('xmlexport', 'redshop_export32.png', JText::_('COM_REDSHOP_XML_EXPORT'), JText::_('COM_REDSHOP_XML_EXPORT'), false, false); - JToolBarHelper::save(); - - if ($isNew) - { - JToolBarHelper::cancel(); - } - else - { - JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); - } - - $section_typelist = $xmlhelper->getSectionTypeList(); - $auto_sync_interval = $xmlhelper->getSynchIntervalList(); - $columns = $xmlhelper->getSectionColumnList($detail->section_type, $parentsection); - $iparray = $xmlhelper->getXMLExportIpAddress($detail->xmlexport_id); - $dbfield = ""; - $dbchildname = ""; - - switch ($parentsection) - { - case "orderdetail": - case "productdetail": - if (isset($childelement[$parentsection])) - { - $detail->element_name = $childelement[$parentsection][0]; - $detail->xmlexport_filetag = $childelement[$parentsection][1]; - } - - $dbfield = $detail->xmlexport_filetag; - $dbchildname = $detail->element_name; - break; - case "stockdetail": - if (isset($childelement[$parentsection])) - { - $detail->stock_element_name = $childelement[$parentsection][0]; - $detail->xmlexport_stocktag = $childelement[$parentsection][1]; - } - - $dbfield = $detail->xmlexport_stocktag; - $dbchildname = $detail->stock_element_name; - break; - case "billingdetail": - if (isset($childelement[$parentsection])) - { - $detail->billing_element_name = $childelement[$parentsection][0]; - $detail->xmlexport_billingtag = $childelement[$parentsection][1]; - } - - $dbfield = $detail->xmlexport_billingtag; - $dbchildname = $detail->billing_element_name; - break; - case "shippingdetail": - if (isset($childelement[$parentsection])) - { - $detail->shipping_element_name = $childelement[$parentsection][0]; - $detail->xmlexport_shippingtag = $childelement[$parentsection][1]; - } - - $dbfield = $detail->xmlexport_shippingtag; - $dbchildname = $detail->shipping_element_name; - break; - case "orderitem": - if (isset($childelement[$parentsection])) - { - $detail->orderitem_element_name = $childelement[$parentsection][0]; - $detail->xmlexport_orderitemtag = $childelement[$parentsection][1]; - } - - $dbfield = $detail->xmlexport_orderitemtag; - $dbchildname = $detail->orderitem_element_name; - break; - case "prdextrafield": - if (isset($childelement[$parentsection])) - { - $detail->prdextrafield_element_name = $childelement[$parentsection][0]; - $detail->xmlexport_prdextrafieldtag = $childelement[$parentsection][1]; - } - - $dbfield = $detail->xmlexport_prdextrafieldtag; - $dbchildname = $detail->prdextrafield_element_name; - break; - } - - for ($i = 0, $in = count($columns); $i < $in; $i++) - { - $tmpVal = $xmlhelper->getXMLFileTag($columns[$i]->Field, $dbfield); - $colvalue[] = $tmpVal[0]; - } - - $lists['auto_sync'] = JHTML::_('select.booleanlist', 'auto_sync', 'class="inputbox" size="1"', $detail->auto_sync); - $lists['sync_on_request'] = JHTML::_('select.booleanlist', 'sync_on_request', 'class="inputbox" size="1"', $detail->sync_on_request); - $lists['section_type'] = JHTML::_('select.genericlist', $section_typelist, 'section_type', - 'class="inputbox" size="1" onchange="setExportSectionType();" ', 'value', 'text', $detail->section_type - ); - $lists['auto_sync_interval'] = JHTML::_('select.genericlist', $auto_sync_interval, 'auto_sync_interval', - 'class="inputbox" size="1" ', 'value', 'text', $detail->auto_sync_interval - ); - $lists['published'] = JHTML::_('select.booleanlist', 'xmlpublished', 'class="inputbox"', $detail->published); - $lists['use_to_all_users'] = JHTML::_('select.booleanlist', 'use_to_all_users', 'class="inputbox"', $detail->use_to_all_users); - $categoryData = $model->getCategoryList(); - $detail->xmlexport_on_category = explode(',', $detail->xmlexport_on_category); - $lists['xmlexport_on_category'] = JHTML::_('select.genericlist', $categoryData, 'xmlexport_on_category[]', - 'class="inputbox" multiple="multiple" ', 'value', 'text', $detail->xmlexport_on_category - ); - - if ($layout != "") - { - $this->setlayout($layout); - } - else - { - $this->setlayout("default"); - } - - $this->lists = $lists; - $this->detail = $detail; - $this->columns = $columns; - $this->colvalue = $colvalue; - $this->childname = $dbchildname; - $this->iparray = $iparray; - $this->request_url = $uri->toString(); - - parent::display($tpl); - } + /** + * Do we have to display a sidebar ? + * + * @var boolean + */ + protected $displaySidebar = false; + + public function display($tpl = null) + { + global $context; + $jinput = JFactory::getApplication()->input; + $context = 'xmlexport_id'; + $layout = $jinput->getCmd('layout', ''); + $xmlhelper = new xmlHelper; + $session = JFactory::getSession(); + $childelement = $session->get('childelement'); + $document = JFactory::getDocument(); + $document->setTitle(JText::_('COM_REDSHOP_xmlexport')); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.xmlfunc.min.js', false, true); + + $uri = JUri::getInstance(); + $lists = array(); + $colvalue = array(); + $model = $this->getModel(); + $detail = $this->get('data'); + $parentsection = $jinput->get('parentsection', ''); + $detail->section_type = $jinput->get('section_type', $detail->section_type); + $isNew = ($detail->xmlexport_id < 1); + $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); + + JToolBarHelper::title( + JText::_('COM_REDSHOP_XML_EXPORT_MANAGEMENT') . ': [ ' . $text . ' ]', + 'redshop_export48' + ); + JToolBarHelper::custom( + 'xmlexport', + 'redshop_export32.png', + JText::_('COM_REDSHOP_XML_EXPORT'), + JText::_('COM_REDSHOP_XML_EXPORT'), + false, + false + ); + JToolBarHelper::save(); + + if ($isNew) { + JToolBarHelper::cancel(); + } else { + JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); + } + + $section_typelist = $xmlhelper->getSectionTypeList(); + $auto_sync_interval = $xmlhelper->getSynchIntervalList(); + $columns = $xmlhelper->getSectionColumnList($detail->section_type, $parentsection); + $iparray = $xmlhelper->getXMLExportIpAddress($detail->xmlexport_id); + $dbfield = ""; + $dbchildname = ""; + + switch ($parentsection) { + case "orderdetail": + case "productdetail": + if (isset($childelement[$parentsection])) { + $detail->element_name = $childelement[$parentsection][0]; + $detail->xmlexport_filetag = $childelement[$parentsection][1]; + } + + $dbfield = $detail->xmlexport_filetag; + $dbchildname = $detail->element_name; + break; + case "stockdetail": + if (isset($childelement[$parentsection])) { + $detail->stock_element_name = $childelement[$parentsection][0]; + $detail->xmlexport_stocktag = $childelement[$parentsection][1]; + } + + $dbfield = $detail->xmlexport_stocktag; + $dbchildname = $detail->stock_element_name; + break; + case "billingdetail": + if (isset($childelement[$parentsection])) { + $detail->billing_element_name = $childelement[$parentsection][0]; + $detail->xmlexport_billingtag = $childelement[$parentsection][1]; + } + + $dbfield = $detail->xmlexport_billingtag; + $dbchildname = $detail->billing_element_name; + break; + case "shippingdetail": + if (isset($childelement[$parentsection])) { + $detail->shipping_element_name = $childelement[$parentsection][0]; + $detail->xmlexport_shippingtag = $childelement[$parentsection][1]; + } + + $dbfield = $detail->xmlexport_shippingtag; + $dbchildname = $detail->shipping_element_name; + break; + case "orderitem": + if (isset($childelement[$parentsection])) { + $detail->orderitem_element_name = $childelement[$parentsection][0]; + $detail->xmlexport_orderitemtag = $childelement[$parentsection][1]; + } + + $dbfield = $detail->xmlexport_orderitemtag; + $dbchildname = $detail->orderitem_element_name; + break; + case "prdextrafield": + if (isset($childelement[$parentsection])) { + $detail->prdextrafield_element_name = $childelement[$parentsection][0]; + $detail->xmlexport_prdextrafieldtag = $childelement[$parentsection][1]; + } + + $dbfield = $detail->xmlexport_prdextrafieldtag; + $dbchildname = $detail->prdextrafield_element_name; + break; + } + + for ($i = 0, $in = count($columns); $i < $in; $i++) { + $tmpVal = $xmlhelper->getXMLFileTag($columns[$i]->Field, $dbfield); + $colvalue[] = $tmpVal[0]; + } + + $lists['auto_sync'] = JHTML::_( + 'select.booleanlist', + 'auto_sync', + 'class="inputbox" size="1"', + $detail->auto_sync + ); + $lists['sync_on_request'] = JHTML::_( + 'select.booleanlist', + 'sync_on_request', + 'class="inputbox" size="1"', + $detail->sync_on_request + ); + $lists['section_type'] = JHTML::_( + 'select.genericlist', + $section_typelist, + 'section_type', + 'class="inputbox" size="1" onchange="setExportSectionType();" ', + 'value', + 'text', + $detail->section_type + ); + $lists['auto_sync_interval'] = JHTML::_( + 'select.genericlist', + $auto_sync_interval, + 'auto_sync_interval', + 'class="inputbox" size="1" ', + 'value', + 'text', + $detail->auto_sync_interval + ); + $lists['published'] = JHTML::_( + 'select.booleanlist', + 'xmlpublished', + 'class="inputbox"', + $detail->published + ); + $lists['use_to_all_users'] = JHTML::_( + 'select.booleanlist', + 'use_to_all_users', + 'class="inputbox"', + $detail->use_to_all_users + ); + $categoryData = $model->getCategoryList(); + $detail->xmlexport_on_category = explode(',', $detail->xmlexport_on_category); + $lists['xmlexport_on_category'] = JHTML::_( + 'select.genericlist', + $categoryData, + 'xmlexport_on_category[]', + 'class="inputbox" multiple="multiple" ', + 'value', + 'text', + $detail->xmlexport_on_category + ); + + if ($layout != "") { + $this->setlayout($layout); + } else { + $this->setlayout("default"); + } + + $this->lists = $lists; + $this->detail = $detail; + $this->columns = $columns; + $this->colvalue = $colvalue; + $this->childname = $dbchildname; + $this->iparray = $iparray; + $this->request_url = $uri->toString(); + + parent::display($tpl); + } } diff --git a/component/admin/views/xmlimport/index.html b/component/admin/views/xmlimport/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/xmlimport/index.html +++ b/component/admin/views/xmlimport/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/xmlimport/tmpl/default.php b/component/admin/views/xmlimport/tmpl/default.php index 9142e3e6a61..768d536eb78 100644 --- a/component/admin/views/xmlimport/tmpl/default.php +++ b/component/admin/views/xmlimport/tmpl/default.php @@ -1,4 +1,5 @@ lists;?> +$lists = $this->lists; ?>
    -
    - - - - - - - - - - - - - - - data); $i < $n; $i++) - { - $row = $this->data[$i]; - $row->id = $row->xmlimport_id; - $link = JRoute::_('index.php?option=com_redshop&view=xmlimport_detail&task=edit&cid[]=' . $row->id); +
    +
    - - - lists['order_Dir'], $this->lists['order']); ?> - lists['order_Dir'], $this->lists['order']); ?> - lists['order_Dir'], $this->lists['order']); ?> - lists['order_Dir'], $this->lists['order']); ?> - lists['order_Dir'], $this->lists['order']); ?>
    + + + + + + + + + + + + + + data); $i < $n; $i++) { + $row = $this->data[$i]; + $row->id = $row->xmlimport_id; + $link = JRoute::_('index.php?option=com_redshop&view=xmlimport_detail&task=edit&cid[]=' . $row->id); - $published = JHtml::_('jgrid.published', $row->published, $i, '', 1);?> - "> - - - - - - - - - - - - - - -
    + + + lists['order_Dir'], + $this->lists['order'] + ); ?> + lists['order_Dir'], + $this->lists['order'] + ); ?> + lists['order_Dir'], + $this->lists['order'] + ); ?> + lists['order_Dir'], + $this->lists['order'] + ); ?> + lists['order_Dir'], + $this->lists['order'] + ); ?>
    pagination->getRowOffset($i); ?>id); ?>display_filename; ?> - filename;?>section_type;?>published = $row->auto_sync; - echo $auto_sync = JHTML::_('grid.published', $row, $i, 'tick.png', 'publish_x.png', 'auto_sync');?>id; ?>
    - =')): ?> -
    - pagination->getLimitBox(); ?> -
    - - pagination->getListFooter(); ?>
    -
    + $published = JHtml::_('jgrid.published', $row->published, $i, '', 1); ?> + "> + pagination->getRowOffset($i); ?> + id); ?> + display_filename; ?> + + filename; ?> + section_type; ?> + published = $row->auto_sync; + echo $auto_sync = JHTML::_( + 'grid.published', + $row, + $i, + 'tick.png', + 'publish_x.png', + 'auto_sync' + ); ?> + + + id; ?> + + + + + + =')): ?> +
    + pagination->getLimitBox(); ?> +
    + + pagination->getListFooter(); ?> + + - - - - - + + + + +
    diff --git a/component/admin/views/xmlimport/tmpl/index.html b/component/admin/views/xmlimport/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/xmlimport/tmpl/index.html +++ b/component/admin/views/xmlimport/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/xmlimport/view.html.php b/component/admin/views/xmlimport/view.html.php index edba711b426..9596956ff73 100644 --- a/component/admin/views/xmlimport/view.html.php +++ b/component/admin/views/xmlimport/view.html.php @@ -12,37 +12,37 @@ class RedshopViewXmlimport extends RedshopViewAdmin { - public function display($tpl = null) - { - global $context; + public function display($tpl = null) + { + global $context; - $uri = JFactory::getURI(); - $app = JFactory::getApplication(); - $document = JFactory::getDocument(); + $uri = JFactory::getURI(); + $app = JFactory::getApplication(); + $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_xmlimport')); + $document->setTitle(JText::_('COM_REDSHOP_xmlimport')); - JToolBarHelper::title(JText::_('COM_REDSHOP_XML_IMPORT_MANAGEMENT'), 'redshop_import48'); - JToolbarHelper::addNew(); - JToolbarHelper::EditList(); - JToolBarHelper::deleteList(); - JToolBarHelper::publishList(); - JToolBarHelper::unpublishList(); + JToolBarHelper::title(JText::_('COM_REDSHOP_XML_IMPORT_MANAGEMENT'), 'redshop_import48'); + JToolbarHelper::addNew(); + JToolbarHelper::EditList(); + JToolBarHelper::deleteList(); + JToolBarHelper::publishList(); + JToolBarHelper::unpublishList(); - $filter_order = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'xmlimport_date'); - $filter_order_Dir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', 'DESC'); + $filter_order = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'xmlimport_date'); + $filter_order_Dir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', 'DESC'); - $lists['order'] = $filter_order; - $lists['order_Dir'] = $filter_order_Dir; + $lists['order'] = $filter_order; + $lists['order_Dir'] = $filter_order_Dir; - $data = $this->get('Data'); - $pagination = $this->get('Pagination'); + $data = $this->get('Data'); + $pagination = $this->get('Pagination'); - $this->lists = $lists; - $this->data = $data; - $this->pagination = $pagination; - $this->request_url = $uri->toString(); + $this->lists = $lists; + $this->data = $data; + $this->pagination = $pagination; + $this->request_url = $uri->toString(); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/xmlimport_detail/index.html b/component/admin/views/xmlimport_detail/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/xmlimport_detail/index.html +++ b/component/admin/views/xmlimport_detail/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/xmlimport_detail/tmpl/default.php b/component/admin/views/xmlimport_detail/tmpl/default.php index f7223a3f23e..b59e10ddee1 100644 --- a/component/admin/views/xmlimport_detail/tmpl/default.php +++ b/component/admin/views/xmlimport_detail/tmpl/default.php @@ -1,4 +1,5 @@ getModel('xmlimport_detail'); -$uri = JURI::getInstance(); -$url = $uri->root(); +$uri = JURI::getInstance(); +$url = $uri->root(); -$style = "none"; -$orderstyle = "none"; +$style = "none"; +$orderstyle = "none"; $productstyle = "none"; -switch ($this->detail->section_type) -{ - case "product": - $orderstyle = "none"; - $productstyle = ""; - $style = ""; - break; - case "order": - $orderstyle = ""; - $productstyle = "none"; - $style = ""; - break; -} ?> +switch ($this->detail->section_type) { + case "product": + $orderstyle = "none"; + $productstyle = ""; + $style = ""; + break; + case "order": + $orderstyle = ""; + $productstyle = "none"; + $style = ""; + break; +} ?>
    -
    -
    - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    : -
    - : -
    :
    :lists['section_type'];?>
    +
    +
    + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    : +
    + : +
    :
    :lists['section_type']; ?>
    : + style="display: ;"> : -
    : - -
    : - -
    : - -
    : - -
    : - -
    : - lists['auto_sync'];?>
    : - lists['sync_on_request'];?>
    : - lists['auto_sync_interval'];?>
    :lists['xmlpublished']; ?>
    : - lists['override_existing'];?>
    : -
    -
    -
    detail->section_type != "") - { - ?> -
    -
    - - - - - - - - xmlfiletag) > 0) - { - if ($this->detail->section_type == "order") - { - ?> - - - - - detail->section_type == "product") - { - ?> - - - - - xmlfiletag); $i++) - { - $chk = ($this->updatefiletag[$i] == 1) ? "checked" : ""; - if ($this->xmlfiletag[$i] == "category_id") - { - ?> - - - - - - - - - xmlbillingtag) > 0) - { - ?> - - - - - xmlbillingtag); $i++) - { - $chk = ($this->updatebillingtag[$i] == 1) ? "checked" : ""; ?> - - - - - - xmlshippingtag) > 0) - { - ?> - - - - - xmlshippingtag); $i++) - { - $chk = ($this->updateshippingtag[$i] == 1) ? "checked" : ""; ?> - - - - - - xmlitemtag) > 0) - { - ?> - - - - - xmlitemtag); $i++) - { - $chk = ($this->updateitemtag[$i] == 1) ? "checked" : ""; ?> - - - - - - xmlstocktag) > 0) - { - ?> - - - - - xmlstocktag); $i++) - { - $chk = ($this->updatestocktag[$i] == 1) ? "checked" : ""; ?> - - - - - - xmlprdextrafieldtag) > 0) - { - ?> - - - - - xmlprdextrafieldtag); $i++) - { - $chk = ($this->updateprdexttag[$i] == 1) ? "checked" : ""; ?> - - - - - - -
    xmlfiletag[$i]; ?>:lists[$this->xmlfiletag[$i]];?> - />
     
    xmlbillingtag[$i]; ?>:lists["bill_" . $this->xmlbillingtag[$i]];?> - />
     
    xmlshippingtag[$i]; ?>:lists["shipp_" . $this->xmlshippingtag[$i]];?> - />
    xmlitemtag[$i]; ?>:lists["item_" . $this->xmlitemtag[$i]];?> - />
    xmlstocktag[$i]; ?>:lists["stock_" . $this->xmlstocktag[$i]];?> - - />
    xmlprdextrafieldtag[$i]; ?>:lists["prdext_" . $this->xmlprdextrafieldtag[$i]];?> - />
    -
    -
    -
    -
    - - - - - -
    -
    -
    -
    - - - - - - - +
    +
    : + +
    : + +
    : + +
    : + +
    : + +
    : + lists['auto_sync']; ?>
    : + lists['sync_on_request']; ?>
    : + lists['auto_sync_interval']; ?>
    :lists['xmlpublished']; ?>
    : + lists['override_existing']; ?>
    : +
    +
    +
    detail->section_type != "") { + ?> +
    +
    + + + + + + + + xmlfiletag) > 0) { + if ($this->detail->section_type == "order") { + ?> + + + + + detail->section_type == "product") { + ?> + + + + + xmlfiletag); $i++) { + $chk = ($this->updatefiletag[$i] == 1) ? "checked" : ""; + if ($this->xmlfiletag[$i] == "category_id") { + ?> + + + + + + + + + xmlbillingtag) > 0) { + ?> + + + + + xmlbillingtag); $i++) { + $chk = ($this->updatebillingtag[$i] == 1) ? "checked" : ""; ?> + + + + + + xmlshippingtag) > 0) { + ?> + + + + + xmlshippingtag); $i++) { + $chk = ($this->updateshippingtag[$i] == 1) ? "checked" : ""; ?> + + + + + + xmlitemtag) > 0) { + ?> + + + + + xmlitemtag); $i++) { + $chk = ($this->updateitemtag[$i] == 1) ? "checked" : ""; ?> + + + + + + xmlstocktag) > 0) { + ?> + + + + + xmlstocktag); $i++) { + $chk = ($this->updatestocktag[$i] == 1) ? "checked" : ""; ?> + + + + + + xmlprdextrafieldtag) > 0) { + ?> + + + + + xmlprdextrafieldtag); $i++) { + $chk = ($this->updateprdexttag[$i] == 1) ? "checked" : ""; ?> + + + + + + +
    xmlfiletag[$i]; ?>:lists[$this->xmlfiletag[$i]]; ?> + />
     
    xmlbillingtag[$i]; ?>:lists["bill_" . $this->xmlbillingtag[$i]]; ?> + />
     
    xmlshippingtag[$i]; ?>:lists["shipp_" . $this->xmlshippingtag[$i]]; ?> + />
    xmlitemtag[$i]; ?>:lists["item_" . $this->xmlitemtag[$i]]; ?> + + />
    xmlstocktag[$i]; ?>:lists["stock_" . $this->xmlstocktag[$i]]; ?> + + />
    xmlprdextrafieldtag[$i]; ?>: + lists["prdext_" . $this->xmlprdextrafieldtag[$i]]; ?> + />
    +
    +
    +
    +
    + + + + + +
    +
    +
    +
    + + + + + + +
    diff --git a/component/admin/views/xmlimport_detail/tmpl/index.html b/component/admin/views/xmlimport_detail/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/xmlimport_detail/tmpl/index.html +++ b/component/admin/views/xmlimport_detail/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/xmlimport_detail/view.html.php b/component/admin/views/xmlimport_detail/view.html.php index 5e60fc94bf1..a445b184a64 100644 --- a/component/admin/views/xmlimport_detail/view.html.php +++ b/component/admin/views/xmlimport_detail/view.html.php @@ -1,4 +1,5 @@ setTitle(JText::_('COM_REDSHOP_xmlimport')); - /** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/redshop.xmlfunc.min.js', false, true); - - $uri = JUri::getInstance(); - $columns = array(); - $lists = array(); - $updateshippingtag = array(); - $resultarray = array(); - $xmlfiletag = array(); - $xmlbillingtag = array(); - $xmlshippingtag = array(); - $xmlitemtag = array(); - $xmlstocktag = array(); - $xmlprdextrafieldtag = array(); - $updatefiletag = array(); - $updatebillingtag = array(); - $updateprdexttag = array(); - $updateitemtag = array(); - $updatestocktag = array(); - $model = $this->getModel(); - - $detail = $this->get('data'); - $detail->section_type = JFactory::getApplication()->input->get('section_type', $detail->section_type); - - $xmlimport_url = $model->updateFile(); - - $detail->xmlimport_url = $model->getXMLImporturl(); - - $isNew = ($detail->xmlimport_id < 1); - $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); - - JToolBarHelper::title(JText::_('COM_REDSHOP_XML_IMPORT_MANAGEMENT') . ': [ ' . $text . ' ]', 'redshop_import48'); - JToolBarHelper::custom('xmlimport', 'redshop_import_import32.png', JText::_('COM_REDSHOP_XML_IMPORT'), - JText::_('COM_REDSHOP_XML_IMPORT'), false, false - ); - JToolBarHelper::save(); - - if ($isNew) - { - JToolBarHelper::cancel(); - } - else - { - JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); - } - - $section_type = $xmlhelper->getSectionTypeList(); - $auto_sync_interval = $xmlhelper->getSynchIntervalList(); - $lists['auto_sync'] = JHTML::_('select.booleanlist', 'auto_sync', 'class="inputbox" size="1"', $detail->auto_sync); - $lists['sync_on_request'] = JHTML::_('select.booleanlist', 'sync_on_request', 'class="inputbox" size="1"', $detail->sync_on_request); - $lists['auto_sync_interval'] = JHTML::_('select.genericlist', $auto_sync_interval, - 'auto_sync_interval', 'class="inputbox" size="1" ', 'value', 'text', $detail->auto_sync_interval - ); - $lists['override_existing'] = JHTML::_('select.booleanlist', 'override_existing', 'class="inputbox" size="1"', $detail->override_existing); - $lists['xmlpublished'] = JHTML::_('select.booleanlist', 'xmlpublished', 'class="inputbox"', $detail->published); - - if ($xmlimport_url != "") - { - $filedetail = $xmlhelper->readXMLImportFile($xmlimport_url, $detail); - $xmlfiletag = $filedetail['xmlsectionarray']; - $xmlbillingtag = $filedetail['xmlbillingarray']; - $xmlshippingtag = $filedetail['xmlshippingarray']; - $xmlitemtag = $filedetail['xmlorderitemarray']; - $xmlstocktag = $filedetail['xmlstockarray']; - $xmlprdextrafieldtag = $filedetail['xmlprdextarray']; - } - - $lists['section_type'] = JHTML::_('select.genericlist', $section_type, 'section_type', - 'class="inputbox" size="1" onchange="setExportSectionType();" ', 'value', 'text', $detail->section_type - ); - - if ($detail->section_type != "") - { - $cols = array(); - $columns = $xmlhelper->getSectionColumnList($detail->section_type); - - for ($i = 0, $in = count($columns); $i < $in; $i++) - { - $cols[$i] = new stdClass; - $cols[$i]->value = $columns[$i]->Field; - $cols[$i]->text = $columns[$i]->Field; - } - - $op = array(); - $op[0] = new stdClass; - $op[0]->value = ''; - $op[0]->text = JText::_('COM_REDSHOP_SELECT'); - $columns = array_merge($op, $cols); - - for ($i = 0, $in = count($xmlfiletag); $i < $in; $i++) - { - $colvalue = $xmlhelper->getXMLFileTag($xmlfiletag[$i], $detail->xmlimport_filetag); - $updatefiletag[$i] = $colvalue[1]; - $lists[$xmlfiletag[$i]] = JHTML::_('select.genericlist', $columns, $xmlfiletag[$i], 'class="inputbox" size="1" ', 'value', 'text', $colvalue[0]); - } - - if (count($xmlbillingtag) > 0) - { - $cols = array(); - $columns = $xmlhelper->getSectionColumnList($detail->section_type, "billingdetail"); - - for ($i = 0, $in = count($columns); $i < $in; $i++) - { - $cols[$i] = new stdClass; - $cols[$i]->value = $columns[$i]->Field; - $cols[$i]->text = $columns[$i]->Field; - } - - $columns = array_merge($op, $cols); - - for ($i = 0, $in = count($xmlbillingtag); $i < $in; $i++) - { - $colvalue = $xmlhelper->getXMLFileTag($xmlbillingtag[$i], $detail->xmlimport_billingtag); - $updatebillingtag[$i] = $colvalue[1]; - $lists["bill_" . $xmlbillingtag[$i]] = JHTML::_('select.genericlist', $columns, "bill_" . $xmlbillingtag[$i], - 'class="inputbox" size="1" ', 'value', 'text', $colvalue[0] - ); - } - } - - if (count($xmlshippingtag) > 0) - { - $cols = array(); - $columns = $xmlhelper->getSectionColumnList($detail->section_type, "shippingdetail"); - - for ($i = 0, $in = count($columns); $i < $in; $i++) - { - $cols[$i] = new stdClass; - $cols[$i]->value = $columns[$i]->Field; - $cols[$i]->text = $columns[$i]->Field; - } - - $columns = array_merge($op, $cols); - - for ($i = 0, $in = count($xmlshippingtag); $i < $in; $i++) - { - $colvalue = $xmlhelper->getXMLFileTag($xmlshippingtag[$i], $detail->xmlimport_shippingtag); - $updateshippingtag[$i] = $colvalue[1]; - $lists["shipp_" . $xmlshippingtag[$i]] = JHTML::_('select.genericlist', $columns, "shipp_" . $xmlshippingtag[$i], - 'class="inputbox" size="1" ', 'value', 'text', $colvalue[0] - ); - } - } - - if (count($xmlitemtag) > 0) - { - $cols = array(); - $columns = $xmlhelper->getSectionColumnList($detail->section_type, "orderitem"); - - for ($i = 0, $in = count($columns); $i < $in; $i++) - { - $cols[$i] = new stdClass; - $cols[$i]->value = $columns[$i]->Field; - $cols[$i]->text = $columns[$i]->Field; - } - - $columns = array_merge($op, $cols); - - for ($i = 0, $in = count($xmlitemtag); $i < $in; $i++) - { - $colvalue = $xmlhelper->getXMLFileTag($xmlitemtag[$i], $detail->xmlimport_orderitemtag); - $updateitemtag[$i] = $colvalue[1]; - $lists["item_" . $xmlitemtag[$i]] = JHTML::_('select.genericlist', $columns, "item_" . $xmlitemtag[$i], - 'class="inputbox" size="1" ', 'value', 'text', $colvalue[0] - ); - } - } - - if (count($xmlstocktag) > 0) - { - $cols = array(); - $columns = $xmlhelper->getSectionColumnList($detail->section_type, "stockdetail"); - - for ($i = 0, $in = count($columns); $i < $in; $i++) - { - $cols[$i]->value = $columns[$i]->Field; - $cols[$i]->text = $columns[$i]->Field; - } - - $columns = array_merge($op, $cols); - - for ($i = 0, $in = count($xmlstocktag); $i < $in; $i++) - { - $colvalue = $xmlhelper->getXMLFileTag($xmlstocktag[$i], $detail->xmlimport_stocktag); - $updatestocktag[$i] = $colvalue[1]; - $lists["stock_" . $xmlstocktag[$i]] = JHTML::_('select.genericlist', $columns, "stock_" . $xmlstocktag[$i], - 'class="inputbox" size="1" ', 'value', 'text', $colvalue[0] - ); - } - } - - if (count($xmlprdextrafieldtag) > 0) - { - $cols = array(); - $columns = $xmlhelper->getSectionColumnList($detail->section_type, "prdextrafield"); - - for ($i = 0, $in = count($columns); $i < $in; $i++) - { - $cols[$i]->value = $columns[$i]->Field; - $cols[$i]->text = $columns[$i]->Field; - } - - $columns = array_merge($op, $cols); - - for ($i = 0, $in = count($xmlprdextrafieldtag); $i < $in; $i++) - { - $colvalue = $xmlhelper->getXMLFileTag($xmlprdextrafieldtag[$i], $detail->xmlimport_prdextrafieldtag); - $updateprdexttag[$i] = $colvalue[1]; - $lists["prdext_" . $xmlprdextrafieldtag[$i]] = JHTML::_('select.genericlist', $columns, "prdext_" . $xmlprdextrafieldtag[$i], - 'class="inputbox" size="1" ', 'value', 'text', $colvalue[0] - ); - } - } - } - - $this->resultarray = $resultarray; - $this->lists = $lists; - $this->detail = $detail; - $this->columns = $columns; - $this->xmlfiletag = $xmlfiletag; - $this->xmlbillingtag = $xmlbillingtag; - $this->xmlshippingtag = $xmlshippingtag; - $this->xmlitemtag = $xmlitemtag; - $this->xmlstocktag = $xmlstocktag; - $this->xmlprdextrafieldtag = $xmlprdextrafieldtag; - $this->updatefiletag = $updatefiletag; - $this->updatebillingtag = $updatebillingtag; - $this->updateshippingtag = $updateshippingtag; - $this->updateitemtag = $updateitemtag; - $this->updatestocktag = $updatestocktag; - $this->updateprdexttag = $updateprdexttag; - $this->tmpxmlimport_url = $xmlimport_url; - $this->request_url = $uri->toString(); - - parent::display($tpl); - } + /** + * Do we have to display a sidebar ? + * + * @var boolean + */ + protected $displaySidebar = false; + + public function display($tpl = null) + { + $xmlhelper = new xmlHelper; + $document = JFactory::getDocument(); + $document->setTitle(JText::_('COM_REDSHOP_xmlimport')); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.xmlfunc.min.js', false, true); + + $uri = JUri::getInstance(); + $columns = array(); + $lists = array(); + $updateshippingtag = array(); + $resultarray = array(); + $xmlfiletag = array(); + $xmlbillingtag = array(); + $xmlshippingtag = array(); + $xmlitemtag = array(); + $xmlstocktag = array(); + $xmlprdextrafieldtag = array(); + $updatefiletag = array(); + $updatebillingtag = array(); + $updateprdexttag = array(); + $updateitemtag = array(); + $updatestocktag = array(); + $model = $this->getModel(); + + $detail = $this->get('data'); + $detail->section_type = JFactory::getApplication()->input->get('section_type', $detail->section_type); + + $xmlimport_url = $model->updateFile(); + + $detail->xmlimport_url = $model->getXMLImporturl(); + + $isNew = ($detail->xmlimport_id < 1); + $text = $isNew ? JText::_('COM_REDSHOP_NEW') : JText::_('COM_REDSHOP_EDIT'); + + JToolBarHelper::title( + JText::_('COM_REDSHOP_XML_IMPORT_MANAGEMENT') . ': [ ' . $text . ' ]', + 'redshop_import48' + ); + JToolBarHelper::custom( + 'xmlimport', + 'redshop_import_import32.png', + JText::_('COM_REDSHOP_XML_IMPORT'), + JText::_('COM_REDSHOP_XML_IMPORT'), + false, + false + ); + JToolBarHelper::save(); + + if ($isNew) { + JToolBarHelper::cancel(); + } else { + JToolBarHelper::cancel('cancel', JText::_('JTOOLBAR_CLOSE')); + } + + $section_type = $xmlhelper->getSectionTypeList(); + $auto_sync_interval = $xmlhelper->getSynchIntervalList(); + $lists['auto_sync'] = JHTML::_( + 'select.booleanlist', + 'auto_sync', + 'class="inputbox" size="1"', + $detail->auto_sync + ); + $lists['sync_on_request'] = JHTML::_( + 'select.booleanlist', + 'sync_on_request', + 'class="inputbox" size="1"', + $detail->sync_on_request + ); + $lists['auto_sync_interval'] = JHTML::_( + 'select.genericlist', + $auto_sync_interval, + 'auto_sync_interval', + 'class="inputbox" size="1" ', + 'value', + 'text', + $detail->auto_sync_interval + ); + $lists['override_existing'] = JHTML::_( + 'select.booleanlist', + 'override_existing', + 'class="inputbox" size="1"', + $detail->override_existing + ); + $lists['xmlpublished'] = JHTML::_( + 'select.booleanlist', + 'xmlpublished', + 'class="inputbox"', + $detail->published + ); + + if ($xmlimport_url != "") { + $filedetail = $xmlhelper->readXMLImportFile($xmlimport_url, $detail); + $xmlfiletag = $filedetail['xmlsectionarray']; + $xmlbillingtag = $filedetail['xmlbillingarray']; + $xmlshippingtag = $filedetail['xmlshippingarray']; + $xmlitemtag = $filedetail['xmlorderitemarray']; + $xmlstocktag = $filedetail['xmlstockarray']; + $xmlprdextrafieldtag = $filedetail['xmlprdextarray']; + } + + $lists['section_type'] = JHTML::_( + 'select.genericlist', + $section_type, + 'section_type', + 'class="inputbox" size="1" onchange="setExportSectionType();" ', + 'value', + 'text', + $detail->section_type + ); + + if ($detail->section_type != "") { + $cols = array(); + $columns = $xmlhelper->getSectionColumnList($detail->section_type); + + for ($i = 0, $in = count($columns); $i < $in; $i++) { + $cols[$i] = new stdClass; + $cols[$i]->value = $columns[$i]->Field; + $cols[$i]->text = $columns[$i]->Field; + } + + $op = array(); + $op[0] = new stdClass; + $op[0]->value = ''; + $op[0]->text = JText::_('COM_REDSHOP_SELECT'); + $columns = array_merge($op, $cols); + + for ($i = 0, $in = count($xmlfiletag); $i < $in; $i++) { + $colvalue = $xmlhelper->getXMLFileTag($xmlfiletag[$i], $detail->xmlimport_filetag); + $updatefiletag[$i] = $colvalue[1]; + $lists[$xmlfiletag[$i]] = JHTML::_( + 'select.genericlist', + $columns, + $xmlfiletag[$i], + 'class="inputbox" size="1" ', + 'value', + 'text', + $colvalue[0] + ); + } + + if (count($xmlbillingtag) > 0) { + $cols = array(); + $columns = $xmlhelper->getSectionColumnList($detail->section_type, "billingdetail"); + + for ($i = 0, $in = count($columns); $i < $in; $i++) { + $cols[$i] = new stdClass; + $cols[$i]->value = $columns[$i]->Field; + $cols[$i]->text = $columns[$i]->Field; + } + + $columns = array_merge($op, $cols); + + for ($i = 0, $in = count($xmlbillingtag); $i < $in; $i++) { + $colvalue = $xmlhelper->getXMLFileTag( + $xmlbillingtag[$i], + $detail->xmlimport_billingtag + ); + $updatebillingtag[$i] = $colvalue[1]; + $lists["bill_" . $xmlbillingtag[$i]] = JHTML::_( + 'select.genericlist', + $columns, + "bill_" . $xmlbillingtag[$i], + 'class="inputbox" size="1" ', + 'value', + 'text', + $colvalue[0] + ); + } + } + + if (count($xmlshippingtag) > 0) { + $cols = array(); + $columns = $xmlhelper->getSectionColumnList($detail->section_type, "shippingdetail"); + + for ($i = 0, $in = count($columns); $i < $in; $i++) { + $cols[$i] = new stdClass; + $cols[$i]->value = $columns[$i]->Field; + $cols[$i]->text = $columns[$i]->Field; + } + + $columns = array_merge($op, $cols); + + for ($i = 0, $in = count($xmlshippingtag); $i < $in; $i++) { + $colvalue = $xmlhelper->getXMLFileTag( + $xmlshippingtag[$i], + $detail->xmlimport_shippingtag + ); + $updateshippingtag[$i] = $colvalue[1]; + $lists["shipp_" . $xmlshippingtag[$i]] = JHTML::_( + 'select.genericlist', + $columns, + "shipp_" . $xmlshippingtag[$i], + 'class="inputbox" size="1" ', + 'value', + 'text', + $colvalue[0] + ); + } + } + + if (count($xmlitemtag) > 0) { + $cols = array(); + $columns = $xmlhelper->getSectionColumnList($detail->section_type, "orderitem"); + + for ($i = 0, $in = count($columns); $i < $in; $i++) { + $cols[$i] = new stdClass; + $cols[$i]->value = $columns[$i]->Field; + $cols[$i]->text = $columns[$i]->Field; + } + + $columns = array_merge($op, $cols); + + for ($i = 0, $in = count($xmlitemtag); $i < $in; $i++) { + $colvalue = $xmlhelper->getXMLFileTag( + $xmlitemtag[$i], + $detail->xmlimport_orderitemtag + ); + $updateitemtag[$i] = $colvalue[1]; + $lists["item_" . $xmlitemtag[$i]] = JHTML::_( + 'select.genericlist', + $columns, + "item_" . $xmlitemtag[$i], + 'class="inputbox" size="1" ', + 'value', + 'text', + $colvalue[0] + ); + } + } + + if (count($xmlstocktag) > 0) { + $cols = array(); + $columns = $xmlhelper->getSectionColumnList($detail->section_type, "stockdetail"); + + for ($i = 0, $in = count($columns); $i < $in; $i++) { + $cols[$i]->value = $columns[$i]->Field; + $cols[$i]->text = $columns[$i]->Field; + } + + $columns = array_merge($op, $cols); + + for ($i = 0, $in = count($xmlstocktag); $i < $in; $i++) { + $colvalue = $xmlhelper->getXMLFileTag( + $xmlstocktag[$i], + $detail->xmlimport_stocktag + ); + $updatestocktag[$i] = $colvalue[1]; + $lists["stock_" . $xmlstocktag[$i]] = JHTML::_( + 'select.genericlist', + $columns, + "stock_" . $xmlstocktag[$i], + 'class="inputbox" size="1" ', + 'value', + 'text', + $colvalue[0] + ); + } + } + + if (count($xmlprdextrafieldtag) > 0) { + $cols = array(); + $columns = $xmlhelper->getSectionColumnList($detail->section_type, "prdextrafield"); + + for ($i = 0, $in = count($columns); $i < $in; $i++) { + $cols[$i]->value = $columns[$i]->Field; + $cols[$i]->text = $columns[$i]->Field; + } + + $columns = array_merge($op, $cols); + + for ($i = 0, $in = count($xmlprdextrafieldtag); $i < $in; $i++) { + $colvalue = $xmlhelper->getXMLFileTag( + $xmlprdextrafieldtag[$i], + $detail->xmlimport_prdextrafieldtag + ); + $updateprdexttag[$i] = $colvalue[1]; + $lists["prdext_" . $xmlprdextrafieldtag[$i]] = JHTML::_( + 'select.genericlist', + $columns, + "prdext_" . $xmlprdextrafieldtag[$i], + 'class="inputbox" size="1" ', + 'value', + 'text', + $colvalue[0] + ); + } + } + } + + $this->resultarray = $resultarray; + $this->lists = $lists; + $this->detail = $detail; + $this->columns = $columns; + $this->xmlfiletag = $xmlfiletag; + $this->xmlbillingtag = $xmlbillingtag; + $this->xmlshippingtag = $xmlshippingtag; + $this->xmlitemtag = $xmlitemtag; + $this->xmlstocktag = $xmlstocktag; + $this->xmlprdextrafieldtag = $xmlprdextrafieldtag; + $this->updatefiletag = $updatefiletag; + $this->updatebillingtag = $updatebillingtag; + $this->updateshippingtag = $updateshippingtag; + $this->updateitemtag = $updateitemtag; + $this->updatestocktag = $updatestocktag; + $this->updateprdexttag = $updateprdexttag; + $this->tmpxmlimport_url = $xmlimport_url; + $this->request_url = $uri->toString(); + + parent::display($tpl); + } } diff --git a/component/admin/views/zip_import/index.html b/component/admin/views/zip_import/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/zip_import/index.html +++ b/component/admin/views/zip_import/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/zip_import/tmpl/confirmupdate.php b/component/admin/views/zip_import/tmpl/confirmupdate.php index 3a76e5a2d30..c66eae508de 100644 --- a/component/admin/views/zip_import/tmpl/confirmupdate.php +++ b/component/admin/views/zip_import/tmpl/confirmupdate.php @@ -10,43 +10,43 @@ ?>
    - - - - - - - - - - - - - - - - - - - - - - +
     
     
     
    + + + + + + + + + + + + + + + + + + + + + -
     
     
     
    - - + + +
    diff --git a/component/admin/views/zip_import/tmpl/default.php b/component/admin/views/zip_import/tmpl/default.php index bf0c7d1682c..23ff29c8095 100644 --- a/component/admin/views/zip_import/tmpl/default.php +++ b/component/admin/views/zip_import/tmpl/default.php @@ -6,4 +6,5 @@ * @copyright Copyright (C) 2008 - 2020 redCOMPONENT.com. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ + ?> diff --git a/component/admin/views/zip_import/tmpl/index.html b/component/admin/views/zip_import/tmpl/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/zip_import/tmpl/index.html +++ b/component/admin/views/zip_import/tmpl/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/zip_import/view.html.php b/component/admin/views/zip_import/view.html.php index 4c3775c40da..40a52f4c5d5 100644 --- a/component/admin/views/zip_import/view.html.php +++ b/component/admin/views/zip_import/view.html.php @@ -12,20 +12,17 @@ class RedshopViewZip_import extends RedshopViewAdmin { - public function display($tpl = null) - { - $layout = JFactory::getApplication()->input->getCmd('layout', ''); + public function display($tpl = null) + { + $layout = JFactory::getApplication()->input->getCmd('layout', ''); - if ($layout == 'confirmupdate') - { - $this->setLayout('confirmupdate'); - } - else - { - $result = $this->get('Data'); - $this->result = $result; - } + if ($layout == 'confirmupdate') { + $this->setLayout('confirmupdate'); + } else { + $result = $this->get('Data'); + $this->result = $result; + } - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/admin/views/zipcode/index.html b/component/admin/views/zipcode/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/admin/views/zipcode/index.html +++ b/component/admin/views/zipcode/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/admin/views/zipcode/tmpl/edit.php b/component/admin/views/zipcode/tmpl/edit.php index f2642c00811..61666e90606 100644 --- a/component/admin/views/zipcode/tmpl/edit.php +++ b/component/admin/views/zipcode/tmpl/edit.php @@ -17,8 +17,7 @@ ?> - close(); - } - } - else - { - $link = 'index.php?option=com_redshop&view=account&Itemid=' . $itemId; - } - - $this->setRedirect($link, $msg); - } + close(); + } + } else { + $link = 'index.php?option=com_redshop&view=account&Itemid=' . $itemId; + } + + $this->setRedirect($link, $msg); + } } diff --git a/component/site/controllers/account_shipto.php b/component/site/controllers/account_shipto.php index 58fd9f26a2e..7bfce706552 100644 --- a/component/site/controllers/account_shipto.php +++ b/component/site/controllers/account_shipto.php @@ -18,126 +18,126 @@ */ class RedshopControllerAccount_Shipto extends RedshopController { - /** - * Method to save Shipping Address - * - * @return void - * @throws Exception - */ - public function save() - { - $app = JFactory::getApplication(); - $input = $app->input; - $post = $input->post->getArray(); - $return = $input->getString('return', ''); - $itemId = $input->getInt('Itemid', 0); - $setExit = $input->getInt('setexit', 1); - - $post['users_info_id'] = $input->post->getInt('cid', 1); - $post['id'] = $post['user_id']; - $post['address_type'] = REDSHOP_ADDRESS_TYPE_SHIPPING; - - /** @var RedshopModelAccount_shipto $model */ - $model = $this->getModel('account_shipto'); - $redUser = $model->store($post); - - $msg = JText::_('COM_REDSHOP_ERROR_SAVING_SHIPPING_INFORMATION'); - $link = JRoute::_('index.php?option=com_redshop&view=account_shipto&Itemid=' . $itemId, false); - - if (false !== $redUser) - { - $post['users_info_id'] = $redUser->users_info_id; - $msg = JText::_('COM_REDSHOP_SHIPPING_INFORMATION_SAVE'); - } - - if (!empty($return)) - { - $link = JRoute::_( - 'index.php?option=com_redshop&view=' . $return - . '&users_info_id=' . $post['users_info_id'] . '&Itemid=' . $itemId, - false - ); - - if (!isset($setExit) || $setExit != 0) - { - $app->redirect('index.php?option=com_redshop&view=account_shipto&tmpl=component&is_edit=1&return=' - . $return . '&Itemid=' . $itemId, $msg); - } - } - - $this->setRedirect($link, $msg); - } - - /** - * Method to delete shipping address - * - * @return void - * @throws Exception - */ - public function remove() - { - $input = JFactory::getApplication()->input; - $itemId = $input->get('Itemid'); - $infoId = $input->getInt('infoid', 0); - - /** @var RedshopModelAccount_shipto $model */ - $model = $this->getModel('account_shipto'); - - if (!$infoId) - { - JError::raiseError(500, JText::_('COM_REDSHOP_SELECT_AN_ITEM_TO_DELETE')); - } - - if (!$model->delete($infoId)) - { - echo "\n"; - } - - $msg = JText::_('COM_REDSHOP_ACCOUNT_SHIPPING_DELETED_SUCCESSFULLY'); - $return = $input->get('return'); - $link = JRoute::_('index.php?option=com_redshop&view=account_shipto&Itemid=' . $itemId, false); - - if (!empty($return)) - { - $link = JRoute::_('index.php?option=com_redshop&view=' . $return . '&Itemid=' . $itemId, false); - } - - $this->setRedirect($link, $msg); - } - - /** - * Method called when user pressed cancel button - * - * @return void - * @throws Exception - */ - public function cancel() - { - $input = JFactory::getApplication()->input; - $itemId = $input->getInt('Itemid'); - $return = $input->get('return'); - $message = JText::_('COM_REDSHOP_SHIPPING_INFORMATION_EDITING_CANCELLED'); - - if (empty($return)) - { - $this->setRedirect(JRoute::_('index.php?option=com_redshop&view=account_shipto&Itemid=' . $itemId, false), $message); - $this->redirect(); - } - - $setExit = $input->getInt('setexit', 1); - $link = JRoute::_( - 'index.php?option=com_redshop&view=' . $return . '&users_info_id=' . $input->getInt('cid') . '&Itemid=' . $itemId . '', - false - ); - - if ($setExit != 1) - { - $this->setRedirect($link, $message); - $this->redirect(); - } - ?> + /** + * Method to save Shipping Address + * + * @return void + * @throws Exception + */ + public function save() + { + $app = JFactory::getApplication(); + $input = $app->input; + $post = $input->post->getArray(); + $return = $input->getString('return', ''); + $itemId = $input->getInt('Itemid', 0); + $setExit = $input->getInt('setexit', 1); + + $post['users_info_id'] = $input->post->getInt('cid', 1); + $post['id'] = $post['user_id']; + $post['address_type'] = REDSHOP_ADDRESS_TYPE_SHIPPING; + + /** @var RedshopModelAccount_shipto $model */ + $model = $this->getModel('account_shipto'); + $redUser = $model->store($post); + + $msg = JText::_('COM_REDSHOP_ERROR_SAVING_SHIPPING_INFORMATION'); + $link = JRoute::_('index.php?option=com_redshop&view=account_shipto&Itemid=' . $itemId, false); + + if (false !== $redUser) { + $post['users_info_id'] = $redUser->users_info_id; + $msg = JText::_('COM_REDSHOP_SHIPPING_INFORMATION_SAVE'); + } + + if (!empty($return)) { + $link = JRoute::_( + 'index.php?option=com_redshop&view=' . $return + . '&users_info_id=' . $post['users_info_id'] . '&Itemid=' . $itemId, + false + ); + + if (!isset($setExit) || $setExit != 0) { + $app->redirect( + 'index.php?option=com_redshop&view=account_shipto&tmpl=component&is_edit=1&return=' + . $return . '&Itemid=' . $itemId, + $msg + ); + } + } + + $this->setRedirect($link, $msg); + } + + /** + * Method to delete shipping address + * + * @return void + * @throws Exception + */ + public function remove() + { + $input = JFactory::getApplication()->input; + $itemId = $input->get('Itemid'); + $infoId = $input->getInt('infoid', 0); + + /** @var RedshopModelAccount_shipto $model */ + $model = $this->getModel('account_shipto'); + + if (!$infoId) { + JError::raiseError(500, JText::_('COM_REDSHOP_SELECT_AN_ITEM_TO_DELETE')); + } + + if (!$model->delete($infoId)) { + echo "\n"; + } + + $msg = JText::_('COM_REDSHOP_ACCOUNT_SHIPPING_DELETED_SUCCESSFULLY'); + $return = $input->get('return'); + $link = JRoute::_('index.php?option=com_redshop&view=account_shipto&Itemid=' . $itemId, false); + + if (!empty($return)) { + $link = JRoute::_('index.php?option=com_redshop&view=' . $return . '&Itemid=' . $itemId, false); + } + + $this->setRedirect($link, $msg); + } + + /** + * Method called when user pressed cancel button + * + * @return void + * @throws Exception + */ + public function cancel() + { + $input = JFactory::getApplication()->input; + $itemId = $input->getInt('Itemid'); + $return = $input->get('return'); + $message = JText::_('COM_REDSHOP_SHIPPING_INFORMATION_EDITING_CANCELLED'); + + if (empty($return)) { + $this->setRedirect( + JRoute::_('index.php?option=com_redshop&view=account_shipto&Itemid=' . $itemId, false), + $message + ); + $this->redirect(); + } + + $setExit = $input->getInt('setexit', 1); + $link = JRoute::_( + 'index.php?option=com_redshop&view=' . $return . '&users_info_id=' . $input->getInt( + 'cid' + ) . '&Itemid=' . $itemId . '', + false + ); + + if ($setExit != 1) { + $this->setRedirect($link, $message); + $this->redirect(); + } + ?> - close(); - } + close(); + } } diff --git a/component/site/controllers/ask_question.php b/component/site/controllers/ask_question.php index 2a29fb1d7ee..eadb2588d60 100644 --- a/component/site/controllers/ask_question.php +++ b/component/site/controllers/ask_question.php @@ -18,121 +18,103 @@ */ class RedshopControllerAsk_Question extends RedshopControllerForm { - /** - * Method to send Ask Question Mail. - * - * @return boolean - * @throws Exception - */ - public function submit() - { - // Check for request forgeries. - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); - - $app = JFactory::getApplication(); - $data = $app->input->post->get('jform', array(), 'array'); - $productId = $app->input->getInt('pid', 0); - $itemId = $app->input->getInt('Itemid', 0); - $ask = $app->input->getInt('ask', 0); - $categoryId = $app->input->getInt('category_id', 0); - - /** @var RedshopModelAsk_Question $model */ - $model = $this->getModel('ask_question'); - - if ($ask) - { - $link = 'index.php?option=com_redshop&view=product&pid=' . $productId . '&cid=' . $categoryId . '&Itemid=' . $itemId; - } - else - { - $link = 'index.php?option=com_redshop&view=ask_question&pid=' . $productId . '&tmpl=component&Itemid=' . $itemId; - } - - // Validate the posted data. - $form = $model->getForm(); - - if (!$form) - { - /** @scrutinizer ignore-deprecated */ JError::raiseError(500, $model->getError()); - $this->setRedirect(JRoute::_($link, false)); - - return false; - } - - // Save the data in the session. - $app->setUserState('com_redshop.ask_question.data', $data); - - // Check captcha only for guests - if (JFactory::getUser()->guest) - { - // Check exists captcha tag in question template form - $template = RedshopHelperTemplate::getTemplate('ask_question_template'); - - try - { - if (count($template) > 0 && strstr($template[0]->template_desc, '{captcha}') - && !Redshop\Helper\Utility::checkCaptcha($data, false)) - { - $app->enqueueMessage(JText::_('COM_REDSHOP_INVALID_SECURITY'), 'warning'); - $this->setRedirect($link); - - return false; - } - } - catch (Exception $e) - { - $app->enqueueMessage($e->getMessage(), 'warning'); - $this->setRedirect($link); - return false; - } - } - - $validate = $model->validate($form, $data); - - if ($validate === false) - { - // Get the validation messages. - $errors = /** @scrutinizer ignore-deprecated */ $model->getErrors(); - - foreach ($errors as $index => $error) - { - if ($error instanceof Exception) - { - $app->enqueueMessage($error->getMessage(), 'warning'); - } - else - { - $app->enqueueMessage($error, 'warning'); - } - - if ($index > 2) - { - break; - } - } - } - else - { - $data['product_id'] = $productId; - $data['Itemid'] = $itemId; - - if ($model->sendMailForAskQuestion($data)) - { - // Flush the data from the session - $app->setUserState('com_redshop.ask_question.data', null); - $app->enqueueMessage(JText::_('COM_REDSHOP_EMAIL_HAS_BEEN_SENT_SUCCESSFULLY')); - - if (!$ask) - { - $link = JUri::root() . $link . '&questionSend=1'; - } - } - else - { - $app->enqueueMessage(/** @scrutinizer ignore-deprecated */ $model->getError(), 'warning'); - } - } - - $this->setRedirect(JRoute::_($link, false)); - } + /** + * Method to send Ask Question Mail. + * + * @return boolean + * @throws Exception + */ + public function submit() + { + // Check for request forgeries. + JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + + $app = JFactory::getApplication(); + $data = $app->input->post->get('jform', array(), 'array'); + $productId = $app->input->getInt('pid', 0); + $itemId = $app->input->getInt('Itemid', 0); + $ask = $app->input->getInt('ask', 0); + $categoryId = $app->input->getInt('category_id', 0); + + /** @var RedshopModelAsk_Question $model */ + $model = $this->getModel('ask_question'); + + if ($ask) { + $link = 'index.php?option=com_redshop&view=product&pid=' . $productId . '&cid=' . $categoryId . '&Itemid=' . $itemId; + } else { + $link = 'index.php?option=com_redshop&view=ask_question&pid=' . $productId . '&tmpl=component&Itemid=' . $itemId; + } + + // Validate the posted data. + $form = $model->getForm(); + + if (!$form) { + /** @scrutinizer ignore-deprecated */ + JError::raiseError(500, $model->getError()); + $this->setRedirect(JRoute::_($link, false)); + + return false; + } + + // Save the data in the session. + $app->setUserState('com_redshop.ask_question.data', $data); + + // Check captcha only for guests + if (JFactory::getUser()->guest) { + // Check exists captcha tag in question template form + $template = RedshopHelperTemplate::getTemplate('ask_question_template'); + + try { + if (count($template) > 0 && strstr($template[0]->template_desc, '{captcha}') + && !Redshop\Helper\Utility::checkCaptcha($data, false)) { + $app->enqueueMessage(JText::_('COM_REDSHOP_INVALID_SECURITY'), 'warning'); + $this->setRedirect($link); + + return false; + } + } catch (Exception $e) { + $app->enqueueMessage($e->getMessage(), 'warning'); + $this->setRedirect($link); + + return false; + } + } + + $validate = $model->validate($form, $data); + + if ($validate === false) { + // Get the validation messages. + $errors = /** @scrutinizer ignore-deprecated */ + $model->getErrors(); + + foreach ($errors as $index => $error) { + if ($error instanceof Exception) { + $app->enqueueMessage($error->getMessage(), 'warning'); + } else { + $app->enqueueMessage($error, 'warning'); + } + + if ($index > 2) { + break; + } + } + } else { + $data['product_id'] = $productId; + $data['Itemid'] = $itemId; + + if ($model->sendMailForAskQuestion($data)) { + // Flush the data from the session + $app->setUserState('com_redshop.ask_question.data', null); + $app->enqueueMessage(JText::_('COM_REDSHOP_EMAIL_HAS_BEEN_SENT_SUCCESSFULLY')); + + if (!$ask) { + $link = JUri::root() . $link . '&questionSend=1'; + } + } else { + $app->enqueueMessage(/** @scrutinizer ignore-deprecated */ $model->getError(), 'warning'); + } + } + + $this->setRedirect(JRoute::_($link, false)); + } } diff --git a/component/site/controllers/catalog.php b/component/site/controllers/catalog.php index 9b20fdd320d..7b80bdc7633 100644 --- a/component/site/controllers/catalog.php +++ b/component/site/controllers/catalog.php @@ -18,78 +18,78 @@ */ class RedshopControllerCatalog extends RedshopController { - /** - * Method to send catalog - * - * @throws Exception - * - * @return void - */ - public function catalog_send() - { - $input = JFactory::getApplication()->input; - $post = $input->post->getArray(); - $itemId = $input->get('Itemid'); + /** + * Method to send catalog + * + * @return void + * @throws Exception + * + */ + public function catalog_send() + { + $input = JFactory::getApplication()->input; + $post = $input->post->getArray(); + $itemId = $input->get('Itemid'); - /** @var RedshopModelCatalog $model */ - $model = $this->getModel('catalog'); + /** @var RedshopModelCatalog $model */ + $model = $this->getModel('catalog'); - $post["registerDate"] = time(); - $post["email"] = $post["email_address"]; - $post["name"] = $post["name_2"]; + $post["registerDate"] = time(); + $post["email"] = $post["email_address"]; + $post["name"] = $post["name_2"]; - $row = $model->catalogStore($post); + $row = $model->catalogStore($post); - if ($row) - { - Redshop\Mail\Catalog::sendRequest($row); - $msg = JText::_('COM_REDSHOP_CATALOG_SEND_SUCCSEEFULLY'); - } - else - { - $msg = JText::_('COM_REDSHOP_ERROR_CATALOG_SEND_SUCCSEEFULLY'); - } + if ($row) { + Redshop\Mail\Catalog::sendRequest($row); + $msg = JText::_('COM_REDSHOP_CATALOG_SEND_SUCCSEEFULLY'); + } else { + $msg = JText::_('COM_REDSHOP_ERROR_CATALOG_SEND_SUCCSEEFULLY'); + } - $this->setRedirect(JRoute::_('index.php?option=com_redshop&view=catalog&Itemid=' . $itemId, false), $msg); - } + $this->setRedirect(JRoute::_('index.php?option=com_redshop&view=catalog&Itemid=' . $itemId, false), $msg); + } - /** - * Method to send catalog sample - * - * @return void - * - * @throws Exception - */ - public function catalogsample_send() - { - $input = JFactory::getApplication()->input; - $post = $input->post->getArray(); - $itemId = $input->get('Itemid'); + /** + * Method to send catalog sample + * + * @return void + * + * @throws Exception + */ + public function catalogsample_send() + { + $input = JFactory::getApplication()->input; + $post = $input->post->getArray(); + $itemId = $input->get('Itemid'); - /** @var RedshopModelCatalog $model */ - $model = $this->getModel('catalog'); + /** @var RedshopModelCatalog $model */ + $model = $this->getModel('catalog'); - if (isset($post["sample_code"])) - { - $colourId = implode(",", $post["sample_code"]); - $post ['colour_id'] = $colourId; - } + if (isset($post["sample_code"])) { + $colourId = implode(",", $post["sample_code"]); + $post ['colour_id'] = $colourId; + } - $post["registerdate"] = time(); - $post["email"] = $post["email_address"]; - $post["name"] = $post["name_2"]; - $row = $model->catalogSampleStore($post); + $post["registerdate"] = time(); + $post["email"] = $post["email_address"]; + $post["name"] = $post["name_2"]; + $row = $model->catalogSampleStore($post); - if ($row) - { - RedshopHelperExtrafields::extraFieldSave($post, RedshopHelperExtrafields::SECTION_COLOR_SAMPLE, $post['request_id']); - $msg = JText::_('COM_REDSHOP_SAMPLE_SEND_SUCCSEEFULLY'); - } - else - { - $msg = JText::_('COM_REDSHOP_ERROR_SAMPLE_SEND_SUCCSEEFULLY'); - } + if ($row) { + RedshopHelperExtrafields::extraFieldSave( + $post, + RedshopHelperExtrafields::SECTION_COLOR_SAMPLE, + $post['request_id'] + ); + $msg = JText::_('COM_REDSHOP_SAMPLE_SEND_SUCCSEEFULLY'); + } else { + $msg = JText::_('COM_REDSHOP_ERROR_SAMPLE_SEND_SUCCSEEFULLY'); + } - $this->setRedirect(JRoute::_('index.php?option=com_redshop&view=catalog&layout=sample&Itemid=' . $itemId, false), $msg); - } + $this->setRedirect( + JRoute::_('index.php?option=com_redshop&view=catalog&layout=sample&Itemid=' . $itemId, false), + $msg + ); + } } diff --git a/component/site/controllers/category.php b/component/site/controllers/category.php index 90cfec5bb12..edf01cd3401 100644 --- a/component/site/controllers/category.php +++ b/component/site/controllers/category.php @@ -19,327 +19,296 @@ */ class RedshopControllerCategory extends RedshopController { - /** - * Typical view method for MVC based architecture - * - * This function is provide as a default implementation, in most cases - * you will need to override it in your own controllers. - * - * @param boolean $cachable If true, the view output will be cached - * @param array $urlparams An array of safe URL parameters and their variable types, for valid values see {@link JFilterInput::clean()}. - * - * @return JControllerLegacy A JControllerLegacy object to support chaining. - * - * @since 3.0 - */ - public function display($cachable = false, $urlparams = array()) - { - $urlparams['Itemid'] = 'INT'; - $urlparams['cid'] = 'INT'; - $urlparams['lang'] = 'STRING'; - $urlparams['manufacturer_id'] = 'INT'; - $urlparams['view'] = 'STRING'; - $urlparams['layout'] = 'STRING'; - $urlparams['xmlexport_id'] = 'INT'; - $urlparams['q'] = 'STRING'; - $urlparams['limit'] = 'UINT'; - $urlparams['limitstart'] = 'UINT'; - $urlparams['showall'] = 'INT'; - $urlparams['return'] = 'BASE64'; - $urlparams['filter'] = 'STRING'; - $urlparams['filter_order'] = 'CMD'; - $urlparams['filter_order_Dir'] = 'CMD'; - $urlparams['filter-search'] = 'STRING'; - $urlparams['print'] = 'BOOLEAN'; - - parent::display(true, $urlparams); - - return $this; - } - - /** - * Method to Export XML file - * - * @return void - */ - public function download() - { - $filename = $this->input->getString('file', ''); - $db = JFactory::getDbo(); - $this->_table_prefix = "#__redshop_"; - - session_cache_limiter('public'); - - // To avoid an error notice of an undefined index. - if (empty($_SERVER['HTTP_REFERER'])) - { - $_SERVER['HTTP_REFERER'] = 'NoRef'; - } - - if (empty($_SERVER['REMOTE_ADDR'])) - { - return false; - } - - $query = "SELECT x.* FROM " . $this->_table_prefix . "xml_export AS x " - . "WHERE x.published=1 " - . "AND x.filename='" . $filename . "' "; - $db->setQuery($query); - $data = $db->loadObject(); - - if (count($data) > 0) - { - if (!$data->use_to_all_users && $_SERVER['SERVER_ADDR'] != $_SERVER['REMOTE_ADDR']) - { - $query = "SELECT x.*,xl.*,xi.* FROM " . $this->_table_prefix . "xml_export AS x " - . "LEFT JOIN " . $this->_table_prefix . "xml_export_log AS xl ON x.xmlexport_id=xl.xmlexport_id " - . "LEFT JOIN " . $this->_table_prefix . "xml_export_ipaddress AS xi ON x.xmlexport_id=xi.xmlexport_id " - . "WHERE x.published=1 " - . "AND (x.filename=" . $db->quote((string) $filename) . " " - . "OR xl.xmlexport_filename=" . $db->quote((string) $filename) . ") " - . "AND xi.access_ipaddress=" . $db->quote((string) $_SERVER['REMOTE_ADDR']) . " " - . "ORDER BY xl.xmlexport_date DESC "; - $db->setQuery($query); - $data = $db->loadObject(); - - if (count($data) <= 0) - { - echo $msg = JText::_('COM_REDSHOP_YOU_ARE_NOT_AUTHORIZED_TO_ACCESS'); - - return false; - } - } - } - else - { - echo $msg = JText::_('COM_REDSHOP_XMLFILE_IS_UNPUBLISHED'); - - return false; - } - - // Clean them variables boys (always clean variables at the start of your script to prevent injection attacks. Always limit input to expected chars and patterns.) - if (preg_match('/^([A-Za-z0-9.?=_\-\/:\s(%20)]{1,255})$/', stripslashes($_SERVER['HTTP_REFERER']), $matchref)) - { - $tempvar = $matchref[0]; - } - else - { - $tempvar = 'NoRef'; - } - - define('HTTP_REF', $tempvar); - - if (preg_match('/^([0-9.]{7,24})$/', stripslashes($_SERVER['REMOTE_ADDR']), $matchadd)) - { - $tempvar = $matchadd[0]; - } - else - { - $tempvar = '1.1.1.1'; - } - - // Required for IE, otherwise Content-disposition is ignored - if (ini_get('zlib.output_compression')) - { - ini_set('zlib.output_compression', 'Off'); - } - - $filepath = '#'; - - if ($filename != "") - { - $filepath = JPATH_COMPONENT_SITE . "/assets/xmlfile/export/" . $filename; - - if (!JFile::exists($filepath)) - { - JError::raiseError(500, "Oops. File not found"); - JFactory::getApplication()->close(); - } - } - else - { - JError::raiseError(500, "File name not specified"); - } - - session_write_close(); - - // IE Bug in download name workaround - if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) - { - try - { - ini_set('zlib.output_compression', 'Off'); - } - catch (Exception $ex) - { - JFactory::getApplication()->enqueueMessage($ex->getMessage(), 'error'); - } - } - - if (!$this->downloadFile($filepath)) - { - JError::raiseError('', 'The file transfer failed'); - } - - die(); - } - - /** - * Logic for download - * - * @param string $fil path - * @param null $p null variable not used - * - * @return bool - */ - public function downloadFile($fil, $p = null) - { - ob_clean(); - - if (connection_status() != 0) - { - return (false); - } - - $fn = basename($fil); - header("Cache-Control: no-store, no-cache, must-revalidate"); - header("Cache-Control: post-check=0, pre-check=0", false); - header("Pragma: no-cache"); - header("Expires: " . gmdate("D, d M Y H:i:s", mktime(date("H") + 2, date("i"), date("s"), date("m"), date("d"), date("Y"))) . " GMT"); - header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); - header("Content-Transfer-Encoding: binary"); - - // TODO: Not sure of this is working - if (function_exists('mime_content_type')) - { - $ctype = mime_content_type($fil); - } - elseif (function_exists('finfo_file')) - { - $finfo = finfo_open(FILEINFO_MIME); - $ctype = finfo_file($finfo, $fil); - finfo_close($finfo); - } - else - { - $ctype = "application/octet-stream"; - } - - header('Content-Type: ' . $ctype); - - if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) - { - // Workaround for IE filename bug with multiple periods / multiple dots in filename - // that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe - $iefilename = preg_replace('/\./', '%2e', $fn, substr_count($fn, '.') - 1); - header("Content-Disposition: attachment; filename=\"$iefilename\""); - } - else - { - header("Content-Disposition: attachment; filename=\"$fn\""); - } - - header("Accept-Ranges: bytes"); - - // Default to begining of file - $range = 0; - - // @ToDo make the download speed configurable - $size = filesize($fil); - - // Check if http_range is set. If so, change the range of the download to complete. - if (isset($_SERVER['HTTP_RANGE'])) - { - list($a, $range) = explode("=", $_SERVER['HTTP_RANGE']); - str_replace($range, "-", $range); - $size2 = $size - 1; - $new_length = $size - $range; - header("HTTP/1.1 206 Partial Content"); - header("Content-Length: $new_length"); - header("Content-Range: bytes $range$size2/$size"); - } - else - { - $size2 = $size - 1; - header("HTTP/1.0 200 OK"); - header("Content-Range: bytes 0-$size2/$size"); - header("Content-Length: " . $size); - } - - // Check to ensure it is not an empty file so the feof does not get stuck in an infinte loop. - if ($size == 0) - { - JError::raiseError(500, 'ERROR.ZERO_BYE_FILE'); - JFactory::getApplication()->close(); - } - - if (version_compare(PHP_VERSION, '5.3.0', '<')) - { - // Disable magic quotes for older version of php - set_magic_quotes_runtime(0); - } - - // We should check to ensure the file really exits to ensure feof does not get stuck in an infite loop, but we do so earlier on, so no need here. - $fp = fopen("$fil", "rb"); - - // Go to the start of missing part of the file - fseek($fp, $range); - - if (function_exists("set_time_limit")) - set_time_limit(0); - - while (!feof($fp) && connection_status() == 0) - { - // Reset time limit for big files - if (function_exists("set_time_limit")) - { - set_time_limit(0); - } - - print(fread($fp, 1024 * 8)); - flush(); - ob_flush(); - } - - sleep(1); - fclose($fp); - - return ((connection_status() == 0) and !connection_aborted()); - } - - /** - * Autofill city name - * - * @return string - */ - public function autofillcityname() - { - $db = JFactory::getDbo(); - ob_clean(); - $mainzipcode = $this->input->getString('q', ''); - $sel_zipcode = "select city_name from #__redshop_zipcode where zipcode='" . $mainzipcode . "'"; - $db->setQuery($sel_zipcode); - echo $db->loadResult(); - JFactory::getApplication()->close(); - } - - /** - * Generate XML file. - * - * @return void - */ - public function generateXMLExportFile() - { - $app = JFactory::getApplication(); - $exportId = $this->input->getInt('xmlexport_id'); - - if ($exportId) - { - $xmlHelper = new xmlHelper; - $xmlHelper->writeXMLExportFile($exportId); - $row = $xmlHelper->getXMLExportInfo($exportId); - $link = JRoute::_(JURI::root() . 'index.php?option=com_redshop&view=category&tmpl=component&task=download&file=' . $row->filename); - $app->redirect($link); - } - } + /** + * Typical view method for MVC based architecture + * + * This function is provide as a default implementation, in most cases + * you will need to override it in your own controllers. + * + * @param boolean $cachable If true, the view output will be cached + * @param array $urlparams An array of safe URL parameters and their variable types, for valid values see {@link JFilterInput::clean()}. + * + * @return JControllerLegacy A JControllerLegacy object to support chaining. + * + * @since 3.0 + */ + public function display($cachable = false, $urlparams = array()) + { + $urlparams['Itemid'] = 'INT'; + $urlparams['cid'] = 'INT'; + $urlparams['lang'] = 'STRING'; + $urlparams['manufacturer_id'] = 'INT'; + $urlparams['view'] = 'STRING'; + $urlparams['layout'] = 'STRING'; + $urlparams['xmlexport_id'] = 'INT'; + $urlparams['q'] = 'STRING'; + $urlparams['limit'] = 'UINT'; + $urlparams['limitstart'] = 'UINT'; + $urlparams['showall'] = 'INT'; + $urlparams['return'] = 'BASE64'; + $urlparams['filter'] = 'STRING'; + $urlparams['filter_order'] = 'CMD'; + $urlparams['filter_order_Dir'] = 'CMD'; + $urlparams['filter-search'] = 'STRING'; + $urlparams['print'] = 'BOOLEAN'; + + parent::display(true, $urlparams); + + return $this; + } + + /** + * Method to Export XML file + * + * @return void + */ + public function download() + { + $filename = $this->input->getString('file', ''); + $db = JFactory::getDbo(); + $this->_table_prefix = "#__redshop_"; + + session_cache_limiter('public'); + + // To avoid an error notice of an undefined index. + if (empty($_SERVER['HTTP_REFERER'])) { + $_SERVER['HTTP_REFERER'] = 'NoRef'; + } + + if (empty($_SERVER['REMOTE_ADDR'])) { + return false; + } + + $query = "SELECT x.* FROM " . $this->_table_prefix . "xml_export AS x " + . "WHERE x.published=1 " + . "AND x.filename='" . $filename . "' "; + $db->setQuery($query); + $data = $db->loadObject(); + + if (count($data) > 0) { + if (!$data->use_to_all_users && $_SERVER['SERVER_ADDR'] != $_SERVER['REMOTE_ADDR']) { + $query = "SELECT x.*,xl.*,xi.* FROM " . $this->_table_prefix . "xml_export AS x " + . "LEFT JOIN " . $this->_table_prefix . "xml_export_log AS xl ON x.xmlexport_id=xl.xmlexport_id " + . "LEFT JOIN " . $this->_table_prefix . "xml_export_ipaddress AS xi ON x.xmlexport_id=xi.xmlexport_id " + . "WHERE x.published=1 " + . "AND (x.filename=" . $db->quote((string)$filename) . " " + . "OR xl.xmlexport_filename=" . $db->quote((string)$filename) . ") " + . "AND xi.access_ipaddress=" . $db->quote((string)$_SERVER['REMOTE_ADDR']) . " " + . "ORDER BY xl.xmlexport_date DESC "; + $db->setQuery($query); + $data = $db->loadObject(); + + if (count($data) <= 0) { + echo $msg = JText::_('COM_REDSHOP_YOU_ARE_NOT_AUTHORIZED_TO_ACCESS'); + + return false; + } + } + } else { + echo $msg = JText::_('COM_REDSHOP_XMLFILE_IS_UNPUBLISHED'); + + return false; + } + + // Clean them variables boys (always clean variables at the start of your script to prevent injection attacks. Always limit input to expected chars and patterns.) + if (preg_match('/^([A-Za-z0-9.?=_\-\/:\s(%20)]{1,255})$/', stripslashes($_SERVER['HTTP_REFERER']), $matchref)) { + $tempvar = $matchref[0]; + } else { + $tempvar = 'NoRef'; + } + + define('HTTP_REF', $tempvar); + + if (preg_match('/^([0-9.]{7,24})$/', stripslashes($_SERVER['REMOTE_ADDR']), $matchadd)) { + $tempvar = $matchadd[0]; + } else { + $tempvar = '1.1.1.1'; + } + + // Required for IE, otherwise Content-disposition is ignored + if (ini_get('zlib.output_compression')) { + ini_set('zlib.output_compression', 'Off'); + } + + $filepath = '#'; + + if ($filename != "") { + $filepath = JPATH_COMPONENT_SITE . "/assets/xmlfile/export/" . $filename; + + if (!JFile::exists($filepath)) { + JError::raiseError(500, "Oops. File not found"); + JFactory::getApplication()->close(); + } + } else { + JError::raiseError(500, "File name not specified"); + } + + session_write_close(); + + // IE Bug in download name workaround + if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { + try { + ini_set('zlib.output_compression', 'Off'); + } catch (Exception $ex) { + JFactory::getApplication()->enqueueMessage($ex->getMessage(), 'error'); + } + } + + if (!$this->downloadFile($filepath)) { + JError::raiseError('', 'The file transfer failed'); + } + + die(); + } + + /** + * Logic for download + * + * @param string $fil path + * @param null $p null variable not used + * + * @return bool + */ + public function downloadFile($fil, $p = null) + { + ob_clean(); + + if (connection_status() != 0) { + return (false); + } + + $fn = basename($fil); + header("Cache-Control: no-store, no-cache, must-revalidate"); + header("Cache-Control: post-check=0, pre-check=0", false); + header("Pragma: no-cache"); + header( + "Expires: " . gmdate( + "D, d M Y H:i:s", + mktime(date("H") + 2, date("i"), date("s"), date("m"), date("d"), date("Y")) + ) . " GMT" + ); + header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); + header("Content-Transfer-Encoding: binary"); + + // TODO: Not sure of this is working + if (function_exists('mime_content_type')) { + $ctype = mime_content_type($fil); + } elseif (function_exists('finfo_file')) { + $finfo = finfo_open(FILEINFO_MIME); + $ctype = finfo_file($finfo, $fil); + finfo_close($finfo); + } else { + $ctype = "application/octet-stream"; + } + + header('Content-Type: ' . $ctype); + + if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) { + // Workaround for IE filename bug with multiple periods / multiple dots in filename + // that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe + $iefilename = preg_replace('/\./', '%2e', $fn, substr_count($fn, '.') - 1); + header("Content-Disposition: attachment; filename=\"$iefilename\""); + } else { + header("Content-Disposition: attachment; filename=\"$fn\""); + } + + header("Accept-Ranges: bytes"); + + // Default to begining of file + $range = 0; + + // @ToDo make the download speed configurable + $size = filesize($fil); + + // Check if http_range is set. If so, change the range of the download to complete. + if (isset($_SERVER['HTTP_RANGE'])) { + list($a, $range) = explode("=", $_SERVER['HTTP_RANGE']); + str_replace($range, "-", $range); + $size2 = $size - 1; + $new_length = $size - $range; + header("HTTP/1.1 206 Partial Content"); + header("Content-Length: $new_length"); + header("Content-Range: bytes $range$size2/$size"); + } else { + $size2 = $size - 1; + header("HTTP/1.0 200 OK"); + header("Content-Range: bytes 0-$size2/$size"); + header("Content-Length: " . $size); + } + + // Check to ensure it is not an empty file so the feof does not get stuck in an infinte loop. + if ($size == 0) { + JError::raiseError(500, 'ERROR.ZERO_BYE_FILE'); + JFactory::getApplication()->close(); + } + + if (version_compare(PHP_VERSION, '5.3.0', '<')) { + // Disable magic quotes for older version of php + set_magic_quotes_runtime(0); + } + + // We should check to ensure the file really exits to ensure feof does not get stuck in an infite loop, but we do so earlier on, so no need here. + $fp = fopen("$fil", "rb"); + + // Go to the start of missing part of the file + fseek($fp, $range); + + if (function_exists("set_time_limit")) { + set_time_limit(0); + } + + while (!feof($fp) && connection_status() == 0) { + // Reset time limit for big files + if (function_exists("set_time_limit")) { + set_time_limit(0); + } + + print(fread($fp, 1024 * 8)); + flush(); + ob_flush(); + } + + sleep(1); + fclose($fp); + + return ((connection_status() == 0) and !connection_aborted()); + } + + /** + * Autofill city name + * + * @return string + */ + public function autofillcityname() + { + $db = JFactory::getDbo(); + ob_clean(); + $mainzipcode = $this->input->getString('q', ''); + $sel_zipcode = "select city_name from #__redshop_zipcode where zipcode='" . $mainzipcode . "'"; + $db->setQuery($sel_zipcode); + echo $db->loadResult(); + JFactory::getApplication()->close(); + } + + /** + * Generate XML file. + * + * @return void + */ + public function generateXMLExportFile() + { + $app = JFactory::getApplication(); + $exportId = $this->input->getInt('xmlexport_id'); + + if ($exportId) { + $xmlHelper = new xmlHelper; + $xmlHelper->writeXMLExportFile($exportId); + $row = $xmlHelper->getXMLExportInfo($exportId); + $link = JRoute::_( + JURI::root( + ) . 'index.php?option=com_redshop&view=category&tmpl=component&task=download&file=' . $row->filename + ); + $app->redirect($link); + } + } } diff --git a/component/site/controllers/checkout.php b/component/site/controllers/checkout.php index dbfc34569d7..7cd75cd6985 100644 --- a/component/site/controllers/checkout.php +++ b/component/site/controllers/checkout.php @@ -33,14 +33,14 @@ class RedshopControllerCheckout extends RedshopController /** * Constructor. * - * @param array $default config array + * @param array $default config array * * @throws Exception */ public function __construct($default = array()) { $this->_order_functions = order_functions::getInstance(); - $this->_shippinghelper = shipping::getInstance(); + $this->_shippinghelper = shipping::getInstance(); JFactory::getApplication()->input->set('layout', 'default'); parent::__construct($default); } @@ -55,7 +55,7 @@ public function __construct($default = array()) public function checkoutprocess() { $input = JFactory::getApplication()->input; - $post = $input->post->getArray(); + $post = $input->post->getArray(); /** @var RedshopModelCheckout $model */ $model = $this->getModel('checkout'); @@ -80,14 +80,14 @@ public function checkoutprocess() */ public function checkoutNext() { - $app = \JFactory::getApplication(); - $input = $app->input; + $app = \JFactory::getApplication(); + $input = $app->input; $session = \JFactory::getSession(); - $post = $input->post->getArray(); - $cart = \Redshop\Cart\Helper::getCart(); + $post = $input->post->getArray(); + $cart = \Redshop\Cart\Helper::getCart(); if (isset($post['extrafields0']) - && isset($post['extrafields']) + && isset($post['extrafields']) && count($cart) > 0) { if (count($post['extrafields0']) > 0 && count($post['extrafields']) > 0) { for ($r = 0, $countExtrafield = count($post['extrafields']); $r < $countExtrafield; $r++) { @@ -99,10 +99,10 @@ public function checkoutNext() } } - $itemId = $input->post->getInt('Itemid', 0); - $userInfoIds = $input->post->getInt('users_info_id', 0); + $itemId = $input->post->getInt('Itemid', 0); + $userInfoIds = $input->post->getInt('users_info_id', 0); $creditCardInfo = $input->post->getString('ccinfo', ''); - $rsUser = $session->get('rs_user'); + $rsUser = $session->get('rs_user'); if ($userInfoIds) { $rsUser['rs_user_info_id'] = $userInfoIds; @@ -136,65 +136,10 @@ public function checkoutNext() } } - /** - * Update GLS Location - * - * @return void - * - * @throws Exception - */ - public function updateGLSLocation() - { - $app = JFactory::getApplication(); - $input = $app->input; - JPluginHelper::importPlugin('redshop_shipping'); - $dispatcher = RedshopHelperUtility::getDispatcher(); - $usersInfoId = $input->getInt('users_info_id', 0); - $values = RedshopHelperUser::getUserInformation(0, '', $usersInfoId, false); - $values->zipcode = $input->get('zipcode', ''); - $ShopResponses = $dispatcher->trigger('GetNearstParcelShops', array($values)); - - if ($ShopResponses && isset($ShopResponses[0]) && $ShopResponses[0]) { - if (is_array($ShopResponses[0])) { - $ShopRespons = $ShopResponses[0]; - $shopList = array(); - - for ($i = 0, $c = count($ShopRespons); $i < $c; $i++) { - $shopList[] = JHTML::_('select.option', $ShopRespons[$i]->shop_id, $ShopRespons[$i]->CompanyName . ", " . $ShopRespons[$i]->Streetname . ", " . $ShopRespons[$i]->ZipCode . ", " . $ShopRespons[$i]->CityName); - } - - echo JHTML::_('select.genericlist', $shopList, 'shop_id', 'class="inputbox" ', 'value', 'text', $ShopRespons[0]->shop_id); - } else { - echo $ShopResponses[0]; - } - } - - $app->close(); - } - - /** - * Get Shipping Information - * - * @return void - * - * @throws Exception - */ - public function getShippingInformation() - { - $app = JFactory::getApplication(); - $plugin = $app->input->getCmd('plugin', ''); - - JPluginHelper::importPlugin('redshop_shipping'); - $dispatcher = RedshopHelperUtility::getDispatcher(); - $dispatcher->trigger('on' . $plugin . 'AjaxRequest'); - - $app->close(); - } - /** * Check validation * - * @param integer $userInfoIds not used + * @param integer $userInfoIds not used * * @return integer * @@ -203,7 +148,7 @@ public function getShippingInformation() public function checkValidation($userInfoIds) { /** @var RedshopModelCheckout $model */ - $model = $this->getModel('checkout'); + $model = $this->getModel('checkout'); $billingAddresses = $model->billingaddresses(); $return = 0; @@ -211,13 +156,13 @@ public function checkValidation($userInfoIds) if (!$billingAddresses->is_company) { if ($billingAddresses->firstname == '') { $return = 1; - $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_FIRST_NAME'); + $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_FIRST_NAME'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; } elseif ($billingAddresses->lastname == '') { $return = 1; - $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_LAST_NAME'); + $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_LAST_NAME'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; @@ -225,7 +170,7 @@ public function checkValidation($userInfoIds) } else { if ($billingAddresses->company_name == '') { $return = 1; - $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_COMPANY_NAME'); + $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_COMPANY_NAME'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; @@ -233,13 +178,13 @@ public function checkValidation($userInfoIds) if ($billingAddresses->firstname == '') { $return = 1; - $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_FIRST_NAME'); + $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_FIRST_NAME'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; } elseif ($billingAddresses->lastname == '') { $return = 1; - $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_LAST_NAME'); + $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_LAST_NAME'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; @@ -248,11 +193,13 @@ public function checkValidation($userInfoIds) && trim($billingAddresses->ean_number) != '') { RedshopEconomic::createUserInEconomic($billingAddresses); - if (/** @scrutinizer ignore-deprecated */ JError::isError(/** @scrutinizer ignore-deprecated */ JError::getError())) { + if (/** @scrutinizer ignore-deprecated */ JError::isError( + /** @scrutinizer ignore-deprecated */ JError::getError() + )) { $return = 1; - $error = /** @scrutinizer ignore-deprecated */ + $error = /** @scrutinizer ignore-deprecated */ JError::getError(); - $msg = $error->getMessage(); + $msg = $error->getMessage(); \JFactory::getApplication()->enqueueMessage($msg, 'error'); return $return; @@ -262,25 +209,25 @@ public function checkValidation($userInfoIds) if (!trim($billingAddresses->address) && Redshop::getConfig()->get('REQUIRED_ADDRESS')) { $return = 1; - $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_ADDRESS'); + $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_ADDRESS'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; } elseif (!$billingAddresses->country_code && Redshop::getConfig()->get('REQUIRED_COUNTRY_CODE')) { $return = 1; - $msg = JText::_('COM_REDSHOP_PLEASE_SELECT_COUNTRY'); + $msg = JText::_('COM_REDSHOP_PLEASE_SELECT_COUNTRY'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; } elseif (!$billingAddresses->zipcode && Redshop::getConfig()->get('REQUIRED_POSTAL_CODE')) { $return = 1; - $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_ZIPCODE'); + $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_ZIPCODE'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; } elseif (!$billingAddresses->phone && Redshop::getConfig()->get('REQUIRED_PHONE')) { $return = 1; - $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_PHONE'); + $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_PHONE'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; @@ -288,24 +235,26 @@ public function checkValidation($userInfoIds) if ($billingAddresses->is_company == 1) { $extraFieldName = RedshopHelperExtrafields::CheckExtraFieldValidation( - RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS, $billingAddresses->users_info_id + RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS, + $billingAddresses->users_info_id ); if (!empty($extraFieldName)) { $return = 1; - $msg = $extraFieldName . JText::_('COM_REDSHOP_IS_REQUIRED'); + $msg = $extraFieldName . JText::_('COM_REDSHOP_IS_REQUIRED'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; } } else { $extraFieldName = RedshopHelperExtrafields::CheckExtraFieldValidation( - RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS, $billingAddresses->users_info_id + RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS, + $billingAddresses->users_info_id ); if (!empty($extraFieldName)) { $return = 1; - $msg = $extraFieldName . JText::_('COM_REDSHOP_IS_REQUIRED'); + $msg = $extraFieldName . JText::_('COM_REDSHOP_IS_REQUIRED'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; @@ -315,24 +264,26 @@ public function checkValidation($userInfoIds) if (Redshop::getConfig()->get('SHIPPING_METHOD_ENABLE') && $userInfoIds != $billingAddresses->users_info_id) { if ($billingAddresses->is_company == 1) { $extraFieldName = RedshopHelperExtrafields::CheckExtraFieldValidation( - RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS, $userInfoIds + RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS, + $userInfoIds ); if (!empty($extraFieldName)) { $return = 2; - $msg = $extraFieldName . JText::_('COM_REDSHOP_IS_REQUIRED'); + $msg = $extraFieldName . JText::_('COM_REDSHOP_IS_REQUIRED'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; } } else { $extraFieldName = RedshopHelperExtrafields::CheckExtraFieldValidation( - RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS, $userInfoIds + RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS, + $userInfoIds ); if (!empty($extraFieldName)) { $return = 2; - $msg = $extraFieldName . JText::_('COM_REDSHOP_IS_REQUIRED'); + $msg = $extraFieldName . JText::_('COM_REDSHOP_IS_REQUIRED'); \JFactory::getApplication()->enqueueMessage($msg, 'warning'); return $return; @@ -343,6 +294,111 @@ public function checkValidation($userInfoIds) return $return; } + /** + * Set credit Card info + * + * @return string + */ + public function setCreditCardInfo() + { + $input = JFactory::getApplication()->input; + $model = $this->getModel('checkout'); + $session = JFactory::getSession(); + $paymentMethodId = $input->post->getCmd('payment_method_id', ''); + $paymentMethod = RedshopHelperOrder::getPaymentMethodInfo($paymentMethodId); + $paymentParams = new JRegistry($paymentMethod[0]->params); + $isCreditcard = $paymentParams->get('is_creditcard', 0); + + if (!$isCreditcard) { + return ""; + } + + $data = array(); + $data['order_payment_name'] = $input->post->getString('order_payment_name', ''); + $data['creditcard_code'] = $input->post->getString('creditcard_code', ''); + $data['order_payment_number'] = $input->post->getString('order_payment_number', ''); + $data['order_payment_expire_month'] = $input->post->getString('order_payment_expire_month', ''); + $data['order_payment_expire_year'] = $input->post->getString('order_payment_expire_year', ''); + $data['credit_card_code'] = $input->post->getString('credit_card_code', ''); + $data['selectedCardId'] = $input->post->getString('selectedCard', ''); + $session->set('ccdata', $data); + + $validPayment = $model->validatePaymentCreditCardInfo(); + + if ($validPayment[0]) { + return ""; + } + + return $validPayment[1]; + } + + /** + * Update GLS Location + * + * @return void + * + * @throws Exception + */ + public function updateGLSLocation() + { + $app = JFactory::getApplication(); + $input = $app->input; + JPluginHelper::importPlugin('redshop_shipping'); + $dispatcher = RedshopHelperUtility::getDispatcher(); + $usersInfoId = $input->getInt('users_info_id', 0); + $values = RedshopHelperUser::getUserInformation(0, '', $usersInfoId, false); + $values->zipcode = $input->get('zipcode', ''); + $ShopResponses = $dispatcher->trigger('GetNearstParcelShops', array($values)); + + if ($ShopResponses && isset($ShopResponses[0]) && $ShopResponses[0]) { + if (is_array($ShopResponses[0])) { + $ShopRespons = $ShopResponses[0]; + $shopList = array(); + + for ($i = 0, $c = count($ShopRespons); $i < $c; $i++) { + $shopList[] = JHTML::_( + 'select.option', + $ShopRespons[$i]->shop_id, + $ShopRespons[$i]->CompanyName . ", " . $ShopRespons[$i]->Streetname . ", " . $ShopRespons[$i]->ZipCode . ", " . $ShopRespons[$i]->CityName + ); + } + + echo JHTML::_( + 'select.genericlist', + $shopList, + 'shop_id', + 'class="inputbox" ', + 'value', + 'text', + $ShopRespons[0]->shop_id + ); + } else { + echo $ShopResponses[0]; + } + } + + $app->close(); + } + + /** + * Get Shipping Information + * + * @return void + * + * @throws Exception + */ + public function getShippingInformation() + { + $app = JFactory::getApplication(); + $plugin = $app->input->getCmd('plugin', ''); + + JPluginHelper::importPlugin('redshop_shipping'); + $dispatcher = RedshopHelperUtility::getDispatcher(); + $dispatcher->trigger('on' . $plugin . 'AjaxRequest'); + + $app->close(); + } + /** * Checkout final step function * @@ -352,17 +408,17 @@ public function checkValidation($userInfoIds) */ public function checkoutfinal() { - $app = JFactory::getApplication(); - $input = $app->input; + $app = JFactory::getApplication(); + $input = $app->input; $dispatcher = RedshopHelperUtility::getDispatcher(); - $post = $input->post->getArray(); - $itemId = $input->post->getInt('Itemid', 0); + $post = $input->post->getArray(); + $itemId = $input->post->getInt('Itemid', 0); /** @var RedshopModelCheckout $model */ - $model = $this->getModel('checkout'); - $session = JFactory::getSession(); - $cart = $session->get('cart'); - $user = JFactory::getUser(); + $model = $this->getModel('checkout'); + $session = JFactory::getSession(); + $cart = $session->get('cart'); + $user = JFactory::getUser(); $payment_method_id = $input->post->getString('payment_method_id', ''); if (isset($post['extrafields0']) && isset($post['extrafields']) && count($cart) > 0) { @@ -378,7 +434,7 @@ public function checkoutfinal() if (Redshop::getConfig()->get('SHIPPING_METHOD_ENABLE')) { $shipping_rate_id = $input->post->getString('shipping_rate_id', ''); - $shippingdetail = Redshop\Shipping\Rate::decrypt($shipping_rate_id); + $shippingdetail = Redshop\Shipping\Rate::decrypt($shipping_rate_id); if (count($shippingdetail) < 4) { $shipping_rate_id = ""; @@ -404,7 +460,7 @@ public function checkoutfinal() $userInfoIds = $input->getInt('users_info_id'); if (empty($userInfoIds)) { - $userDetail = $model->store($post); + $userDetail = $model->store($post); $userInfoIds = $userDetail !== false ? $userDetail->users_info_id : 0; } @@ -427,7 +483,10 @@ public function checkoutfinal() $errorMsg = $this->setCreditCardInfo(); if ($errorMsg != "") { - $app->redirect(JRoute::_('index.php?option=com_redshop&view=checkout&Itemid=' . $itemId), $errorMsg); + $app->redirect( + JRoute::_('index.php?option=com_redshop&view=checkout&Itemid=' . $itemId), + $errorMsg + ); return; } @@ -443,7 +502,7 @@ public function checkoutfinal() // Add plugin support $dispatcher->trigger('beforeOrderPlace', array($cart)); $orderresult = $model->orderplace(); - $order_id = $orderresult->order_id; + $order_id = $orderresult->order_id; } else { $input->set('order_id', $order_id); } @@ -461,7 +520,14 @@ public function checkoutfinal() $labelClass = 'label-success'; } - $message = JText::sprintf('COM_REDSHOP_ALERT_ORDER_SUCCESSFULLY', $order_id, $billingAddresses->firstname . ' ' . $billingAddresses->lastname, RedshopHelperProductPrice::formattedPrice($orderresult->order_total), $labelClass, $orderresult->order_payment_status); + $message = JText::sprintf( + 'COM_REDSHOP_ALERT_ORDER_SUCCESSFULLY', + $order_id, + $billingAddresses->firstname . ' ' . $billingAddresses->lastname, + RedshopHelperProductPrice::formattedPrice($orderresult->order_total), + $labelClass, + $orderresult->order_payment_status + ); $dispatcher->trigger('storeAlert', array($message)); $model->resetcart(); @@ -481,18 +547,24 @@ public function checkoutfinal() */ $paymentmethod = RedshopHelperOrder::getPaymentMethodInfo($payment_method_id); $paymentmethod = $paymentmethod[0]; - $params = new \Joomla\Registry\Registry($paymentmethod->params); + $params = new \Joomla\Registry\Registry($paymentmethod->params); $is_creditcard = $params->get('is_creditcard', 0); $is_redirected = $params->get('is_redirected', 0); $session->clear('userDocument'); if ($is_creditcard && !$is_redirected) { - $link = JRoute::_('index.php?option=com_redshop&view=order_detail&layout=receipt&oid=' . $order_id . '&Itemid=' . $itemId, false); + $link = JRoute::_( + 'index.php?option=com_redshop&view=order_detail&layout=receipt&oid=' . $order_id . '&Itemid=' . $itemId, + false + ); $this->setRedirect($link, JText::_('COM_REDSHOP_ORDER_PLACED')); } else { - $link = JRoute::_('index.php?option=com_redshop&view=order_detail&layout=checkout_final&oid=' . $order_id - . '&Itemid=' . $itemId, false); + $link = JRoute::_( + 'index.php?option=com_redshop&view=order_detail&layout=checkout_final&oid=' . $order_id + . '&Itemid=' . $itemId, + false + ); $this->setRedirect($link); } } else { @@ -503,46 +575,12 @@ public function checkoutfinal() } } else { $msg = JText::_('COM_REDSHOP_SELECT_PAYMENT_METHOD'); - $app->redirect(JRoute::_('index.php?option=com_redshop&view=checkout&Itemid=' . $itemId, false), $msg, 'error'); - } - } - - /** - * Set credit Card info - * - * @return string - */ - public function setCreditCardInfo() - { - $input = JFactory::getApplication()->input; - $model = $this->getModel('checkout'); - $session = JFactory::getSession(); - $paymentMethodId = $input->post->getCmd('payment_method_id', ''); - $paymentMethod = RedshopHelperOrder::getPaymentMethodInfo($paymentMethodId); - $paymentParams = new JRegistry($paymentMethod[0]->params); - $isCreditcard = $paymentParams->get('is_creditcard', 0); - - if (!$isCreditcard) { - return ""; - } - - $data = array(); - $data['order_payment_name'] = $input->post->getString('order_payment_name', ''); - $data['creditcard_code'] = $input->post->getString('creditcard_code', ''); - $data['order_payment_number'] = $input->post->getString('order_payment_number', ''); - $data['order_payment_expire_month'] = $input->post->getString('order_payment_expire_month', ''); - $data['order_payment_expire_year'] = $input->post->getString('order_payment_expire_year', ''); - $data['credit_card_code'] = $input->post->getString('credit_card_code', ''); - $data['selectedCardId'] = $input->post->getString('selectedCard', ''); - $session->set('ccdata', $data); - - $validPayment = $model->validatePaymentCreditCardInfo(); - - if ($validPayment[0]) { - return ""; + $app->redirect( + JRoute::_('index.php?option=com_redshop&view=checkout&Itemid=' . $itemId, false), + $msg, + 'error' + ); } - - return $validPayment[1]; } /** @@ -554,11 +592,11 @@ public function setCreditCardInfo() */ public function oneStepCheckoutProcess() { - $app = JFactory::getApplication(); - $input = $app->input; - $session = JFactory::getSession(); + $app = JFactory::getApplication(); + $input = $app->input; + $session = JFactory::getSession(); $redShopUser = $session->get('rs_user'); - $post = $input->post->getArray(); + $post = $input->post->getArray(); $usersInfoId = $post['users_info_id']; if ($usersInfoId) { @@ -566,38 +604,42 @@ public function oneStepCheckoutProcess() } elseif (!empty($post['anonymous'])) { if (!empty($post['anonymous']['BT'])) { $redShopUser['vatCountry'] = $post['anonymous']['BT']['country_code']; - $redShopUser['vatState'] = $post['anonymous']['BT']['state_code']; + $redShopUser['vatState'] = $post['anonymous']['BT']['state_code']; } - if (Redshop::getConfig()->getInt('VAT_BASED_ON') != 0 && Redshop::getConfig()->getString('CALCULATE_VAT_ON') == 'ST' + if (Redshop::getConfig()->getInt('VAT_BASED_ON') != 0 && Redshop::getConfig()->getString( + 'CALCULATE_VAT_ON' + ) == 'ST' && !empty($post['anonymous']['ST'])) { $redShopUser['vatCountry'] = $post['anonymous']['ST']['country_code_ST']; - $redShopUser['vatState'] = $post['anonymous']['ST']['state_code_ST']; + $redShopUser['vatState'] = $post['anonymous']['ST']['state_code_ST']; } } $session->set('rs_user', $redShopUser); - $user = JFactory::getUser(); - $cart = $session->get('cart'); - $shipping_box_id = $post['shipping_box_id']; + $user = JFactory::getUser(); + $cart = $session->get('cart'); + $shipping_box_id = $post['shipping_box_id']; $shipping_rate_id = $post['shipping_rate_id']; - $customer_note = $post['customer_note']; - $req_number = $post['requisition_number']; + $customer_note = $post['customer_note']; + $req_number = $post['requisition_number']; $customer_message = $post['rs_customer_message_ta']; - $referral_code = $post['txt_referral_code']; + $referral_code = $post['txt_referral_code']; $payment_method_id = $post['payment_method_id']; - $order_total = $cart['total']; - $total_discount = $cart['cart_discount'] + $cart['voucher_discount'] + $cart['coupon_discount']; - $order_subtotal = (Redshop::getConfig()->get('SHIPPING_AFTER') == 'total') ? $cart['product_subtotal_excl_vat'] - $total_discount : $cart['product_subtotal_excl_vat']; - $itemId = $post['Itemid']; - $objectName = $post['objectname']; - $rate_template_id = $post['rate_template_id']; - $cart_template_id = $post['cart_template_id']; + $order_total = $cart['total']; + $total_discount = $cart['cart_discount'] + $cart['voucher_discount'] + $cart['coupon_discount']; + $order_subtotal = (Redshop::getConfig()->get( + 'SHIPPING_AFTER' + ) == 'total') ? $cart['product_subtotal_excl_vat'] - $total_discount : $cart['product_subtotal_excl_vat']; + $itemId = $post['Itemid']; + $objectName = $post['objectname']; + $rate_template_id = $post['rate_template_id']; + $cart_template_id = $post['cart_template_id']; $oneStepTemplateHtml = ""; - $rateTemplateHtml = ""; + $rateTemplateHtml = ""; if ($objectName == "users_info_id" || $objectName == "shipping_box_id") { $shipping_template = RedshopHelperTemplate::getTemplate("redshop_shipping", $rate_template_id); @@ -606,47 +648,56 @@ public function oneStepCheckoutProcess() $rateTemplateHtml = $shipping_template[0]->template_desc; } - $return = \Redshop\Shipping\Tag::replaceShippingTemplate($rateTemplateHtml, $shipping_rate_id, $shipping_box_id, $user->id, $usersInfoId, $order_total, $order_subtotal, $post); + $return = \Redshop\Shipping\Tag::replaceShippingTemplate( + $rateTemplateHtml, + $shipping_rate_id, + $shipping_box_id, + $user->id, + $usersInfoId, + $order_total, + $order_subtotal, + $post + ); $rateTemplateHtml = $return['template_desc']; $shipping_rate_id = $return['shipping_rate_id']; } if ($shipping_rate_id != "") { - $shipArr = Redshop\Helper\Shipping::calculateShipping($shipping_rate_id); - $cart['shipping'] = $shipArr['order_shipping_rate']; + $shipArr = Redshop\Helper\Shipping::calculateShipping($shipping_rate_id); + $cart['shipping'] = $shipArr['order_shipping_rate']; $cart['shipping_vat'] = $shipArr['shipping_vat']; - $cart = RedshopHelperDiscount::modifyDiscount($cart); + $cart = RedshopHelperDiscount::modifyDiscount($cart); } if ($cart_template_id != 0) { - $templatelist = RedshopHelperTemplate::getTemplate("checkout", $cart_template_id); + $templatelist = RedshopHelperTemplate::getTemplate("checkout", $cart_template_id); $oneStepTemplateHtml = $templatelist[0]->template_desc; $oneStepTemplateHtml = \RedshopTagsReplacer::_( 'commondisplaycart', $oneStepTemplateHtml, array( - 'usersInfoId' => $usersInfoId, - 'shippingRateId' => $shipping_rate_id, + 'usersInfoId' => $usersInfoId, + 'shippingRateId' => $shipping_rate_id, 'paymentMethodId' => $payment_method_id, - 'itemId' => $itemId, - 'customerNote' => $customer_note, - 'regNumber' => $req_number, - 'thirpartyEmail' => '', + 'itemId' => $itemId, + 'customerNote' => $customer_note, + 'regNumber' => $req_number, + 'thirpartyEmail' => '', 'customerMessage' => $customer_message, - 'referralCode' => $referral_code, - 'shopId' => '', - 'data' => $post + 'referralCode' => $referral_code, + 'shopId' => '', + 'data' => $post ) ); } $display_shippingrate = '
    ' . $rateTemplateHtml . '
    '; - $display_cart = '
    ' . $oneStepTemplateHtml . '
    '; + $display_cart = '
    ' . $oneStepTemplateHtml . '
    '; $description = $display_shippingrate . $display_cart; - $lang = JFactory::getLanguage(); - $locale = $lang->getLocale(); + $lang = JFactory::getLanguage(); + $locale = $lang->getLocale(); if (in_array('ru', $locale)) { // Commented because redshop currency symbol has been changed because of ajax response @@ -666,7 +717,7 @@ public function oneStepCheckoutProcess() */ public function displaycreditcard() { - $app = JFactory::getApplication(); + $app = JFactory::getApplication(); $cart = JFactory::getSession()->get('cart'); $creditcard = ""; @@ -695,7 +746,7 @@ public function ajaxDisplayPaymentExtraField() { \Redshop\Helper\Ajax::validateAjaxRequest('get'); - $app = JFactory::getApplication(); + $app = JFactory::getApplication(); $plugin = RedshopHelperPayment::info($app->input->getCmd('paymentMethod')); $layoutFile = new JLayoutFile('order.payment.extrafields'); @@ -716,20 +767,27 @@ public function ajaxDisplayPaymentExtraField() public function displayshippingextrafield() { ob_clean(); - $app = JFactory::getApplication(); - $shipping_rate_id = $app->input->post->getCmd('shipping_rate_id', ''); - $shippingmethod = RedshopHelperOrder::getShippingMethodInfo($shipping_rate_id); - $shippingparams = new JRegistry($shippingmethod[0]->params); + $app = JFactory::getApplication(); + $shipping_rate_id = $app->input->post->getCmd('shipping_rate_id', ''); + $shippingmethod = RedshopHelperOrder::getShippingMethodInfo($shipping_rate_id); + $shippingparams = new JRegistry($shippingmethod[0]->params); $extrafield_shipping = $shippingparams->get('extrafield_shipping', ''); - $extrafield_total = ""; + $extrafield_total = ""; $extrafield_hidden = ''; if (count($extrafield_shipping) > 0) { for ($ui = 0, $countExtrafield = count($extrafield_shipping); $ui < $countExtrafield; $ui++) { if ($extrafield_shipping[$ui] != "") { - $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields($extrafield_shipping[$ui], 19, '', 0, 0, 0); - $extrafield_total .= $productUserFields[0] . " " . $productUserFields[1] . "
    "; + $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields( + $extrafield_shipping[$ui], + 19, + '', + 0, + 0, + 0 + ); + $extrafield_total .= $productUserFields[0] . " " . $productUserFields[1] . "
    "; $extrafield_hidden .= ""; } } @@ -748,13 +806,13 @@ public function displayshippingextrafield() */ public function ajaxDisplayPaymentAnonymous() { - $app = JFactory::getApplication(); + $app = JFactory::getApplication(); $post = $app->input->post->getArray(); $cart = \Redshop\Cart\Helper::getCart(); - $isCompany = $post['is_company']; - $eanNumber = $post['eanNumber']; - $paymentMethods = RedshopHelperUtility::getPlugins('redshop_payment'); + $isCompany = $post['is_company']; + $eanNumber = $post['eanNumber']; + $paymentMethods = RedshopHelperUtility::getPlugins('redshop_payment'); $selectedPaymentMethodId = 0; if (count($paymentMethods) > 0) { @@ -772,7 +830,7 @@ public function ajaxDisplayPaymentAnonymous() } } - $templates = RedshopHelperTemplate::getTemplate("redshop_payment"); + $templates = RedshopHelperTemplate::getTemplate("redshop_payment"); $templateHtml = !empty($templates) ? $templates[0]->template_desc : ''; echo RedshopTagsReplacer::_( @@ -780,8 +838,8 @@ public function ajaxDisplayPaymentAnonymous() $templateHtml, array( 'paymentMethodId' => $selectedPaymentMethodId, - 'isCompany' => $isCompany, - 'eanNumber' => $eanNumber + 'isCompany' => $isCompany, + 'eanNumber' => $eanNumber ) ); diff --git a/component/site/controllers/login.php b/component/site/controllers/login.php index 9c11ee835e0..a3a722a85d4 100644 --- a/component/site/controllers/login.php +++ b/component/site/controllers/login.php @@ -19,128 +19,105 @@ */ class RedshopControllerLogin extends RedshopController { - /** - * Setlogin function - * - * @return void - */ - public function setlogin() - { - $username = $this->input->getUsername('username', ''); - $password = $this->input->post->get('password', '', 'raw'); - $Itemid = $this->input->get('Itemid'); - $returnitemid = $this->input->get('returnitemid'); - $mywishlist = $this->input->get('mywishlist'); - $productId = $this->input->get('product_id'); - $menu = JFactory::getApplication()->getMenu(); - $item = $menu->getItem($returnitemid); - - $model = $this->getModel('login'); - - $shoppergroupid = $this->input->post->getInt('protalid', ''); - - $msg = ""; - - if ($shoppergroupid != 0) - { - $check = $model->CheckShopperGroup($username, $shoppergroupid); - $link = "index.php?option=com_redshop&view=login&layout=portal&protalid=" . $shoppergroupid; - - if ($check > 0) - { - $model->setlogin($username, $password); - $return = $this->input->get('return'); - } - else - { - $msg = JText::_("COM_REDSHOP_SHOPPERGROUP_NOT_MATCH"); - $return = ""; - } - } - else - { - $model->setlogin($username, $password); - $return = $this->input->get('return'); - } - - if ($mywishlist == 1) - { - $error = $model->setlogin($username, $password); - - if ($error == true) - { - $wishreturn = JRoute::_('index.php?option=com_redshop&view=product&pid=' . $productId, false); - } - else - { - $wishreturn = JRoute::_('index.php?loginwishlist=1&option=com_redshop&view=login&wishlist=1&Itemid=' . $Itemid, false); - } - $this->setRedirect($wishreturn); - } - else - { - if ($item) - { - $link = $item->link . '&Itemid=' . $returnitemid; - - if ($item->params->get('aliasoptions')) - { - $link = '/?Itemid=' . $returnitemid; - } - } - else - { - $error = $model->setlogin($username, $password); - - if ($error == true) - { - $link = JRoute::_('index.php?option=com_redshop&Itemid=' . $returnitemid, false); - } - else - { - $link = JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . $Itemid, false); - } - } - - if (!empty($return)) - { - $s_Itemid = RedshopHelperRouter::getCheckoutItemId(); - $Itemid = $s_Itemid ? $s_Itemid : $Itemid; - $return = JRoute::_('index.php?option=com_redshop&view=checkout&Itemid=' . $Itemid, false); - - $this->setRedirect($return); - } - else - { - $this->setRedirect($link, $msg); - } - } - - } - - /** - * logout function - * - * @return void - */ - public function logout() - { - $app = JFactory::getApplication(); - $params = $app->getParams('com_redshop'); - $logout_itemid = $this->input->get('logout'); - $menu = JFactory::getApplication()->getMenu(); - $item = $menu->getItem($logout_itemid); - - if ($item) - { - $link = JRoute::_($item->link . '&Itemid=' . $logout_itemid, false); - } - else - { - $link = JRoute::_('index.php?option=com_redshop', false); - } - - $app->logout(); - $this->setRedirect($link); - } + /** + * Setlogin function + * + * @return void + */ + public function setlogin() + { + $username = $this->input->getUsername('username', ''); + $password = $this->input->post->get('password', '', 'raw'); + $Itemid = $this->input->get('Itemid'); + $returnitemid = $this->input->get('returnitemid'); + $mywishlist = $this->input->get('mywishlist'); + $productId = $this->input->get('product_id'); + $menu = JFactory::getApplication()->getMenu(); + $item = $menu->getItem($returnitemid); + + $model = $this->getModel('login'); + + $shoppergroupid = $this->input->post->getInt('protalid', ''); + + $msg = ""; + + if ($shoppergroupid != 0) { + $check = $model->CheckShopperGroup($username, $shoppergroupid); + $link = "index.php?option=com_redshop&view=login&layout=portal&protalid=" . $shoppergroupid; + + if ($check > 0) { + $model->setlogin($username, $password); + $return = $this->input->get('return'); + } else { + $msg = JText::_("COM_REDSHOP_SHOPPERGROUP_NOT_MATCH"); + $return = ""; + } + } else { + $model->setlogin($username, $password); + $return = $this->input->get('return'); + } + + if ($mywishlist == 1) { + $error = $model->setlogin($username, $password); + + if ($error == true) { + $wishreturn = JRoute::_('index.php?option=com_redshop&view=product&pid=' . $productId, false); + } else { + $wishreturn = JRoute::_( + 'index.php?loginwishlist=1&option=com_redshop&view=login&wishlist=1&Itemid=' . $Itemid, + false + ); + } + $this->setRedirect($wishreturn); + } else { + if ($item) { + $link = $item->link . '&Itemid=' . $returnitemid; + + if ($item->params->get('aliasoptions')) { + $link = '/?Itemid=' . $returnitemid; + } + } else { + $error = $model->setlogin($username, $password); + + if ($error == true) { + $link = JRoute::_('index.php?option=com_redshop&Itemid=' . $returnitemid, false); + } else { + $link = JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . $Itemid, false); + } + } + + if (!empty($return)) { + $s_Itemid = RedshopHelperRouter::getCheckoutItemId(); + $Itemid = $s_Itemid ? $s_Itemid : $Itemid; + $return = JRoute::_('index.php?option=com_redshop&view=checkout&Itemid=' . $Itemid, false); + + $this->setRedirect($return); + } else { + $this->setRedirect($link, $msg); + } + } + } + + /** + * logout function + * + * @return void + */ + public function logout() + { + $app = JFactory::getApplication(); + $params = $app->getParams('com_redshop'); + $logout_itemid = $this->input->get('logout'); + $menu = JFactory::getApplication()->getMenu(); + $item = $menu->getItem($logout_itemid); + + if ($item) { + $link = JRoute::_($item->link . '&Itemid=' . $logout_itemid, false); + } else { + $link = JRoute::_('index.php?option=com_redshop', false); + } + + $app->logout(); + $this->setRedirect($link); + } } diff --git a/component/site/controllers/newsletter.php b/component/site/controllers/newsletter.php index 5c5ab94850a..493728186f1 100644 --- a/component/site/controllers/newsletter.php +++ b/component/site/controllers/newsletter.php @@ -18,133 +18,111 @@ */ class RedshopControllerNewsletter extends RedshopController { - /** - * Method to subscribe newsletter - * - * @return void - * @throws Exception - */ - public function subscribe() - { - /** @var RedshopModelNewsletter $model */ - $model = $this->getModel('newsletter'); - $post = $this->input->post->getArray(); - $itemId = $this->input->get('Itemid'); - $newsletterId = $this->input->get('newsletteritemid'); - $menu = JFactory::getApplication()->getMenu(); - $item = $menu->getItem($newsletterId); - - if ($item) - { - $return = $item->link . '&Itemid=' . $newsletterId; - } - else - { - $return = "index.php?option=com_redshop&view=newsletter&layout=thankyou&Itemid=" . $itemId; - } - - // Check if user has already subscribe. - if ($model->checkSubscriptionByEmail($post['email'])) - { - $msg = JText::_('COM_REDSHOP_ALREADY_NEWSLETTER_SUBSCRIBER'); - } - else - { - if (RedshopHelperNewsletter::subscribe(0, $post, 1)) - { - if (Redshop::getConfig()->get('NEWSLETTER_CONFIRMATION')) - { - $msg = JText::_('COM_REDSHOP_SUBSCRIBE_SUCCESS'); - } - else - { - $msg = JText::_('COM_REDSHOP_NEWSLEETER_SUBSCRIBE_SUCCESS'); - } - } - else - { - $msg = JText::_('COM_REDSHOP_NEWSLEETER_SUBSCRIBE_FAIL'); - } - } - - $this->setRedirect($return, $msg); - } - - /** - * Method to unsubscribe newsletter - * - * @return void - * @throws Exception - */ - public function unsubscribe() - { - /** @var RedshopModelNewsletter $model */ - $model = $this->getModel('newsletter'); - $itemId = $this->input->get('Itemid'); - $email = $this->input->get('email'); - $newsletterId = $this->input->get('newsletteritemid'); - $menu = JFactory::getApplication()->getMenu(); - $item = $menu->getItem($newsletterId); - - if ($item) - { - $return = $item->link . '&Itemid=' . $newsletterId; - } - else - { - $return = "index.php?option=com_redshop&view=newsletter&layout=thankyou&Itemid=" . $itemId; - } - - // Check if user has subscribe or not. - if ($model->checkSubscriptionByEmail($email)) - { - if (RedshopHelperNewsletter::removeSubscribe($email)) - { - $msg = JText::_('COM_REDSHOP_CANCLE_SUBSCRIPTION'); - } - else - { - $msg = JText::_('COM_REDSHOP_CANCLE_SUBSCRIPTION_FAIL'); - } - } - else - { - $msg = JText::_('COM_REDSHOP_ALREADY_CANCLE_SUBSCRIPTION'); - } - - $this->setRedirect($return, $msg); - } - - /** - * Newsletter tracker to confirm email is read - * - * @return void - * @throws Exception - */ - public function tracker() - { - $db = JFactory::getDbo(); - - $trackerId = $this->input->getInt('tracker_id', 0); - - if (!$trackerId) - { - JError::raiseError(500, 'No Tracking Id found.'); - } - - // Mark Newsletter as read - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_newsletter_tracker')) - ->set($db->qn('read') . ' = 1') - ->where($db->qn('tracker_id') . ' = ' . (int) $trackerId); - - // Set the query and execute the update. - $db->setQuery($query)->execute(); - - // Set image header - header("Content-type: image/gif"); - readfile(JUri::root() . 'components/com_redshop/assets/images/spacer.gif'); - - JFactory::getApplication()->close(); - } + /** + * Method to subscribe newsletter + * + * @return void + * @throws Exception + */ + public function subscribe() + { + /** @var RedshopModelNewsletter $model */ + $model = $this->getModel('newsletter'); + $post = $this->input->post->getArray(); + $itemId = $this->input->get('Itemid'); + $newsletterId = $this->input->get('newsletteritemid'); + $menu = JFactory::getApplication()->getMenu(); + $item = $menu->getItem($newsletterId); + + if ($item) { + $return = $item->link . '&Itemid=' . $newsletterId; + } else { + $return = "index.php?option=com_redshop&view=newsletter&layout=thankyou&Itemid=" . $itemId; + } + + // Check if user has already subscribe. + if ($model->checkSubscriptionByEmail($post['email'])) { + $msg = JText::_('COM_REDSHOP_ALREADY_NEWSLETTER_SUBSCRIBER'); + } else { + if (RedshopHelperNewsletter::subscribe(0, $post, 1)) { + if (Redshop::getConfig()->get('NEWSLETTER_CONFIRMATION')) { + $msg = JText::_('COM_REDSHOP_SUBSCRIBE_SUCCESS'); + } else { + $msg = JText::_('COM_REDSHOP_NEWSLEETER_SUBSCRIBE_SUCCESS'); + } + } else { + $msg = JText::_('COM_REDSHOP_NEWSLEETER_SUBSCRIBE_FAIL'); + } + } + + $this->setRedirect($return, $msg); + } + + /** + * Method to unsubscribe newsletter + * + * @return void + * @throws Exception + */ + public function unsubscribe() + { + /** @var RedshopModelNewsletter $model */ + $model = $this->getModel('newsletter'); + $itemId = $this->input->get('Itemid'); + $email = $this->input->get('email'); + $newsletterId = $this->input->get('newsletteritemid'); + $menu = JFactory::getApplication()->getMenu(); + $item = $menu->getItem($newsletterId); + + if ($item) { + $return = $item->link . '&Itemid=' . $newsletterId; + } else { + $return = "index.php?option=com_redshop&view=newsletter&layout=thankyou&Itemid=" . $itemId; + } + + // Check if user has subscribe or not. + if ($model->checkSubscriptionByEmail($email)) { + if (RedshopHelperNewsletter::removeSubscribe($email)) { + $msg = JText::_('COM_REDSHOP_CANCLE_SUBSCRIPTION'); + } else { + $msg = JText::_('COM_REDSHOP_CANCLE_SUBSCRIPTION_FAIL'); + } + } else { + $msg = JText::_('COM_REDSHOP_ALREADY_CANCLE_SUBSCRIPTION'); + } + + $this->setRedirect($return, $msg); + } + + /** + * Newsletter tracker to confirm email is read + * + * @return void + * @throws Exception + */ + public function tracker() + { + $db = JFactory::getDbo(); + + $trackerId = $this->input->getInt('tracker_id', 0); + + if (!$trackerId) { + JError::raiseError(500, 'No Tracking Id found.'); + } + + // Mark Newsletter as read + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_newsletter_tracker')) + ->set($db->qn('read') . ' = 1') + ->where($db->qn('tracker_id') . ' = ' . (int)$trackerId); + + // Set the query and execute the update. + $db->setQuery($query)->execute(); + + // Set image header + header("Content-type: image/gif"); + readfile(JUri::root() . 'components/com_redshop/assets/images/spacer.gif'); + + JFactory::getApplication()->close(); + } } diff --git a/component/site/controllers/order_detail.php b/component/site/controllers/order_detail.php index f1d784850ff..3f41c785171 100644 --- a/component/site/controllers/order_detail.php +++ b/component/site/controllers/order_detail.php @@ -18,406 +18,402 @@ */ class RedshopControllerOrder_Detail extends RedshopController { - /** - * Constructor - * - * @param array $default config - */ - public function __construct($default = array()) - { - parent::__construct($default); - $this->_redshopMail = redshopMail::getInstance(); - $this->_order_functions = order_functions::getInstance(); - } - - /** - * bookinvoice function - * - * @return void - */ - public function bookinvoice() - { - } - - /** - * Process payment function for creditcard payment. - * - * @return void - */ - public function process_payment() - { - $app = JFactory::getApplication(); - $session = JFactory::getSession(); - $model = $this->getModel('order_detail'); - $data = array(); - - $request = $this->input->getArray(); - - // Get Order Detail - $order = RedshopEntityOrder::getInstance((int) $request['order_id'])->getItem(); - - // Get Billing and Shipping Info - $billingAddresses = RedshopHelperOrder::getBillingAddress($order->user_id); - $data['billingaddress'] = $billingAddresses; - - $shippingaddresses = RedshopHelperOrder::getOrderShippingUserInfo($order->order_id); - $data['shippingaddress'] = $shippingaddresses; - - $Itemid = $this->input->getInt('Itemid'); - - if (isset($billingAddresses)) - { - if (isset($billingAddresses->country_code)) - { - $billingAddresses->country_2_code = RedshopHelperWorld::getCountryCode2($billingAddresses->country_code); - $data ["billingaddress"]->country_2_code = $billingAddresses->country_2_code; - } - - if (isset($billingAddresses->state_code)) - { - $billingAddresses->state_2_code = $billingAddresses->state_code; - $data ["billingaddress"]->state_2_code = $billingAddresses->state_2_code; - } - } - - if (isset($shippingaddresses)) - { - if (isset($shippingaddresses->country_code)) - { - $shippingaddresses->country_2_code = RedshopHelperWorld::getCountryCode2($shippingaddresses->country_code); - $data ["shippingaddress"]->country_2_code = $shippingaddresses->country_2_code; - } - - if (isset($shippingaddresses->state_code)) - { - $shippingaddresses->state_2_code = $shippingaddresses->state_code; - $data ["shippingaddress"]->state_2_code = $shippingaddresses->state_2_code; - } - } - - // Get data for credit card - $ccData = array(); - $ccData['order_payment_name'] = $request['order_payment_name']; - $ccData['creditcard_code'] = $request['creditcard_code']; - $ccData['order_payment_number'] = $request['order_payment_number']; - $ccData['order_payment_expire_month'] = $request['order_payment_expire_month']; - $ccData['order_payment_expire_year'] = $request['order_payment_expire_year']; - $ccData['credit_card_code'] = $request['credit_card_code']; - $ccData['selectedCardId'] = $this->input->getString('selectedCard'); - - // Create session - $session->set('ccdata', $ccData); - - $values = array(); - $values['order_shipping'] = $order->order_shipping; - $values['order_number'] = $request['order_id']; - $values['order_tax'] = $order->order_tax; - $values['shippinginfo'] = $data ["shippingaddress"]; - $values['billinginfo'] = $data ["billingaddress"]; - $values['order_total'] = $order->order_total; - $values['order_subtotal'] = $order->order_subtotal; - $values["order_id"] = $request['order_id']; - $values['payment_plugin'] = $request['payment_method_id']; - $values['order'] = $order; - - // Call payment plugin - JPluginHelper::importPlugin('redshop_payment'); - $dispatcher = RedshopHelperUtility::getDispatcher(); - - $results = $dispatcher->trigger('onPrePayment_' . $values['payment_plugin'], array($values['payment_plugin'], $values)); - $paymentResponse = $results[0]; - - $paymentResponse->log = $paymentResponse->message; - $paymentResponse->msg = $paymentResponse->message; - - if ($paymentResponse->responsestatus == "Success" || $values['payment_plugin'] == "") - { - $paymentResponse->order_status_code = (isset($paymentResponse->status)) ? $paymentResponse->status : 'C'; - $paymentResponse->order_payment_status_code = (isset($paymentResponse->paymentStatus)) ? $paymentResponse->paymentStatus : 'Paid'; - $paymentResponse->order_id = $request['order_id']; - - // Change order status - RedshopHelperOrder::changeOrderStatus($paymentResponse); - } - - // Update order payment table with credit card details - $model->update_ccdata($request['order_id'], $paymentResponse->transaction_id); - $model->resetcart(); - - $link = 'index.php?option=com_redshop&view=order_detail&Itemid=' . $Itemid . '&oid=' . $request['order_id']; - $app->redirect(JRoute::_($link, false), $paymentResponse->message); - - } - - /** - * Notify payment function - * - * @return void - */ - public function notify_payment() - { - $request = $this->input->getArray(); - $Itemid = $this->input->getInt('Itemid'); - - JPluginHelper::importPlugin('redshop_payment'); - $dispatcher = RedshopHelperUtility::getDispatcher(); - - $results = $dispatcher->trigger( - 'onNotifyPayment' . $request['payment_plugin'], - array( - $request['payment_plugin'], - $request - ) - ); - - $msg = $results[0]->msg; - $type = (!empty($results[0]->type)) ? $results[0]->type : ''; - - if ($results[0] === false) - { - $order_id = $this->input->getInt('orderid'); - } - elseif (array_key_exists("order_id_temp", $results[0])) - { - $order_id = $results[0]->order_id_temp; - } - else - { - $order_id = $results[0]->order_id; - } - - // Change Order Status based on resutls - RedshopHelperOrder::changeOrderStatus($results[0]); - - $model = $this->getModel('order_detail'); - $model->resetcart(); - - /* - * Plugin will trigger onAfterNotifyPayment - */ - $dispatcher->trigger( - 'onAfterNotifyPayment' . $request['payment_plugin'], - array( - $request['payment_plugin'], - $order_id - ) - ); - - JPluginHelper::importPlugin('system'); - $dispatcher->trigger('afterOrderNotify', array($results)); - - if ($request['payment_plugin'] == "rs_payment_payer") - { - echo "TRUE"; - JFactory::getApplication()->close(); - } - - if ($request['payment_plugin'] != "rs_payment_worldpay") - { - // New checkout flow - $redirect_url = JRoute::_( - JUri::base() . "index.php?option=com_redshop&view=order_detail&layout=receipt&Itemid=$Itemid&oid=" . $order_id, false + /** + * Constructor + * + * @param array $default config + */ + public function __construct($default = array()) + { + parent::__construct($default); + $this->_redshopMail = redshopMail::getInstance(); + $this->_order_functions = order_functions::getInstance(); + } + + /** + * bookinvoice function + * + * @return void + */ + public function bookinvoice() + { + } + + /** + * Process payment function for creditcard payment. + * + * @return void + */ + public function process_payment() + { + $app = JFactory::getApplication(); + $session = JFactory::getSession(); + $model = $this->getModel('order_detail'); + $data = array(); + + $request = $this->input->getArray(); + + // Get Order Detail + $order = RedshopEntityOrder::getInstance((int)$request['order_id'])->getItem(); + + // Get Billing and Shipping Info + $billingAddresses = RedshopHelperOrder::getBillingAddress($order->user_id); + $data['billingaddress'] = $billingAddresses; + + $shippingaddresses = RedshopHelperOrder::getOrderShippingUserInfo($order->order_id); + $data['shippingaddress'] = $shippingaddresses; + + $Itemid = $this->input->getInt('Itemid'); + + if (isset($billingAddresses)) { + if (isset($billingAddresses->country_code)) { + $billingAddresses->country_2_code = RedshopHelperWorld::getCountryCode2( + $billingAddresses->country_code + ); + $data ["billingaddress"]->country_2_code = $billingAddresses->country_2_code; + } + + if (isset($billingAddresses->state_code)) { + $billingAddresses->state_2_code = $billingAddresses->state_code; + $data ["billingaddress"]->state_2_code = $billingAddresses->state_2_code; + } + } + + if (isset($shippingaddresses)) { + if (isset($shippingaddresses->country_code)) { + $shippingaddresses->country_2_code = RedshopHelperWorld::getCountryCode2( + $shippingaddresses->country_code + ); + $data ["shippingaddress"]->country_2_code = $shippingaddresses->country_2_code; + } + + if (isset($shippingaddresses->state_code)) { + $shippingaddresses->state_2_code = $shippingaddresses->state_code; + $data ["shippingaddress"]->state_2_code = $shippingaddresses->state_2_code; + } + } + + // Get data for credit card + $ccData = array(); + $ccData['order_payment_name'] = $request['order_payment_name']; + $ccData['creditcard_code'] = $request['creditcard_code']; + $ccData['order_payment_number'] = $request['order_payment_number']; + $ccData['order_payment_expire_month'] = $request['order_payment_expire_month']; + $ccData['order_payment_expire_year'] = $request['order_payment_expire_year']; + $ccData['credit_card_code'] = $request['credit_card_code']; + $ccData['selectedCardId'] = $this->input->getString('selectedCard'); + + // Create session + $session->set('ccdata', $ccData); + + $values = array(); + $values['order_shipping'] = $order->order_shipping; + $values['order_number'] = $request['order_id']; + $values['order_tax'] = $order->order_tax; + $values['shippinginfo'] = $data ["shippingaddress"]; + $values['billinginfo'] = $data ["billingaddress"]; + $values['order_total'] = $order->order_total; + $values['order_subtotal'] = $order->order_subtotal; + $values["order_id"] = $request['order_id']; + $values['payment_plugin'] = $request['payment_method_id']; + $values['order'] = $order; + + // Call payment plugin + JPluginHelper::importPlugin('redshop_payment'); + $dispatcher = RedshopHelperUtility::getDispatcher(); + + $results = $dispatcher->trigger( + 'onPrePayment_' . $values['payment_plugin'], + array($values['payment_plugin'], $values) + ); + $paymentResponse = $results[0]; + + $paymentResponse->log = $paymentResponse->message; + $paymentResponse->msg = $paymentResponse->message; + + if ($paymentResponse->responsestatus == "Success" || $values['payment_plugin'] == "") { + $paymentResponse->order_status_code = (isset($paymentResponse->status)) ? $paymentResponse->status : 'C'; + $paymentResponse->order_payment_status_code = (isset($paymentResponse->paymentStatus)) ? $paymentResponse->paymentStatus : 'Paid'; + $paymentResponse->order_id = $request['order_id']; + + // Change order status + RedshopHelperOrder::changeOrderStatus($paymentResponse); + } + + // Update order payment table with credit card details + $model->update_ccdata($request['order_id'], $paymentResponse->transaction_id); + $model->resetcart(); + + $link = 'index.php?option=com_redshop&view=order_detail&Itemid=' . $Itemid . '&oid=' . $request['order_id']; + $app->redirect(JRoute::_($link, false), $paymentResponse->message); + } + + /** + * Notify payment function + * + * @return void + */ + public function notify_payment() + { + $request = $this->input->getArray(); + $Itemid = $this->input->getInt('Itemid'); + + JPluginHelper::importPlugin('redshop_payment'); + $dispatcher = RedshopHelperUtility::getDispatcher(); + + $results = $dispatcher->trigger( + 'onNotifyPayment' . $request['payment_plugin'], + array( + $request['payment_plugin'], + $request + ) + ); + + $msg = $results[0]->msg; + $type = (!empty($results[0]->type)) ? $results[0]->type : ''; + + if ($results[0] === false) { + $order_id = $this->input->getInt('orderid'); + } elseif (array_key_exists("order_id_temp", $results[0])) { + $order_id = $results[0]->order_id_temp; + } else { + $order_id = $results[0]->order_id; + } + + // Change Order Status based on resutls + RedshopHelperOrder::changeOrderStatus($results[0]); + + $model = $this->getModel('order_detail'); + $model->resetcart(); + + /* + * Plugin will trigger onAfterNotifyPayment + */ + $dispatcher->trigger( + 'onAfterNotifyPayment' . $request['payment_plugin'], + array( + $request['payment_plugin'], + $order_id + ) + ); + + JPluginHelper::importPlugin('system'); + $dispatcher->trigger('afterOrderNotify', array($results)); + + if ($request['payment_plugin'] == "rs_payment_payer") { + echo "TRUE"; + JFactory::getApplication()->close(); + } + + if ($request['payment_plugin'] != "rs_payment_worldpay") { + // New checkout flow + $redirect_url = JRoute::_( + JUri::base( + ) . "index.php?option=com_redshop&view=order_detail&layout=receipt&Itemid=$Itemid&oid=" . $order_id, + false ); - $this->setRedirect($redirect_url, $msg, $type); - } - } - - /** - * Copy Order Item to Cart - * - * @param array $row Order Item information if not empty - * @param boolean $redirect If true will redirect to cart else not. - * - * @return mixed void / boolean - */ - public function copyOrderItemToCart($row = array(), $redirect = true) - { - // Import redSHOP Product Plugin - JPluginHelper::importPlugin('redshop_product'); - $dispatcher = RedshopHelperUtility::getDispatcher(); - $app = JFactory::getApplication(); - - // If empty then load order item detail from order table - if (empty($row)) - { - $order_item_id = $this->input->getInt('order_item_id'); - - $orderItem = RedshopHelperOrder::getOrderItemDetail(0, 0, $order_item_id); - $row = (array) $orderItem[0]; - } - - // Event Trigger on reordering cart item - $dispatcher->trigger('onReorderCartItem', array(&$row)); - - $subscription_id = 0; - $row['quantity'] = $row['product_quantity']; - - if ($row['is_giftcard'] == 1) - { - $row['giftcard_id'] = $row['product_id']; - $row['reciver_name'] = $row['giftcard_user_name']; - $row['reciver_email'] = $row['giftcard_user_email']; - } - else - { - $product_data = \Redshop\Product\Product::getProductById($row['product_id']); - - if ($product_data->product_type == 'subscription') - { - $productSubscription = RedshopHelperProduct::getUserProductSubscriptionDetail($row['order_item_id']); - - if ($productSubscription->subscription_id != "") - { - $subscription_id = $productSubscription->subscription_id; - } - } - - $generateAttributeCart = \Redshop\Attribute\Helper::generateAttributeFromOrder($row['order_item_id'], 0, $row['product_id'], $row['product_quantity']); - $generateAccessoryCart = \Redshop\Accessory\Helper::generateAccessoryFromOrder($row['order_item_id'], $row['product_id'], $row['product_quantity']); - - $row['cart_attribute'] = $generateAttributeCart; - $row['cart_accessory'] = $generateAccessoryCart; - $row['subscription_id'] = $subscription_id; - $row['sel_wrapper_id'] = $row['wrapper_id']; - $row['category_id'] = 0; - - if (JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . "orderMergeImages/" . $row['attribute_image'])) - { - $newMedia = JPATH_ROOT . '/components/com_redshop/assets/images/mergeImages/' . $row['attribute_image']; - $oldMedia = JPATH_ROOT . '/components/com_redshop/assets/images/orderMergeImages/' . $row['attribute_image']; - copy($oldMedia, $newMedia); - } - - $row['attributeImage'] = $row['attribute_image']; - - if (JFile::exists(JPATH_COMPONENT_SITE . "/assets/images/product_attributes/" . $row['attribute_image'])) - { - $row['hidden_attribute_cartimage'] = REDSHOP_FRONT_IMAGES_ABSPATH . "product_attributes/" . $row['attribute_image']; - } - } - - $result = Redshop\Cart\Cart::addProduct($row); - - if (is_bool($result) && $result) - { - // Set success message for product line - $app->enqueueMessage($row['order_item_name'] . ": " . JText::_("COM_REDSHOP_PRODUCT_ADDED_TO_CART")); - - if ($redirect) - { - // Do final cart calculations - RedshopHelperCart::cartFinalCalculation(); - - $app->redirect(JRoute::_('index.php?option=com_redshop&view=cart&Itemid=' . RedshopHelperRouter::getCartItemId(), false)); - } - } - else - { - $ItemData = RedshopHelperProduct::getMenuInformation(0, 0, '', 'product&pid=' . $row['product_id']); - - if (count($ItemData) > 0) - { - $Itemid = $ItemData->id; - } - else - { - $Itemid = RedshopHelperRouter::getItemId($row['product_id']); - } - - $errorMessage = ($result) ? $result : JText::_("COM_REDSHOP_PRODUCT_NOT_ADDED_TO_CART"); - - if (/** @scrutinizer ignore-deprecated */ JError::isError(/** @scrutinizer ignore-deprecated */ JError::getError())) - { - $errorMessage = /** @scrutinizer ignore-deprecated */ JError::getError()->getMessage(); - } - - $app->redirect( - JRoute::_('index.php?option=com_redshop&view=product&pid=' . $row['product_id'] . '&Itemid=' . $Itemid, false), - $errorMessage - ); - } - } - - /** - * On Reorder Order - * - * @return void - */ - public function reorder() - { - $app = JFactory::getApplication(); - $orderId = $this->input->getInt('order_id'); - $session = JFactory::getSession(); - $auth = $session->get('auth'); - - if ($orderId) - { - if (empty($auth['users_info_id'])) - { - $orderDetail = RedshopEntityOrder::getInstance($orderId)->getItem(); - $auth['users_info_id'] = $orderDetail->user_info_id; - $session->set('auth', $auth); - } - - // First Empty Cart and then oder it again - $cart = array(); - $cart['idx'] = 0; - JFactory::getSession()->set('cart', $cart); - - $orderItem = RedshopHelperOrder::getOrderItemDetail($orderId); - - for ($i = 0, $in = count($orderItem); $i < $in; $i++) - { - $row = (array) $orderItem[$i]; - - // Copy Order Item to cart - $this->copyOrderItemToCart($row, false); - } - - RedshopHelperCart::cartFinalCalculation(); - } - - $app->redirect(JRoute::_('index.php?option=com_redshop&view=cart&Itemid=' . RedshopHelperRouter::getCartItemId(), false)); - } - - /** - * payment function - * - * @return void - */ - public function payment() - { - $itemId = $this->input->getInt('Itemid'); - $orderId = $this->input->getInt('order_id'); - - $order = RedshopEntityOrder::getInstance($orderId)->getItem(); - $paymentInfo = RedshopEntityOrder::getInstance($orderId); - - if ($paymentInfo !== null) - { - $paymentInfo = $paymentInfo->getItem(); - } - - if ($paymentInfo) - { - $paymentMethod = RedshopHelperOrder::getPaymentMethodInfo($paymentInfo->payment_method_class); - - if (!empty($paymentMethod)) - { - $paymentParams = new JRegistry($paymentMethod[0]->params); - $isCreditcard = $paymentParams->get('is_creditcard', 0); - - if ($isCreditcard) - { - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/redshop.creditcard.min.js', false, true); - ?> + $this->setRedirect($redirect_url, $msg, $type); + } + } + + /** + * On Reorder Order + * + * @return void + */ + public function reorder() + { + $app = JFactory::getApplication(); + $orderId = $this->input->getInt('order_id'); + $session = JFactory::getSession(); + $auth = $session->get('auth'); + + if ($orderId) { + if (empty($auth['users_info_id'])) { + $orderDetail = RedshopEntityOrder::getInstance($orderId)->getItem(); + $auth['users_info_id'] = $orderDetail->user_info_id; + $session->set('auth', $auth); + } + + // First Empty Cart and then oder it again + $cart = array(); + $cart['idx'] = 0; + JFactory::getSession()->set('cart', $cart); + + $orderItem = RedshopHelperOrder::getOrderItemDetail($orderId); + + for ($i = 0, $in = count($orderItem); $i < $in; $i++) { + $row = (array)$orderItem[$i]; + + // Copy Order Item to cart + $this->copyOrderItemToCart($row, false); + } + + RedshopHelperCart::cartFinalCalculation(); + } + + $app->redirect( + JRoute::_('index.php?option=com_redshop&view=cart&Itemid=' . RedshopHelperRouter::getCartItemId(), false) + ); + } + + /** + * Copy Order Item to Cart + * + * @param array $row Order Item information if not empty + * @param boolean $redirect If true will redirect to cart else not. + * + * @return mixed void / boolean + */ + public function copyOrderItemToCart($row = array(), $redirect = true) + { + // Import redSHOP Product Plugin + JPluginHelper::importPlugin('redshop_product'); + $dispatcher = RedshopHelperUtility::getDispatcher(); + $app = JFactory::getApplication(); + + // If empty then load order item detail from order table + if (empty($row)) { + $order_item_id = $this->input->getInt('order_item_id'); + + $orderItem = RedshopHelperOrder::getOrderItemDetail(0, 0, $order_item_id); + $row = (array)$orderItem[0]; + } + + // Event Trigger on reordering cart item + $dispatcher->trigger('onReorderCartItem', array(&$row)); + + $subscription_id = 0; + $row['quantity'] = $row['product_quantity']; + + if ($row['is_giftcard'] == 1) { + $row['giftcard_id'] = $row['product_id']; + $row['reciver_name'] = $row['giftcard_user_name']; + $row['reciver_email'] = $row['giftcard_user_email']; + } else { + $product_data = \Redshop\Product\Product::getProductById($row['product_id']); + + if ($product_data->product_type == 'subscription') { + $productSubscription = RedshopHelperProduct::getUserProductSubscriptionDetail($row['order_item_id']); + + if ($productSubscription->subscription_id != "") { + $subscription_id = $productSubscription->subscription_id; + } + } + + $generateAttributeCart = \Redshop\Attribute\Helper::generateAttributeFromOrder( + $row['order_item_id'], + 0, + $row['product_id'], + $row['product_quantity'] + ); + $generateAccessoryCart = \Redshop\Accessory\Helper::generateAccessoryFromOrder( + $row['order_item_id'], + $row['product_id'], + $row['product_quantity'] + ); + + $row['cart_attribute'] = $generateAttributeCart; + $row['cart_accessory'] = $generateAccessoryCart; + $row['subscription_id'] = $subscription_id; + $row['sel_wrapper_id'] = $row['wrapper_id']; + $row['category_id'] = 0; + + if (JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . "orderMergeImages/" . $row['attribute_image'])) { + $newMedia = JPATH_ROOT . '/components/com_redshop/assets/images/mergeImages/' . $row['attribute_image']; + $oldMedia = JPATH_ROOT . '/components/com_redshop/assets/images/orderMergeImages/' . $row['attribute_image']; + copy($oldMedia, $newMedia); + } + + $row['attributeImage'] = $row['attribute_image']; + + if (JFile::exists(JPATH_COMPONENT_SITE . "/assets/images/product_attributes/" . $row['attribute_image'])) { + $row['hidden_attribute_cartimage'] = REDSHOP_FRONT_IMAGES_ABSPATH . "product_attributes/" . $row['attribute_image']; + } + } + + $result = Redshop\Cart\Cart::addProduct($row); + + if (is_bool($result) && $result) { + // Set success message for product line + $app->enqueueMessage($row['order_item_name'] . ": " . JText::_("COM_REDSHOP_PRODUCT_ADDED_TO_CART")); + + if ($redirect) { + // Do final cart calculations + RedshopHelperCart::cartFinalCalculation(); + + $app->redirect( + JRoute::_( + 'index.php?option=com_redshop&view=cart&Itemid=' . RedshopHelperRouter::getCartItemId(), + false + ) + ); + } + } else { + $ItemData = RedshopHelperProduct::getMenuInformation(0, 0, '', 'product&pid=' . $row['product_id']); + + if (count($ItemData) > 0) { + $Itemid = $ItemData->id; + } else { + $Itemid = RedshopHelperRouter::getItemId($row['product_id']); + } + + $errorMessage = ($result) ? $result : JText::_("COM_REDSHOP_PRODUCT_NOT_ADDED_TO_CART"); + + if (/** @scrutinizer ignore-deprecated */ JError::isError( + /** @scrutinizer ignore-deprecated */ JError::getError() + )) { + $errorMessage = /** @scrutinizer ignore-deprecated */ + JError::getError()->getMessage(); + } + + $app->redirect( + JRoute::_( + 'index.php?option=com_redshop&view=product&pid=' . $row['product_id'] . '&Itemid=' . $Itemid, + false + ), + $errorMessage + ); + } + } + + /** + * payment function + * + * @return void + */ + public function payment() + { + $itemId = $this->input->getInt('Itemid'); + $orderId = $this->input->getInt('order_id'); + + $order = RedshopEntityOrder::getInstance($orderId)->getItem(); + $paymentInfo = RedshopEntityOrder::getInstance($orderId); + + if ($paymentInfo !== null) { + $paymentInfo = $paymentInfo->getItem(); + } + + if ($paymentInfo) { + $paymentMethod = RedshopHelperOrder::getPaymentMethodInfo($paymentInfo->payment_method_class); + + if (!empty($paymentMethod)) { + $paymentParams = new JRegistry($paymentMethod[0]->params); + $isCreditcard = $paymentParams->get('is_creditcard', 0); + + if ($isCreditcard) { + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.creditcard.min.js', false, true); + ?>
    - payment_method_class); ?> + payment_method_class + ); ?>
    @@ -432,63 +428,58 @@ public function payment() value="payment_method_class; ?>"/>
    - setRedirect($link); - } - } - } - } - - /** - * Get order payament status using ajax - */ - public function AjaxOrderPaymentStatusCheck() - { - $orderId = $this->input->post->getInt('id'); - - $orderPaymentStatus = RedshopEntityOrder::load($orderId)->get('order_payment_status'); - - $status = JText::_('COM_REDSHOP_PAYMENT_STA_UNPAID'); - - if ($orderPaymentStatus == 'Paid') - { - $status = JText::_('COM_REDSHOP_PAYMENT_STA_PAID'); - } - - ob_clean(); - echo $status; - } - - /** - * Method for generate PDF for order detail . - * - * @return void - */ - public function printPDF() - { - $app = JFactory::getApplication(); - $orderId = $this->input->get->getInt('oid', 0); - - if (!$orderId) - { - $this->setMessage(JText::_('COM_REDSHOP_ORDER_DOWNLOAD_ERROR_MISSING_ORDER_ID'), 'error'); - $this->setRedirect('index.php?option=com_redshop&view=order'); - } - - // Check pdf plugins - if (!RedshopHelperPdf::isAvailablePdfPlugins()) - { - $this->setMessage(JText::_('COM_REDSHOP_ERROR_MISSING_PDF_PLUGIN'), 'error'); - $this->setRedirect(JRoute::_('index.php?option=com_redshop&view=order')); - } - - RedshopHelperOrder::generateInvoicePdf($orderId, 'I'); - - $app->close(); - } - + setRedirect($link); + } + } + } + } + + /** + * Get order payament status using ajax + */ + public function AjaxOrderPaymentStatusCheck() + { + $orderId = $this->input->post->getInt('id'); + + $orderPaymentStatus = RedshopEntityOrder::load($orderId)->get('order_payment_status'); + + $status = JText::_('COM_REDSHOP_PAYMENT_STA_UNPAID'); + + if ($orderPaymentStatus == 'Paid') { + $status = JText::_('COM_REDSHOP_PAYMENT_STA_PAID'); + } + + ob_clean(); + echo $status; + } + + /** + * Method for generate PDF for order detail . + * + * @return void + */ + public function printPDF() + { + $app = JFactory::getApplication(); + $orderId = $this->input->get->getInt('oid', 0); + + if (!$orderId) { + $this->setMessage(JText::_('COM_REDSHOP_ORDER_DOWNLOAD_ERROR_MISSING_ORDER_ID'), 'error'); + $this->setRedirect('index.php?option=com_redshop&view=order'); + } + + // Check pdf plugins + if (!RedshopHelperPdf::isAvailablePdfPlugins()) { + $this->setMessage(JText::_('COM_REDSHOP_ERROR_MISSING_PDF_PLUGIN'), 'error'); + $this->setRedirect(JRoute::_('index.php?option=com_redshop&view=order')); + } + + RedshopHelperOrder::generateInvoicePdf($orderId, 'I'); + + $app->close(); + } + } diff --git a/component/site/controllers/product.php b/component/site/controllers/product.php index d67544e466f..d9b0815e350 100644 --- a/component/site/controllers/product.php +++ b/component/site/controllers/product.php @@ -235,7 +235,7 @@ public function displayAdditionImage() $result['attrbimg'] = $pluginResults['attrbimg']; } } else { - $result = \RedshopHelperProductTag::displayAdditionalImage( + $result = \RedshopHelperProductTag::displayAdditionalImage( $productId, $accessoryId, $relatedProductId, @@ -821,6 +821,7 @@ public function ajaxupload() // If Extension is not legal than don't upload file if (!in_array(strtolower($fileExtension), $legalExts)) { echo '
  • ' . JText::_('COM_REDSHOP_FILE_EXTENSION_NOT_ALLOWED') . '
  • '; + return; } diff --git a/component/site/controllers/product_mini.php b/component/site/controllers/product_mini.php index 548b9024d3e..2fc81727703 100644 --- a/component/site/controllers/product_mini.php +++ b/component/site/controllers/product_mini.php @@ -31,8 +31,9 @@ public function cancel() } /** - * @param bool $cachable - * @param array $urlparams + * @param bool $cachable + * @param array $urlparams + * * @return JControllerLegacy|void */ public function display($cachable = false, $urlparams = array()) diff --git a/component/site/controllers/product_rating.php b/component/site/controllers/product_rating.php index 9fcff490565..2847f96c3f5 100644 --- a/component/site/controllers/product_rating.php +++ b/component/site/controllers/product_rating.php @@ -18,242 +18,211 @@ */ class RedshopControllerProduct_Rating extends RedshopControllerForm { - /** - * Method to send Ask Question Mail. - * - * @return bool - */ - public function submit() - { - // Check for request forgeries. - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); - - $app = JFactory::getApplication(); - $data = $app->input->post->get('jform', array(), 'array'); - $files = $app->input->post->files->get('jform', array(), 'array'); - $model = $this->getModel('product_rating'); - - $productId = $app->input->getInt('product_id', 0); - $Itemid = $app->input->getInt('Itemid', 0); - $modal = $app->input->getInt('modal', 0); - $category_id = $app->input->getInt('category_id', 0); - $returnUrl = $app->input->getString('returnurl', ''); - $user = JFactory::getUser(); - - if (!empty($returnUrl)) - { - $link = base64_decode($returnUrl); - } - elseif ($modal) - { - $link = 'index.php?option=com_redshop&view=product_rating&product_id=' . $productId . '&tmpl=component&Itemid=' . $Itemid; - } - else - { - $link = 'index.php?option=com_redshop&view=product&pid=' . $productId . '&cid=' . $category_id . '&Itemid=' . $Itemid; - } - - // Preform security checks - if (!$user->id && Redshop::getConfig()->get('RATING_REVIEW_LOGIN_REQUIRED')) - { - $app->enqueueMessage(JText::_('COM_REDSHOP_ALERTNOTAUTH_REVIEW'), 'warning'); - $this->setRedirect(JRoute::_($link, false)); - - return false; - } - - // Validate the posted data. - $form = $model->getForm(); - - if (!$form) - { - /** @scrutinizer ignore-deprecated */ JError::raiseError(500, $model->getError()); - $this->setRedirect(JRoute::_($link, false)); - - return false; - } - - // Save the data in the session. - $app->setUserState('com_redshop.edit.product_rating.' . $productId . '.data', $data); - - // Check captcha only for guests - if (JFactory::getUser()->guest) - { - if (!Redshop\Helper\Utility::checkCaptcha(/** @scrutinizer ignore-type */ $data, false)) - { - $app->enqueueMessage(JText::_('COM_REDSHOP_INVALID_SECURITY'), 'warning'); - $this->setRedirect($link); - - return false; - } - } - - if ($user->guest) - { - $data['userid'] = 0; - } - else - { - $data['userid'] = $user->id; - - if ($userInfo = RedshopHelperUser::getUserInformation($user->id)) - { - $data['username'] = $userInfo->firstname . " " . $userInfo->lastname; - $data['email'] = $userInfo->user_email; - - if ($userInfo->is_company) - { - $data['company_name'] = $userInfo->company_name; - } - } - else - { - $data['username'] = $user->name; - $data['email'] = $user->email; - } - } - - $images = array(); - $this->uploadImage($files, $images); - - if (!empty($images)) - { - $data['images'] = json_encode($images); - } - - $validate = $model->validate($form, $data); - - if ($validate === false) - { - // Get the validation messages. - $errors = $model->getErrors(); - - // Push up to three validation messages out to the user. - for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) - { - if ($errors[$i] instanceof Exception) - { - $app->enqueueMessage($errors[$i]->getMessage(), 'warning'); - } - else - { - $app->enqueueMessage($errors[$i], 'warning'); - } - } - - $this->setRedirect($link); - - return false; - } - - if ((Redshop::getConfig()->get('RATING_REVIEW_LOGIN_REQUIRED') && $model->checkRatedProduct($productId, $user->id)) - || (!Redshop::getConfig()->get('RATING_REVIEW_LOGIN_REQUIRED') && $model->checkRatedProduct($productId, 0, $data['email']))) - { - if ($modal) - { - $link .= '&rate=1'; - } - - $app->enqueueMessage(JText::_('COM_REDSHOP_YOU_CAN_NOT_REVIEW_SAME_PRODUCT_AGAIN'), 'warning'); - $this->setRedirect($link); - - return false; - } - - $data['published'] = 0; - $data['favoured'] = 0; - $data['time'] = time(); - $data['product_id'] = $productId; - $data['Itemid'] = $Itemid; - - if ($model->sendMailForReview($data)) - { - // Flush the data from the session - $app->setUserState('com_redshop.edit.product_rating.' . $productId . '.data', null); - - if (Redshop::getConfig()->get('RATING_MSG')) - { - $msg = Redshop::getConfig()->get('RATING_MSG'); - } - else - { - $msg = JText::_('COM_REDSHOP_EMAIL_HAS_BEEN_SENT_SUCCESSFULLY'); - } - - $app->enqueueMessage($msg); - - if ($modal) - { - $link .= '&rate=1'; - } - } - else - { - $app->enqueueMessage($model->getError(), 'warning'); - } - - $this->setRedirect($link); - } - - /** - * Method upload images - * - * @param array $files - * @param array $images - * - * @return void - * @since 2.1.4 - */ - public function uploadImage($files, &$images) - { - - foreach ($files['images'] as $file) - { - if ($file['error'] > 0 || $file['size'] > 2000000) - { - continue; - } - - $fileName = $file['name']; - $uploadedFileNameParts = explode('.',$fileName); - $uploadedFileExtension = array_pop($uploadedFileNameParts); - - $validFileExts = explode(',', 'jpeg,jpg,png,gif'); - $extOk = false; - - foreach($validFileExts as $key => $value) - { - if( preg_match("/$value/i", $uploadedFileExtension ) ) - { - $extOk = true; - } - } - - if ($extOk === false) - { - continue; - } - - $fileTemp = $file['tmp_name']; - $imageinfo = getimagesize($fileTemp); - - $okMIMETypes = 'image/jpeg,image/pjpeg,image/png,image/x-png,image/gif'; - $validFileTypes = explode(",", $okMIMETypes); - - if( !is_int($imageinfo[0]) || !is_int($imageinfo[1]) || !in_array($imageinfo['mime'], $validFileTypes) ) - { - continue; - } - - $fileName = RedshopHelperMedia::cleanFileName($fileName); - $uploadPath = REDSHOP_FRONT_IMAGES_RELPATH . 'product_rating/' . $fileName; - - if(!JFile::upload($fileTemp, $uploadPath)) - { - continue; - } - - $images[] = $fileName; - } - } + /** + * Method to send Ask Question Mail. + * + * @return bool + */ + public function submit() + { + // Check for request forgeries. + JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); + + $app = JFactory::getApplication(); + $data = $app->input->post->get('jform', array(), 'array'); + $files = $app->input->post->files->get('jform', array(), 'array'); + $model = $this->getModel('product_rating'); + + $productId = $app->input->getInt('product_id', 0); + $Itemid = $app->input->getInt('Itemid', 0); + $modal = $app->input->getInt('modal', 0); + $category_id = $app->input->getInt('category_id', 0); + $returnUrl = $app->input->getString('returnurl', ''); + $user = JFactory::getUser(); + + if (!empty($returnUrl)) { + $link = base64_decode($returnUrl); + } elseif ($modal) { + $link = 'index.php?option=com_redshop&view=product_rating&product_id=' . $productId . '&tmpl=component&Itemid=' . $Itemid; + } else { + $link = 'index.php?option=com_redshop&view=product&pid=' . $productId . '&cid=' . $category_id . '&Itemid=' . $Itemid; + } + + // Preform security checks + if (!$user->id && Redshop::getConfig()->get('RATING_REVIEW_LOGIN_REQUIRED')) { + $app->enqueueMessage(JText::_('COM_REDSHOP_ALERTNOTAUTH_REVIEW'), 'warning'); + $this->setRedirect(JRoute::_($link, false)); + + return false; + } + + // Validate the posted data. + $form = $model->getForm(); + + if (!$form) { + /** @scrutinizer ignore-deprecated */ + JError::raiseError(500, $model->getError()); + $this->setRedirect(JRoute::_($link, false)); + + return false; + } + + // Save the data in the session. + $app->setUserState('com_redshop.edit.product_rating.' . $productId . '.data', $data); + + // Check captcha only for guests + if (JFactory::getUser()->guest) { + if (!Redshop\Helper\Utility::checkCaptcha(/** @scrutinizer ignore-type */ $data, false)) { + $app->enqueueMessage(JText::_('COM_REDSHOP_INVALID_SECURITY'), 'warning'); + $this->setRedirect($link); + + return false; + } + } + + if ($user->guest) { + $data['userid'] = 0; + } else { + $data['userid'] = $user->id; + + if ($userInfo = RedshopHelperUser::getUserInformation($user->id)) { + $data['username'] = $userInfo->firstname . " " . $userInfo->lastname; + $data['email'] = $userInfo->user_email; + + if ($userInfo->is_company) { + $data['company_name'] = $userInfo->company_name; + } + } else { + $data['username'] = $user->name; + $data['email'] = $user->email; + } + } + + $images = array(); + $this->uploadImage($files, $images); + + if (!empty($images)) { + $data['images'] = json_encode($images); + } + + $validate = $model->validate($form, $data); + + if ($validate === false) { + // Get the validation messages. + $errors = $model->getErrors(); + + // Push up to three validation messages out to the user. + for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) { + if ($errors[$i] instanceof Exception) { + $app->enqueueMessage($errors[$i]->getMessage(), 'warning'); + } else { + $app->enqueueMessage($errors[$i], 'warning'); + } + } + + $this->setRedirect($link); + + return false; + } + + if ((Redshop::getConfig()->get('RATING_REVIEW_LOGIN_REQUIRED') && $model->checkRatedProduct( + $productId, + $user->id + )) + || (!Redshop::getConfig()->get('RATING_REVIEW_LOGIN_REQUIRED') && $model->checkRatedProduct( + $productId, + 0, + $data['email'] + ))) { + if ($modal) { + $link .= '&rate=1'; + } + + $app->enqueueMessage(JText::_('COM_REDSHOP_YOU_CAN_NOT_REVIEW_SAME_PRODUCT_AGAIN'), 'warning'); + $this->setRedirect($link); + + return false; + } + + $data['published'] = 0; + $data['favoured'] = 0; + $data['time'] = time(); + $data['product_id'] = $productId; + $data['Itemid'] = $Itemid; + + if ($model->sendMailForReview($data)) { + // Flush the data from the session + $app->setUserState('com_redshop.edit.product_rating.' . $productId . '.data', null); + + if (Redshop::getConfig()->get('RATING_MSG')) { + $msg = Redshop::getConfig()->get('RATING_MSG'); + } else { + $msg = JText::_('COM_REDSHOP_EMAIL_HAS_BEEN_SENT_SUCCESSFULLY'); + } + + $app->enqueueMessage($msg); + + if ($modal) { + $link .= '&rate=1'; + } + } else { + $app->enqueueMessage($model->getError(), 'warning'); + } + + $this->setRedirect($link); + } + + /** + * Method upload images + * + * @param array $files + * @param array $images + * + * @return void + * @since 2.1.4 + */ + public function uploadImage($files, &$images) + { + foreach ($files['images'] as $file) { + if ($file['error'] > 0 || $file['size'] > 2000000) { + continue; + } + + $fileName = $file['name']; + $uploadedFileNameParts = explode('.', $fileName); + $uploadedFileExtension = array_pop($uploadedFileNameParts); + + $validFileExts = explode(',', 'jpeg,jpg,png,gif'); + $extOk = false; + + foreach ($validFileExts as $key => $value) { + if (preg_match("/$value/i", $uploadedFileExtension)) { + $extOk = true; + } + } + + if ($extOk === false) { + continue; + } + + $fileTemp = $file['tmp_name']; + $imageinfo = getimagesize($fileTemp); + + $okMIMETypes = 'image/jpeg,image/pjpeg,image/png,image/x-png,image/gif'; + $validFileTypes = explode(",", $okMIMETypes); + + if (!is_int($imageinfo[0]) || !is_int($imageinfo[1]) || !in_array($imageinfo['mime'], $validFileTypes)) { + continue; + } + + $fileName = RedshopHelperMedia::cleanFileName($fileName); + $uploadPath = REDSHOP_FRONT_IMAGES_RELPATH . 'product_rating/' . $fileName; + + if (!JFile::upload($fileTemp, $uploadPath)) { + continue; + } + + $images[] = $fileName; + } + } } diff --git a/component/site/controllers/quotation.php b/component/site/controllers/quotation.php index cb3e7e102f5..f77c510f966 100644 --- a/component/site/controllers/quotation.php +++ b/component/site/controllers/quotation.php @@ -19,128 +19,133 @@ */ class RedshopControllerQuotation extends RedshopController { - /** - * add quotation function - * - * @access public - * @return void - */ - public function addquotation() - { - $app = JFactory::getApplication(); - $Itemid = $app->input->get('Itemid'); - $return = $app->input->get('return'); - $post = $app->input->post->getArray(); - - JPluginHelper::importPlugin('redshop_product'); - $dispatcher = RedshopHelperUtility::getDispatcher(); - - if (!$post['user_email']) - { - $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_VALID_EMAIL_ADDRESS'); - $this->setRedirect('index.php?tmpl=component&option=com_redshop&view=quotation&return=1&Itemid=' . $Itemid, $msg); - die(); - } - - /** @var RedshopModelQuotation $model */ - $model = $this->getModel('quotation'); - $session = JFactory::getSession(); - $cart = $session->get('cart'); - $cart['quotation_note'] = $post['quotation_note']; - - $dispatcher->trigger('onRedshopQuotationBeforeAdding', array(&$cart, &$post)); - - $row = $model->store($cart, $post); - - if ($row) - { - RedshopHelperExtrafields::extraFieldSave($post, RedshopHelperExtrafields::SECTION_QUOTATION, $row->quotation_id); - $dispatcher->trigger('onRedshopQuotationAfterAdded', array(&$cart, &$post, $row)); - - $sent = $model->sendQuotationMail($row->quotation_id); - - if ($sent) - { - $msg = JText::_('COM_REDSHOP_QUOTATION_DETAIL_SENT'); - } - else - { - $msg = JText::_('COM_REDSHOP_ERROR_SENDING_QUOTATION_MAIL'); - } - - $session = JFactory::getSession(); - \Redshop\Cart\Helper::setCart(null); - $session->set('ccdata', null); - $session->set('issplit', null); - $session->set('userfield', null); - unset ($_SESSION ['ccdata']); - - if ($return != "") - { - $link = JRoute::_('index.php?option=com_redshop&view=cart&Itemid=' . $Itemid . '"emsg=' . $msg, false); - - ?> - - close(); - } - - $this->setRedirect('index.php?option=com_redshop&view=cart&Itemid=' . $Itemid, $msg); - } - else - { - $msg = JText::_('COM_REDSHOP_ERROR_SAVING_QUOTATION_DETAIL'); - $this->setRedirect('index.php?tmpl=component&option=com_redshop&view=quotation&return=1&Itemid=' . $Itemid, $msg); - } - } - - /** - * user create function - * - * @access public - * @return void - */ - public function usercreate() - { - $input = JFactory::getApplication()->input; - $Itemid = $input->get('Itemid'); - $model = $this->getModel('quotation'); - $post = $input->post->getArray(); - - $model->usercreate($post); - - $msg = JText::_('COM_REDSHOP_QUOTATION_SENT_AND_USERNAME_PASSWORD_HAS_BEEN_MAILED'); - $this->setRedirect('index.php?tmpl=component&option=com_redshop&view=quotation&return=1&Itemid=' . $Itemid, $msg); - } - - /** - * cancel function - * - * @access public - * @return void - */ - public function cancel() - { - $app = JFactory::getApplication(); - $Itemid = $app->input->get('Itemid'); - $return = $app->input->get('return'); - - if ($return != "") - { - $link = JRoute::_('index.php?option=com_redshop&view=cart&Itemid=' . $Itemid, false); - - ?> - - close(); - } - else - { - $this->setRedirect('index.php?option=com_redshop&view=cart&Itemid=' . $Itemid); - } - } + /** + * add quotation function + * + * @access public + * @return void + */ + public function addquotation() + { + $app = JFactory::getApplication(); + $Itemid = $app->input->get('Itemid'); + $return = $app->input->get('return'); + $post = $app->input->post->getArray(); + + JPluginHelper::importPlugin('redshop_product'); + $dispatcher = RedshopHelperUtility::getDispatcher(); + + if (!$post['user_email']) { + $msg = JText::_('COM_REDSHOP_PLEASE_ENTER_VALID_EMAIL_ADDRESS'); + $this->setRedirect( + 'index.php?tmpl=component&option=com_redshop&view=quotation&return=1&Itemid=' . $Itemid, + $msg + ); + die(); + } + + /** @var RedshopModelQuotation $model */ + $model = $this->getModel('quotation'); + $session = JFactory::getSession(); + $cart = $session->get('cart'); + $cart['quotation_note'] = $post['quotation_note']; + + $dispatcher->trigger('onRedshopQuotationBeforeAdding', array(&$cart, &$post)); + + $row = $model->store($cart, $post); + + if ($row) { + RedshopHelperExtrafields::extraFieldSave( + $post, + RedshopHelperExtrafields::SECTION_QUOTATION, + $row->quotation_id + ); + $dispatcher->trigger('onRedshopQuotationAfterAdded', array(&$cart, &$post, $row)); + + $sent = $model->sendQuotationMail($row->quotation_id); + + if ($sent) { + $msg = JText::_('COM_REDSHOP_QUOTATION_DETAIL_SENT'); + } else { + $msg = JText::_('COM_REDSHOP_ERROR_SENDING_QUOTATION_MAIL'); + } + + $session = JFactory::getSession(); + \Redshop\Cart\Helper::setCart(null); + $session->set('ccdata', null); + $session->set('issplit', null); + $session->set('userfield', null); + unset ($_SESSION ['ccdata']); + + if ($return != "") { + $link = JRoute::_( + 'index.php?option=com_redshop&view=cart&Itemid=' . $Itemid . '"emsg=' . $msg, + false + ); + + ?> + + close(); + } + + $this->setRedirect('index.php?option=com_redshop&view=cart&Itemid=' . $Itemid, $msg); + } else { + $msg = JText::_('COM_REDSHOP_ERROR_SAVING_QUOTATION_DETAIL'); + $this->setRedirect( + 'index.php?tmpl=component&option=com_redshop&view=quotation&return=1&Itemid=' . $Itemid, + $msg + ); + } + } + + /** + * user create function + * + * @access public + * @return void + */ + public function usercreate() + { + $input = JFactory::getApplication()->input; + $Itemid = $input->get('Itemid'); + $model = $this->getModel('quotation'); + $post = $input->post->getArray(); + + $model->usercreate($post); + + $msg = JText::_('COM_REDSHOP_QUOTATION_SENT_AND_USERNAME_PASSWORD_HAS_BEEN_MAILED'); + $this->setRedirect( + 'index.php?tmpl=component&option=com_redshop&view=quotation&return=1&Itemid=' . $Itemid, + $msg + ); + } + + /** + * cancel function + * + * @access public + * @return void + */ + public function cancel() + { + $app = JFactory::getApplication(); + $Itemid = $app->input->get('Itemid'); + $return = $app->input->get('return'); + + if ($return != "") { + $link = JRoute::_('index.php?option=com_redshop&view=cart&Itemid=' . $Itemid, false); + + ?> + + close(); + } else { + $this->setRedirect('index.php?option=com_redshop&view=cart&Itemid=' . $Itemid); + } + } } diff --git a/component/site/controllers/quotation_detail.php b/component/site/controllers/quotation_detail.php index 40d8f982055..855708dca67 100644 --- a/component/site/controllers/quotation_detail.php +++ b/component/site/controllers/quotation_detail.php @@ -19,71 +19,75 @@ */ class RedshopControllerQuotation_detail extends RedshopController { - /** - * update status function - * - * @access public - * @return void - */ - public function updatestatus() - { - $post = $this->input->post->getArray(); - - $Itemid = $this->input->get('Itemid'); - $encr = $this->input->get('encr'); - $model = $this->getModel('quotation_detail'); - - // Update Status - RedshopHelperQuotation::updateQuotationStatus($post['quotation_id'], $post['quotation_status']); - - // Add Customer Note - $model->addQuotationCustomerNote($post); - - Redshop\Mail\Quotation::sendMail($post['quotation_id'], $post['quotation_status']); - - $msg = JText::_('COM_REDSHOP_QUOTATION_STATUS_UPDATED_SUCCESSFULLY'); - - $this->setRedirect('index.php?option=com_redshop&view=quotation_detail&quoid=' . $post['quotation_id'] . '&encr=' . $encr . '&Itemid=' . $Itemid, $msg); - } - - /** - * checkout function - * - * @access public - * @return void - * @throws Exception - */ - public function checkout() - { - $Itemid = $this->input->get('Itemid'); - $post = $this->input->post->getArray(); - $encr = $this->input->get('encr'); - - $model = $this->getModel('quotation_detail'); - $session = JFactory::getSession(); - - $cart = array(); - $cart['idx'] = 0; - \Redshop\Cart\Helper::setCart($cart); - - $quotationProducts = RedshopHelperQuotation::getQuotationProduct($post['quotation_id']); - - for ($q = 0, $qn = count($quotationProducts); $q < $qn; $q++) - { - $model->addtocart($quotationProducts[$q]); - } - - $cart = $session->get('cart'); - - $quotationDetail = RedshopHelperQuotation::getQuotationDetail($post['quotation_id']); - $cart['customer_note'] = $quotationDetail->quotation_note; - $cart['quotation_id'] = $quotationDetail->quotation_id; - $cart['cart_discount'] = $quotationDetail->quotation_discount; - $cart['quotation'] = 1; - \Redshop\Cart\Helper::setCart($cart); - - $model->modifyQuotation($quotationDetail->user_id); - $Itemid = RedshopHelperRouter::getCheckoutItemId(); - $this->setRedirect('index.php?option=com_redshop&view=checkout"ation=1&encr=' . $encr . '&Itemid=' . $Itemid); - } + /** + * update status function + * + * @access public + * @return void + */ + public function updatestatus() + { + $post = $this->input->post->getArray(); + + $Itemid = $this->input->get('Itemid'); + $encr = $this->input->get('encr'); + $model = $this->getModel('quotation_detail'); + + // Update Status + RedshopHelperQuotation::updateQuotationStatus($post['quotation_id'], $post['quotation_status']); + + // Add Customer Note + $model->addQuotationCustomerNote($post); + + Redshop\Mail\Quotation::sendMail($post['quotation_id'], $post['quotation_status']); + + $msg = JText::_('COM_REDSHOP_QUOTATION_STATUS_UPDATED_SUCCESSFULLY'); + + $this->setRedirect( + 'index.php?option=com_redshop&view=quotation_detail&quoid=' . $post['quotation_id'] . '&encr=' . $encr . '&Itemid=' . $Itemid, + $msg + ); + } + + /** + * checkout function + * + * @access public + * @return void + * @throws Exception + */ + public function checkout() + { + $Itemid = $this->input->get('Itemid'); + $post = $this->input->post->getArray(); + $encr = $this->input->get('encr'); + + $model = $this->getModel('quotation_detail'); + $session = JFactory::getSession(); + + $cart = array(); + $cart['idx'] = 0; + \Redshop\Cart\Helper::setCart($cart); + + $quotationProducts = RedshopHelperQuotation::getQuotationProduct($post['quotation_id']); + + for ($q = 0, $qn = count($quotationProducts); $q < $qn; $q++) { + $model->addtocart($quotationProducts[$q]); + } + + $cart = $session->get('cart'); + + $quotationDetail = RedshopHelperQuotation::getQuotationDetail($post['quotation_id']); + $cart['customer_note'] = $quotationDetail->quotation_note; + $cart['quotation_id'] = $quotationDetail->quotation_id; + $cart['cart_discount'] = $quotationDetail->quotation_discount; + $cart['quotation'] = 1; + \Redshop\Cart\Helper::setCart($cart); + + $model->modifyQuotation($quotationDetail->user_id); + $Itemid = RedshopHelperRouter::getCheckoutItemId(); + $this->setRedirect( + 'index.php?option=com_redshop&view=checkout"ation=1&encr=' . $encr . '&Itemid=' . $Itemid + ); + } } diff --git a/component/site/controllers/registration.php b/component/site/controllers/registration.php index 5811579a649..3367775a07d 100644 --- a/component/site/controllers/registration.php +++ b/component/site/controllers/registration.php @@ -18,251 +18,227 @@ */ class RedshopControllerRegistration extends RedshopController { - /** - * New registration function - * - * @access public - * @return void - */ - public function newRegistration() - { - $input = JFactory::getApplication()->input; - $post = $input->post->getArray(); - $itemId = $input->getInt('Itemid', 0); - $dispatcher = RedshopHelperUtility::getDispatcher(); - - /** @var RedshopModelRegistration $model */ - $model = $this->getModel('registration'); - $success = $model->store($post); - - if ($success) - { - $message = JText::sprintf('COM_REDSHOP_ALERT_REGISTRATION_SUCCESSFULLY', $post['username']); - JPluginHelper::importPlugin('redshop_alert'); - $dispatcher->trigger('storeAlert', array($message)); - - if ($post['mywishlist'] == 1) - { - $this->setRedirect(JRoute::_('index.php?loginwishlist=1&option=com_redshop&view=wishlist&Itemid=' . $itemId, false)); - } - else - { - $msg = Redshop::getConfig()->get('WELCOME_MSG'); - - if (Redshop::getConfig()->get('SHOP_NAME') != "") - { - $msg = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $msg); - } - - // Redirection settings - $link = JRoute::_('index.php?option=com_redshop&view=redshop&Itemid=' . $itemId); - - $menu = JFactory::getApplication()->getMenu(); - $retMenuItem = $menu->getItem($menu->getParams($itemId)->get('registrationredirect')); - - if (!empty($retMenuItem)) - { - $link = JRoute::_($retMenuItem->link . '&Itemid=' . $retMenuItem->id, false); - } - - // Redirection settings End - $this->setRedirect($link, $msg); - } - } - else - { - $this->display(); - } - } - - /** - * Method for search user detail by phone - * - * @return void - */ - public function searchUserdetailByPhone() - { - ob_clean(); - $app = JFactory::getApplication(); - $get = $app->input->get->getArray(); - $return = ""; - - JPluginHelper::importPlugin('telesearch'); - - $telephone = array('phone' => $get['phone']); - $accountHandle = RedshopHelperUtility::getDispatcher()->trigger('onSearchUserDetails', array($telephone)); - - if (count($accountHandle) > 0) - { - $response = $accountHandle[0]; - - if (count($response) > 0) - { - $return = implode("`_`", $response); - } - } - - echo $return; - - $app->close(); - } - - /** - * getCompanyOrCustomer - * - * @return void - * @throws Exception - */ - public function getCompanyOrCustomer() - { - $app = JFactory::getApplication(); - $get = $app->input->get->getArray(); - $templateId = $get['template_id']; - $isCompany = $get['is_company']; - $lists = array('isAjax' => 1); - - if ($isCompany == 1) - { - $lists['extra_field_company'] = Redshop\Fields\SiteHelper::renderFields(8); - $template = RedshopHelperTemplate::getTemplate("company_billing_template", $templateId); - - if (count($template) > 0 && $template[0]->template_desc != "") - { - $templateHtml = $template[0]->template_desc; - } - else - { - $templateHtml = '
    {email_lbl}:{email}*
    {retype_email_lbl}{retype_email}*
    {company_name_lbl}{company_name}*
    {vat_number_lbl}{vat_number}*
    {firstname_lbl}{firstname}*
    {lastname_lbl}{lastname}*
    {address_lbl}{address}*
    {zipcode_lbl}{zipcode}*
    {city_lbl}{city}*
    {country_lbl}{country}*
    {state_lbl}{state}*
    {phone_lbl}{phone}*
    {ean_number_lbl}{ean_number}
    {tax_exempt_lbl}{tax_exempt}
    {company_extrafield}
    '; - } - - $templateHtml = RedshopTagsReplacer::_( - 'companybillingtemplate', - $templateHtml, - array( - 'data' => $get, - 'lists' => $lists - ) - ); - } - else - { - $lists['extra_field_user'] = Redshop\Fields\SiteHelper::renderFields(7); - $template = RedshopHelperTemplate::getTemplate("private_billing_template", $templateId); - - if (count($template) > 0 && $template[0]->template_desc != "") - { - $templateHtml = $template[0]->template_desc; - } - else - { - $templateHtml = '
    {email_lbl}:{email}*
    {retype_email_lbl}{retype_email}*
    {firstname_lbl}{firstname}*
    {lastname_lbl}{lastname}*
    {address_lbl}{address}*
    {zipcode_lbl}{zipcode}*
    {city_lbl}{city}*
    {country_lbl}{country}*
    {state_lbl}{state}*
    {phone_lbl}{phone}*
    {private_extrafield}
    '; - } - - $templateHtml = RedshopTagsReplacer::_( - 'privatebillingtemplate', - $templateHtml, - array( - 'data' => $get, - 'lists' => $lists, - ) - ); - } - - echo $return = '
    ' . $templateHtml . '
    '; - - $app->close(); - } - - /** - * Get Billing One Step checkout template - * - * @return void - * @throws Exception - */ - public function getBillingTemplate() - { - $app = JFactory::getApplication(); - $input = $app->input; - $isCompany = $input->post->getInt('isCompany'); - $type = $input->post->getString('type'); - $lists = array(); - $html = ""; - - if ($isCompany == 1 && $type == 'company') - { - $lists['extra_field_company'] = Redshop\Fields\SiteHelper::renderFields(RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS); - - $template = RedshopHelperTemplate::getTemplate("company_billing_template"); - - if (count($template) > 0 && $template[0]->template_desc != "") - { - $html = $template[0]->template_desc; - } - else - { - $html = RedshopHelperTemplate::getDefaultTemplateContent('company_billing_template'); - } - - $html = RedshopTagsReplacer::_( - 'companybillingtemplate', - $html, - array( - 'data' => array(), - 'lists' => $lists - ) - ); - } - elseif ($isCompany == 0 && $type == 'private') - { - $lists['extra_field_user'] = Redshop\Fields\SiteHelper::renderFields(RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS); - - $template = RedshopHelperTemplate::getTemplate("private_billing_template"); - - if (count($template) > 0 && $template[0]->template_desc != "") - { - $html = $template[0]->template_desc; - } - else - { - $html = RedshopHelperTemplate::getDefaultTemplateContent('private_billing_template'); - } - - $html = RedshopTagsReplacer::_( - 'privatebillingtemplate', - $html, - array( - 'data' => array(), - 'lists' => $lists - ) - ); - } - - JPluginHelper::importPlugin('redshop_checkout'); - RedshopHelperUtility::getDispatcher()->trigger('onRenderBillingOneStepCheckout', array(&$html)); - - echo $html; - - $app->close(); - } - - public function ajaxValidateNewJoomlaUser() - { - $app = JFactory::getApplication(); - $return = true; - - $username = $app->input->getString('username', ''); - - if (!empty($username)) - { - if (!empty(RedshopHelperUser::validateUser($username))) - { - $return = false; - } - } - - ob_clean(); - echo json_encode($return); - - $app->close(); - } + /** + * New registration function + * + * @access public + * @return void + */ + public function newRegistration() + { + $input = JFactory::getApplication()->input; + $post = $input->post->getArray(); + $itemId = $input->getInt('Itemid', 0); + $dispatcher = RedshopHelperUtility::getDispatcher(); + + /** @var RedshopModelRegistration $model */ + $model = $this->getModel('registration'); + $success = $model->store($post); + + if ($success) { + $message = JText::sprintf('COM_REDSHOP_ALERT_REGISTRATION_SUCCESSFULLY', $post['username']); + JPluginHelper::importPlugin('redshop_alert'); + $dispatcher->trigger('storeAlert', array($message)); + + if ($post['mywishlist'] == 1) { + $this->setRedirect( + JRoute::_('index.php?loginwishlist=1&option=com_redshop&view=wishlist&Itemid=' . $itemId, false) + ); + } else { + $msg = Redshop::getConfig()->get('WELCOME_MSG'); + + if (Redshop::getConfig()->get('SHOP_NAME') != "") { + $msg = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $msg); + } + + // Redirection settings + $link = JRoute::_('index.php?option=com_redshop&view=redshop&Itemid=' . $itemId); + + $menu = JFactory::getApplication()->getMenu(); + $retMenuItem = $menu->getItem($menu->getParams($itemId)->get('registrationredirect')); + + if (!empty($retMenuItem)) { + $link = JRoute::_($retMenuItem->link . '&Itemid=' . $retMenuItem->id, false); + } + + // Redirection settings End + $this->setRedirect($link, $msg); + } + } else { + $this->display(); + } + } + + /** + * Method for search user detail by phone + * + * @return void + */ + public function searchUserdetailByPhone() + { + ob_clean(); + $app = JFactory::getApplication(); + $get = $app->input->get->getArray(); + $return = ""; + + JPluginHelper::importPlugin('telesearch'); + + $telephone = array('phone' => $get['phone']); + $accountHandle = RedshopHelperUtility::getDispatcher()->trigger('onSearchUserDetails', array($telephone)); + + if (count($accountHandle) > 0) { + $response = $accountHandle[0]; + + if (count($response) > 0) { + $return = implode("`_`", $response); + } + } + + echo $return; + + $app->close(); + } + + /** + * getCompanyOrCustomer + * + * @return void + * @throws Exception + */ + public function getCompanyOrCustomer() + { + $app = JFactory::getApplication(); + $get = $app->input->get->getArray(); + $templateId = $get['template_id']; + $isCompany = $get['is_company']; + $lists = array('isAjax' => 1); + + if ($isCompany == 1) { + $lists['extra_field_company'] = Redshop\Fields\SiteHelper::renderFields(8); + $template = RedshopHelperTemplate::getTemplate("company_billing_template", $templateId); + + if (count($template) > 0 && $template[0]->template_desc != "") { + $templateHtml = $template[0]->template_desc; + } else { + $templateHtml = '
    {email_lbl}:{email}*
    {retype_email_lbl}{retype_email}*
    {company_name_lbl}{company_name}*
    {vat_number_lbl}{vat_number}*
    {firstname_lbl}{firstname}*
    {lastname_lbl}{lastname}*
    {address_lbl}{address}*
    {zipcode_lbl}{zipcode}*
    {city_lbl}{city}*
    {country_lbl}{country}*
    {state_lbl}{state}*
    {phone_lbl}{phone}*
    {ean_number_lbl}{ean_number}
    {tax_exempt_lbl}{tax_exempt}
    {company_extrafield}
    '; + } + + $templateHtml = RedshopTagsReplacer::_( + 'companybillingtemplate', + $templateHtml, + array( + 'data' => $get, + 'lists' => $lists + ) + ); + } else { + $lists['extra_field_user'] = Redshop\Fields\SiteHelper::renderFields(7); + $template = RedshopHelperTemplate::getTemplate("private_billing_template", $templateId); + + if (count($template) > 0 && $template[0]->template_desc != "") { + $templateHtml = $template[0]->template_desc; + } else { + $templateHtml = '
    {email_lbl}:{email}*
    {retype_email_lbl}{retype_email}*
    {firstname_lbl}{firstname}*
    {lastname_lbl}{lastname}*
    {address_lbl}{address}*
    {zipcode_lbl}{zipcode}*
    {city_lbl}{city}*
    {country_lbl}{country}*
    {state_lbl}{state}*
    {phone_lbl}{phone}*
    {private_extrafield}
    '; + } + + $templateHtml = RedshopTagsReplacer::_( + 'privatebillingtemplate', + $templateHtml, + array( + 'data' => $get, + 'lists' => $lists, + ) + ); + } + + echo $return = '
    ' . $templateHtml . '
    '; + + $app->close(); + } + + /** + * Get Billing One Step checkout template + * + * @return void + * @throws Exception + */ + public function getBillingTemplate() + { + $app = JFactory::getApplication(); + $input = $app->input; + $isCompany = $input->post->getInt('isCompany'); + $type = $input->post->getString('type'); + $lists = array(); + $html = ""; + + if ($isCompany == 1 && $type == 'company') { + $lists['extra_field_company'] = Redshop\Fields\SiteHelper::renderFields( + RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS + ); + + $template = RedshopHelperTemplate::getTemplate("company_billing_template"); + + if (count($template) > 0 && $template[0]->template_desc != "") { + $html = $template[0]->template_desc; + } else { + $html = RedshopHelperTemplate::getDefaultTemplateContent('company_billing_template'); + } + + $html = RedshopTagsReplacer::_( + 'companybillingtemplate', + $html, + array( + 'data' => array(), + 'lists' => $lists + ) + ); + } elseif ($isCompany == 0 && $type == 'private') { + $lists['extra_field_user'] = Redshop\Fields\SiteHelper::renderFields( + RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS + ); + + $template = RedshopHelperTemplate::getTemplate("private_billing_template"); + + if (count($template) > 0 && $template[0]->template_desc != "") { + $html = $template[0]->template_desc; + } else { + $html = RedshopHelperTemplate::getDefaultTemplateContent('private_billing_template'); + } + + $html = RedshopTagsReplacer::_( + 'privatebillingtemplate', + $html, + array( + 'data' => array(), + 'lists' => $lists + ) + ); + } + + JPluginHelper::importPlugin('redshop_checkout'); + RedshopHelperUtility::getDispatcher()->trigger('onRenderBillingOneStepCheckout', array(&$html)); + + echo $html; + + $app->close(); + } + + public function ajaxValidateNewJoomlaUser() + { + $app = JFactory::getApplication(); + $return = true; + + $username = $app->input->getString('username', ''); + + if (!empty($username)) { + if (!empty(RedshopHelperUser::validateUser($username))) { + $return = false; + } + } + + ob_clean(); + echo json_encode($return); + + $app->close(); + } } diff --git a/component/site/controllers/search.php b/component/site/controllers/search.php index 6f491280ccd..72776a76618 100644 --- a/component/site/controllers/search.php +++ b/component/site/controllers/search.php @@ -21,289 +21,275 @@ */ class RedshopControllerSearch extends RedshopController { - /** - * cancel function - * - * @access public - * @return void - */ - public function cancel() - { - $this->setRedirect('index.php'); - } - - /** - * loadProducts function - * - * @return - * - * @access public - */ - public function loadProducts() - { - $app = JFactory::getApplication(); - $get = $app->input->get->getArray(); - $taskId = $get['taskid']; - - /** @var RedshopModelSearch $model */ - $model = $this->getModel('search'); - - $brands = $model->loadCatProductsManufacturer($taskId); - - // Manufacturer Select Id - $manufacturer = $app->input->getInt('manufacture_id', 0); - - JLoader::import('joomla.application.module.helper'); - - $module = JModuleHelper::getModule('redshop_search'); - $params = new Registry($module->params); - $javaFun = $params->get('enableAjaxsearch') ? 'makeUrl();' : ''; - - if (count($brands) > 0) - { - $manufacturerOptions = array(); - $manufacturerOptions[] = JHtml::_('select.option', '0', JText::_('COM_REDSHOP_SELECT_MANUFACTURE')); - $manufacturerOptions = @array_merge($manufacturerOptions, $brands); - - echo JText::_('COM_REDSHOP_SELECT_MANUFACTURE') . '
    ' - . JHtml::_( - 'select.genericlist', - $manufacturerOptions, - 'manufacture_id', 'class="inputbox span12" size="1" onChange="' . $javaFun . '" ', - 'value', - 'text', - $manufacturer - ); - } - - $app->close(); - } - - /** - * ajaxsearch function - * - * @access public - * - * @return void - */ - public function ajaxsearch() - { - /** @var RedshopModelSearch $model */ - $model = $this->getModel('Search'); - $detail = $model->getajaxData(); - - $encoded = json_encode($detail); - ob_clean(); - echo "{\"results\": " . $encoded . "}"; - - JFactory::getApplication()->close(); - } - - /** - * AJAX Task to get states list - * - * @return void - */ - public function getStatesAjax() - { - // Only verify token for frontend - \Redshop\Helper\Ajax::validateAjaxRequest('get'); - - $app = JFactory::getApplication(); - - ob_clean(); - - echo RedshopHelperWorld::getStatesAjax($app->input->getCmd('country')); - - $app->close(); - } - - /** - * AJAX Task to filter products - * - * @return void - */ - public function findProducts() - { - $app = JFactory::getApplication(); - $input = $app->input; - - /** @var RedshopModelSearch $model */ - $model = $this->getModel('Search'); - $post = $input->post->getArray(); - $data = $post['redform']; - - $model->setState('filter.data', $post); - $list = $model->getItem(); - $pagination = $model->getFilterPagination(); - $total = $model->getFilterTotal(); - $url = JRoute::_( - 'index.php?option=' . $post['option'] - . '&view=' . $post['view'] - . '&layout=' . $post['layout'] - . '&cid=' . $data['cid'] - . '&manufacturer_id=' . $data['mid'] - . '&Itemid=' . $post['Itemid'] - . '&categories=' . (isset($data['category']) ? implode(',', $data['category']) : '') - . '&manufacturers=' . (isset($data['manufacturer']) ? implode(',', $data['manufacturer']) : '') - . '&filterprice[min]=' . (isset($data['filterprice']) ? $data['filterprice']['min'] : '') - . '&filterprice[max]=' . (isset($data['filterprice']) ? $data['filterprice']['max'] : '') - . '&template_id=' . $data['template_id'] - . '&keyword=' . $data['keyword'] - . '&order_by=' . $post['order_by'] - . '&limit=' . $post['limit'] - . '&limitstart=' . $post['limitstart'] - ); - - if (!empty($data['custom_field'])) - { - foreach ($data['custom_field'] as $fieldId => $fieldValues) - { - $url .= '&custom_field[' . $fieldId . ']=' . implode(',', $fieldValues); - } - } - - // Get layout HTML - if (empty($list)) - { - echo JText::_('COM_REDSHOP_MSG_SORRY_NO_RESULT_FOUND'); - $app->close(); - } - - echo RedshopLayoutHelper::render( - 'filter.result', - array( - 'products' => $list, - 'model' => $model, - 'post' => $data, - 'pagination' => $pagination, - 'orderBy' => $post['order_by'], - 'total' => $total, - 'templateId' => $data['template_id'], - 'url' => $url, - 'keyword' => $data['keyword'] - ), - '', - array( - 'component' => 'com_redshop' - ) - ); - - $app->close(); - } - - /** - * AJAX Task to restricted data - * - * @return void - */ - public function restrictedData() - { - JLoader::register('ModRedshopFilter', JPATH_SITE . '/modules/mod_redshop_filter/helper.php'); - - $app = JFactory::getApplication(); - $input = $app->input; - $params = new Registry($input->post->getString('params', '')); - $pids = explode(',', $input->post->getString('pids', '')); - $form = urldecode(stripslashes($input->post->get('form', '', 'RAW'))); - parse_str($form, $formData); - - $cid = $formData['redform']['cid']; - $mid = $formData['redform']['mid']; - $rootCategory = $params->get('root_category', 0); - $productFields = $params->get('product_fields', array()); - $manufacturers = array(); - $categories = array(); - $productList = array(); - - if (!empty($cid)) - { - $productList = \Redshop\Product\Product::getProductsByIds($pids); - $manuList = array(); - $catList = array(); - - foreach ($productList as $k => $value) - { - $tmpCategories = is_array($value->categories) ? $value->categories : explode(',', $value->categories); - $catList = array_merge($catList, $tmpCategories); - - if ($value->manufacturer_id && $value->manufacturer_id != $mid) - { - $manuList[] = $value->manufacturer_id; - } - } - - $catList = array_unique($catList); - $manufacturers = ModRedshopFilter::getManufacturers(array_unique($manuList)); - $categories = ModRedshopFilter::getCategories($catList, $rootCategory, $cid); - $rangePrice = ModRedshopFilter::getRange($pids); - } - elseif (!empty($mid)) - { - $productList = \Redshop\Product\Product::getProductsByIds($pids); - $manuList = array(); - $catList = array(); - - foreach ($productList as $k => $value) - { - $tmpCategories = is_array($value->categories) ? $value->categories : explode(',', $value->categories); - $catList = array_merge($catList, $tmpCategories); - - if ($value->manufacturer_id && $value->manufacturer_id != $mid) - { - $manuList[] = $value->manufacturer_id; - } - } - - $manufacturers = array(); - $pids = ModRedshopFilter::getProductByManufacturer($mid); - $categories = ModRedshopFilter::getCategorybyPids($pids, $rootCategory); - $rangePrice = ModRedshopFilter::getRange($pids); - } - elseif ($formData['view'] == 'search') - { - $productList = \Redshop\Product\Product::getProductsByIds($pids); - $manuList = array(); - $catList = array(); - - foreach ($productList as $k => $value) - { - $tmpCategories = is_array($value->categories) ? $value->categories : explode(',', $value->categories); - $catList = array_merge($catList, $tmpCategories); - - if ($value->manufacturer_id && $value->manufacturer_id != $mid) - { - $manuList[] = $value->manufacturer_id; - } - } - - $manufacturers = ModRedshopFilter::getManufacturers(array_unique($manuList)); - $categories = ModRedshopFilter::getSearchCategories(array_unique($catList)); - $rangePrice = ModRedshopFilter::getRange($pids); - } - - $customFields = ModRedshopFilter::getCustomFields($pids, $productFields); - $rangeMin = $formData['redform']['filterprice']['min'] ? $formData['redform']['filterprice']['min'] : $rangePrice['min']; - $rangeMax = $formData['redform']['filterprice']['max'] ? $formData['redform']['filterprice']['max'] : $rangePrice['max']; - - echo RedshopLayoutHelper::render( - 'filter.restricted', - array( - "params" => $params->toObject(), - "manufacturers" => $manufacturers, - "categories" => $categories, - "rangeMin" => $rangeMin, - "rangeMax" => $rangeMax, - "customFields" => $customFields, - 'formData' => $formData, - "productList" => $productList - ), - '', - array( - 'component' => 'com_redshop' - ) - ); - - $app->close(); - } + /** + * cancel function + * + * @access public + * @return void + */ + public function cancel() + { + $this->setRedirect('index.php'); + } + + /** + * loadProducts function + * + * @return + * + * @access public + */ + public function loadProducts() + { + $app = JFactory::getApplication(); + $get = $app->input->get->getArray(); + $taskId = $get['taskid']; + + /** @var RedshopModelSearch $model */ + $model = $this->getModel('search'); + + $brands = $model->loadCatProductsManufacturer($taskId); + + // Manufacturer Select Id + $manufacturer = $app->input->getInt('manufacture_id', 0); + + JLoader::import('joomla.application.module.helper'); + + $module = JModuleHelper::getModule('redshop_search'); + $params = new Registry($module->params); + $javaFun = $params->get('enableAjaxsearch') ? 'makeUrl();' : ''; + + if (count($brands) > 0) { + $manufacturerOptions = array(); + $manufacturerOptions[] = JHtml::_('select.option', '0', JText::_('COM_REDSHOP_SELECT_MANUFACTURE')); + $manufacturerOptions = @array_merge($manufacturerOptions, $brands); + + echo JText::_('COM_REDSHOP_SELECT_MANUFACTURE') . '
    ' + . JHtml::_( + 'select.genericlist', + $manufacturerOptions, + 'manufacture_id', + 'class="inputbox span12" size="1" onChange="' . $javaFun . '" ', + 'value', + 'text', + $manufacturer + ); + } + + $app->close(); + } + + /** + * ajaxsearch function + * + * @access public + * + * @return void + */ + public function ajaxsearch() + { + /** @var RedshopModelSearch $model */ + $model = $this->getModel('Search'); + $detail = $model->getajaxData(); + + $encoded = json_encode($detail); + ob_clean(); + echo "{\"results\": " . $encoded . "}"; + + JFactory::getApplication()->close(); + } + + /** + * AJAX Task to get states list + * + * @return void + */ + public function getStatesAjax() + { + // Only verify token for frontend + \Redshop\Helper\Ajax::validateAjaxRequest('get'); + + $app = JFactory::getApplication(); + + ob_clean(); + + echo RedshopHelperWorld::getStatesAjax($app->input->getCmd('country')); + + $app->close(); + } + + /** + * AJAX Task to filter products + * + * @return void + */ + public function findProducts() + { + $app = JFactory::getApplication(); + $input = $app->input; + + /** @var RedshopModelSearch $model */ + $model = $this->getModel('Search'); + $post = $input->post->getArray(); + $data = $post['redform']; + + $model->setState('filter.data', $post); + $list = $model->getItem(); + $pagination = $model->getFilterPagination(); + $total = $model->getFilterTotal(); + $url = JRoute::_( + 'index.php?option=' . $post['option'] + . '&view=' . $post['view'] + . '&layout=' . $post['layout'] + . '&cid=' . $data['cid'] + . '&manufacturer_id=' . $data['mid'] + . '&Itemid=' . $post['Itemid'] + . '&categories=' . (isset($data['category']) ? implode(',', $data['category']) : '') + . '&manufacturers=' . (isset($data['manufacturer']) ? implode(',', $data['manufacturer']) : '') + . '&filterprice[min]=' . (isset($data['filterprice']) ? $data['filterprice']['min'] : '') + . '&filterprice[max]=' . (isset($data['filterprice']) ? $data['filterprice']['max'] : '') + . '&template_id=' . $data['template_id'] + . '&keyword=' . $data['keyword'] + . '&order_by=' . $post['order_by'] + . '&limit=' . $post['limit'] + . '&limitstart=' . $post['limitstart'] + ); + + if (!empty($data['custom_field'])) { + foreach ($data['custom_field'] as $fieldId => $fieldValues) { + $url .= '&custom_field[' . $fieldId . ']=' . implode(',', $fieldValues); + } + } + + // Get layout HTML + if (empty($list)) { + echo JText::_('COM_REDSHOP_MSG_SORRY_NO_RESULT_FOUND'); + $app->close(); + } + + echo RedshopLayoutHelper::render( + 'filter.result', + array( + 'products' => $list, + 'model' => $model, + 'post' => $data, + 'pagination' => $pagination, + 'orderBy' => $post['order_by'], + 'total' => $total, + 'templateId' => $data['template_id'], + 'url' => $url, + 'keyword' => $data['keyword'] + ), + '', + array( + 'component' => 'com_redshop' + ) + ); + + $app->close(); + } + + /** + * AJAX Task to restricted data + * + * @return void + */ + public function restrictedData() + { + JLoader::register('ModRedshopFilter', JPATH_SITE . '/modules/mod_redshop_filter/helper.php'); + + $app = JFactory::getApplication(); + $input = $app->input; + $params = new Registry($input->post->getString('params', '')); + $pids = explode(',', $input->post->getString('pids', '')); + $form = urldecode(stripslashes($input->post->get('form', '', 'RAW'))); + parse_str($form, $formData); + + $cid = $formData['redform']['cid']; + $mid = $formData['redform']['mid']; + $rootCategory = $params->get('root_category', 0); + $productFields = $params->get('product_fields', array()); + $manufacturers = array(); + $categories = array(); + $productList = array(); + + if (!empty($cid)) { + $productList = \Redshop\Product\Product::getProductsByIds($pids); + $manuList = array(); + $catList = array(); + + foreach ($productList as $k => $value) { + $tmpCategories = is_array($value->categories) ? $value->categories : explode(',', $value->categories); + $catList = array_merge($catList, $tmpCategories); + + if ($value->manufacturer_id && $value->manufacturer_id != $mid) { + $manuList[] = $value->manufacturer_id; + } + } + + $catList = array_unique($catList); + $manufacturers = ModRedshopFilter::getManufacturers(array_unique($manuList)); + $categories = ModRedshopFilter::getCategories($catList, $rootCategory, $cid); + $rangePrice = ModRedshopFilter::getRange($pids); + } elseif (!empty($mid)) { + $productList = \Redshop\Product\Product::getProductsByIds($pids); + $manuList = array(); + $catList = array(); + + foreach ($productList as $k => $value) { + $tmpCategories = is_array($value->categories) ? $value->categories : explode(',', $value->categories); + $catList = array_merge($catList, $tmpCategories); + + if ($value->manufacturer_id && $value->manufacturer_id != $mid) { + $manuList[] = $value->manufacturer_id; + } + } + + $manufacturers = array(); + $pids = ModRedshopFilter::getProductByManufacturer($mid); + $categories = ModRedshopFilter::getCategorybyPids($pids, $rootCategory); + $rangePrice = ModRedshopFilter::getRange($pids); + } elseif ($formData['view'] == 'search') { + $productList = \Redshop\Product\Product::getProductsByIds($pids); + $manuList = array(); + $catList = array(); + + foreach ($productList as $k => $value) { + $tmpCategories = is_array($value->categories) ? $value->categories : explode(',', $value->categories); + $catList = array_merge($catList, $tmpCategories); + + if ($value->manufacturer_id && $value->manufacturer_id != $mid) { + $manuList[] = $value->manufacturer_id; + } + } + + $manufacturers = ModRedshopFilter::getManufacturers(array_unique($manuList)); + $categories = ModRedshopFilter::getSearchCategories(array_unique($catList)); + $rangePrice = ModRedshopFilter::getRange($pids); + } + + $customFields = ModRedshopFilter::getCustomFields($pids, $productFields); + $rangeMin = $formData['redform']['filterprice']['min'] ? $formData['redform']['filterprice']['min'] : $rangePrice['min']; + $rangeMax = $formData['redform']['filterprice']['max'] ? $formData['redform']['filterprice']['max'] : $rangePrice['max']; + + echo RedshopLayoutHelper::render( + 'filter.restricted', + array( + "params" => $params->toObject(), + "manufacturers" => $manufacturers, + "categories" => $categories, + "rangeMin" => $rangeMin, + "rangeMax" => $rangeMax, + "customFields" => $customFields, + 'formData' => $formData, + "productList" => $productList + ), + '', + array( + 'component' => 'com_redshop' + ) + ); + + $app->close(); + } } diff --git a/component/site/controllers/send_friend.php b/component/site/controllers/send_friend.php index 4f29ea90ee5..955da71dfbf 100644 --- a/component/site/controllers/send_friend.php +++ b/component/site/controllers/send_friend.php @@ -18,27 +18,27 @@ */ class RedshopControllerSend_Friend extends RedshopController { - /** - * Method for send mail - * - * @return void - * @throws Exception - * - * @since 1.0.0 - */ - public function sendmail() - { - $input = JFactory::getApplication()->input; - $yourName = $input->getString('your_name', ''); - $friendName = $input->getString('friends_name', ''); - $friendEmail = $input->getString('friends_email', ''); - $productId = $input->getInt('pid', 0); + /** + * Method for send mail + * + * @return void + * @throws Exception + * + * @since 1.0.0 + */ + public function sendmail() + { + $input = JFactory::getApplication()->input; + $yourName = $input->getString('your_name', ''); + $friendName = $input->getString('friends_name', ''); + $friendEmail = $input->getString('friends_email', ''); + $productId = $input->getInt('pid', 0); - /** @var RedshopModelSend_Friend $model */ - $model = $this->getModel('send_friend'); + /** @var RedshopModelSend_Friend $model */ + $model = $this->getModel('send_friend'); - $model->sendProductMailToFriend($yourName, $friendName, $productId, $friendEmail); + $model->sendProductMailToFriend($yourName, $friendName, $productId, $friendEmail); - JFactory::getApplication()->close(); - } + JFactory::getApplication()->close(); + } } diff --git a/component/site/controllers/wishlist.php b/component/site/controllers/wishlist.php index 1d8ac8e11e9..f138f4a9fbe 100644 --- a/component/site/controllers/wishlist.php +++ b/component/site/controllers/wishlist.php @@ -18,151 +18,145 @@ */ class RedshopControllerWishlist extends RedshopController { - /** - * createsave wishlist function - * - * @access public - * @return void - */ - public function createsave() - { - $user = JFactory::getUser(); - - /** @var RedshopModelWishlist $model */ - $model = $this->getModel("wishlist"); - $input = JFactory::getApplication()->input; - - $post = array(); - $post['wishlist_name'] = $input->post->getString('txtWishlistname', ''); - $post['user_id'] = $user->id; - $post['cdate'] = time(); - $post['product_id'] = $input->post->getInt('product_id', 0); - - if ($model->store($post)) - { - echo "
    " . JText::_('COM_REDSHOP_PRODUCT_SAVED_IN_WISHLIST_SUCCESSFULLY') . "
    "; - } - else - { - echo "
    " . JText::_('COM_REDSHOP_PRODUCT_NOT_SAVED_IN_WISHLIST') . "
    "; - } - - if ($input->getInt('loginwishlist', 0) == 1) - { - $return = JRoute::_('index.php?option=com_redshop&view=wishlist&task=viewwishlist&Itemid=' . $this->input->post->getInt('Itemid'), false); - $this->setRedirect($return); - } - else - { - ?> - - getModel("wishlist"); - - $data = JFactory::getApplication()->input->post->getArray(); - - if ($model->savewishlist($data)) - { - echo "
    " . JText::_('COM_REDSHOP_PRODUCT_SAVED_IN_WISHLIST_SUCCESSFULLY') . "
    "; - } - else - { - echo "
    " . JText::_('COM_REDSHOP_PRODUCT_NOT_SAVED_IN_WISHLIST') . "
    "; - } - - ?> - - getModel("wishlist"); - $Itemid = $app->input->get('Itemid'); - $post = $app->input->getArray(); - $link = JRoute::_("index.php?option=com_redshop&view=wishlist&task=viewwishlist&Itemid=" . $Itemid, false); - - if ($model->check_user_wishlist_authority($user->id, $post["wishlist_id"])) - { - if ($model->delwishlist($user->id, $post["wishlist_id"])) - { - $msg = JText::_('COM_REDSHOP_WISHLIST_DELETED_SUCCESSFULLY'); - } - else - { - $msg = JText::_('COM_REDSHOP_ERROR_IN_DELETING_WISHLIST'); - } - } - else - { - $msg = JText::_('COM_REDSHOP_YOU_ARE_NOT_AUTHORIZE_TO_DELETE'); - } - - $app->redirect($link, $msg); - } - - /** - * My sess del wish list - * - * @return void - */ - public function mysessdelwishlist() - { - $input = JFactory::getApplication()->input; - $post = array(); - $mydel = $input->get('mydel'); - $model = $this->getModel("wishlist"); - - $Itemid = $input->getInt('Itemid', 0); - $post['wishlist_id'] = $input->getInt('wishlist_id'); - - if (Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE')) - { - $post['attribute_id'] = $input->getInt('attribute_id', 0); - $post['property_id'] = $input->getInt('property_id', 0); - $post['subattribute_id'] = $input->getInt('subattribute_id', 0); - } - - $link = JRoute::_("index.php?mydel=1&option=com_redshop&view=wishlist&task=viewwishlist&Itemid=" . $Itemid, false); - - if (!empty($mydel)) - { - if ($model->mysessdelwishlist($post)) - { - $msg = JText::_('COM_REDSHOP_WISHLIST_DELETED_SUCCESSFULLY'); - } - - $this->setRedirect($link, $msg); - } - - $this->setRedirect($link); - } + /** + * createsave wishlist function + * + * @access public + * @return void + */ + public function createsave() + { + $user = JFactory::getUser(); + + /** @var RedshopModelWishlist $model */ + $model = $this->getModel("wishlist"); + $input = JFactory::getApplication()->input; + + $post = array(); + $post['wishlist_name'] = $input->post->getString('txtWishlistname', ''); + $post['user_id'] = $user->id; + $post['cdate'] = time(); + $post['product_id'] = $input->post->getInt('product_id', 0); + + if ($model->store($post)) { + echo "
    " . JText::_( + 'COM_REDSHOP_PRODUCT_SAVED_IN_WISHLIST_SUCCESSFULLY' + ) . "
    "; + } else { + echo "
    " . JText::_('COM_REDSHOP_PRODUCT_NOT_SAVED_IN_WISHLIST') . "
    "; + } + + if ($input->getInt('loginwishlist', 0) == 1) { + $return = JRoute::_( + 'index.php?option=com_redshop&view=wishlist&task=viewwishlist&Itemid=' . $this->input->post->getInt( + 'Itemid' + ), + false + ); + $this->setRedirect($return); + } else { + ?> + + getModel("wishlist"); + + $data = JFactory::getApplication()->input->post->getArray(); + + if ($model->savewishlist($data)) { + echo "
    " . JText::_( + 'COM_REDSHOP_PRODUCT_SAVED_IN_WISHLIST_SUCCESSFULLY' + ) . "
    "; + } else { + echo "
    " . JText::_('COM_REDSHOP_PRODUCT_NOT_SAVED_IN_WISHLIST') . "
    "; + } + + ?> + + getModel("wishlist"); + $Itemid = $app->input->get('Itemid'); + $post = $app->input->getArray(); + $link = JRoute::_("index.php?option=com_redshop&view=wishlist&task=viewwishlist&Itemid=" . $Itemid, false); + + if ($model->check_user_wishlist_authority($user->id, $post["wishlist_id"])) { + if ($model->delwishlist($user->id, $post["wishlist_id"])) { + $msg = JText::_('COM_REDSHOP_WISHLIST_DELETED_SUCCESSFULLY'); + } else { + $msg = JText::_('COM_REDSHOP_ERROR_IN_DELETING_WISHLIST'); + } + } else { + $msg = JText::_('COM_REDSHOP_YOU_ARE_NOT_AUTHORIZE_TO_DELETE'); + } + + $app->redirect($link, $msg); + } + + /** + * My sess del wish list + * + * @return void + */ + public function mysessdelwishlist() + { + $input = JFactory::getApplication()->input; + $post = array(); + $mydel = $input->get('mydel'); + $model = $this->getModel("wishlist"); + + $Itemid = $input->getInt('Itemid', 0); + $post['wishlist_id'] = $input->getInt('wishlist_id'); + + if (Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE')) { + $post['attribute_id'] = $input->getInt('attribute_id', 0); + $post['property_id'] = $input->getInt('property_id', 0); + $post['subattribute_id'] = $input->getInt('subattribute_id', 0); + } + + $link = JRoute::_( + "index.php?mydel=1&option=com_redshop&view=wishlist&task=viewwishlist&Itemid=" . $Itemid, + false + ); + + if (!empty($mydel)) { + if ($model->mysessdelwishlist($post)) { + $msg = JText::_('COM_REDSHOP_WISHLIST_DELETED_SUCCESSFULLY'); + } + + $this->setRedirect($link, $msg); + } + + $this->setRedirect($link); + } } diff --git a/component/site/index.html b/component/site/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/site/index.html +++ b/component/site/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/language/en-GB/en-GB.com_redshop.ini b/component/site/language/en-GB/en-GB.com_redshop.ini index 45901daccee..121643d66ed 100755 --- a/component/site/language/en-GB/en-GB.com_redshop.ini +++ b/component/site/language/en-GB/en-GB.com_redshop.ini @@ -6,1055 +6,1055 @@ ; copyright com_redshop (C) 2008 - 2017 redCOMPONENT.com ; license GNU/GPL, see LICENSE.php -COM_REDSHOP_PLEASE_ENTER_EAN_NUMBER="Please enter EAN number" -COM_REDSHOP_EAN_NUMBER="EAN Number" -COM_REDSHOP_REQUISITION_NUMBER="Requisition Number" -COM_REDSHOP_PLEASE_ENTER_REQUISITION_NUMBER="Please enter requisition number" -COM_REDSHOP_COPY_TO_CART="Copy To Cart" -COM_REDSHOP_COPY_ORDERITEM_LBL="Action" -COM_REDSHOP_MINIMUM_QUANTITY_SHOULD_BE="Minimum Quantity should be" -COM_REDSHOP_MAXIMUM_QUANTITY_SHOULD_BE="Maximum Quantity should be" -COM_REDSHOP_DETAIL_ERROR_MESSAGE_LBL="Detail Error message from e-conomic" -COM_REDSHOP_PRODUCT_PRICE_ASC="Product Price Ascending" -COM_REDSHOP_PRODUCT_PRICE_DESC="Product Price Descending" -COM_REDSHOP_LOGIN_NEWWISHLIST="Please login or create an account!" -COM_REDSHOP_LOGIN_PROMPTWISHLIST="You have to login in order to add items to your wishlist" -COM_REDSHOP_ADD_TO_LOGINWISHLIST="Add To Login" -COM_REDSHOP_CREATE_LOGINACCOUNT="Create Account" -COM_REDSHOP_USERNAME_ALREADY_EXISTS="Username already exists" -COM_REDSHOP_EMAIL_ALREADY_EXISTS="Email already exists" -COM_REDSHOP_SUBATTRIBUTE_IS_REQUIRED="Please Select Sub Attribute" -COM_REDSHOP_YES="Yes" -COM_REDSHOP_NO="No" -COM_REDSHOP_NO_DISCOUNT_AVAILABLE="No Discount Available" -COM_REDSHOP_PRINT_LBL="Print" -COM_REDSHOP_BACK="Back" -COM_REDSHOP_DELETE_LBL="Delete" -COM_REDSHOP_EDIT_LBL="Edit" -COM_REDSHOP_CLICK_HERE="Click Here" -COM_REDSHOP_ATTRIBUTE="Attribute(s):" -COM_REDSHOP_MORE="More" -COM_REDSHOP_ORDER_LIST="Order List" -COM_REDSHOP_CREATE_ACCOUNT="Create Account" -COM_REDSHOP_ACCOUNT_MAINTAINANCE="Account Maintenance" -COM_REDSHOP_ACCOUNT_INFORMATION="Account Information" -COM_REDSHOP_ACCOUNT_LAYOUT_CARDS="Credit Cards List" -COM_REDSHOP_ACCOUNT_LAYOUT_CARDS_DESC="This view will show user's credit cards stored in payment gateway. For example: if site has paypal credit card plugin and vault is enabled then it will show list of all the credit cards." -COM_REDSHOP_SHIPPING_INFO="Shipping Information" -COM_REDSHOP_FILL_BILLING_ADDRESS="Fill out billing address" -COM_REDSHOP_FILL_SHIPPING_ADDRESS="Fill out shipping address" -COM_REDSHOP_UPDATE_SHIPPING_INFO="Add/Edit Addresses" -COM_REDSHOP_ORDER_INFORMATION="Order Information" -COM_REDSHOP_ORDER_TRANSACTION_FEE_LABEL="Order Transaction Fee" -COM_REDSHOP_SHIPPING_ADDRESSES="Shipping Addresses" -COM_REDSHOP_DEFAULT_SHIPPING_ADDRESS="Default (Same as Billing)" -COM_REDSHOP_COUPON_INFO="Coupon Information" -COM_REDSHOP_COUPON_CODE="Coupon code" -COM_REDSHOP_COUPON_VALUE="Coupon Value" -COM_REDSHOP_TOTAL_PRODUCT="Total Product" -COM_REDSHOP_TOTAL="Total" -COM_REDSHOP_NEWSLETTER_NAME="Newsletter Name" -COM_REDSHOP_SUBSCRIPTION="Subscription" -COM_REDSHOP_RESERVED_DISCOUNT_LBL="Remaining Discount" -COM_REDSHOP_LOGIN_USER_IS_NOT_REDSHOP_USER="The user logged in is not a redSHOP user, so please enter other required user detail" -COM_REDSHOP_STATUS="Status" -COM_REDSHOP_LOGOUT="Log out" -COM_REDSHOP_ALERTNOTAUTH_ACCOUNT="To access the private area of this site, please log in." -COM_REDSHOP_ORDER_ENCKEY_FAILURE="Order URL provided is not valid" -COM_REDSHOP_EDIT_ACCOUNT_INFORMATION="Edit Account Information" -COM_REDSHOP_DELETE_ACCOUNT="Delete Account" -COM_REDSHOP_DO_YOU_WANT_TO_DELETE="Do you really want to delete?" -COM_REDSHOP_ACCOUNT_DELETED_SUCCESSFULLY="Account Deleted Successfully" -COM_REDSHOP_ACCOUNT_DELETED_FAIL="Account Deleted Fail" -COM_REDSHOP_ORDER_DETAILS="Order Details" -COM_REDSHOP_CUSTOMER_FULLNAME="Full Name" -COM_REDSHOP_CUSTOMER_STATE="State" -COM_REDSHOP_CUSTOMER_COUNTRY="Country" -COM_REDSHOP_CUSTOMER_VATNUMBER="Tax number" -COM_REDSHOP_CUSTOMER_EMAIL="E-mail" -COM_REDSHOP_ORDER_NUM="Order #" -COM_REDSHOP_DETAILS="Details" -COM_REDSHOP_ADDRESS_INFORMATION="Address Information" -COM_REDSHOP_NO_ORDERS_PLACED_YET="No orders placed yet" -COM_REDSHOP_NO_QUOTATION_PLACED_YET="No Quote placed yet" -COM_REDSHOP_NO_COUPONS="No coupons available" -COM_REDSHOP_ORDER_DETAIL="Details" -COM_REDSHOP_ORDER_MAIL="Follow this link to view order details" -COM_REDSHOP_PAY_REMAINING="Pay Remaining" -COM_REDSHOP_MY_WISHLIST="My Wishlist" -COM_REDSHOP_MY_SERIALS="My Serials" -COM_REDSHOP_CREATE_NEWWISHLIST="Create New Wishlist" -COM_REDSHOP_PRODUCT_SAVED_IN_WISHLIST_SUCCESSFULLY="Product added to wishlist successfully" -COM_REDSHOP_WISHLIST_PRODUCT_DELETED_SUCCESSFULLY="Product Deleted From Wishlist Successfully" -COM_REDSHOP_WISHLIST_DELETED_SUCCESSFULLY="Wishlist Deleted Successfully" -COM_REDSHOP_ERROR_IN_DELETING_WISHLIST="Error while deleting Wishlist" -COM_REDSHOP_YOU_ARE_NOT_AUTHORIZE_TO_DELETE="You are not authorize to delete this wishlist" -COM_REDSHOP_MY_TAGS="My Tags" -COM_REDSHOP_TIP_TAGS="Use spaces to separate tags. Use single quotes (') for phrases." -COM_REDSHOP_SHOW_TAG="Show Tag(s)" -COM_REDSHOP_SHOW_WISHLIST_PRODUCTS="Show Wishlist" -COM_REDSHOP_WISHLIST_SAVE_SUCCESSFULLY="Product Added To Wishlist" -COM_REDSHOP_ALLREADY_ADDED_TO_WISHLIST="Already Added To Wishlist" -COM_REDSHOP_ADD_TO_WISHLIST="Add to Wishlist" -COM_REDSHOP_PRODUCT_TAGS="Product Tag(s)" -COM_REDSHOP_ADD_YOUR_TAGS="Add Your Tag(s)" -COM_REDSHOP_TAG_NAME="Tag Name" -COM_REDSHOP_ADD_TAGS="Add Tags" -COM_REDSHOP_TAGS_ARE_ADDED="Tag Is Added" -COM_REDSHOP_ALLREADY_ADDED="Already Added" -COM_REDSHOP_ERROR_SAVING_WISHLIST="Error Saving Wishlist" -COM_REDSHOP_ERROR_ADDING_TAGS="Error Adding Tag" -COM_REDSHOP_ERROR_DELETING_WISHLIST_PRODUCT="Error Deleting Wishlist Product" -COM_REDSHOP_TAG_EDITED_SUCCESSFULLY="Tag Edited Successfully" -COM_REDSHOP_ERROR_EDITING_TAG="Error Editing Tag" -COM_REDSHOP_ERROR_DELETING_TAG="Error Deleting Tag" -COM_REDSHOP_TAG_DELETED_SUCCESSFULLY="Tag Deleted Successfully" -COM_REDSHOP_REMOVE_TAG="Remove Tag" -COM_REDSHOP_EDIT_TAG="Edit Tags" -COM_REDSHOP_NO_TAGS_AVAILABLE="No Tag(s) Available" -COM_REDSHOP_NO_PRODUCTS_IN_WISHLIST="No Products In Wishlist" -COM_REDSHOP_NO_PRODUCTS_TO_COMPARE="No Products to Compare" -COM_REDSHOP_ADD_ONE_MORE_PRODUCT_TO_COMPARE="Add one more product to compare" -COM_REDSHOP_NO_PRODUCTS_IN_TAGS="No Products in This tag" -COM_REDSHOP_AVAILABLE_TAGS="Available Tag(s)" -COM_REDSHOP_BACK_TO_TAG_LIST="Back To Tag List" -COM_REDSHOP_BACK_TO_MYACCOUNT="Back To My account" -COM_REDSHOP_PROCEED="Proceed" -COM_REDSHOP_SELECT="Select" -COM_REDSHOP_PARTIAL_PAYMENT_DONE="Remaining payment done successfully" -COM_REDSHOP_PARTIAL_PAYMENT_FAILURE="Remaining payment failure" -COM_REDSHOP_REMAINING_AMOUNT_TOBE_PAID_BEFORE_DEL="Remaining amount to be paid before delivery" -COM_REDSHOP_REMOVE_ALL_PRODUCT_FROM_COMPARE_LIST="Remove all Items" -COM_REDSHOP_REMOVE_PRODUCT_FROM_COMPARE_LIST="Remove Product From Compare List" -COM_REDSHOP_COMPARE_PRODUCTS="Compare Products" -COM_REDSHOP_DESCRIPTION="Description" -COM_REDSHOP_SHORT_DESCRIPTION="Short Description" -COM_REDSHOP_LIMIT_CROSS_TO_COMPARE="Your Limit of Adding Products to Compare List is Over" -COM_REDSHOP_ADD_TO_COMPARE="Add to Compare" -COM_REDSHOP_SHOW_PRODUCTS_TO_COMPARE="Show Products To Compare" -COM_REDSHOP_PRODUCT_DELETED_FROM_COMPARE_SUCCESSFULLY="Product Deleted From Compare Successfully" -COM_REDSHOP_ERROR_DELETING_PRODUCT_FROM_COMPARE="Error Deleting Product From Compare List" -COM_REDSHOP_ERROR_ADDING_PRODUCT_TO_COMPARE="You can only compare products of the same category" -COM_REDSHOP_ERROR_REQUIRE_UNIQUE_PRODUCT_ID_TO_COMPARE="Items with unique product id are required" -COM_REDSHOP_ALLREADY_ADDED_TO_COMPARE="Already Added To Compare" -COM_REDSHOP_REMAININGTOPAY="Remaining to pay" -COM_REDSHOP_PRODUCT_NAME="Name" -COM_REDSHOP_PRODUCT_LENGTH_LBL="Product Length" -COM_REDSHOP_PRODUCT_WIDTH_LBL="Product width" -COM_REDSHOP_PRODUCT_HEIGHT_LBL="Product Height" -COM_REDSHOP_QUESTION_PRODUCT_NAME="Product Name" -COM_REDSHOP_PRODUCT_PRICE="Product Price" -COM_REDSHOP_NEWEST="Newest" -COM_REDSHOP_ORDERING="Default Order" -COM_REDSHOP_REGULAR_PRICE="Regular Price:" -COM_REDSHOP_WEEKS="weeks" -COM_REDSHOP_DAYS="Days" -COM_REDSHOP_DAY="Day" -COM_REDSHOP_DELIVERY_TIME="Delivery Time :" -COM_REDSHOP_READ_MORE="Read more" -COM_REDSHOP_ADD_TO_CART="Add to cart" -COM_REDSHOP_PRE_ORDER="Pre Order" -COM_REDSHOP_PRODUCT_ID_LBL="Product Id:" -COM_REDSHOP_PRODUCT_NUMBER_LBL="Product Number:" -COM_REDSHOP_ACCESSORY_ADD_CHKBOX_LBL="Add" -COM_REDSHOP_PRODUCT_IN_STOCK_LBL="Total no of product in stock" -COM_REDSHOP_PRODUCT_WEIGHT_LBL="Product weight" -COM_REDSHOP_PRODUCT_VOLUME_LBL="Product volume" -COM_REDSHOP_PRODUCT_VOLUME_UNIT="m3" -COM_REDSHOP_PRODUCT_OLD_PRICE_LBL="Product old price" -COM_REDSHOP_PRODUCT_PRICE_SAVING_LBL="Product saving price" -COM_REDSHOP_PRODUCT_PRICE_SAVING_PERCENTAGE_LBL="You are saving %s" -COM_REDSHOP_SELECT_ORDER_BY="Order By:" -COM_REDSHOP_SELECT_FILTER_BY="Filter By:" -COM_REDSHOP_CATEGORY_IS_NOT_PUBLISHED="%s(%s) is not Published" -COM_REDSHOP_CATEGORY_NOT_FOUND="No category found." -COM_REDSHOP_CUSTOMER_INFORMATION="Customer Information" -COM_REDSHOP_BILL_TO_INFORMATION="Bill to information" -COM_REDSHOP_FIRSTNAME="First name" -COM_REDSHOP_LASTNAME="Last name" -COM_REDSHOP_ADDRESS="Address" -COM_REDSHOP_CITY="City" -COM_REDSHOP_PHONE="Phone" -COM_REDSHOP_ZIP="Postal code" -COM_REDSHOP_COMPANY_NAME="Company name" -COM_REDSHOP_VAT_NUMBER="Tax number" -COM_REDSHOP_TAX_EXEMPT="Tax exempt" -COM_REDSHOP_TAX_NO="No" -COM_REDSHOP_TAX_YES="Yes" -COM_REDSHOP_USERNAME="Username" -COM_REDSHOP_EMAIL="E-mail" -COM_REDSHOP_PASSWORD="Password" -COM_REDSHOP_CONFIRM_PASSWORD="Confirm password" -COM_REDSHOP_STATE="State" -COM_REDSHOP_COUNTRY="Country" -COM_REDSHOP_EMPTY_USERNAME="No username typed in - please try again" -COM_REDSHOP_EMPTY_EMAIL="No e-mail typed in - please try again" -COM_REDSHOP_PLEASE_ENTER_EMAIL_ADDRESS="Please enter email address" -COM_REDSHOP_PLEASE_ENTER_VALID_EMAIL_ADDRESS="Please enter valid email address" -COM_REDSHOP_PLEASE_ENTER_AMOUNT="Please enter valid amount" -COM_REDSHOP_PLEASE_ENTER_USERNAME="Please enter username" -COM_REDSHOP_PLEASE_ENTER_PASSWORD="Please enter password" -COM_REDSHOP_PASSWORD_NOT_MATCH="Password not match" -COM_REDSHOP_PLEASE_ENTER_FIRST_NAME="Please enter first name" -COM_REDSHOP_PLEASE_ENTER_LAST_NAME="Please enter last name" -COM_REDSHOP_PLEASE_ENTER_ADDRESS="Please enter address" -COM_REDSHOP_PLEASE_SELECT_COUNTRY="Please select country" -COM_REDSHOP_PLEASE_ENTER_ZIPCODE="Please enter postal code" -COM_REDSHOP_PLEASE_ENTER_CITY="Please enter city" -COM_REDSHOP_PLEASE_ENTER_PHONE="Please enter phone number" -COM_REDSHOP_PLEASE_ENTER_COMPANY_NAME="Please enter company name" -COM_REDSHOP_ADD_ADDRESS="Add address" -COM_REDSHOP_BILLING_INFORMATION_SAVE="Billing information saved" -COM_REDSHOP_ERROR_SAVING_BILLING_INFORMATION="Error in saving billing information" -COM_REDSHOP_BILLING_INFORMATION_EDITING_CANCELLED="Billing information editing cancelled" -COM_REDSHOP_SHIPPING_INFORMATION_SAVE="Shipping information saved" -COM_REDSHOP_ERROR_SAVING_SHIPPING_INFORMATION="Error in saving shipping information" -COM_REDSHOP_SHIPPING_INFORMATION_EDITING_CANCELLED="Shipping information editing cancelled" -COM_REDSHOP_ACCOUNT_SHIPPING_DELETED_SUCCESSFULLY="Shipping deleted successfully" -COM_REDSHOP_LOGIN_DESCRIPTION="To access the private area of this site, please log in." -COM_REDSHOP_LOGOUT_DESCRIPTION="You are currently logged in to the private area of this site." -COM_REDSHOP_CREATE_USER_LINK="New User Registration" -COM_REDSHOP_FORGOT_PWD_LINK="Forgot Password" -COM_REDSHOP_RELATED_PRODUCT="Related product" -COM_REDSHOP_ACCESSORY="Accessory:" -COM_REDSHOP_ACCESSORIES_OUT_OF_STOCK="%s out of stock" -COM_REDSHOP_ATTRIBUTE_IS_REQUIRED="Please select" -COM_REDSHOP_REQUIRED="Required" -COM_REDSHOP_CHILD_PRODUCTS="Child Product" -COM_REDSHOP_PRODUCT_IS_NOT_PUBLISHED="%s(%s) is not Published" -COM_REDSHOP_ALERTNOTAUTH_REVIEW="Please login to write a review" -COM_REDSHOP_YOU_CAN_NOT_REVIEW_SAME_PRODUCT_AGAIN="You can not review the same product again." -COM_REDSHOP_PLEASE_RATE_THE_PRODUCT="Please rate the product" -COM_REDSHOP_PLEASE_COMMENT_ON_PRODUCT="Please comment on product" -COM_REDSHOP_RATING_TITLE="Title" -COM_REDSHOP_WRITE_REVIEW="Write review" -COM_REDSHOP_USER_FULLNAME="Full name" -COM_REDSHOP_SHOW_ALL_REVIEWS="Show All Reviews" -COM_REDSHOP_REVIEW_TOTAL_REVIEW="%s Review" -COM_REDSHOP_SEND_REVIEW="Send Review" -COM_REDSHOP_COMMENT_IMAGE="Image" -COM_REDSHOP_EXCELLENT="Excellent" -COM_REDSHOP_GOOD="Good" -COM_REDSHOP_RATING="Rating" -COM_REDSHOP_COMMENT="Your Comments" -COM_REDSHOP_WRITE_REVIEWFORM_HEADER_TEXT="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book." -COM_REDSHOP_WRITE_REVIEWFORM_FOOTER_TEXT="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book." -COM_REDSHOP_AVG_RATINGS_1="Average based on" -COM_REDSHOP_AVG_RATINGS_2="customer review(s)." -COM_REDSHOP_SELECT_SHIP_ADDRESS="Please enter or select your shipping address" -COM_REDSHOP_RETURNING_CUSTOMERS="Returning Customers: Please Log In" -COM_REDSHOP_NEW_CUSTOMERS="New customer? Please Provide Your Billing Information" -COM_REDSHOP_SEND_REGISTRATION="Sign Up" -COM_REDSHOP_BTN_CHECKOUTNEXT="Checkout: next step" -COM_REDSHOP_BTN_CHECKOUTFINAL="Checkout: final step" -COM_REDSHOP_ADD="Add" -COM_REDSHOP_CARD_INFORMATION="Credit Card Information" -COM_REDSHOP_NAME_ON_CARD="Card Holder Name" -COM_REDSHOP_CARD_NUM="Card Number" -COM_REDSHOP_EXPIRY_DATE="Expiration Date" -COM_REDSHOP_CARD_SECURITY_CODE="Card Security Number" -COM_REDSHOP_ORDERTOTAL="Order Total" -COM_REDSHOP_ORDER_RECEIPT="Order Receipt" -COM_REDSHOP_ORDER_RECEIPT_TITLE="Order Receipt" -COM_REDSHOP_EMPTY_CART="Empty cart" -COM_REDSHOP_EMPTY="Empty cart" -COM_REDSHOP_PAYMENT="Payment" -COM_REDSHOP_RECEIPT="Receipt" -COM_REDSHOP_SHIPPING_METHOD="Shipping Method" -COM_REDSHOP_PAYMENT_METHOD="Payment Method" -COM_REDSHOP_PAYMENT_METHOD_CONFLICT="Payment Method Is Conflict" -COM_REDSHOP_PAYMENT_CREDIT_CARDS_NOT_FOUND="No credit card option found, please check your payment plugin params." -COM_REDSHOP_PAYMENT_NO_CREDIT_CARDS_PLUGIN_LIST_FOUND="No credit card plugins available." -COM_REDSHOP_SHIPPING_SAME_AS_BILLING="Shipping address same as billing" -COM_REDSHOP_CHECKOUT_ERR_NO_CCDATA="There is no CreditCard data..." -COM_REDSHOP_CHECKOUT_ERR_NO_CCNR_FOUND="Credit Card Number not found!" -COM_REDSHOP_CHECKOUT_ERR_NO_MON_FOUND="Credit card expiration month not found!" -COM_REDSHOP_CHECKOUT_ERR_NO_UNKNOWN_CCTYPE="Unknown card type" -COM_REDSHOP_CHECKOUT_ERR_NO_CARD_PROVIDED="No card number provided" -COM_REDSHOP_CHECKOUT_ERR_NO_CARD_INVALIDFORMAT="Credit card number has invalid format" -COM_REDSHOP_CHECKOUT_ERR_NO_CARD_INVALIDNUMBER="Credit card number is invalid" -COM_REDSHOP_CHECKOUT_ERR_NO_CARD_WRONGLENGTH="Credit card number is wrong length" -COM_REDSHOP_CHECKOUT_VAT_LBL="Tax :" -COM_REDSHOP_CHECKOUT_DISCOUNT_LBL="Discount :" -COM_REDSHOP_CHECKOUT_SHIPPING_LBL="Shipping :" -COM_REDSHOP_SELECT_PAYMENT_STATUS="Select Payment Status" -COM_REDSHOP_PAYMENT_STA_PAID="Paid" -COM_REDSHOP_PAYMENT_STA_UNPAID="Unpaid" -COM_REDSHOP_PAYMENT_STA_PARTIAL_PAID="Partial Paid" -COM_REDSHOP_RECEIPT_PARTIALLY_PAID_AMOUNT="Partially Paid Amount" -COM_REDSHOP_REMAINING_PARTIALLY_AMOUNT="Amount Remaining to pay" -COM_REDSHOP_EPAY_PAYMENT_TRANSACTION_SUCCESS="The payment has been processed. You can review your order details here" -COM_REDSHOP_PLEASE_SELECT_TEMS_CONDITIONS="Please accept Terms and conditions before clicking in the Checkout button." -COM_REDSHOP_TERMS_AND_CONDITIONS_LBL="Accept Terms & conditions" -COM_REDSHOP_TERMS_AND_CONDITIONS_FOR_LBL="For Webshop" -COM_REDSHOP_SELECT_PAYMENT_METHOD="Select Payment Method" -COM_REDSHOP_EMPTY_PASSWORD="Please enter a password" -COM_REDSHOP_ORDER_NUMBER_LBL="Order Number" -COM_REDSHOP_ORDER_ID_LBL="Order ID" -COM_REDSHOP_USER_REGISTRATION="Private Person" -COM_REDSHOP_COMPANY_REGISTRATION="Business" -COM_REDSHOP_REGISTRATION_HEADING="Registration" -COM_REDSHOP_COMPANY_IS_NOT_VAT_EXEMPTED="Company is not tax exempted" -COM_REDSHOP_COMPANY_IS_VAT_EXEMPTED="Company is tax exempted" -COM_REDSHOP_BUSINESS_NUMBER="Business Number" -COM_REDSHOP_SIGN_UP_FOR_NEWSLETTER="Yes, Sign me up for the newsletter" -COM_REDSHOP_DELETE_PRODUCT_FROM_CART_LBL="Delete product in cart" -COM_REDSHOP_UPDATE_PRODUCT_FROM_CART_LBL="Update product in cart" -COM_REDSHOP_CHECKOUT="Checkout" -COM_REDSHOP_VOUCHER_CODE="Voucher code" -COM_REDSHOP_COUPEN_CODE="Coupon Code" -COM_REDSHOP_SHOP_MORE="Continue" -COM_REDSHOP_UPDATE="Update" -COM_REDSHOP_SUBMIT_CODE="Submit" -COM_REDSHOP_DISCOUNT_TEXT="If you order for %s more, you will get at least %s DISCOUNT( %s )" -COM_REDSHOP_CART_TOTAL_PURCHASE_TBL="Total purchases" -COM_REDSHOP_CART_COUPON_CODE_TBL="GIFT CODE" -COM_REDSHOP_CART_DISCOUNT_CODE_TBL="Discount Code" -COM_REDSHOP_CART_CHECKOUT="Checkout" -COM_REDSHOP_PRODUCT_OUTOFSTOCK_MESSAGE="Sorry, This product is out of stock...." -COM_REDSHOP_VIEW_CART="View Cart" -COM_REDSHOP_CONTINUE_SHOPPING="Continue Shopping" -COM_REDSHOP_CART_SAVE="Display Cart" -COM_REDSHOP_CART_PRODUCT_ATTRIBUTE_CALCULATED_PRICE="(+ %s)" -COM_REDSHOP_SHOW_CART_TEXT="Your product(s) has been added to your cart" -COM_REDSHOP_IS_REQUIRED="is Required." -COM_REDSHOP_ENTER_NUMBER="Please Enter Numbers" -COM_REDSHOP_MINIMUM_ORDER_TOTAL_HAS_TO_BE_MORE_THAN="Minimum order total has to be more than" -COM_REDSHOP_NAME="Name" -COM_REDSHOP_SEND_TO_FRIEND="Send to Friend" -COM_REDSHOP_SEND_FRIEND="Send Friend" -COM_REDSHOP_YOUR_NAME="Your Name" -COM_REDSHOP_FRIENDS_NAME="Friend's name" -COM_REDSHOP_FRIENDS_EMAIL="Friend's email" -COM_REDSHOP_PLEASE_ENTER_NAME="Please enter your name." -COM_REDSHOP_PLEASE_ENTER_FRIENDS_NAME="Please enter your friend's name." -COM_REDSHOP_PLEASE_ENTER_FRIENDS_EMAIL_ADDRESS="Please enter your friend's email address." -COM_REDSHOP_EMAIL_HAS_BEEN_SENT_SUCCESSFULLY="Email has been sent successfully" -COM_REDSHOP_EMAIL_HAS_NOT_BEEN_SENT_SUCCESSFULLY="Email has not been sent successfully" -COM_REDSHOP_FILTER="Filter" -COM_REDSHOP_ORDER_ID="Order ID" -COM_REDSHOP_FULLNAME="Full Name" -COM_REDSHOP_ORDER_STATUS="Order Status" -COM_REDSHOP_ORDER_DATE="Order Date" -COM_REDSHOP_ORDER_TOTAL="Order Total" -COM_REDSHOP_ORDER="Order" -COM_REDSHOP_INCLUDE_COMMENT_MSG="Include this comment?" -COM_REDSHOP_NOTIFY_CUSTOMER_MSG="Notify Customer?" -COM_REDSHOP_ORDER_PRODUCT_NOTE="Note" -COM_REDSHOP_PRODUCT_QTY="Quantity" -COM_REDSHOP_TOTAL_PRICE="Total Price" -COM_REDSHOP_ORDER_SUBTOTAL="Order Subtotal" -COM_REDSHOP_ORDER_TAX="TAX" -COM_REDSHOP_ORDER_DISCOUNT="Discount" -COM_REDSHOP_ORDER_SHIPPING="Shipping" -COM_REDSHOP_ORDER_NUMBER="Order Number" -COM_REDSHOP_BILLING_ADDRESS_INFORMATION="Billing Address Information" -COM_REDSHOP_SHIPPING_ADDRESS_INFORMATION="Shipping Address Information" -COM_REDSHOP_RESET="Reset" -COM_REDSHOP_ORDER_DATE_LBL="Order Date" -COM_REDSHOP_ORDER_STAUS_LBL="Order Status" -COM_REDSHOP_PAYMENT_STAUS_LBL="Payment Status" -COM_REDSHOP_ORDER_INFORMATION_LBL="Order Information" -COM_REDSHOP_BILLING_ADDRESS_INFORMATION_LBL="Billing Address Information" -COM_REDSHOP_SHIPPING_ADDRESS_INFO_LBL="Shipping Address Information" -COM_REDSHOP_ORDER_DETAIL_LBL="Order Details" -COM_REDSHOP_PRODUCT_NAME_LBL="Name" -COM_REDSHOP_NOTE_LBL="Note" -COM_REDSHOP_PRICE_LBL="Price" -COM_REDSHOP_QUANTITY_LBL="Quantity" -COM_REDSHOP_TOTAL_PRICE_LBL="Total Price" -COM_REDSHOP_ORDER_SUBTOTAL_LBL="Order Subtotal" -COM_REDSHOP_TOTAL_LBL="Total" -COM_REDSHOP_CART_LBL="Shopping Cart" -COM_REDSHOP_MINIMUM_DELIVERY_TIME="Minimum Delivery Time" -COM_REDSHOP_MAXIMUM_DELIVERY_TIME="Maximum Delivery Time" +COM_REDSHOP_PLEASE_ENTER_EAN_NUMBER = "Please enter EAN number" +COM_REDSHOP_EAN_NUMBER = "EAN Number" +COM_REDSHOP_REQUISITION_NUMBER = "Requisition Number" +COM_REDSHOP_PLEASE_ENTER_REQUISITION_NUMBER = "Please enter requisition number" +COM_REDSHOP_COPY_TO_CART = "Copy To Cart" +COM_REDSHOP_COPY_ORDERITEM_LBL = "Action" +COM_REDSHOP_MINIMUM_QUANTITY_SHOULD_BE = "Minimum Quantity should be" +COM_REDSHOP_MAXIMUM_QUANTITY_SHOULD_BE = "Maximum Quantity should be" +COM_REDSHOP_DETAIL_ERROR_MESSAGE_LBL = "Detail Error message from e-conomic" +COM_REDSHOP_PRODUCT_PRICE_ASC = "Product Price Ascending" +COM_REDSHOP_PRODUCT_PRICE_DESC = "Product Price Descending" +COM_REDSHOP_LOGIN_NEWWISHLIST = "Please login or create an account!" +COM_REDSHOP_LOGIN_PROMPTWISHLIST = "You have to login in order to add items to your wishlist" +COM_REDSHOP_ADD_TO_LOGINWISHLIST = "Add To Login" +COM_REDSHOP_CREATE_LOGINACCOUNT = "Create Account" +COM_REDSHOP_USERNAME_ALREADY_EXISTS = "Username already exists" +COM_REDSHOP_EMAIL_ALREADY_EXISTS = "Email already exists" +COM_REDSHOP_SUBATTRIBUTE_IS_REQUIRED = "Please Select Sub Attribute" +COM_REDSHOP_YES = "Yes" +COM_REDSHOP_NO = "No" +COM_REDSHOP_NO_DISCOUNT_AVAILABLE = "No Discount Available" +COM_REDSHOP_PRINT_LBL = "Print" +COM_REDSHOP_BACK = "Back" +COM_REDSHOP_DELETE_LBL = "Delete" +COM_REDSHOP_EDIT_LBL = "Edit" +COM_REDSHOP_CLICK_HERE = "Click Here" +COM_REDSHOP_ATTRIBUTE = "Attribute(s):" +COM_REDSHOP_MORE = "More" +COM_REDSHOP_ORDER_LIST = "Order List" +COM_REDSHOP_CREATE_ACCOUNT = "Create Account" +COM_REDSHOP_ACCOUNT_MAINTAINANCE = "Account Maintenance" +COM_REDSHOP_ACCOUNT_INFORMATION = "Account Information" +COM_REDSHOP_ACCOUNT_LAYOUT_CARDS = "Credit Cards List" +COM_REDSHOP_ACCOUNT_LAYOUT_CARDS_DESC = "This view will show user's credit cards stored in payment gateway. For example: if site has paypal credit card plugin and vault is enabled then it will show list of all the credit cards." +COM_REDSHOP_SHIPPING_INFO = "Shipping Information" +COM_REDSHOP_FILL_BILLING_ADDRESS = "Fill out billing address" +COM_REDSHOP_FILL_SHIPPING_ADDRESS = "Fill out shipping address" +COM_REDSHOP_UPDATE_SHIPPING_INFO = "Add/Edit Addresses" +COM_REDSHOP_ORDER_INFORMATION = "Order Information" +COM_REDSHOP_ORDER_TRANSACTION_FEE_LABEL = "Order Transaction Fee" +COM_REDSHOP_SHIPPING_ADDRESSES = "Shipping Addresses" +COM_REDSHOP_DEFAULT_SHIPPING_ADDRESS = "Default (Same as Billing)" +COM_REDSHOP_COUPON_INFO = "Coupon Information" +COM_REDSHOP_COUPON_CODE = "Coupon code" +COM_REDSHOP_COUPON_VALUE = "Coupon Value" +COM_REDSHOP_TOTAL_PRODUCT = "Total Product" +COM_REDSHOP_TOTAL = "Total" +COM_REDSHOP_NEWSLETTER_NAME = "Newsletter Name" +COM_REDSHOP_SUBSCRIPTION = "Subscription" +COM_REDSHOP_RESERVED_DISCOUNT_LBL = "Remaining Discount" +COM_REDSHOP_LOGIN_USER_IS_NOT_REDSHOP_USER = "The user logged in is not a redSHOP user, so please enter other required user detail" +COM_REDSHOP_STATUS = "Status" +COM_REDSHOP_LOGOUT = "Log out" +COM_REDSHOP_ALERTNOTAUTH_ACCOUNT = "To access the private area of this site, please log in." +COM_REDSHOP_ORDER_ENCKEY_FAILURE = "Order URL provided is not valid" +COM_REDSHOP_EDIT_ACCOUNT_INFORMATION = "Edit Account Information" +COM_REDSHOP_DELETE_ACCOUNT = "Delete Account" +COM_REDSHOP_DO_YOU_WANT_TO_DELETE = "Do you really want to delete?" +COM_REDSHOP_ACCOUNT_DELETED_SUCCESSFULLY = "Account Deleted Successfully" +COM_REDSHOP_ACCOUNT_DELETED_FAIL = "Account Deleted Fail" +COM_REDSHOP_ORDER_DETAILS = "Order Details" +COM_REDSHOP_CUSTOMER_FULLNAME = "Full Name" +COM_REDSHOP_CUSTOMER_STATE = "State" +COM_REDSHOP_CUSTOMER_COUNTRY = "Country" +COM_REDSHOP_CUSTOMER_VATNUMBER = "Tax number" +COM_REDSHOP_CUSTOMER_EMAIL = "E-mail" +COM_REDSHOP_ORDER_NUM = "Order #" +COM_REDSHOP_DETAILS = "Details" +COM_REDSHOP_ADDRESS_INFORMATION = "Address Information" +COM_REDSHOP_NO_ORDERS_PLACED_YET = "No orders placed yet" +COM_REDSHOP_NO_QUOTATION_PLACED_YET = "No Quote placed yet" +COM_REDSHOP_NO_COUPONS = "No coupons available" +COM_REDSHOP_ORDER_DETAIL = "Details" +COM_REDSHOP_ORDER_MAIL = "Follow this link to view order details" +COM_REDSHOP_PAY_REMAINING = "Pay Remaining" +COM_REDSHOP_MY_WISHLIST = "My Wishlist" +COM_REDSHOP_MY_SERIALS = "My Serials" +COM_REDSHOP_CREATE_NEWWISHLIST = "Create New Wishlist" +COM_REDSHOP_PRODUCT_SAVED_IN_WISHLIST_SUCCESSFULLY = "Product added to wishlist successfully" +COM_REDSHOP_WISHLIST_PRODUCT_DELETED_SUCCESSFULLY = "Product Deleted From Wishlist Successfully" +COM_REDSHOP_WISHLIST_DELETED_SUCCESSFULLY = "Wishlist Deleted Successfully" +COM_REDSHOP_ERROR_IN_DELETING_WISHLIST = "Error while deleting Wishlist" +COM_REDSHOP_YOU_ARE_NOT_AUTHORIZE_TO_DELETE = "You are not authorize to delete this wishlist" +COM_REDSHOP_MY_TAGS = "My Tags" +COM_REDSHOP_TIP_TAGS = "Use spaces to separate tags. Use single quotes (') for phrases." +COM_REDSHOP_SHOW_TAG = "Show Tag(s)" +COM_REDSHOP_SHOW_WISHLIST_PRODUCTS = "Show Wishlist" +COM_REDSHOP_WISHLIST_SAVE_SUCCESSFULLY = "Product Added To Wishlist" +COM_REDSHOP_ALLREADY_ADDED_TO_WISHLIST = "Already Added To Wishlist" +COM_REDSHOP_ADD_TO_WISHLIST = "Add to Wishlist" +COM_REDSHOP_PRODUCT_TAGS = "Product Tag(s)" +COM_REDSHOP_ADD_YOUR_TAGS = "Add Your Tag(s)" +COM_REDSHOP_TAG_NAME = "Tag Name" +COM_REDSHOP_ADD_TAGS = "Add Tags" +COM_REDSHOP_TAGS_ARE_ADDED = "Tag Is Added" +COM_REDSHOP_ALLREADY_ADDED = "Already Added" +COM_REDSHOP_ERROR_SAVING_WISHLIST = "Error Saving Wishlist" +COM_REDSHOP_ERROR_ADDING_TAGS = "Error Adding Tag" +COM_REDSHOP_ERROR_DELETING_WISHLIST_PRODUCT = "Error Deleting Wishlist Product" +COM_REDSHOP_TAG_EDITED_SUCCESSFULLY = "Tag Edited Successfully" +COM_REDSHOP_ERROR_EDITING_TAG = "Error Editing Tag" +COM_REDSHOP_ERROR_DELETING_TAG = "Error Deleting Tag" +COM_REDSHOP_TAG_DELETED_SUCCESSFULLY = "Tag Deleted Successfully" +COM_REDSHOP_REMOVE_TAG = "Remove Tag" +COM_REDSHOP_EDIT_TAG = "Edit Tags" +COM_REDSHOP_NO_TAGS_AVAILABLE = "No Tag(s) Available" +COM_REDSHOP_NO_PRODUCTS_IN_WISHLIST = "No Products In Wishlist" +COM_REDSHOP_NO_PRODUCTS_TO_COMPARE = "No Products to Compare" +COM_REDSHOP_ADD_ONE_MORE_PRODUCT_TO_COMPARE = "Add one more product to compare" +COM_REDSHOP_NO_PRODUCTS_IN_TAGS = "No Products in This tag" +COM_REDSHOP_AVAILABLE_TAGS = "Available Tag(s)" +COM_REDSHOP_BACK_TO_TAG_LIST = "Back To Tag List" +COM_REDSHOP_BACK_TO_MYACCOUNT = "Back To My account" +COM_REDSHOP_PROCEED = "Proceed" +COM_REDSHOP_SELECT = "Select" +COM_REDSHOP_PARTIAL_PAYMENT_DONE = "Remaining payment done successfully" +COM_REDSHOP_PARTIAL_PAYMENT_FAILURE = "Remaining payment failure" +COM_REDSHOP_REMAINING_AMOUNT_TOBE_PAID_BEFORE_DEL = "Remaining amount to be paid before delivery" +COM_REDSHOP_REMOVE_ALL_PRODUCT_FROM_COMPARE_LIST = "Remove all Items" +COM_REDSHOP_REMOVE_PRODUCT_FROM_COMPARE_LIST = "Remove Product From Compare List" +COM_REDSHOP_COMPARE_PRODUCTS = "Compare Products" +COM_REDSHOP_DESCRIPTION = "Description" +COM_REDSHOP_SHORT_DESCRIPTION = "Short Description" +COM_REDSHOP_LIMIT_CROSS_TO_COMPARE = "Your Limit of Adding Products to Compare List is Over" +COM_REDSHOP_ADD_TO_COMPARE = "Add to Compare" +COM_REDSHOP_SHOW_PRODUCTS_TO_COMPARE = "Show Products To Compare" +COM_REDSHOP_PRODUCT_DELETED_FROM_COMPARE_SUCCESSFULLY = "Product Deleted From Compare Successfully" +COM_REDSHOP_ERROR_DELETING_PRODUCT_FROM_COMPARE = "Error Deleting Product From Compare List" +COM_REDSHOP_ERROR_ADDING_PRODUCT_TO_COMPARE = "You can only compare products of the same category" +COM_REDSHOP_ERROR_REQUIRE_UNIQUE_PRODUCT_ID_TO_COMPARE = "Items with unique product id are required" +COM_REDSHOP_ALLREADY_ADDED_TO_COMPARE = "Already Added To Compare" +COM_REDSHOP_REMAININGTOPAY = "Remaining to pay" +COM_REDSHOP_PRODUCT_NAME = "Name" +COM_REDSHOP_PRODUCT_LENGTH_LBL = "Product Length" +COM_REDSHOP_PRODUCT_WIDTH_LBL = "Product width" +COM_REDSHOP_PRODUCT_HEIGHT_LBL = "Product Height" +COM_REDSHOP_QUESTION_PRODUCT_NAME = "Product Name" +COM_REDSHOP_PRODUCT_PRICE = "Product Price" +COM_REDSHOP_NEWEST = "Newest" +COM_REDSHOP_ORDERING = "Default Order" +COM_REDSHOP_REGULAR_PRICE = "Regular Price:" +COM_REDSHOP_WEEKS = "weeks" +COM_REDSHOP_DAYS = "Days" +COM_REDSHOP_DAY = "Day" +COM_REDSHOP_DELIVERY_TIME = "Delivery Time :" +COM_REDSHOP_READ_MORE = "Read more" +COM_REDSHOP_ADD_TO_CART = "Add to cart" +COM_REDSHOP_PRE_ORDER = "Pre Order" +COM_REDSHOP_PRODUCT_ID_LBL = "Product Id:" +COM_REDSHOP_PRODUCT_NUMBER_LBL = "Product Number:" +COM_REDSHOP_ACCESSORY_ADD_CHKBOX_LBL = "Add" +COM_REDSHOP_PRODUCT_IN_STOCK_LBL = "Total no of product in stock" +COM_REDSHOP_PRODUCT_WEIGHT_LBL = "Product weight" +COM_REDSHOP_PRODUCT_VOLUME_LBL = "Product volume" +COM_REDSHOP_PRODUCT_VOLUME_UNIT = "m3" +COM_REDSHOP_PRODUCT_OLD_PRICE_LBL = "Product old price" +COM_REDSHOP_PRODUCT_PRICE_SAVING_LBL = "Product saving price" +COM_REDSHOP_PRODUCT_PRICE_SAVING_PERCENTAGE_LBL = "You are saving %s" +COM_REDSHOP_SELECT_ORDER_BY = "Order By:" +COM_REDSHOP_SELECT_FILTER_BY = "Filter By:" +COM_REDSHOP_CATEGORY_IS_NOT_PUBLISHED = "%s(%s) is not Published" +COM_REDSHOP_CATEGORY_NOT_FOUND = "No category found." +COM_REDSHOP_CUSTOMER_INFORMATION = "Customer Information" +COM_REDSHOP_BILL_TO_INFORMATION = "Bill to information" +COM_REDSHOP_FIRSTNAME = "First name" +COM_REDSHOP_LASTNAME = "Last name" +COM_REDSHOP_ADDRESS = "Address" +COM_REDSHOP_CITY = "City" +COM_REDSHOP_PHONE = "Phone" +COM_REDSHOP_ZIP = "Postal code" +COM_REDSHOP_COMPANY_NAME = "Company name" +COM_REDSHOP_VAT_NUMBER = "Tax number" +COM_REDSHOP_TAX_EXEMPT = "Tax exempt" +COM_REDSHOP_TAX_NO = "No" +COM_REDSHOP_TAX_YES = "Yes" +COM_REDSHOP_USERNAME = "Username" +COM_REDSHOP_EMAIL = "E-mail" +COM_REDSHOP_PASSWORD = "Password" +COM_REDSHOP_CONFIRM_PASSWORD = "Confirm password" +COM_REDSHOP_STATE = "State" +COM_REDSHOP_COUNTRY = "Country" +COM_REDSHOP_EMPTY_USERNAME = "No username typed in - please try again" +COM_REDSHOP_EMPTY_EMAIL = "No e-mail typed in - please try again" +COM_REDSHOP_PLEASE_ENTER_EMAIL_ADDRESS = "Please enter email address" +COM_REDSHOP_PLEASE_ENTER_VALID_EMAIL_ADDRESS = "Please enter valid email address" +COM_REDSHOP_PLEASE_ENTER_AMOUNT = "Please enter valid amount" +COM_REDSHOP_PLEASE_ENTER_USERNAME = "Please enter username" +COM_REDSHOP_PLEASE_ENTER_PASSWORD = "Please enter password" +COM_REDSHOP_PASSWORD_NOT_MATCH = "Password not match" +COM_REDSHOP_PLEASE_ENTER_FIRST_NAME = "Please enter first name" +COM_REDSHOP_PLEASE_ENTER_LAST_NAME = "Please enter last name" +COM_REDSHOP_PLEASE_ENTER_ADDRESS = "Please enter address" +COM_REDSHOP_PLEASE_SELECT_COUNTRY = "Please select country" +COM_REDSHOP_PLEASE_ENTER_ZIPCODE = "Please enter postal code" +COM_REDSHOP_PLEASE_ENTER_CITY = "Please enter city" +COM_REDSHOP_PLEASE_ENTER_PHONE = "Please enter phone number" +COM_REDSHOP_PLEASE_ENTER_COMPANY_NAME = "Please enter company name" +COM_REDSHOP_ADD_ADDRESS = "Add address" +COM_REDSHOP_BILLING_INFORMATION_SAVE = "Billing information saved" +COM_REDSHOP_ERROR_SAVING_BILLING_INFORMATION = "Error in saving billing information" +COM_REDSHOP_BILLING_INFORMATION_EDITING_CANCELLED = "Billing information editing cancelled" +COM_REDSHOP_SHIPPING_INFORMATION_SAVE = "Shipping information saved" +COM_REDSHOP_ERROR_SAVING_SHIPPING_INFORMATION = "Error in saving shipping information" +COM_REDSHOP_SHIPPING_INFORMATION_EDITING_CANCELLED = "Shipping information editing cancelled" +COM_REDSHOP_ACCOUNT_SHIPPING_DELETED_SUCCESSFULLY = "Shipping deleted successfully" +COM_REDSHOP_LOGIN_DESCRIPTION = "To access the private area of this site, please log in." +COM_REDSHOP_LOGOUT_DESCRIPTION = "You are currently logged in to the private area of this site." +COM_REDSHOP_CREATE_USER_LINK = "New User Registration" +COM_REDSHOP_FORGOT_PWD_LINK = "Forgot Password" +COM_REDSHOP_RELATED_PRODUCT = "Related product" +COM_REDSHOP_ACCESSORY = "Accessory:" +COM_REDSHOP_ACCESSORIES_OUT_OF_STOCK = "%s out of stock" +COM_REDSHOP_ATTRIBUTE_IS_REQUIRED = "Please select" +COM_REDSHOP_REQUIRED = "Required" +COM_REDSHOP_CHILD_PRODUCTS = "Child Product" +COM_REDSHOP_PRODUCT_IS_NOT_PUBLISHED = "%s(%s) is not Published" +COM_REDSHOP_ALERTNOTAUTH_REVIEW = "Please login to write a review" +COM_REDSHOP_YOU_CAN_NOT_REVIEW_SAME_PRODUCT_AGAIN = "You can not review the same product again." +COM_REDSHOP_PLEASE_RATE_THE_PRODUCT = "Please rate the product" +COM_REDSHOP_PLEASE_COMMENT_ON_PRODUCT = "Please comment on product" +COM_REDSHOP_RATING_TITLE = "Title" +COM_REDSHOP_WRITE_REVIEW = "Write review" +COM_REDSHOP_USER_FULLNAME = "Full name" +COM_REDSHOP_SHOW_ALL_REVIEWS = "Show All Reviews" +COM_REDSHOP_REVIEW_TOTAL_REVIEW = "%s Review" +COM_REDSHOP_SEND_REVIEW = "Send Review" +COM_REDSHOP_COMMENT_IMAGE = "Image" +COM_REDSHOP_EXCELLENT = "Excellent" +COM_REDSHOP_GOOD = "Good" +COM_REDSHOP_RATING = "Rating" +COM_REDSHOP_COMMENT = "Your Comments" +COM_REDSHOP_WRITE_REVIEWFORM_HEADER_TEXT = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book." +COM_REDSHOP_WRITE_REVIEWFORM_FOOTER_TEXT = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book." +COM_REDSHOP_AVG_RATINGS_1 = "Average based on" +COM_REDSHOP_AVG_RATINGS_2 = "customer review(s)." +COM_REDSHOP_SELECT_SHIP_ADDRESS = "Please enter or select your shipping address" +COM_REDSHOP_RETURNING_CUSTOMERS = "Returning Customers: Please Log In" +COM_REDSHOP_NEW_CUSTOMERS = "New customer? Please Provide Your Billing Information" +COM_REDSHOP_SEND_REGISTRATION = "Sign Up" +COM_REDSHOP_BTN_CHECKOUTNEXT = "Checkout: next step" +COM_REDSHOP_BTN_CHECKOUTFINAL = "Checkout: final step" +COM_REDSHOP_ADD = "Add" +COM_REDSHOP_CARD_INFORMATION = "Credit Card Information" +COM_REDSHOP_NAME_ON_CARD = "Card Holder Name" +COM_REDSHOP_CARD_NUM = "Card Number" +COM_REDSHOP_EXPIRY_DATE = "Expiration Date" +COM_REDSHOP_CARD_SECURITY_CODE = "Card Security Number" +COM_REDSHOP_ORDERTOTAL = "Order Total" +COM_REDSHOP_ORDER_RECEIPT = "Order Receipt" +COM_REDSHOP_ORDER_RECEIPT_TITLE = "Order Receipt" +COM_REDSHOP_EMPTY_CART = "Empty cart" +COM_REDSHOP_EMPTY = "Empty cart" +COM_REDSHOP_PAYMENT = "Payment" +COM_REDSHOP_RECEIPT = "Receipt" +COM_REDSHOP_SHIPPING_METHOD = "Shipping Method" +COM_REDSHOP_PAYMENT_METHOD = "Payment Method" +COM_REDSHOP_PAYMENT_METHOD_CONFLICT = "Payment Method Is Conflict" +COM_REDSHOP_PAYMENT_CREDIT_CARDS_NOT_FOUND = "No credit card option found, please check your payment plugin params." +COM_REDSHOP_PAYMENT_NO_CREDIT_CARDS_PLUGIN_LIST_FOUND = "No credit card plugins available." +COM_REDSHOP_SHIPPING_SAME_AS_BILLING = "Shipping address same as billing" +COM_REDSHOP_CHECKOUT_ERR_NO_CCDATA = "There is no CreditCard data..." +COM_REDSHOP_CHECKOUT_ERR_NO_CCNR_FOUND = "Credit Card Number not found!" +COM_REDSHOP_CHECKOUT_ERR_NO_MON_FOUND = "Credit card expiration month not found!" +COM_REDSHOP_CHECKOUT_ERR_NO_UNKNOWN_CCTYPE = "Unknown card type" +COM_REDSHOP_CHECKOUT_ERR_NO_CARD_PROVIDED = "No card number provided" +COM_REDSHOP_CHECKOUT_ERR_NO_CARD_INVALIDFORMAT = "Credit card number has invalid format" +COM_REDSHOP_CHECKOUT_ERR_NO_CARD_INVALIDNUMBER = "Credit card number is invalid" +COM_REDSHOP_CHECKOUT_ERR_NO_CARD_WRONGLENGTH = "Credit card number is wrong length" +COM_REDSHOP_CHECKOUT_VAT_LBL = "Tax :" +COM_REDSHOP_CHECKOUT_DISCOUNT_LBL = "Discount :" +COM_REDSHOP_CHECKOUT_SHIPPING_LBL = "Shipping :" +COM_REDSHOP_SELECT_PAYMENT_STATUS = "Select Payment Status" +COM_REDSHOP_PAYMENT_STA_PAID = "Paid" +COM_REDSHOP_PAYMENT_STA_UNPAID = "Unpaid" +COM_REDSHOP_PAYMENT_STA_PARTIAL_PAID = "Partial Paid" +COM_REDSHOP_RECEIPT_PARTIALLY_PAID_AMOUNT = "Partially Paid Amount" +COM_REDSHOP_REMAINING_PARTIALLY_AMOUNT = "Amount Remaining to pay" +COM_REDSHOP_EPAY_PAYMENT_TRANSACTION_SUCCESS = "The payment has been processed. You can review your order details here" +COM_REDSHOP_PLEASE_SELECT_TEMS_CONDITIONS = "Please accept Terms and conditions before clicking in the Checkout button." +COM_REDSHOP_TERMS_AND_CONDITIONS_LBL = "Accept Terms & conditions" +COM_REDSHOP_TERMS_AND_CONDITIONS_FOR_LBL = "For Webshop" +COM_REDSHOP_SELECT_PAYMENT_METHOD = "Select Payment Method" +COM_REDSHOP_EMPTY_PASSWORD = "Please enter a password" +COM_REDSHOP_ORDER_NUMBER_LBL = "Order Number" +COM_REDSHOP_ORDER_ID_LBL = "Order ID" +COM_REDSHOP_USER_REGISTRATION = "Private Person" +COM_REDSHOP_COMPANY_REGISTRATION = "Business" +COM_REDSHOP_REGISTRATION_HEADING = "Registration" +COM_REDSHOP_COMPANY_IS_NOT_VAT_EXEMPTED = "Company is not tax exempted" +COM_REDSHOP_COMPANY_IS_VAT_EXEMPTED = "Company is tax exempted" +COM_REDSHOP_BUSINESS_NUMBER = "Business Number" +COM_REDSHOP_SIGN_UP_FOR_NEWSLETTER = "Yes, Sign me up for the newsletter" +COM_REDSHOP_DELETE_PRODUCT_FROM_CART_LBL = "Delete product in cart" +COM_REDSHOP_UPDATE_PRODUCT_FROM_CART_LBL = "Update product in cart" +COM_REDSHOP_CHECKOUT = "Checkout" +COM_REDSHOP_VOUCHER_CODE = "Voucher code" +COM_REDSHOP_COUPEN_CODE = "Coupon Code" +COM_REDSHOP_SHOP_MORE = "Continue" +COM_REDSHOP_UPDATE = "Update" +COM_REDSHOP_SUBMIT_CODE = "Submit" +COM_REDSHOP_DISCOUNT_TEXT = "If you order for %s more, you will get at least %s DISCOUNT( %s )" +COM_REDSHOP_CART_TOTAL_PURCHASE_TBL = "Total purchases" +COM_REDSHOP_CART_COUPON_CODE_TBL = "GIFT CODE" +COM_REDSHOP_CART_DISCOUNT_CODE_TBL = "Discount Code" +COM_REDSHOP_CART_CHECKOUT = "Checkout" +COM_REDSHOP_PRODUCT_OUTOFSTOCK_MESSAGE = "Sorry, This product is out of stock...." +COM_REDSHOP_VIEW_CART = "View Cart" +COM_REDSHOP_CONTINUE_SHOPPING = "Continue Shopping" +COM_REDSHOP_CART_SAVE = "Display Cart" +COM_REDSHOP_CART_PRODUCT_ATTRIBUTE_CALCULATED_PRICE = "(+ %s)" +COM_REDSHOP_SHOW_CART_TEXT = "Your product(s) has been added to your cart" +COM_REDSHOP_IS_REQUIRED = "is Required." +COM_REDSHOP_ENTER_NUMBER = "Please Enter Numbers" +COM_REDSHOP_MINIMUM_ORDER_TOTAL_HAS_TO_BE_MORE_THAN = "Minimum order total has to be more than" +COM_REDSHOP_NAME = "Name" +COM_REDSHOP_SEND_TO_FRIEND = "Send to Friend" +COM_REDSHOP_SEND_FRIEND = "Send Friend" +COM_REDSHOP_YOUR_NAME = "Your Name" +COM_REDSHOP_FRIENDS_NAME = "Friend's name" +COM_REDSHOP_FRIENDS_EMAIL = "Friend's email" +COM_REDSHOP_PLEASE_ENTER_NAME = "Please enter your name." +COM_REDSHOP_PLEASE_ENTER_FRIENDS_NAME = "Please enter your friend's name." +COM_REDSHOP_PLEASE_ENTER_FRIENDS_EMAIL_ADDRESS = "Please enter your friend's email address." +COM_REDSHOP_EMAIL_HAS_BEEN_SENT_SUCCESSFULLY = "Email has been sent successfully" +COM_REDSHOP_EMAIL_HAS_NOT_BEEN_SENT_SUCCESSFULLY = "Email has not been sent successfully" +COM_REDSHOP_FILTER = "Filter" +COM_REDSHOP_ORDER_ID = "Order ID" +COM_REDSHOP_FULLNAME = "Full Name" +COM_REDSHOP_ORDER_STATUS = "Order Status" +COM_REDSHOP_ORDER_DATE = "Order Date" +COM_REDSHOP_ORDER_TOTAL = "Order Total" +COM_REDSHOP_ORDER = "Order" +COM_REDSHOP_INCLUDE_COMMENT_MSG = "Include this comment?" +COM_REDSHOP_NOTIFY_CUSTOMER_MSG = "Notify Customer?" +COM_REDSHOP_ORDER_PRODUCT_NOTE = "Note" +COM_REDSHOP_PRODUCT_QTY = "Quantity" +COM_REDSHOP_TOTAL_PRICE = "Total Price" +COM_REDSHOP_ORDER_SUBTOTAL = "Order Subtotal" +COM_REDSHOP_ORDER_TAX = "TAX" +COM_REDSHOP_ORDER_DISCOUNT = "Discount" +COM_REDSHOP_ORDER_SHIPPING = "Shipping" +COM_REDSHOP_ORDER_NUMBER = "Order Number" +COM_REDSHOP_BILLING_ADDRESS_INFORMATION = "Billing Address Information" +COM_REDSHOP_SHIPPING_ADDRESS_INFORMATION = "Shipping Address Information" +COM_REDSHOP_RESET = "Reset" +COM_REDSHOP_ORDER_DATE_LBL = "Order Date" +COM_REDSHOP_ORDER_STAUS_LBL = "Order Status" +COM_REDSHOP_PAYMENT_STAUS_LBL = "Payment Status" +COM_REDSHOP_ORDER_INFORMATION_LBL = "Order Information" +COM_REDSHOP_BILLING_ADDRESS_INFORMATION_LBL = "Billing Address Information" +COM_REDSHOP_SHIPPING_ADDRESS_INFO_LBL = "Shipping Address Information" +COM_REDSHOP_ORDER_DETAIL_LBL = "Order Details" +COM_REDSHOP_PRODUCT_NAME_LBL = "Name" +COM_REDSHOP_NOTE_LBL = "Note" +COM_REDSHOP_PRICE_LBL = "Price" +COM_REDSHOP_QUANTITY_LBL = "Quantity" +COM_REDSHOP_TOTAL_PRICE_LBL = "Total Price" +COM_REDSHOP_ORDER_SUBTOTAL_LBL = "Order Subtotal" +COM_REDSHOP_TOTAL_LBL = "Total" +COM_REDSHOP_CART_LBL = "Shopping Cart" +COM_REDSHOP_MINIMUM_DELIVERY_TIME = "Minimum Delivery Time" +COM_REDSHOP_MAXIMUM_DELIVERY_TIME = "Maximum Delivery Time" -COM_REDSHOP_QUANTITY="Quantity" -COM_REDSHOP_VOLUME="Volume" +COM_REDSHOP_QUANTITY = "Quantity" +COM_REDSHOP_VOLUME = "Volume" -COM_REDSHOP_SUBSCRIBE_SUCCESS="Please, check your emails for newsletter confirmation message" -COM_REDSHOP_MESSAGE_CONFIRMED_SUBSCRIBE="please, confirm your email for newsletter." -COM_REDSHOP_ALREADY_NEWSLETTER_SUBSCRIBER="Newsletter was correctly confirmed/email address match/or similar" -COM_REDSHOP_CANCLE_SUBSCRIPTION="Cancel Subscription" -COM_REDSHOP_CANCLE_SUBSCRIPTION_FAIL="Cancel Subscription Fail" -COM_REDSHOP_NEWSLETTER_SUBSCRIPTION="Newsletter Subscription" -COM_REDSHOP_SUBSCRIBE="Subscribe" -COM_REDSHOP_UNSUBSCRIBE="Unsubscribe" -COM_REDSHOP_NEWSLETTER="Newsletter" -COM_REDSHOP_ENTER_AN_EMAIL_ADDRESS="Enter an E-mail Address." -COM_REDSHOP_EMAIL_ADDRESS_NOT_VALID="Enter Valid E-mail Address." -COM_REDSHOP_ENTER_NAME="Enter an Name" -COM_REDSHOP_SELECT_CATALOG="Please choose catalog" -COM_REDSHOP_PRODUCT_ON_SALE="Product On Sale" -COM_REDSHOP_ORDER_ITEM="Order Item" -COM_REDSHOP_ORDER_NOT_FOUND="Order Not Found" -COM_REDSHOP_SHIPPING_NAME="Shipping Method Name" -COM_REDSHOP_SHIPPING_CLASS="Shipping Class" -COM_REDSHOP_SHIPPING_METHOD_MUST_HAVE_A_NAME="Shipping Method Must Have a Name." -COM_REDSHOP_SHIPPING_RATE_NAME="Shipping Rate Name" -COM_REDSHOP_SHIPPING_RATE_VOLUME_START="Volume Start" -COM_REDSHOP_SHIPPING_RATE_VOLUME_END="Volume End" -COM_REDSHOP_SHIPPING_RATE_ORDERTOTAL_START="Order Total Start" -COM_REDSHOP_SHIPPING_RATE_ORDERTOTAL_END="Order Total End" -COM_REDSHOP_SHIPPING_RATE_ZIP_START="Zip code start" -COM_REDSHOP_SHIPPING_RATE_ZIP_END="Zip code end" -COM_REDSHOP_SHIPPING_RATE_VALUE="Shipping Rate" -COM_REDSHOP_SHIPPING_RATE_PRIORITY="Shipping Priority" -COM_REDSHOP_SHIPPING_RATE_NAME_MUST_HAVE_A_NAME="Shipping Rate Name Must Have a Name." -COM_REDSHOP_SHIPPING_RATE_SAVED="Shipping Rate Saved" -COM_REDSHOP_SEARCH="Search" -COM_REDSHOP_GO="Go" -COM_REDSHOP_MSG_SORRY_NO_RESULT_FOUND="Sorry, No Result Found." -COM_REDSHOP_SAMPLE_SEND_SUCCSEEFULLY="Sample Sent Successfully" -COM_REDSHOP_VIEW_ALL_MANUFACTURER_PRODUCTS="View All Manufacturer Products" -COM_REDSHOP_SPECIAL_PRICE="Special Price:" -COM_REDSHOP_EPAY_PAYMENT_ERROR="Error in online payment - try again" -COM_REDSHOP_PHPSHOP_PAYMENT_ERROR="Error in online payment - try again" -COM_REDSHOP_PAY="Pay" -COM_REDSHOP_ALPHABETICALLY="Alphabetically" -COM_REDSHOP_EMAIL_TO_FRIEND="Send E-Mail to Friend" -COM_REDSHOP_EMAIL_TO="Your Friend E-Mail" -COM_REDSHOP_SENDER="Sender" -COM_REDSHOP_SUBJECT="Subject" -COM_REDSHOP_SEND="Send" -COM_REDSHOP_PLEASE_ENTER_EMAIL_TO="Please enter your friend's address" -COM_REDSHOP_PLEASE_ENTER_SENDER_NAME="Please enter Your Name" -COM_REDSHOP_PLEASE_ENTER_SENDER_EMAIL="Please enter Your E-Mail" -COM_REDSHOP_PLEASE_ENTER_SUBJECT="Please enter E-mail Subject" -COM_REDSHOP_SEND_SUCCESSFULLY="Send Successfully" -COM_REDSHOP_ERROR_SENDING="Error Sending E-Mail" -COM_REDSHOP_REMOVE_PRODUCT_FROM_WISHLIST="Remove Product" -COM_REDSHOP_SELECT_MANUFACTURE="Select Manufacturer" -COM_REDSHOP_CATALOG_SEND_SUCCSEEFULLY="Catalogue Sent Successfully" -COM_REDSHOP_SELECT_WRAPPER="Select wrapping" -COM_REDSHOP_ADD_WRAPPER="Add Wrapping" -COM_REDSHOP_WRAPPER="Wrapping" -COM_REDSHOP_JANUARY="January" -COM_REDSHOP_FEBRUARY="February" -COM_REDSHOP_MARCH="March" -COM_REDSHOP_APRIL="April" -COM_REDSHOP_MAY="May" -COM_REDSHOP_JUNE="June" -COM_REDSHOP_JULY="July" -COM_REDSHOP_AUGUST="August" -COM_REDSHOP_SEPTEMBER="September" -COM_REDSHOP_OCTOBER="October" -COM_REDSHOP_NOVEMBER="November" -COM_REDSHOP_DECEMBER="December" -COM_REDSHOP_JAN="Jan" -COM_REDSHOP_FEB="Feb" -COM_REDSHOP_MAR="Mar" -COM_REDSHOP_APR="Apr" -COM_REDSHOP_JUN="Jun" -COM_REDSHOP_JUL="Jul" -COM_REDSHOP_AUG="Aug" -COM_REDSHOP_SEP="Sep" -COM_REDSHOP_OCT="Oct" -COM_REDSHOP_NOV="Nov" -COM_REDSHOP_DEC="Dec" -COM_REDSHOP_MONDAY="Monday" -COM_REDSHOP_TUESDAY="Tuesday" -COM_REDSHOP_WEDNESDAY="Wednesday" -COM_REDSHOP_THURSDAY="Thursday" -COM_REDSHOP_FRIDAY="Friday" -COM_REDSHOP_SATURDAY="Saturday" -COM_REDSHOP_SUNDAY="Sunday" -COM_REDSHOP_MON="Mon" -COM_REDSHOP_TUE="Tue" -COM_REDSHOP_WED="Wed" -COM_REDSHOP_THU="Thu" -COM_REDSHOP_FRI="Fri" -COM_REDSHOP_SAT="Sat" -COM_REDSHOP_SUN="Sun" -COM_REDSHOP_SHIPPING_METHOD_LBL="Shipping Method Name" -COM_REDSHOP_CUSTOMER_NOTE_LBL="Customer Note" -COM_REDSHOP_PAYMENT_DISCOUNT_LBL="Payment Discount" -COM_REDSHOP_PAYMENT_CHARGES_LBL="Payment Charges" -COM_REDSHOP_THIRDPARTY_EMAIL_LBL="Third-party Email" -COM_REDSHOP_TEMPLATE_SELECTOR_CATEGORY_LBL="Switch Layout" -COM_REDSHOP_PRODUCT_NUMBER="Product Number" -COM_REDSHOP_PRODUCT_QUANTITY="Product Quantity" -COM_REDSHOP_ASK_QUESTION_ABOUT_PRODUCT="Ask Question About Product" -COM_REDSHOP_YOUR_EMAIL="Your Email" -COM_REDSHOP_YOUR_QUESTION="Your Question" -COM_REDSHOP_NO_PRODUCT_FOUND="No Product Found." -COM_REDSHOP_LOADING="Loading" -COM_REDSHOP_SAVE_WISHLIST="Save Wishlist" -COM_REDSHOP_WISHLIST_NAME="Wishlist Name" -COM_REDSHOP_CREATE_SAVE="Save" -COM_REDSHOP_PLEASE_ENTER_WISHLIST_NAME="Please Enter Wishlist Name" -COM_REDSHOP_CREATE_NEW_WISHLIST="Create New Wishlist" -COM_REDSHOP_PLEASE_SELECT_WISHLIST="Please Select Wishlist" -COM_REDSHOP_YOU_DONT_HAVE_ACCESS_TO_DELETE_THIS_PRODUCT="You don't have access to delete this product" -COM_REDSHOP_TOKEN_VARIFICATION="Token Verification" -COM_REDSHOP_DOWNLOAD_PRODUCTS="Downloadable Product Types" -COM_REDSHOP_TOKEN_ID="Token ID" -COM_REDSHOP_SUBMIT_TOKEN="Verify Token" -COM_REDSHOP_FILE_EXTENSION_NOT_ALLOWED="File extension is not legal." -COM_REDSHOP_NO_FILE_SELECTED="No file is Selected" -COM_REDSHOP_DOWNLOAD_LIMIT_OVER="Download Limit is Over" -COM_REDSHOP_DOWNLOADABLE_THIS_PRODUCT="Your Products for Download" -COM_REDSHOP_TOKEN_VERIFICATION_FAIL="Your Token is not Valid" -COM_REDSHOP_AREA="Area" -COM_REDSHOP_MILLIMETER="Millimetre" -COM_REDSHOP_CENTIMETER="Centimetre" -COM_REDSHOP_METER="Meter" -COM_REDSHOP_CIRCUMFERENCE="Circumference" -COM_REDSHOP_SAGEPAY_AUTHORISED="AUTHORISED - The transaction was successfully authorised with the bank." -COM_REDSHOP_SAGEPAY_MALFORMED="MALFORMED - The StatusDetail was malformed" -COM_REDSHOP_SAGEPAY_INVALID="INVALID - The StatusDetail was invalid" -COM_REDSHOP_SAGEPAY_DECLINED="DECLINED - The transaction was not authorised by the bank." -COM_REDSHOP_SAGEPAY_REJECTED="REJECTED - The transaction was failed by your 3D-Secure or AVS/CV2 rule-bases." -COM_REDSHOP_SAGEPAY_AUTHENTICATED="AUTHENTICATED - The transaction was successfully 3D-Secure Authenticated and can now be Authorised." -COM_REDSHOP_SAGEPAY_REGISTERED="REGISTERED - The transaction was could not be 3D-Secure Authenticated, but has been registered to be Authorised." -COM_REDSHOP_SAGEPAY_ERROR="ERROR - There was an error during the payment process." -COM_REDSHOP_SAGEPAY_UNKNOWN="UNKNOWN - An unknown status was returned from Sage Pay." -COM_REDSHOP_UPLOAD="Upload" -COM_REDSHOP_UPLOADING="Uploading" -COM_REDSHOP_UPLOADED_FILE="Uploaded File" -COM_REDSHOP_PLEASE_ENTER_PRODUCT_NUMBER="Please Enter Product Number" -COM_REDSHOP_SHIPPING_CALCULATOR="Shipping Calculator" -COM_REDSHOP_REQUEST_QUOTATION="Request a Quote" -COM_REDSHOP_REQUESTED="Requested" -COM_REDSHOP_REPLIED="Replied" -COM_REDSHOP_ACCEPTED="Accepted" -COM_REDSHOP_REJECTED="Rejected" -COM_REDSHOP_ORDERED="Ordered" -COM_REDSHOP_ACCEPT="Accept" -COM_REDSHOP_REJECT="Reject" -COM_REDSHOP_QUOTATION="Quotation" -COM_REDSHOP_VIEW_QUOTATION="View Quotation" -COM_REDSHOP_QUOTATION_ID="Quotation ID" -COM_REDSHOP_QUOTATION_STATUS="Quotation Status" -COM_REDSHOP_QUOTATION_DATE="Quotation Date" -COM_REDSHOP_QUOTATION_DETAIL="Quotation Detail" -COM_REDSHOP_QUOTATION_MANAGEMENT="Quotation Management" -COM_REDSHOP_QUOTATION_INFORMATION="Quotation Information" -COM_REDSHOP_QUOTATION_NUMBER="Quotation Number" -COM_REDSHOP_QUOTATION_IPADDRESS="Quotation IP Address" -COM_REDSHOP_QUOTATION_NOTE="Quotation Note" -COM_REDSHOP_QUOTATION_CUSTOMER_NOTE="Customer Note:" -COM_REDSHOP_QUOTATION_DETAILS="Quotation Details" -COM_REDSHOP_ERROR_SAVING_QUOTATION_DETAIL="Error Saving Quotation Detail" -COM_REDSHOP_ERROR_SENDING_QUOTATION_MAIL="Error sending Quotation mail" -COM_REDSHOP_QUOTATION_DETAIL_SENT="Quotation detail has been sent successfully" -COM_REDSHOP_CONFIRM_SEND_QUOTATION="Are you sure you want to submit Quotation?" -COM_REDSHOP_QUOTATION_SUBTOTAL="Quotation SubTotal" -COM_REDSHOP_QUOTATION_TAX="Quotation Tax" -COM_REDSHOP_QUOTATION_TOTAL="Quotation Total" -COM_REDSHOP_QUOTATION_ENCKEY_FAILURE="URL provided for Quote is not valid or Quotation is not existed" -COM_REDSHOP_QUOTATION_STATUS_UPDATED_SUCCESSFULLY="Quotation Status updated successfully" -COM_REDSHOP_NOACCESS_QUOTATION="You are not authorised to access this Quotation" -COM_REDSHOP_QUOTATION_DETAIL_SAVED="Quotation detail saved" -COM_REDSHOP_QUOTATION_DETAIL_EDITING_CANCELLED="Quotation detail editing cancelled" -COM_REDSHOP_QUOTATION_SENT_AND_USERNAME_PASSWORD_HAS_BEEN_MAILED="Quotation has been sent & username, password has been sent in your mail" -COM_REDSHOP_UNIT="Unit" -COM_REDSHOP_RADIUS="Radius" -COM_REDSHOP_HEIGHT="Height" -COM_REDSHOP_WIDTH="Width" -COM_REDSHOP_LENGTH="Length" -COM_REDSHOP_CALCULATE="Calculate" -COM_REDSHOP_TOTAL_PIECE="Total Piece:" -COM_REDSHOP_TOTAL_AREA="Total Area:" -COM_REDSHOP_PRICE_PER_PIECE="Price Per Piece:" -COM_REDSHOP_PRICE_OF_ALL_PIECE="Price of all Piece:" -COM_REDSHOP_PRICE_TOTAL="Total Price:" -COM_REDSHOP_PRICE_PER_AREA="Price Per Area:" -COM_REDSHOP_SHIPPING_BOXES="Shipping Boxes" -COM_REDSHOP_NO_SHIPPING_BOX="No Shipping Box" -COM_REDSHOP_YOU_ARE_NOT_AUTHORIZED_TO_ACCESS="Sorry, You are not authorised to access this file." -COM_REDSHOP_XMLFILE_IS_UNPUBLISHED="Sorry, XML file is unpublished." -COM_REDSHOP_AUTHENTICATIONFAIL="Shopper Group has no access to this page" -COM_REDSHOP_PRICE_INCLUDING_TAX="(price including tax)" -COM_REDSHOP_PRICE_EXCLUDING_TAX="(price excluding tax)" -COM_REDSHOP_STOCK_AMOUNT="Stock Amount" -COM_REDSHOP_STOCK_AMOUNT_LEFT="%s products left" -COM_REDSHOP_COUPON_CODE_IS_NOT_VALID="The discount code is not valid" -COM_REDSHOP_VOUCHER_CODE_IS_NOT_VALID="The voucher discount code is note valid" -COM_REDSHOP_DISCOUNT_CODE_IS_VALID="The discount code is valid" -COM_REDSHOP_DISCOUNT_CODE_IS_VALID_NOT_APPLY_PRODUCTS_ON_SALE="The discount code is valid. Please notice that discount code do not apply to products on sale" -COM_REDSHOP_PLEASE_SELECT_DISCOUNT_TYPE="Please select a discount type" -COM_REDSHOP_ORDER_NOT_PLACED="Order not placed yet." -COM_REDSHOP_ORDER_PLACED="Order placed." -COM_REDSHOP_DEFAULT_SHOPPER_GROUP_SHIPPING="Default Shopper Group Shipping" -COM_REDSHOP_TRANSACTION_APPROVED="This transaction has been approved." -COM_REDSHOP_TRANSACTION_DECLINE="This transaction has been declined." -COM_REDSHOP_CAPTCHA="Captcha" -COM_REDSHOP_FRONT_IMAGE="Front Image" -COM_REDSHOP_BACK_IMAGE="Back Image" -COM_REDSHOP_NO_ATTRIBUTE_TO_CHANGE="No Attribute to change" -COM_REDSHOP_CHANGE_ATTRIBUTE="Change Attribute" -COM_REDSHOP_SELECT_PRODUCT_SUBSCRIPTION="Select product subscription" -COM_REDSHOP_PRODUCT_USERFIELD="Product Userfield" -COM_REDSHOP_CONFIRM_CART_EMPTY="Are you sure want to reorder? It will empty Current cart." -COM_REDSHOP_REORDER="Reorder" -COM_REDSHOP_FILE_NOT_AVAILABLE_IN_DB="File not available in database" -COM_REDSHOP_PLEASE_SELECT_YOUR="Please select your" -COM_REDSHOP_RETYPE_CUSTOMER_EMAIL="Retype Email Address" -COM_REDSHOP_ACCESSORY_QUANTITY_LBL="Accessory Quantity" -COM_REDSHOP_PRODUCT_ADDED_TO_CART="Product has been added to your cart." -COM_REDSHOP_USER_REQUEST_TAX_EXEMPT_LBL="User requested Tax exempt" -COM_REDSHOP_TOOLTIP_USER_REQUEST_TAX_EXEMPT="User requested Tax exempt" -COM_REDSHOP_PROPERTY_IMAGE_LBL="Property Image" -COM_REDSHOP_VIRTUAL_NUMBER_LBL="Virtual Number" -COM_REDSHOP_PROPERTY_NAME_LBL="Property Name" -COM_REDSHOP_PROPERTY_PRICE_LBL="Property Price" -COM_REDSHOP_PROPERTY_STOCK_LBL="Property Stock" -COM_REDSHOP_ADD_TO_CART_LBL="Add To Cart" -COM_REDSHOP_IN_STOCK="In Stock" -COM_REDSHOP_NOT_IN_STOCK="Not In Stock" -COM_REDSHOP_PRODUCT_DATE_FIELD_EXPIRED="Product Date Expired" -COM_REDSHOP_PRODUCT_DIAMETER_LBL="Diameter" -COM_REDSHOP_USER_TAX_EXEMPT_REQUEST_LBL="User tax exempt Request" -COM_REDSHOP_SUBTOTAL_EXCL_VAT_LBL="Subtotal Excluding Tax" -COM_REDSHOP_NEWSLETTER_NOT_AVAILABLE="Newsletter is not available" -COM_REDSHOP_USER_INFORMATION_NOT_MATCH="User country, state, zipcode might not be matched..." -COM_REDSHOP_PRODUCT_DETAIL_NOT_MATCH="Product or product category might not be shipped into this county." -COM_REDSHOP_CART_DIMENTION_NOT_MATCH="Cart volume(weight,height,length), order total might not be matched...." -COM_REDSHOP_VIEW_MANUFACTURER="View Manufacturer" -COM_REDSHOP_ADD_TO_CART_TOOLTIP="Add To Cart" -COM_REDSHOP_REQUEST_A_QUOTE_TOOLTIP="Request a Quote" -COM_REDSHOP_REQUEST_A_QUOTE="Request a Quote" -COM_REDSHOP_YOU_NEED_TO_LOGIN_TO_POST_A_REVIEW="You need to log in to write review" -COM_REDSHOP_YOUR_MUST_PROVIDE_A_ADDRESS="Please enter address" -COM_REDSHOP_YOUR_MUST_PROVIDE_A_ZIP="Please enter post code" -COM_REDSHOP_YOUR_MUST_PROVIDE_A_CITY="Please enter city" -COM_REDSHOP_YOUR_MUST_PROVIDE_A_PHONE="Please enter the phone" -COM_REDSHOP_YOUR_MUST_PROVIDE_A_FIRSTNAME="Please enter first name" -COM_REDSHOP_YOUR_MUST_PROVIDE_A_LASTNAME="Please enter last name" -COM_REDSHOP_YOU_MUST_PROVIDE_LOGIN_NAME="Please enter username" -COM_REDSHOP_PROVIDE_EMAIL_ADDRESS="Please enter email address" -COM_REDSHOP_EMAIL_NOT_MATCH="Email address do not match" -COM_REDSHOP_THIS_FIELD_IS_REQUIRED="This field is required" -COM_REDSHOP_DENOTATION_TXT="* Values denoted are vat exempt and will be calculated accordingly." -COM_REDSHOP_SHIPPING_TEXT_LBL="If you order for %s more, you will get free shipping" -COM_REDSHOP_FREE_SHIPPING_RATE_IS_IN_USED="Free shipping rate is in used" -COM_REDSHOP_NO_SHIPPING_RATE_AVAILABLE="No Free shipping rate is available." -COM_REDSHOP_OUT_OF_STOCK="Out of Stock." -COM_REDSHOP_AVAILABLE_STOCK="In Stock." -COM_REDSHOP_BACK_BUTTON="Back" -COM_REDSHOP_PRODUCT_SUBTOTAL_LBL="Subtotal" -COM_REDSHOP_PRODUCT_SUBTOTAL_EXCL_LBL="Subtotal excl vat" -COM_REDSHOP_SHIPPING_WITH_VAT_LBL="Shipping with vat" -COM_REDSHOP_SHIPPING_EXCL_VAT_LBL="Shipping excl vat" -COM_REDSHOP_PRODUCT_PRICE_EXCL_LBL="Price excl" -COM_REDSHOP_NO_SHIPPING_RATE_AVAILABLE_WHEN_NOPRODUCT_IN_CART="No free shipping rate is available since there is no product in cart" -COM_REDSHOP_NOT_AVAILABLE="Not Available" -COM_REDSHOP_GO_BACK="Go Back" -COM_REDSHOP_DISCOUNT_CALC_HEIGHT="Height:" -COM_REDSHOP_DISCOUNT_CALC_WIDTH="Width:" -COM_REDSHOP_DISCOUNT_CALC_LENGTH="Length:" -COM_REDSHOP_DISCOUNT_CALC_RADIUS="Radius:" -COM_REDSHOP_DISCOUNT_CALC_UNIT="Unit:" -COM_REDSHOP_DISCOUNT_CALC_DEPTH="Depth:" -COM_REDSHOP_PLEASE_INSERT_HEIGHT="Please Insert Height" -COM_REDSHOP_PLEASE_INSERT_WIDTH="Please Insert Width" -COM_REDSHOP_PLEASE_INSERT_DEPTH="Please Insert Depth" -COM_REDSHOP_PLEASE_INSERT_RADIUS="Please Insert Radius" -COM_REDSHOP_PLEASE_INSERT_UNIT="Please Insert Unit" -COM_REDSHOP_SELECT_SUBSCRIPTION_PLAN="Please Select Your Subscription Plan" -COM_REDSHOP_VIEW_FULL_SIZE_IMAGE_LBL="View Full-Size Image" -COM_REDSHOP_WARNING_MSG_MAXIMUM_QUANTITY="Product is not available more than %s amount." -COM_REDSHOP_WARNING_MSG_MINIMUM_QUANTITY="Product is not available less than %s amount." -COM_REDSHOP_CHECKOUT_ERR_NO_CCNM_FOUND="Numeric value not accepted in card name." -COM_REDSHOP_CHECKOUT_ERR_NO_CCNR_NUM_FOUND="Only numeric value accepted in card number." -COM_REDSHOP_PRODUCT_IS_EXPIRED="%s(%s) is Expired" -COM_REDSHOP_PROVIDE_CORRECT_EMAIL_ADDRESS="Please enter a valid email address." -COM_REDSHOP_RELATED_PRODUCT_LIST_IN_LIGHTBOX="Related Product List" -COM_REDSHOP_NEWSLEETER_SUBSCRIBE_SUCCESS="You are successfully subscribed for newsletter." -COM_REDSHOP_PREORDER_PRODUCT_OUTOFSTOCK_MESSAGE="Sorry.... Pre-order Stock is out of Order." -COM_REDSHOP_SUBSCRIPTION_PERIOD="Subscription Period" -COM_REDSHOP_SUBSCRIPTION_PRICE="Subscription Price" -COM_REDSHOP_DEBITOR_NUMBER="Debtor Number" -COM_REDSHOP_PASSWORD_MIN_CHARACTER_LIMIT="Your password must be at least 5 characters long" -COM_REDSHOP_PRODUCT_NOT_ADDED_TO_CART="Product was not added to cart" -COM_REDSHOP_ERROR_CATALOG_SEND_SUCCSEEFULLY="Error Sending Catalogue Successfully" -COM_REDSHOP_SHOPPERGROUP_NOT_MATCH="Shopper group not match" -COM_REDSHOP_ERROR_SAMPLE_SEND_SUCCSEEFULLY="Error Sample Send Successfully" -COM_REDSHOP_PRODUCT_NOT_SAVED_IN_WISHLIST="Product was not saved in wishlist" -COM_REDSHOP_DOWNLOAD_TOKEN="Download Token" -COM_REDSHOP_DOWNLOAD_LEFT="Download(s) Left" -COM_REDSHOP_DOWNLOAD_ENDDATE="Download End Date" -COM_REDSHOP_ON="On" -COM_REDSHOP_FROM="From" -COM_REDSHOP_DOWNLOAD_LOG="Download Log" -COM_REDSHOP_QUOTATION_DISCOUNT_LBL="Quote Discount" -COM_REDSHOP_MONTH="Month" -COM_REDSHOP_PLEASE_SELECT_YOUR_SUBSCRIPTION_PLAN="Please select your subscription plan" -COM_REDSHOP_PRODUCT_NAME_ASC="Sort by product name asc" -COM_REDSHOP_PRODUCT_NAME_DESC="Sort by product name desc" -COM_REDSHOP_PRODUCT_NUMBER_ASC="Sort by product number asc" -COM_REDSHOP_PRODUCT_NUMBER_DESC="Sort by product number desc" -COM_REDSHOP_ORDERING_ASC="Sort order by asc" -COM_REDSHOP_ORDERING_DESC="Sort order by desc" -COM_REDSHOP_DATEPICKER_ASC="Date picker Asc" -COM_REDSHOP_DATEPICKER_DESC="Date picker Desc" -COM_REDSHOP_PRODUCT_ID_ASC="Sort by product ID asc" -COM_REDSHOP_PRODUCT_ID_DESC="Sort by product ID desc" -COM_REDSHOP_ACCESSORY_ID_ASC="Sort Accessories by ID Asc" -COM_REDSHOP_ACCESSORY_ID_DESC="Sort Accessories by ID Desc" -COM_REDSHOP_ACCESSORY_PRICE_ASC="Sort Accessories by Price Asc" -COM_REDSHOP_ACCESSORY_PRICE_DESC="Sort Accessories by Price Desc" -COM_REDSHOP_GLOBAL="Global" -COM_REDSHOP_CHILD_PRODUCT_NAME="Child Product Name" -COM_REDSHOP_CHILD_PRODUCT_NUMBER="Child Product Number" -COM_REDSHOP_TWO_LETTER_ABBRIVATION="Two Letter Abbreviation" -COM_REDSHOP_THREE_LETTER_ABBRIVATION="Three Letter Abbreviation" -COM_REDSHOP_NONE="None" -COM_REDSHOP_PRICE="Price" -COM_REDSHOP_TO="To" -COM_REDSHOP_COMPARE="Compare" -COM_REDSHOP_DELETE="Delete" -COM_REDSHOP_PASSWORDS_DO_NOT_MATCH="Passwords do not match" -COM_REDSHOP_ACCESS_FORBIDDEN="Access Forbidden" -COM_REDSHOP_INVALID_SECURITY="Sorry, you have provided an invalid security code." -COM_REDSHOP_SECURITY_CODE="Security Code :" -COM_REDSHOP_PRODUCT_IS_NOT_FOR_SALE="%s(%s) is Not For Sale" -COM_REDSHOP_ZIPCODE="ZIP code" -COM_REDSHOP_REG_COMPLETE_ACTIVATE="Registration Complete Activate" -COM_REDSHOP_REG_COMPLETE="Registration complete" -COM_REDSHOP_SEARCH_RESULT="Search results" -COM_REDSHOP_CLEAR_ALL="Clear All" -COM_REDSHOP_SEARCH_CRITERIA="Search criteria" -COM_REDSHOP_BULK_ORDER_LINK="Bulk order link" -COM_REDSHOP_BULK_ORDER="Bulk order" -COM_REDSHOP_CANCEL="Cancel" -COM_REDSHOP_SAVE="Save" -COM_REDSHOP_="Redshop" -COM_REDSHOP_ALERTNOTAUTH="Alert: You are not authorised" -COM_REDSHOP_PLEASE_ENTER_YOUR_NAME="Please enter your name" -COM_REDSHOP_APPLY="Apply" -COM_REDSHOP_EDIT="Edit" -COM_REDSHOP_TEMPLATE_NOT_EXISTS="Template not exists" -COM_REDSHOP_CUSTOMER_QUANTITY_LBL="Quantity" -COM_REDSHOP_CUSTOMER_AMOUNT_LBL="Amount" -COM_REDSHOP_REDSHOP="redSHOP" -COM_REDSHOP_LOGIN="Log in" -COM_REDSHOP_LOGOUT_SUCCESS="Logout success" -COM_REDSHOP_MANUFACTURER="Manufacturer" -COM_REDSHOP_MANUFACTURER_DETAIL="Manufacturer Details" -COM_REDSHOP_MANUFACTURER_PRODUCTS="Manufacturer Products" -COM_REDSHOP_ENTER_A_NAME="Enter a name" -COM_REDSHOP_PRODCUT_PRICE_YOU_SAVED="Product Price You Saved" -COM_REDSHOP_CATEGORY="Category" -COM_REDSHOP_NUM="Num" -COM_REDSHOP_PRODUCT="Product" -COM_REDSHOP_ACCOUNT_CREATION="Account Creation" -COM_REDSHOP_SUBMIT="Submit" -COM_REDSHOP_REGISTRATION_INTROTEXT="Registration intro text" -COM_REDSHOP_REGISTRATION_COMPANY_INTROTEXT="Company registration intro text" +COM_REDSHOP_SUBSCRIBE_SUCCESS = "Please, check your emails for newsletter confirmation message" +COM_REDSHOP_MESSAGE_CONFIRMED_SUBSCRIBE = "please, confirm your email for newsletter." +COM_REDSHOP_ALREADY_NEWSLETTER_SUBSCRIBER = "Newsletter was correctly confirmed/email address match/or similar" +COM_REDSHOP_CANCLE_SUBSCRIPTION = "Cancel Subscription" +COM_REDSHOP_CANCLE_SUBSCRIPTION_FAIL = "Cancel Subscription Fail" +COM_REDSHOP_NEWSLETTER_SUBSCRIPTION = "Newsletter Subscription" +COM_REDSHOP_SUBSCRIBE = "Subscribe" +COM_REDSHOP_UNSUBSCRIBE = "Unsubscribe" +COM_REDSHOP_NEWSLETTER = "Newsletter" +COM_REDSHOP_ENTER_AN_EMAIL_ADDRESS = "Enter an E-mail Address." +COM_REDSHOP_EMAIL_ADDRESS_NOT_VALID = "Enter Valid E-mail Address." +COM_REDSHOP_ENTER_NAME = "Enter an Name" +COM_REDSHOP_SELECT_CATALOG = "Please choose catalog" +COM_REDSHOP_PRODUCT_ON_SALE = "Product On Sale" +COM_REDSHOP_ORDER_ITEM = "Order Item" +COM_REDSHOP_ORDER_NOT_FOUND = "Order Not Found" +COM_REDSHOP_SHIPPING_NAME = "Shipping Method Name" +COM_REDSHOP_SHIPPING_CLASS = "Shipping Class" +COM_REDSHOP_SHIPPING_METHOD_MUST_HAVE_A_NAME = "Shipping Method Must Have a Name." +COM_REDSHOP_SHIPPING_RATE_NAME = "Shipping Rate Name" +COM_REDSHOP_SHIPPING_RATE_VOLUME_START = "Volume Start" +COM_REDSHOP_SHIPPING_RATE_VOLUME_END = "Volume End" +COM_REDSHOP_SHIPPING_RATE_ORDERTOTAL_START = "Order Total Start" +COM_REDSHOP_SHIPPING_RATE_ORDERTOTAL_END = "Order Total End" +COM_REDSHOP_SHIPPING_RATE_ZIP_START = "Zip code start" +COM_REDSHOP_SHIPPING_RATE_ZIP_END = "Zip code end" +COM_REDSHOP_SHIPPING_RATE_VALUE = "Shipping Rate" +COM_REDSHOP_SHIPPING_RATE_PRIORITY = "Shipping Priority" +COM_REDSHOP_SHIPPING_RATE_NAME_MUST_HAVE_A_NAME = "Shipping Rate Name Must Have a Name." +COM_REDSHOP_SHIPPING_RATE_SAVED = "Shipping Rate Saved" +COM_REDSHOP_SEARCH = "Search" +COM_REDSHOP_GO = "Go" +COM_REDSHOP_MSG_SORRY_NO_RESULT_FOUND = "Sorry, No Result Found." +COM_REDSHOP_SAMPLE_SEND_SUCCSEEFULLY = "Sample Sent Successfully" +COM_REDSHOP_VIEW_ALL_MANUFACTURER_PRODUCTS = "View All Manufacturer Products" +COM_REDSHOP_SPECIAL_PRICE = "Special Price:" +COM_REDSHOP_EPAY_PAYMENT_ERROR = "Error in online payment - try again" +COM_REDSHOP_PHPSHOP_PAYMENT_ERROR = "Error in online payment - try again" +COM_REDSHOP_PAY = "Pay" +COM_REDSHOP_ALPHABETICALLY = "Alphabetically" +COM_REDSHOP_EMAIL_TO_FRIEND = "Send E-Mail to Friend" +COM_REDSHOP_EMAIL_TO = "Your Friend E-Mail" +COM_REDSHOP_SENDER = "Sender" +COM_REDSHOP_SUBJECT = "Subject" +COM_REDSHOP_SEND = "Send" +COM_REDSHOP_PLEASE_ENTER_EMAIL_TO = "Please enter your friend's address" +COM_REDSHOP_PLEASE_ENTER_SENDER_NAME = "Please enter Your Name" +COM_REDSHOP_PLEASE_ENTER_SENDER_EMAIL = "Please enter Your E-Mail" +COM_REDSHOP_PLEASE_ENTER_SUBJECT = "Please enter E-mail Subject" +COM_REDSHOP_SEND_SUCCESSFULLY = "Send Successfully" +COM_REDSHOP_ERROR_SENDING = "Error Sending E-Mail" +COM_REDSHOP_REMOVE_PRODUCT_FROM_WISHLIST = "Remove Product" +COM_REDSHOP_SELECT_MANUFACTURE = "Select Manufacturer" +COM_REDSHOP_CATALOG_SEND_SUCCSEEFULLY = "Catalogue Sent Successfully" +COM_REDSHOP_SELECT_WRAPPER = "Select wrapping" +COM_REDSHOP_ADD_WRAPPER = "Add Wrapping" +COM_REDSHOP_WRAPPER = "Wrapping" +COM_REDSHOP_JANUARY = "January" +COM_REDSHOP_FEBRUARY = "February" +COM_REDSHOP_MARCH = "March" +COM_REDSHOP_APRIL = "April" +COM_REDSHOP_MAY = "May" +COM_REDSHOP_JUNE = "June" +COM_REDSHOP_JULY = "July" +COM_REDSHOP_AUGUST = "August" +COM_REDSHOP_SEPTEMBER = "September" +COM_REDSHOP_OCTOBER = "October" +COM_REDSHOP_NOVEMBER = "November" +COM_REDSHOP_DECEMBER = "December" +COM_REDSHOP_JAN = "Jan" +COM_REDSHOP_FEB = "Feb" +COM_REDSHOP_MAR = "Mar" +COM_REDSHOP_APR = "Apr" +COM_REDSHOP_JUN = "Jun" +COM_REDSHOP_JUL = "Jul" +COM_REDSHOP_AUG = "Aug" +COM_REDSHOP_SEP = "Sep" +COM_REDSHOP_OCT = "Oct" +COM_REDSHOP_NOV = "Nov" +COM_REDSHOP_DEC = "Dec" +COM_REDSHOP_MONDAY = "Monday" +COM_REDSHOP_TUESDAY = "Tuesday" +COM_REDSHOP_WEDNESDAY = "Wednesday" +COM_REDSHOP_THURSDAY = "Thursday" +COM_REDSHOP_FRIDAY = "Friday" +COM_REDSHOP_SATURDAY = "Saturday" +COM_REDSHOP_SUNDAY = "Sunday" +COM_REDSHOP_MON = "Mon" +COM_REDSHOP_TUE = "Tue" +COM_REDSHOP_WED = "Wed" +COM_REDSHOP_THU = "Thu" +COM_REDSHOP_FRI = "Fri" +COM_REDSHOP_SAT = "Sat" +COM_REDSHOP_SUN = "Sun" +COM_REDSHOP_SHIPPING_METHOD_LBL = "Shipping Method Name" +COM_REDSHOP_CUSTOMER_NOTE_LBL = "Customer Note" +COM_REDSHOP_PAYMENT_DISCOUNT_LBL = "Payment Discount" +COM_REDSHOP_PAYMENT_CHARGES_LBL = "Payment Charges" +COM_REDSHOP_THIRDPARTY_EMAIL_LBL = "Third-party Email" +COM_REDSHOP_TEMPLATE_SELECTOR_CATEGORY_LBL = "Switch Layout" +COM_REDSHOP_PRODUCT_NUMBER = "Product Number" +COM_REDSHOP_PRODUCT_QUANTITY = "Product Quantity" +COM_REDSHOP_ASK_QUESTION_ABOUT_PRODUCT = "Ask Question About Product" +COM_REDSHOP_YOUR_EMAIL = "Your Email" +COM_REDSHOP_YOUR_QUESTION = "Your Question" +COM_REDSHOP_NO_PRODUCT_FOUND = "No Product Found." +COM_REDSHOP_LOADING = "Loading" +COM_REDSHOP_SAVE_WISHLIST = "Save Wishlist" +COM_REDSHOP_WISHLIST_NAME = "Wishlist Name" +COM_REDSHOP_CREATE_SAVE = "Save" +COM_REDSHOP_PLEASE_ENTER_WISHLIST_NAME = "Please Enter Wishlist Name" +COM_REDSHOP_CREATE_NEW_WISHLIST = "Create New Wishlist" +COM_REDSHOP_PLEASE_SELECT_WISHLIST = "Please Select Wishlist" +COM_REDSHOP_YOU_DONT_HAVE_ACCESS_TO_DELETE_THIS_PRODUCT = "You don't have access to delete this product" +COM_REDSHOP_TOKEN_VARIFICATION = "Token Verification" +COM_REDSHOP_DOWNLOAD_PRODUCTS = "Downloadable Product Types" +COM_REDSHOP_TOKEN_ID = "Token ID" +COM_REDSHOP_SUBMIT_TOKEN = "Verify Token" +COM_REDSHOP_FILE_EXTENSION_NOT_ALLOWED = "File extension is not legal." +COM_REDSHOP_NO_FILE_SELECTED = "No file is Selected" +COM_REDSHOP_DOWNLOAD_LIMIT_OVER = "Download Limit is Over" +COM_REDSHOP_DOWNLOADABLE_THIS_PRODUCT = "Your Products for Download" +COM_REDSHOP_TOKEN_VERIFICATION_FAIL = "Your Token is not Valid" +COM_REDSHOP_AREA = "Area" +COM_REDSHOP_MILLIMETER = "Millimetre" +COM_REDSHOP_CENTIMETER = "Centimetre" +COM_REDSHOP_METER = "Meter" +COM_REDSHOP_CIRCUMFERENCE = "Circumference" +COM_REDSHOP_SAGEPAY_AUTHORISED = "AUTHORISED - The transaction was successfully authorised with the bank." +COM_REDSHOP_SAGEPAY_MALFORMED = "MALFORMED - The StatusDetail was malformed" +COM_REDSHOP_SAGEPAY_INVALID = "INVALID - The StatusDetail was invalid" +COM_REDSHOP_SAGEPAY_DECLINED = "DECLINED - The transaction was not authorised by the bank." +COM_REDSHOP_SAGEPAY_REJECTED = "REJECTED - The transaction was failed by your 3D-Secure or AVS/CV2 rule-bases." +COM_REDSHOP_SAGEPAY_AUTHENTICATED = "AUTHENTICATED - The transaction was successfully 3D-Secure Authenticated and can now be Authorised." +COM_REDSHOP_SAGEPAY_REGISTERED = "REGISTERED - The transaction was could not be 3D-Secure Authenticated, but has been registered to be Authorised." +COM_REDSHOP_SAGEPAY_ERROR = "ERROR - There was an error during the payment process." +COM_REDSHOP_SAGEPAY_UNKNOWN = "UNKNOWN - An unknown status was returned from Sage Pay." +COM_REDSHOP_UPLOAD = "Upload" +COM_REDSHOP_UPLOADING = "Uploading" +COM_REDSHOP_UPLOADED_FILE = "Uploaded File" +COM_REDSHOP_PLEASE_ENTER_PRODUCT_NUMBER = "Please Enter Product Number" +COM_REDSHOP_SHIPPING_CALCULATOR = "Shipping Calculator" +COM_REDSHOP_REQUEST_QUOTATION = "Request a Quote" +COM_REDSHOP_REQUESTED = "Requested" +COM_REDSHOP_REPLIED = "Replied" +COM_REDSHOP_ACCEPTED = "Accepted" +COM_REDSHOP_REJECTED = "Rejected" +COM_REDSHOP_ORDERED = "Ordered" +COM_REDSHOP_ACCEPT = "Accept" +COM_REDSHOP_REJECT = "Reject" +COM_REDSHOP_QUOTATION = "Quotation" +COM_REDSHOP_VIEW_QUOTATION = "View Quotation" +COM_REDSHOP_QUOTATION_ID = "Quotation ID" +COM_REDSHOP_QUOTATION_STATUS = "Quotation Status" +COM_REDSHOP_QUOTATION_DATE = "Quotation Date" +COM_REDSHOP_QUOTATION_DETAIL = "Quotation Detail" +COM_REDSHOP_QUOTATION_MANAGEMENT = "Quotation Management" +COM_REDSHOP_QUOTATION_INFORMATION = "Quotation Information" +COM_REDSHOP_QUOTATION_NUMBER = "Quotation Number" +COM_REDSHOP_QUOTATION_IPADDRESS = "Quotation IP Address" +COM_REDSHOP_QUOTATION_NOTE = "Quotation Note" +COM_REDSHOP_QUOTATION_CUSTOMER_NOTE = "Customer Note:" +COM_REDSHOP_QUOTATION_DETAILS = "Quotation Details" +COM_REDSHOP_ERROR_SAVING_QUOTATION_DETAIL = "Error Saving Quotation Detail" +COM_REDSHOP_ERROR_SENDING_QUOTATION_MAIL = "Error sending Quotation mail" +COM_REDSHOP_QUOTATION_DETAIL_SENT = "Quotation detail has been sent successfully" +COM_REDSHOP_CONFIRM_SEND_QUOTATION = "Are you sure you want to submit Quotation?" +COM_REDSHOP_QUOTATION_SUBTOTAL = "Quotation SubTotal" +COM_REDSHOP_QUOTATION_TAX = "Quotation Tax" +COM_REDSHOP_QUOTATION_TOTAL = "Quotation Total" +COM_REDSHOP_QUOTATION_ENCKEY_FAILURE = "URL provided for Quote is not valid or Quotation is not existed" +COM_REDSHOP_QUOTATION_STATUS_UPDATED_SUCCESSFULLY = "Quotation Status updated successfully" +COM_REDSHOP_NOACCESS_QUOTATION = "You are not authorised to access this Quotation" +COM_REDSHOP_QUOTATION_DETAIL_SAVED = "Quotation detail saved" +COM_REDSHOP_QUOTATION_DETAIL_EDITING_CANCELLED = "Quotation detail editing cancelled" +COM_REDSHOP_QUOTATION_SENT_AND_USERNAME_PASSWORD_HAS_BEEN_MAILED = "Quotation has been sent & username, password has been sent in your mail" +COM_REDSHOP_UNIT = "Unit" +COM_REDSHOP_RADIUS = "Radius" +COM_REDSHOP_HEIGHT = "Height" +COM_REDSHOP_WIDTH = "Width" +COM_REDSHOP_LENGTH = "Length" +COM_REDSHOP_CALCULATE = "Calculate" +COM_REDSHOP_TOTAL_PIECE = "Total Piece:" +COM_REDSHOP_TOTAL_AREA = "Total Area:" +COM_REDSHOP_PRICE_PER_PIECE = "Price Per Piece:" +COM_REDSHOP_PRICE_OF_ALL_PIECE = "Price of all Piece:" +COM_REDSHOP_PRICE_TOTAL = "Total Price:" +COM_REDSHOP_PRICE_PER_AREA = "Price Per Area:" +COM_REDSHOP_SHIPPING_BOXES = "Shipping Boxes" +COM_REDSHOP_NO_SHIPPING_BOX = "No Shipping Box" +COM_REDSHOP_YOU_ARE_NOT_AUTHORIZED_TO_ACCESS = "Sorry, You are not authorised to access this file." +COM_REDSHOP_XMLFILE_IS_UNPUBLISHED = "Sorry, XML file is unpublished." +COM_REDSHOP_AUTHENTICATIONFAIL = "Shopper Group has no access to this page" +COM_REDSHOP_PRICE_INCLUDING_TAX = "(price including tax)" +COM_REDSHOP_PRICE_EXCLUDING_TAX = "(price excluding tax)" +COM_REDSHOP_STOCK_AMOUNT = "Stock Amount" +COM_REDSHOP_STOCK_AMOUNT_LEFT = "%s products left" +COM_REDSHOP_COUPON_CODE_IS_NOT_VALID = "The discount code is not valid" +COM_REDSHOP_VOUCHER_CODE_IS_NOT_VALID = "The voucher discount code is note valid" +COM_REDSHOP_DISCOUNT_CODE_IS_VALID = "The discount code is valid" +COM_REDSHOP_DISCOUNT_CODE_IS_VALID_NOT_APPLY_PRODUCTS_ON_SALE = "The discount code is valid. Please notice that discount code do not apply to products on sale" +COM_REDSHOP_PLEASE_SELECT_DISCOUNT_TYPE = "Please select a discount type" +COM_REDSHOP_ORDER_NOT_PLACED = "Order not placed yet." +COM_REDSHOP_ORDER_PLACED = "Order placed." +COM_REDSHOP_DEFAULT_SHOPPER_GROUP_SHIPPING = "Default Shopper Group Shipping" +COM_REDSHOP_TRANSACTION_APPROVED = "This transaction has been approved." +COM_REDSHOP_TRANSACTION_DECLINE = "This transaction has been declined." +COM_REDSHOP_CAPTCHA = "Captcha" +COM_REDSHOP_FRONT_IMAGE = "Front Image" +COM_REDSHOP_BACK_IMAGE = "Back Image" +COM_REDSHOP_NO_ATTRIBUTE_TO_CHANGE = "No Attribute to change" +COM_REDSHOP_CHANGE_ATTRIBUTE = "Change Attribute" +COM_REDSHOP_SELECT_PRODUCT_SUBSCRIPTION = "Select product subscription" +COM_REDSHOP_PRODUCT_USERFIELD = "Product Userfield" +COM_REDSHOP_CONFIRM_CART_EMPTY = "Are you sure want to reorder? It will empty Current cart." +COM_REDSHOP_REORDER = "Reorder" +COM_REDSHOP_FILE_NOT_AVAILABLE_IN_DB = "File not available in database" +COM_REDSHOP_PLEASE_SELECT_YOUR = "Please select your" +COM_REDSHOP_RETYPE_CUSTOMER_EMAIL = "Retype Email Address" +COM_REDSHOP_ACCESSORY_QUANTITY_LBL = "Accessory Quantity" +COM_REDSHOP_PRODUCT_ADDED_TO_CART = "Product has been added to your cart." +COM_REDSHOP_USER_REQUEST_TAX_EXEMPT_LBL = "User requested Tax exempt" +COM_REDSHOP_TOOLTIP_USER_REQUEST_TAX_EXEMPT = "User requested Tax exempt" +COM_REDSHOP_PROPERTY_IMAGE_LBL = "Property Image" +COM_REDSHOP_VIRTUAL_NUMBER_LBL = "Virtual Number" +COM_REDSHOP_PROPERTY_NAME_LBL = "Property Name" +COM_REDSHOP_PROPERTY_PRICE_LBL = "Property Price" +COM_REDSHOP_PROPERTY_STOCK_LBL = "Property Stock" +COM_REDSHOP_ADD_TO_CART_LBL = "Add To Cart" +COM_REDSHOP_IN_STOCK = "In Stock" +COM_REDSHOP_NOT_IN_STOCK = "Not In Stock" +COM_REDSHOP_PRODUCT_DATE_FIELD_EXPIRED = "Product Date Expired" +COM_REDSHOP_PRODUCT_DIAMETER_LBL = "Diameter" +COM_REDSHOP_USER_TAX_EXEMPT_REQUEST_LBL = "User tax exempt Request" +COM_REDSHOP_SUBTOTAL_EXCL_VAT_LBL = "Subtotal Excluding Tax" +COM_REDSHOP_NEWSLETTER_NOT_AVAILABLE = "Newsletter is not available" +COM_REDSHOP_USER_INFORMATION_NOT_MATCH = "User country, state, zipcode might not be matched..." +COM_REDSHOP_PRODUCT_DETAIL_NOT_MATCH = "Product or product category might not be shipped into this county." +COM_REDSHOP_CART_DIMENTION_NOT_MATCH = "Cart volume(weight,height,length), order total might not be matched...." +COM_REDSHOP_VIEW_MANUFACTURER = "View Manufacturer" +COM_REDSHOP_ADD_TO_CART_TOOLTIP = "Add To Cart" +COM_REDSHOP_REQUEST_A_QUOTE_TOOLTIP = "Request a Quote" +COM_REDSHOP_REQUEST_A_QUOTE = "Request a Quote" +COM_REDSHOP_YOU_NEED_TO_LOGIN_TO_POST_A_REVIEW = "You need to log in to write review" +COM_REDSHOP_YOUR_MUST_PROVIDE_A_ADDRESS = "Please enter address" +COM_REDSHOP_YOUR_MUST_PROVIDE_A_ZIP = "Please enter post code" +COM_REDSHOP_YOUR_MUST_PROVIDE_A_CITY = "Please enter city" +COM_REDSHOP_YOUR_MUST_PROVIDE_A_PHONE = "Please enter the phone" +COM_REDSHOP_YOUR_MUST_PROVIDE_A_FIRSTNAME = "Please enter first name" +COM_REDSHOP_YOUR_MUST_PROVIDE_A_LASTNAME = "Please enter last name" +COM_REDSHOP_YOU_MUST_PROVIDE_LOGIN_NAME = "Please enter username" +COM_REDSHOP_PROVIDE_EMAIL_ADDRESS = "Please enter email address" +COM_REDSHOP_EMAIL_NOT_MATCH = "Email address do not match" +COM_REDSHOP_THIS_FIELD_IS_REQUIRED = "This field is required" +COM_REDSHOP_DENOTATION_TXT = "* Values denoted are vat exempt and will be calculated accordingly." +COM_REDSHOP_SHIPPING_TEXT_LBL = "If you order for %s more, you will get free shipping" +COM_REDSHOP_FREE_SHIPPING_RATE_IS_IN_USED = "Free shipping rate is in used" +COM_REDSHOP_NO_SHIPPING_RATE_AVAILABLE = "No Free shipping rate is available." +COM_REDSHOP_OUT_OF_STOCK = "Out of Stock." +COM_REDSHOP_AVAILABLE_STOCK = "In Stock." +COM_REDSHOP_BACK_BUTTON = "Back" +COM_REDSHOP_PRODUCT_SUBTOTAL_LBL = "Subtotal" +COM_REDSHOP_PRODUCT_SUBTOTAL_EXCL_LBL = "Subtotal excl vat" +COM_REDSHOP_SHIPPING_WITH_VAT_LBL = "Shipping with vat" +COM_REDSHOP_SHIPPING_EXCL_VAT_LBL = "Shipping excl vat" +COM_REDSHOP_PRODUCT_PRICE_EXCL_LBL = "Price excl" +COM_REDSHOP_NO_SHIPPING_RATE_AVAILABLE_WHEN_NOPRODUCT_IN_CART = "No free shipping rate is available since there is no product in cart" +COM_REDSHOP_NOT_AVAILABLE = "Not Available" +COM_REDSHOP_GO_BACK = "Go Back" +COM_REDSHOP_DISCOUNT_CALC_HEIGHT = "Height:" +COM_REDSHOP_DISCOUNT_CALC_WIDTH = "Width:" +COM_REDSHOP_DISCOUNT_CALC_LENGTH = "Length:" +COM_REDSHOP_DISCOUNT_CALC_RADIUS = "Radius:" +COM_REDSHOP_DISCOUNT_CALC_UNIT = "Unit:" +COM_REDSHOP_DISCOUNT_CALC_DEPTH = "Depth:" +COM_REDSHOP_PLEASE_INSERT_HEIGHT = "Please Insert Height" +COM_REDSHOP_PLEASE_INSERT_WIDTH = "Please Insert Width" +COM_REDSHOP_PLEASE_INSERT_DEPTH = "Please Insert Depth" +COM_REDSHOP_PLEASE_INSERT_RADIUS = "Please Insert Radius" +COM_REDSHOP_PLEASE_INSERT_UNIT = "Please Insert Unit" +COM_REDSHOP_SELECT_SUBSCRIPTION_PLAN = "Please Select Your Subscription Plan" +COM_REDSHOP_VIEW_FULL_SIZE_IMAGE_LBL = "View Full-Size Image" +COM_REDSHOP_WARNING_MSG_MAXIMUM_QUANTITY = "Product is not available more than %s amount." +COM_REDSHOP_WARNING_MSG_MINIMUM_QUANTITY = "Product is not available less than %s amount." +COM_REDSHOP_CHECKOUT_ERR_NO_CCNM_FOUND = "Numeric value not accepted in card name." +COM_REDSHOP_CHECKOUT_ERR_NO_CCNR_NUM_FOUND = "Only numeric value accepted in card number." +COM_REDSHOP_PRODUCT_IS_EXPIRED = "%s(%s) is Expired" +COM_REDSHOP_PROVIDE_CORRECT_EMAIL_ADDRESS = "Please enter a valid email address." +COM_REDSHOP_RELATED_PRODUCT_LIST_IN_LIGHTBOX = "Related Product List" +COM_REDSHOP_NEWSLEETER_SUBSCRIBE_SUCCESS = "You are successfully subscribed for newsletter." +COM_REDSHOP_PREORDER_PRODUCT_OUTOFSTOCK_MESSAGE = "Sorry.... Pre-order Stock is out of Order." +COM_REDSHOP_SUBSCRIPTION_PERIOD = "Subscription Period" +COM_REDSHOP_SUBSCRIPTION_PRICE = "Subscription Price" +COM_REDSHOP_DEBITOR_NUMBER = "Debtor Number" +COM_REDSHOP_PASSWORD_MIN_CHARACTER_LIMIT = "Your password must be at least 5 characters long" +COM_REDSHOP_PRODUCT_NOT_ADDED_TO_CART = "Product was not added to cart" +COM_REDSHOP_ERROR_CATALOG_SEND_SUCCSEEFULLY = "Error Sending Catalogue Successfully" +COM_REDSHOP_SHOPPERGROUP_NOT_MATCH = "Shopper group not match" +COM_REDSHOP_ERROR_SAMPLE_SEND_SUCCSEEFULLY = "Error Sample Send Successfully" +COM_REDSHOP_PRODUCT_NOT_SAVED_IN_WISHLIST = "Product was not saved in wishlist" +COM_REDSHOP_DOWNLOAD_TOKEN = "Download Token" +COM_REDSHOP_DOWNLOAD_LEFT = "Download(s) Left" +COM_REDSHOP_DOWNLOAD_ENDDATE = "Download End Date" +COM_REDSHOP_ON = "On" +COM_REDSHOP_FROM = "From" +COM_REDSHOP_DOWNLOAD_LOG = "Download Log" +COM_REDSHOP_QUOTATION_DISCOUNT_LBL = "Quote Discount" +COM_REDSHOP_MONTH = "Month" +COM_REDSHOP_PLEASE_SELECT_YOUR_SUBSCRIPTION_PLAN = "Please select your subscription plan" +COM_REDSHOP_PRODUCT_NAME_ASC = "Sort by product name asc" +COM_REDSHOP_PRODUCT_NAME_DESC = "Sort by product name desc" +COM_REDSHOP_PRODUCT_NUMBER_ASC = "Sort by product number asc" +COM_REDSHOP_PRODUCT_NUMBER_DESC = "Sort by product number desc" +COM_REDSHOP_ORDERING_ASC = "Sort order by asc" +COM_REDSHOP_ORDERING_DESC = "Sort order by desc" +COM_REDSHOP_DATEPICKER_ASC = "Date picker Asc" +COM_REDSHOP_DATEPICKER_DESC = "Date picker Desc" +COM_REDSHOP_PRODUCT_ID_ASC = "Sort by product ID asc" +COM_REDSHOP_PRODUCT_ID_DESC = "Sort by product ID desc" +COM_REDSHOP_ACCESSORY_ID_ASC = "Sort Accessories by ID Asc" +COM_REDSHOP_ACCESSORY_ID_DESC = "Sort Accessories by ID Desc" +COM_REDSHOP_ACCESSORY_PRICE_ASC = "Sort Accessories by Price Asc" +COM_REDSHOP_ACCESSORY_PRICE_DESC = "Sort Accessories by Price Desc" +COM_REDSHOP_GLOBAL = "Global" +COM_REDSHOP_CHILD_PRODUCT_NAME = "Child Product Name" +COM_REDSHOP_CHILD_PRODUCT_NUMBER = "Child Product Number" +COM_REDSHOP_TWO_LETTER_ABBRIVATION = "Two Letter Abbreviation" +COM_REDSHOP_THREE_LETTER_ABBRIVATION = "Three Letter Abbreviation" +COM_REDSHOP_NONE = "None" +COM_REDSHOP_PRICE = "Price" +COM_REDSHOP_TO = "To" +COM_REDSHOP_COMPARE = "Compare" +COM_REDSHOP_DELETE = "Delete" +COM_REDSHOP_PASSWORDS_DO_NOT_MATCH = "Passwords do not match" +COM_REDSHOP_ACCESS_FORBIDDEN = "Access Forbidden" +COM_REDSHOP_INVALID_SECURITY = "Sorry, you have provided an invalid security code." +COM_REDSHOP_SECURITY_CODE = "Security Code :" +COM_REDSHOP_PRODUCT_IS_NOT_FOR_SALE = "%s(%s) is Not For Sale" +COM_REDSHOP_ZIPCODE = "ZIP code" +COM_REDSHOP_REG_COMPLETE_ACTIVATE = "Registration Complete Activate" +COM_REDSHOP_REG_COMPLETE = "Registration complete" +COM_REDSHOP_SEARCH_RESULT = "Search results" +COM_REDSHOP_CLEAR_ALL = "Clear All" +COM_REDSHOP_SEARCH_CRITERIA = "Search criteria" +COM_REDSHOP_BULK_ORDER_LINK = "Bulk order link" +COM_REDSHOP_BULK_ORDER = "Bulk order" +COM_REDSHOP_CANCEL = "Cancel" +COM_REDSHOP_SAVE = "Save" +COM_REDSHOP_ = "Redshop" +COM_REDSHOP_ALERTNOTAUTH = "Alert: You are not authorised" +COM_REDSHOP_PLEASE_ENTER_YOUR_NAME = "Please enter your name" +COM_REDSHOP_APPLY = "Apply" +COM_REDSHOP_EDIT = "Edit" +COM_REDSHOP_TEMPLATE_NOT_EXISTS = "Template not exists" +COM_REDSHOP_CUSTOMER_QUANTITY_LBL = "Quantity" +COM_REDSHOP_CUSTOMER_AMOUNT_LBL = "Amount" +COM_REDSHOP_REDSHOP = "redSHOP" +COM_REDSHOP_LOGIN = "Log in" +COM_REDSHOP_LOGOUT_SUCCESS = "Logout success" +COM_REDSHOP_MANUFACTURER = "Manufacturer" +COM_REDSHOP_MANUFACTURER_DETAIL = "Manufacturer Details" +COM_REDSHOP_MANUFACTURER_PRODUCTS = "Manufacturer Products" +COM_REDSHOP_ENTER_A_NAME = "Enter a name" +COM_REDSHOP_PRODCUT_PRICE_YOU_SAVED = "Product Price You Saved" +COM_REDSHOP_CATEGORY = "Category" +COM_REDSHOP_NUM = "Num" +COM_REDSHOP_PRODUCT = "Product" +COM_REDSHOP_ACCOUNT_CREATION = "Account Creation" +COM_REDSHOP_SUBMIT = "Submit" +COM_REDSHOP_REGISTRATION_INTROTEXT = "Registration intro text" +COM_REDSHOP_REGISTRATION_COMPANY_INTROTEXT = "Company registration intro text" -COM_REDSHOP_COUNTRY_AFGHANISTAN="Afghanistan" -COM_REDSHOP_COUNTRY_ALBANIA="Albania" -COM_REDSHOP_COUNTRY_ALGERIA="Algeria" -COM_REDSHOP_COUNTRY_ANDORRA="Andorra" -COM_REDSHOP_COUNTRY_ANGOLA="Angola" -COM_REDSHOP_COUNTRY_ANGUILLA="Anguilla" -COM_REDSHOP_COUNTRY_ANTARCTICA="Antarctica" -COM_REDSHOP_COUNTRY_ARGENTINA="Argentina" -COM_REDSHOP_COUNTRY_ARMENIA="Armenia" -COM_REDSHOP_COUNTRY_ARUBA="Aruba" -COM_REDSHOP_COUNTRY_AUSTRALIA="Australia" -COM_REDSHOP_COUNTRY_AUSTRIA="Austria" -COM_REDSHOP_COUNTRY_AZERBAIJAN="Azerbaijan" -COM_REDSHOP_COUNTRY_BAHAMAS="Bahamas" -COM_REDSHOP_COUNTRY_BAHRAIN="Bahrain" -COM_REDSHOP_COUNTRY_BANGLADESH="Bangladesh" -COM_REDSHOP_COUNTRY_BARBADOS="Barbados" -COM_REDSHOP_COUNTRY_BELARUS="Belarus" -COM_REDSHOP_COUNTRY_BELGIUM="Belgium" -COM_REDSHOP_COUNTRY_BELIZE="Belize" -COM_REDSHOP_COUNTRY_BENIN="Benin" -COM_REDSHOP_COUNTRY_BERMUDA="Bermuda" -COM_REDSHOP_COUNTRY_BHUTAN="Bhutan" -COM_REDSHOP_COUNTRY_BOLIVIA="Bolivia" -COM_REDSHOP_COUNTRY_BOTSWANA="Botswana" -COM_REDSHOP_COUNTRY_BRAZIL="Brazil" -COM_REDSHOP_COUNTRY_BRUNEI="Brunei Darussalam" -COM_REDSHOP_COUNTRY_BULGARIA="Bulgaria" -COM_REDSHOP_COUNTRY_BURUNDI="Burundi" -COM_REDSHOP_COUNTRY_CAMBODIA="Cambodia" -COM_REDSHOP_COUNTRY_CAMEROON="Cameroon" -COM_REDSHOP_COUNTRY_CANADA="Canada" -COM_REDSHOP_COUNTRY_CHAD="Chad" -COM_REDSHOP_COUNTRY_CHILE="Chile" -COM_REDSHOP_COUNTRY_CHINA="China" -COM_REDSHOP_COUNTRY_COLOMBIA="Colombia" -COM_REDSHOP_COUNTRY_CONGO="The Democratic Republic of Congo" -COM_REDSHOP_COUNTRY_CROATIA="Croatia" -COM_REDSHOP_COUNTRY_CUBA="Cuba" -COM_REDSHOP_COUNTRY_CYPRUS="Cyprus" -COM_REDSHOP_COUNTRY_DENMARK="Denmark" -COM_REDSHOP_COUNTRY_DJIBOUTI="Djibouti" -COM_REDSHOP_COUNTRY_DOMINICA="Dominica" -COM_REDSHOP_COUNTRY_ECUADOR="Ecuador" -COM_REDSHOP_COUNTRY_EGYPT="Egypt" -COM_REDSHOP_COUNTRY_ERITREA="Eritrea" -COM_REDSHOP_COUNTRY_ESTONIA="Estonia" -COM_REDSHOP_COUNTRY_ETHIOPIA="Ethiopia" -COM_REDSHOP_COUNTRY_FIJI="Fiji" -COM_REDSHOP_COUNTRY_FINLAND="Finland" -COM_REDSHOP_COUNTRY_FRANCE="France" -COM_REDSHOP_COUNTRY_GABON="Gabon" -COM_REDSHOP_COUNTRY_GAMBIA="Gambia" -COM_REDSHOP_COUNTRY_GEORGIA="Georgia" -COM_REDSHOP_COUNTRY_GERMANY="Germany" -COM_REDSHOP_COUNTRY_GHANA="Ghana" -COM_REDSHOP_COUNTRY_GIBRALTAR="Gibraltar" -COM_REDSHOP_COUNTRY_GREECE="Greece" -COM_REDSHOP_COUNTRY_GREENLAND="Greenland" -COM_REDSHOP_COUNTRY_GRENADA="Grenada" -COM_REDSHOP_COUNTRY_GUADELOUPE="Guadeloupe" -COM_REDSHOP_COUNTRY_GUAM="Guam" -COM_REDSHOP_COUNTRY_GUATEMALA="Guatemala" -COM_REDSHOP_COUNTRY_GUERNSEY="Guernsey" -COM_REDSHOP_COUNTRY_GUINEA="Guinea" -COM_REDSHOP_COUNTRY_GUYANA="Guyana" -COM_REDSHOP_COUNTRY_HAITI="Haiti" -COM_REDSHOP_COUNTRY_HONDURAS="Honduras" -COM_REDSHOP_COUNTRY_HUNGARY="Hungary" -COM_REDSHOP_COUNTRY_ICELAND="Iceland" -COM_REDSHOP_COUNTRY_INDIA="India" -COM_REDSHOP_COUNTRY_INDONESIA="Indonesia" -COM_REDSHOP_COUNTRY_IRAN="Iran (Islamic Republic of)" -COM_REDSHOP_COUNTRY_IRAQ="Iraq" -COM_REDSHOP_COUNTRY_IRELAND="Ireland" -COM_REDSHOP_COUNTRY_ISRAEL="Israel" -COM_REDSHOP_COUNTRY_ITALY="Italy" -COM_REDSHOP_COUNTRY_JAMAICA="Jamaica" -COM_REDSHOP_COUNTRY_JAPAN="Japan" -COM_REDSHOP_COUNTRY_JERSEY="Jersey" -COM_REDSHOP_COUNTRY_JORDAN="Jordan" -COM_REDSHOP_COUNTRY_KAZAKHSTAN="Kasakhstan" -COM_REDSHOP_COUNTRY_KENYA="Kenya" -COM_REDSHOP_COUNTRY_KIRIBATI="Kiribati" -COM_REDSHOP_COUNTRY_KUWAIT="Kuwait" -COM_REDSHOP_COUNTRY_KYRGYZSTAN="Kyrgyzstan" -COM_REDSHOP_COUNTRY_LAO="Lao People's Democratic Republic" -COM_REDSHOP_COUNTRY_LATVIA="Latvia" -COM_REDSHOP_COUNTRY_LEBANON="Lebanon" -COM_REDSHOP_COUNTRY_LESOTHO="Lesotho" -COM_REDSHOP_COUNTRY_LIBERIA="Liberia" -COM_REDSHOP_COUNTRY_LIBYA="Libya" -COM_REDSHOP_COUNTRY_LIECHTENSTEIN="Liechtenstein" -COM_REDSHOP_COUNTRY_LITHUANIA="Lithuania" -COM_REDSHOP_COUNTRY_LUXEMBOURG="Luxembourg" -COM_REDSHOP_COUNTRY_MACAU="Macau" -COM_REDSHOP_COUNTRY_MACEDONIA="Macedonia (Former Yugoslav Republic of)" -COM_REDSHOP_COUNTRY_MADAGASCAR="Madagascar" -COM_REDSHOP_COUNTRY_MALAWI="Malawi" -COM_REDSHOP_COUNTRY_MALAYSIA="Malaysia" -COM_REDSHOP_COUNTRY_MALDIVES="Maldives" -COM_REDSHOP_COUNTRY_MALI="Mali" -COM_REDSHOP_COUNTRY_MALTA="Malta" -COM_REDSHOP_COUNTRY_MARTINIQUE="Martinique" -COM_REDSHOP_COUNTRY_MAURITANIA="Mauritania" -COM_REDSHOP_COUNTRY_MAURITIUS="Mauritius" -COM_REDSHOP_COUNTRY_MAYOTTE="Mayotte" -COM_REDSHOP_COUNTRY_MEXICO="Mexico" -COM_REDSHOP_COUNTRY_MICRONESIA="Micronesia (Federated States of)" -COM_REDSHOP_COUNTRY_MOLDOVA="Moldova (Republic of)" -COM_REDSHOP_COUNTRY_MONACO="Monaco" -COM_REDSHOP_COUNTRY_MONGOLIA="Mongolia" -COM_REDSHOP_COUNTRY_MONTENEGRO="Montenegro" -COM_REDSHOP_COUNTRY_MONTSERRAT="Montserrat" -COM_REDSHOP_COUNTRY_MOROCCO="Morocco" -COM_REDSHOP_COUNTRY_MOZAMBIQUE="Mozambique" -COM_REDSHOP_COUNTRY_MYANMAR="Myanmar, Burma" -COM_REDSHOP_COUNTRY_NAMIBIA="Namibia" -COM_REDSHOP_COUNTRY_NAURU="Nauru" -COM_REDSHOP_COUNTRY_NEPAL="Nepal" -COM_REDSHOP_COUNTRY_NETHERLANDS="Holland" -COM_REDSHOP_COUNTRY_NICARAGUA="Nicaragua" -COM_REDSHOP_COUNTRY_NIGER="Niger" -COM_REDSHOP_COUNTRY_NIGERIA="Nigeria" -COM_REDSHOP_COUNTRY_NIUE="Niue" -COM_REDSHOP_COUNTRY_NORWAY="Norway" -COM_REDSHOP_COUNTRY_OMAN="Oman" -COM_REDSHOP_COUNTRY_PAKISTAN="Pakistan" -COM_REDSHOP_COUNTRY_PALAU="Palau" -COM_REDSHOP_COUNTRY_PANAMA="Panama" -COM_REDSHOP_COUNTRY_PARAGUAY="Paraguay" -COM_REDSHOP_COUNTRY_PERU="Peru" -COM_REDSHOP_COUNTRY_PHILIPPINES="Philippines" -COM_REDSHOP_COUNTRY_PITCAIRN="Pitcairn" -COM_REDSHOP_COUNTRY_POLAND="Poland" -COM_REDSHOP_COUNTRY_PORTUGAL="Portugal" -COM_REDSHOP_COUNTRY_QATAR="Qatar" -COM_REDSHOP_COUNTRY_ROMANIA="Romania" -COM_REDSHOP_COUNTRY_RUSSIA="Russian Federation" -COM_REDSHOP_COUNTRY_RWANDA="Rwanda" -COM_REDSHOP_COUNTRY_SAMOA="Samoa" -COM_REDSHOP_COUNTRY_SENEGAL="Senegal" -COM_REDSHOP_COUNTRY_SERBIA="Serbia" -COM_REDSHOP_COUNTRY_SEYCHELLES="Seychelles" -COM_REDSHOP_COUNTRY_SINGAPORE="Singapore" -COM_REDSHOP_COUNTRY_SLOVAKIA="Slovakia (Slovak Republic)" -COM_REDSHOP_COUNTRY_SLOVENIA="Slovenia" -COM_REDSHOP_COUNTRY_SOMALIA="Somalia" -COM_REDSHOP_COUNTRY_SPAIN="Spain" -COM_REDSHOP_COUNTRY_ST_BARTHELEMY="St. Barthelemy" -COM_REDSHOP_COUNTRY_ST_EUSTATIUS="St. Eustatius" -COM_REDSHOP_COUNTRY_ST_HELENA="St. Helena" -COM_REDSHOP_COUNTRY_SUDAN="Sudan" -COM_REDSHOP_COUNTRY_SVALBARD="Svalbard and Jan Mayen Islands" -COM_REDSHOP_COUNTRY_SWAZILAND="Swaziland" -COM_REDSHOP_COUNTRY_SWEDEN="Sweden" -COM_REDSHOP_COUNTRY_SWITZERLAND="Switzerland" -COM_REDSHOP_COUNTRY_SYRIA="Syrian Arab Republic" -COM_REDSHOP_COUNTRY_TAIWAN="Taiwan" -COM_REDSHOP_COUNTRY_TAJIKISTAN="Tadsjikistan" -COM_REDSHOP_COUNTRY_TANZANIA="Tanzania" -COM_REDSHOP_COUNTRY_THAILAND="Thailand" -COM_REDSHOP_COUNTRY_TOGO="Togo" -COM_REDSHOP_COUNTRY_TOKELAU="Tokelau" -COM_REDSHOP_COUNTRY_TONGA="Tonga" -COM_REDSHOP_COUNTRY_TUNISIA="Tunisia" -COM_REDSHOP_COUNTRY_TURKEY="Turkey" -COM_REDSHOP_COUNTRY_TURKMENISTAN="Turkmenistan" -COM_REDSHOP_COUNTRY_TUVALU="Tuvalu" -COM_REDSHOP_COUNTRY_UGANDA="Uganda" -COM_REDSHOP_COUNTRY_UKRAINE="Ukraine" -COM_REDSHOP_COUNTRY_URUGUAY="Uruguay" -COM_REDSHOP_COUNTRY_UZBEKISTAN="Uzbekistan" -COM_REDSHOP_COUNTRY_VANUATU="Vanuatu" -COM_REDSHOP_COUNTRY_VENEZUELA="Venezuela" -COM_REDSHOP_COUNTRY_VIETNAM="Vietnam" -COM_REDSHOP_COUNTRY_YEMEN="Yemen" -COM_REDSHOP_COUNTRY_YUGOSLAVIA="Yugoslavia" -COM_REDSHOP_COUNTRY_ZAMBIA="Zambia" -COM_REDSHOP_COUNTRY_ZIMBABWE="Zimbabwe" -COM_REDSHOP_DAY_FRI="Fri" -COM_REDSHOP_DAY_FRIDAY="Friday" -COM_REDSHOP_DAY_MON="Mon" -COM_REDSHOP_DAY_MONDAY="Monday" -COM_REDSHOP_DAY_SAT="Sat" -COM_REDSHOP_DAY_SATURDAY="Saturday" -COM_REDSHOP_DAY_SUN="Sun" -COM_REDSHOP_DAY_SUNDAY="Sunday" -COM_REDSHOP_DAY_THU="Thu" -COM_REDSHOP_DAY_THURSDAY="Thursday" -COM_REDSHOP_DAY_TUE="Tue" -COM_REDSHOP_DAY_TUESDAY="Tuesday" -COM_REDSHOP_DAY_WED="Wed" -COM_REDSHOP_DAY_WEDNESDAY="Wednesday" -COM_REDSHOP_DEBITOR_MONEY_TRANSFER_NUMBER="Debtor Money Transfer Number" -COM_REDSHOP_DOWNLOAD="Download" -COM_REDSHOP_MOBILE_PHONE="Mobile Phone" -COM_REDSHOP_MONTH_APR="Apr" -COM_REDSHOP_MONTH_APRIL="April" -COM_REDSHOP_MONTH_AUG="Aug" -COM_REDSHOP_MONTH_AUGUST="August" -COM_REDSHOP_MONTH_DEC="Dec" -COM_REDSHOP_MONTH_DECEMBER="December" -COM_REDSHOP_MONTH_FEB="Feb" -COM_REDSHOP_MONTH_FEBRUARY="February" -COM_REDSHOP_MONTH_JAN="Jan" -COM_REDSHOP_MONTH_JANUARY="January" -COM_REDSHOP_MONTH_JUL="Jul" -COM_REDSHOP_MONTH_JULY="July" -COM_REDSHOP_MONTH_JUN="Jun" -COM_REDSHOP_MONTH_JUNE="June" -COM_REDSHOP_MONTH_MAR="Mar" -COM_REDSHOP_MONTH_MARCH="March" -COM_REDSHOP_MONTH_MAY="May" -COM_REDSHOP_MONTH_NOV="Nov" -COM_REDSHOP_MONTH_NOVEMBER="November" -COM_REDSHOP_MONTH_OCT="Oct" -COM_REDSHOP_MONTH_OCTOBER="October" -COM_REDSHOP_MONTH_SEP="Sep" -COM_REDSHOP_MONTH_SEPTEMBER="September" -COM_REDSHOP_NEW="New" -COM_REDSHOP_ORDERS="Orders" -COM_REDSHOP_SELECT_MANUFACTURER="Select Manufacturer" -COM_REDSHOP_SHIPPING_BOX="Shipping Box" -COM_REDSHOP_TXT_READ_MORE="Read More" -COM_REDSHOP_UPDATE_STATUS_BUTTON="Update Status" -COM_REDSHOP_ORDER_DETAIL_LINK_LBL="Order Detail Link" -COM_REDSHOP_USERNAME_REGISTER="Select Username" -COM_REDSHOP_PASSWORD_REGISTER="Select Password" -COM_REDSHOP_MANUFACTURER_PRODUCT="Products of" -COM_REDSHOP_PRODUCT_CUSTOM_FIELD="Product Custom Field" -COM_REDSHOP_GET_ADDRESS_BY_PHONE="Get Address By Phone" -COM_REDSHOP_NO_RESULT_FOUND_BY_SEARCHPHONE="Sorry, No result found by phone" -COM_REDSHOP_TOTAL_PRICE_EXEL_LBL="Total Price excl" -COM_REDSHOP_CUSTOMER_MESSAGE_LBL="Customer message" -COM_REDSHOP_REFERRAL_CODE_LBL="Referral code" -COM_REDSHOP_MANUFACTURER_LINK_LBL="Read more about manufacturer" -COM_REDSHOP_MANUFACTURER_ALLPRODUCTSLINK_LBL="See all manufacturer Products" -COM_REDSHOP_TELEPHONE="Your Phone No." -COM_REDSHOP_AVAILABLE_STOCK_MESSAGE="Products are available for this item." -COM_REDSHOP_META_BUY="Buy" -COM_REDSHOP_META_AT_ONLY="at only" -COM_REDSHOP_META_SAVE="save" -COM_REDSHOP_PREORDER_BTN="PreOrder" -COM_REDSHOP_PROVIDE_ZIPCODE_TO_PICKUP_PARCEL="Zipcode" -COM_REDSHOP_SELECT_GLS_LOCATION="Pickup location" -COM_REDSHOP_ENTER_GLS_MOBILE="Mobile" -COM_REDSHOP_GLS_UPDATE="Update" -COM_REDSHOP_INVOICE="Invoice" -COM_REDSHOP_SHOPPER_GROUP_PORTAL_IS_DISABLE="Access denied" -COM_REDSHOP_SUBSCRIPTION_PLAN="Select Subscription Plan" -COM_REDSHOP_USERNAME_MIN_CHARACTER_LIMIT="Your username must consist of at least 2 characters" -COM_REDSHOP_YOUR_MUST_PROVIDE_A_VALID_PHONE="Please specify a valid phone number" -COM_REDSHOP_UNUSED_COUPON_LBL="Unused Amount" -COM_REDSHOP_ALREADY_REQUESTED_FOR_NOTIFICATION="You have requested for notification when product back in stock" -COM_REDSHOP_USER_PHONE_LBL="User Phone" -COM_REDSHOP_USER_ADDRESS_LBL="User Address" -COM_REDSHOP_ORDER_PAYMENT_EXTRA_FILEDS="Additional Payment data" -COM_REDSHOP_ORDER_SHIPPING_EXTRA_FILEDS="Additional Shipping data" -COM_REDSHOP_USER_EMAIL="User E-mail" -COM_REDSHOP_NAME_LBL="Name/Username" -COM_REDSHOP_EMAIL_LBL="E-mail" -COM_REDSHOP_CATALOG_SEND="Send" -COM_REDSHOP_SAMPLE_SEND="Send" -COM_REDSHOP_SELECT_SAMPLE_COLOR="Please select sample color" -COM_REDSHOP_PER_PRODUCT_TOTAL="Minimum Per Product Total" -COM_REDSHOP_ALL_CATEGORY_VIEW_NO_RESULT_TEXT="No category found." -COM_REDSHOP_EAN_MIN_CHARACTER_LIMIT="Enter only 13 digits without spaces" -COM_REDSHOP_SPECIAL_DISCOUNT="Special discount" -COM_REDSHOP_ACCOUNT_LINK="Account Link" -COM_REDSHOP_NOTIFY_STOCK_LBL="You can requested notification when product back in stock" -COM_REDSHOP_NOTIFY_STOCK_BUTTON="Notify me" -COM_REDSHOP_STOCK_NOTIFICATION_ADDED_SUCCESSFULLY="Notification added" -COM_REDSHOP_THERE_ARE_NO_CATEGORIES_TO_SHOW="There are no categories to show" -COM_REDSHOP_VALIDATE_EXTRA_FIELD_IS_REQUIRED="Select %s" -COM_REDSHOP_ALERT_REGISTRATION_SUCCESSFULLY="%s registered successfully" -COM_REDSHOP_ALERT_ORDER_SUCCESSFULLY="%s ordered for %s %s" -COM_REDSHOP_ALERT_STOCKROOM_BELOW_AMOUNT_NUMBER_MAIN_SUBJECT="Product has stockroom below amount number" -COM_REDSHOP_ALERT_STOCKROOM_BELOW_AMOUNT_NUMBER="Product: %s SKU: %s has remaining %s in stockroom %s." +COM_REDSHOP_COUNTRY_AFGHANISTAN = "Afghanistan" +COM_REDSHOP_COUNTRY_ALBANIA = "Albania" +COM_REDSHOP_COUNTRY_ALGERIA = "Algeria" +COM_REDSHOP_COUNTRY_ANDORRA = "Andorra" +COM_REDSHOP_COUNTRY_ANGOLA = "Angola" +COM_REDSHOP_COUNTRY_ANGUILLA = "Anguilla" +COM_REDSHOP_COUNTRY_ANTARCTICA = "Antarctica" +COM_REDSHOP_COUNTRY_ARGENTINA = "Argentina" +COM_REDSHOP_COUNTRY_ARMENIA = "Armenia" +COM_REDSHOP_COUNTRY_ARUBA = "Aruba" +COM_REDSHOP_COUNTRY_AUSTRALIA = "Australia" +COM_REDSHOP_COUNTRY_AUSTRIA = "Austria" +COM_REDSHOP_COUNTRY_AZERBAIJAN = "Azerbaijan" +COM_REDSHOP_COUNTRY_BAHAMAS = "Bahamas" +COM_REDSHOP_COUNTRY_BAHRAIN = "Bahrain" +COM_REDSHOP_COUNTRY_BANGLADESH = "Bangladesh" +COM_REDSHOP_COUNTRY_BARBADOS = "Barbados" +COM_REDSHOP_COUNTRY_BELARUS = "Belarus" +COM_REDSHOP_COUNTRY_BELGIUM = "Belgium" +COM_REDSHOP_COUNTRY_BELIZE = "Belize" +COM_REDSHOP_COUNTRY_BENIN = "Benin" +COM_REDSHOP_COUNTRY_BERMUDA = "Bermuda" +COM_REDSHOP_COUNTRY_BHUTAN = "Bhutan" +COM_REDSHOP_COUNTRY_BOLIVIA = "Bolivia" +COM_REDSHOP_COUNTRY_BOTSWANA = "Botswana" +COM_REDSHOP_COUNTRY_BRAZIL = "Brazil" +COM_REDSHOP_COUNTRY_BRUNEI = "Brunei Darussalam" +COM_REDSHOP_COUNTRY_BULGARIA = "Bulgaria" +COM_REDSHOP_COUNTRY_BURUNDI = "Burundi" +COM_REDSHOP_COUNTRY_CAMBODIA = "Cambodia" +COM_REDSHOP_COUNTRY_CAMEROON = "Cameroon" +COM_REDSHOP_COUNTRY_CANADA = "Canada" +COM_REDSHOP_COUNTRY_CHAD = "Chad" +COM_REDSHOP_COUNTRY_CHILE = "Chile" +COM_REDSHOP_COUNTRY_CHINA = "China" +COM_REDSHOP_COUNTRY_COLOMBIA = "Colombia" +COM_REDSHOP_COUNTRY_CONGO = "The Democratic Republic of Congo" +COM_REDSHOP_COUNTRY_CROATIA = "Croatia" +COM_REDSHOP_COUNTRY_CUBA = "Cuba" +COM_REDSHOP_COUNTRY_CYPRUS = "Cyprus" +COM_REDSHOP_COUNTRY_DENMARK = "Denmark" +COM_REDSHOP_COUNTRY_DJIBOUTI = "Djibouti" +COM_REDSHOP_COUNTRY_DOMINICA = "Dominica" +COM_REDSHOP_COUNTRY_ECUADOR = "Ecuador" +COM_REDSHOP_COUNTRY_EGYPT = "Egypt" +COM_REDSHOP_COUNTRY_ERITREA = "Eritrea" +COM_REDSHOP_COUNTRY_ESTONIA = "Estonia" +COM_REDSHOP_COUNTRY_ETHIOPIA = "Ethiopia" +COM_REDSHOP_COUNTRY_FIJI = "Fiji" +COM_REDSHOP_COUNTRY_FINLAND = "Finland" +COM_REDSHOP_COUNTRY_FRANCE = "France" +COM_REDSHOP_COUNTRY_GABON = "Gabon" +COM_REDSHOP_COUNTRY_GAMBIA = "Gambia" +COM_REDSHOP_COUNTRY_GEORGIA = "Georgia" +COM_REDSHOP_COUNTRY_GERMANY = "Germany" +COM_REDSHOP_COUNTRY_GHANA = "Ghana" +COM_REDSHOP_COUNTRY_GIBRALTAR = "Gibraltar" +COM_REDSHOP_COUNTRY_GREECE = "Greece" +COM_REDSHOP_COUNTRY_GREENLAND = "Greenland" +COM_REDSHOP_COUNTRY_GRENADA = "Grenada" +COM_REDSHOP_COUNTRY_GUADELOUPE = "Guadeloupe" +COM_REDSHOP_COUNTRY_GUAM = "Guam" +COM_REDSHOP_COUNTRY_GUATEMALA = "Guatemala" +COM_REDSHOP_COUNTRY_GUERNSEY = "Guernsey" +COM_REDSHOP_COUNTRY_GUINEA = "Guinea" +COM_REDSHOP_COUNTRY_GUYANA = "Guyana" +COM_REDSHOP_COUNTRY_HAITI = "Haiti" +COM_REDSHOP_COUNTRY_HONDURAS = "Honduras" +COM_REDSHOP_COUNTRY_HUNGARY = "Hungary" +COM_REDSHOP_COUNTRY_ICELAND = "Iceland" +COM_REDSHOP_COUNTRY_INDIA = "India" +COM_REDSHOP_COUNTRY_INDONESIA = "Indonesia" +COM_REDSHOP_COUNTRY_IRAN = "Iran (Islamic Republic of)" +COM_REDSHOP_COUNTRY_IRAQ = "Iraq" +COM_REDSHOP_COUNTRY_IRELAND = "Ireland" +COM_REDSHOP_COUNTRY_ISRAEL = "Israel" +COM_REDSHOP_COUNTRY_ITALY = "Italy" +COM_REDSHOP_COUNTRY_JAMAICA = "Jamaica" +COM_REDSHOP_COUNTRY_JAPAN = "Japan" +COM_REDSHOP_COUNTRY_JERSEY = "Jersey" +COM_REDSHOP_COUNTRY_JORDAN = "Jordan" +COM_REDSHOP_COUNTRY_KAZAKHSTAN = "Kasakhstan" +COM_REDSHOP_COUNTRY_KENYA = "Kenya" +COM_REDSHOP_COUNTRY_KIRIBATI = "Kiribati" +COM_REDSHOP_COUNTRY_KUWAIT = "Kuwait" +COM_REDSHOP_COUNTRY_KYRGYZSTAN = "Kyrgyzstan" +COM_REDSHOP_COUNTRY_LAO = "Lao People's Democratic Republic" +COM_REDSHOP_COUNTRY_LATVIA = "Latvia" +COM_REDSHOP_COUNTRY_LEBANON = "Lebanon" +COM_REDSHOP_COUNTRY_LESOTHO = "Lesotho" +COM_REDSHOP_COUNTRY_LIBERIA = "Liberia" +COM_REDSHOP_COUNTRY_LIBYA = "Libya" +COM_REDSHOP_COUNTRY_LIECHTENSTEIN = "Liechtenstein" +COM_REDSHOP_COUNTRY_LITHUANIA = "Lithuania" +COM_REDSHOP_COUNTRY_LUXEMBOURG = "Luxembourg" +COM_REDSHOP_COUNTRY_MACAU = "Macau" +COM_REDSHOP_COUNTRY_MACEDONIA = "Macedonia (Former Yugoslav Republic of)" +COM_REDSHOP_COUNTRY_MADAGASCAR = "Madagascar" +COM_REDSHOP_COUNTRY_MALAWI = "Malawi" +COM_REDSHOP_COUNTRY_MALAYSIA = "Malaysia" +COM_REDSHOP_COUNTRY_MALDIVES = "Maldives" +COM_REDSHOP_COUNTRY_MALI = "Mali" +COM_REDSHOP_COUNTRY_MALTA = "Malta" +COM_REDSHOP_COUNTRY_MARTINIQUE = "Martinique" +COM_REDSHOP_COUNTRY_MAURITANIA = "Mauritania" +COM_REDSHOP_COUNTRY_MAURITIUS = "Mauritius" +COM_REDSHOP_COUNTRY_MAYOTTE = "Mayotte" +COM_REDSHOP_COUNTRY_MEXICO = "Mexico" +COM_REDSHOP_COUNTRY_MICRONESIA = "Micronesia (Federated States of)" +COM_REDSHOP_COUNTRY_MOLDOVA = "Moldova (Republic of)" +COM_REDSHOP_COUNTRY_MONACO = "Monaco" +COM_REDSHOP_COUNTRY_MONGOLIA = "Mongolia" +COM_REDSHOP_COUNTRY_MONTENEGRO = "Montenegro" +COM_REDSHOP_COUNTRY_MONTSERRAT = "Montserrat" +COM_REDSHOP_COUNTRY_MOROCCO = "Morocco" +COM_REDSHOP_COUNTRY_MOZAMBIQUE = "Mozambique" +COM_REDSHOP_COUNTRY_MYANMAR = "Myanmar, Burma" +COM_REDSHOP_COUNTRY_NAMIBIA = "Namibia" +COM_REDSHOP_COUNTRY_NAURU = "Nauru" +COM_REDSHOP_COUNTRY_NEPAL = "Nepal" +COM_REDSHOP_COUNTRY_NETHERLANDS = "Holland" +COM_REDSHOP_COUNTRY_NICARAGUA = "Nicaragua" +COM_REDSHOP_COUNTRY_NIGER = "Niger" +COM_REDSHOP_COUNTRY_NIGERIA = "Nigeria" +COM_REDSHOP_COUNTRY_NIUE = "Niue" +COM_REDSHOP_COUNTRY_NORWAY = "Norway" +COM_REDSHOP_COUNTRY_OMAN = "Oman" +COM_REDSHOP_COUNTRY_PAKISTAN = "Pakistan" +COM_REDSHOP_COUNTRY_PALAU = "Palau" +COM_REDSHOP_COUNTRY_PANAMA = "Panama" +COM_REDSHOP_COUNTRY_PARAGUAY = "Paraguay" +COM_REDSHOP_COUNTRY_PERU = "Peru" +COM_REDSHOP_COUNTRY_PHILIPPINES = "Philippines" +COM_REDSHOP_COUNTRY_PITCAIRN = "Pitcairn" +COM_REDSHOP_COUNTRY_POLAND = "Poland" +COM_REDSHOP_COUNTRY_PORTUGAL = "Portugal" +COM_REDSHOP_COUNTRY_QATAR = "Qatar" +COM_REDSHOP_COUNTRY_ROMANIA = "Romania" +COM_REDSHOP_COUNTRY_RUSSIA = "Russian Federation" +COM_REDSHOP_COUNTRY_RWANDA = "Rwanda" +COM_REDSHOP_COUNTRY_SAMOA = "Samoa" +COM_REDSHOP_COUNTRY_SENEGAL = "Senegal" +COM_REDSHOP_COUNTRY_SERBIA = "Serbia" +COM_REDSHOP_COUNTRY_SEYCHELLES = "Seychelles" +COM_REDSHOP_COUNTRY_SINGAPORE = "Singapore" +COM_REDSHOP_COUNTRY_SLOVAKIA = "Slovakia (Slovak Republic)" +COM_REDSHOP_COUNTRY_SLOVENIA = "Slovenia" +COM_REDSHOP_COUNTRY_SOMALIA = "Somalia" +COM_REDSHOP_COUNTRY_SPAIN = "Spain" +COM_REDSHOP_COUNTRY_ST_BARTHELEMY = "St. Barthelemy" +COM_REDSHOP_COUNTRY_ST_EUSTATIUS = "St. Eustatius" +COM_REDSHOP_COUNTRY_ST_HELENA = "St. Helena" +COM_REDSHOP_COUNTRY_SUDAN = "Sudan" +COM_REDSHOP_COUNTRY_SVALBARD = "Svalbard and Jan Mayen Islands" +COM_REDSHOP_COUNTRY_SWAZILAND = "Swaziland" +COM_REDSHOP_COUNTRY_SWEDEN = "Sweden" +COM_REDSHOP_COUNTRY_SWITZERLAND = "Switzerland" +COM_REDSHOP_COUNTRY_SYRIA = "Syrian Arab Republic" +COM_REDSHOP_COUNTRY_TAIWAN = "Taiwan" +COM_REDSHOP_COUNTRY_TAJIKISTAN = "Tadsjikistan" +COM_REDSHOP_COUNTRY_TANZANIA = "Tanzania" +COM_REDSHOP_COUNTRY_THAILAND = "Thailand" +COM_REDSHOP_COUNTRY_TOGO = "Togo" +COM_REDSHOP_COUNTRY_TOKELAU = "Tokelau" +COM_REDSHOP_COUNTRY_TONGA = "Tonga" +COM_REDSHOP_COUNTRY_TUNISIA = "Tunisia" +COM_REDSHOP_COUNTRY_TURKEY = "Turkey" +COM_REDSHOP_COUNTRY_TURKMENISTAN = "Turkmenistan" +COM_REDSHOP_COUNTRY_TUVALU = "Tuvalu" +COM_REDSHOP_COUNTRY_UGANDA = "Uganda" +COM_REDSHOP_COUNTRY_UKRAINE = "Ukraine" +COM_REDSHOP_COUNTRY_URUGUAY = "Uruguay" +COM_REDSHOP_COUNTRY_UZBEKISTAN = "Uzbekistan" +COM_REDSHOP_COUNTRY_VANUATU = "Vanuatu" +COM_REDSHOP_COUNTRY_VENEZUELA = "Venezuela" +COM_REDSHOP_COUNTRY_VIETNAM = "Vietnam" +COM_REDSHOP_COUNTRY_YEMEN = "Yemen" +COM_REDSHOP_COUNTRY_YUGOSLAVIA = "Yugoslavia" +COM_REDSHOP_COUNTRY_ZAMBIA = "Zambia" +COM_REDSHOP_COUNTRY_ZIMBABWE = "Zimbabwe" +COM_REDSHOP_DAY_FRI = "Fri" +COM_REDSHOP_DAY_FRIDAY = "Friday" +COM_REDSHOP_DAY_MON = "Mon" +COM_REDSHOP_DAY_MONDAY = "Monday" +COM_REDSHOP_DAY_SAT = "Sat" +COM_REDSHOP_DAY_SATURDAY = "Saturday" +COM_REDSHOP_DAY_SUN = "Sun" +COM_REDSHOP_DAY_SUNDAY = "Sunday" +COM_REDSHOP_DAY_THU = "Thu" +COM_REDSHOP_DAY_THURSDAY = "Thursday" +COM_REDSHOP_DAY_TUE = "Tue" +COM_REDSHOP_DAY_TUESDAY = "Tuesday" +COM_REDSHOP_DAY_WED = "Wed" +COM_REDSHOP_DAY_WEDNESDAY = "Wednesday" +COM_REDSHOP_DEBITOR_MONEY_TRANSFER_NUMBER = "Debtor Money Transfer Number" +COM_REDSHOP_DOWNLOAD = "Download" +COM_REDSHOP_MOBILE_PHONE = "Mobile Phone" +COM_REDSHOP_MONTH_APR = "Apr" +COM_REDSHOP_MONTH_APRIL = "April" +COM_REDSHOP_MONTH_AUG = "Aug" +COM_REDSHOP_MONTH_AUGUST = "August" +COM_REDSHOP_MONTH_DEC = "Dec" +COM_REDSHOP_MONTH_DECEMBER = "December" +COM_REDSHOP_MONTH_FEB = "Feb" +COM_REDSHOP_MONTH_FEBRUARY = "February" +COM_REDSHOP_MONTH_JAN = "Jan" +COM_REDSHOP_MONTH_JANUARY = "January" +COM_REDSHOP_MONTH_JUL = "Jul" +COM_REDSHOP_MONTH_JULY = "July" +COM_REDSHOP_MONTH_JUN = "Jun" +COM_REDSHOP_MONTH_JUNE = "June" +COM_REDSHOP_MONTH_MAR = "Mar" +COM_REDSHOP_MONTH_MARCH = "March" +COM_REDSHOP_MONTH_MAY = "May" +COM_REDSHOP_MONTH_NOV = "Nov" +COM_REDSHOP_MONTH_NOVEMBER = "November" +COM_REDSHOP_MONTH_OCT = "Oct" +COM_REDSHOP_MONTH_OCTOBER = "October" +COM_REDSHOP_MONTH_SEP = "Sep" +COM_REDSHOP_MONTH_SEPTEMBER = "September" +COM_REDSHOP_NEW = "New" +COM_REDSHOP_ORDERS = "Orders" +COM_REDSHOP_SELECT_MANUFACTURER = "Select Manufacturer" +COM_REDSHOP_SHIPPING_BOX = "Shipping Box" +COM_REDSHOP_TXT_READ_MORE = "Read More" +COM_REDSHOP_UPDATE_STATUS_BUTTON = "Update Status" +COM_REDSHOP_ORDER_DETAIL_LINK_LBL = "Order Detail Link" +COM_REDSHOP_USERNAME_REGISTER = "Select Username" +COM_REDSHOP_PASSWORD_REGISTER = "Select Password" +COM_REDSHOP_MANUFACTURER_PRODUCT = "Products of" +COM_REDSHOP_PRODUCT_CUSTOM_FIELD = "Product Custom Field" +COM_REDSHOP_GET_ADDRESS_BY_PHONE = "Get Address By Phone" +COM_REDSHOP_NO_RESULT_FOUND_BY_SEARCHPHONE = "Sorry, No result found by phone" +COM_REDSHOP_TOTAL_PRICE_EXEL_LBL = "Total Price excl" +COM_REDSHOP_CUSTOMER_MESSAGE_LBL = "Customer message" +COM_REDSHOP_REFERRAL_CODE_LBL = "Referral code" +COM_REDSHOP_MANUFACTURER_LINK_LBL = "Read more about manufacturer" +COM_REDSHOP_MANUFACTURER_ALLPRODUCTSLINK_LBL = "See all manufacturer Products" +COM_REDSHOP_TELEPHONE = "Your Phone No." +COM_REDSHOP_AVAILABLE_STOCK_MESSAGE = "Products are available for this item." +COM_REDSHOP_META_BUY = "Buy" +COM_REDSHOP_META_AT_ONLY = "at only" +COM_REDSHOP_META_SAVE = "save" +COM_REDSHOP_PREORDER_BTN = "PreOrder" +COM_REDSHOP_PROVIDE_ZIPCODE_TO_PICKUP_PARCEL = "Zipcode" +COM_REDSHOP_SELECT_GLS_LOCATION = "Pickup location" +COM_REDSHOP_ENTER_GLS_MOBILE = "Mobile" +COM_REDSHOP_GLS_UPDATE = "Update" +COM_REDSHOP_INVOICE = "Invoice" +COM_REDSHOP_SHOPPER_GROUP_PORTAL_IS_DISABLE = "Access denied" +COM_REDSHOP_SUBSCRIPTION_PLAN = "Select Subscription Plan" +COM_REDSHOP_USERNAME_MIN_CHARACTER_LIMIT = "Your username must consist of at least 2 characters" +COM_REDSHOP_YOUR_MUST_PROVIDE_A_VALID_PHONE = "Please specify a valid phone number" +COM_REDSHOP_UNUSED_COUPON_LBL = "Unused Amount" +COM_REDSHOP_ALREADY_REQUESTED_FOR_NOTIFICATION = "You have requested for notification when product back in stock" +COM_REDSHOP_USER_PHONE_LBL = "User Phone" +COM_REDSHOP_USER_ADDRESS_LBL = "User Address" +COM_REDSHOP_ORDER_PAYMENT_EXTRA_FILEDS = "Additional Payment data" +COM_REDSHOP_ORDER_SHIPPING_EXTRA_FILEDS = "Additional Shipping data" +COM_REDSHOP_USER_EMAIL = "User E-mail" +COM_REDSHOP_NAME_LBL = "Name/Username" +COM_REDSHOP_EMAIL_LBL = "E-mail" +COM_REDSHOP_CATALOG_SEND = "Send" +COM_REDSHOP_SAMPLE_SEND = "Send" +COM_REDSHOP_SELECT_SAMPLE_COLOR = "Please select sample color" +COM_REDSHOP_PER_PRODUCT_TOTAL = "Minimum Per Product Total" +COM_REDSHOP_ALL_CATEGORY_VIEW_NO_RESULT_TEXT = "No category found." +COM_REDSHOP_EAN_MIN_CHARACTER_LIMIT = "Enter only 13 digits without spaces" +COM_REDSHOP_SPECIAL_DISCOUNT = "Special discount" +COM_REDSHOP_ACCOUNT_LINK = "Account Link" +COM_REDSHOP_NOTIFY_STOCK_LBL = "You can requested notification when product back in stock" +COM_REDSHOP_NOTIFY_STOCK_BUTTON = "Notify me" +COM_REDSHOP_STOCK_NOTIFICATION_ADDED_SUCCESSFULLY = "Notification added" +COM_REDSHOP_THERE_ARE_NO_CATEGORIES_TO_SHOW = "There are no categories to show" +COM_REDSHOP_VALIDATE_EXTRA_FIELD_IS_REQUIRED = "Select %s" +COM_REDSHOP_ALERT_REGISTRATION_SUCCESSFULLY = "%s registered successfully" +COM_REDSHOP_ALERT_ORDER_SUCCESSFULLY = "%s ordered for %s %s" +COM_REDSHOP_ALERT_STOCKROOM_BELOW_AMOUNT_NUMBER_MAIN_SUBJECT = "Product has stockroom below amount number" +COM_REDSHOP_ALERT_STOCKROOM_BELOW_AMOUNT_NUMBER = "Product: %s SKU: %s has remaining %s in stockroom %s." ; Library -COM_REDSHOP_ERROR_INVALID_PRODUCT_ID="Invalid product ID" -COM_REDSHOP_UPLOAD_FILE_TOO_BIG="File upload too big" -COM_REDSHOP_MEDIA_ERROR_FILE_UPLOAD_INVALID="File upload invalid!" -COM_REDSHOP_QUANTITY_START_LBL="Quantity start" -COM_REDSHOP_QUANTITY_END_LBL="Quantity end" -COM_REDSHOP_ORDER_STATUS_LOG="Order status log" -COM_REDSHOP_ORDER_STATUS_CHANGE_TO="Status has been changed to" -COM_REDSHOP_ORDER_PAYMENT_STATUS_CHANGE_TO="Payment status has been changed to" +COM_REDSHOP_ERROR_INVALID_PRODUCT_ID = "Invalid product ID" +COM_REDSHOP_UPLOAD_FILE_TOO_BIG = "File upload too big" +COM_REDSHOP_MEDIA_ERROR_FILE_UPLOAD_INVALID = "File upload invalid!" +COM_REDSHOP_QUANTITY_START_LBL = "Quantity start" +COM_REDSHOP_QUANTITY_END_LBL = "Quantity end" +COM_REDSHOP_ORDER_STATUS_LOG = "Order status log" +COM_REDSHOP_ORDER_STATUS_CHANGE_TO = "Status has been changed to" +COM_REDSHOP_ORDER_PAYMENT_STATUS_CHANGE_TO = "Payment status has been changed to" ; Extra fields Layout -COM_REDSHOP_PUBLISHED_DATE="Publish Date" -COM_REDSHOP_ENTER_AVAILABLE_DATE="Enter Available Date" -COM_REDSHOP_ADD_VALUE="Add Value" -COM_REDSHOP_VALUE="Value" -COM_REDSHOP_OPTION_VALUE="Option Value" -COM_REDSHOP_REMOVE_MEDIA="Remove media" +COM_REDSHOP_PUBLISHED_DATE = "Publish Date" +COM_REDSHOP_ENTER_AVAILABLE_DATE = "Enter Available Date" +COM_REDSHOP_ADD_VALUE = "Add Value" +COM_REDSHOP_VALUE = "Value" +COM_REDSHOP_OPTION_VALUE = "Option Value" +COM_REDSHOP_REMOVE_MEDIA = "Remove media" -COM_REDSHOP_ORDER_TRACKING_NUMBER="Tracking number" -COM_REDSHOP_TRACK_LINK_LBL="Tracking URL" -COM_REDSHOP_ACCESSORY_HAS_REQUIRED_ATTRIBUTES="Accessory that you selected has required attributes" +COM_REDSHOP_ORDER_TRACKING_NUMBER = "Tracking number" +COM_REDSHOP_TRACK_LINK_LBL = "Tracking URL" +COM_REDSHOP_ACCESSORY_HAS_REQUIRED_ATTRIBUTES = "Accessory that you selected has required attributes" ; Registration -COM_REDSHOP_REGISTRATION_MISSING_VAT_NUMBER="Enter VAT number" -COM_REDSHOP_REGISTRATION_INVALID_VAT_NUMBER="You entered an invalid VAT number" +COM_REDSHOP_REGISTRATION_MISSING_VAT_NUMBER = "Enter VAT number" +COM_REDSHOP_REGISTRATION_INVALID_VAT_NUMBER = "You entered an invalid VAT number" ; Cart -COM_REDSHOP_CART_INVALID_REQUEST="Invalid request" +COM_REDSHOP_CART_INVALID_REQUEST = "Invalid request" ; Newsletter -COM_REDSHOP_ALREADY_CANCLE_SUBSCRIPTION="Newsletter subscription cancelled" +COM_REDSHOP_ALREADY_CANCLE_SUBSCRIPTION = "Newsletter subscription cancelled" ; Category -COM_REDSHOP_SELECT_CATEGORY="Select Category" \ No newline at end of file +COM_REDSHOP_SELECT_CATEGORY = "Select Category" \ No newline at end of file diff --git a/component/site/layouts/assets.php b/component/site/layouts/assets.php index 643c35395c5..8427b296fa3 100644 --- a/component/site/layouts/assets.php +++ b/component/site/layouts/assets.php @@ -11,25 +11,31 @@ JHtml::_('redshopjquery.framework'); JHtml::_('behavior.framework', true); -JHtml::_('redshopjquery.select2', 'select:not(".disableBootstrapChosen")', array("width" => "auto", "dropdownAutoWidth" => "auto")); +JHtml::_( + 'redshopjquery.select2', + 'select:not(".disableBootstrapChosen")', + array("width" => "auto", "dropdownAutoWidth" => "auto") +); -/** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/redshop.attribute.min.js', false, true); -/** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/redshop.common.min.js', false, true); -/** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/redshop.redbox.min.js', false, true); -/** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/bootstrap.min.js', false, true); +/** @scrutinizer ignore-deprecated */ +JHtml::script('com_redshop/redshop.attribute.min.js', false, true); +/** @scrutinizer ignore-deprecated */ +JHtml::script('com_redshop/redshop.common.min.js', false, true); +/** @scrutinizer ignore-deprecated */ +JHtml::script('com_redshop/redshop.redbox.min.js', false, true); +/** @scrutinizer ignore-deprecated */ +JHtml::script('com_redshop/bootstrap.min.js', false, true); $app = JFactory::getApplication(); $doc = new RedshopHelperDocument; $doc->addBottomStylesheet(JURI::root() . 'media/com_redshop/css/bootstrap-grid.min.css'); -if (Redshop::getConfig()->getBool('LOAD_REDSHOP_STYLE', true)) -{ - $doc->addBottomStylesheet(JURI::root() . 'media/com_redshop/css/redshop.min.css'); +if (Redshop::getConfig()->getBool('LOAD_REDSHOP_STYLE', true)) { + $doc->addBottomStylesheet(JURI::root() . 'media/com_redshop/css/redshop.min.css'); } // Use different CSS for print layout -if ($app->input->getCmd('print', '')) -{ - $doc->addBottomStylesheet(JURI::root() . 'media/com_redshop/css/redshop.print.min.css'); +if ($app->input->getCmd('print', '')) { + $doc->addBottomStylesheet(JURI::root() . 'media/com_redshop/css/redshop.print.min.css'); } diff --git a/component/site/layouts/cart/billing.php b/component/site/layouts/cart/billing.php index 66819280d86..1f395b2e6ed 100644 --- a/component/site/layouts/cart/billing.php +++ b/component/site/layouts/cart/billing.php @@ -18,16 +18,16 @@ extract($displayData); $extraSections = ($billingAddresses->is_company == 1) ? - RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS : RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS; + RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS : RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS; ?>
    - is_company == 1) : ?> + is_company == 1) : ?>
    company_name; ?>
    - +
    @@ -39,95 +39,94 @@
    lastname; ?>
    - address)) : ?> + address)) : ?>
    address; ?>
    - + - zipcode)) : ?> + zipcode)) : ?>
    zipcode; ?>
    - + - city)) : ?> + city)) : ?>
    city; ?>
    - + - country_code)): ?> + country_code)): ?>
    -
    country_code)) ?>
    +
    country_code) + ) ?>
    - + - state_code, $billingAddresses->country_code); ?> - + state_code, $billingAddresses->country_code); ?> +
    - + - phone)) : ?> + phone)) : ?>
    phone; ?>
    - + - user_email)) : ?> + user_email)) : ?>
    user_email ? $billingAddresses->user_email : $user->email; ?>
    - + - is_company == 1) : ?> + is_company == 1) : ?> - ean_number)) : ?> + ean_number)) : ?>
    ean_number; ?>
    - - requisition_number)) : ?> + + requisition_number)) : ?>
    requisition_number ?>
    - + - get('USE_TAX_EXEMPT') == 1) : ?> + get('USE_TAX_EXEMPT') == 1) : ?>
    vat_number; ?>
    - - - get('SHOW_TAX_EXEMPT_INFRONT')) : ?> - tax_exempt == 1) - { - $tax_exempt = JText::_('COM_REDSHOP_TAX_YES'); - } - else - { - $tax_exempt = JText::_('COM_REDSHOP_TAX_NO'); - } - ?> + + + get('SHOW_TAX_EXEMPT_INFRONT')) : ?> + tax_exempt == 1) { + $tax_exempt = JText::_('COM_REDSHOP_TAX_YES'); + } else { + $tax_exempt = JText::_('COM_REDSHOP_TAX_NO'); + } + ?>
    - - - users_info_id) ?> + + + users_info_id) ?>
    diff --git a/component/site/layouts/cart/cart.php b/component/site/layouts/cart/cart.php index 6184c40f5f7..ee774832de6 100644 --- a/component/site/layouts/cart/cart.php +++ b/component/site/layouts/cart/cart.php @@ -12,123 +12,125 @@ /** * Layout data * ============================== - * @var array $displayData Display data. + * @var array $displayData Display data. */ -$cart = $displayData['cart']; -$total = 0; +$cart = $displayData['cart']; +$total = 0; -if (isset($cart) && isset($cart['idx']) && $cart['idx'] > 0) -{ - $total = $cart['mod_cart_total']; +if (isset($cart) && isset($cart['idx']) && $cart['idx'] > 0) { + $total = $cart['mod_cart_total']; } if ($displayData['cartOutput'] == 'simple'): ?>
    - - - + + +
    - - + getItem(); - $name = $giftCardData->giftcard_name; - } - else - { - $productDetail = \Redshop\Product\Product::getProductById($cart[$i]['product_id']); - $name = $productDetail->product_name; - } - ?> + if (\Redshop\Helper\Utility::rsMultiArrayKeyExists('giftcard_id', $cart[$i]) && $cart[$i]['giftcard_id']) { + $giftCardData = RedshopEntityGiftcard::getInstance($cart[$i]['giftcard_id'])->getItem(); + $name = $giftCardData->giftcard_name; + } else { + $productDetail = \Redshop\Product\Product::getProductById($cart[$i]['product_id']); + $name = $productDetail->product_name; + } + ?>
    - +
    - get('DEFAULT_QUOTATION_MODE') || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') && Redshop::getConfig()->get('SHOW_QUOTATION_PRICE'))): - if ($displayData['showWithVat']) - { - $price = $cart[$i]['product_price']; - } - else - { - $price = $cart[$i]['product_price_excl_vat']; - } - ?> + get('DEFAULT_QUOTATION_MODE') || (Redshop::getConfig()->get( + 'DEFAULT_QUOTATION_MODE' + ) && Redshop::getConfig()->get('SHOW_QUOTATION_PRICE'))): + if ($displayData['showWithVat']) { + $price = $cart[$i]['product_price']; + } else { + $price = $cart[$i]['product_price_excl_vat']; + } + ?>
    - +
    - +
    - - + +
    - -get('DEFAULT_QUOTATION_MODE') || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') && Redshop::getConfig()->get('SHOW_QUOTATION_PRICE'))) && $displayData['totalQuantity']): ?> + +get('DEFAULT_QUOTATION_MODE') || (Redshop::getConfig()->get( + 'DEFAULT_QUOTATION_MODE' + ) && Redshop::getConfig()->get('SHOW_QUOTATION_PRICE'))) && $displayData['totalQuantity']): ?>
    - + $shippingValue = $cart['shipping'] - $cart['shipping_tax']; + } + ?>
    - : + :
    - +
    - + - 0) : - ?> + if ($discountValue > 0) : + ?>
    - : + :
    - +
    - - + +
    - +
    - +
    - + diff --git a/component/site/layouts/cart/index.html b/component/site/layouts/cart/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/site/layouts/cart/index.html +++ b/component/site/layouts/cart/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/layouts/cart/shipping.php b/component/site/layouts/cart/shipping.php index 12a221e814d..1dca58ff8a8 100644 --- a/component/site/layouts/cart/shipping.php +++ b/component/site/layouts/cart/shipping.php @@ -16,12 +16,12 @@ ?>
    - is_company == 1) : ?> + is_company == 1) : ?>
    company_name; ?>
    - +
    @@ -33,48 +33,53 @@
    lastname; ?>
    - address != "") : ?> + address != "") : ?>
    address; ?>
    - + - zipcode != "") : ?> + zipcode != "") : ?>
    zipcode; ?>
    - + - city != "") : ?> + city != "") : ?>
    city; ?>
    - + - country_code != "") : ?> + country_code != "") : ?>
    -
    country_code)) ?>
    +
    country_code) + ) ?>
    - + - state_code, $shippingaddresses->country_code); ?> - + state_code, + $shippingaddresses->country_code + ); ?> +
    - + - phone != "") : ?> + phone != "") : ?>
    phone; ?>
    - + - users_info_id) ?> + users_info_id) ?>
    diff --git a/component/site/layouts/cart/wizard.php b/component/site/layouts/cart/wizard.php index a44e70ce76b..3630b462aee 100644 --- a/component/site/layouts/cart/wizard.php +++ b/component/site/layouts/cart/wizard.php @@ -14,17 +14,17 @@ diff --git a/component/site/layouts/checkout/login.php b/component/site/layouts/checkout/login.php index ce29ae68df7..a2141e3d1c9 100644 --- a/component/site/layouts/checkout/login.php +++ b/component/site/layouts/checkout/login.php @@ -32,6 +32,6 @@ - + diff --git a/component/site/layouts/checkout/onestep/billing.php b/component/site/layouts/checkout/onestep/billing.php index 05d4d025fad..fb31d981ec6 100644 --- a/component/site/layouts/checkout/onestep/billing.php +++ b/component/site/layouts/checkout/onestep/billing.php @@ -18,24 +18,23 @@ $registerMethod = Redshop::getConfig()->getInt('REGISTER_METHOD'); -if (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 0) -{ - $company = ""; - $customer = ""; -} -elseif (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 1) -{ - $openToStretcher = 0; -} -elseif (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 2) -{ - $openToStretcher = 1; +if (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 0) { + $company = ""; + $customer = ""; +} elseif (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 1) { + $openToStretcher = 0; +} elseif (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 2) { + $openToStretcher = 1; } $isCompany = $openToStretcher == 1 ? 1 : 0; -$lists['shipping_customer_field'] = Redshop\Fields\SiteHelper::renderFields(RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS); -$lists['shipping_company_field'] = Redshop\Fields\SiteHelper::renderFields(RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS); +$lists['shipping_customer_field'] = Redshop\Fields\SiteHelper::renderFields( + RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS +); +$lists['shipping_company_field'] = Redshop\Fields\SiteHelper::renderFields( + RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS +); $input = JFactory::getApplication()->input; ?> @@ -45,16 +44,18 @@
    + style="display: get( + 'CREATE_ACCOUNT_CHECKBOX' + ) == 1 || $registerMethod == 0) ? 'block' : 'none' ?>;">
    -
    +
    - trigger('onRenderOnstepCheckout'); ?> + trigger('onRenderOnstepCheckout'); ?>
    diff --git a/component/site/layouts/checkout/payment_radio.php b/component/site/layouts/checkout/payment_radio.php index 0c60bee0cd5..d40f95e3ee3 100644 --- a/component/site/layouts/checkout/payment_radio.php +++ b/component/site/layouts/checkout/payment_radio.php @@ -45,10 +45,10 @@ /> - <?php echo JText::_('PLG_' . strtoupper($oneMethod->name)) ?> + <?php echo JText::_('PLG_' . strtoupper($oneMethod->name)) ?> name)) ?> diff --git a/component/site/layouts/checkout/register.php b/component/site/layouts/checkout/register.php index e6661a26dab..ae20a7c3a56 100644 --- a/component/site/layouts/checkout/register.php +++ b/component/site/layouts/checkout/register.php @@ -14,79 +14,82 @@ ?>
    - get('REGISTER_METHOD') == 2) : - $checked_style = (Redshop::getConfig()->get('CREATE_ACCOUNT_CHECKBOX') == 1) ? 'checked="checked"' : "''"; - ?> -
    - -
    - + name="adminForm" id="adminForm" enctype="multipart/form-data"> + get('REGISTER_METHOD') == 2) : + $checked_style = (Redshop::getConfig()->get('CREATE_ACCOUNT_CHECKBOX') == 1) ? 'checked="checked"' : "''"; + ?> +
    + +
    + -
    - +
    + - get('OPTIONAL_SHIPPING_ADDRESS'), 1, Redshop::getConfig()->get('CREATE_ACCOUNT_CHECKBOX')); ?> -
    + get('OPTIONAL_SHIPPING_ADDRESS'), + 1, + Redshop::getConfig()->get('CREATE_ACCOUNT_CHECKBOX') + ); ?> +
    - get('SHIPPING_METHOD_ENABLE')) : ?> + get('SHIPPING_METHOD_ENABLE')) : ?> - 0) - { - if (isset($post['billisship']) && $post['billisship'] == 1) - { - $billingisshipping = "style='display:none'"; - } - } - elseif (Redshop::getConfig()->get('OPTIONAL_SHIPPING_ADDRESS')) - { - $billingisshipping = "style='display:none'"; - } - ?> + if (count($_POST) > 0) { + if (isset($post['billisship']) && $post['billisship'] == 1) { + $billingisshipping = "style='display:none'"; + } + } elseif (Redshop::getConfig()->get('OPTIONAL_SHIPPING_ADDRESS')) { + $billingisshipping = "style='display:none'"; + } + ?> -
    > -
    - - $post, - 'isCompany' => $isCompany, - 'lists' => $this->lists - ) - ); - ?> -
    -
    +
    > +
    + + $post, + 'isCompany' => $isCompany, + 'lists' => $this->lists + ) + ); + ?> +
    +
    - + - + -
    - - -
    +
    + + +
    -
    - - - - - - - - +
    + + + + + + + +
    \ No newline at end of file diff --git a/component/site/layouts/fields/display.php b/component/site/layouts/fields/display.php index 91189e27d14..9e60fd9293d 100644 --- a/component/site/layouts/fields/display.php +++ b/component/site/layouts/fields/display.php @@ -12,8 +12,8 @@ /** * $displayData extract * - * @var array $displayData Layout data. - * @var string $extraFieldValue Extra Field Value + * @var array $displayData Layout data. + * @var string $extraFieldValue Extra Field Value */ extract($displayData); diff --git a/component/site/layouts/fields/html.php b/component/site/layouts/fields/html.php index a7d04db5914..5d3db2f9579 100644 --- a/component/site/layouts/fields/html.php +++ b/component/site/layouts/fields/html.php @@ -14,7 +14,7 @@ * * @var array $displayData Layout data * @var object $form A JForm object - * @var integer $productId Id current product + * @var integer $productId Id current product * @var integer $modal Flag use form in modal */ extract($displayData); @@ -22,13 +22,13 @@
    - - required == 1) : ?> + + required == 1) : ?> * - - desc) != '') : ?> - desc, '', 'tooltip.png', '', '', false); - ?> - + + desc) != '') : ?> + desc, '', 'tooltip.png', '', '', false); + ?> +
    diff --git a/component/site/layouts/fields/index.html b/component/site/layouts/fields/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/site/layouts/fields/index.html +++ b/component/site/layouts/fields/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/layouts/filter/index.html b/component/site/layouts/filter/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/site/layouts/filter/index.html +++ b/component/site/layouts/filter/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/layouts/filter/restricted.php b/component/site/layouts/filter/restricted.php index ab9a603c1c3..c2805d03108 100644 --- a/component/site/layouts/filter/restricted.php +++ b/component/site/layouts/filter/restricted.php @@ -11,30 +11,30 @@ ?>
    - category == 1 && !empty($categories)): ?> + category == 1 && !empty($categories)): ?>

      - $cat) : ?> + $cat) : ?>
    • - +
    - +
    - manufacturer == 1 && !empty($manufacturers)): ?> + manufacturer == 1 && !empty($manufacturers)): ?>
    @@ -43,59 +43,59 @@
      - - - $manu) : ?> + + + $manu) : ?>
    • - - + +
    - +
    - custom_field == 1 && !empty($customFields)): ?> + custom_field == 1 && !empty($customFields)): ?>

      - $fields) : ?> + $fields) : ?>

      - $name) : ?> + $name) : ?>
    • - - + +
    - +
    - price == 1) : ?> + price == 1) : ?>
    @@ -112,7 +112,7 @@
    - + diff --git a/component/site/layouts/filter/result.php b/component/site/layouts/filter/result.php index ffa8f681662..a8360f25057 100755 --- a/component/site/layouts/filter/result.php +++ b/component/site/layouts/filter/result.php @@ -1,4 +1,5 @@ template . ',' . $categoryDetail->more_template; - $template = RedshopHelperTemplate::getTemplate('category', $categoryTemplate); - - $renderTemplate = JHtml::_( - 'select.genericlist', - $template, - 'category_template', - 'class="inputbox" size="1" onchange="loadTemplate(this);"', - 'id', - 'name', - $templateId - ); - - if ($renderTemplate != "") - { - $templateDesc = str_replace("{template_selector_category_lbl}", JText::_('COM_REDSHOP_TEMPLATE_SELECTOR_CATEGORY_LBL'), $templateDesc); - $templateDesc = str_replace("{template_selector_category}", $renderTemplate, $templateDesc); - } - - $templateDesc = str_replace("{template_selector_category_lbl}", "", $templateDesc); - $templateDesc = str_replace("{template_selector_category}", "", $templateDesc); +if (strpos($templateDesc, "{template_selector_category}") !== false) { + $categoryTemplate = $categoryDetail->template . ',' . $categoryDetail->more_template; + $template = RedshopHelperTemplate::getTemplate('category', $categoryTemplate); + + $renderTemplate = JHtml::_( + 'select.genericlist', + $template, + 'category_template', + 'class="inputbox" size="1" onchange="loadTemplate(this);"', + 'id', + 'name', + $templateId + ); + + if ($renderTemplate != "") { + $templateDesc = str_replace( + "{template_selector_category_lbl}", + JText::_('COM_REDSHOP_TEMPLATE_SELECTOR_CATEGORY_LBL'), + $templateDesc + ); + $templateDesc = str_replace("{template_selector_category}", $renderTemplate, $templateDesc); + } + + $templateDesc = str_replace("{template_selector_category_lbl}", "", $templateDesc); + $templateDesc = str_replace("{template_selector_category}", "", $templateDesc); } $templateDesc = RedshopHelperProductTag::getExtraSectionTag($extraFieldCategory, $cid, "2", $templateDesc); -if (strpos($templateDesc, "{load_more}") !== false) -{ - $loadMore = ''; - $templateDesc = str_replace("{load_more}", $loadMore, $templateDesc); +if (strpos($templateDesc, "{load_more}") !== false) { + $loadMore = ''; + $templateDesc = str_replace("{load_more}", $loadMore, $templateDesc); } // Replace Sub Category -if (strpos($templateDesc, "{category_loop_start}") !== false && strpos($templateDesc, "{category_loop_end}") !== false) -{ - $templateD1 = explode("{category_loop_start}", $templateDesc); - $templateD2 = explode("{category_loop_end}", $templateD1[1]); - $subcatTemplate = $templateD2[0]; - - if (strpos($subcatTemplate, '{category_thumb_image_2}') !== false) - { - $tag = '{category_thumb_image_2}'; - $hThumb = Redshop::getConfig()->get('THUMB_HEIGHT_2'); - $wThumb = Redshop::getConfig()->get('THUMB_WIDTH_2'); - } - elseif (strpos($subcatTemplate, '{category_thumb_image_3}') !== false) - { - $tag = '{category_thumb_image_3}'; - $hThumb = Redshop::getConfig()->get('THUMB_HEIGHT_3'); - $wThumb = Redshop::getConfig()->get('THUMB_WIDTH_3'); - } - elseif (strpos($subcatTemplate, '{category_thumb_image_1}') !== false) - { - $tag = '{category_thumb_image_1}'; - $hThumb = Redshop::getConfig()->get('THUMB_HEIGHT'); - $wThumb = Redshop::getConfig()->get('THUMB_WIDTH'); - } - else - { - $tag = '{category_thumb_image}'; - $hThumb = Redshop::getConfig()->get('THUMB_HEIGHT'); - $wThumb = Redshop::getConfig()->get('THUMB_WIDTH'); - } - - $catDetail = ""; - $extraFieldsForCurrentTemplate = RedshopHelperTemplate::getExtraFieldsForCurrentTemplate($extraFieldCategory, $subcatTemplate); - - for ($i = 0, $nc = count($categoryData); $i < $nc; $i++) - { - $row = $categoryData[$i]; - - // Filter categories based on Shopper group category ACL - $checkCid = RedshopHelperAccess::checkPortalCategoryPermission($row->id); - $sgportal = RedshopHelperShopper_Group::getShopperGroupPortal(); - $portal = 0; - - if (count($sgportal) > 0) - { - $portal = $sgportal->shopper_group_portal; - } - - if (!$checkCid && (Redshop::getConfig()->get('PORTAL_SHOP') == 1 || $portal == 1)) - { - continue; - } - - $dataAdd = $subcatTemplate; - - $categoryItemId = RedshopHelperRouter::getCategoryItemid($row->id); - - $link = JRoute::_( - 'index.php?option=com_redshop&view=category&cid=' - . $row->id . '&manufacturer_id=' - . $categoryModel->getState('manufacturer_id') . '&layout=detail&Itemid=' - . $categoryItemId - ); - - $middlePath = REDSHOP_FRONT_IMAGES_RELPATH . 'category/'; - $title = " title='" . $row->name . "' "; - $alt = " alt='" . $row->name . "' "; - $productImage = REDSHOP_FRONT_IMAGES_ABSPATH . "noimage.jpg"; - $linkImage = $productImage; - - if ($row->category_full_image && JFile::exists($middlePath . $row->category_full_image)) - { - $categoryFullImage = $row->category_full_image; - $productImage = RedshopHelperMedia::watermark( - 'category', - $row->category_full_image, - $wThumb, - $hThumb, - Redshop::getConfig()->get('WATERMARK_CATEGORY_THUMB_IMAGE'), - '0' - ); - - $linkImage = RedshopHelperMedia::watermark( - 'category', - $row->category_full_image, - '', - '', - Redshop::getConfig()->get('WATERMARK_CATEGORY_IMAGE'), - '0' - ); - } - elseif (Redshop::getConfig()->get('CATEGORY_DEFAULT_IMAGE') && JFile::exists($middlePath . Redshop::getConfig()->get('CATEGORY_DEFAULT_IMAGE'))) - { - $categoryFullImage = Redshop::getConfig()->get('CATEGORY_DEFAULT_IMAGE'); - $productImage = RedshopHelperMedia::watermark( - 'category', - Redshop::getConfig()->get('CATEGORY_DEFAULT_IMAGE'), - $wThumb, - $hThumb, - Redshop::getConfig()->get('WATERMARK_CATEGORY_THUMB_IMAGE'), - '0' - ); - - $linkImage = RedshopHelperMedia::watermark( - 'category', - Redshop::getConfig()->get('CATEGORY_DEFAULT_IMAGE'), - '', - '', - Redshop::getConfig()->get('WATERMARK_CATEGORY_IMAGE'), - '0' - ); - } - - if (Redshop::getConfig()->get('CAT_IS_LIGHTBOX')) - { - $catThumb = ""; - } - else - { - $catThumb = ""; - } - - $catThumb .= ""; - $catThumb .= ""; - $dataAdd = str_replace($tag, $catThumb, $dataAdd); - - if (strpos($dataAdd, '{category_name}') !== false) - { - $catName = '' . $row->name . ''; - $dataAdd = str_replace("{category_name}", $catName, $dataAdd); - } - - if (strpos($dataAdd, '{category_readmore}') !== false) - { - $catName = '' . JText::_('COM_REDSHOP_READ_MORE') . ''; - $dataAdd = str_replace("{category_readmore}", $catName, $dataAdd); - } - - if (strpos($dataAdd, '{category_description}') !== false) - { - $catDesc = $redconfiguration->maxchar( - $row->description, - Redshop::getConfig()->get('CATEGORY_SHORT_DESC_MAX_CHARS'), - Redshop::getConfig()->get('CATEGORY_SHORT_DESC_END_SUFFIX') - ); - - $dataAdd = str_replace("{category_description}", $catDesc, $dataAdd); - } - - if (strpos($dataAdd, '{category_short_desc}') !== false) - { - $catShortDesc = $redconfiguration->maxchar( - $row->short_description, - Redshop::getConfig()->get('CATEGORY_SHORT_DESC_MAX_CHARS'), - Redshop::getConfig()->get('CATEGORY_SHORT_DESC_END_SUFFIX') - ); - - $dataAdd = str_replace("{category_short_desc}", $catShortDesc, $dataAdd); - } - - if (strpos($dataAdd, '{category_total_product}') !== false) - { - $totalprd = RedshopHelperProduct::getProductCategory($row->id); - $dataAdd = str_replace("{category_total_product}", count($totalprd), $dataAdd); - $dataAdd = str_replace("{category_total_product_lbl}", JText::_('COM_REDSHOP_TOTAL_PRODUCT'), $dataAdd); - } - - /* - * Category template extra field - * "2" argument is set for category - */ - if ($extraFieldsForCurrentTemplate) - { - $dataAdd = Redshop\Helper\ExtraFields::displayExtraFields(2, $row->id, $extraFieldsForCurrentTemplate, $dataAdd); - } - - $catDetail .= $dataAdd; - } - - $templateDesc = str_replace("{category_loop_start}", "", $templateDesc); - $templateDesc = str_replace("{category_loop_end}", "", $templateDesc); - $templateDesc = str_replace($subcatTemplate, $catDetail, $templateDesc); +if (strpos($templateDesc, "{category_loop_start}") !== false && strpos( + $templateDesc, + "{category_loop_end}" + ) !== false) { + $templateD1 = explode("{category_loop_start}", $templateDesc); + $templateD2 = explode("{category_loop_end}", $templateD1[1]); + $subcatTemplate = $templateD2[0]; + + if (strpos($subcatTemplate, '{category_thumb_image_2}') !== false) { + $tag = '{category_thumb_image_2}'; + $hThumb = Redshop::getConfig()->get('THUMB_HEIGHT_2'); + $wThumb = Redshop::getConfig()->get('THUMB_WIDTH_2'); + } elseif (strpos($subcatTemplate, '{category_thumb_image_3}') !== false) { + $tag = '{category_thumb_image_3}'; + $hThumb = Redshop::getConfig()->get('THUMB_HEIGHT_3'); + $wThumb = Redshop::getConfig()->get('THUMB_WIDTH_3'); + } elseif (strpos($subcatTemplate, '{category_thumb_image_1}') !== false) { + $tag = '{category_thumb_image_1}'; + $hThumb = Redshop::getConfig()->get('THUMB_HEIGHT'); + $wThumb = Redshop::getConfig()->get('THUMB_WIDTH'); + } else { + $tag = '{category_thumb_image}'; + $hThumb = Redshop::getConfig()->get('THUMB_HEIGHT'); + $wThumb = Redshop::getConfig()->get('THUMB_WIDTH'); + } + + $catDetail = ""; + $extraFieldsForCurrentTemplate = RedshopHelperTemplate::getExtraFieldsForCurrentTemplate( + $extraFieldCategory, + $subcatTemplate + ); + + for ($i = 0, $nc = count($categoryData); $i < $nc; $i++) { + $row = $categoryData[$i]; + + // Filter categories based on Shopper group category ACL + $checkCid = RedshopHelperAccess::checkPortalCategoryPermission($row->id); + $sgportal = RedshopHelperShopper_Group::getShopperGroupPortal(); + $portal = 0; + + if (count($sgportal) > 0) { + $portal = $sgportal->shopper_group_portal; + } + + if (!$checkCid && (Redshop::getConfig()->get('PORTAL_SHOP') == 1 || $portal == 1)) { + continue; + } + + $dataAdd = $subcatTemplate; + + $categoryItemId = RedshopHelperRouter::getCategoryItemid($row->id); + + $link = JRoute::_( + 'index.php?option=com_redshop&view=category&cid=' + . $row->id . '&manufacturer_id=' + . $categoryModel->getState('manufacturer_id') . '&layout=detail&Itemid=' + . $categoryItemId + ); + + $middlePath = REDSHOP_FRONT_IMAGES_RELPATH . 'category/'; + $title = " title='" . $row->name . "' "; + $alt = " alt='" . $row->name . "' "; + $productImage = REDSHOP_FRONT_IMAGES_ABSPATH . "noimage.jpg"; + $linkImage = $productImage; + + if ($row->category_full_image && JFile::exists($middlePath . $row->category_full_image)) { + $categoryFullImage = $row->category_full_image; + $productImage = RedshopHelperMedia::watermark( + 'category', + $row->category_full_image, + $wThumb, + $hThumb, + Redshop::getConfig()->get('WATERMARK_CATEGORY_THUMB_IMAGE'), + '0' + ); + + $linkImage = RedshopHelperMedia::watermark( + 'category', + $row->category_full_image, + '', + '', + Redshop::getConfig()->get('WATERMARK_CATEGORY_IMAGE'), + '0' + ); + } elseif (Redshop::getConfig()->get('CATEGORY_DEFAULT_IMAGE') && JFile::exists( + $middlePath . Redshop::getConfig()->get('CATEGORY_DEFAULT_IMAGE') + )) { + $categoryFullImage = Redshop::getConfig()->get('CATEGORY_DEFAULT_IMAGE'); + $productImage = RedshopHelperMedia::watermark( + 'category', + Redshop::getConfig()->get('CATEGORY_DEFAULT_IMAGE'), + $wThumb, + $hThumb, + Redshop::getConfig()->get('WATERMARK_CATEGORY_THUMB_IMAGE'), + '0' + ); + + $linkImage = RedshopHelperMedia::watermark( + 'category', + Redshop::getConfig()->get('CATEGORY_DEFAULT_IMAGE'), + '', + '', + Redshop::getConfig()->get('WATERMARK_CATEGORY_IMAGE'), + '0' + ); + } + + if (Redshop::getConfig()->get('CAT_IS_LIGHTBOX')) { + $catThumb = ""; + } else { + $catThumb = ""; + } + + $catThumb .= ""; + $catThumb .= ""; + $dataAdd = str_replace($tag, $catThumb, $dataAdd); + + if (strpos($dataAdd, '{category_name}') !== false) { + $catName = '' . $row->name . ''; + $dataAdd = str_replace("{category_name}", $catName, $dataAdd); + } + + if (strpos($dataAdd, '{category_readmore}') !== false) { + $catName = '' . JText::_('COM_REDSHOP_READ_MORE') . ''; + $dataAdd = str_replace("{category_readmore}", $catName, $dataAdd); + } + + if (strpos($dataAdd, '{category_description}') !== false) { + $catDesc = $redconfiguration->maxchar( + $row->description, + Redshop::getConfig()->get('CATEGORY_SHORT_DESC_MAX_CHARS'), + Redshop::getConfig()->get('CATEGORY_SHORT_DESC_END_SUFFIX') + ); + + $dataAdd = str_replace("{category_description}", $catDesc, $dataAdd); + } + + if (strpos($dataAdd, '{category_short_desc}') !== false) { + $catShortDesc = $redconfiguration->maxchar( + $row->short_description, + Redshop::getConfig()->get('CATEGORY_SHORT_DESC_MAX_CHARS'), + Redshop::getConfig()->get('CATEGORY_SHORT_DESC_END_SUFFIX') + ); + + $dataAdd = str_replace("{category_short_desc}", $catShortDesc, $dataAdd); + } + + if (strpos($dataAdd, '{category_total_product}') !== false) { + $totalprd = RedshopHelperProduct::getProductCategory($row->id); + $dataAdd = str_replace("{category_total_product}", count($totalprd), $dataAdd); + $dataAdd = str_replace("{category_total_product_lbl}", JText::_('COM_REDSHOP_TOTAL_PRODUCT'), $dataAdd); + } + + /* + * Category template extra field + * "2" argument is set for category + */ + if ($extraFieldsForCurrentTemplate) { + $dataAdd = Redshop\Helper\ExtraFields::displayExtraFields( + 2, + $row->id, + $extraFieldsForCurrentTemplate, + $dataAdd + ); + } + + $catDetail .= $dataAdd; + } + + $templateDesc = str_replace("{category_loop_start}", "", $templateDesc); + $templateDesc = str_replace("{category_loop_end}", "", $templateDesc); + $templateDesc = str_replace($subcatTemplate, $catDetail, $templateDesc); } -if (strpos($templateDesc, "{if subcats}") !== false && strpos($templateDesc, "{subcats end if}") !== false) -{ - $templateD1 = explode("{if subcats}", $templateDesc); - $templateD2 = explode("{subcats end if}", $templateD1[1]); - - if (count($categoryData) > 0) - { - $templateDesc = str_replace("{if subcats}", "", $templateDesc); - $templateDesc = str_replace("{subcats end if}", "", $templateDesc); - } - else - { - $templateDesc = $templateD1[0] . $templateD2[1]; - } +if (strpos($templateDesc, "{if subcats}") !== false && strpos($templateDesc, "{subcats end if}") !== false) { + $templateD1 = explode("{if subcats}", $templateDesc); + $templateD2 = explode("{subcats end if}", $templateD1[1]); + + if (count($categoryData) > 0) { + $templateDesc = str_replace("{if subcats}", "", $templateDesc); + $templateDesc = str_replace("{subcats end if}", "", $templateDesc); + } else { + $templateDesc = $templateD1[0] . $templateD2[1]; + } } // End replace sub category // Replace Main Category -if (strpos($templateDesc, '{category_main_description}') !== false) -{ - $mainCategoryDesc = $redconfiguration->maxchar( - $mainCategory->description, - Redshop::getConfig()->get('CATEGORY_SHORT_DESC_MAX_CHARS'), - Redshop::getConfig()->get('CATEGORY_SHORT_DESC_END_SUFFIX') - ); - - $templateDesc = str_replace("{category_main_description}", $mainCategoryDesc, $templateDesc); +if (strpos($templateDesc, '{category_main_description}') !== false) { + $mainCategoryDesc = $redconfiguration->maxchar( + $mainCategory->description, + Redshop::getConfig()->get('CATEGORY_SHORT_DESC_MAX_CHARS'), + Redshop::getConfig()->get('CATEGORY_SHORT_DESC_END_SUFFIX') + ); + + $templateDesc = str_replace("{category_main_description}", $mainCategoryDesc, $templateDesc); } -if (strpos($templateDesc, '{category_main_short_desc}') !== false) -{ - $mainCategoryShortDesc = $redconfiguration->maxchar( - $mainCategory->short_description, - Redshop::getConfig()->get('CATEGORY_SHORT_DESC_MAX_CHARS'), - Redshop::getConfig()->get('CATEGORY_SHORT_DESC_END_SUFFIX') - ); +if (strpos($templateDesc, '{category_main_short_desc}') !== false) { + $mainCategoryShortDesc = $redconfiguration->maxchar( + $mainCategory->short_description, + Redshop::getConfig()->get('CATEGORY_SHORT_DESC_MAX_CHARS'), + Redshop::getConfig()->get('CATEGORY_SHORT_DESC_END_SUFFIX') + ); - $templateDesc = str_replace("{category_main_short_desc}", $mainCategoryShortDesc, $templateDesc); + $templateDesc = str_replace("{category_main_short_desc}", $mainCategoryShortDesc, $templateDesc); } $mainCategoryName = ""; -if (strpos($templateDesc, '{category_main_name}') !== false) -{ - $mainCategoryName = $redconfiguration->maxchar( - $mainCategory->name, - Redshop::getConfig()->get('CATEGORY_TITLE_MAX_CHARS'), - Redshop::getConfig()->get('CATEGORY_TITLE_END_SUFFIX') - ); +if (strpos($templateDesc, '{category_main_name}') !== false) { + $mainCategoryName = $redconfiguration->maxchar( + $mainCategory->name, + Redshop::getConfig()->get('CATEGORY_TITLE_MAX_CHARS'), + Redshop::getConfig()->get('CATEGORY_TITLE_END_SUFFIX') + ); - $templateDesc = str_replace("{category_main_name}", $mainCategoryName, $templateDesc); + $templateDesc = str_replace("{category_main_name}", $mainCategoryName, $templateDesc); } -if (strpos($templateDesc, '{category_main_thumb_image_2}') !== false) -{ - $cTag = '{category_main_thumb_image_2}'; - $chThumb = Redshop::getConfig()->get('THUMB_HEIGHT_2'); - $cwThumb = Redshop::getConfig()->get('THUMB_WIDTH_2'); -} -elseif (strpos($templateDesc, '{category_main_thumb_image_3}') !== false) -{ - $cTag = '{category_main_thumb_image_3}'; - $chThumb = Redshop::getConfig()->get('THUMB_HEIGHT_3'); - $cwThumb = Redshop::getConfig()->get('THUMB_WIDTH_3'); -} -elseif (strpos($templateDesc, '{category_main_thumb_image_1}') !== false) -{ - $cTag = '{category_main_thumb_image_1}'; - $chThumb = Redshop::getConfig()->get('THUMB_HEIGHT'); - $cwThumb = Redshop::getConfig()->get('THUMB_WIDTH'); -} -else -{ - $cTag = '{category_main_thumb_image}'; - $chThumb = Redshop::getConfig()->get('THUMB_HEIGHT'); - $cwThumb = Redshop::getConfig()->get('THUMB_WIDTH'); +if (strpos($templateDesc, '{category_main_thumb_image_2}') !== false) { + $cTag = '{category_main_thumb_image_2}'; + $chThumb = Redshop::getConfig()->get('THUMB_HEIGHT_2'); + $cwThumb = Redshop::getConfig()->get('THUMB_WIDTH_2'); +} elseif (strpos($templateDesc, '{category_main_thumb_image_3}') !== false) { + $cTag = '{category_main_thumb_image_3}'; + $chThumb = Redshop::getConfig()->get('THUMB_HEIGHT_3'); + $cwThumb = Redshop::getConfig()->get('THUMB_WIDTH_3'); +} elseif (strpos($templateDesc, '{category_main_thumb_image_1}') !== false) { + $cTag = '{category_main_thumb_image_1}'; + $chThumb = Redshop::getConfig()->get('THUMB_HEIGHT'); + $cwThumb = Redshop::getConfig()->get('THUMB_WIDTH'); +} else { + $cTag = '{category_main_thumb_image}'; + $chThumb = Redshop::getConfig()->get('THUMB_HEIGHT'); + $cwThumb = Redshop::getConfig()->get('THUMB_WIDTH'); } $catMainThumb = ""; -if ($mainCategory->category_full_image && JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . 'category/' . $mainCategory->category_full_image)) -{ - $waterCatImg = RedshopHelperMedia::watermark( - 'category', - $mainCategory->category_full_image, - $cwThumb, - $chThumb, - Redshop::getConfig()->get('WATERMARK_CATEGORY_THUMB_IMAGE'), - '0' - ); - - $catMainThumb = "" . $mainCategoryName . ""; +if ($mainCategory->category_full_image && JFile::exists( + REDSHOP_FRONT_IMAGES_RELPATH . 'category/' . $mainCategory->category_full_image + )) { + $waterCatImg = RedshopHelperMedia::watermark( + 'category', + $mainCategory->category_full_image, + $cwThumb, + $chThumb, + Redshop::getConfig()->get('WATERMARK_CATEGORY_THUMB_IMAGE'), + '0' + ); + + $catMainThumb = "" . $mainCategoryName . ""; } $templateDesc = str_replace($cTag, $catMainThumb, $templateDesc); -if (strpos($templateDesc, "{include_product_in_sub_cat}") !== false) -{ - $templateDesc = str_replace("{include_product_in_sub_cat}", '', $templateDesc); +if (strpos($templateDesc, "{include_product_in_sub_cat}") !== false) { + $templateDesc = str_replace("{include_product_in_sub_cat}", '', $templateDesc); } // End replace Main Category // Replace Products -if (strpos($templateDesc, "{product_loop_start}") !== false && strpos($templateDesc, "{product_loop_end}") !== false) -{ - // Get only Product template - $templateD1 = explode("{product_loop_start}", $templateDesc); - $templateD2 = explode("{product_loop_end}", $templateD1[1]); - $templateProduct = $templateD2[0]; - - $attributeTemplate = \Redshop\Template\Helper::getAttribute($templateProduct); - $products = \Redshop\Product\Product::getProductsByIds($products); - $productIds = array(); - - // Loop product lists - foreach ($products as $product) - { - $catid = $product->category_id; - $productIds[] = $product->product_id; - - // Count accessory - $accessorylist = RedshopHelperAccessory::getProductAccessories(0, $product->product_id); - $totacc = count($accessorylist); - $netPrice = RedshopHelperProductPrice::getNetPrice($product->product_id); - $productPrice = $netPrice['productPrice']; - - $dataAdd = $templateProduct; - - // ProductFinderDatepicker Extra Field Start - $dataAdd = RedshopHelperProduct::getProductFinderDatepickerValue($dataAdd, $product->product_id, $fieldArray); - $itemData = RedshopHelperProduct::getMenuInformation(0, 0, '', 'product&pid=' . $product->product_id); - $pItemid = count($itemData) > 0 ? $itemData->id : RedshopHelperRouter::getItemId($product->product_id, $cid); - - $dataAdd = str_replace("{product_price}", RedshopHelperProductPrice::formattedPrice($productPrice), $dataAdd); - $dataAdd = str_replace("{product_id_lbl}", JText::_('COM_REDSHOP_PRODUCT_ID_LBL'), $dataAdd); - $dataAdd = str_replace("{product_id}", $product->product_id, $dataAdd); - $dataAdd = str_replace("{product_number_lbl}", JText::_('COM_REDSHOP_PRODUCT_NUMBER_LBL'), $dataAdd); - - $productNumberOutput = '' . $product->product_number . ''; - $dataAdd = str_replace("{product_number}", $productNumberOutput, $dataAdd); - - // Replace VAT information - $dataAdd = RedshopHelperTax::replaceVatInformation($dataAdd); - - $link = JRoute::_('index.php?option=com_redshop&view=product&pid=' . $product->product_id . '&cid=' . $catid . '&Itemid=' . $pItemid); - - $productName = RedshopHelperUtility::maxChars( - $product->product_name, - Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_MAX_CHARS'), - Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_END_SUFFIX') - ); - - if (!empty($keyword)) - { - $productName = preg_replace("/($keyword)/i", "$1", $productName); - } - - if (strstr($dataAdd, '{product_name_nolink}')) - { - $dataAdd = str_replace("{product_name_nolink}", $productName, $dataAdd); - } - - if (strstr($dataAdd, '{product_name}')) - { - $productName = "" . $productName . ""; - $dataAdd = str_replace("{product_name}", $productName, $dataAdd); - } - - if (strstr($dataAdd, '{category_product_link}')) - { - $dataAdd = str_replace("{category_product_link}", $link, $dataAdd); - } - - if (strstr($dataAdd, '{read_more}')) - { - $rmore = "" . JText::_('COM_REDSHOP_READ_MORE') . ""; - $dataAdd = str_replace("{read_more}", $rmore, $dataAdd); - } - - if (strstr($dataAdd, '{read_more_link}')) - { - $dataAdd = str_replace("{read_more_link}", $link, $dataAdd); - } - - if (strstr($dataAdd, '{product_s_desc}')) - { - $productShortDesc = RedshopHelperUtility::maxChars( - $product->product_s_desc, - Redshop::getConfig()->get('CATEGORY_PRODUCT_SHORT_DESC_MAX_CHARS'), - Redshop::getConfig()->get('CATEGORY_PRODUCT_SHORT_DESC_END_SUFFIX') - ); - - if (!empty($keyword)) - { - $productShortDesc = preg_replace("/($keyword)/i", "$1", $productShortDesc); - } - - $dataAdd = str_replace("{product_s_desc}", $productShortDesc, $dataAdd); - } - - if (strstr($dataAdd, '{product_desc}')) - { - $productDesc = RedshopHelperUtility::maxChars( - $product->product_desc, - Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_MAX_CHARS'), - Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_END_SUFFIX') - ); - - if (!empty($keyword)) - { - $productDesc = preg_replace("/($keyword)/i", "$1", $productDesc); - } - - $dataAdd = str_replace("{product_desc}", $productDesc, $dataAdd); - } - - if (strstr($dataAdd, '{product_rating_summary}')) - { - // Product Review/Rating Fetching reviews - $finalAvgReviewData = Redshop\Product\Rating::getRating($product->product_id); - $dataAdd = str_replace("{product_rating_summary}", $finalAvgReviewData, $dataAdd); - } - - if (strstr($dataAdd, '{manufacturer_link}')) - { - $manufacturerLinkHref = JRoute::_('index.php?option=com_redshop&view=manufacturers&layout=detail&mid=' . $product->manufacturer_id . '&Itemid=' . $itemId); - $manufacturerLink = ''; - - if ($product->manufacturer_name != '') - { - $manufacturerLink = '' . $product->manufacturer_name . ''; - } - - $dataAdd = str_replace("{manufacturer_link}", $manufacturerLink, $dataAdd); - - if (strstr($dataAdd, "{manufacturer_link}")) - { - $dataAdd = str_replace("{manufacturer_name}", "", $dataAdd); - } - } - - if (strstr($dataAdd, '{manufacturer_product_link}')) - { - $manufacturerPLink = "manufacturer_id . '&Itemid=' . $itemId) . "'>" . JText::_("COM_REDSHOP_VIEW_ALL_MANUFACTURER_PRODUCTS") . " " . $product->manufacturer_name . ""; - $dataAdd = str_replace("{manufacturer_product_link}", $manufacturerPLink, $dataAdd); - } - - if (strstr($dataAdd, '{manufacturer_name}')) - { - if ($product->manufacturer_name != "") - { - $dataAdd = str_replace("{manufacturer_name}", $product->manufacturer_name, $dataAdd); - } - else - { - $dataAdd = str_replace("{manufacturer_name}", "", $dataAdd); - } - } - - $extraFieldsForCurrentTemplate = RedshopHelperTemplate::getExtraFieldsForCurrentTemplate($extraFieldProduct, $templateProduct, 1); - - /* - * Product loop template extra field - * lat arg set to "1" for identify parsing data for product tag loop in category - * last arg will parse {producttag:NAMEOFPRODUCTTAG} nameing tags. - * "1" is for section as product - */ - if ($extraFieldsForCurrentTemplate) - { - $dataAdd = Redshop\Helper\ExtraFields::displayExtraFields( - 1, - $product->product_id, - $extraFieldsForCurrentTemplate, - $dataAdd, - true - ); - } - - if (strstr($dataAdd, "{product_thumb_image_3}")) - { - $pImgTag = '{product_thumb_image_3}'; - $phThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_3'); - $pwThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_3'); - } - elseif (strstr($dataAdd, "{product_thumb_image_2}")) - { - $pImgTag = '{product_thumb_image_2}'; - $phThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_2'); - $pwThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_2'); - } - elseif (strstr($dataAdd, "{product_thumb_image_1}")) - { - $pImgTag = '{product_thumb_image_1}'; - $phThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); - $pwThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); - } - else - { - $pImgTag = '{product_thumb_image}'; - $phThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); - $pwThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); - } - - $hiddenThumbImage = ""; - $thumbImage = Redshop\Product\Image\Image::getImage($product->product_id, $link, $pwThumb, $phThumb, 2, 1); - - // Product image flying addwishlist time start - $thumbImage = "" . Redshop\Product\Image\Image::getImage($product->product_id, $link, $pwThumb, $phThumb, 2, 1) . ""; - - // Product image flying addwishlist time end - $dataAdd = str_replace($pImgTag, $thumbImage . $hiddenThumbImage, $dataAdd); - - // Front-back image tag - if (strstr($dataAdd, "{front_img_link}") || strstr($dataAdd, "{back_img_link}")) - { - if ($this->_data->product_thumb_image) - { - $mainsrcPath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $product->product_thumb_image; - } - else - { - $mainsrcPath = $url . "components/com_redshop/helpers/thumb.php?filename=product/" . $product->product_full_image . "&newxsize=" . $pwThumb . "&newysize=" . $phThumb . "&swap=" . Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); - } - - if ($this->_data->product_back_thumb_image) - { - $backsrcPath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $product->product_back_thumb_image; - } - else - { - $backsrcPath = $url . "components/com_redshop/helpers/thumb.php?filename=product/" . $product->product_back_full_image . "&newxsize=" . $pwThumb . "&newysize=" . $phThumb . "&swap=" . Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); - } - - $aHrefPath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $product->product_full_image; - $aHrefBackPath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $product->product_back_full_image; - - $productFrontImageLink = "" . JText::_('COM_REDSHOP_FRONT_IMAGE') . ""; - $productBackImageLink = "" . JText::_('COM_REDSHOP_BACK_IMAGE') . ""; - - $dataAdd = str_replace("{front_img_link}", $productFrontImageLink, $dataAdd); - $dataAdd = str_replace("{back_img_link}", $productBackImageLink, $dataAdd); - } - else - { - $dataAdd = str_replace("{front_img_link}", "", $dataAdd); - $dataAdd = str_replace("{back_img_link}", "", $dataAdd); - } - - // Front-back image tag end - - - // Product preview image. - if (strstr($dataAdd, '{product_preview_img}')) - { - if (JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . 'product/' . $product->product_preview_image)) - { - $previewsrcPath = $url . "components/com_redshop/helpers/thumb.php?filename=product/" - . $product->product_preview_image . "&newxsize=" . Redshop::getConfig()->get('CATEGORY_PRODUCT_PREVIEW_IMAGE_WIDTH') - . "&newysize=" . Redshop::getConfig()->get('CATEGORY_PRODUCT_PREVIEW_IMAGE_HEIGHT') - . "&swap=" . Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); - $previewImg = ""; - $dataAdd = str_replace("{product_preview_img}", $previewImg, $dataAdd); - } - else - { - $dataAdd = str_replace("{product_preview_img}", "", $dataAdd); - } - } - - // Product preview image end. - - // Front-back preview image tag... - if (strstr($dataAdd, "{front_preview_img_link}") || strstr($dataAdd, "{back_preview_img_link}")) - { - if ($product->product_preview_image) - { - $mainPreviewSrcPath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $product->product_preview_image - . "&newxsize=" . Redshop::getConfig()->get('CATEGORY_PRODUCT_PREVIEW_IMAGE_WIDTH') . "&newysize=" - . Redshop::getConfig()->get('CATEGORY_PRODUCT_PREVIEW_IMAGE_HEIGHT') - . "&swap=" . Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); - } - - if ($product->product_preview_back_image) - { - $backPreviewSrcPath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" - . $product->product_preview_back_image . "&newxsize=" . Redshop::getConfig()->get('CATEGORY_PRODUCT_PREVIEW_IMAGE_WIDTH') - . "&newysize=" . Redshop::getConfig()->get('CATEGORY_PRODUCT_PREVIEW_IMAGE_HEIGHT') - . "&swap=" . Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); - } - - $productFrontImageLink = "" . JText::_('COM_REDSHOP_FRONT_IMAGE') . ""; - $productBackImageLink = "" . JText::_('COM_REDSHOP_BACK_IMAGE') . ""; - - $dataAdd = str_replace("{front_preview_img_link}", $productFrontImageLink, $dataAdd); - $dataAdd = str_replace("{back_preview_img_link}", $productBackImageLink, $dataAdd); - } - else - { - $dataAdd = str_replace("{front_preview_img_link}", "", $dataAdd); - $dataAdd = str_replace("{back_preview_img_link}", "", $dataAdd); - } - - // Front-back preview image tag end - - $dataAdd = RedshopHelperProduct::getJcommentEditor($product, $dataAdd); - - /* - * Conditional tag - * if product on discount : Yes - * {if product_on_sale} This product is on sale {product_on_sale end if} // OUTPUT : This product is on sale - * NO : // OUTPUT : Display blank - */ - $dataAdd = RedshopHelperProduct::getProductOnSaleComment($product, $dataAdd); - - // Replace Wishlist Button - $dataAdd = RedshopHelperWishlist::replaceWishlistTag($product->product_id, $dataAdd); - - // Replace compare product button - $dataAdd = Redshop\Product\Compare::replaceCompareProductsButton($product->product_id, $catid, $dataAdd); - - if (strstr($dataAdd, "{stockroom_detail}")) - { - $dataAdd = RedshopHelperStockroom::replaceStockroomAmountDetail($dataAdd, $product->product_id); - } - - // Checking for child products - $childProducts = RedshopHelperProduct::getChildProduct($product->product_id); - - if (count($childProducts) > 0) - { - if (Redshop::getConfig()->get('PURCHASE_PARENT_WITH_CHILD') == 1) - { - $isChilds = false; - - // Get attributes - $attributesSet = array(); - - if ($product->attribute_set_id > 0) - { - $attributesSet = \Redshop\Product\Attribute::getProductAttribute( - 0, - $product->attribute_set_id, - 0, - 1 - ); - } - - $attributes = \Redshop\Product\Attribute::getProductAttribute($product->product_id); - $attributes = array_merge($attributes, $attributesSet); - } - else - { - $isChilds = true; - $attributes = array(); - } - } - else - { - $isChilds = false; - - // Get attributes - $attributesSet = array(); - - if ($product->attribute_set_id > 0) - { - $attributesSet = \Redshop\Product\Attribute::getProductAttribute( - 0, - $product->attribute_set_id, - 0, - 1 - ); - } - - $attributes = \Redshop\Product\Attribute::getProductAttribute($product->product_id); - $attributes = array_merge($attributes, $attributesSet); - } - - $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($dataAdd); - $userfieldArr = $returnArr[1]; - - // Product attribute Start - $totalatt = count($attributes); - - // Check product for not for sale - $dataAdd = RedshopHelperProduct::getProductNotForSaleComment($product, $dataAdd, $attributes); - - $dataAdd = Redshop\Product\Stock::replaceInStock( - $product->product_id, - $dataAdd, - $attributes, - $attributeTemplate - ); - - $dataAdd = RedshopHelperAttribute::replaceAttributeData( - $product->product_id, - 0, - 0, - $attributes, - $dataAdd, - $attributeTemplate, - $isChilds - ); - - // Replace attribute with null value if it exist - if (!empty($attributeTemplate)) - { - $templateAttribute = "{attributeTemplate:" . $attributeTemplate->name . "}"; - - if (strstr($dataAdd, $templateAttribute)) - { - $dataAdd = str_replace($templateAttribute, "", $dataAdd); - } - } - - // Get cart template - $dataAdd = Redshop\Cart\Render::replace( - $product->product_id, - $catid, - 0, - 0, - $dataAdd, - $isChilds, - $userfieldArr, - $totalatt, - $totacc - ); - - $dataAdd = RedshopHelperProductTag::getExtraSectionTag($extraFieldProduct, $product->product_id, "1", $dataAdd); - - $results = $dispatcher->trigger('onPrepareProduct', array(&$dataAdd, &$params, $product)); - - $productData .= $dataAdd; - } - - $productTmpl = $productData; - - if (strstr($templateDesc, "{pagination}")) - { - $pagination = $displayData["pagination"]; - $templateDesc = str_replace("{pagination}", $pagination->getPaginationLinks('pagination.customize'), $templateDesc); - } - - $usePerPageLimit = false; - - if (strstr($templateDesc, "perpagelimit:")) - { - $usePerPageLimit = true; - $perpage = explode('{perpagelimit:', $templateDesc); - $perpage = explode('}', $perpage[1]); - $templateDesc = str_replace("{perpagelimit:" . intval($perpage[0]) . "}", "", $templateDesc); - } - - if (strstr($templateDesc, "{product_display_limit}")) - { - if ($usePerPageLimit == false) - { - $limitBox = ''; - } - else - { - $limitBox = $pagination->getLimitBox(); - } - - $templateDesc = str_replace("{product_display_limit}", $limitBox, $templateDesc); - } - - if (strpos($templateDesc, '{filter_by}') !== false) - { - /** @var JApplicationSite $app */ - $app = JFactory::getApplication(); - $data = $app->input->get('redform', array(), 'ARRAY'); - $min = isset($data['filterprice']['min']) ? (float) $data['filterprice']['min'] : 0.0; - $max = isset($data['filterprice']['max']) ? (float) $data['filterprice']['max'] : 0.0; - $templateId = isset($data['template_id']) ? (int) $data['template_id'] : 0; - - if (isset($data['cid'])) - { - $app->input->set('cid', $data['cid']); - } - - $temps = array( - (object) array( - 'id' => 0, - 'name' => JText::_('COM_REDSHOP_SELECT_MANUFACTURE') - ) - ); - - $manufacturers = array_merge($temps, $categoryModel->getManufacturer()); - $manufacturers = JHtml::_( - 'select.genericlist', - $manufacturers, - 'manufacturer_id', - 'class="inputbox form-control" onchange="javascript:setSliderMinMaxForManufactur();" ', - 'id', - 'name', - $categoryModel->getState('manufacturer_id') - ); - - $filterByForm = "
    "; - $filterByForm .= $manufacturers; - $filterByForm .= ""; - $filterByForm .= ""; - $filterByForm .= ""; - $filterByForm .= ''; - $filterByForm .= ""; - $filterByForm .= "
    "; - - $templateDesc = str_replace( - array('{filter_by_lbl}', '{filter_by}'), - array(JText::_('COM_REDSHOP_SELECT_FILTER_BY'), $filterByForm), - $templateDesc - ); - } - - $templateDesc = str_replace("{order_by_lbl}", JText::_('COM_REDSHOP_SELECT_ORDER_BY'), $templateDesc); - $templateDesc = str_replace("{order_by}", $orderBy, $templateDesc); - $templateDesc = str_replace("{filter_by_lbl}", '', $templateDesc); - $templateDesc = str_replace("{product_loop_start}", "", $templateDesc); - $templateDesc = str_replace("{product_loop_end}", "", $templateDesc); - $templateDesc = str_replace("{category_main_name}", $categoryDetail->name, $templateDesc); - $templateDesc = str_replace("{category_main_description}", '', $templateDesc); - $templateDesc = str_replace($templateProduct, $productTmpl, $templateDesc); - $templateDesc = str_replace("{with_vat}", "", $templateDesc); - $templateDesc = str_replace("{without_vat}", "", $templateDesc); - $templateDesc = str_replace("{attribute_price_with_vat}", "", $templateDesc); - $templateDesc = str_replace("{attribute_price_without_vat}", "", $templateDesc); - $templateDesc = str_replace("{redproductfinderfilter_formstart}", "", $templateDesc); - $templateDesc = str_replace("{product_price_slider1}", "", $templateDesc); - $templateDesc = str_replace("{redproductfinderfilter_formend}", "", $templateDesc); - $templateDesc = str_replace("{redproductfinderfilter:rp_myfilter}", "", $templateDesc); - - // Trigger plugin for content redshop - $templateDesc = RedshopHelperTemplate::parseRedshopPlugin($templateDesc); - $templateDesc = RedshopHelperText::replaceTexts($templateDesc); - $templateDesc .= ''; - $templateDesc .= ''; +if (strpos($templateDesc, "{product_loop_start}") !== false && strpos($templateDesc, "{product_loop_end}") !== false) { + // Get only Product template + $templateD1 = explode("{product_loop_start}", $templateDesc); + $templateD2 = explode("{product_loop_end}", $templateD1[1]); + $templateProduct = $templateD2[0]; + + $attributeTemplate = \Redshop\Template\Helper::getAttribute($templateProduct); + $products = \Redshop\Product\Product::getProductsByIds($products); + $productIds = array(); + + // Loop product lists + foreach ($products as $product) { + $catid = $product->category_id; + $productIds[] = $product->product_id; + + // Count accessory + $accessorylist = RedshopHelperAccessory::getProductAccessories(0, $product->product_id); + $totacc = count($accessorylist); + $netPrice = RedshopHelperProductPrice::getNetPrice($product->product_id); + $productPrice = $netPrice['productPrice']; + + $dataAdd = $templateProduct; + + // ProductFinderDatepicker Extra Field Start + $dataAdd = RedshopHelperProduct::getProductFinderDatepickerValue($dataAdd, $product->product_id, $fieldArray); + $itemData = RedshopHelperProduct::getMenuInformation(0, 0, '', 'product&pid=' . $product->product_id); + $pItemid = count($itemData) > 0 ? $itemData->id : RedshopHelperRouter::getItemId($product->product_id, $cid); + + $dataAdd = str_replace("{product_price}", RedshopHelperProductPrice::formattedPrice($productPrice), $dataAdd); + $dataAdd = str_replace("{product_id_lbl}", JText::_('COM_REDSHOP_PRODUCT_ID_LBL'), $dataAdd); + $dataAdd = str_replace("{product_id}", $product->product_id, $dataAdd); + $dataAdd = str_replace("{product_number_lbl}", JText::_('COM_REDSHOP_PRODUCT_NUMBER_LBL'), $dataAdd); + + $productNumberOutput = '' . $product->product_number . ''; + $dataAdd = str_replace("{product_number}", $productNumberOutput, $dataAdd); + + // Replace VAT information + $dataAdd = RedshopHelperTax::replaceVatInformation($dataAdd); + + $link = JRoute::_( + 'index.php?option=com_redshop&view=product&pid=' . $product->product_id . '&cid=' . $catid . '&Itemid=' . $pItemid + ); + + $productName = RedshopHelperUtility::maxChars( + $product->product_name, + Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_MAX_CHARS'), + Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_END_SUFFIX') + ); + + if (!empty($keyword)) { + $productName = preg_replace("/($keyword)/i", "$1", $productName); + } + + if (strstr($dataAdd, '{product_name_nolink}')) { + $dataAdd = str_replace("{product_name_nolink}", $productName, $dataAdd); + } + + if (strstr($dataAdd, '{product_name}')) { + $productName = "" . $productName . ""; + $dataAdd = str_replace("{product_name}", $productName, $dataAdd); + } + + if (strstr($dataAdd, '{category_product_link}')) { + $dataAdd = str_replace("{category_product_link}", $link, $dataAdd); + } + + if (strstr($dataAdd, '{read_more}')) { + $rmore = "" . JText::_( + 'COM_REDSHOP_READ_MORE' + ) . ""; + $dataAdd = str_replace("{read_more}", $rmore, $dataAdd); + } + + if (strstr($dataAdd, '{read_more_link}')) { + $dataAdd = str_replace("{read_more_link}", $link, $dataAdd); + } + + if (strstr($dataAdd, '{product_s_desc}')) { + $productShortDesc = RedshopHelperUtility::maxChars( + $product->product_s_desc, + Redshop::getConfig()->get('CATEGORY_PRODUCT_SHORT_DESC_MAX_CHARS'), + Redshop::getConfig()->get('CATEGORY_PRODUCT_SHORT_DESC_END_SUFFIX') + ); + + if (!empty($keyword)) { + $productShortDesc = preg_replace( + "/($keyword)/i", + "$1", + $productShortDesc + ); + } + + $dataAdd = str_replace("{product_s_desc}", $productShortDesc, $dataAdd); + } + + if (strstr($dataAdd, '{product_desc}')) { + $productDesc = RedshopHelperUtility::maxChars( + $product->product_desc, + Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_MAX_CHARS'), + Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_END_SUFFIX') + ); + + if (!empty($keyword)) { + $productDesc = preg_replace("/($keyword)/i", "$1", $productDesc); + } + + $dataAdd = str_replace("{product_desc}", $productDesc, $dataAdd); + } + + if (strstr($dataAdd, '{product_rating_summary}')) { + // Product Review/Rating Fetching reviews + $finalAvgReviewData = Redshop\Product\Rating::getRating($product->product_id); + $dataAdd = str_replace("{product_rating_summary}", $finalAvgReviewData, $dataAdd); + } + + if (strstr($dataAdd, '{manufacturer_link}')) { + $manufacturerLinkHref = JRoute::_( + 'index.php?option=com_redshop&view=manufacturers&layout=detail&mid=' . $product->manufacturer_id . '&Itemid=' . $itemId + ); + $manufacturerLink = ''; + + if ($product->manufacturer_name != '') { + $manufacturerLink = '' . $product->manufacturer_name . ''; + } + + $dataAdd = str_replace("{manufacturer_link}", $manufacturerLink, $dataAdd); + + if (strstr($dataAdd, "{manufacturer_link}")) { + $dataAdd = str_replace("{manufacturer_name}", "", $dataAdd); + } + } + + if (strstr($dataAdd, '{manufacturer_product_link}')) { + $manufacturerPLink = "manufacturer_id . '&Itemid=' . $itemId + ) . "'>" . JText::_( + "COM_REDSHOP_VIEW_ALL_MANUFACTURER_PRODUCTS" + ) . " " . $product->manufacturer_name . ""; + $dataAdd = str_replace("{manufacturer_product_link}", $manufacturerPLink, $dataAdd); + } + + if (strstr($dataAdd, '{manufacturer_name}')) { + if ($product->manufacturer_name != "") { + $dataAdd = str_replace("{manufacturer_name}", $product->manufacturer_name, $dataAdd); + } else { + $dataAdd = str_replace("{manufacturer_name}", "", $dataAdd); + } + } + + $extraFieldsForCurrentTemplate = RedshopHelperTemplate::getExtraFieldsForCurrentTemplate( + $extraFieldProduct, + $templateProduct, + 1 + ); + + /* + * Product loop template extra field + * lat arg set to "1" for identify parsing data for product tag loop in category + * last arg will parse {producttag:NAMEOFPRODUCTTAG} nameing tags. + * "1" is for section as product + */ + if ($extraFieldsForCurrentTemplate) { + $dataAdd = Redshop\Helper\ExtraFields::displayExtraFields( + 1, + $product->product_id, + $extraFieldsForCurrentTemplate, + $dataAdd, + true + ); + } + + if (strstr($dataAdd, "{product_thumb_image_3}")) { + $pImgTag = '{product_thumb_image_3}'; + $phThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_3'); + $pwThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_3'); + } elseif (strstr($dataAdd, "{product_thumb_image_2}")) { + $pImgTag = '{product_thumb_image_2}'; + $phThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_2'); + $pwThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_2'); + } elseif (strstr($dataAdd, "{product_thumb_image_1}")) { + $pImgTag = '{product_thumb_image_1}'; + $phThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); + $pwThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); + } else { + $pImgTag = '{product_thumb_image}'; + $phThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); + $pwThumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); + } + + $hiddenThumbImage = ""; + $thumbImage = Redshop\Product\Image\Image::getImage( + $product->product_id, + $link, + $pwThumb, + $phThumb, + 2, + 1 + ); + + // Product image flying addwishlist time start + $thumbImage = "" . Redshop\Product\Image\Image::getImage( + $product->product_id, + $link, + $pwThumb, + $phThumb, + 2, + 1 + ) . ""; + + // Product image flying addwishlist time end + $dataAdd = str_replace($pImgTag, $thumbImage . $hiddenThumbImage, $dataAdd); + + // Front-back image tag + if (strstr($dataAdd, "{front_img_link}") || strstr($dataAdd, "{back_img_link}")) { + if ($this->_data->product_thumb_image) { + $mainsrcPath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $product->product_thumb_image; + } else { + $mainsrcPath = $url . "components/com_redshop/helpers/thumb.php?filename=product/" . $product->product_full_image . "&newxsize=" . $pwThumb . "&newysize=" . $phThumb . "&swap=" . Redshop::getConfig( + )->get('USE_IMAGE_SIZE_SWAPPING'); + } + + if ($this->_data->product_back_thumb_image) { + $backsrcPath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $product->product_back_thumb_image; + } else { + $backsrcPath = $url . "components/com_redshop/helpers/thumb.php?filename=product/" . $product->product_back_full_image . "&newxsize=" . $pwThumb . "&newysize=" . $phThumb . "&swap=" . Redshop::getConfig( + )->get('USE_IMAGE_SIZE_SWAPPING'); + } + + $aHrefPath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $product->product_full_image; + $aHrefBackPath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $product->product_back_full_image; + + $productFrontImageLink = "" . JText::_( + 'COM_REDSHOP_FRONT_IMAGE' + ) . ""; + $productBackImageLink = "" . JText::_( + 'COM_REDSHOP_BACK_IMAGE' + ) . ""; + + $dataAdd = str_replace("{front_img_link}", $productFrontImageLink, $dataAdd); + $dataAdd = str_replace("{back_img_link}", $productBackImageLink, $dataAdd); + } else { + $dataAdd = str_replace("{front_img_link}", "", $dataAdd); + $dataAdd = str_replace("{back_img_link}", "", $dataAdd); + } + + // Front-back image tag end + + + // Product preview image. + if (strstr($dataAdd, '{product_preview_img}')) { + if (JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . 'product/' . $product->product_preview_image)) { + $previewsrcPath = $url . "components/com_redshop/helpers/thumb.php?filename=product/" + . $product->product_preview_image . "&newxsize=" . Redshop::getConfig()->get( + 'CATEGORY_PRODUCT_PREVIEW_IMAGE_WIDTH' + ) + . "&newysize=" . Redshop::getConfig()->get('CATEGORY_PRODUCT_PREVIEW_IMAGE_HEIGHT') + . "&swap=" . Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); + $previewImg = ""; + $dataAdd = str_replace("{product_preview_img}", $previewImg, $dataAdd); + } else { + $dataAdd = str_replace("{product_preview_img}", "", $dataAdd); + } + } + + // Product preview image end. + + // Front-back preview image tag... + if (strstr($dataAdd, "{front_preview_img_link}") || strstr($dataAdd, "{back_preview_img_link}")) { + if ($product->product_preview_image) { + $mainPreviewSrcPath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . $product->product_preview_image + . "&newxsize=" . Redshop::getConfig()->get('CATEGORY_PRODUCT_PREVIEW_IMAGE_WIDTH') . "&newysize=" + . Redshop::getConfig()->get('CATEGORY_PRODUCT_PREVIEW_IMAGE_HEIGHT') + . "&swap=" . Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); + } + + if ($product->product_preview_back_image) { + $backPreviewSrcPath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" + . $product->product_preview_back_image . "&newxsize=" . Redshop::getConfig()->get( + 'CATEGORY_PRODUCT_PREVIEW_IMAGE_WIDTH' + ) + . "&newysize=" . Redshop::getConfig()->get('CATEGORY_PRODUCT_PREVIEW_IMAGE_HEIGHT') + . "&swap=" . Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); + } + + $productFrontImageLink = "" . JText::_( + 'COM_REDSHOP_FRONT_IMAGE' + ) . ""; + $productBackImageLink = "" . JText::_( + 'COM_REDSHOP_BACK_IMAGE' + ) . ""; + + $dataAdd = str_replace("{front_preview_img_link}", $productFrontImageLink, $dataAdd); + $dataAdd = str_replace("{back_preview_img_link}", $productBackImageLink, $dataAdd); + } else { + $dataAdd = str_replace("{front_preview_img_link}", "", $dataAdd); + $dataAdd = str_replace("{back_preview_img_link}", "", $dataAdd); + } + + // Front-back preview image tag end + + $dataAdd = RedshopHelperProduct::getJcommentEditor($product, $dataAdd); + + /* + * Conditional tag + * if product on discount : Yes + * {if product_on_sale} This product is on sale {product_on_sale end if} // OUTPUT : This product is on sale + * NO : // OUTPUT : Display blank + */ + $dataAdd = RedshopHelperProduct::getProductOnSaleComment($product, $dataAdd); + + // Replace Wishlist Button + $dataAdd = RedshopHelperWishlist::replaceWishlistTag($product->product_id, $dataAdd); + + // Replace compare product button + $dataAdd = Redshop\Product\Compare::replaceCompareProductsButton($product->product_id, $catid, $dataAdd); + + if (strstr($dataAdd, "{stockroom_detail}")) { + $dataAdd = RedshopHelperStockroom::replaceStockroomAmountDetail($dataAdd, $product->product_id); + } + + // Checking for child products + $childProducts = RedshopHelperProduct::getChildProduct($product->product_id); + + if (count($childProducts) > 0) { + if (Redshop::getConfig()->get('PURCHASE_PARENT_WITH_CHILD') == 1) { + $isChilds = false; + + // Get attributes + $attributesSet = array(); + + if ($product->attribute_set_id > 0) { + $attributesSet = \Redshop\Product\Attribute::getProductAttribute( + 0, + $product->attribute_set_id, + 0, + 1 + ); + } + + $attributes = \Redshop\Product\Attribute::getProductAttribute($product->product_id); + $attributes = array_merge($attributes, $attributesSet); + } else { + $isChilds = true; + $attributes = array(); + } + } else { + $isChilds = false; + + // Get attributes + $attributesSet = array(); + + if ($product->attribute_set_id > 0) { + $attributesSet = \Redshop\Product\Attribute::getProductAttribute( + 0, + $product->attribute_set_id, + 0, + 1 + ); + } + + $attributes = \Redshop\Product\Attribute::getProductAttribute($product->product_id); + $attributes = array_merge($attributes, $attributesSet); + } + + $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($dataAdd); + $userfieldArr = $returnArr[1]; + + // Product attribute Start + $totalatt = count($attributes); + + // Check product for not for sale + $dataAdd = RedshopHelperProduct::getProductNotForSaleComment($product, $dataAdd, $attributes); + + $dataAdd = Redshop\Product\Stock::replaceInStock( + $product->product_id, + $dataAdd, + $attributes, + $attributeTemplate + ); + + $dataAdd = RedshopHelperAttribute::replaceAttributeData( + $product->product_id, + 0, + 0, + $attributes, + $dataAdd, + $attributeTemplate, + $isChilds + ); + + // Replace attribute with null value if it exist + if (!empty($attributeTemplate)) { + $templateAttribute = "{attributeTemplate:" . $attributeTemplate->name . "}"; + + if (strstr($dataAdd, $templateAttribute)) { + $dataAdd = str_replace($templateAttribute, "", $dataAdd); + } + } + + // Get cart template + $dataAdd = Redshop\Cart\Render::replace( + $product->product_id, + $catid, + 0, + 0, + $dataAdd, + $isChilds, + $userfieldArr, + $totalatt, + $totacc + ); + + $dataAdd = RedshopHelperProductTag::getExtraSectionTag($extraFieldProduct, $product->product_id, "1", $dataAdd); + + $results = $dispatcher->trigger('onPrepareProduct', array(&$dataAdd, &$params, $product)); + + $productData .= $dataAdd; + } + + $productTmpl = $productData; + + if (strstr($templateDesc, "{pagination}")) { + $pagination = $displayData["pagination"]; + $templateDesc = str_replace( + "{pagination}", + $pagination->getPaginationLinks('pagination.customize'), + $templateDesc + ); + } + + $usePerPageLimit = false; + + if (strstr($templateDesc, "perpagelimit:")) { + $usePerPageLimit = true; + $perpage = explode('{perpagelimit:', $templateDesc); + $perpage = explode('}', $perpage[1]); + $templateDesc = str_replace("{perpagelimit:" . intval($perpage[0]) . "}", "", $templateDesc); + } + + if (strstr($templateDesc, "{product_display_limit}")) { + if ($usePerPageLimit == false) { + $limitBox = ''; + } else { + $limitBox = $pagination->getLimitBox(); + } + + $templateDesc = str_replace("{product_display_limit}", $limitBox, $templateDesc); + } + + if (strpos($templateDesc, '{filter_by}') !== false) { + /** @var JApplicationSite $app */ + $app = JFactory::getApplication(); + $data = $app->input->get('redform', array(), 'ARRAY'); + $min = isset($data['filterprice']['min']) ? (float)$data['filterprice']['min'] : 0.0; + $max = isset($data['filterprice']['max']) ? (float)$data['filterprice']['max'] : 0.0; + $templateId = isset($data['template_id']) ? (int)$data['template_id'] : 0; + + if (isset($data['cid'])) { + $app->input->set('cid', $data['cid']); + } + + $temps = array( + (object)array( + 'id' => 0, + 'name' => JText::_('COM_REDSHOP_SELECT_MANUFACTURE') + ) + ); + + $manufacturers = array_merge($temps, $categoryModel->getManufacturer()); + $manufacturers = JHtml::_( + 'select.genericlist', + $manufacturers, + 'manufacturer_id', + 'class="inputbox form-control" onchange="javascript:setSliderMinMaxForManufactur();" ', + 'id', + 'name', + $categoryModel->getState('manufacturer_id') + ); + + $filterByForm = "
    "; + $filterByForm .= $manufacturers; + $filterByForm .= ""; + $filterByForm .= ""; + $filterByForm .= ""; + $filterByForm .= ''; + $filterByForm .= ""; + $filterByForm .= "
    "; + + $templateDesc = str_replace( + array('{filter_by_lbl}', '{filter_by}'), + array(JText::_('COM_REDSHOP_SELECT_FILTER_BY'), $filterByForm), + $templateDesc + ); + } + + $templateDesc = str_replace("{order_by_lbl}", JText::_('COM_REDSHOP_SELECT_ORDER_BY'), $templateDesc); + $templateDesc = str_replace("{order_by}", $orderBy, $templateDesc); + $templateDesc = str_replace("{filter_by_lbl}", '', $templateDesc); + $templateDesc = str_replace("{product_loop_start}", "", $templateDesc); + $templateDesc = str_replace("{product_loop_end}", "", $templateDesc); + $templateDesc = str_replace("{category_main_name}", $categoryDetail->name, $templateDesc); + $templateDesc = str_replace("{category_main_description}", '', $templateDesc); + $templateDesc = str_replace($templateProduct, $productTmpl, $templateDesc); + $templateDesc = str_replace("{with_vat}", "", $templateDesc); + $templateDesc = str_replace("{without_vat}", "", $templateDesc); + $templateDesc = str_replace("{attribute_price_with_vat}", "", $templateDesc); + $templateDesc = str_replace("{attribute_price_without_vat}", "", $templateDesc); + $templateDesc = str_replace("{redproductfinderfilter_formstart}", "", $templateDesc); + $templateDesc = str_replace("{product_price_slider1}", "", $templateDesc); + $templateDesc = str_replace("{redproductfinderfilter_formend}", "", $templateDesc); + $templateDesc = str_replace("{redproductfinderfilter:rp_myfilter}", "", $templateDesc); + + // Trigger plugin for content redshop + $templateDesc = RedshopHelperTemplate::parseRedshopPlugin($templateDesc); + $templateDesc = RedshopHelperText::replaceTexts($templateDesc); + $templateDesc .= ''; + $templateDesc .= ''; } // End Replace Products diff --git a/component/site/layouts/index.html b/component/site/layouts/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/site/layouts/index.html +++ b/component/site/layouts/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/layouts/joomla/index.html b/component/site/layouts/joomla/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/site/layouts/joomla/index.html +++ b/component/site/layouts/joomla/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/layouts/joomla/pagination/index.html b/component/site/layouts/joomla/pagination/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/site/layouts/joomla/pagination/index.html +++ b/component/site/layouts/joomla/pagination/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/layouts/joomla/pagination/link.php b/component/site/layouts/joomla/pagination/link.php index f759eb24fed..8e37cf88441 100644 --- a/component/site/layouts/joomla/pagination/link.php +++ b/component/site/layouts/joomla/pagination/link.php @@ -13,89 +13,79 @@ $display = $item->text; -switch ((string) $item->text) -{ - // Check for "Start" item - case JText::_('JLIB_HTML_START'): - $icon = "icon-backward"; - break; +switch ((string)$item->text) { + // Check for "Start" item + case JText::_('JLIB_HTML_START'): + $icon = "icon-backward"; + break; - // Check for "Prev" item - case $item->text == JText::_('JPREV'): - $item->text = JText::_('JPREVIOUS'); - $icon = "icon-step-backward"; - break; + // Check for "Prev" item + case $item->text == JText::_('JPREV'): + $item->text = JText::_('JPREVIOUS'); + $icon = "icon-step-backward"; + break; - // Check for "Next" item - case JText::_('JNEXT'): - $icon = "icon-step-forward"; - break; + // Check for "Next" item + case JText::_('JNEXT'): + $icon = "icon-step-forward"; + break; - // Check for "End" item - case JText::_('JLIB_HTML_END'): - $icon = "icon-forward"; - break; + // Check for "End" item + case JText::_('JLIB_HTML_END'): + $icon = "icon-forward"; + break; - default: - $icon = null; - break; + default: + $icon = null; + break; } -if ($icon !== null) -{ - $display = ''; +if ($icon !== null) { + $display = ''; } -if ($displayData['active']) -{ - if ($item->base > 0) - { - $limit = 'limitstart.value=' . $item->base; - } - else - { - $limit = 'limitstart.value=0'; - } +if ($displayData['active']) { + if ($item->base > 0) { + $limit = 'limitstart.value=' . $item->base; + } else { + $limit = 'limitstart.value=0'; + } - $cssClasses = array(); + $cssClasses = array(); - $title = ''; + $title = ''; - if (!is_numeric($item->text)) - { - JHtml::_('bootstrap.tooltip'); - $cssClasses[] = 'hasTooltip'; - $title = ' title="' . $item->text . '" '; - } + if (!is_numeric($item->text)) { + JHtml::_('bootstrap.tooltip'); + $cssClasses[] = 'hasTooltip'; + $title = ' title="' . $item->text . '" '; + } - $onClick = ''; - $href = $item->link; + $onClick = ''; + $href = $item->link; - // Still using javascript approach in backend - if (JFactory::getApplication()->isAdmin()) - { - $onClick = 'onclick="document.adminForm.' . $item->prefix . 'limitstart.value=' . ($item->base > 0 ? $item->base : '0') . '; Joomla.submitform();return false;"'; - $href = '#'; - } -} -else -{ - $class = (property_exists($item, 'active') && $item->active) ? 'active' : 'disabled'; + // Still using javascript approach in backend + if (JFactory::getApplication()->isAdmin()) { + $onClick = 'onclick="document.adminForm.' . $item->prefix . 'limitstart.value=' . ($item->base > 0 ? $item->base : '0') . '; Joomla.submitform();return false;"'; + $href = '#'; + } +} else { + $class = (property_exists($item, 'active') && $item->active) ? 'active' : 'disabled'; } ?> -
  • - - - - href="" - > - - -
  • +
  • + + + + href="" + > + + +
  • -
  • - -
  • +
  • + +
  • is_company == 1) ? +$extra_field = extra_field::getInstance(); +$extra_section = ($billingAddresses->is_company == 1) ? RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS : RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS; ?> - is_company == 1) : ?> - - - - - - - - - - - - - - - - - address != "") : ?> - - - - - - - zipcode != "") : ?> - - - - - - - city != "") : ?> - - - - - - - country_code != "") : ?> - - - - - - - state_code, $billingAddresses->country_code); ?> - - - - - - - - phone != "") : ?> - - - - - - - user_email != "") : ?> - - - - - - - is_company == 1) : ?> - - ean_number != "") : ?> - - - - - - - - - - - - - - - - - - - get('SHOW_TAX_EXEMPT_INFRONT')) : ?> - tax_exempt == 1) - { - $tax_exempt = JText::_('COM_REDSHOP_TAX_YES'); - } - else - { - $tax_exempt = JText::_('COM_REDSHOP_TAX_NO'); - } - ?> - - - - - - - - - - users_info_id, 0, "", "", true); ?> + is_company == 1) : ?> + + + + + + + + + + + + + + + + + address != "") : ?> + + + + + + + zipcode != "") : ?> + + + + + + + city != "") : ?> + + + + + + + country_code != "") : ?> + + + + + + + state_code, $billingAddresses->country_code); ?> + + + + + + + + phone != "") : ?> + + + + + + + user_email != "") : ?> + + + + + + + is_company == 1) : ?> + + ean_number != "") : ?> + + + + + + + + + + + + + + + + + + + get('SHOW_TAX_EXEMPT_INFRONT')) : ?> + tax_exempt == 1) { + $tax_exempt = JText::_('COM_REDSHOP_TAX_YES'); + } else { + $tax_exempt = JText::_('COM_REDSHOP_TAX_NO'); + } + ?> + + + + + + + + + + users_info_id, + 0, + "", + "", + true + ); ?>
    :company_name;?>
    :firstname;?>
    :lastname;?>
    :address;?>
    :zipcode;?>
    :city;?>
    :country_code));?>
    :
    :phone;?>
    :user_email ? $billingAddresses->user_email : $user->email;?>
    :ean_number;?>
    :requisition_number;?>
    :vat_number;?>
    :
    :company_name; ?>
    :firstname; ?>
    :lastname; ?>
    :address; ?>
    :zipcode; ?>
    :city; ?>
    :country_code)); ?>
    :
    :phone; ?>
    :user_email ? $billingAddresses->user_email : $user->email; ?>
    :ean_number; ?>
    :requisition_number; ?>
    :vat_number; ?>
    :
    diff --git a/component/site/layouts/mail/index.html b/component/site/layouts/mail/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/site/layouts/mail/index.html +++ b/component/site/layouts/mail/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/layouts/mail/shipping.php b/component/site/layouts/mail/shipping.php index 8a027c6d840..78cb939662d 100644 --- a/component/site/layouts/mail/shipping.php +++ b/component/site/layouts/mail/shipping.php @@ -12,73 +12,83 @@ extract($displayData); $order_functions = order_functions::getInstance(); -$extra_field = extra_field::getInstance(); -$extra_section = ($shippingaddresses->is_company == 1) ? +$extra_field = extra_field::getInstance(); +$extra_section = ($shippingaddresses->is_company == 1) ? RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS : RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS; ?> - is_company == 1) : ?> - - - - - + is_company == 1) : ?> + + + + + - - - - + + + + - - - - + + + + - address != "") : ?> - - - - - + address != "") : ?> + + + + + - zipcode != "") : ?> - - - - - + zipcode != "") : ?> + + + + + - city != "") : ?> - - - - - + city != "") : ?> + + + + + - country_code != "") : ?> - - - - - + country_code != "") : ?> + + + + + - state_code, $shippingaddresses->country_code); ?> - - - - - - + state_code, + $shippingaddresses->country_code + ); ?> + + + + + + - phone != "") : ?> - - - - - + phone != "") : ?> + + + + + - users_info_id, 0, "", "", true); - ?> + users_info_id, + 0, + "", + "", + true + ); + ?>
    :company_name;?>
    :company_name; ?>
    :firstname;?>
    :firstname; ?>
    :lastname;?>
    :lastname; ?>
    :address;?>
    :address; ?>
    :zipcode;?>
    :zipcode; ?>
    :city;?>
    :city; ?>
    :country_code));?>
    :country_code)); ?>
    :
    :
    :phone;?>
    :phone; ?>
    diff --git a/component/site/layouts/order/index.html b/component/site/layouts/order/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/site/layouts/order/index.html +++ b/component/site/layouts/order/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/layouts/order/payment/creditcard.php b/component/site/layouts/order/payment/creditcard.php index 5055e10f1e0..cf9ef9ba701 100644 --- a/component/site/layouts/order/payment/creditcard.php +++ b/component/site/layouts/order/payment/creditcard.php @@ -54,40 +54,39 @@
    - +
    - get("accepted_credict_card", array()); + get("accepted_credict_card", array()); - for ($ic = 0, $nic = count($creditCard); $ic < $nic; $ic++) - { - $url = REDSHOP_FRONT_IMAGES_ABSPATH . 'checkout/' . $creditCardList[$creditCard[$ic]]->img; - $text = ''; - $cardTypes[] = JHtml::_('select.option', $creditCard[$ic], $text); - } + for ($ic = 0, $nic = count($creditCard); $ic < $nic; $ic++) { + $url = REDSHOP_FRONT_IMAGES_ABSPATH . 'checkout/' . $creditCardList[$creditCard[$ic]]->img; + $text = ''; + $cardTypes[] = JHtml::_('select.option', $creditCard[$ic], $text); + } - echo JHtml::_( - 'redshopselect.radiolist', - $cardTypes, - 'creditcard_code', - ['cssClassSuffix' => ''], - 'value', - 'text', - $creditCardData['creditcard_code'] ?? '' + echo JHtml::_( + 'redshopselect.radiolist', + $cardTypes, + 'creditcard_code', + ['cssClassSuffix' => ''], + 'value', + 'text', + $creditCardData['creditcard_code'] ?? '' ); - ?> + ?>
    - +
    - +
    - +
    - + echo JHtml::_( + 'select.genericlist', + $years, + 'order_payment_expire_year', + 'size="1" class="input-small" ', + 'value', + 'text', + $creditCardData['order_payment_expire_year'] ?? '' + ); + ?>
    - + 0) : ?>
    - - "; - echo ''; - ?> - + + "; + echo ''; + ?> +
    diff --git a/component/site/layouts/order/payment/index.html b/component/site/layouts/order/payment/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/site/layouts/order/payment/index.html +++ b/component/site/layouts/order/payment/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/layouts/order/status_log.php b/component/site/layouts/order/status_log.php index 980330be8fe..37af77046c7 100644 --- a/component/site/layouts/order/status_log.php +++ b/component/site/layouts/order/status_log.php @@ -12,8 +12,8 @@ /** * Layout variables * ============================= - * @var array $displayData Display data - * @var object $orderStatusLogs Order status log + * @var array $displayData Display data + * @var object $orderStatusLogs Order status log */ extract($displayData); ?> @@ -29,7 +29,9 @@ $log): ?>
  • - date_changed) ?> + date_changed + ) ?>
  • @@ -38,16 +40,26 @@

    : order_status_name ?> + class="label order_status_order_status + ) ?>">order_status_name ?>

    order_payment_status)): ?>

    : + class="label order_payment_status_unpaid">

    - order_payment_status))); ?> + order_payment_status) + ) + ); ?>

    : + class="label order_payment_status_order_payment_status + ) ?>">

    customer_note ?>

    @@ -61,19 +73,28 @@ class="label order_payment_status_order_payment_stat
     order_status_name ?> + class="label order_status_order_status + ) ?>">order_status_name ?>
  • order_payment_status != $nextLog->order_payment_status && $log->order_payment_status): ?> - order_payment_status))); ?> + order_payment_status) + ) + ); ?>
  • -   + +  
  • diff --git a/component/site/layouts/pagination/customize.php b/component/site/layouts/pagination/customize.php index 46d011ac8af..facfa5960d1 100755 --- a/component/site/layouts/pagination/customize.php +++ b/component/site/layouts/pagination/customize.php @@ -11,7 +11,7 @@ use Joomla\Registry\Registry; -$list = $displayData['list']; +$list = $displayData['list']; $pages = $list['pages']; $options = new Registry($displayData['options']); @@ -22,56 +22,49 @@ // Calculate to display range of pages $currentPage = 1; -$range = 1; -$step = 1; +$range = 1; +$step = 1; -if (!empty($pages['pages'])) -{ - foreach ($pages['pages'] as $k => $page) - { - if (!$page['active']) - { - $currentPage = $k; - } - } +if (!empty($pages['pages'])) { + foreach ($pages['pages'] as $k => $page) { + if (!$page['active']) { + $currentPage = $k; + } + } } -if ($currentPage >= $step) -{ - if ($currentPage % $step == 0) - { - $range = ceil($currentPage / $step) + 1; - } - else - { - $range = ceil($currentPage / $step); - } +if ($currentPage >= $step) { + if ($currentPage % $step == 0) { + $range = ceil($currentPage / $step) + 1; + } else { + $range = ceil($currentPage / $step); + } } ?> - -
    - -
    - + +
    + +
    + - -
      - - $page) : ?> + +
        + + $page) : ?> - - - - ).*?()#', '$1...$2', $output); ?> - - + + + + ).*?()#', '$1...$2', $output); ?> + + - - - -
      - + + + +
    + diff --git a/component/site/layouts/pagination/customize_link.php b/component/site/layouts/pagination/customize_link.php index 58756e3354d..9ab1da23cb0 100755 --- a/component/site/layouts/pagination/customize_link.php +++ b/component/site/layouts/pagination/customize_link.php @@ -13,84 +13,76 @@ $display = $item->text; -switch ((string) $item->text) -{ - // Check for "Start" item - case JText::_('JLIB_HTML_START') : - $icon = "pagenav icon-backward icon-first"; - $text = JText::_('JLIB_HTML_START'); - $class = "pagination-start"; - break; +switch ((string)$item->text) { + // Check for "Start" item + case JText::_('JLIB_HTML_START') : + $icon = "pagenav icon-backward icon-first"; + $text = JText::_('JLIB_HTML_START'); + $class = "pagination-start"; + break; - // Check for "Prev" item - case $item->text == JText::_('JPREV') : - $item->text = JText::_('JPREVIOUS'); - $icon = "pagenav icon-step-backward icon-previous"; - $text = JText::_('JPREVIOUS'); - $class = "pagination-prev"; - break; + // Check for "Prev" item + case $item->text == JText::_('JPREV') : + $item->text = JText::_('JPREVIOUS'); + $icon = "pagenav icon-step-backward icon-previous"; + $text = JText::_('JPREVIOUS'); + $class = "pagination-prev"; + break; - // Check for "Next" item - case JText::_('JNEXT') : - $icon = "icon-step-forward icon-next"; - $text = JText::_('JNEXT'); - $class = "pagination-next"; - break; + // Check for "Next" item + case JText::_('JNEXT') : + $icon = "icon-step-forward icon-next"; + $text = JText::_('JNEXT'); + $class = "pagination-next"; + break; - // Check for "End" item - case JText::_('JLIB_HTML_END') : - $icon = "icon-forward icon-last"; - $text = JText::_('JLIB_HTML_END'); - $class = "pagination-end"; - break; + // Check for "End" item + case JText::_('JLIB_HTML_END') : + $icon = "icon-forward icon-last"; + $text = JText::_('JLIB_HTML_END'); + $class = "pagination-end"; + break; - default: - $icon = null; - break; + default: + $icon = null; + break; } -if ($icon !== null) -{ - $display = $text; +if ($icon !== null) { + $display = $text; } -if ($displayData['active']) -{ - if ($item->base > 0) - { - $limit = 'limitstart.value=' . $item->base; - } - else - { - $limit = 'limitstart.value=0'; - } +if ($displayData['active']) { + if ($item->base > 0) { + $limit = 'limitstart.value=' . $item->base; + } else { + $limit = 'limitstart.value=0'; + } - $cssClasses = array(); + $cssClasses = array(); - $title = ''; + $title = ''; - if (!is_numeric($item->text)) - { - JHtml::_('bootstrap.tooltip'); - $cssClasses[] = 'hasTooltip'; - $title = ' title="' . $item->text . '" '; - } + if (!is_numeric($item->text)) { + JHtml::_('bootstrap.tooltip'); + $cssClasses[] = 'hasTooltip'; + $title = ' title="' . $item->text . '" '; + } - $onClick = 'pagination(' . ($item->base > 0 ? $item->base : '0') . ');'; -} -else -{ - $class = (property_exists($item, 'active') && $item->active) ? 'pagenav' : $class; + $onClick = 'pagination(' . ($item->base > 0 ? $item->base : '0') . ');'; +} else { + $class = (property_exists($item, 'active') && $item->active) ? 'pagenav' : $class; } ?> -
  • - href="javascript:void(0);" onclick=""> - - -
  • +
  • + href="javascript:void(0);" + onclick=""> + + +
  • -
  • - -
  • +
  • + +
  • \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/layouts/product/compare.php b/component/site/layouts/product/compare.php index e8c96bae58e..04c9f02656b 100644 --- a/component/site/layouts/product/compare.php +++ b/component/site/layouts/product/compare.php @@ -10,17 +10,19 @@ defined('_JEXEC') or die; $itemId = RedshopHelperRouter::getRedShopMenuItem( - array( - 'option' => 'com_redshop', - 'view' => 'product', - 'layout' => 'compare' - ) + array( + 'option' => 'com_redshop', + 'view' => 'product', + 'layout' => 'compare' + ) ); $compareLink = JRoute::_('index.php?option=com_redshop&view=product&layout=compare&Itemid=' . $itemId); ?>
    - +
    diff --git a/component/site/layouts/product/compare_ajax.php b/component/site/layouts/product/compare_ajax.php index ba16ab9c9fa..c805fd5d424 100644 --- a/component/site/layouts/product/compare_ajax.php +++ b/component/site/layouts/product/compare_ajax.php @@ -12,38 +12,37 @@ /** * $displayData extract * - * @param object $form A JForm object - * @param int $productId Id current product - * @param int $modal Flag use form in modal + * @param object $form A JForm object + * @param int $productId Id current product + * @param int $modal Flag use form in modal */ extract($displayData); -$compare = $displayData['object']; -$cmd = JFactory::getApplication()->input->get('cmd'); -$total = $compare->getItemsTotal(); +$compare = $displayData['object']; +$cmd = JFactory::getApplication()->input->get('cmd'); +$total = $compare->getItemsTotal(); ?> getItems()) > 0) : ?>
      - getItems() as $data) : ?> - productId; - $categoryId = $data['item']->categoryId; - $product = \Redshop\Product\Product::getProductById($productId); + getItems() as $data) : ?> + productId; + $categoryId = $data['item']->categoryId; + $product = \Redshop\Product\Product::getProductById($productId); - $ItemData = RedshopHelperProduct::getMenuInformation(0, 0, '', 'product&pid=' . $product->product_id); - $catidmain = $product->cat_in_sefurl; + $ItemData = RedshopHelperProduct::getMenuInformation(0, 0, '', 'product&pid=' . $product->product_id); + $catidmain = $product->cat_in_sefurl; - if (count($ItemData) > 0) - { - $pItemid = $ItemData->id; - } - else - { - $pItemid = RedshopHelperRouter::getItemId($product->product_id, $catidmain); - } + if (count($ItemData) > 0) { + $pItemid = $ItemData->id; + } else { + $pItemid = RedshopHelperRouter::getItemId($product->product_id, $catidmain); + } - $link = JRoute::_('index.php?option=com_redshop&view=product&pid=' . $productId . '&cid=' . $categoryId . '&Itemid=' . $pItemid); - ?> + $link = JRoute::_( + 'index.php?option=com_redshop&view=product&pid=' . $productId . '&cid=' . $categoryId . '&Itemid=' . $pItemid + ); + ?>
    • product_name ?> @@ -55,7 +54,7 @@
    • - +
    diff --git a/component/site/layouts/product/index.html b/component/site/layouts/product/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/site/layouts/product/index.html +++ b/component/site/layouts/product/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/layouts/product/order_attribute.php b/component/site/layouts/product/order_attribute.php index 78877fa614a..2e17850ce1e 100644 --- a/component/site/layouts/product/order_attribute.php +++ b/component/site/layouts/product/order_attribute.php @@ -10,7 +10,7 @@ defined('_JEXEC') or die; extract($displayData); -$orderFunctions = order_functions::getInstance(); +$orderFunctions = order_functions::getInstance(); ?> @@ -31,19 +31,36 @@
    - section_id); ?> + section_id + ); ?> - section_id, $orderPropdata[$p]->parent_section_id, 0, 0, 0, 0, false); ?> + section_id, + $orderPropdata[$p]->parent_section_id, + 0, + 0, + 0, + 0, + false + ); ?> section_price + $orderPropdata[$p]->section_vat; ?> - section_oprand . Redshop::getConfig()->get('REDCURRENCY_SYMBOL') . $propertyPrice . ")"; ?> + section_oprand . Redshop::getConfig()->get( + 'REDCURRENCY_SYMBOL' + ) . $propertyPrice . ")"; ?> - section_oprand . RedshopHelperProductPrice::formattedPrice($propertyPrice) . ")"; ?> + section_oprand . RedshopHelperProductPrice::formattedPrice( + $propertyPrice + ) . ")"; ?> section_oprand; ?> @@ -64,26 +81,39 @@ property_number) . $disPrice; ?>
    - property_number)) :?> + property_number)) : ?>
    property_number; ?>
    - section_id); ?> + section_id + ); ?> section_id)) : ?> section_price; ?> - section_id, $orderSubpropdata[$sp]->parent_section_id, false); ?> + section_id, + $orderSubpropdata[$sp]->parent_section_id, + false + ); ?> section_price + $orderSubpropdata[$sp]->section_vat; ?> - section_oprand . Redshop::getConfig()->get('REDCURRENCY_SYMBOL') . $subPropertyPrice . ")"; ?> + section_oprand . Redshop::getConfig()->get( + 'REDCURRENCY_SYMBOL' + ) . $subPropertyPrice . ")"; ?> - section_oprand . RedshopHelperProductPrice::formattedPrice($subPropertyPrice) . ")"; ?> + section_oprand . RedshopHelperProductPrice::formattedPrice( + $subPropertyPrice + ) . ")"; ?> section_oprand; ?> diff --git a/component/site/layouts/product/product_accessory.php b/component/site/layouts/product/product_accessory.php index f893419919c..9ad626670f7 100644 --- a/component/site/layouts/product/product_accessory.php +++ b/component/site/layouts/product/product_accessory.php @@ -12,101 +12,129 @@ /** * $displayData extract * - * @param array $accessories Accessory Data - * @param int $productId Product id - * @param int $userId User id - * @param boolean $checkTag Check Tag + * @param array $accessories Accessory Data + * @param int $productId Product id + * @param int $userId User id + * @param boolean $checkTag Check Tag */ extract($displayData); ?> -
    - -
    - $accessory): ?> - - - 0): ?> - - - - - - - get('DEFAULT_QUOTATION_MODE') && !Redshop::getConfig()->get('SHOW_QUOTATION_PRICE')): ?> - - -
    - -
    - - - - - - - - 0): ?> - hide_attribute_price; ?> - -
    - : -
    - - - - 0): ?> - - - - - - - get('DEFAULT_QUOTATION_MODE') && !Redshop::getConfig()->get('SHOW_QUOTATION_PRICE') || $hideAttribute): ?> - - - - - 0 && $property[0]->property_number) : ?> - " . $property[0]->property_number - . "
    "; ?> - -
    -
    - -
    - -
    - - - - - 0): ?> - - - - - - - get('DEFAULT_QUOTATION_MODE') && !Redshop::getConfig()->get('SHOW_QUOTATION_PRICE') || $hideAttribute): ?> - - - - - 0 && $subProperty[0]->subattribute_color_number) : ?> - [" . $subProperty[0]->subattribute_color_number - . "]
    "; ?> - -
    -
    - -
    - -
    - - - - - - +
    + +
    + $accessory): ?> + + + 0): ?> + + + + + + + get('DEFAULT_QUOTATION_MODE') && !Redshop::getConfig()->get( + 'SHOW_QUOTATION_PRICE' + )): ?> + + +
    + +
    + + + + + + + + 0): ?> + hide_attribute_price; ?> + +
    + : +
    + + + + 0): ?> + + + + + + + get('DEFAULT_QUOTATION_MODE') && !Redshop::getConfig()->get( + 'SHOW_QUOTATION_PRICE' + ) || $hideAttribute): ?> + + + + + 0 && $property[0]->property_number) : ?> + " . $property[0]->property_number + . "
    "; ?> + +
    +
    + +
    + +
    + + + + + 0): ?> + + + + + + + get('DEFAULT_QUOTATION_MODE') && !Redshop::getConfig()->get( + 'SHOW_QUOTATION_PRICE' + ) || $hideAttribute): ?> + + + + + 0 && $subProperty[0]->subattribute_color_number) : ?> + [" . $subProperty[0]->subattribute_color_number + . "]"; ?> + +
    +
    + +
    + +
    + + + + + + diff --git a/component/site/layouts/product/product_attribute.php b/component/site/layouts/product/product_attribute.php index fbfb9a71795..4afb484d922 100644 --- a/component/site/layouts/product/product_attribute.php +++ b/component/site/layouts/product/product_attribute.php @@ -12,85 +12,93 @@ /** * Layout variables * ====================================== - * @var integer $displayData Layout data - * @var integer $displayAttribute Display attributes - * @var string $data HTML content - * @var array $attributes Attributes data + * @var integer $displayData Layout data + * @var integer $displayAttribute Display attributes + * @var string $data HTML content + * @var array $attributes Attributes data */ extract($displayData); ?> 0) : ?>
    - - - - - - hide_attribute_price; ?> - - 0) : ?> + + + + + + hide_attribute_price; ?> + + 0) : ?>
    - +
    - - - + + - get('DEFAULT_QUOTATION_MODE') && !Redshop::getConfig()->get('SHOW_QUOTATION_PRICE')) || $hideAttributePrice): ?> - - - - - - - 0 && $property[0]->property_number): ?> - " . $property[0]->property_number . ""; ?> - - - - + $propertyOperator = $properties[$k]['property_oprand']; + $propertyPrice = (isset($properties[$k]['property_price'])) ? $properties[$k]['property_price'] : 0; + $displayPrice = " (" . $propertyOperator . " " . RedshopHelperProductPrice::formattedPrice( + $propertyPrice + ) . ")"; + ?> + get('DEFAULT_QUOTATION_MODE') && !Redshop::getConfig()->get( + 'SHOW_QUOTATION_PRICE' + )) || $hideAttributePrice): ?> + + + + + + + 0 && $property[0]->property_number): ?> + " . $property[0]->property_number . ""; ?> + + + +
    - +
    - +
    - - 0): ?> + + 0): ?>
    - +
    - - - - - - get('DEFAULT_QUOTATION_MODE') && !Redshop::getConfig()->get('SHOW_QUOTATION_PRICE')) || $hideAttributePrice): ?> - - - - - - - - " . $subProperties[0]['subattribute_color_number'] . ""; ?> - - - - + + + + + + get('DEFAULT_QUOTATION_MODE') && !Redshop::getConfig()->get( + 'SHOW_QUOTATION_PRICE' + )) || $hideAttributePrice): ?> + + + + + + + + " . $subProperties[0]['subattribute_color_number'] . ""; ?> + + + +
    - +
    - +
    - - - + + + - - - - - $value): ?> - discount_price != 0 && $value->discount_start_date != 0 && $value->discount_end_date != 0 && $value->discount_start_date <= time() && $value->discount_end_date >= time()) : ?> - product_price = $value->discount_price; ?> - - product_price, $userId); - $price = RedshopHelperProductPrice::formattedPrice($value->product_price + $tax); - ?> - - - - - + + + + + $value): ?> + discount_price != 0 && $value->discount_start_date != 0 && $value->discount_end_date != 0 && $value->discount_start_date <= time( + ) && $value->discount_end_date >= time()) : ?> + product_price = $value->discount_price; ?> + + product_price, $userId); + $price = RedshopHelperProductPrice::formattedPrice($value->product_price + $tax); + ?> + + + + +
    price_quantity_start; ?> - price_quantity_end; ?>
    price_quantity_start; ?> - price_quantity_end; ?>
    \ No newline at end of file diff --git a/component/site/layouts/product/product_rating.php b/component/site/layouts/product/product_rating.php index e604eb65d57..267c188c973 100644 --- a/component/site/layouts/product/product_rating.php +++ b/component/site/layouts/product/product_rating.php @@ -12,14 +12,14 @@ /** * $displayData extract * - * @param object $form A JForm object + * @param object $form A JForm object * @param int $productId Id current product - * @param int $modal Flag use form in modal + * @param int $modal Flag use form in modal */ extract($displayData); -$app = JFactory::getApplication(); -$Itemid = $app->input->getInt('Itemid', 0); +$app = JFactory::getApplication(); +$Itemid = $app->input->getInt('Itemid', 0); $category_id = $app->input->getInt('cid', 0); JHtml::_('behavior.keepalive'); @@ -28,84 +28,81 @@ $user = JFactory::getUser(); -if ($user->id) -{ - if ($userInfo = RedshopHelperUser::getUserInformation($user->id)) - { - $username = $userInfo->firstname . " " . $userInfo->lastname; - } - else - { - $username = $user->name; - } - - $form->setValue('username', null, $form->getValue('username', null, $username)); - $form->setFieldAttribute('username', 'disabled', 'true', null); - $form->setFieldAttribute('username', 'required', 'false', null); - $form->setFieldAttribute('email', 'required', 'false', null); +if ($user->id) { + if ($userInfo = RedshopHelperUser::getUserInformation($user->id)) { + $username = $userInfo->firstname . " " . $userInfo->lastname; + } else { + $username = $user->name; + } + + $form->setValue('username', null, $form->getValue('username', null, $username)); + $form->setFieldAttribute('username', 'disabled', 'true', null); + $form->setFieldAttribute('username', 'required', 'false', null); + $form->setFieldAttribute('email', 'required', 'false', null); } ?>
    -
    -
    - -
    -
    getInput('user_rating'); ?>
    -
    -
    - -
    - -
    getInput('images'); ?>
    -
    - -
    - -
    getInput('username'); ?>
    -
    - - guest): ?> -
    - -
    getInput('email'); ?>
    -
    - - -
    - -
    getInput('title'); ?>
    -
    - -
    - -
    getInput('comment'); ?>
    -
    - - guest): ?> - + id="productRatingForm" class="form-validate form-vertical" enctype="multipart/form-data"> +
    +
    + +
    +
    getInput('user_rating'); ?>
    +
    +
    + +
    + +
    getInput('images'); ?>
    +
    + +
    + +
    getInput('username'); ?>
    +
    + + guest): ?> +
    + +
    getInput('email'); ?>
    +
    -
    - -
    - -
    - - - - - - - - - + +
    + +
    getInput('title'); ?>
    +
    + +
    + +
    getInput('comment'); ?>
    +
    + + guest): ?> + + +
    + +
    + +
    + + + + + + + + +
    diff --git a/component/site/layouts/product/quotation_attribute.php b/component/site/layouts/product/quotation_attribute.php index c7b27b2d318..369424f906e 100644 --- a/component/site/layouts/product/quotation_attribute.php +++ b/component/site/layouts/product/quotation_attribute.php @@ -14,57 +14,67 @@ ?> -
    - section_name ?> +
    + section_name ?> - section_id - ); - ?> + section_id + ); + ?> - -
    - section_name ?> + +
    + section_name ?> - get('SHOW_QUOTATION_PRICE') == 1)) : ?> - section_oprand; - $propertyPrice = RedshopHelperProductPrice::formattedPrice($property->section_price); - $propertyPriceWithVat = RedshopHelperProductPrice::formattedPrice($property->section_price + $property->section_vat); + get( + 'SHOW_QUOTATION_PRICE' + ) == 1)) : ?> + section_oprand; + $propertyPrice = RedshopHelperProductPrice::formattedPrice($property->section_price); + $propertyPriceWithVat = RedshopHelperProductPrice::formattedPrice( + $property->section_price + $property->section_vat + ); - echo "(" . $propertyOprand . " " . $propertyPrice . " excl. vat / " . $propertyPriceWithVat . ")"; - ?> - -
    + echo "(" . $propertyOprand . " " . $propertyPrice . " excl. vat / " . $propertyPriceWithVat . ")"; + ?> + +
    - section_id - ); - ?> + section_id + ); + ?> - -
    - section_name ?> + +
    + section_name ?> - get('SHOW_QUOTATION_PRICE') == 1)) : ?> - section_oprand; - $subpropertyPrice = RedshopHelperProductPrice::formattedPrice($subProperty->section_price); - $subpropertyPriceWithVat = RedshopHelperProductPrice::formattedPrice($subProperty->section_price + $subProperty->section_vat); + get( + 'SHOW_QUOTATION_PRICE' + ) == 1)) : ?> + section_oprand; + $subpropertyPrice = RedshopHelperProductPrice::formattedPrice( + $subProperty->section_price + ); + $subpropertyPriceWithVat = RedshopHelperProductPrice::formattedPrice( + $subProperty->section_price + $subProperty->section_vat + ); - echo "(" . $subpropertyOprand . " " . $subpropertyPrice . " excl. vat / " . $subpropertyPriceWithVat . ")"; - ?> - -
    - - -
    + echo "(" . $subpropertyOprand . " " . $subpropertyPrice . " excl. vat / " . $subpropertyPriceWithVat . ")"; + ?> + +
    + + +
    \ No newline at end of file diff --git a/component/site/layouts/product/rating.php b/component/site/layouts/product/rating.php index 89b3e4e27ca..902516b3ad1 100644 --- a/component/site/layouts/product/rating.php +++ b/component/site/layouts/product/rating.php @@ -12,7 +12,7 @@ extract($displayData); ?> - + stock_amount_image, - '', - 'thumb', - 'stockroom', - Redshop::getConfig()->get('DEFAULT_STOCKAMOUNT_THUMB_WIDTH'), - Redshop::getConfig()->get('DEFAULT_STOCKAMOUNT_THUMB_HEIGHT'), - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') + $stockamountImage->stock_amount_image, + '', + 'thumb', + 'stockroom', + Redshop::getConfig()->get('DEFAULT_STOCKAMOUNT_THUMB_WIDTH'), + Redshop::getConfig()->get('DEFAULT_STOCKAMOUNT_THUMB_HEIGHT'), + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') ); ?> - <?php echo $stockamountImage->stock_amount_image_tooltip ?> + <?php echo $stockamountImage->stock_amount_image_tooltip ?> diff --git a/component/site/layouts/product/stockroom_detail.php b/component/site/layouts/product/stockroom_detail.php index 68ea67520ab..1c280d2176b 100644 --- a/component/site/layouts/product/stockroom_detail.php +++ b/component/site/layouts/product/stockroom_detail.php @@ -14,10 +14,10 @@ 0) : ?>
    - +
    stockroom_name ?>:quantity ?>
    - +
    diff --git a/component/site/layouts/registration/captcha.php b/component/site/layouts/registration/captcha.php index bc677dcc435..4c349010cad 100644 --- a/component/site/layouts/registration/captcha.php +++ b/component/site/layouts/registration/captcha.php @@ -13,19 +13,18 @@ $default = JFactory::getConfig()->get('captcha'); -if ($app->isSite()) -{ - $default = $app->getParams()->get('captcha', JFactory::getConfig()->get('captcha')); +if ($app->isSite()) { + $default = $app->getParams()->get('captcha', JFactory::getConfig()->get('captcha')); } ?> - 'redshop')); ?> + 'redshop')); ?> - +
    - display('security_code', 'security_code', 'required'); ?> + display('security_code', 'security_code', 'required'); ?>
    - + diff --git a/component/site/layouts/registration/index.html b/component/site/layouts/registration/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/component/site/layouts/registration/index.html +++ b/component/site/layouts/registration/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/component/site/models/account.php b/component/site/models/account.php index d00fca8a7a5..c02556fedb7 100755 --- a/component/site/models/account.php +++ b/component/site/models/account.php @@ -18,475 +18,439 @@ */ class RedshopModelAccount extends RedshopModel { - /** - * @var null - */ - public $_id = null; - - /** - * @var null - */ - public $_data = null; - - /** - * @var null - */ - public $_table_prefix = null; - - /** - * @var JPagination - */ - public $_pagination; - - /** - * @var integer - */ - public $_total; - - /** - * Constructor - */ - public function __construct() - { - parent::__construct(); - - $this->_table_prefix = '#__redshop_'; - } - - /** - * Get user Account information - * - * @param integer $uid User ID - * - * @return object|boolean - */ - public function getUserAccountInfo($uid) - { - $user = JFactory::getUser(); - $session = JFactory::getSession(); - $auth = $session->get('auth'); - $list = new stdClass; - - if ($user->id) - { - $list = RedshopHelperOrder::getBillingAddress($user->id); - } - elseif ($auth['users_info_id']) - { - $uid = -$auth['users_info_id']; - $list = RedshopHelperOrder::getBillingAddress($uid); - } - - if (!empty($list)) - { - $list->email = $list->user_email; - } - - return $list; - } - - /** - * Method for get current account detail - * - * @return null|object[] - * @throws Exception - */ - public function getMyDetail() - { - /** @var JApplicationSite $app */ - $app = JFactory::getApplication(); - - $start = $app->input->getInt('limitstart', 0); - $limit = $app->getParams()->get('maxcategory'); - - if (empty($this->_data)) - { - $query = $this->_buildQuery(); - - if ($query) - { - $this->_data = $this->_getList($query, $start, $limit); - } - } - - return $this->_data; - } - - /** - * Method for build query - * - * @return JDatabaseQuery|boolean - * - * @throws Exception - */ - public function _buildQuery() - { - $app = JFactory::getApplication(); - $layout = $app->input->getCmd('layout', ''); - - if ($layout !== 'mytags' && $layout !== 'mywishlist') - { - return false; - } - - $tagId = $app->input->getInt('tagid', 0); - $wishListId = $app->input->getInt('wishlist_id', 0); - $userId = JFactory::getUser()->id; - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - // Layout: mytags - if ($layout == 'mytags') - { - $query->select('DISTINCT pt.*') - ->from($db->qn('#__redshop_product_tags', 'pt')) - ->leftJoin( - $db->qn('#__redshop_product_tags_xref', 'ptx') - . ' ON ' . $db->qn('pt.tags_id') . ' = ' . $db->qn('ptx.tags_id') - ) - ->where($db->qn('ptx.users_id') . ' = ' . (int) $userId) - ->where($db->qn('pt.published') . ' = 1'); - - if ($tagId != 0) - { - $query->select(array('ptx.product_id', 'p.*')) - ->leftJoin( - $db->qn('#__redshop_product', 'p') - . ' ON ' . $db->qn('ptx.product_id') . ' = ' . $db->qn('p.product_id') - ) - ->where($db->qn('pt.tags_id') . ' = ' . (int) $tagId); - } - - return $query; - } - - // Layout: mywishlist - if ($userId && $wishListId) - { - $query->select('DISTINCT(' . $db->qn('w.wishlist_id') . ')') - ->select(array('w.*', 'p.*')) - ->from($db->qn('#__redshop_wishlist', 'w')) - ->leftJoin($db->qn('#__redshop_wishlist_product', 'pw') . ' ON w.wishlist_id = pw.wishlist_id') - ->leftJoin($db->qn('#__redshop_product', 'p') . ' ON p.product_id = pw.product_id') - ->where('w.user_id = ' . (int) $userId) - ->where('w.wishlist_id = ' . (int) $wishListId) - ->where('pw.wishlist_id = ' . (int) $wishListId); - - return $query; - } - - // Add this code to send wishlist while user is not logged in ... - $productIds = array(); - - if (isset($_SESSION["no_of_prod"])) - { - for ($index = 1; $index <= $_SESSION["no_of_prod"]; $index++) - { - if ($_SESSION['wish_' . $index]->product_id != '') - { - $productIds[] = (int) $_SESSION['wish_' . $index]->product_id; - } - } - - $productIds[] = (int) $_SESSION['wish_' . $index]->product_id; - } - - if (!empty($productIds)) - { - $query->select('p.*') - ->from($db->quoteName('#__redshop_product', 'p')) - ->where('p.product_id IN (' . implode(',', $productIds) . ')'); - } - - return $query; - } - - /** - * Method for get pagination - * - * @return JPagination - * @throws Exception - */ - public function getPagination() - { - /** @var JApplicationSite $app */ - $app = JFactory::getApplication(); - $start = $app->input->getInt('limitstart', 0); - $limit = $app->getParams()->get('maxcategory', 5); - - if (empty($this->_pagination)) - { - JLoader::import('joomla.html.pagination'); - - $this->_pagination = new JPagination($this->getTotal(), $start, $limit); - } - - return $this->_pagination; - } - - /** - * Get total data - * - * @return integer - * @throws Exception - */ - public function getTotal() - { - if (empty($this->_total)) - { - $query = $this->_buildQuery(); - $this->_total = 0; - - if ($query) - { - $this->_total = $this->_getListCount($query); - } - } - - return $this->_total; - } - - /** - * Remove product from wishlist - * - * @return void - * @throws Exception - */ - public function removeWishlistProduct() - { - $app = JFactory::getApplication(); - $db = JFactory::getDbo(); - - $itemId = $app->input->getInt('Itemid', 0); - $wishListId = $app->input->getInt('wishlist_id', 0); - $pid = $app->input->getInt('pid', 0); - $wishlistProductId = $app->input->getInt('wishlist_product_id', 0); - - $user = JFactory::getUser(); - - // Check is user have access to wishlist - $query = $db->getQuery(true) - ->select('wishlist_id') - ->from($db->quoteName('#__redshop_wishlist')) - ->where('user_id = ' . (int) $user->id) - ->where('wishlist_id = ' . (int) $wishListId); - - echo "
    ";
    -
    -		$list = $db->setQuery($query)->loadResult();
    -
    -		if (count($list) > 0)
    -		{
    -			$query->clear()
    -				->delete($db->quoteName('#__redshop_wishlist_product'))
    -				->where('product_id = ' . (int) $pid)
    -				->where('wishlist_id = ' . (int) $wishListId);
    -
    -			if ($wishlistProductId)
    -			{
    -				$query->where($db->qn('wishlist_product_id') . ' = ' . $wishlistProductId);
    -			}
    -
    -			$db->setQuery($query);
    -
    -			if ($db->execute())
    -			{
    -				$app->enqueueMessage(JText::_('COM_REDSHOP_WISHLIST_PRODUCT_DELETED_SUCCESSFULLY'));
    -			}
    -			else
    -			{
    -				$app->enqueueMessage(JText::_('COM_REDSHOP_ERROR_DELETING_WISHLIST_PRODUCT'));
    -			}
    -		}
    -		else
    -		{
    -			$app->enqueueMessage(JText::_('COM_REDSHOP_YOU_DONT_HAVE_ACCESS_TO_DELETE_THIS_PRODUCT'));
    -		}
    -
    -		$app->redirect(
    -			JRoute::_(
    -				'index.php?option=com_redshop&wishlist_id=' . $wishListId . '&view=account&layout=mywishlist&Itemid=' . $itemId,
    -				false
    -			)
    -		);
    -	}
    -
    -	/**
    -	 * Method for remove tag
    -	 *
    -	 * @return  void
    -	 * @throws Exception
    -	 */
    -	public function removeTag()
    -	{
    -		$app = JFactory::getApplication();
    -
    -		$itemId = $app->input->getInt('Itemid', 0);
    -		$tagId  = $app->input->getInt('tagid', 0);
    -
    -		if ($this->removeTags($tagId))
    -		{
    -			$app->enqueueMessage(JText::_('COM_REDSHOP_TAG_DELETED_SUCCESSFULLY'));
    -		}
    -		else
    -		{
    -			$app->enqueueMessage(JText::_('COM_REDSHOP_ERROR_DELETING_TAG'));
    -		}
    -
    -		$app->redirect(JRoute::_('index.php?option=com_redshop&view=account&layout=mytags&Itemid=' . $itemId));
    -	}
    -
    -	/**
    -	 * Method for remove tags
    -	 *
    -	 * @param   integer $tagId Tag ID
    -	 *
    -	 * @return  boolean
    -	 * @throws  Exception
    -	 */
    -	public function removeTags($tagId)
    -	{
    -		$user  = JFactory::getUser();
    -		$db    = JFactory::getDbo();
    -		$query = $db->getQuery(true)
    -			->delete($db->quoteName('#__redshop_product_tags_xref'))
    -			->where('tags_id = ' . (int) $tagId)
    -			->where('users_id = ' . (int) $user->id);
    -
    -		if (!$db->setQuery($query)->execute())
    -		{
    -			return false;
    -		}
    -
    -		$query->clear()
    -			->select('COUNT(tags_id)')
    -			->from($db->quoteName('#__redshop_product_tags_xref'))
    -			->where('tags_id =' . (int) $tagId);;
    -
    -		// If this tag still have reference with other products. Return
    -		if ($db->setQuery($query)->loadResult() > 0)
    -		{
    -			return true;
    -		}
    -
    -		// Delete this tags if not have any reference
    -		$query->clear()
    -			->delete($db->quoteName('#__redshop_product_tags'))
    -			->where('tags_id = ' . (int) $tagId);
    -
    -		return $db->setQuery($query)->execute();
    -	}
    -
    -	/**
    -	 * Method for get my tag
    -	 *
    -	 * @param   integer $tagId Tag Id
    -	 *
    -	 * @return  integer
    -	 */
    -	public function getMyTag($tagId)
    -	{
    -		$db    = JFactory::getDbo();
    -		$query = $db->getQuery(true)
    -			->select('tags_name')
    -			->from($db->quoteName('#__redshop_product_tags'))
    -			->where('tags_id = ' . (int) $tagId);
    -
    -		return $db->setQuery($query)->loadResult();
    -	}
    -
    -	/**
    -	 * Method for update tag
    -	 *
    -	 * @param   array $post Tag Id
    -	 *
    -	 * @return  boolean
    -	 */
    -	public function editTag($post)
    -	{
    -		if (empty($post) || empty($post['tag_id']))
    -		{
    -			return false;
    -		}
    -
    -		/** @var Tableproduct_tags $table */
    -		$table = RedshopTable::getInstance('product_tags', 'Table');
    -
    -		if (!$table->load($post['tag_id']))
    -		{
    -			return false;
    -		}
    -
    -		$table->tags_name = $post['tags_name'];
    -
    -		return $table->store();
    -	}
    -
    -	/**
    -	 * Method for remove compare
    -	 *
    -	 * @return void
    -	 *
    -	 * @throws Exception
    -	 */
    -	public function removeCompare()
    -	{
    -		$app       = JFactory::getApplication();
    -		$itemId    = $app->input->get('Itemid');
    -		$productId = $app->input->getInt('pid', 0);
    -		$db        = $this->getDbo();
    -
    -		$query = $db->getQuery(true)
    -			->delete($db->qn('#__redshop_product_compare'))
    -			->where($db->qn('product_id') . ' = ' . $productId)
    -			->where($db->qn('user_id') . ' = ' . JFactory::getUser()->id);
    -
    -		if ($db->setQuery($query)->execute())
    -		{
    -			$app->enqueueMessage(JText::_('COM_REDSHOP_PRODUCT_DELETED_FROM_COMPARE_SUCCESSFULLY'));
    -		}
    -		else
    -		{
    -			$app->enqueueMessage(JText::_('COM_REDSHOP_ERROR_DELETING_PRODUCT_FROM_COMPARE'));
    -		}
    -
    -		$app->redirect(JRoute::_('index.php?option=com_redshop&view=account&layout=compare&Itemid=' . $itemId, false));
    -	}
    -
    -	/**
    -	 * Function to delete account user
    -	 *
    -	 * @param   int $userId User Id
    -	 *
    -	 * @return  boolean
    -	 *
    -	 * @since   2.1.2
    -	 */
    -	public function deleteAccount($userId)
    -	{
    -		$db    = JFactory::getDbo();
    -		$query = $db->getQuery(true)
    -			->delete($db->qn('#__users'))
    -			->where($db->qn('id') . ' = ' . $userId);
    -
    -		if (!$db->setQuery($query)->execute())
    -		{
    -			return false;
    -		}
    -
    -		$query->clear()
    -			->delete($db->qn('#__redshop_order_users_info'))
    -			->where($db->qn('user_id') . ' = ' . $userId);
    -
    -		if (!$db->setQuery($query)->execute())
    -		{
    -			return false;
    -		}
    -
    -		$query->clear()
    -			->delete($db->qn('#__redshop_users_info'))
    -			->where($db->qn('user_id') . ' = ' . $userId);
    -
    -		return (boolean) $db->setQuery($query)->execute();
    -	}
    +    /**
    +     * @var null
    +     */
    +    public $_id = null;
    +
    +    /**
    +     * @var null
    +     */
    +    public $_data = null;
    +
    +    /**
    +     * @var null
    +     */
    +    public $_table_prefix = null;
    +
    +    /**
    +     * @var  JPagination
    +     */
    +    public $_pagination;
    +
    +    /**
    +     * @var integer
    +     */
    +    public $_total;
    +
    +    /**
    +     * Constructor
    +     */
    +    public function __construct()
    +    {
    +        parent::__construct();
    +
    +        $this->_table_prefix = '#__redshop_';
    +    }
    +
    +    /**
    +     * Get user Account information
    +     *
    +     * @param   integer  $uid  User ID
    +     *
    +     * @return  object|boolean
    +     */
    +    public function getUserAccountInfo($uid)
    +    {
    +        $user    = JFactory::getUser();
    +        $session = JFactory::getSession();
    +        $auth    = $session->get('auth');
    +        $list    = new stdClass;
    +
    +        if ($user->id) {
    +            $list = RedshopHelperOrder::getBillingAddress($user->id);
    +        } elseif ($auth['users_info_id']) {
    +            $uid  = -$auth['users_info_id'];
    +            $list = RedshopHelperOrder::getBillingAddress($uid);
    +        }
    +
    +        if (!empty($list)) {
    +            $list->email = $list->user_email;
    +        }
    +
    +        return $list;
    +    }
    +
    +    /**
    +     * Method for get current account detail
    +     *
    +     * @return null|object[]
    +     * @throws Exception
    +     */
    +    public function getMyDetail()
    +    {
    +        /** @var JApplicationSite $app */
    +        $app = JFactory::getApplication();
    +
    +        $start = $app->input->getInt('limitstart', 0);
    +        $limit = $app->getParams()->get('maxcategory');
    +
    +        if (empty($this->_data)) {
    +            $query = $this->_buildQuery();
    +
    +            if ($query) {
    +                $this->_data = $this->_getList($query, $start, $limit);
    +            }
    +        }
    +
    +        return $this->_data;
    +    }
    +
    +    /**
    +     * Method for build query
    +     *
    +     * @return JDatabaseQuery|boolean
    +     *
    +     * @throws Exception
    +     */
    +    public function _buildQuery()
    +    {
    +        $app    = JFactory::getApplication();
    +        $layout = $app->input->getCmd('layout', '');
    +
    +        if ($layout !== 'mytags' && $layout !== 'mywishlist') {
    +            return false;
    +        }
    +
    +        $tagId      = $app->input->getInt('tagid', 0);
    +        $wishListId = $app->input->getInt('wishlist_id', 0);
    +        $userId     = JFactory::getUser()->id;
    +        $db         = JFactory::getDbo();
    +        $query      = $db->getQuery(true);
    +
    +        // Layout: mytags
    +        if ($layout == 'mytags') {
    +            $query->select('DISTINCT pt.*')
    +                ->from($db->qn('#__redshop_product_tags', 'pt'))
    +                ->leftJoin(
    +                    $db->qn('#__redshop_product_tags_xref', 'ptx')
    +                    . ' ON ' . $db->qn('pt.tags_id') . ' = ' . $db->qn('ptx.tags_id')
    +                )
    +                ->where($db->qn('ptx.users_id') . ' = ' . (int)$userId)
    +                ->where($db->qn('pt.published') . ' = 1');
    +
    +            if ($tagId != 0) {
    +                $query->select(array('ptx.product_id', 'p.*'))
    +                    ->leftJoin(
    +                        $db->qn('#__redshop_product', 'p')
    +                        . ' ON ' . $db->qn('ptx.product_id') . ' = ' . $db->qn('p.product_id')
    +                    )
    +                    ->where($db->qn('pt.tags_id') . ' = ' . (int)$tagId);
    +            }
    +
    +            return $query;
    +        }
    +
    +        // Layout: mywishlist
    +        if ($userId && $wishListId) {
    +            $query->select('DISTINCT(' . $db->qn('w.wishlist_id') . ')')
    +                ->select(array('w.*', 'p.*'))
    +                ->from($db->qn('#__redshop_wishlist', 'w'))
    +                ->leftJoin($db->qn('#__redshop_wishlist_product', 'pw') . ' ON w.wishlist_id = pw.wishlist_id')
    +                ->leftJoin($db->qn('#__redshop_product', 'p') . ' ON p.product_id = pw.product_id')
    +                ->where('w.user_id = ' . (int)$userId)
    +                ->where('w.wishlist_id = ' . (int)$wishListId)
    +                ->where('pw.wishlist_id = ' . (int)$wishListId);
    +
    +            return $query;
    +        }
    +
    +        // Add this code to send wishlist while user is not logged in ...
    +        $productIds = array();
    +
    +        if (isset($_SESSION["no_of_prod"])) {
    +            for ($index = 1; $index <= $_SESSION["no_of_prod"]; $index++) {
    +                if ($_SESSION['wish_' . $index]->product_id != '') {
    +                    $productIds[] = (int)$_SESSION['wish_' . $index]->product_id;
    +                }
    +            }
    +
    +            $productIds[] = (int)$_SESSION['wish_' . $index]->product_id;
    +        }
    +
    +        if (!empty($productIds)) {
    +            $query->select('p.*')
    +                ->from($db->quoteName('#__redshop_product', 'p'))
    +                ->where('p.product_id IN (' . implode(',', $productIds) . ')');
    +        }
    +
    +        return $query;
    +    }
    +
    +    /**
    +     * Method for get pagination
    +     *
    +     * @return JPagination
    +     * @throws Exception
    +     */
    +    public function getPagination()
    +    {
    +        /** @var JApplicationSite $app */
    +        $app   = JFactory::getApplication();
    +        $start = $app->input->getInt('limitstart', 0);
    +        $limit = $app->getParams()->get('maxcategory', 5);
    +
    +        if (empty($this->_pagination)) {
    +            JLoader::import('joomla.html.pagination');
    +
    +            $this->_pagination = new JPagination($this->getTotal(), $start, $limit);
    +        }
    +
    +        return $this->_pagination;
    +    }
    +
    +    /**
    +     * Get total data
    +     *
    +     * @return  integer
    +     * @throws Exception
    +     */
    +    public function getTotal()
    +    {
    +        if (empty($this->_total)) {
    +            $query        = $this->_buildQuery();
    +            $this->_total = 0;
    +
    +            if ($query) {
    +                $this->_total = $this->_getListCount($query);
    +            }
    +        }
    +
    +        return $this->_total;
    +    }
    +
    +    /**
    +     * Remove product from wishlist
    +     *
    +     * @return  void
    +     * @throws  Exception
    +     */
    +    public function removeWishlistProduct()
    +    {
    +        $app = JFactory::getApplication();
    +        $db  = JFactory::getDbo();
    +
    +        $itemId            = $app->input->getInt('Itemid', 0);
    +        $wishListId        = $app->input->getInt('wishlist_id', 0);
    +        $pid               = $app->input->getInt('pid', 0);
    +        $wishlistProductId = $app->input->getInt('wishlist_product_id', 0);
    +
    +        $user = JFactory::getUser();
    +
    +        // Check is user have access to wishlist
    +        $query = $db->getQuery(true)
    +            ->select('wishlist_id')
    +            ->from($db->quoteName('#__redshop_wishlist'))
    +            ->where('user_id = ' . (int)$user->id)
    +            ->where('wishlist_id = ' . (int)$wishListId);
    +
    +        echo "
    ";
    +
    +        $list = $db->setQuery($query)->loadResult();
    +
    +        if (count($list) > 0) {
    +            $query->clear()
    +                ->delete($db->quoteName('#__redshop_wishlist_product'))
    +                ->where('product_id = ' . (int)$pid)
    +                ->where('wishlist_id = ' . (int)$wishListId);
    +
    +            if ($wishlistProductId) {
    +                $query->where($db->qn('wishlist_product_id') . ' = ' . $wishlistProductId);
    +            }
    +
    +            $db->setQuery($query);
    +
    +            if ($db->execute()) {
    +                $app->enqueueMessage(JText::_('COM_REDSHOP_WISHLIST_PRODUCT_DELETED_SUCCESSFULLY'));
    +            } else {
    +                $app->enqueueMessage(JText::_('COM_REDSHOP_ERROR_DELETING_WISHLIST_PRODUCT'));
    +            }
    +        } else {
    +            $app->enqueueMessage(JText::_('COM_REDSHOP_YOU_DONT_HAVE_ACCESS_TO_DELETE_THIS_PRODUCT'));
    +        }
    +
    +        $app->redirect(
    +            JRoute::_(
    +                'index.php?option=com_redshop&wishlist_id=' . $wishListId . '&view=account&layout=mywishlist&Itemid=' . $itemId,
    +                false
    +            )
    +        );
    +    }
    +
    +    /**
    +     * Method for remove tag
    +     *
    +     * @return  void
    +     * @throws Exception
    +     */
    +    public function removeTag()
    +    {
    +        $app = JFactory::getApplication();
    +
    +        $itemId = $app->input->getInt('Itemid', 0);
    +        $tagId  = $app->input->getInt('tagid', 0);
    +
    +        if ($this->removeTags($tagId)) {
    +            $app->enqueueMessage(JText::_('COM_REDSHOP_TAG_DELETED_SUCCESSFULLY'));
    +        } else {
    +            $app->enqueueMessage(JText::_('COM_REDSHOP_ERROR_DELETING_TAG'));
    +        }
    +
    +        $app->redirect(JRoute::_('index.php?option=com_redshop&view=account&layout=mytags&Itemid=' . $itemId));
    +    }
    +
    +    /**
    +     * Method for remove tags
    +     *
    +     * @param   integer  $tagId  Tag ID
    +     *
    +     * @return  boolean
    +     * @throws  Exception
    +     */
    +    public function removeTags($tagId)
    +    {
    +        $user  = JFactory::getUser();
    +        $db    = JFactory::getDbo();
    +        $query = $db->getQuery(true)
    +            ->delete($db->quoteName('#__redshop_product_tags_xref'))
    +            ->where('tags_id = ' . (int)$tagId)
    +            ->where('users_id = ' . (int)$user->id);
    +
    +        if (!$db->setQuery($query)->execute()) {
    +            return false;
    +        }
    +
    +        $query->clear()
    +            ->select('COUNT(tags_id)')
    +            ->from($db->quoteName('#__redshop_product_tags_xref'))
    +            ->where('tags_id =' . (int)$tagId);;
    +
    +        // If this tag still have reference with other products. Return
    +        if ($db->setQuery($query)->loadResult() > 0) {
    +            return true;
    +        }
    +
    +        // Delete this tags if not have any reference
    +        $query->clear()
    +            ->delete($db->quoteName('#__redshop_product_tags'))
    +            ->where('tags_id = ' . (int)$tagId);
    +
    +        return $db->setQuery($query)->execute();
    +    }
    +
    +    /**
    +     * Method for get my tag
    +     *
    +     * @param   integer  $tagId  Tag Id
    +     *
    +     * @return  integer
    +     */
    +    public function getMyTag($tagId)
    +    {
    +        $db    = JFactory::getDbo();
    +        $query = $db->getQuery(true)
    +            ->select('tags_name')
    +            ->from($db->quoteName('#__redshop_product_tags'))
    +            ->where('tags_id = ' . (int)$tagId);
    +
    +        return $db->setQuery($query)->loadResult();
    +    }
    +
    +    /**
    +     * Method for update tag
    +     *
    +     * @param   array  $post  Tag Id
    +     *
    +     * @return  boolean
    +     */
    +    public function editTag($post)
    +    {
    +        if (empty($post) || empty($post['tag_id'])) {
    +            return false;
    +        }
    +
    +        /** @var Tableproduct_tags $table */
    +        $table = RedshopTable::getInstance('product_tags', 'Table');
    +
    +        if (!$table->load($post['tag_id'])) {
    +            return false;
    +        }
    +
    +        $table->tags_name = $post['tags_name'];
    +
    +        return $table->store();
    +    }
    +
    +    /**
    +     * Method for remove compare
    +     *
    +     * @return void
    +     *
    +     * @throws Exception
    +     */
    +    public function removeCompare()
    +    {
    +        $app       = JFactory::getApplication();
    +        $itemId    = $app->input->get('Itemid');
    +        $productId = $app->input->getInt('pid', 0);
    +        $db        = $this->getDbo();
    +
    +        $query = $db->getQuery(true)
    +            ->delete($db->qn('#__redshop_product_compare'))
    +            ->where($db->qn('product_id') . ' = ' . $productId)
    +            ->where($db->qn('user_id') . ' = ' . JFactory::getUser()->id);
    +
    +        if ($db->setQuery($query)->execute()) {
    +            $app->enqueueMessage(JText::_('COM_REDSHOP_PRODUCT_DELETED_FROM_COMPARE_SUCCESSFULLY'));
    +        } else {
    +            $app->enqueueMessage(JText::_('COM_REDSHOP_ERROR_DELETING_PRODUCT_FROM_COMPARE'));
    +        }
    +
    +        $app->redirect(JRoute::_('index.php?option=com_redshop&view=account&layout=compare&Itemid=' . $itemId, false));
    +    }
    +
    +    /**
    +     * Function to delete account user
    +     *
    +     * @param   int  $userId  User Id
    +     *
    +     * @return  boolean
    +     *
    +     * @since   2.1.2
    +     */
    +    public function deleteAccount($userId)
    +    {
    +        $db    = JFactory::getDbo();
    +        $query = $db->getQuery(true)
    +            ->delete($db->qn('#__users'))
    +            ->where($db->qn('id') . ' = ' . $userId);
    +
    +        if (!$db->setQuery($query)->execute()) {
    +            return false;
    +        }
    +
    +        $query->clear()
    +            ->delete($db->qn('#__redshop_order_users_info'))
    +            ->where($db->qn('user_id') . ' = ' . $userId);
    +
    +        if (!$db->setQuery($query)->execute()) {
    +            return false;
    +        }
    +
    +        $query->clear()
    +            ->delete($db->qn('#__redshop_users_info'))
    +            ->where($db->qn('user_id') . ' = ' . $userId);
    +
    +        return (boolean)$db->setQuery($query)->execute();
    +    }
     }
    diff --git a/component/site/models/account_billto.php b/component/site/models/account_billto.php
    index f2dea64a5f0..8234b2e8a82 100644
    --- a/component/site/models/account_billto.php
    +++ b/component/site/models/account_billto.php
    @@ -18,105 +18,96 @@
      */
     class RedshopModelAccount_Billto extends RedshopModel
     {
    -	/**
    -	 * @var  object
    -	 */
    -	public $_data = null;
    +    /**
    +     * @var  object
    +     */
    +    public $_data = null;
     
    -	/**
    -	 * Init billing address data
    -	 *
    -	 * @return   mixed
    -	 */
    -	public function _initData()
    -	{
    -		$billingAddress = Redshop\User\Billing\Billing::getGlobal();
    +    /**
    +     * Init billing address data
    +     *
    +     * @return   mixed
    +     */
    +    public function _initData()
    +    {
    +        $billingAddress = Redshop\User\Billing\Billing::getGlobal();
     
    -		if (empty($billingAddress) || $billingAddress == new stdClass())
    -		{
    -			$auth = JFactory::getSession()->get('auth');
    +        if (empty($billingAddress) || $billingAddress == new stdClass()) {
    +            $auth = JFactory::getSession()->get('auth');
     
    -			if (isset($auth['users_info_id']) && $auth['users_info_id'])
    -			{
    -				$detail = RedshopHelperOrder::getBillingAddress(-$auth['users_info_id']);
    +            if (isset($auth['users_info_id']) && $auth['users_info_id']) {
    +                $detail = RedshopHelperOrder::getBillingAddress(-$auth['users_info_id']);
     
    -				if (!isset($detail->user_id))
    -				{
    -					$detail->user_id = -$auth['users_info_id'];
    -				}
    -			}
    -			else
    -			{
    -				// Toggle settings
    -				$isCompany = (Redshop::getConfig()->get('DEFAULT_CUSTOMER_REGISTER_TYPE') == 2) ? 1 : 0;
    +                if (!isset($detail->user_id)) {
    +                    $detail->user_id = -$auth['users_info_id'];
    +                }
    +            } else {
    +                // Toggle settings
    +                $isCompany = (Redshop::getConfig()->get('DEFAULT_CUSTOMER_REGISTER_TYPE') == 2) ? 1 : 0;
     
    -				// Allow registration type settings
    -				if (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 1)
    -				{
    -					$isCompany = 0;
    -				}
    -				elseif (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 2)
    -				{
    -					$isCompany = 1;
    -				}
    +                // Allow registration type settings
    +                if (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 1) {
    +                    $isCompany = 0;
    +                } elseif (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 2) {
    +                    $isCompany = 1;
    +                }
     
    -				$user   = JFactory::getUser();
    -				$detail = new stdClass;
    +                $user   = JFactory::getUser();
    +                $detail = new stdClass;
     
    -				$detail->users_info_id         = 0;
    -				$detail->user_id               = $user->id;
    -				$detail->id                    = $user->id;
    -				$detail->name                  = $user->name;
    -				$detail->username              = $user->username;
    -				$detail->email                 = $user->email;
    -				$detail->user_email            = $user->email;
    -				$detail->password              = null;
    -				$detail->is_company            = $isCompany;
    -				$detail->firstname             = null;
    -				$detail->lastname              = null;
    -				$detail->address_type          = 'BT';
    -				$detail->company_name          = null;
    -				$detail->vat_number            = null;
    -				$detail->tax_exempt            = 0;
    -				$detail->country_code          = null;
    -				$detail->state_code            = null;
    -				$detail->shopper_group_id      = null;
    -				$detail->published             = 1;
    -				$detail->address               = null;
    -				$detail->city                  = null;
    -				$detail->zipcode               = null;
    -				$detail->phone                 = null;
    -				$detail->requesting_tax_exempt = 0;
    -				$detail->tax_exempt_approved   = 0;
    -				$detail->approved              = 1;
    -			}
    +                $detail->users_info_id         = 0;
    +                $detail->user_id               = $user->id;
    +                $detail->id                    = $user->id;
    +                $detail->name                  = $user->name;
    +                $detail->username              = $user->username;
    +                $detail->email                 = $user->email;
    +                $detail->user_email            = $user->email;
    +                $detail->password              = null;
    +                $detail->is_company            = $isCompany;
    +                $detail->firstname             = null;
    +                $detail->lastname              = null;
    +                $detail->address_type          = 'BT';
    +                $detail->company_name          = null;
    +                $detail->vat_number            = null;
    +                $detail->tax_exempt            = 0;
    +                $detail->country_code          = null;
    +                $detail->state_code            = null;
    +                $detail->shopper_group_id      = null;
    +                $detail->published             = 1;
    +                $detail->address               = null;
    +                $detail->city                  = null;
    +                $detail->zipcode               = null;
    +                $detail->phone                 = null;
    +                $detail->requesting_tax_exempt = 0;
    +                $detail->tax_exempt_approved   = 0;
    +                $detail->approved              = 1;
    +            }
     
    -			return $detail;
    -		}
    +            return $detail;
    +        }
     
    -		return null;
    -	}
    +        return null;
    +    }
     
    -	/**
    -	 * Method for store billing address
    -	 *
    -	 * @param   array  $post  Data
    -	 *
    -	 * @return  boolean|Tableuser_detail
    -	 * @throws  Exception
    -	 */
    -	public function store($post)
    -	{
    -		$post['billisship']    = 1;
    -		$post['createaccount'] = (isset($post['username']) && $post['username'] != "") ? 1 : 0;
    +    /**
    +     * Method for store billing address
    +     *
    +     * @param   array  $post  Data
    +     *
    +     * @return  boolean|Tableuser_detail
    +     * @throws  Exception
    +     */
    +    public function store($post)
    +    {
    +        $post['billisship']    = 1;
    +        $post['createaccount'] = (isset($post['username']) && $post['username'] != "") ? 1 : 0;
     
    -		$joomlaUser = RedshopHelperJoomla::updateJoomlaUser($post);
    +        $joomlaUser = RedshopHelperJoomla::updateJoomlaUser($post);
     
    -		if (!$joomlaUser)
    -		{
    -			return false;
    -		}
    +        if (!$joomlaUser) {
    +            return false;
    +        }
     
    -		return RedshopHelperUser::storeRedshopUser($post, $joomlaUser->id);
    -	}
    +        return RedshopHelperUser::storeRedshopUser($post, $joomlaUser->id);
    +    }
     }
    diff --git a/component/site/models/account_shipto.php b/component/site/models/account_shipto.php
    index f4683f703b7..ee06e52234a 100644
    --- a/component/site/models/account_shipto.php
    +++ b/component/site/models/account_shipto.php
    @@ -18,150 +18,146 @@
      */
     class RedshopModelAccount_Shipto extends RedshopModel
     {
    -	/**
    -	 * @var integer
    -	 */
    -	public $_id = null;
    -
    -	/**
    -	 * @var mixed
    -	 */
    -	public $_data = null;
    -
    -	/**
    -	 * @var null|string
    -	 */
    -	public $_table_prefix = null;
    -
    -	/**
    -	 * RedshopModelAccount_Shipto constructor.
    -	 *
    -	 * @throws Exception
    -	 */
    -	public function __construct()
    -	{
    -		parent::__construct();
    -
    -		$this->_table_prefix = '#__redshop_';
    -		$infoid              = JFactory::getApplication()->input->getInt('infoid');
    -
    -		$this->setId($infoid);
    -	}
    -
    -	/**
    -	 * Method for set Id
    -	 *
    -	 * @param   integer $id ID
    -	 *
    -	 * @return  void
    -	 */
    -	public function setId($id)
    -	{
    -		$this->_id   = $id;
    -		$this->_data = null;
    -	}
    -
    -	/**
    -	 * Method for get data
    -	 *
    -	 * @return mixed|null
    -	 */
    -	public function &getData()
    -	{
    -		if (!$this->_loadData())
    -		{
    -			$this->_initData();
    -		}
    -
    -		return $this->_data;
    -	}
    -
    -	/**
    -	 * Method for init data
    -	 *
    -	 * @return  boolean
    -	 */
    -	public function _initData()
    -	{
    -		if (empty($this->_data))
    -		{
    -			$detail = new stdClass;
    -
    -			$detail->users_info_id = 0;
    -			$detail->user_id       = 0;
    -			$detail->firstname     = null;
    -			$detail->lastname      = null;
    -			$detail->company_name  = null;
    -			$detail->address       = null;
    -			$detail->state_code    = null;
    -			$detail->country_code  = null;
    -			$detail->city          = null;
    -			$detail->zipcode       = null;
    -			$detail->phone         = 0;
    -
    -			$this->_data = $detail;
    -
    -			return true;
    -		}
    -
    -		return true;
    -	}
    -
    -	/**
    -	 * Method for load data
    -	 *
    -	 * @param   integer $userInfoId User infor Id
    -	 *
    -	 * @return  mixed
    -	 */
    -	public function _loadData($userInfoId = 0)
    -	{
    -		if ($userInfoId)
    -		{
    -			return RedshopEntityUser::getInstance((int) $userInfoId)->getItem();
    -		}
    -
    -		if (empty($this->_data))
    -		{
    -			$this->_data = RedshopEntityUser::getInstance((int) $this->_id)->getItem();
    -
    -			return $this->_data;
    -		}
    -
    -		return true;
    -	}
    -
    -	/**
    -	 * Method for delete shipping data
    -	 *
    -	 * @param   integer  $infoid  Infor data
    -	 *
    -	 * @return  boolean
    -	 */
    -	public function delete($infoid)
    -	{
    -		// Init variables.
    -		$db    = JFactory::getDbo();
    -		$query = $db->getQuery(true)
    -			->delete($db->qn('#__redshop_users_info'))
    -			->where($db->qn('users_info_id') . ' = ' . (int) $infoid);
    -
    -		// Set the query and execute the delete.
    -		return $db->setQuery($query)->execute();
    -	}
    -
    -	/**
    -	 * Method for store shipping data
    -	 *
    -	 * @param   array  $post  Infor data
    -	 *
    -	 * @return  boolean|Tableuser_detail
    -	 * @throws  Exception
    -	 */
    -	public function store($post)
    -	{
    -		$post['user_email'] = $post['email1'] = $post['email'];
    -
    -		return RedshopHelperUser::storeRedshopUserShipping($post);
    -	}
    +    /**
    +     * @var integer
    +     */
    +    public $_id = null;
    +
    +    /**
    +     * @var mixed
    +     */
    +    public $_data = null;
    +
    +    /**
    +     * @var null|string
    +     */
    +    public $_table_prefix = null;
    +
    +    /**
    +     * RedshopModelAccount_Shipto constructor.
    +     *
    +     * @throws Exception
    +     */
    +    public function __construct()
    +    {
    +        parent::__construct();
    +
    +        $this->_table_prefix = '#__redshop_';
    +        $infoid              = JFactory::getApplication()->input->getInt('infoid');
    +
    +        $this->setId($infoid);
    +    }
    +
    +    /**
    +     * Method for set Id
    +     *
    +     * @param   integer  $id  ID
    +     *
    +     * @return  void
    +     */
    +    public function setId($id)
    +    {
    +        $this->_id   = $id;
    +        $this->_data = null;
    +    }
    +
    +    /**
    +     * Method for get data
    +     *
    +     * @return mixed|null
    +     */
    +    public function &getData()
    +    {
    +        if (!$this->_loadData()) {
    +            $this->_initData();
    +        }
    +
    +        return $this->_data;
    +    }
    +
    +    /**
    +     * Method for load data
    +     *
    +     * @param   integer  $userInfoId  User infor Id
    +     *
    +     * @return  mixed
    +     */
    +    public function _loadData($userInfoId = 0)
    +    {
    +        if ($userInfoId) {
    +            return RedshopEntityUser::getInstance((int)$userInfoId)->getItem();
    +        }
    +
    +        if (empty($this->_data)) {
    +            $this->_data = RedshopEntityUser::getInstance((int)$this->_id)->getItem();
    +
    +            return $this->_data;
    +        }
    +
    +        return true;
    +    }
    +
    +    /**
    +     * Method for init data
    +     *
    +     * @return  boolean
    +     */
    +    public function _initData()
    +    {
    +        if (empty($this->_data)) {
    +            $detail = new stdClass;
    +
    +            $detail->users_info_id = 0;
    +            $detail->user_id       = 0;
    +            $detail->firstname     = null;
    +            $detail->lastname      = null;
    +            $detail->company_name  = null;
    +            $detail->address       = null;
    +            $detail->state_code    = null;
    +            $detail->country_code  = null;
    +            $detail->city          = null;
    +            $detail->zipcode       = null;
    +            $detail->phone         = 0;
    +
    +            $this->_data = $detail;
    +
    +            return true;
    +        }
    +
    +        return true;
    +    }
    +
    +    /**
    +     * Method for delete shipping data
    +     *
    +     * @param   integer  $infoid  Infor data
    +     *
    +     * @return  boolean
    +     */
    +    public function delete($infoid)
    +    {
    +        // Init variables.
    +        $db    = JFactory::getDbo();
    +        $query = $db->getQuery(true)
    +            ->delete($db->qn('#__redshop_users_info'))
    +            ->where($db->qn('users_info_id') . ' = ' . (int)$infoid);
    +
    +        // Set the query and execute the delete.
    +        return $db->setQuery($query)->execute();
    +    }
    +
    +    /**
    +     * Method for store shipping data
    +     *
    +     * @param   array  $post  Infor data
    +     *
    +     * @return  boolean|Tableuser_detail
    +     * @throws  Exception
    +     */
    +    public function store($post)
    +    {
    +        $post['user_email'] = $post['email1'] = $post['email'];
    +
    +        return RedshopHelperUser::storeRedshopUserShipping($post);
    +    }
     }
    diff --git a/component/site/models/ask_question.php b/component/site/models/ask_question.php
    index 0bfe1b62066..bf1a1c32824 100644
    --- a/component/site/models/ask_question.php
    +++ b/component/site/models/ask_question.php
    @@ -18,128 +18,127 @@
      */
     class RedshopModelAsk_Question extends RedshopModelForm
     {
    -	/**
    -	 * @var string
    -	 */
    -	protected $context = 'com_redshop.ask_question';
    -
    -	/**
    -	 * Method to get the record form.
    -	 *
    -	 * @param   array   $data     Data for the form.
    -	 * @param   boolean $loadData True if the form is to load its own data (default case), false if not.
    -	 *
    -	 * @return  mixed  A JForm object on success, false on failure
    -	 *
    -	 * @since   1.5
    -	 */
    -	public function getForm($data = array(), $loadData = true)
    -	{
    -		// Get the form.
    -		$form = $this->loadForm('com_redshop.ask_question', 'ask_question', array('control' => 'jform', 'load_data' => $loadData));
    -
    -		if (empty($form))
    -		{
    -			return false;
    -		}
    -
    -		return $form;
    -	}
    -
    -	/**
    -	 * Method to get the data that should be injected in the form.
    -	 *
    -	 * @return  array    The default data is an empty array.
    -	 * @throws  Exception
    -	 *
    -	 * @since   1.5
    -	 */
    -	protected function loadFormData()
    -	{
    -		$data = (array) JFactory::getApplication()->getUserState('com_redshop.ask_question.data', array());
    -
    -		return $data;
    -	}
    -
    -	/**
    -	 * Method to store the records
    -	 *
    -	 * @param   array $data array of data
    -	 *
    -	 * @return  boolean
    -	 * @throws  Exception
    -	 */
    -	public function store($data)
    -	{
    -		$user                  = JFactory::getUser();
    -		$data['user_id']       = $user->id;
    -		$data['user_name']     = $data['your_name'];
    -		$data['user_email']    = $data['your_email'];
    -		$data['question']      = $data['your_question'];
    -		$data['published']     = 1;
    -		$data['question_date'] = time();
    -
    -		$row = $this->getTable('Question');
    -
    -		$data['ordering'] = $this->maxOrdering();
    -
    -		if (!$row->bind($data))
    -		{
    -			$this->setError($this->_db->getErrorMsg());
    -
    -			return false;
    -		}
    -
    -		if (!$row->store())
    -		{
    -			$this->setError($this->_db->getErrorMsg());
    -
    -			return false;
    -		}
    -
    -		return true;
    -	}
    -
    -	/**
    -	 * Method to get max ordering
    -	 *
    -	 * @access public
    -	 *
    -	 * @return boolean
    -	 */
    -	public function maxOrdering()
    -	{
    -		$db    = JFactory::getDbo();
    -		$query = $db->getQuery(true)
    -			->select('MAX(ordering)+1')
    -			->from($db->qn('#__redshop_customer_question'))
    -			->where('parent_id = 0');
    -
    -		return $db->setQuery($query)->loadResult();
    -	}
    -
    -	/**
    -	 * Send Mail For Ask Question
    -	 *
    -	 * @param   array $data Question data
    -	 *
    -	 * @return  boolean
    -	 * @throws  Exception
    -	 */
    -	public function sendMailForAskQuestion($data)
    -	{
    -		if (!$this->store($data))
    -		{
    -			return false;
    -		}
    -
    -		if (!Redshop\Mail\AskQuestion::sendAskQuestion($data))
    -		{
    -			$this->setError(JText::_('COM_REDSHOP_EMAIL_HAS_NOT_BEEN_SENT_SUCCESSFULLY'));
    -
    -			return false;
    -		}
    -
    -		return true;
    -	}
    +    /**
    +     * @var string
    +     */
    +    protected $context = 'com_redshop.ask_question';
    +
    +    /**
    +     * Method to get the record form.
    +     *
    +     * @param   array    $data      Data for the form.
    +     * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
    +     *
    +     * @return  mixed  A JForm object on success, false on failure
    +     *
    +     * @since   1.5
    +     */
    +    public function getForm($data = array(), $loadData = true)
    +    {
    +        // Get the form.
    +        $form = $this->loadForm(
    +            'com_redshop.ask_question',
    +            'ask_question',
    +            array('control' => 'jform', 'load_data' => $loadData)
    +        );
    +
    +        if (empty($form)) {
    +            return false;
    +        }
    +
    +        return $form;
    +    }
    +
    +    /**
    +     * Send Mail For Ask Question
    +     *
    +     * @param   array  $data  Question data
    +     *
    +     * @return  boolean
    +     * @throws  Exception
    +     */
    +    public function sendMailForAskQuestion($data)
    +    {
    +        if (!$this->store($data)) {
    +            return false;
    +        }
    +
    +        if (!Redshop\Mail\AskQuestion::sendAskQuestion($data)) {
    +            $this->setError(JText::_('COM_REDSHOP_EMAIL_HAS_NOT_BEEN_SENT_SUCCESSFULLY'));
    +
    +            return false;
    +        }
    +
    +        return true;
    +    }
    +
    +    /**
    +     * Method to store the records
    +     *
    +     * @param   array  $data  array of data
    +     *
    +     * @return  boolean
    +     * @throws  Exception
    +     */
    +    public function store($data)
    +    {
    +        $user                  = JFactory::getUser();
    +        $data['user_id']       = $user->id;
    +        $data['user_name']     = $data['your_name'];
    +        $data['user_email']    = $data['your_email'];
    +        $data['question']      = $data['your_question'];
    +        $data['published']     = 1;
    +        $data['question_date'] = time();
    +
    +        $row = $this->getTable('Question');
    +
    +        $data['ordering'] = $this->maxOrdering();
    +
    +        if (!$row->bind($data)) {
    +            $this->setError($this->_db->getErrorMsg());
    +
    +            return false;
    +        }
    +
    +        if (!$row->store()) {
    +            $this->setError($this->_db->getErrorMsg());
    +
    +            return false;
    +        }
    +
    +        return true;
    +    }
    +
    +    /**
    +     * Method to get max ordering
    +     *
    +     * @access public
    +     *
    +     * @return boolean
    +     */
    +    public function maxOrdering()
    +    {
    +        $db    = JFactory::getDbo();
    +        $query = $db->getQuery(true)
    +            ->select('MAX(ordering)+1')
    +            ->from($db->qn('#__redshop_customer_question'))
    +            ->where('parent_id = 0');
    +
    +        return $db->setQuery($query)->loadResult();
    +    }
    +
    +    /**
    +     * Method to get the data that should be injected in the form.
    +     *
    +     * @return  array    The default data is an empty array.
    +     * @throws  Exception
    +     *
    +     * @since   1.5
    +     */
    +    protected function loadFormData()
    +    {
    +        $data = (array)JFactory::getApplication()->getUserState('com_redshop.ask_question.data', array());
    +
    +        return $data;
    +    }
     }
    diff --git a/component/site/models/cart.php b/component/site/models/cart.php
    index 367a95dd031..e9a352e74bd 100644
    --- a/component/site/models/cart.php
    +++ b/component/site/models/cart.php
    @@ -19,872 +19,866 @@
      */
     class RedshopModelCart extends RedshopModel
     {
    -	public $_id = null;
    +    public $_id = null;
     
    -	public $_data = null;
    +    public $_data = null;
     
    -	/**
    -	 *  Product data
    -	 *
    -	 * @var  [type]
    -	 */
    -	public $_product = null;
    +    /**
    +     *  Product data
    +     *
    +     * @var  [type]
    +     */
    +    public $_product = null;
     
    -	public $_table_prefix = null;
    +    public $_table_prefix = null;
     
    -	public $_template = null;
    +    public $_template = null;
     
    -	public $_r_voucher = 0;
    +    public $_r_voucher = 0;
     
    -	public $_c_remain = 0;
    +    public $_c_remain = 0;
     
    -	public $_globalvoucher = 0;
    +    public $_globalvoucher = 0;
     
    -	public $_producthelper = null;
    +    public $_producthelper = null;
     
    -	public $_carthelper = null;
    +    public $_carthelper = null;
     
    -	public $_userhelper = null;
    +    public $_userhelper = null;
     
    -	public $_objshipping = null;
    +    public $_objshipping = null;
     
    -	public function __construct()
    -	{
    -		parent::__construct();
    +    public function __construct()
    +    {
    +        parent::__construct();
     
    -		$this->_table_prefix = '#__redshop_';
    -		$this->_objshipping   = shipping::getInstance();
    -		$user                 = JFactory::getUser();
    +        $this->_table_prefix = '#__redshop_';
    +        $this->_objshipping  = shipping::getInstance();
    +        $user                = JFactory::getUser();
     
    -		// Remove expired products from cart
    +        // Remove expired products from cart
             $this->emptyExpiredCartProducts();
     
    -		$cart = \Redshop\Cart\Helper::getCart();
    -
    -		if (!empty($cart))
    -		{
    -			$cart = \Redshop\Cart\Helper::getCart();
    -
    -			$userId         = $user->id;
    -			$userSession    = \JFactory::getSession()->get('rs_user');
    -			$shopperGroupId = \RedshopHelperUser::getShopperGroup($userId);
    -
    -			if (array_key_exists('user_shopper_group_id', $cart))
    -			{
    -				$userArr = \RedshopHelperUser::getVatUserInformation($userId);
    -
    -				// Removed due to discount issue $userSession['vatCountry']
    -				if ($cart['user_shopper_group_id'] != $shopperGroupId
    -					|| (!isset($userSession['vatCountry']) || !isset($userSession['vatState']) || $userSession['vatCountry'] != $userArr->country_code || $userSession['vatState'] != $userArr->state_code)
    -				)
    -				{
    -					$cart = \Redshop\Cart\Cart::modify($cart, $userId);
    -					$cart['user_shopper_group_id'] = $shopperGroupId;
    -
    -					$task = JFactory::getApplication()->input->getCmd('task');
    -
    -					if ($task != 'coupon' && $task != 'voucher')
    -					{
    -						$cart = RedshopHelperDiscount::modifyDiscount($cart);
    -					}
    -				}
    -			}
    -
    -			\Redshop\Cart\Helper::setCart($cart);
    -		}
    -	}
    -
    -	/**
    -	 * @return  void
    -	 *
    -	 * @since   1.0
    -	 */
    -	public function emptyExpiredCartProducts()
    -	{
    -		if (Redshop::getConfig()->get('IS_PRODUCT_RESERVE') && Redshop::getConfig()->get('USE_STOCKROOM'))
    -		{
    -			$session     = JFactory::getSession();
    -			$db          = JFactory::getDbo();
    -			$query       = $db->getQuery(true);
    -			$sessionId   = session_id();
    -			$carttimeout = (int) Redshop::getConfig()->get('CART_TIMEOUT');
    -			$time        = time() - ($carttimeout * 60);
    -
    -			$query->select($db->quoteName('product_id'))
    -				->from($db->quoteName('#__redshop_cart'))
    -				->where($db->quoteName('session_id') . ' = ' . $db->quote($sessionId))
    -				->where($db->quoteName('section') . ' = ' . $db->quote('product'));
    -			$db->setQuery($query);
    -			$includedrs = $db->loadColumn();
    -
    -			$query->where($db->quoteName('time') . ' < ' . $db->quote($time));
    -
    -			$db->setQuery($query);
    -			$deletedrs = $db->loadColumn();
    -
    -			$cart = $session->get('cart');
    -
    -			if ($cart)
    -			{
    -				$idx = (int) (isset($cart['idx']) ? $cart['idx'] : 0);
    -
    -				for ($j = 0; $j < $idx; $j++)
    -				{
    -					if (count($deletedrs) > 0 && in_array($cart[$j]['product_id'], $deletedrs))
    -					{
    -						$this->delete($j);
    -					}
    -
    -					if (count($includedrs) > 0 && !in_array($cart[$j]['product_id'], $includedrs))
    -					{
    -						$this->delete($j);
    -					}
    -				}
    -			}
    -
    -			RedshopHelperStockroom::deleteExpiredCartProduct();
    -		}
    -	}
    -
    -	/**
    -	 * Empty cart
    -	 *
    -	 * @return  boolean
    -	 *
    -	 * @since   2.0.6
    -	 */
    -	public function emptyCart()
    -	{
    -		return RedshopHelperCart::emptyCart();
    -	}
    -
    -	/**
    -	 *
    -	 * @return  array|null
    -	 *
    -	 * @since   2.0.6
    -	 */
    -	public function getData()
    -	{
    -		if (empty($this->_data))
    -		{
    -			if (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE'))
    -			{
    -				$this->_data = RedshopHelperTemplate::getTemplate("quotation_cart");
    -			}
    -			else
    -			{
    -				if (!Redshop::getConfig()->get('USE_AS_CATALOG'))
    -				{
    -					$this->_data = RedshopHelperTemplate::getTemplate("cart");
    -				}
    -				else
    -				{
    -					$this->_data = RedshopHelperTemplate::getTemplate("catalogue_cart");
    -				}
    -			}
    -		}
    -
    -		return $this->_data;
    -	}
    -
    -	/**
    -	 * Update cart.
    -	 *
    -	 * @param   array $data data in cart
    -	 */
    -	public function update($data)
    -	{
    -		$cart = \Redshop\Cart\Helper::getCart();
    -		$user = JFactory::getUser();
    -
    -		$cartElement = $data['cart_index'];
    -		$newQuantity = intval(abs($data['quantity']) > 0 ? $data['quantity'] : 1);
    -		$oldQuantity = intval($cart[$cartElement]['quantity']);
    -
    -		$calculator_price = 0;
    -		$wrapper_price    = 0;
    -		$wrapper_vat      = 0;
    -
    -		if ($newQuantity <= 0)
    -		{
    -			$newQuantity = 1;
    -		}
    -
    -		if ($newQuantity != $oldQuantity)
    -		{
    -			if (isset($cart[$cartElement]['giftcard_id']) && $cart[$cartElement]['giftcard_id'])
    -			{
    -				$cart[$cartElement]['quantity'] = $newQuantity;
    -			}
    -			else
    -			{
    -				if (array_key_exists('checkQuantity', $data))
    -				{
    -					$cart[$cartElement]['quantity'] = $data['checkQuantity'];
    -				}
    -				else
    -				{
    -					$cart[$cartElement]['quantity'] = \Redshop\Stock\Helper::checkQuantityInStock($cart[$cartElement], $newQuantity);
    -				}
    -
    -				if ($newQuantity > $cart[$cartElement]['quantity'])
    -				{
    -					$cart['notice_message'] = $cart[$cartElement]['quantity'] . " " . JTEXT::_('COM_REDSHOP_AVAILABLE_STOCK_MESSAGE');
    -				}
    -				else
    -				{
    -					$cart['notice_message'] = "";
    -				}
    -
    -				$cart[$cartElement]['cart_accessory'] = $this->updateAccessoryPriceArray($cart[$cartElement], $cart[$cartElement]['quantity']);
    -				$cart[$cartElement]['cart_attribute'] = $this->updateAttributePriceArray($cart[$cartElement], $cart[$cartElement]['quantity']);
    -
    -				// Discount calculator
    -				if (!empty($cart[$cartElement]['discount_calc']))
    -				{
    -					$calcdata               = $cart[$cartElement]['discount_calc'];
    -					$calcdata['product_id'] = $cart[$cartElement]['product_id'];
    -
    -					$discount_cal = \Redshop\Promotion\Discount::discountCalculator($calcdata);
    -
    -					$calculator_price  = $discount_cal['product_price'];
    -					$product_price_tax = $discount_cal['product_price_tax'];
    -				}
    -
    -				// Attribute price
    -				$retAttArr                  = RedshopHelperProduct::makeAttributeCart($cart[$cartElement]['cart_attribute'], $cart[$cartElement]['product_id'], $user->id, $calculator_price, $cart[$cartElement]['quantity']);
    -				$product_price              = $retAttArr[1];
    -				$product_vat_price          = $retAttArr[2];
    -				$product_old_price          = $retAttArr[5] + $retAttArr[6];
    -				$product_old_price_excl_vat = $retAttArr[5];
    -
    -				// Accessory price
    -				$retAccArr             = RedshopHelperProduct::makeAccessoryCart($cart[$cartElement]['cart_accessory'], $cart[$cartElement]['product_id']);
    -				$accessory_total_price = $retAccArr[1];
    -				$accessory_vat_price   = $retAccArr[2];
    -
    -				if ($cart[$cartElement]['wrapper_id'])
    -				{
    -					$wrapperArr    = \Redshop\Wrapper\Helper::getWrapperPrice(array('product_id' => $cart[$cartElement]['product_id'], 'wrapper_id' => $cart[$cartElement]['wrapper_id']));
    -					$wrapper_vat   = $wrapperArr['wrapper_vat'];
    -					$wrapper_price = $wrapperArr['wrapper_price'];
    -				}
    -
    -				if (isset($cart[$cartElement]['subscription_id']) && $cart[$cartElement]['subscription_id'] != "")
    -				{
    -					$subscription_vat    = 0;
    -					$subscription_detail = RedshopHelperProduct::getProductSubscriptionDetail($cart[$cartElement]['product_id'], $cart[$cartElement]['subscription_id']);
    -					$subscription_price  = $subscription_detail->subscription_price;
    -
    -					if ($subscription_price)
    -					{
    -						$subscription_vat = RedshopHelperProduct::getProductTax($cart[$cartElement]['product_id'], $subscription_price);
    -					}
    -
    -					$product_vat_price += $subscription_vat;
    -					$product_price     = $product_price + $subscription_price;
    -
    -					$product_old_price_excl_vat += $subscription_price;
    -				}
    -
    -				$cart[$cartElement]['product_price']              = $product_price + $product_vat_price + $accessory_total_price + $accessory_vat_price + $wrapper_price + $wrapper_vat;
    -				$cart[$cartElement]['product_old_price']          = $product_old_price + $accessory_total_price + $accessory_vat_price + $wrapper_price + $wrapper_vat;
    -				$cart[$cartElement]['product_old_price_excl_vat'] = $product_old_price_excl_vat + $accessory_total_price + $wrapper_price;
    -				$cart[$cartElement]['product_price_excl_vat']     = $product_price + $accessory_total_price + $wrapper_price;
    -				$cart[$cartElement]['product_vat']                = $product_vat_price + $accessory_vat_price + $wrapper_vat;
    -				JPluginHelper::importPlugin('redshop_product');
    -				$dispatcher = RedshopHelperUtility::getDispatcher();
    -				$dispatcher->trigger('onAfterCartUpdate', array(&$cart, $cartElement, $data));
    -			}
    -		}
    -
    -		\Redshop\Cart\Helper::setCart($cart);
    -	}
    -
    -	public function update_all($data)
    -	{
    -		JPluginHelper::importPlugin('redshop_product');
    -		$dispatcher    = RedshopHelperUtility::getDispatcher();
    -
    -		$cart = \Redshop\Cart\Helper::getCart();
    -		$user = JFactory::getUser();
    -
    -		if (empty($cart))
    -		{
    -			$cart        = array();
    -			$cart['idx'] = 0;
    -			\Redshop\Cart\Helper::setCart($cart);
    -			$cart        = \Redshop\Cart\Helper::getCart();
    -		}
    -
    -		$idx           = (int) ($cart['idx']);
    -		$quantity_all  = $data['quantity_all'];
    -		$quantity      = explode(",", $quantity_all);
    -		$totalQuantity = array_sum($quantity);
    -
    -		for ($i = 0; $i < $idx; $i++)
    -		{
    -			if ($quantity[$i] < 0)
    -			{
    -				$quantity[$i] = $cart[$i]['quantity'];
    -			}
    -
    -			$quantity[$i] = intval(abs($quantity[$i]) > 0 ? $quantity[$i] : 1);
    -
    -			if ($quantity[$i] != $cart[$i]['quantity'])
    -			{
    -				if (isset($cart[$i]['giftcard_id']) && $cart[$i]['giftcard_id'])
    -				{
    -					$cart[$i]['quantity'] = $quantity[$i];
    -				}
    -				else
    -				{
    -					// Reinit price
    -					$productPriceInit = 0;
    -
    -					// Accessory price fix during update
    -					$accessoryAsProdut           = RedshopHelperAccessory::getAccessoryAsProduct($cart['AccessoryAsProduct']);
    -					$accessoryAsProdutWithoutVat = false;
    -
    -					if (isset($accessoryAsProdut->accessory)
    -						&& isset($accessoryAsProdut->accessory[$cart[$i]['product_id']])
    -						&& isset($cart[$i]['accessoryAsProductEligible'])
    -					)
    -					{
    -						$accessoryAsProdutWithoutVat = '{without_vat}';
    -						$accessoryPrice              = (float) $accessoryAsProdut->accessory[$cart[$i]['product_id']]->newaccessory_price;
    -
    -						$productPriceInit                   = RedshopHelperProductPrice::priceRound($accessoryPrice);
    -						$cart[$i]['product_vat']            = 0;
    -						$cart[$i]['product_price_excl_vat'] = RedshopHelperProductPrice::priceRound($accessoryPrice);
    -					}
    -
    -					$cart[$i]['quantity'] = \Redshop\Stock\Helper::checkQuantityInStock($cart[$i], $quantity[$i]);
    -
    -					$cart[$i]['cart_accessory'] = $this->updateAccessoryPriceArray($cart[$i], $cart[$i]['quantity']);
    -					$cart[$i]['cart_attribute'] = $this->updateAttributePriceArray($cart[$i], $cart[$i]['quantity']);
    -
    -					// Discount calculator
    -					if (!empty($cart[$i]['discount_calc']))
    -					{
    -						$calcdata               = $cart[$i]['discount_calc'];
    -						$calcdata['product_id'] = $cart[$i]['product_id'];
    -
    -						$discount_cal = \Redshop\Promotion\Discount::discountCalculator($calcdata);
    -
    -						$calculator_price = $discount_cal['product_price'];
    -					}
    -
    -					$dispatcher->trigger('onBeforeCartItemUpdate', array(&$cart, $i, &$calculator_price));
    -
    -					// Attribute price
    -					$retAttArr = RedshopHelperProduct::makeAttributeCart(
    -						$cart[$i]['cart_attribute'],
    -						$cart[$i]['product_id'],
    -						$user->id,
    -						$productPriceInit,
    -						$totalQuantity,    // Total Quantity based discount applied here
    -						$accessoryAsProdutWithoutVat
    -					);
    -
    -					$accessoryAsProductZero     = (count($retAttArr[8]) == 0 && $productPriceInit == 0 && ($accessoryAsProdutWithoutVat !== false));
    -					$product_price              = ($accessoryAsProductZero) ? 0 : $retAttArr[1];
    -					$product_vat_price          = ($accessoryAsProductZero) ? 0 : $retAttArr[2];
    -					$product_old_price          = ($accessoryAsProductZero) ? 0 : $retAttArr[5] + $retAttArr[6];
    -					$product_old_price_excl_vat = ($accessoryAsProductZero) ? 0 : $retAttArr[5];
    -
    -					// Accessory price
    -					$retAccArr             = RedshopHelperProduct::makeAccessoryCart(
    -						$cart[$i]['cart_accessory'],
    -						$cart[$i]['product_id']
    -					);
    -					$accessory_total_price = $retAccArr[1];
    -					$accessory_vat_price   = $retAccArr[2];
    -
    -					$wrapper_price = 0;
    -					$wrapper_vat   = 0;
    -
    -					if ($cart[$i]['wrapper_id'])
    -					{
    -						$wrapperArr    = \Redshop\Wrapper\Helper::getWrapperPrice(array('product_id' => $cart[$i]['product_id'], 'wrapper_id' => $cart[$i]['wrapper_id']));
    -						$wrapper_vat   = $wrapperArr['wrapper_vat'];
    -						$wrapper_price = $wrapperArr['wrapper_price'];
    -					}
    -
    -					$subscription_vat = 0;
    -
    -					if (isset($cart[$i]['subscription_id']) && $cart[$i]['subscription_id'] != "")
    -					{
    -						$productId          = $cart[$i]['product_id'];
    -						$subscription_detail = RedshopHelperProduct::getProductSubscriptionDetail($productId, $cart[$i]['subscription_id']);
    -						$subscription_price  = $subscription_detail->subscription_price;
    -
    -						if ($subscription_price)
    -						{
    -							$subscription_vat = RedshopHelperProduct::getProductTax($productId, $subscription_price);
    -						}
    -
    -						$product_vat_price += $subscription_vat;
    -						$product_price     = $product_price + $subscription_price;
    -
    -						$product_old_price_excl_vat += $subscription_price;
    -					}
    -
    -					$cart[$i]['product_price']              = $product_price + $product_vat_price + $accessory_total_price + $accessory_vat_price + $wrapper_price + $wrapper_vat;
    -					$cart[$i]['product_old_price']          = $product_old_price + $accessory_total_price + $accessory_vat_price + $wrapper_price + $wrapper_vat;
    -					$cart[$i]['product_old_price_excl_vat'] = $product_old_price_excl_vat + $accessory_total_price + $wrapper_price;
    -					$cart[$i]['product_price_excl_vat']     = $product_price + $accessory_total_price + $wrapper_price;
    -					$cart[$i]['product_vat']                = $product_vat_price + $accessory_vat_price + $wrapper_vat;
    -
    -					$dispatcher->trigger('onAfterCartItemUpdate', array(&$cart, $i, $data));
    -				}
    -			}
    -		}
    -
    -		unset($cart[$idx]);
    -
    -		\Redshop\Cart\Helper::setCart($cart);
    -	}
    -
    -	public function delete($cartElement)
    -	{
    -		$stockroomhelper = rsstockroomhelper::getInstance();
    -		$cart            = \Redshop\Cart\Helper::getCart();
    -
    -		if (array_key_exists($cartElement, $cart))
    -		{
    -			if (array_key_exists('cart_attribute', $cart[$cartElement]))
    -			{
    -				foreach ($cart[$cartElement]['cart_attribute'] as $cartAttribute)
    -				{
    -					if (array_key_exists('attribute_childs', $cartAttribute))
    -					{
    -						foreach ($cartAttribute['attribute_childs'] as $attributeChilds)
    -						{
    -							if (array_key_exists('property_childs', $attributeChilds))
    -							{
    -								foreach ($attributeChilds['property_childs'] as $propertyChilds)
    -								{
    -									RedshopHelperStockroom::deleteCartAfterEmpty($propertyChilds['subproperty_id'], 'subproperty', $cart[$cartElement]['quantity']);
    -								}
    -							}
    -
    -							RedshopHelperStockroom::deleteCartAfterEmpty($attributeChilds['property_id'], 'property', $cart[$cartElement]['quantity']);
    -						}
    -					}
    -				}
    -			}
    -
    -			$db = JFactory::getDbo();
    -			$query   = $db->getQuery(true)
    -				->select('voucher_id')
    -				->from($db->qn('#__redshop_product_voucher_xref'))
    -				->where($db->qn('product_id') . ' = ' . $db->q((int) $cart[$cartElement]['product_id']));
    -			$voucherId = $db->setQuery($query)->loadResult();
    -
    -			if (!empty($voucherId))
    -			{
    -				$countVoucher = count($cart['voucher']);
    -				if ($countVoucher > 1)
    -				{
    -					for ($i = 0; $i < $countVoucher; $i ++)
    -					{
    -						if ($cart['voucher'][$i]['voucher_id'] == $voucherId)
    -						{
    -							unset($cart['voucher'][$i]);
    -						}
    -					}
    -				}
    -				else
    -				{
    -					for ($i = 0; $i < $countVoucher; $i ++)
    -					{
    -						if ($cart['voucher'][$i]['voucher_id'] == $voucherId)
    -						{
    -							unset($cart['voucher']);
    -						}
    -					}
    -				}
    -			}
    -
    -			RedshopHelperStockroom::deleteCartAfterEmpty($cart[$cartElement]['product_id'], 'product', $cart[$cartElement]['quantity']);
    -			unset($cart[$cartElement]);
    -			$cart = array_merge(array(), $cart);
    -
    -			$Index = $cart['idx'] - 1;
    -
    -			if ($Index > 0)
    -			{
    -				$cart['idx'] = $Index;
    -			}
    -			else
    -			{
    -				$cart        = array();
    -				$cart['idx'] = 0;
    -			}
    -		}
    -
    -		\Redshop\Cart\Helper::setCart($cart);
    -	}
    -
    -	public function coupon()
    -	{
    -		return \RedshopHelperCartDiscount::applyCoupon();
    -	}
    -
    -	public function voucher()
    -	{
    -		return \RedshopHelperCartDiscount::applyVoucher();
    -	}
    -
    -	public function redmasscart($post)
    -	{
    -		$data            = array();
    -		$products_number = explode("\n", $post["numbercart"]);
    -		$db              = JFactory::getDbo();
    -
    -		foreach ($products_number as $productNumber)
    -		{
    -			$productNumber = trim($productNumber);
    -
    -			if ($productNumber === '')
    -			{
    -				continue;
    -			}
    -
    -			$query   = $db->getQuery(true)
    -				->select('product_id, published, not_for_sale, expired, product_name')
    -				->from($db->qn('#__redshop_product'))
    -				->where('product_number = ' . $db->quote($productNumber));
    -			$product = $db->setQuery($query)->loadObject();
    -
    -			if (!$product)
    -			{
    -				continue;
    -			}
    -
    -			$productId = $product->product_id;
    -
    -			if ($product->published == 0)
    -			{
    -				$msg = sprintf(JText::_('COM_REDSHOP_PRODUCT_IS_NOT_PUBLISHED'), $product->product_name, $productId);
    -				/** @scrutinizer ignore-deprecated */ JError::raiseWarning(20, $msg);
    -				continue;
    -			}
    -
    -			if ($product->not_for_sale > 0)
    -			{
    -				$msg = sprintf(JText::_('COM_REDSHOP_PRODUCT_IS_NOT_FOR_SALE'), $product->product_name, $productId);
    -				/** @scrutinizer ignore-deprecated */ JError::raiseWarning(20, $msg);
    -				continue;
    -			}
    -
    -			if ($product->expired == 1)
    -			{
    -				$msg = sprintf(JText::_('COM_REDSHOP_PRODUCT_IS_EXPIRED'), $product->product_name, $productId);
    -				/** @scrutinizer ignore-deprecated */ JError::raiseWarning(20, $msg);
    -				continue;
    -			}
    -
    -			$data["product_id"] = $productId;
    -
    -			if (isset($post["mod_quantity"]) && $post["mod_quantity"] !== "")
    -			{
    -				$data["quantity"] = $post["mod_quantity"];
    -			}
    -			else
    -			{
    -				$data["quantity"] = 1;
    -			}
    -
    -			Redshop\Cart\Cart::addProduct($data);
    -			RedshopHelperCart::cartFinalCalculation();
    -		}
    -	}
    -
    -	/**
    -	 * check if attribute tag is present in product template.
    -	 *
    -	 * @param   int $productId Product ID
    -	 *
    -	 * @return  boolean
    -	 *
    -	 * @since   2.0.6
    -	 */
    -	public function checkifTagAvailable($productId)
    -	{
    -		$db    = JFactory::getDbo();
    -		$query = $db->getQuery(true);
    -		$query->select($db->quoteName('product_template'))
    -			->from($db->quoteName('#__redshop_product'))
    -			->where($db->quoteName('product_id') . ' = ' . (int) $productId);
    -
    -		$productTemplate = $db->setQuery($query)->loadResult();
    -
    -		$template              = RedshopHelperTemplate::getTemplate("product", $productTemplate);
    -		$product_template_desc = $template[0]->template_desc;
    -
    -		return strpos($product_template_desc, "{attribute_template:") !== false;
    -	}
    -
    -	public function updateAccessoryPriceArray($data = array(), $newquantity = 1)
    -	{
    -		$attArr = $data['cart_accessory'];
    -
    -		for ($i = 0, $in = count($attArr); $i < $in; $i++)
    -		{
    -			$attchildArr = $attArr[$i]['accessory_childs'];
    -
    -			$attArr[$i]['accessory_quantity'] = $newquantity;
    -
    -			for ($j = 0, $jn = count($attchildArr); $j < $jn; $j++)
    -			{
    -				$propArr = $attchildArr[$j]['attribute_childs'];
    -
    -				for ($k = 0, $kn = count($propArr); $k < $kn; $k++)
    -				{
    -					$pricelist = RedshopHelperProduct_Attribute::getPropertyPrice($propArr[$k]['property_id'], $newquantity, 'property');
    -
    -					if (count($pricelist) > 0)
    -					{
    -						$propArr[$k]['property_price'] = $pricelist->product_price;
    -					}
    -					else
    -					{
    -						$pricelist                     = RedshopHelperProduct::getProperty($propArr[$k]['property_id'], 'property');
    -						$propArr[$k]['property_price'] = $pricelist->product_price;
    -					}
    -
    -					$subpropArr = $propArr[$k]['property_childs'];
    -
    -					for ($l = 0, $ln = count($subpropArr); $l < $ln; $l++)
    -					{
    -						$pricelist = RedshopHelperProduct_Attribute::getPropertyPrice($subpropArr[$l]['subproperty_id'], $newquantity, 'subproperty');
    -
    -						if (count($pricelist) > 0)
    -						{
    -							$subpropArr[$l]['subproperty_price'] = $pricelist->product_price;
    -						}
    -						else
    -						{
    -							$pricelist                           = RedshopHelperProduct::getProperty($subpropArr[$l]['subproperty_id'], 'subproperty');
    -							$subpropArr[$k]['subproperty_price'] = $pricelist->product_price;
    -						}
    -					}
    -
    -					$propArr[$k]['property_childs'] = $subpropArr;
    -				}
    -
    -				$attchildArr[$j]['attribute_childs'] = $propArr;
    -			}
    -
    -			$attArr[$i]['accessory_childs'] = $attchildArr;
    -		}
    -
    -		return $attArr;
    -	}
    -
    -	public function updateAttributePriceArray($data = array(), $newquantity = 1)
    -	{
    -		$attArr = $data['cart_attribute'];
    -
    -		for ($i = 0, $in = count($attArr); $i < $in; $i++)
    -		{
    -			$propArr = $attArr[$i]['attribute_childs'];
    -
    -			for ($k = 0, $kn = count($propArr); $k < $kn; $k++)
    -			{
    -				$pricelist = RedshopHelperProduct_Attribute::getPropertyPrice($propArr[$k]['property_id'], $newquantity, 'property');
    -
    -				if (count($pricelist) > 0)
    -				{
    -					$propArr[$k]['property_price'] = $pricelist->product_price;
    -				}
    -				else
    -				{
    -					$pricelist                     = RedshopHelperProduct::getProperty($propArr[$k]['property_id'], 'property');
    -					$propArr[$k]['property_price'] = $pricelist->product_price;
    -				}
    -
    -				$subpropArr = $propArr[$k]['property_childs'];
    -
    -				for ($l = 0, $ln = count($subpropArr); $l < $ln; $l++)
    -				{
    -					$pricelist = RedshopHelperProduct_Attribute::getPropertyPrice($subpropArr[$l]['subproperty_id'], $newquantity, 'subproperty');
    -
    -					if (count($pricelist) > 0)
    -					{
    -						$subpropArr[$l]['subproperty_price'] = $pricelist->product_price;
    -					}
    -					else
    -					{
    -						$pricelist                           = RedshopHelperProduct::getProperty($subpropArr[$l]['subproperty_id'], 'subproperty');
    -						$subpropArr[$k]['subproperty_price'] = $pricelist->product_price;
    -					}
    -				}
    -
    -				$propArr[$k]['property_childs'] = $subpropArr;
    -			}
    -
    -			$attArr[$i]['attribute_childs'] = $propArr;
    -		}
    -
    -		return $attArr;
    -	}
    -
    -	public function getCartProductPrice($productId, $cart, $voucher_left)
    -	{
    -		$productArr             = array();
    -		$affected_product_idArr = array();
    -		$idx                    = $cart['idx'];
    -		$product_price          = 0;
    -		$product_price_excl_vat = 0;
    -		$p_quantity             = 0;
    -
    -		$productIdArr = explode(',', $productId);
    -
    -		for ($v = 0; ($v < $idx) && ($voucher_left > 0); $v++)
    -		{
    -			if ($voucher_left < $cart[$v]['quantity'] && $voucher_left)
    -			{
    -				$cart[$v]['quantity'] = $voucher_left;
    -			}
    -
    -			if (in_array($cart[$v]['product_id'], $productIdArr) || $this->_globalvoucher)
    -			{
    -				$product_price            += $cart[$v]['product_price'] * $cart[$v]['quantity'];
    -				$p_quantity               += $cart[$v]['quantity'];
    -				$product_price_excl_vat   += $cart[$v]['product_price_excl_vat'] * $cart[$v]['quantity'];
    -				$affected_product_idArr[] = $cart[$v]['product_id'];
    -				$voucher_left             = $voucher_left - $cart[$v]['quantity'];
    -			}
    -		}
    -
    -		$productArr['product_ids']            = implode(',', $affected_product_idArr);
    -		$productArr['product_price']          = $product_price;
    -		$productArr['product_price_excl_vat'] = $product_price_excl_vat;
    -		$productArr['product_quantity']       = $p_quantity;
    -
    -		return $productArr;
    -	}
    -
    -	/**
    -	 * @param    array $data Data
    -	 *
    -	 * @return   array
    -	 *
    -	 * @since    2.0.6
    -	 */
    -	public function changeAttribute($data)
    -	{
    -		$imagename = '';
    -		$type      = '';
    -		$cart      = \Redshop\Cart\Helper::getCart();
    -
    -		$generateAttributeCart = array();
    -		$productId            = $data['product_id'];
    -		$idx                   = $data['cart_index'];
    -
    -		if (isset($data['attribute_id_prd_' . $productId . '_0']))
    -		{
    -			$attribute_data = $data['attribute_id_prd_' . $productId . '_0'];
    -
    -			for ($ia = 0, $countAttribute = count($attribute_data); $ia < $countAttribute; $ia++)
    -			{
    -				$accPropertyCart                              = array();
    -				$attribute                                    = \Redshop\Product\Attribute::getProductAttribute(0, 0, $attribute_data[$ia]);
    -				$generateAttributeCart[$ia]['attribute_id']   = $attribute_data[$ia];
    -				$generateAttributeCart[$ia]['attribute_name'] = $attribute[0]->text;
    -
    -				if ($attribute[0]->text != "" && isset($data['property_id_prd_' . $productId . '_0_' . $attribute_data[$ia]]))
    -				{
    -					$acc_property_data = $data['property_id_prd_' . $productId . '_0_' . $attribute_data[$ia]];
    -
    -					for ($ip = 0, $countProperty = count($acc_property_data); $ip < $countProperty; $ip++)
    -					{
    -						if ($acc_property_data[$ip] != 0)
    -						{
    -							$accSubpropertyCart = array();
    -							$property_price     = 0;
    -							$property           = RedshopHelperProduct_Attribute::getAttributeProperties($acc_property_data[$ip]);
    -							$pricelist          = RedshopHelperProduct_Attribute::getPropertyPrice($acc_property_data[$ip], $cart[$idx]['quantity'], 'property');
    -
    -							if (isset($pricelist->product_price))
    -							{
    -								$property_price = $pricelist->product_price;
    -							}
    -							else
    -							{
    -								$property_price = $property[0]->property_price;
    -							}
    -
    -							if (count($property) > 0 && JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . "product_attributes/" . $property[0]->property_image))
    -							{
    -								$type      = 'product_attributes';
    -								$imagename = $property[0]->property_image;
    -							}
    -
    -							$accPropertyCart[$ip]['property_id']     = $acc_property_data[$ip];
    -							$accPropertyCart[$ip]['property_name']   = $property[0]->text;
    -							$accPropertyCart[$ip]['property_oprand'] = $property[0]->oprand;
    -							$accPropertyCart[$ip]['property_price']  = $property_price;
    -
    -							if (isset($data['subproperty_id_prd_' . $productId . '_0_' . $attribute_data[$ia] . '_' . $acc_property_data[$ip]]))
    -							{
    -								$acc_subproperty_data = $data['subproperty_id_prd_' . $productId . '_0_' . $attribute_data[$ia] . '_' . $acc_property_data[$ip]];
    -								$countSubProperty     = count($acc_subproperty_data);
    -
    -								for ($isp = 0; $isp < $countSubProperty; $isp++)
    -								{
    -									if ($acc_subproperty_data[$isp] != 0)
    -									{
    -										$subproperty_price = 0;
    -										$subproperty       = RedshopHelperProduct_Attribute::getAttributeSubProperties($acc_subproperty_data[$isp]);
    -										$pricelist         = RedshopHelperProduct_Attribute::getPropertyPrice($acc_subproperty_data[$isp], $cart[$idx]['quantity'], 'subproperty');
    -
    -										if (count($pricelist) > 0)
    -										{
    -											$subproperty_price = $pricelist->product_price;
    -										}
    -										else
    -										{
    -											$subproperty_price = $subproperty[0]->subattribute_color_price;
    -										}
    -
    -										if (count($subproperty) > 0 && JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . "subcolor/" . $subproperty[0]->subattribute_color_image))
    -										{
    -											$type      = 'subcolor';
    -											$imagename = $subproperty[0]->subattribute_color_image;
    -										}
    -
    -										$accSubpropertyCart[$isp]['subproperty_id']           = $acc_subproperty_data[$isp];
    -										$accSubpropertyCart[$isp]['subproperty_name']         = $subproperty[0]->text;
    -										$accSubpropertyCart[$isp]['subproperty_oprand']       = $subproperty[0]->oprand;
    -										$accSubpropertyCart[$isp]['subattribute_color_title'] = $subproperty[0]->subattribute_color_title;
    -										$accSubpropertyCart[$isp]['subproperty_price']        = $subproperty_price;
    -									}
    -								}
    -							}
    -
    -							$accPropertyCart[$ip]['property_childs'] = $accSubpropertyCart;
    -						}
    -					}
    -				}
    -
    -				$generateAttributeCart[$ia]['attribute_childs'] = $accPropertyCart;
    -			}
    -		}
    -
    -		$cart[$idx]['cart_attribute'] = $generateAttributeCart;
    -
    -		if (!empty($imagename) && !empty($type))
    -		{
    -			$cart[$idx]['hidden_attribute_cartimage'] = REDSHOP_FRONT_IMAGES_ABSPATH . $type . "/" . $imagename;
    -		}
    -
    -		// @TODO Do we need setCart back ?
    -
    -		return $cart;
    -	}
    +        $cart = \Redshop\Cart\Helper::getCart();
    +
    +        if (!empty($cart)) {
    +            $cart = \Redshop\Cart\Helper::getCart();
    +
    +            $userId         = $user->id;
    +            $userSession    = \JFactory::getSession()->get('rs_user');
    +            $shopperGroupId = \RedshopHelperUser::getShopperGroup($userId);
    +
    +            if (array_key_exists('user_shopper_group_id', $cart)) {
    +                $userArr = \RedshopHelperUser::getVatUserInformation($userId);
    +
    +                // Removed due to discount issue $userSession['vatCountry']
    +                if ($cart['user_shopper_group_id'] != $shopperGroupId
    +                    || (!isset($userSession['vatCountry']) || !isset($userSession['vatState']) || $userSession['vatCountry'] != $userArr->country_code || $userSession['vatState'] != $userArr->state_code)
    +                ) {
    +                    $cart                          = \Redshop\Cart\Cart::modify($cart, $userId);
    +                    $cart['user_shopper_group_id'] = $shopperGroupId;
    +
    +                    $task = JFactory::getApplication()->input->getCmd('task');
    +
    +                    if ($task != 'coupon' && $task != 'voucher') {
    +                        $cart = RedshopHelperDiscount::modifyDiscount($cart);
    +                    }
    +                }
    +            }
    +
    +            \Redshop\Cart\Helper::setCart($cart);
    +        }
    +    }
    +
    +    /**
    +     * @return  void
    +     *
    +     * @since   1.0
    +     */
    +    public function emptyExpiredCartProducts()
    +    {
    +        if (Redshop::getConfig()->get('IS_PRODUCT_RESERVE') && Redshop::getConfig()->get('USE_STOCKROOM')) {
    +            $session     = JFactory::getSession();
    +            $db          = JFactory::getDbo();
    +            $query       = $db->getQuery(true);
    +            $sessionId   = session_id();
    +            $carttimeout = (int)Redshop::getConfig()->get('CART_TIMEOUT');
    +            $time        = time() - ($carttimeout * 60);
    +
    +            $query->select($db->quoteName('product_id'))
    +                ->from($db->quoteName('#__redshop_cart'))
    +                ->where($db->quoteName('session_id') . ' = ' . $db->quote($sessionId))
    +                ->where($db->quoteName('section') . ' = ' . $db->quote('product'));
    +            $db->setQuery($query);
    +            $includedrs = $db->loadColumn();
    +
    +            $query->where($db->quoteName('time') . ' < ' . $db->quote($time));
    +
    +            $db->setQuery($query);
    +            $deletedrs = $db->loadColumn();
    +
    +            $cart = $session->get('cart');
    +
    +            if ($cart) {
    +                $idx = (int)(isset($cart['idx']) ? $cart['idx'] : 0);
    +
    +                for ($j = 0; $j < $idx; $j++) {
    +                    if (count($deletedrs) > 0 && in_array($cart[$j]['product_id'], $deletedrs)) {
    +                        $this->delete($j);
    +                    }
    +
    +                    if (count($includedrs) > 0 && !in_array($cart[$j]['product_id'], $includedrs)) {
    +                        $this->delete($j);
    +                    }
    +                }
    +            }
    +
    +            RedshopHelperStockroom::deleteExpiredCartProduct();
    +        }
    +    }
    +
    +    public function delete($cartElement)
    +    {
    +        $stockroomhelper = rsstockroomhelper::getInstance();
    +        $cart            = \Redshop\Cart\Helper::getCart();
    +
    +        if (array_key_exists($cartElement, $cart)) {
    +            if (array_key_exists('cart_attribute', $cart[$cartElement])) {
    +                foreach ($cart[$cartElement]['cart_attribute'] as $cartAttribute) {
    +                    if (array_key_exists('attribute_childs', $cartAttribute)) {
    +                        foreach ($cartAttribute['attribute_childs'] as $attributeChilds) {
    +                            if (array_key_exists('property_childs', $attributeChilds)) {
    +                                foreach ($attributeChilds['property_childs'] as $propertyChilds) {
    +                                    RedshopHelperStockroom::deleteCartAfterEmpty(
    +                                        $propertyChilds['subproperty_id'],
    +                                        'subproperty',
    +                                        $cart[$cartElement]['quantity']
    +                                    );
    +                                }
    +                            }
    +
    +                            RedshopHelperStockroom::deleteCartAfterEmpty(
    +                                $attributeChilds['property_id'],
    +                                'property',
    +                                $cart[$cartElement]['quantity']
    +                            );
    +                        }
    +                    }
    +                }
    +            }
    +
    +            $db        = JFactory::getDbo();
    +            $query     = $db->getQuery(true)
    +                ->select('voucher_id')
    +                ->from($db->qn('#__redshop_product_voucher_xref'))
    +                ->where($db->qn('product_id') . ' = ' . $db->q((int)$cart[$cartElement]['product_id']));
    +            $voucherId = $db->setQuery($query)->loadResult();
    +
    +            if (!empty($voucherId)) {
    +                $countVoucher = count($cart['voucher']);
    +                if ($countVoucher > 1) {
    +                    for ($i = 0; $i < $countVoucher; $i++) {
    +                        if ($cart['voucher'][$i]['voucher_id'] == $voucherId) {
    +                            unset($cart['voucher'][$i]);
    +                        }
    +                    }
    +                } else {
    +                    for ($i = 0; $i < $countVoucher; $i++) {
    +                        if ($cart['voucher'][$i]['voucher_id'] == $voucherId) {
    +                            unset($cart['voucher']);
    +                        }
    +                    }
    +                }
    +            }
    +
    +            RedshopHelperStockroom::deleteCartAfterEmpty(
    +                $cart[$cartElement]['product_id'],
    +                'product',
    +                $cart[$cartElement]['quantity']
    +            );
    +            unset($cart[$cartElement]);
    +            $cart = array_merge(array(), $cart);
    +
    +            $Index = $cart['idx'] - 1;
    +
    +            if ($Index > 0) {
    +                $cart['idx'] = $Index;
    +            } else {
    +                $cart        = array();
    +                $cart['idx'] = 0;
    +            }
    +        }
    +
    +        \Redshop\Cart\Helper::setCart($cart);
    +    }
    +
    +    /**
    +     * Empty cart
    +     *
    +     * @return  boolean
    +     *
    +     * @since   2.0.6
    +     */
    +    public function emptyCart()
    +    {
    +        return RedshopHelperCart::emptyCart();
    +    }
    +
    +    /**
    +     *
    +     * @return  array|null
    +     *
    +     * @since   2.0.6
    +     */
    +    public function getData()
    +    {
    +        if (empty($this->_data)) {
    +            if (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE')) {
    +                $this->_data = RedshopHelperTemplate::getTemplate("quotation_cart");
    +            } else {
    +                if (!Redshop::getConfig()->get('USE_AS_CATALOG')) {
    +                    $this->_data = RedshopHelperTemplate::getTemplate("cart");
    +                } else {
    +                    $this->_data = RedshopHelperTemplate::getTemplate("catalogue_cart");
    +                }
    +            }
    +        }
    +
    +        return $this->_data;
    +    }
    +
    +    /**
    +     * Update cart.
    +     *
    +     * @param   array  $data  data in cart
    +     */
    +    public function update($data)
    +    {
    +        $cart = \Redshop\Cart\Helper::getCart();
    +        $user = JFactory::getUser();
    +
    +        $cartElement = $data['cart_index'];
    +        $newQuantity = intval(abs($data['quantity']) > 0 ? $data['quantity'] : 1);
    +        $oldQuantity = intval($cart[$cartElement]['quantity']);
    +
    +        $calculator_price = 0;
    +        $wrapper_price    = 0;
    +        $wrapper_vat      = 0;
    +
    +        if ($newQuantity <= 0) {
    +            $newQuantity = 1;
    +        }
    +
    +        if ($newQuantity != $oldQuantity) {
    +            if (isset($cart[$cartElement]['giftcard_id']) && $cart[$cartElement]['giftcard_id']) {
    +                $cart[$cartElement]['quantity'] = $newQuantity;
    +            } else {
    +                if (array_key_exists('checkQuantity', $data)) {
    +                    $cart[$cartElement]['quantity'] = $data['checkQuantity'];
    +                } else {
    +                    $cart[$cartElement]['quantity'] = \Redshop\Stock\Helper::checkQuantityInStock(
    +                        $cart[$cartElement],
    +                        $newQuantity
    +                    );
    +                }
    +
    +                if ($newQuantity > $cart[$cartElement]['quantity']) {
    +                    $cart['notice_message'] = $cart[$cartElement]['quantity'] . " " . JTEXT::_(
    +                            'COM_REDSHOP_AVAILABLE_STOCK_MESSAGE'
    +                        );
    +                } else {
    +                    $cart['notice_message'] = "";
    +                }
    +
    +                $cart[$cartElement]['cart_accessory'] = $this->updateAccessoryPriceArray(
    +                    $cart[$cartElement],
    +                    $cart[$cartElement]['quantity']
    +                );
    +                $cart[$cartElement]['cart_attribute'] = $this->updateAttributePriceArray(
    +                    $cart[$cartElement],
    +                    $cart[$cartElement]['quantity']
    +                );
    +
    +                // Discount calculator
    +                if (!empty($cart[$cartElement]['discount_calc'])) {
    +                    $calcdata               = $cart[$cartElement]['discount_calc'];
    +                    $calcdata['product_id'] = $cart[$cartElement]['product_id'];
    +
    +                    $discount_cal = \Redshop\Promotion\Discount::discountCalculator($calcdata);
    +
    +                    $calculator_price  = $discount_cal['product_price'];
    +                    $product_price_tax = $discount_cal['product_price_tax'];
    +                }
    +
    +                // Attribute price
    +                $retAttArr                  = RedshopHelperProduct::makeAttributeCart(
    +                    $cart[$cartElement]['cart_attribute'],
    +                    $cart[$cartElement]['product_id'],
    +                    $user->id,
    +                    $calculator_price,
    +                    $cart[$cartElement]['quantity']
    +                );
    +                $product_price              = $retAttArr[1];
    +                $product_vat_price          = $retAttArr[2];
    +                $product_old_price          = $retAttArr[5] + $retAttArr[6];
    +                $product_old_price_excl_vat = $retAttArr[5];
    +
    +                // Accessory price
    +                $retAccArr             = RedshopHelperProduct::makeAccessoryCart(
    +                    $cart[$cartElement]['cart_accessory'],
    +                    $cart[$cartElement]['product_id']
    +                );
    +                $accessory_total_price = $retAccArr[1];
    +                $accessory_vat_price   = $retAccArr[2];
    +
    +                if ($cart[$cartElement]['wrapper_id']) {
    +                    $wrapperArr    = \Redshop\Wrapper\Helper::getWrapperPrice(
    +                        array(
    +                            'product_id' => $cart[$cartElement]['product_id'],
    +                            'wrapper_id' => $cart[$cartElement]['wrapper_id']
    +                        )
    +                    );
    +                    $wrapper_vat   = $wrapperArr['wrapper_vat'];
    +                    $wrapper_price = $wrapperArr['wrapper_price'];
    +                }
    +
    +                if (isset($cart[$cartElement]['subscription_id']) && $cart[$cartElement]['subscription_id'] != "") {
    +                    $subscription_vat    = 0;
    +                    $subscription_detail = RedshopHelperProduct::getProductSubscriptionDetail(
    +                        $cart[$cartElement]['product_id'],
    +                        $cart[$cartElement]['subscription_id']
    +                    );
    +                    $subscription_price  = $subscription_detail->subscription_price;
    +
    +                    if ($subscription_price) {
    +                        $subscription_vat = RedshopHelperProduct::getProductTax(
    +                            $cart[$cartElement]['product_id'],
    +                            $subscription_price
    +                        );
    +                    }
    +
    +                    $product_vat_price += $subscription_vat;
    +                    $product_price     = $product_price + $subscription_price;
    +
    +                    $product_old_price_excl_vat += $subscription_price;
    +                }
    +
    +                $cart[$cartElement]['product_price']              = $product_price + $product_vat_price + $accessory_total_price + $accessory_vat_price + $wrapper_price + $wrapper_vat;
    +                $cart[$cartElement]['product_old_price']          = $product_old_price + $accessory_total_price + $accessory_vat_price + $wrapper_price + $wrapper_vat;
    +                $cart[$cartElement]['product_old_price_excl_vat'] = $product_old_price_excl_vat + $accessory_total_price + $wrapper_price;
    +                $cart[$cartElement]['product_price_excl_vat']     = $product_price + $accessory_total_price + $wrapper_price;
    +                $cart[$cartElement]['product_vat']                = $product_vat_price + $accessory_vat_price + $wrapper_vat;
    +                JPluginHelper::importPlugin('redshop_product');
    +                $dispatcher = RedshopHelperUtility::getDispatcher();
    +                $dispatcher->trigger('onAfterCartUpdate', array(&$cart, $cartElement, $data));
    +            }
    +        }
    +
    +        \Redshop\Cart\Helper::setCart($cart);
    +    }
    +
    +    public function updateAccessoryPriceArray($data = array(), $newquantity = 1)
    +    {
    +        $attArr = $data['cart_accessory'];
    +
    +        for ($i = 0, $in = count($attArr); $i < $in; $i++) {
    +            $attchildArr = $attArr[$i]['accessory_childs'];
    +
    +            $attArr[$i]['accessory_quantity'] = $newquantity;
    +
    +            for ($j = 0, $jn = count($attchildArr); $j < $jn; $j++) {
    +                $propArr = $attchildArr[$j]['attribute_childs'];
    +
    +                for ($k = 0, $kn = count($propArr); $k < $kn; $k++) {
    +                    $pricelist = RedshopHelperProduct_Attribute::getPropertyPrice(
    +                        $propArr[$k]['property_id'],
    +                        $newquantity,
    +                        'property'
    +                    );
    +
    +                    if (count($pricelist) > 0) {
    +                        $propArr[$k]['property_price'] = $pricelist->product_price;
    +                    } else {
    +                        $pricelist                     = RedshopHelperProduct::getProperty(
    +                            $propArr[$k]['property_id'],
    +                            'property'
    +                        );
    +                        $propArr[$k]['property_price'] = $pricelist->product_price;
    +                    }
    +
    +                    $subpropArr = $propArr[$k]['property_childs'];
    +
    +                    for ($l = 0, $ln = count($subpropArr); $l < $ln; $l++) {
    +                        $pricelist = RedshopHelperProduct_Attribute::getPropertyPrice(
    +                            $subpropArr[$l]['subproperty_id'],
    +                            $newquantity,
    +                            'subproperty'
    +                        );
    +
    +                        if (count($pricelist) > 0) {
    +                            $subpropArr[$l]['subproperty_price'] = $pricelist->product_price;
    +                        } else {
    +                            $pricelist                           = RedshopHelperProduct::getProperty(
    +                                $subpropArr[$l]['subproperty_id'],
    +                                'subproperty'
    +                            );
    +                            $subpropArr[$k]['subproperty_price'] = $pricelist->product_price;
    +                        }
    +                    }
    +
    +                    $propArr[$k]['property_childs'] = $subpropArr;
    +                }
    +
    +                $attchildArr[$j]['attribute_childs'] = $propArr;
    +            }
    +
    +            $attArr[$i]['accessory_childs'] = $attchildArr;
    +        }
    +
    +        return $attArr;
    +    }
    +
    +    public function updateAttributePriceArray($data = array(), $newquantity = 1)
    +    {
    +        $attArr = $data['cart_attribute'];
    +
    +        for ($i = 0, $in = count($attArr); $i < $in; $i++) {
    +            $propArr = $attArr[$i]['attribute_childs'];
    +
    +            for ($k = 0, $kn = count($propArr); $k < $kn; $k++) {
    +                $pricelist = RedshopHelperProduct_Attribute::getPropertyPrice(
    +                    $propArr[$k]['property_id'],
    +                    $newquantity,
    +                    'property'
    +                );
    +
    +                if (count($pricelist) > 0) {
    +                    $propArr[$k]['property_price'] = $pricelist->product_price;
    +                } else {
    +                    $pricelist                     = RedshopHelperProduct::getProperty(
    +                        $propArr[$k]['property_id'],
    +                        'property'
    +                    );
    +                    $propArr[$k]['property_price'] = $pricelist->product_price;
    +                }
    +
    +                $subpropArr = $propArr[$k]['property_childs'];
    +
    +                for ($l = 0, $ln = count($subpropArr); $l < $ln; $l++) {
    +                    $pricelist = RedshopHelperProduct_Attribute::getPropertyPrice(
    +                        $subpropArr[$l]['subproperty_id'],
    +                        $newquantity,
    +                        'subproperty'
    +                    );
    +
    +                    if (count($pricelist) > 0) {
    +                        $subpropArr[$l]['subproperty_price'] = $pricelist->product_price;
    +                    } else {
    +                        $pricelist                           = RedshopHelperProduct::getProperty(
    +                            $subpropArr[$l]['subproperty_id'],
    +                            'subproperty'
    +                        );
    +                        $subpropArr[$k]['subproperty_price'] = $pricelist->product_price;
    +                    }
    +                }
    +
    +                $propArr[$k]['property_childs'] = $subpropArr;
    +            }
    +
    +            $attArr[$i]['attribute_childs'] = $propArr;
    +        }
    +
    +        return $attArr;
    +    }
    +
    +    public function update_all($data)
    +    {
    +        JPluginHelper::importPlugin('redshop_product');
    +        $dispatcher = RedshopHelperUtility::getDispatcher();
    +
    +        $cart = \Redshop\Cart\Helper::getCart();
    +        $user = JFactory::getUser();
    +
    +        if (empty($cart)) {
    +            $cart        = array();
    +            $cart['idx'] = 0;
    +            \Redshop\Cart\Helper::setCart($cart);
    +            $cart = \Redshop\Cart\Helper::getCart();
    +        }
    +
    +        $idx           = (int)($cart['idx']);
    +        $quantity_all  = $data['quantity_all'];
    +        $quantity      = explode(",", $quantity_all);
    +        $totalQuantity = array_sum($quantity);
    +
    +        for ($i = 0; $i < $idx; $i++) {
    +            if ($quantity[$i] < 0) {
    +                $quantity[$i] = $cart[$i]['quantity'];
    +            }
    +
    +            $quantity[$i] = intval(abs($quantity[$i]) > 0 ? $quantity[$i] : 1);
    +
    +            if ($quantity[$i] != $cart[$i]['quantity']) {
    +                if (isset($cart[$i]['giftcard_id']) && $cart[$i]['giftcard_id']) {
    +                    $cart[$i]['quantity'] = $quantity[$i];
    +                } else {
    +                    // Reinit price
    +                    $productPriceInit = 0;
    +
    +                    // Accessory price fix during update
    +                    $accessoryAsProdut           = RedshopHelperAccessory::getAccessoryAsProduct(
    +                        $cart['AccessoryAsProduct']
    +                    );
    +                    $accessoryAsProdutWithoutVat = false;
    +
    +                    if (isset($accessoryAsProdut->accessory)
    +                        && isset($accessoryAsProdut->accessory[$cart[$i]['product_id']])
    +                        && isset($cart[$i]['accessoryAsProductEligible'])
    +                    ) {
    +                        $accessoryAsProdutWithoutVat = '{without_vat}';
    +                        $accessoryPrice              = (float)$accessoryAsProdut->accessory[$cart[$i]['product_id']]->newaccessory_price;
    +
    +                        $productPriceInit                   = RedshopHelperProductPrice::priceRound($accessoryPrice);
    +                        $cart[$i]['product_vat']            = 0;
    +                        $cart[$i]['product_price_excl_vat'] = RedshopHelperProductPrice::priceRound($accessoryPrice);
    +                    }
    +
    +                    $cart[$i]['quantity'] = \Redshop\Stock\Helper::checkQuantityInStock($cart[$i], $quantity[$i]);
    +
    +                    $cart[$i]['cart_accessory'] = $this->updateAccessoryPriceArray($cart[$i], $cart[$i]['quantity']);
    +                    $cart[$i]['cart_attribute'] = $this->updateAttributePriceArray($cart[$i], $cart[$i]['quantity']);
    +
    +                    // Discount calculator
    +                    if (!empty($cart[$i]['discount_calc'])) {
    +                        $calcdata               = $cart[$i]['discount_calc'];
    +                        $calcdata['product_id'] = $cart[$i]['product_id'];
    +
    +                        $discount_cal = \Redshop\Promotion\Discount::discountCalculator($calcdata);
    +
    +                        $calculator_price = $discount_cal['product_price'];
    +                    }
    +
    +                    $dispatcher->trigger('onBeforeCartItemUpdate', array(&$cart, $i, &$calculator_price));
    +
    +                    // Attribute price
    +                    $retAttArr = RedshopHelperProduct::makeAttributeCart(
    +                        $cart[$i]['cart_attribute'],
    +                        $cart[$i]['product_id'],
    +                        $user->id,
    +                        $productPriceInit,
    +                        $totalQuantity,    // Total Quantity based discount applied here
    +                        $accessoryAsProdutWithoutVat
    +                    );
    +
    +                    $accessoryAsProductZero     = (count(
    +                            $retAttArr[8]
    +                        ) == 0 && $productPriceInit == 0 && ($accessoryAsProdutWithoutVat !== false));
    +                    $product_price              = ($accessoryAsProductZero) ? 0 : $retAttArr[1];
    +                    $product_vat_price          = ($accessoryAsProductZero) ? 0 : $retAttArr[2];
    +                    $product_old_price          = ($accessoryAsProductZero) ? 0 : $retAttArr[5] + $retAttArr[6];
    +                    $product_old_price_excl_vat = ($accessoryAsProductZero) ? 0 : $retAttArr[5];
    +
    +                    // Accessory price
    +                    $retAccArr             = RedshopHelperProduct::makeAccessoryCart(
    +                        $cart[$i]['cart_accessory'],
    +                        $cart[$i]['product_id']
    +                    );
    +                    $accessory_total_price = $retAccArr[1];
    +                    $accessory_vat_price   = $retAccArr[2];
    +
    +                    $wrapper_price = 0;
    +                    $wrapper_vat   = 0;
    +
    +                    if ($cart[$i]['wrapper_id']) {
    +                        $wrapperArr    = \Redshop\Wrapper\Helper::getWrapperPrice(
    +                            array('product_id' => $cart[$i]['product_id'], 'wrapper_id' => $cart[$i]['wrapper_id'])
    +                        );
    +                        $wrapper_vat   = $wrapperArr['wrapper_vat'];
    +                        $wrapper_price = $wrapperArr['wrapper_price'];
    +                    }
    +
    +                    $subscription_vat = 0;
    +
    +                    if (isset($cart[$i]['subscription_id']) && $cart[$i]['subscription_id'] != "") {
    +                        $productId           = $cart[$i]['product_id'];
    +                        $subscription_detail = RedshopHelperProduct::getProductSubscriptionDetail(
    +                            $productId,
    +                            $cart[$i]['subscription_id']
    +                        );
    +                        $subscription_price  = $subscription_detail->subscription_price;
    +
    +                        if ($subscription_price) {
    +                            $subscription_vat = RedshopHelperProduct::getProductTax($productId, $subscription_price);
    +                        }
    +
    +                        $product_vat_price += $subscription_vat;
    +                        $product_price     = $product_price + $subscription_price;
    +
    +                        $product_old_price_excl_vat += $subscription_price;
    +                    }
    +
    +                    $cart[$i]['product_price']              = $product_price + $product_vat_price + $accessory_total_price + $accessory_vat_price + $wrapper_price + $wrapper_vat;
    +                    $cart[$i]['product_old_price']          = $product_old_price + $accessory_total_price + $accessory_vat_price + $wrapper_price + $wrapper_vat;
    +                    $cart[$i]['product_old_price_excl_vat'] = $product_old_price_excl_vat + $accessory_total_price + $wrapper_price;
    +                    $cart[$i]['product_price_excl_vat']     = $product_price + $accessory_total_price + $wrapper_price;
    +                    $cart[$i]['product_vat']                = $product_vat_price + $accessory_vat_price + $wrapper_vat;
    +
    +                    $dispatcher->trigger('onAfterCartItemUpdate', array(&$cart, $i, $data));
    +                }
    +            }
    +        }
    +
    +        unset($cart[$idx]);
    +
    +        \Redshop\Cart\Helper::setCart($cart);
    +    }
    +
    +    public function coupon()
    +    {
    +        return \RedshopHelperCartDiscount::applyCoupon();
    +    }
    +
    +    public function voucher()
    +    {
    +        return \RedshopHelperCartDiscount::applyVoucher();
    +    }
    +
    +    public function redmasscart($post)
    +    {
    +        $data            = array();
    +        $products_number = explode("\n", $post["numbercart"]);
    +        $db              = JFactory::getDbo();
    +
    +        foreach ($products_number as $productNumber) {
    +            $productNumber = trim($productNumber);
    +
    +            if ($productNumber === '') {
    +                continue;
    +            }
    +
    +            $query   = $db->getQuery(true)
    +                ->select('product_id, published, not_for_sale, expired, product_name')
    +                ->from($db->qn('#__redshop_product'))
    +                ->where('product_number = ' . $db->quote($productNumber));
    +            $product = $db->setQuery($query)->loadObject();
    +
    +            if (!$product) {
    +                continue;
    +            }
    +
    +            $productId = $product->product_id;
    +
    +            if ($product->published == 0) {
    +                $msg = sprintf(JText::_('COM_REDSHOP_PRODUCT_IS_NOT_PUBLISHED'), $product->product_name, $productId);
    +                /** @scrutinizer ignore-deprecated */
    +                JError::raiseWarning(20, $msg);
    +                continue;
    +            }
    +
    +            if ($product->not_for_sale > 0) {
    +                $msg = sprintf(JText::_('COM_REDSHOP_PRODUCT_IS_NOT_FOR_SALE'), $product->product_name, $productId);
    +                /** @scrutinizer ignore-deprecated */
    +                JError::raiseWarning(20, $msg);
    +                continue;
    +            }
    +
    +            if ($product->expired == 1) {
    +                $msg = sprintf(JText::_('COM_REDSHOP_PRODUCT_IS_EXPIRED'), $product->product_name, $productId);
    +                /** @scrutinizer ignore-deprecated */
    +                JError::raiseWarning(20, $msg);
    +                continue;
    +            }
    +
    +            $data["product_id"] = $productId;
    +
    +            if (isset($post["mod_quantity"]) && $post["mod_quantity"] !== "") {
    +                $data["quantity"] = $post["mod_quantity"];
    +            } else {
    +                $data["quantity"] = 1;
    +            }
    +
    +            Redshop\Cart\Cart::addProduct($data);
    +            RedshopHelperCart::cartFinalCalculation();
    +        }
    +    }
    +
    +    /**
    +     * check if attribute tag is present in product template.
    +     *
    +     * @param   int  $productId  Product ID
    +     *
    +     * @return  boolean
    +     *
    +     * @since   2.0.6
    +     */
    +    public function checkifTagAvailable($productId)
    +    {
    +        $db    = JFactory::getDbo();
    +        $query = $db->getQuery(true);
    +        $query->select($db->quoteName('product_template'))
    +            ->from($db->quoteName('#__redshop_product'))
    +            ->where($db->quoteName('product_id') . ' = ' . (int)$productId);
    +
    +        $productTemplate = $db->setQuery($query)->loadResult();
    +
    +        $template              = RedshopHelperTemplate::getTemplate("product", $productTemplate);
    +        $product_template_desc = $template[0]->template_desc;
    +
    +        return strpos($product_template_desc, "{attribute_template:") !== false;
    +    }
    +
    +    public function getCartProductPrice($productId, $cart, $voucher_left)
    +    {
    +        $productArr             = array();
    +        $affected_product_idArr = array();
    +        $idx                    = $cart['idx'];
    +        $product_price          = 0;
    +        $product_price_excl_vat = 0;
    +        $p_quantity             = 0;
    +
    +        $productIdArr = explode(',', $productId);
    +
    +        for ($v = 0; ($v < $idx) && ($voucher_left > 0); $v++) {
    +            if ($voucher_left < $cart[$v]['quantity'] && $voucher_left) {
    +                $cart[$v]['quantity'] = $voucher_left;
    +            }
    +
    +            if (in_array($cart[$v]['product_id'], $productIdArr) || $this->_globalvoucher) {
    +                $product_price            += $cart[$v]['product_price'] * $cart[$v]['quantity'];
    +                $p_quantity               += $cart[$v]['quantity'];
    +                $product_price_excl_vat   += $cart[$v]['product_price_excl_vat'] * $cart[$v]['quantity'];
    +                $affected_product_idArr[] = $cart[$v]['product_id'];
    +                $voucher_left             = $voucher_left - $cart[$v]['quantity'];
    +            }
    +        }
    +
    +        $productArr['product_ids']            = implode(',', $affected_product_idArr);
    +        $productArr['product_price']          = $product_price;
    +        $productArr['product_price_excl_vat'] = $product_price_excl_vat;
    +        $productArr['product_quantity']       = $p_quantity;
    +
    +        return $productArr;
    +    }
    +
    +    /**
    +     * @param   array  $data  Data
    +     *
    +     * @return   array
    +     *
    +     * @since    2.0.6
    +     */
    +    public function changeAttribute($data)
    +    {
    +        $imagename = '';
    +        $type      = '';
    +        $cart      = \Redshop\Cart\Helper::getCart();
    +
    +        $generateAttributeCart = array();
    +        $productId             = $data['product_id'];
    +        $idx                   = $data['cart_index'];
    +
    +        if (isset($data['attribute_id_prd_' . $productId . '_0'])) {
    +            $attribute_data = $data['attribute_id_prd_' . $productId . '_0'];
    +
    +            for ($ia = 0, $countAttribute = count($attribute_data); $ia < $countAttribute; $ia++) {
    +                $accPropertyCart                              = array();
    +                $attribute                                    = \Redshop\Product\Attribute::getProductAttribute(
    +                    0,
    +                    0,
    +                    $attribute_data[$ia]
    +                );
    +                $generateAttributeCart[$ia]['attribute_id']   = $attribute_data[$ia];
    +                $generateAttributeCart[$ia]['attribute_name'] = $attribute[0]->text;
    +
    +                if ($attribute[0]->text != "" && isset($data['property_id_prd_' . $productId . '_0_' . $attribute_data[$ia]])) {
    +                    $acc_property_data = $data['property_id_prd_' . $productId . '_0_' . $attribute_data[$ia]];
    +
    +                    for ($ip = 0, $countProperty = count($acc_property_data); $ip < $countProperty; $ip++) {
    +                        if ($acc_property_data[$ip] != 0) {
    +                            $accSubpropertyCart = array();
    +                            $property_price     = 0;
    +                            $property           = RedshopHelperProduct_Attribute::getAttributeProperties(
    +                                $acc_property_data[$ip]
    +                            );
    +                            $pricelist          = RedshopHelperProduct_Attribute::getPropertyPrice(
    +                                $acc_property_data[$ip],
    +                                $cart[$idx]['quantity'],
    +                                'property'
    +                            );
    +
    +                            if (isset($pricelist->product_price)) {
    +                                $property_price = $pricelist->product_price;
    +                            } else {
    +                                $property_price = $property[0]->property_price;
    +                            }
    +
    +                            if (count($property) > 0 && JFile::exists(
    +                                    REDSHOP_FRONT_IMAGES_RELPATH . "product_attributes/" . $property[0]->property_image
    +                                )) {
    +                                $type      = 'product_attributes';
    +                                $imagename = $property[0]->property_image;
    +                            }
    +
    +                            $accPropertyCart[$ip]['property_id']     = $acc_property_data[$ip];
    +                            $accPropertyCart[$ip]['property_name']   = $property[0]->text;
    +                            $accPropertyCart[$ip]['property_oprand'] = $property[0]->oprand;
    +                            $accPropertyCart[$ip]['property_price']  = $property_price;
    +
    +                            if (isset($data['subproperty_id_prd_' . $productId . '_0_' . $attribute_data[$ia] . '_' . $acc_property_data[$ip]])) {
    +                                $acc_subproperty_data = $data['subproperty_id_prd_' . $productId . '_0_' . $attribute_data[$ia] . '_' . $acc_property_data[$ip]];
    +                                $countSubProperty     = count($acc_subproperty_data);
    +
    +                                for ($isp = 0; $isp < $countSubProperty; $isp++) {
    +                                    if ($acc_subproperty_data[$isp] != 0) {
    +                                        $subproperty_price = 0;
    +                                        $subproperty       = RedshopHelperProduct_Attribute::getAttributeSubProperties(
    +                                            $acc_subproperty_data[$isp]
    +                                        );
    +                                        $pricelist         = RedshopHelperProduct_Attribute::getPropertyPrice(
    +                                            $acc_subproperty_data[$isp],
    +                                            $cart[$idx]['quantity'],
    +                                            'subproperty'
    +                                        );
    +
    +                                        if (count($pricelist) > 0) {
    +                                            $subproperty_price = $pricelist->product_price;
    +                                        } else {
    +                                            $subproperty_price = $subproperty[0]->subattribute_color_price;
    +                                        }
    +
    +                                        if (count($subproperty) > 0 && JFile::exists(
    +                                                REDSHOP_FRONT_IMAGES_RELPATH . "subcolor/" . $subproperty[0]->subattribute_color_image
    +                                            )) {
    +                                            $type      = 'subcolor';
    +                                            $imagename = $subproperty[0]->subattribute_color_image;
    +                                        }
    +
    +                                        $accSubpropertyCart[$isp]['subproperty_id']           = $acc_subproperty_data[$isp];
    +                                        $accSubpropertyCart[$isp]['subproperty_name']         = $subproperty[0]->text;
    +                                        $accSubpropertyCart[$isp]['subproperty_oprand']       = $subproperty[0]->oprand;
    +                                        $accSubpropertyCart[$isp]['subattribute_color_title'] = $subproperty[0]->subattribute_color_title;
    +                                        $accSubpropertyCart[$isp]['subproperty_price']        = $subproperty_price;
    +                                    }
    +                                }
    +                            }
    +
    +                            $accPropertyCart[$ip]['property_childs'] = $accSubpropertyCart;
    +                        }
    +                    }
    +                }
    +
    +                $generateAttributeCart[$ia]['attribute_childs'] = $accPropertyCart;
    +            }
    +        }
    +
    +        $cart[$idx]['cart_attribute'] = $generateAttributeCart;
    +
    +        if (!empty($imagename) && !empty($type)) {
    +            $cart[$idx]['hidden_attribute_cartimage'] = REDSHOP_FRONT_IMAGES_ABSPATH . $type . "/" . $imagename;
    +        }
    +
    +        // @TODO Do we need setCart back ?
    +
    +        return $cart;
    +    }
     }
    diff --git a/component/site/models/catalog.php b/component/site/models/catalog.php
    index 3769dbed58b..37b67e7e54a 100644
    --- a/component/site/models/catalog.php
    +++ b/component/site/models/catalog.php
    @@ -18,77 +18,77 @@
      */
     class RedshopModelCatalog extends RedshopModel
     {
    -	/**
    -	 * @var null|string
    -	 */
    -	public $_table_prefix = null;
    +    /**
    +     * @var null|string
    +     */
    +    public $_table_prefix = null;
     
    -	/**
    -	 * RedshopModelCatalog constructor.
    -	 */
    -	public function __construct()
    -	{
    -		parent::__construct();
    -		$this->_table_prefix = '#__redshop_';
    -	}
    +    /**
    +     * RedshopModelCatalog constructor.
    +     */
    +    public function __construct()
    +    {
    +        parent::__construct();
    +        $this->_table_prefix = '#__redshop_';
    +    }
     
    -	/**
    -	 * Method for store catalog
    -	 *
    -	 * @param   array  $data  Data
    -	 *
    -	 * @return  boolean
    -	 * @throws  Exception
    -	 */
    -	public function catalogStore($data)
    -	{
    -		/** @var Tablecatalog_request $row */
    -		$row = $this->getTable('catalog_request');
    +    /**
    +     * Method for store catalog
    +     *
    +     * @param   array  $data  Data
    +     *
    +     * @return  boolean
    +     * @throws  Exception
    +     */
    +    public function catalogStore($data)
    +    {
    +        /** @var Tablecatalog_request $row */
    +        $row = $this->getTable('catalog_request');
     
    -		if (!$row->bind($data))
    -		{
    -			/** @scrutinizer ignore-deprecated */$this->setError(/** @scrutinizer ignore-deprecated */$this->_db->getErrorMsg());
    +        if (!$row->bind($data)) {
    +            /** @scrutinizer ignore-deprecated */
    +            $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg());
     
    -			return false;
    -		}
    +            return false;
    +        }
     
    -		if (!$row->store())
    -		{
    -			/** @scrutinizer ignore-deprecated */$this->setError(/** @scrutinizer ignore-deprecated */$this->_db->getErrorMsg());
    +        if (!$row->store()) {
    +            /** @scrutinizer ignore-deprecated */
    +            $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg());
     
    -			return false;
    -		}
    +            return false;
    +        }
     
    -		return true;
    -	}
    +        return true;
    +    }
     
    -	/**
    -	 * Method for store catalog sample
    -	 *
    -	 * @param   array  $data  Data
    -	 *
    -	 * @return  boolean
    -	 * @throws  Exception
    -	 */
    -	public function catalogSampleStore($data)
    -	{
    -		/** @var Tablesample_request $row */
    -		$row = $this->getTable('sample_request');
    +    /**
    +     * Method for store catalog sample
    +     *
    +     * @param   array  $data  Data
    +     *
    +     * @return  boolean
    +     * @throws  Exception
    +     */
    +    public function catalogSampleStore($data)
    +    {
    +        /** @var Tablesample_request $row */
    +        $row = $this->getTable('sample_request');
     
    -		if (!$row->bind($data))
    -		{
    -			/** @scrutinizer ignore-deprecated */$this->setError(/** @scrutinizer ignore-deprecated */$this->_db->getErrorMsg());
    +        if (!$row->bind($data)) {
    +            /** @scrutinizer ignore-deprecated */
    +            $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg());
     
    -			return false;
    -		}
    +            return false;
    +        }
     
    -		if (!$row->store())
    -		{
    -			/** @scrutinizer ignore-deprecated */$this->setError(/** @scrutinizer ignore-deprecated */$this->_db->getErrorMsg());
    +        if (!$row->store()) {
    +            /** @scrutinizer ignore-deprecated */
    +            $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg());
     
    -			return false;
    -		}
    +            return false;
    +        }
     
    -		return true;
    -	}
    +        return true;
    +    }
     }
    diff --git a/component/site/models/category.php b/component/site/models/category.php
    index e420571d07d..c4e7bb8eded 100644
    --- a/component/site/models/category.php
    +++ b/component/site/models/category.php
    @@ -18,921 +18,878 @@
      */
     class RedshopModelCategory extends RedshopModel
     {
    -	public $_id = null;
    -
    -	public $_data = null;
    -
    -	public $_product = null;
    -
    -	public $_template = null;
    -
    -	public $_limit = null;
    -
    -	public $_slidercount = 0;
    -
    -	public $_maincat = null;
    -
    -	public $count_no_user_field = 0;
    -
    -	public $minmaxArr = array(0, 0);
    -
    -	public $_total = 0;
    -
    -	// @ToDo In feature, when class Category extends RedshopModelList, replace filter_fields in constructor
    -	public $filter_fields = array(
    -		'p.product_name', 'product_name',
    -		'p.product_price', 'product_price',
    -		'p.product_price', 'product_price',
    -		'p.product_number', 'product_number',
    -		'p.product_id', 'product_id',
    -		'c.ordering', 'ordering'
    -	);
    -
    -	/**
    -	 * Constructor
    -	 */
    -	public function __construct()
    -	{
    -		$app = JFactory::getApplication();
    -		$input = JFactory::getApplication()->input;
    -		$params = $app->getParams('com_redshop');
    -		$layout = $input->getCmd('layout', 'detail');
    -		$print  = $input->getCmd('print', '');
    -		$Id     = $input->getInt('cid', 0);
    -
    -		if (!$print && !$Id)
    -		{
    -			$Id = (int) $params->get('cid');
    -		}
    -
    -		// Different context depending on the view
    -		if (empty($this->context))
    -		{
    -			$this->context = strtolower('com_redshop.category.' . $this->getName() . '.' . $layout . '.' . $Id);
    -		}
    -
    -		parent::__construct();
    -
    -		$this->setId((int) $Id);
    -	}
    -
    -	/**
    -	 * Method to auto-populate the model state.
    -	 *
    -	 * @param   string  $ordering   An optional ordering field.
    -	 * @param   string  $direction  An optional direction (asc|desc).
    -	 *
    -	 * @return  void
    -	 *
    -	 * @note    Calling getState in this method will result in recursion.
    -	 */
    -	protected function populateState($ordering = '', $direction = '')
    -	{
    -		$app = JFactory::getApplication();
    -		$params = $app->getParams('com_redshop');
    -		$selectedTemplate = Redshop::getConfig()->get('DEFAULT_CATEGORYLIST_TEMPLATE');
    -		$layout = $app->input->getCmd('layout', 'detail');
    -
    -		if ($this->_id)
    -		{
    -			$selectedTemplate  = (int) $params->get('category_template', 0);
    -			$mainCat = $this->_loadCategory();
    -
    -			if (!$selectedTemplate && isset($mainCat->template))
    -			{
    -				$selectedTemplate = $mainCat->template;
    -			}
    -		}
    -
    -		$categoryTemplate = $app->getUserStateFromRequest($this->context . '.category_template', 'category_template', $selectedTemplate, 'int');
    -		$this->setState('category_template', $categoryTemplate);
    -
    -		$filterData = $app->getUserStateFromRequest($this->context . '.filter_data', 'filterform', '', 'array');
    -		$this->setState('filterform', $filterData);
    -
    -		if ($_POST)
    -		{
    -			$manufacturerId = $app->input->post->getInt('manufacturer_id', 0);
    -
    -			if ($manufacturerId != $app->getUserState($this->context . '.manufacturer_id', $app->input->get->getInt('manufacturer_id', 0)))
    -			{
    -				$app->redirect(
    -					JRoute::_(
    -						'index.php?option=com_redshop&view=category&layout=' . $layout . '&cid=' . $this->_id . '&manufacturer_id=' . $manufacturerId
    -						. '&Itemid=' . $app->input->getInt('Itemid', 0),
    -						true
    -					)
    -				);
    -			}
    -		}
    -		else
    -		{
    -			$manufacturerId = $app->input->getInt('manufacturer_id', 0);
    -			$app->setUserState($this->context . '.manufacturer_id', $manufacturerId);
    -		}
    -
    -		$categoryId     = $app->input->post->getInt('category_id', 0);
    -		$this->setState('category_id', $categoryId);
    -		$this->setState('manufacturer_id', $manufacturerId);
    -
    -		// Get default ordering
    -		$orderBySelect = $params->get('order_by', Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD'));
    -		$editTimestamp = $params->get('editTimestamp', 0);
    -		$userTimestamp = $app->getUserState($this->context . '.editTimestamp', 0);
    -
    -		if ($editTimestamp > $userTimestamp)
    -		{
    -			$app->setUserState($this->context . '.order_by', $orderBySelect);
    -		}
    -
    -		$app->setUserState($this->context . '.editTimestamp', time());
    -
    -		$orderByMethod = $app->getUserStateFromRequest($this->context . '.order_by', 'order_by', $orderBySelect);
    -		$orderBy       = RedshopHelperUtility::prepareOrderBy($orderByMethod);
    -
    -		$this->setState('list.ordering', $orderBy->ordering);
    -		$this->setState('list.direction', $orderBy->direction);
    -
    -		$this->loadCategoryTemplate($categoryTemplate);
    -
    -		if (isset($this->_template[0]->template_desc)
    -			&& strstr($this->_template[0]->template_desc, "{show_all_products_in_category}"))
    -		{
    -			$limit = 0;
    -		}
    -		elseif (isset($this->_template[0]->template_desc)
    -			&& strpos($this->_template[0]->template_desc, "{show_all_products_in_category}") === false
    -			&& strpos($this->_template[0]->template_desc, "{pagination}") !== false
    -			&& strpos($this->_template[0]->template_desc, "perpagelimit:") !== false)
    -		{
    -			$perpage = explode('{perpagelimit:', $this->_template[0]->template_desc);
    -			$perpage = explode('}', $perpage[1]);
    -			$limit   = intval($perpage[0]);
    -		}
    -		else
    -		{
    -			$limit = 0;
    -
    -			if ($this->_id)
    -			{
    -				$item = $app->getMenu()->getActive();
    -
    -				if (isset($this->_template[0]->template_desc) && strstr($this->_template[0]->template_desc, "{product_display_limit}"))
    -				{
    -					$limit = $app->getUserStateFromRequest($this->context . '.limit', 'limit', 0, 'int');
    -				}
    -
    -				if (!$limit && $item)
    -				{
    -					$limit = (int) $item->params->get('maxproduct', 0);
    -				}
    -
    -				if (!$limit)
    -				{
    -					$limit = $this->_maincat->products_per_page;
    -				}
    -			}
    -
    -			if (!$limit)
    -			{
    -				$limit = Redshop::getConfig()->get('MAXCATEGORY');
    -			}
    -		}
    -
    -		$this->setState('list.limit', $limit);
    -		$value = $app->input->get('limitstart', 0, 'int');
    -		$limitstart = ($limit != 0 ? (floor($value / $limit) * $limit) : 0);
    -		$this->setState('list.start', $limitstart);
    -	}
    -
    -	public function setId($id)
    -	{
    -		$this->_id   = $id;
    -		$this->_data = null;
    -	}
    -
    -	/**
    -	 * Build a query
    -	 *
    -	 * @return  JDatabaseQuery
    -	 */
    -	public function _buildQuery()
    -	{
    -		$db              = $this->getDbo();
    -		$app             = JFactory::getApplication();
    -		$menu            = $app->getMenu();
    -		$item            = $menu->getActive();
    -		$manufacturer_id = (isset($item)) ? intval($item->params->get('manufacturer_id')) : 0;
    -		$manufacturer_id = $app->input->getInt('manufacturer_id', $manufacturer_id, '', 'int');
    -		$layout          = $app->input->getCmd('layout');
    -
    -		$query = $db->getQuery(true);
    -		$query->select(
    -				array(
    -					'DISTINCT(' . $db->qn('c.id') . ')',
    -					'c.*'
    -				)
    -			)
    -			->from($db->qn('#__redshop_category', 'c'))
    -			->where($db->qn('c.published') . ' = 1');
    -
    -		if ($this->_id > 0)
    -		{
    -			$query->where($db->qn('c.parent_id') . ' = ' . (int) $this->_id);
    -		}
    -		else
    -		{
    -			$query->where($db->qn('c.parent_id') . ' = ' . (int) RedshopHelperCategory::getRootId());
    -		}
    -
    -		if ($layout != 'categoryproduct')
    -		{
    -			$query->order($this->_buildContentOrderBy());
    -		}
    -
    -		if ($manufacturer_id)
    -		{
    -			$query->leftJoin($db->qn('#__redshop_product_category_xref', 'pcx') . ' ON ' . $db->qn('pcx.category_id') . ' = ' . $db->qn('c.id'))
    -				->leftJoin($db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('pcx.product_id'))
    -				->leftJoin($db->qn('#__redshop_manufacturer', 'm') . ' ON ' . $db->qn('m.id') . ' = ' . $db->qn('p.manufacturer_id'))
    -				->where($db->qn('m.id') . ' = ' . (int) $manufacturer_id)
    -				->group($db->qn('c.id'));
    -		}
    -
    -		return $query;
    -	}
    -
    -	public function _buildContentOrderBy()
    -	{
    -		if (Redshop::getConfig()->get('DEFAULT_CATEGORY_ORDERING_METHOD'))
    -		{
    -			$orderby = Redshop::getConfig()->get('DEFAULT_CATEGORY_ORDERING_METHOD');
    -		}
    -		else
    -		{
    -			$orderby = "c.ordering";
    -		}
    -
    -		return $orderby;
    -	}
    -
    -	public function _loadCategory()
    -	{
    -		$this->_maincat = RedshopHelperCategory::getCategoryById($this->_id);
    -
    -		return $this->_maincat;
    -	}
    -
    -	public function getCategorylistProduct($categoryId = 0)
    -	{
    -		$app           = JFactory::getApplication();
    -		$menu          = $app->getMenu();
    -		$item          = $menu->getActive();
    -		$limit         = (isset($item)) ? intval($item->params->get('maxproduct')) : 0;
    -		$db            = $this->getDbo();
    -		$orderBySelect = (isset($item)) ? $item->params->get('order_by', 'p.product_name ASC') : 'p.product_name ASC';
    -		$orderByMethod = $app->getUserStateFromRequest($this->context . '.order_by', 'order_by', $orderBySelect);
    -		$orderBy       = RedshopHelperUtility::prepareOrderBy($orderByMethod);
    -
    -		$query = $db->getQuery(true)
    -			->select('*')
    -			->from($db->qn('#__redshop_product', 'p'))
    -			->leftjoin($db->qn('#__redshop_product_category_xref', 'pc') . ' ON ' . $db->qn('pc.product_id') . ' = ' . $db->qn('p.product_id'))
    -			->leftjoin($db->qn('#__redshop_category', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('pc.category_id'))
    -			->leftjoin($db->qn('#__redshop_manufacturer', 'm') . ' ON ' . $db->qn('m.id') . ' = ' . $db->qn('p.manufacturer_id'))
    -			->where($db->qn('p.published') . ' = 1')
    -			->where($db->qn('p.expired') . ' = 0')
    -			->where($db->qn('pc.category_id') . ' = ' . $db->q((int) $categoryId))
    -			->where($db->qn('p.product_parent_id') . ' = 0')
    -			->order($orderBy->ordering . ' ' . $orderBy->direction)
    -			->setLimit(0, $limit);
    -
    -		$this->_product = $this->_getList($query);
    -
    -		return $this->_product;
    -	}
    -
    -	/**
    -	 * Method get Product of Category
    -	 *
    -	 * @param   int   $minmax    default variable is 0
    -	 * @param   bool  $isSlider  default variable is false
    -	 *
    -	 * @return mixed
    -	 *
    -	 * @since   2.1.0
    -	 */
    -	public function getCategoryProduct($minmax = 0, $isSlider = false)
    -	{
    -		JPluginHelper::importPlugin('redshop_product');
    -
    -		$db      = JFactory::getDbo();
    -		$user    = JFactory::getUser();
    -		$orderBy = $this->buildProductOrderBy();
    -
    -		if ($minmax && !(strpos($orderBy, "p.product_price ASC") !== false || strpos($orderBy, "p.product_price DESC") !== false))
    -		{
    -			$orderBy = "p.product_price ASC";
    -		}
    -
    -		$query = $db->getQuery(true);
    -
    -		$manufacturerId = $this->getState('manufacturer_id');
    -		$endlimit       = $this->getState('list.limit');
    -		$limitstart     = $this->getState('list.start');
    -		$sort           = "";
    -
    -		// Shopper group - choose from manufactures Start
    -		$shopperGroupManufactures = RedshopHelperShopper_Group::getShopperGroupManufacturers();
    -
    -		if ($shopperGroupManufactures != "")
    -		{
    -			$shopperGroupManufactures = explode(',', $shopperGroupManufactures);
    -			$shopperGroupManufactures = \Joomla\Utilities\ArrayHelper::toInteger($shopperGroupManufactures);
    -			$shopperGroupManufactures = implode(',', $shopperGroupManufactures);
    -			$query->where('p.manufacturer_id IN (' . $shopperGroupManufactures . ')');
    -		}
    -
    -		// Shopper group - choose from manufactures End
    -
    -		if ($manufacturerId && $manufacturerId > 0)
    -		{
    -			$query->where('p.manufacturer_id = ' . (int) $manufacturerId);
    -		}
    -
    -		$query->select('DISTINCT(p.product_id)')
    -			->from($db->qn('#__redshop_product', 'p'))
    -			->leftJoin($db->qn('#__redshop_product_category_xref', 'pc') . ' ON ' . $db->qn('pc.product_id') . ' = ' . $db->qn('p.product_id'))
    -			->where($db->qn('p.published') . ' = 1')
    -			->where($db->qn('p.expired') . ' = 0')
    -			->where($db->qn('p.product_parent_id') . ' = 0')
    -			->group($db->qn('p.product_id'))
    -			->order($orderBy);
    -
    -		$filterIncludeProductFromSubCat = $this->getState('include_sub_categories_products', false);
    -		$categories                     = array($this->_id);
    -
    -		if ($filterIncludeProductFromSubCat === true)
    -		{
    -			$tmpCategories = RedshopHelperCategory::getCategoryTree($this->_id);
    -
    -			if (!empty($tmpCategories))
    -			{
    -				foreach ($tmpCategories as $child)
    -				{
    -					$categories[] = $child->id;
    -				}
    -			}
    -		}
    -
    -		if ($this->getState('category_id') !== 0)
    -		{
    -			$query->where($db->qn('pc.category_id') . ' = ' . $db->q($this->getState('category_id')));
    -		}
    -		else
    -		{
    -		$query->where($db->qn('pc.category_id') . ' IN (' . implode(',', $categories) . ')');
    -		}
    -
    -		$finderCondition = $this->getredproductfindertags();
    -
    -		if ($finderCondition != '')
    -		{
    -			$finderCondition = str_replace("AND", "", $finderCondition);
    -			$query->where($finderCondition);
    -		}
    -
    -		RedshopHelperUtility::getDispatcher()->trigger('onQueryCategoryProduct', array(&$query, $categories));
    -
    -		// First steep get product ids
    -		if ($minmax != 0 || $isSlider)
    -		{
    -			$db->setQuery($query);
    -		}
    -		else
    -		{
    -			$db->setQuery($query, $limitstart, $endlimit);
    -		}
    -
    -		$productFilters = $this->getState('filterform');
    -
    -		if (!empty($productFilters))
    -		{
    -			$query->clear();
    -			$query = RedshopHelperCategory::buildQueryFilterProduct($this->_id, $categories, $productFilters);
    -			$db->setQuery($query, $limitstart, $endlimit);
    -		}
    -
    -		$queryCount = clone $query;
    -		$queryCount->clear('select')->clear('group')->clear('limit')
    -			->select('COUNT(DISTINCT(p.product_id))');
    -
    -		$this->_product = array();
    -
    -		$productIds = $db->loadColumn();
    -
    -		if (!empty($productIds))
    -		{
    -			// Third steep get all product relate info
    -			$query->clear()
    -				->where('p.product_id IN (' . implode(',', $productIds) . ')')
    -				->order('FIELD(p.product_id, ' . implode(',', $productIds) . ')');
    -
    -			$query = \Redshop\Product\Product::getMainProductQuery($query, $user->id)
    -				->select(
    -					array(
    -						'pc.ordering', 'c.*', 'm.*',
    -						'CONCAT_WS(' . $db->q('.') . ', p.product_id, ' . (int) $user->id . ') AS concat_id'
    -					)
    -				)
    -				->leftJoin('#__redshop_category AS c ON c.id = pc.category_id')
    -				->leftJoin('#__redshop_manufacturer AS m ON m.id = p.manufacturer_id')
    -				->where('pc.category_id IN (' . implode(',', $categories) . ')');
    -
    -			$products = $db->setQuery($query)->loadObjectList('concat_id');
    -
    -			if (!empty($products))
    -			{
    -				\Redshop\Product\Product::setProduct($products);
    -				$this->_product = array_values($products);
    -			}
    -		}
    -
    -		if (empty($this->_product))
    -		{
    -			$this->_total = 0;
    -
    -			return $this->_product;
    -		}
    -
    -		$priceSort = false;
    -		$count     = count($this->_product);
    -
    -		if (strpos($orderBy, "p.product_price ASC") !== false)
    -		{
    -			$priceSort = true;
    -
    -			for ($i = 0; $i < $count; $i++)
    -			{
    -				$productPrices = RedshopHelperProductPrice::getNetPrice($this->_product[$i]->product_id);
    -
    -				$this->_product[$i]->productPrice = $productPrices['product_price'];
    -			}
    -
    -			$this->_product = $this->columnSort($this->_product, 'productPrice', 'ASC');
    -		}
    -		elseif (strpos($orderBy, "p.product_price DESC") !== false)
    -		{
    -			$priceSort = true;
    -			$sort      = "DESC";
    -
    -			for ($i = 0; $i < $count; $i++)
    -			{
    -				$productPrices = RedshopHelperProductPrice::getNetPrice($this->_product[$i]->product_id);
    -
    -				$this->_product[$i]->productPrice = $productPrices['product_price'];
    -			}
    -
    -			$this->_product = $this->columnSort($this->_product, 'productPrice', 'DESC');
    -		}
    -
    -		if ($minmax > 0)
    -		{
    -			$min = 0;
    -
    -			if (!empty($priceSort) && !empty($this->_product))
    -			{
    -				if ($sort == "DESC")
    -				{
    -					$max = $this->_product[0]->productPrice + 100;
    -					$min = $this->_product[count($this->_product) - 1]->productPrice;
    -				}
    -				else
    -				{
    -					$min = $this->_product[0]->productPrice;
    -					$max = $this->_product[count($this->_product) - 1]->productPrice + 100;
    -				}
    -			}
    -			else
    -			{
    -				$productPrices = RedshopHelperProductPrice::getNetPrice($this->_product[0]->product_id);
    -				$min           = $productPrices['product_price'];
    -				$productPrices = RedshopHelperProductPrice::getNetPrice($this->_product[count($this->_product) - 1]->product_id);
    -				$max           = $productPrices['product_price'];
    -
    -				if ($min >= $max)
    -				{
    -					$min = $this->_product[0]->product_price;
    -					$max = $max + 100;
    -				}
    -			}
    -
    -			$this->setState('minprice', floor($min));
    -			$this->setState('maxprice', ceil($max));
    -			$this->setMaxMinProductPrice(array(floor($min), ceil($max)));
    -		}
    -		elseif ($isSlider)
    -		{
    -			$newProduct = array();
    -
    -			for ($i = 0, $cp = count($this->_product); $i < $cp; $i++)
    -			{
    -				$productPrices = RedshopHelperProductPrice::getNetPrice($this->_product[$i]->product_id);
    -
    -				$this->_product[$i]->sliderprice = $productPrices['product_price'];
    -
    -				if ($this->_product[$i]->sliderprice >= $this->minmaxArr[0] && $this->_product[$i]->sliderprice <= $this->minmaxArr[1])
    -				{
    -					$newProduct[] = $this->_product[$i];
    -				}
    -			}
    -
    -			$this->_total   = count($newProduct);
    -			$this->_product = array_slice($newProduct, $limitstart, $endlimit);
    -		}
    -		else
    -		{
    -			$db->setQuery($queryCount);
    -			$this->_total = $db->loadResult();
    -		}
    -
    -		return $this->_product;
    -	}
    -
    -	public function columnSort($unsorted, $column, $sort)
    -	{
    -		$sorted = $unsorted;
    -
    -		if ($sort == "ASC")
    -		{
    -			for ($i = 0; $i < count($sorted) - 1; $i++)
    -			{
    -				for ($j = 0; $j < count($sorted) - 1 - $i; $j++)
    -				{
    -					if ($sorted[$j]->$column > $sorted[$j + 1]->$column)
    -					{
    -						$tmp            = $sorted[$j];
    -						$sorted[$j]     = $sorted[$j + 1];
    -						$sorted[$j + 1] = $tmp;
    -					}
    -				}
    -			}
    -		}
    -		else
    -		{
    -			for ($i = 0; $i < count($sorted) - 1; $i++)
    -			{
    -				for ($j = 0; $j < count($sorted) - 1 - $i; $j++)
    -				{
    -					if ($sorted[$j]->$column < $sorted[$j + 1]->$column)
    -					{
    -						$tmp            = $sorted[$j];
    -						$sorted[$j]     = $sorted[$j + 1];
    -						$sorted[$j + 1] = $tmp;
    -					}
    -				}
    -			}
    -		}
    -
    -		return $sorted;
    -	}
    -
    -	/**
    -	 * Method get string order by of product when choose category
    -	 *
    -	 * @return  string
    -	 */
    -	public function buildProductOrderBy()
    -	{
    -		$orderBy        = RedshopHelperUtility::prepareOrderBy(Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD'));
    -		$filterOrder    = $this->getState('list.ordering', $orderBy->ordering);
    -		$filterOrderDir = $this->getState('list.direction', $orderBy->direction);
    -
    -		return JFactory::getDbo()->escape($filterOrder . ' ' . $filterOrderDir);
    -	}
    -
    -	public function getData()
    -	{
    -		$app = JFactory::getApplication();
    -		$endlimit   = $this->getState('list.limit');
    -		$limitstart = $this->getState('list.start');
    -		$layout     = $app->input->getCmd('layout');
    -		$query      = $this->_buildQuery();
    -
    -		if ($layout == "categoryproduct")
    -		{
    -			$menu        = $app->getMenu();
    -			$item        = $menu->getActive();
    -			$endlimit    = (isset($item)) ? intval($item->params->get('maxcategory')) : 0;
    -			$this->_data = $this->_getList($query, $limitstart, $endlimit);
    -
    -			return $this->_data;
    -		}
    -
    -		if ($this->_id)
    -		{
    -			$this->_data = $this->_getList($query);
    -		}
    -		else
    -		{
    -		    if (isset($this->_template[0]->template_desc)){
    -                if (strpos($this->_template[0]->template_desc, "{show_all_products_in_category}") === false && strpos($this->_template[0]->template_desc, "{pagination}") !== false)
    -                {
    -                    $this->_data = $this->_getList($query, $limitstart, $endlimit);
    +    public $_id = null;
    +
    +    public $_data = null;
    +
    +    public $_product = null;
    +
    +    public $_template = null;
    +
    +    public $_limit = null;
    +
    +    public $_slidercount = 0;
    +
    +    public $_maincat = null;
    +
    +    public $count_no_user_field = 0;
    +
    +    public $minmaxArr = array(0, 0);
    +
    +    public $_total = 0;
    +
    +    // @ToDo In feature, when class Category extends RedshopModelList, replace filter_fields in constructor
    +    public $filter_fields = array(
    +        'p.product_name',
    +        'product_name',
    +        'p.product_price',
    +        'product_price',
    +        'p.product_price',
    +        'product_price',
    +        'p.product_number',
    +        'product_number',
    +        'p.product_id',
    +        'product_id',
    +        'c.ordering',
    +        'ordering'
    +    );
    +
    +    /**
    +     * Constructor
    +     */
    +    public function __construct()
    +    {
    +        $app    = JFactory::getApplication();
    +        $input  = JFactory::getApplication()->input;
    +        $params = $app->getParams('com_redshop');
    +        $layout = $input->getCmd('layout', 'detail');
    +        $print  = $input->getCmd('print', '');
    +        $Id     = $input->getInt('cid', 0);
    +
    +        if (!$print && !$Id) {
    +            $Id = (int)$params->get('cid');
    +        }
    +
    +        // Different context depending on the view
    +        if (empty($this->context)) {
    +            $this->context = strtolower('com_redshop.category.' . $this->getName() . '.' . $layout . '.' . $Id);
    +        }
    +
    +        parent::__construct();
    +
    +        $this->setId((int)$Id);
    +    }
    +
    +    public function setId($id)
    +    {
    +        $this->_id   = $id;
    +        $this->_data = null;
    +    }
    +
    +    public function getCategorylistProduct($categoryId = 0)
    +    {
    +        $app           = JFactory::getApplication();
    +        $menu          = $app->getMenu();
    +        $item          = $menu->getActive();
    +        $limit         = (isset($item)) ? intval($item->params->get('maxproduct')) : 0;
    +        $db            = $this->getDbo();
    +        $orderBySelect = (isset($item)) ? $item->params->get('order_by', 'p.product_name ASC') : 'p.product_name ASC';
    +        $orderByMethod = $app->getUserStateFromRequest($this->context . '.order_by', 'order_by', $orderBySelect);
    +        $orderBy       = RedshopHelperUtility::prepareOrderBy($orderByMethod);
    +
    +        $query = $db->getQuery(true)
    +            ->select('*')
    +            ->from($db->qn('#__redshop_product', 'p'))
    +            ->leftjoin(
    +                $db->qn('#__redshop_product_category_xref', 'pc') . ' ON ' . $db->qn('pc.product_id') . ' = ' . $db->qn(
    +                    'p.product_id'
    +                )
    +            )
    +            ->leftjoin(
    +                $db->qn('#__redshop_category', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('pc.category_id')
    +            )
    +            ->leftjoin(
    +                $db->qn('#__redshop_manufacturer', 'm') . ' ON ' . $db->qn('m.id') . ' = ' . $db->qn(
    +                    'p.manufacturer_id'
    +                )
    +            )
    +            ->where($db->qn('p.published') . ' = 1')
    +            ->where($db->qn('p.expired') . ' = 0')
    +            ->where($db->qn('pc.category_id') . ' = ' . $db->q((int)$categoryId))
    +            ->where($db->qn('p.product_parent_id') . ' = 0')
    +            ->order($orderBy->ordering . ' ' . $orderBy->direction)
    +            ->setLimit(0, $limit);
    +
    +        $this->_product = $this->_getList($query);
    +
    +        return $this->_product;
    +    }
    +
    +    /**
    +     * Method get Product of Category
    +     *
    +     * @param   int   $minmax    default variable is 0
    +     * @param   bool  $isSlider  default variable is false
    +     *
    +     * @return mixed
    +     *
    +     * @since   2.1.0
    +     */
    +    public function getCategoryProduct($minmax = 0, $isSlider = false)
    +    {
    +        JPluginHelper::importPlugin('redshop_product');
    +
    +        $db      = JFactory::getDbo();
    +        $user    = JFactory::getUser();
    +        $orderBy = $this->buildProductOrderBy();
    +
    +        if ($minmax && !(strpos($orderBy, "p.product_price ASC") !== false || strpos(
    +                    $orderBy,
    +                    "p.product_price DESC"
    +                ) !== false)) {
    +            $orderBy = "p.product_price ASC";
    +        }
    +
    +        $query = $db->getQuery(true);
    +
    +        $manufacturerId = $this->getState('manufacturer_id');
    +        $endlimit       = $this->getState('list.limit');
    +        $limitstart     = $this->getState('list.start');
    +        $sort           = "";
    +
    +        // Shopper group - choose from manufactures Start
    +        $shopperGroupManufactures = RedshopHelperShopper_Group::getShopperGroupManufacturers();
    +
    +        if ($shopperGroupManufactures != "") {
    +            $shopperGroupManufactures = explode(',', $shopperGroupManufactures);
    +            $shopperGroupManufactures = \Joomla\Utilities\ArrayHelper::toInteger($shopperGroupManufactures);
    +            $shopperGroupManufactures = implode(',', $shopperGroupManufactures);
    +            $query->where('p.manufacturer_id IN (' . $shopperGroupManufactures . ')');
    +        }
    +
    +        // Shopper group - choose from manufactures End
    +
    +        if ($manufacturerId && $manufacturerId > 0) {
    +            $query->where('p.manufacturer_id = ' . (int)$manufacturerId);
    +        }
    +
    +        $query->select('DISTINCT(p.product_id)')
    +            ->from($db->qn('#__redshop_product', 'p'))
    +            ->leftJoin(
    +                $db->qn('#__redshop_product_category_xref', 'pc') . ' ON ' . $db->qn('pc.product_id') . ' = ' . $db->qn(
    +                    'p.product_id'
    +                )
    +            )
    +            ->where($db->qn('p.published') . ' = 1')
    +            ->where($db->qn('p.expired') . ' = 0')
    +            ->where($db->qn('p.product_parent_id') . ' = 0')
    +            ->group($db->qn('p.product_id'))
    +            ->order($orderBy);
    +
    +        $filterIncludeProductFromSubCat = $this->getState('include_sub_categories_products', false);
    +        $categories                     = array($this->_id);
    +
    +        if ($filterIncludeProductFromSubCat === true) {
    +            $tmpCategories = RedshopHelperCategory::getCategoryTree($this->_id);
    +
    +            if (!empty($tmpCategories)) {
    +                foreach ($tmpCategories as $child) {
    +                    $categories[] = $child->id;
                     }
    -                else
    -                {
    -                    if (strpos($this->_template[0]->template_desc, "{show_all_products_in_category}") !== false)
    -                    {
    -                        $this->_data = $this->_getList($query);
    +            }
    +        }
    +
    +        if ($this->getState('category_id') !== 0) {
    +            $query->where($db->qn('pc.category_id') . ' = ' . $db->q($this->getState('category_id')));
    +        } else {
    +            $query->where($db->qn('pc.category_id') . ' IN (' . implode(',', $categories) . ')');
    +        }
    +
    +        $finderCondition = $this->getredproductfindertags();
    +
    +        if ($finderCondition != '') {
    +            $finderCondition = str_replace("AND", "", $finderCondition);
    +            $query->where($finderCondition);
    +        }
    +
    +        RedshopHelperUtility::getDispatcher()->trigger('onQueryCategoryProduct', array(&$query, $categories));
    +
    +        // First steep get product ids
    +        if ($minmax != 0 || $isSlider) {
    +            $db->setQuery($query);
    +        } else {
    +            $db->setQuery($query, $limitstart, $endlimit);
    +        }
    +
    +        $productFilters = $this->getState('filterform');
    +
    +        if (!empty($productFilters)) {
    +            $query->clear();
    +            $query = RedshopHelperCategory::buildQueryFilterProduct($this->_id, $categories, $productFilters);
    +            $db->setQuery($query, $limitstart, $endlimit);
    +        }
    +
    +        $queryCount = clone $query;
    +        $queryCount->clear('select')->clear('group')->clear('limit')
    +            ->select('COUNT(DISTINCT(p.product_id))');
    +
    +        $this->_product = array();
    +
    +        $productIds = $db->loadColumn();
    +
    +        if (!empty($productIds)) {
    +            // Third steep get all product relate info
    +            $query->clear()
    +                ->where('p.product_id IN (' . implode(',', $productIds) . ')')
    +                ->order('FIELD(p.product_id, ' . implode(',', $productIds) . ')');
    +
    +            $query = \Redshop\Product\Product::getMainProductQuery($query, $user->id)
    +                ->select(
    +                    array(
    +                        'pc.ordering',
    +                        'c.*',
    +                        'm.*',
    +                        'CONCAT_WS(' . $db->q('.') . ', p.product_id, ' . (int)$user->id . ') AS concat_id'
    +                    )
    +                )
    +                ->leftJoin('#__redshop_category AS c ON c.id = pc.category_id')
    +                ->leftJoin('#__redshop_manufacturer AS m ON m.id = p.manufacturer_id')
    +                ->where('pc.category_id IN (' . implode(',', $categories) . ')');
    +
    +            $products = $db->setQuery($query)->loadObjectList('concat_id');
    +
    +            if (!empty($products)) {
    +                \Redshop\Product\Product::setProduct($products);
    +                $this->_product = array_values($products);
    +            }
    +        }
    +
    +        if (empty($this->_product)) {
    +            $this->_total = 0;
    +
    +            return $this->_product;
    +        }
    +
    +        $priceSort = false;
    +        $count     = count($this->_product);
    +
    +        if (strpos($orderBy, "p.product_price ASC") !== false) {
    +            $priceSort = true;
    +
    +            for ($i = 0; $i < $count; $i++) {
    +                $productPrices = RedshopHelperProductPrice::getNetPrice($this->_product[$i]->product_id);
    +
    +                $this->_product[$i]->productPrice = $productPrices['product_price'];
    +            }
    +
    +            $this->_product = $this->columnSort($this->_product, 'productPrice', 'ASC');
    +        } elseif (strpos($orderBy, "p.product_price DESC") !== false) {
    +            $priceSort = true;
    +            $sort      = "DESC";
    +
    +            for ($i = 0; $i < $count; $i++) {
    +                $productPrices = RedshopHelperProductPrice::getNetPrice($this->_product[$i]->product_id);
    +
    +                $this->_product[$i]->productPrice = $productPrices['product_price'];
    +            }
    +
    +            $this->_product = $this->columnSort($this->_product, 'productPrice', 'DESC');
    +        }
    +
    +        if ($minmax > 0) {
    +            $min = 0;
    +
    +            if (!empty($priceSort) && !empty($this->_product)) {
    +                if ($sort == "DESC") {
    +                    $max = $this->_product[0]->productPrice + 100;
    +                    $min = $this->_product[count($this->_product) - 1]->productPrice;
    +                } else {
    +                    $min = $this->_product[0]->productPrice;
    +                    $max = $this->_product[count($this->_product) - 1]->productPrice + 100;
    +                }
    +            } else {
    +                $productPrices = RedshopHelperProductPrice::getNetPrice($this->_product[0]->product_id);
    +                $min           = $productPrices['product_price'];
    +                $productPrices = RedshopHelperProductPrice::getNetPrice(
    +                    $this->_product[count($this->_product) - 1]->product_id
    +                );
    +                $max           = $productPrices['product_price'];
    +
    +                if ($min >= $max) {
    +                    $min = $this->_product[0]->product_price;
    +                    $max = $max + 100;
    +                }
    +            }
    +
    +            $this->setState('minprice', floor($min));
    +            $this->setState('maxprice', ceil($max));
    +            $this->setMaxMinProductPrice(array(floor($min), ceil($max)));
    +        } elseif ($isSlider) {
    +            $newProduct = array();
    +
    +            for ($i = 0, $cp = count($this->_product); $i < $cp; $i++) {
    +                $productPrices = RedshopHelperProductPrice::getNetPrice($this->_product[$i]->product_id);
    +
    +                $this->_product[$i]->sliderprice = $productPrices['product_price'];
    +
    +                if ($this->_product[$i]->sliderprice >= $this->minmaxArr[0] && $this->_product[$i]->sliderprice <= $this->minmaxArr[1]) {
    +                    $newProduct[] = $this->_product[$i];
    +                }
    +            }
    +
    +            $this->_total   = count($newProduct);
    +            $this->_product = array_slice($newProduct, $limitstart, $endlimit);
    +        } else {
    +            $db->setQuery($queryCount);
    +            $this->_total = $db->loadResult();
    +        }
    +
    +        return $this->_product;
    +    }
    +
    +    /**
    +     * Method get string order by of product when choose category
    +     *
    +     * @return  string
    +     */
    +    public function buildProductOrderBy()
    +    {
    +        $orderBy        = RedshopHelperUtility::prepareOrderBy(
    +            Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD')
    +        );
    +        $filterOrder    = $this->getState('list.ordering', $orderBy->ordering);
    +        $filterOrderDir = $this->getState('list.direction', $orderBy->direction);
    +
    +        return JFactory::getDbo()->escape($filterOrder . ' ' . $filterOrderDir);
    +    }
    +
    +    public function getredproductfindertags()
    +    {
    +        global $context;
    +
    +        $app = JFactory::getApplication();
    +
    +        $setproductfinder = RedshopHelperUtility::isRedProductFinder();
    +        $finder_condition = "";
    +
    +        if ($setproductfinder) {
    +            $query = "SELECT id FROM #__redproductfinder_filters WHERE published=1";
    +            $this->_db->setQuery($query);
    +            $rs_filters = $this->_db->loadColumn();
    +
    +            if (count($rs_filters) > 0) {
    +                $this->_is_filter_enable = true;
    +            }
    +
    +            $tag = array();
    +
    +            for ($f = 0, $fn = count($rs_filters); $f < $fn; $f++) {
    +                $tmp_tag = $app->getUserStateFromRequest(
    +                    $context . 'tag' . $rs_filters[$f],
    +                    'tag' . $rs_filters[$f],
    +                    ''
    +                );
    +
    +                if (is_array($tmp_tag)) {
    +                    $tag = $tmp_tag;
    +                } elseif ($tmp_tag != "" && $tmp_tag != "0") {
    +                    $tag[] = $tmp_tag;
    +                }
    +            }
    +
    +            $finder_condition = "";
    +
    +            if ($tag) {
    +                if (count($tag) > 1 || $tag[0] != 0) {
    +                    $finder_query = "SELECT product_id FROM #__redproductfinder_associations AS a,#__redproductfinder_association_tag AS at ";
    +                    $finder_where = array();
    +
    +                    if (count($tag) > 1) {
    +                        $i = 1;
    +
    +                        for ($t = 1, $tn = count($tag); $t < $tn; $t++) {
    +                            $finder_query   .= " LEFT JOIN #__redproductfinder_association_tag AS at" . $t . " ON at" . $t . ".association_id=at.association_id";
    +                            $finder_where[] = " at" . $t . ".tag_id = " . (int)$tag[$t] . " ";
    +                            $i++;
    +                        }
                         }
    -                    else
    -                    {
    +
    +                    $finder_query     .= " WHERE a.id = at.association_id AND at.tag_id = " . (int)$tag[0] . " ";
    +                    $finder_where_str = "";
    +
    +                    if (!empty($finder_where)) {
    +                        $finder_where_str = " AND " . implode(" AND ", $finder_where);
    +                    }
    +
    +                    $finder_query .= $finder_where_str;
    +                    $this->_db->setQuery($finder_query);
    +                    $rs              = $this->_db->loadColumn();
    +                    $finder_products = "";
    +
    +                    if (!empty($rs)) {
    +                        // Sanitise ids
    +                        $rs = \Joomla\Utilities\ArrayHelper::toInteger($rs);
    +
    +                        $finder_products = implode("','", $rs);
    +                    }
    +
    +                    $finder_condition        = " AND p.product_id IN('" . $finder_products . "')";
    +                    $this->_is_filter_enable = true;
    +                }
    +
    +                if (count($tag) == 1 && $tag[0] == 0) {
    +                    $finder_condition = "";
    +                }
    +            }
    +        }
    +
    +        return $finder_condition;
    +    }
    +
    +    public function columnSort($unsorted, $column, $sort)
    +    {
    +        $sorted = $unsorted;
    +
    +        if ($sort == "ASC") {
    +            for ($i = 0; $i < count($sorted) - 1; $i++) {
    +                for ($j = 0; $j < count($sorted) - 1 - $i; $j++) {
    +                    if ($sorted[$j]->$column > $sorted[$j + 1]->$column) {
    +                        $tmp            = $sorted[$j];
    +                        $sorted[$j]     = $sorted[$j + 1];
    +                        $sorted[$j + 1] = $tmp;
    +                    }
    +                }
    +            }
    +        } else {
    +            for ($i = 0; $i < count($sorted) - 1; $i++) {
    +                for ($j = 0; $j < count($sorted) - 1 - $i; $j++) {
    +                    if ($sorted[$j]->$column < $sorted[$j + 1]->$column) {
    +                        $tmp            = $sorted[$j];
    +                        $sorted[$j]     = $sorted[$j + 1];
    +                        $sorted[$j + 1] = $tmp;
    +                    }
    +                }
    +            }
    +        }
    +
    +        return $sorted;
    +    }
    +
    +    public function setMaxMinProductPrice($minmax = array(0, 0))
    +    {
    +        $this->minmaxArr = $minmax;
    +    }
    +
    +    public function getData()
    +    {
    +        $app        = JFactory::getApplication();
    +        $endlimit   = $this->getState('list.limit');
    +        $limitstart = $this->getState('list.start');
    +        $layout     = $app->input->getCmd('layout');
    +        $query      = $this->_buildQuery();
    +
    +        if ($layout == "categoryproduct") {
    +            $menu        = $app->getMenu();
    +            $item        = $menu->getActive();
    +            $endlimit    = (isset($item)) ? intval($item->params->get('maxcategory')) : 0;
    +            $this->_data = $this->_getList($query, $limitstart, $endlimit);
    +
    +            return $this->_data;
    +        }
    +
    +        if ($this->_id) {
    +            $this->_data = $this->_getList($query);
    +        } else {
    +            if (isset($this->_template[0]->template_desc)) {
    +                if (strpos($this->_template[0]->template_desc, "{show_all_products_in_category}") === false && strpos(
    +                        $this->_template[0]->template_desc,
    +                        "{pagination}"
    +                    ) !== false) {
    +                    $this->_data = $this->_getList($query, $limitstart, $endlimit);
    +                } else {
    +                    if (strpos($this->_template[0]->template_desc, "{show_all_products_in_category}") !== false) {
    +                        $this->_data = $this->_getList($query);
    +                    } else {
                             $this->_data = $this->_getList($query, 0, Redshop::getConfig()->get('MAXCATEGORY'));
                         }
                     }
                 }
    -		}
    -
    -		return $this->_data;
    -	}
    -
    -	public function getCategoryPagination()
    -	{
    -		$endlimit          = $this->getState('list.limit');
    -		$limitstart        = $this->getState('list.start');
    -		$this->_pagination = new JPagination($this->getTotal(), $limitstart, $endlimit);
    -
    -		return $this->_pagination;
    -	}
    -
    -	public function getCategoryProductPagination()
    -	{
    -		$app = JFactory::getApplication();
    -		$menu     = $app->getMenu();
    -		$item     = $menu->getActive();
    -		$endlimit = (isset($item)) ? intval($item->params->get('maxcategory')) : 0;
    -
    -		$limitstart        = $this->getState('list.start');
    -		$this->_pagination = new JPagination($this->getTotal(), $limitstart, $endlimit);
    -
    -		return $this->_pagination;
    -	}
    -
    -	public function getTotal()
    -	{
    -		$query        = $this->_buildQuery();
    -		$this->_total = $this->_getListCount($query);
    -
    -		return $this->_total;
    -	}
    -
    -	public function getCategoryTemplate()
    -	{
    -		$category_template = $this->getState('category_template');
    -
    -		if ($this->_id)
    -		{
    -			$selected_template = $this->_maincat->template;
    -
    -			if (isset($category_template) && $category_template != '')
    -			{
    -				$selected_template .= "," . $category_template;
    -			}
    -
    -			if ($this->_maincat->more_template != "")
    -			{
    -				$selected_template .= "," . $this->_maincat->more_template;
    -			}
    -
    -			$alltemplate = RedshopHelperTemplate::getTemplate("category", $selected_template);
    -		}
    -		else
    -		{
    -			$alltemplate = RedshopHelperTemplate::getTemplate("frontpage_category");
    -		}
    -
    -		return $alltemplate;
    -	}
    -
    -	/**
    -	 * Load Category Template
    -	 *
    -	 * @param   int  $category_template  Category template id
    -	 *
    -	 * @return  array|null
    -	 */
    -	public function loadCategoryTemplate($category_template = null)
    -	{
    -		$selected_template = Redshop::getConfig()->get('DEFAULT_CATEGORYLIST_TEMPLATE');
    -		$template_section  = "frontpage_category";
    -
    -		if ($this->_id)
    -		{
    -			$template_section = "category";
    -
    -			if (!empty($category_template))
    -			{
    -				$selected_template = $category_template;
    -			}
    -			elseif (isset($this->_maincat->category_template))
    -			{
    -				$selected_template = $this->_maincat->category_template;
    -			}
    -		}
    -
    -		$this->_template = RedshopHelperTemplate::getTemplate($template_section, $selected_template);
    -
    -		return $this->_template;
    -	}
    -
    -	public function getManufacturer($mid = 0)
    -	{
    -		$cid = JFactory::getApplication()->input->getInt('cid', 0);
    -		$db  = $this->getDbo();
    -		$query = $db->getQuery(true)
    -			->select('DISTINCT (' . $db->qn('m.id') . ')')
    -			->select('m.*')
    -			->from($db->qn('#__redshop_manufacturer', 'm'))
    -			->leftjoin($db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('m.id') . ' = ' . 'p.manufacturer_id')
    -			->where($db->qn('p.manufacturer_id') . ' != 0')
    -			->where($db->qn('m.published') . ' = 1')
    -			->order($db->qn('ordering') . ' ASC');
    -
    -		if ($mid != 0)
    -		{
    -			$query->where($db->qn('m.id') . ' = ' . $db->qn((int) $mid));
    -		}
    -
    -		if ($cid != 0)
    -		{
    -			$query->leftjoin($db->qn('#__redshop_product_category_xref', 'pcx') . ' ON ' . $db->qn('p.product_id') . ' = ' . 'pcx.product_id')
    -				->where($db->qn('pcx.category_id') . ' = ' . $db->q((int) $cid));
    -		}
    -
    -		return $db->setQuery($query)->loadObjectList();
    -	}
    -
    -	public function setMaxMinProductPrice($minmax = array(0, 0))
    -	{
    -		$this->minmaxArr = $minmax;
    -	}
    -
    -	public function getMaxMinProductPrice()
    -	{
    -		return $this->minmaxArr;
    -	}
    -
    -	/**
    -	 * Function to get Product List Array with searched Letter
    -	 *
    -	 * @return array
    -	 */
    -	public function getAllproductArrayListwithfirst($letter, $fieldid)
    -	{
    -		$endlimit = $this->getState('list.limit');
    -
    -		$limitstart = $this->getState('list.start');
    -		$query      = $this->_buildfletterQuery($letter, $fieldid);
    -
    -		if (strpos($this->_template[0]->template_desc, "{pagination}") !== false)
    -		{
    -			$product_lists = $this->_getList($query, $limitstart, $endlimit);
    -		}
    -		else
    -		{
    -			$product_lists = $this->_getList($query, $limitstart, $endlimit);
    -		}
    -
    -		return $product_lists;
    -	}
    -
    -	public function _buildfletterQuery($letter, $fieldId)
    -	{
    -		$db = $this->getDbo();
    -		$query = $db->getQuery(true)
    -			->select('p.*')
    -			->select('fd.*')
    -			->from($db->qn('#__redshop_product', 'p'))
    -			->leftjoin($db->qn('#__redshop_fields_data', 'fd') . ' ON ' . $db->qn('fd.itemid') . ' = ' . $db->qn('p.product_id'))
    -			->where($db->qn('fd.txt') . ' LIKE ' . $db->q($letter . '%'))
    -			->where($db->qn('fd.fieldid') . ' = ' . $db->q((int) $fieldId))
    -			->where($db->qn('fd.section') . ' = 1')
    -			->where($db->qn('p.published') . ' = 1')
    -			->order($db->qn('p.product_name'));
    -
    -		return $query;
    -	}
    -
    -	public function getfletterPagination($letter, $fieldid)
    -	{
    -		$endlimit          = $this->getState('list.limit');
    -		$limitstart        = $this->getState('list.start');
    -		$this->_pagination = new JPagination($this->getfletterTotal($letter, $fieldid), $limitstart, $endlimit);
    -
    -		return $this->_pagination;
    -	}
    -
    -	public function getfletterTotal($letter, $fieldid)
    -	{
    -		if (empty ($this->_total))
    -		{
    -			$query        = $this->_buildfletterQuery($letter, $fieldid);
    -			$this->_total = $this->_getListCount($query);
    -		}
    -
    -		return $this->_total;
    -	}
    -
    -	public function getredproductfindertags()
    -	{
    -		global $context;
    -
    -		$app = JFactory::getApplication();
    -
    -		$setproductfinder    = RedshopHelperUtility::isRedProductFinder();
    -		$finder_condition    = "";
    -
    -		if ($setproductfinder)
    -		{
    -			$query = "SELECT id FROM #__redproductfinder_filters WHERE published=1";
    -			$this->_db->setQuery($query);
    -			$rs_filters = $this->_db->loadColumn();
    -
    -			if (count($rs_filters) > 0)
    -			{
    -				$this->_is_filter_enable = true;
    -			}
    -
    -			$tag = array();
    -
    -			for ($f = 0, $fn = count($rs_filters); $f < $fn; $f++)
    -			{
    -				$tmp_tag = $app->getUserStateFromRequest($context . 'tag' . $rs_filters[$f], 'tag' . $rs_filters[$f], '');
    -
    -				if (is_array($tmp_tag))
    -				{
    -					$tag = $tmp_tag;
    -				}
    -				elseif ($tmp_tag != "" && $tmp_tag != "0")
    -				{
    -					$tag[] = $tmp_tag;
    -				}
    -			}
    -
    -			$finder_condition = "";
    -
    -			if ($tag)
    -			{
    -				if (count($tag) > 1 || $tag[0] != 0)
    -				{
    -					$finder_query = "SELECT product_id FROM #__redproductfinder_associations AS a,#__redproductfinder_association_tag AS at ";
    -					$finder_where = array();
    -
    -					if (count($tag) > 1)
    -					{
    -						$i = 1;
    -
    -						for ($t = 1, $tn = count($tag); $t < $tn; $t++)
    -						{
    -							$finder_query .= " LEFT JOIN #__redproductfinder_association_tag AS at" . $t . " ON at" . $t . ".association_id=at.association_id";
    -							$finder_where[] = " at" . $t . ".tag_id = " . (int) $tag[$t] . " ";
    -							$i++;
    -						}
    -					}
    -
    -					$finder_query .= " WHERE a.id = at.association_id AND at.tag_id = " . (int) $tag[0] . " ";
    -					$finder_where_str = "";
    -
    -					if (!empty($finder_where))
    -					{
    -						$finder_where_str = " AND " . implode(" AND ", $finder_where);
    -					}
    -
    -					$finder_query .= $finder_where_str;
    -					$this->_db->setQuery($finder_query);
    -					$rs              = $this->_db->loadColumn();
    -					$finder_products = "";
    -
    -					if (!empty($rs))
    -					{
    -						// Sanitise ids
    -						$rs = \Joomla\Utilities\ArrayHelper::toInteger($rs);
    -
    -						$finder_products = implode("','", $rs);
    -					}
    -
    -					$finder_condition        = " AND p.product_id IN('" . $finder_products . "')";
    -					$this->_is_filter_enable = true;
    -				}
    -
    -				if (count($tag) == 1 && $tag[0] == 0)
    -				{
    -					$finder_condition = "";
    -				}
    -			}
    -		}
    -
    -		return $finder_condition;
    -	}
    +        }
    +
    +        return $this->_data;
    +    }
    +
    +    /**
    +     * Build a query
    +     *
    +     * @return  JDatabaseQuery
    +     */
    +    public function _buildQuery()
    +    {
    +        $db              = $this->getDbo();
    +        $app             = JFactory::getApplication();
    +        $menu            = $app->getMenu();
    +        $item            = $menu->getActive();
    +        $manufacturer_id = (isset($item)) ? intval($item->params->get('manufacturer_id')) : 0;
    +        $manufacturer_id = $app->input->getInt('manufacturer_id', $manufacturer_id, '', 'int');
    +        $layout          = $app->input->getCmd('layout');
    +
    +        $query = $db->getQuery(true);
    +        $query->select(
    +            array(
    +                'DISTINCT(' . $db->qn('c.id') . ')',
    +                'c.*'
    +            )
    +        )
    +            ->from($db->qn('#__redshop_category', 'c'))
    +            ->where($db->qn('c.published') . ' = 1');
    +
    +        if ($this->_id > 0) {
    +            $query->where($db->qn('c.parent_id') . ' = ' . (int)$this->_id);
    +        } else {
    +            $query->where($db->qn('c.parent_id') . ' = ' . (int)RedshopHelperCategory::getRootId());
    +        }
    +
    +        if ($layout != 'categoryproduct') {
    +            $query->order($this->_buildContentOrderBy());
    +        }
    +
    +        if ($manufacturer_id) {
    +            $query->leftJoin(
    +                $db->qn('#__redshop_product_category_xref', 'pcx') . ' ON ' . $db->qn(
    +                    'pcx.category_id'
    +                ) . ' = ' . $db->qn('c.id')
    +            )
    +                ->leftJoin(
    +                    $db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn(
    +                        'pcx.product_id'
    +                    )
    +                )
    +                ->leftJoin(
    +                    $db->qn('#__redshop_manufacturer', 'm') . ' ON ' . $db->qn('m.id') . ' = ' . $db->qn(
    +                        'p.manufacturer_id'
    +                    )
    +                )
    +                ->where($db->qn('m.id') . ' = ' . (int)$manufacturer_id)
    +                ->group($db->qn('c.id'));
    +        }
    +
    +        return $query;
    +    }
    +
    +    public function _buildContentOrderBy()
    +    {
    +        if (Redshop::getConfig()->get('DEFAULT_CATEGORY_ORDERING_METHOD')) {
    +            $orderby = Redshop::getConfig()->get('DEFAULT_CATEGORY_ORDERING_METHOD');
    +        } else {
    +            $orderby = "c.ordering";
    +        }
    +
    +        return $orderby;
    +    }
    +
    +    public function getCategoryPagination()
    +    {
    +        $endlimit          = $this->getState('list.limit');
    +        $limitstart        = $this->getState('list.start');
    +        $this->_pagination = new JPagination($this->getTotal(), $limitstart, $endlimit);
    +
    +        return $this->_pagination;
    +    }
    +
    +    public function getTotal()
    +    {
    +        $query        = $this->_buildQuery();
    +        $this->_total = $this->_getListCount($query);
    +
    +        return $this->_total;
    +    }
    +
    +    public function getCategoryProductPagination()
    +    {
    +        $app      = JFactory::getApplication();
    +        $menu     = $app->getMenu();
    +        $item     = $menu->getActive();
    +        $endlimit = (isset($item)) ? intval($item->params->get('maxcategory')) : 0;
    +
    +        $limitstart        = $this->getState('list.start');
    +        $this->_pagination = new JPagination($this->getTotal(), $limitstart, $endlimit);
    +
    +        return $this->_pagination;
    +    }
    +
    +    public function getCategoryTemplate()
    +    {
    +        $category_template = $this->getState('category_template');
    +
    +        if ($this->_id) {
    +            $selected_template = $this->_maincat->template;
    +
    +            if (isset($category_template) && $category_template != '') {
    +                $selected_template .= "," . $category_template;
    +            }
    +
    +            if ($this->_maincat->more_template != "") {
    +                $selected_template .= "," . $this->_maincat->more_template;
    +            }
    +
    +            $alltemplate = RedshopHelperTemplate::getTemplate("category", $selected_template);
    +        } else {
    +            $alltemplate = RedshopHelperTemplate::getTemplate("frontpage_category");
    +        }
    +
    +        return $alltemplate;
    +    }
    +
    +    public function getManufacturer($mid = 0)
    +    {
    +        $cid   = JFactory::getApplication()->input->getInt('cid', 0);
    +        $db    = $this->getDbo();
    +        $query = $db->getQuery(true)
    +            ->select('DISTINCT (' . $db->qn('m.id') . ')')
    +            ->select('m.*')
    +            ->from($db->qn('#__redshop_manufacturer', 'm'))
    +            ->leftjoin($db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('m.id') . ' = ' . 'p.manufacturer_id')
    +            ->where($db->qn('p.manufacturer_id') . ' != 0')
    +            ->where($db->qn('m.published') . ' = 1')
    +            ->order($db->qn('ordering') . ' ASC');
    +
    +        if ($mid != 0) {
    +            $query->where($db->qn('m.id') . ' = ' . $db->qn((int)$mid));
    +        }
    +
    +        if ($cid != 0) {
    +            $query->leftjoin(
    +                $db->qn('#__redshop_product_category_xref', 'pcx') . ' ON ' . $db->qn(
    +                    'p.product_id'
    +                ) . ' = ' . 'pcx.product_id'
    +            )
    +                ->where($db->qn('pcx.category_id') . ' = ' . $db->q((int)$cid));
    +        }
    +
    +        return $db->setQuery($query)->loadObjectList();
    +    }
    +
    +    public function getMaxMinProductPrice()
    +    {
    +        return $this->minmaxArr;
    +    }
    +
    +    /**
    +     * Function to get Product List Array with searched Letter
    +     *
    +     * @return array
    +     */
    +    public function getAllproductArrayListwithfirst($letter, $fieldid)
    +    {
    +        $endlimit = $this->getState('list.limit');
    +
    +        $limitstart = $this->getState('list.start');
    +        $query      = $this->_buildfletterQuery($letter, $fieldid);
    +
    +        if (strpos($this->_template[0]->template_desc, "{pagination}") !== false) {
    +            $product_lists = $this->_getList($query, $limitstart, $endlimit);
    +        } else {
    +            $product_lists = $this->_getList($query, $limitstart, $endlimit);
    +        }
    +
    +        return $product_lists;
    +    }
    +
    +    public function _buildfletterQuery($letter, $fieldId)
    +    {
    +        $db    = $this->getDbo();
    +        $query = $db->getQuery(true)
    +            ->select('p.*')
    +            ->select('fd.*')
    +            ->from($db->qn('#__redshop_product', 'p'))
    +            ->leftjoin(
    +                $db->qn('#__redshop_fields_data', 'fd') . ' ON ' . $db->qn('fd.itemid') . ' = ' . $db->qn(
    +                    'p.product_id'
    +                )
    +            )
    +            ->where($db->qn('fd.txt') . ' LIKE ' . $db->q($letter . '%'))
    +            ->where($db->qn('fd.fieldid') . ' = ' . $db->q((int)$fieldId))
    +            ->where($db->qn('fd.section') . ' = 1')
    +            ->where($db->qn('p.published') . ' = 1')
    +            ->order($db->qn('p.product_name'));
    +
    +        return $query;
    +    }
    +
    +    public function getfletterPagination($letter, $fieldid)
    +    {
    +        $endlimit          = $this->getState('list.limit');
    +        $limitstart        = $this->getState('list.start');
    +        $this->_pagination = new JPagination($this->getfletterTotal($letter, $fieldid), $limitstart, $endlimit);
    +
    +        return $this->_pagination;
    +    }
    +
    +    public function getfletterTotal($letter, $fieldid)
    +    {
    +        if (empty ($this->_total)) {
    +            $query        = $this->_buildfletterQuery($letter, $fieldid);
    +            $this->_total = $this->_getListCount($query);
    +        }
    +
    +        return $this->_total;
    +    }
    +
    +    /**
    +     * Method to auto-populate the model state.
    +     *
    +     * @param   string  $ordering   An optional ordering field.
    +     * @param   string  $direction  An optional direction (asc|desc).
    +     *
    +     * @return  void
    +     *
    +     * @note    Calling getState in this method will result in recursion.
    +     */
    +    protected function populateState($ordering = '', $direction = '')
    +    {
    +        $app              = JFactory::getApplication();
    +        $params           = $app->getParams('com_redshop');
    +        $selectedTemplate = Redshop::getConfig()->get('DEFAULT_CATEGORYLIST_TEMPLATE');
    +        $layout           = $app->input->getCmd('layout', 'detail');
    +
    +        if ($this->_id) {
    +            $selectedTemplate = (int)$params->get('category_template', 0);
    +            $mainCat          = $this->_loadCategory();
    +
    +            if (!$selectedTemplate && isset($mainCat->template)) {
    +                $selectedTemplate = $mainCat->template;
    +            }
    +        }
    +
    +        $categoryTemplate = $app->getUserStateFromRequest(
    +            $this->context . '.category_template',
    +            'category_template',
    +            $selectedTemplate,
    +            'int'
    +        );
    +        $this->setState('category_template', $categoryTemplate);
    +
    +        $filterData = $app->getUserStateFromRequest($this->context . '.filter_data', 'filterform', '', 'array');
    +        $this->setState('filterform', $filterData);
    +
    +        if ($_POST) {
    +            $manufacturerId = $app->input->post->getInt('manufacturer_id', 0);
    +
    +            if ($manufacturerId != $app->getUserState(
    +                    $this->context . '.manufacturer_id',
    +                    $app->input->get->getInt('manufacturer_id', 0)
    +                )) {
    +                $app->redirect(
    +                    JRoute::_(
    +                        'index.php?option=com_redshop&view=category&layout=' . $layout . '&cid=' . $this->_id . '&manufacturer_id=' . $manufacturerId
    +                        . '&Itemid=' . $app->input->getInt('Itemid', 0),
    +                        true
    +                    )
    +                );
    +            }
    +        } else {
    +            $manufacturerId = $app->input->getInt('manufacturer_id', 0);
    +            $app->setUserState($this->context . '.manufacturer_id', $manufacturerId);
    +        }
    +
    +        $categoryId = $app->input->post->getInt('category_id', 0);
    +        $this->setState('category_id', $categoryId);
    +        $this->setState('manufacturer_id', $manufacturerId);
    +
    +        // Get default ordering
    +        $orderBySelect = $params->get('order_by', Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD'));
    +        $editTimestamp = $params->get('editTimestamp', 0);
    +        $userTimestamp = $app->getUserState($this->context . '.editTimestamp', 0);
    +
    +        if ($editTimestamp > $userTimestamp) {
    +            $app->setUserState($this->context . '.order_by', $orderBySelect);
    +        }
    +
    +        $app->setUserState($this->context . '.editTimestamp', time());
    +
    +        $orderByMethod = $app->getUserStateFromRequest($this->context . '.order_by', 'order_by', $orderBySelect);
    +        $orderBy       = RedshopHelperUtility::prepareOrderBy($orderByMethod);
    +
    +        $this->setState('list.ordering', $orderBy->ordering);
    +        $this->setState('list.direction', $orderBy->direction);
    +
    +        $this->loadCategoryTemplate($categoryTemplate);
    +
    +        if (isset($this->_template[0]->template_desc)
    +            && strstr($this->_template[0]->template_desc, "{show_all_products_in_category}")) {
    +            $limit = 0;
    +        } elseif (isset($this->_template[0]->template_desc)
    +            && strpos($this->_template[0]->template_desc, "{show_all_products_in_category}") === false
    +            && strpos($this->_template[0]->template_desc, "{pagination}") !== false
    +            && strpos($this->_template[0]->template_desc, "perpagelimit:") !== false) {
    +            $perpage = explode('{perpagelimit:', $this->_template[0]->template_desc);
    +            $perpage = explode('}', $perpage[1]);
    +            $limit   = intval($perpage[0]);
    +        } else {
    +            $limit = 0;
    +
    +            if ($this->_id) {
    +                $item = $app->getMenu()->getActive();
    +
    +                if (isset($this->_template[0]->template_desc) && strstr(
    +                        $this->_template[0]->template_desc,
    +                        "{product_display_limit}"
    +                    )) {
    +                    $limit = $app->getUserStateFromRequest($this->context . '.limit', 'limit', 0, 'int');
    +                }
    +
    +                if (!$limit && $item) {
    +                    $limit = (int)$item->params->get('maxproduct', 0);
    +                }
    +
    +                if (!$limit) {
    +                    $limit = $this->_maincat->products_per_page;
    +                }
    +            }
    +
    +            if (!$limit) {
    +                $limit = Redshop::getConfig()->get('MAXCATEGORY');
    +            }
    +        }
    +
    +        $this->setState('list.limit', $limit);
    +        $value      = $app->input->get('limitstart', 0, 'int');
    +        $limitstart = ($limit != 0 ? (floor($value / $limit) * $limit) : 0);
    +        $this->setState('list.start', $limitstart);
    +    }
    +
    +    public function _loadCategory()
    +    {
    +        $this->_maincat = RedshopHelperCategory::getCategoryById($this->_id);
    +
    +        return $this->_maincat;
    +    }
    +
    +    /**
    +     * Load Category Template
    +     *
    +     * @param   int  $category_template  Category template id
    +     *
    +     * @return  array|null
    +     */
    +    public function loadCategoryTemplate($category_template = null)
    +    {
    +        $selected_template = Redshop::getConfig()->get('DEFAULT_CATEGORYLIST_TEMPLATE');
    +        $template_section  = "frontpage_category";
    +
    +        if ($this->_id) {
    +            $template_section = "category";
    +
    +            if (!empty($category_template)) {
    +                $selected_template = $category_template;
    +            } elseif (isset($this->_maincat->category_template)) {
    +                $selected_template = $this->_maincat->category_template;
    +            }
    +        }
    +
    +        $this->_template = RedshopHelperTemplate::getTemplate($template_section, $selected_template);
    +
    +        return $this->_template;
    +    }
     }
    diff --git a/component/site/models/checkout.php b/component/site/models/checkout.php
    index 5b72f917aa3..78b033a507b 100644
    --- a/component/site/models/checkout.php
    +++ b/component/site/models/checkout.php
    @@ -9,7 +9,6 @@
     
     defined('_JEXEC') or die;
     
    -use Joomla\Registry\Registry;
     use Redshop\Economic\RedshopEconomic;
     use Redshop\Environment as RedshopEnvironment;
     
    @@ -51,18 +50,18 @@ class RedshopModelCheckout extends RedshopModel
         public function __construct()
         {
             parent::__construct();
    -        $this->_table_prefix = '#__redshop_';
    -        $session = JFactory::getSession();
    -        $this->_shippinghelper = shipping::getInstance();
    +        $this->_table_prefix    = '#__redshop_';
    +        $session                = JFactory::getSession();
    +        $this->_shippinghelper  = shipping::getInstance();
             $this->_order_functions = order_functions::getInstance();
    -        $this->_redshopMail = redshopMail::getInstance();
    +        $this->_redshopMail     = redshopMail::getInstance();
     
             $user = JFactory::getUser();
             $cart = $session->get('cart');
     
             if (!empty($cart)) {
                 if (!$cart) {
    -                $cart = array();
    +                $cart        = array();
                     $cart['idx'] = 0;
                 } elseif (isset($cart['idx']) === false) {
                     $cart['idx'] = 0;
    @@ -70,7 +69,7 @@ public function __construct()
             }
     
             $noOFGIFTCARD = 0;
    -        $idx = 0;
    +        $idx          = 0;
     
             if (isset($cart['idx'])) {
                 $idx = $cart['idx'];
    @@ -103,7 +102,7 @@ public function __construct()
         }
     
         /**
    -     * @param array $data Data for storing
    +     * @param   array  $data  Data for storing
          *
          * @return  boolean|Tableuser_detail
          *
    @@ -115,22 +114,22 @@ public function store($data)
                 return false;
             }
     
    -        $plugin = JPluginHelper::getPlugin('captcha','recaptcha');
    +        $plugin = JPluginHelper::getPlugin('captcha', 'recaptcha');
     
    -        $dataCaptcha = (string) $data;
    +        $dataCaptcha = (string)$data;
     
    -        if ($plugin)
    -        {
    -            $params  = new JRegistry($plugin->params);
    +        if ($plugin) {
    +            $params = new JRegistry($plugin->params);
     
    -            if ($params->get('version', '') === '2.0')
    -            {
    +            if ($params->get('version', '') === '2.0') {
                     $dataCaptcha = null;
                 }
             }
     
             // Disable check captcha if in One Step Checkout mode.
    -        if (!Redshop::getConfig()->get('ONESTEP_CHECKOUT_ENABLE') && !Redshop\Helper\Utility::checkCaptcha($dataCaptcha)) {
    +        if (!Redshop::getConfig()->get('ONESTEP_CHECKOUT_ENABLE') && !Redshop\Helper\Utility::checkCaptcha(
    +                $dataCaptcha
    +            )) {
                 return false;
             }
     
    @@ -138,38 +137,38 @@ public function store($data)
         }
     
         /**
    -     * @param array $data Array of data
    +     * @param   array           $data        Array of data
    +     * @param   object|boolean  $joomlaUser  Joomla! user objecet
          *
    -     * @return  boolean|JUser|stdClass
    +     * @return  boolean|Tableuser_detail
          *
          * @throws  Exception
          * @since   2.1.0
          */
    -    protected function storeJoomlaUser($data)
    +    protected function storeRedshopUser($data, $joomlaUser)
         {
    -        if (isset($data['user_id']) && $data['user_id']) {
    -            return RedshopHelperJoomla::updateJoomlaUser($data);
    +        if (!$joomlaUser) {
    +            return false;
             }
     
    -        return RedshopHelperJoomla::createJoomlaUser($data);
    +        return RedshopHelperUser::storeRedshopUser($data, $joomlaUser->id);
         }
     
         /**
    -     * @param array $data Array of data
    -     * @param object|boolean $joomlaUser Joomla! user objecet
    +     * @param   array  $data  Array of data
          *
    -     * @return  boolean|Tableuser_detail
    +     * @return  boolean|JUser|stdClass
          *
          * @throws  Exception
          * @since   2.1.0
          */
    -    protected function storeRedshopUser($data, $joomlaUser)
    +    protected function storeJoomlaUser($data)
         {
    -        if (!$joomlaUser) {
    -            return false;
    +        if (isset($data['user_id']) && $data['user_id']) {
    +            return RedshopHelperJoomla::updateJoomlaUser($data);
             }
     
    -        return RedshopHelperUser::storeRedshopUser($data, $joomlaUser->id);
    +        return RedshopHelperJoomla::createJoomlaUser($data);
         }
     
         /**
    @@ -179,15 +178,15 @@ protected function storeRedshopUser($data, $joomlaUser)
          */
         public function orderplace()
         {
    -        $app = JFactory::getApplication();
    -        $input = $app->input;
    -        $post = $input->post->getArray();
    -        $Itemid = $input->post->getInt('Itemid', 0);
    -        $shop_id = $input->post->getString('shop_id', "");
    -        $gls_zipcode = $input->post->getString('gls_zipcode', "");
    -        $gls_mobile = $input->post->getString('gls_mobile', "");
    +        $app              = JFactory::getApplication();
    +        $input            = $app->input;
    +        $post             = $input->post->getArray();
    +        $Itemid           = $input->post->getInt('Itemid', 0);
    +        $shop_id          = $input->post->getString('shop_id', "");
    +        $gls_zipcode      = $input->post->getString('gls_zipcode', "");
    +        $gls_mobile       = $input->post->getString('gls_mobile', "");
             $customer_message = $input->post->getString('rs_customer_message_ta', "");
    -        $referral_code = $input->post->getString('txt_referral_code', "");
    +        $referral_code    = $input->post->getString('txt_referral_code', "");
     
             if ($gls_mobile) {
                 $shop_id .= '###' . $gls_mobile;
    @@ -197,10 +196,10 @@ public function orderplace()
                 $shop_id .= '###' . $gls_zipcode;
             }
     
    -        $user = JFactory::getUser();
    +        $user    = JFactory::getUser();
             $session = JFactory::getSession();
    -        $auth = $session->get('auth');
    -        $userId = $user->id;
    +        $auth    = $session->get('auth');
    +        $userId  = $user->id;
     
             if (!$user->id && $auth['users_info_id']) {
                 $userId = -$auth['users_info_id'];
    @@ -220,30 +219,36 @@ public function orderplace()
             }
     
             $orderPaymentStatus = 'Unpaid';
    -        $userInfoIds = $input->getInt('users_info_id');
    -        $shippingaddresses = $this->shipaddress($userInfoIds);
    -        $billingAddresses = $this->billingaddresses();
    +        $userInfoIds        = $input->getInt('users_info_id');
    +        $shippingaddresses  = $this->shipaddress($userInfoIds);
    +        $billingAddresses   = $this->billingaddresses();
     
             if (isset($shippingaddresses)) {
    -            $d ["shippingaddress"] = $shippingaddresses;
    -            $d ["shippingaddress"]->country_2_code = RedshopHelperWorld::getCountryCode2($d ["shippingaddress"]->country_code);
    -            $d ["shippingaddress"]->state_2_code = RedshopHelperWorld::getStateCode2($d ["shippingaddress"]->state_code);
    +            $d ["shippingaddress"]                 = $shippingaddresses;
    +            $d ["shippingaddress"]->country_2_code = RedshopHelperWorld::getCountryCode2(
    +                $d ["shippingaddress"]->country_code
    +            );
    +            $d ["shippingaddress"]->state_2_code   = RedshopHelperWorld::getStateCode2(
    +                $d ["shippingaddress"]->state_code
    +            );
     
                 $shippingaddresses->country_2_code = $d ["shippingaddress"]->country_2_code;
    -            $shippingaddresses->state_2_code = $d ["shippingaddress"]->state_2_code;
    +            $shippingaddresses->state_2_code   = $d ["shippingaddress"]->state_2_code;
             }
     
             if (isset($billingAddresses)) {
                 $d["billingaddress"] = $billingAddresses;
     
                 if (isset($billingAddresses->country_code)) {
    -                $d["billingaddress"]->country_2_code = RedshopHelperWorld::getCountryCode2($billingAddresses->country_code);
    -                $billingAddresses->country_2_code = $d["billingaddress"]->country_2_code;
    +                $d["billingaddress"]->country_2_code = RedshopHelperWorld::getCountryCode2(
    +                    $billingAddresses->country_code
    +                );
    +                $billingAddresses->country_2_code    = $d["billingaddress"]->country_2_code;
                 }
     
                 if (isset($billingAddresses->state_code)) {
                     $d["billingaddress"]->state_2_code = RedshopHelperWorld::getStateCode2($billingAddresses->state_code);
    -                $billingAddresses->state_2_code = $d["billingaddress"]->state_2_code;
    +                $billingAddresses->state_2_code    = $d["billingaddress"]->state_2_code;
                 }
             }
     
    @@ -263,8 +268,8 @@ public function orderplace()
             $payment_method_id = $input->post->getString('payment_method_id', "");
     
             if ($shipping_rate_id && $cart['free_shipping'] != 1) {
    -            $shipArr = $this->calculateShipping($shipping_rate_id);
    -            $cart['shipping'] = $shipArr['order_shipping_rate'];
    +            $shipArr              = $this->calculateShipping($shipping_rate_id);
    +            $cart['shipping']     = $shipArr['order_shipping_rate'];
                 $cart['shipping_vat'] = $shipArr['shipping_vat'];
             }
     
    @@ -278,25 +283,25 @@ public function orderplace()
             $paymentMethod->params = new JRegistry($paymentMethod->params);
     
             // Prepare payment Information Object for calculations
    -        $paymentInfo = new stdclass;
    -        $paymentInfo->payment_price = $paymentMethod->params->get('payment_price', '');
    -        $paymentInfo->payment_oprand = $paymentMethod->params->get('payment_oprand', '');
    +        $paymentInfo                              = new stdclass;
    +        $paymentInfo->payment_price               = $paymentMethod->params->get('payment_price', '');
    +        $paymentInfo->payment_oprand              = $paymentMethod->params->get('payment_oprand', '');
             $paymentInfo->payment_discount_is_percent = $paymentMethod->params->get('payment_discount_is_percent', '');
    -        $paymentAmount = $cart ['total'];
    +        $paymentAmount                            = $cart ['total'];
     
             if (Redshop::getConfig()->get('PAYMENT_CALCULATION_ON') == 'subtotal') {
                 $paymentAmount = $cart ['product_subtotal'];
             }
     
    -        $paymentArray = RedshopHelperPayment::calculate($paymentAmount, $paymentInfo, $cart['total']);
    +        $paymentArray  = RedshopHelperPayment::calculate($paymentAmount, $paymentInfo, $cart['total']);
             $cart['total'] = $paymentArray[0];
             \Redshop\Cart\Helper::setCart($cart);
     
             $order_shipping = Redshop\Shipping\Rate::decrypt($shipping_rate_id);
    -        $order_status = 'P';
    +        $order_status   = 'P';
             $order_subtotal = $cart ['product_subtotal'];
    -        $cdiscount = $cart ['coupon_discount'];
    -        $order_tax = $cart ['tax'];
    +        $cdiscount      = $cart ['coupon_discount'];
    +        $order_tax      = $cart ['tax'];
             $d['order_tax'] = $order_tax;
     
             $dispatcher = RedshopHelperUtility::getDispatcher();
    @@ -311,12 +316,12 @@ public function orderplace()
                 $tax_after_discount = $cart ['tax_after_discount'];
             }
     
    -        $odiscount = $cart['coupon_discount'] + $cart['voucher_discount'] + $cart['cart_discount'];
    +        $odiscount     = $cart['coupon_discount'] + $cart['voucher_discount'] + $cart['cart_discount'];
             $odiscount_vat = $cart['discount_vat'];
     
             $d["order_payment_trans_id"] = '';
    -        $d['discount'] = $odiscount;
    -        $order_total = $cart['total'];
    +        $d['discount']               = $odiscount;
    +        $order_total                 = $cart['total'];
     
             if ($isSplit) {
                 $order_total = $order_total / 2;
    @@ -330,7 +335,7 @@ public function orderplace()
             $isBankTransferPaymentType = RedshopHelperPayment::isPaymentType($paymentMethod->element);
     
             if ($isBankTransferPaymentType || $paymentMethod->element == "rs_payment_eantransfer") {
    -            $order_status = $paymentMethod->params->get('verify_status', '');
    +            $order_status       = $paymentMethod->params->get('verify_status', '');
                 $orderPaymentStatus = trim("Unpaid");
             }
     
    @@ -349,9 +354,9 @@ public function orderplace()
             }
     
             $economic_payment_terms_id = $paymentMethod->params->get('economic_payment_terms_id');
    -        $economic_design_layout = $paymentMethod->params->get('economic_design_layout');
    -        $is_creditcard = $paymentMethod->params->get('is_creditcard', '');
    -        $is_redirected = $paymentMethod->params->get('is_redirected', 0);
    +        $economic_design_layout    = $paymentMethod->params->get('economic_design_layout');
    +        $is_creditcard             = $paymentMethod->params->get('is_creditcard', '');
    +        $is_redirected             = $paymentMethod->params->get('is_redirected', 0);
     
             $input->set('payment_status', $orderPaymentStatus);
     
    @@ -368,21 +373,24 @@ public function orderplace()
                 JPluginHelper::importPlugin('redshop_payment');
     
                 $values['order_shipping'] = $d['order_shipping'];
    -            $values['order_number'] = $order_number;
    -            $values['order_tax'] = $d['order_tax'];
    -            $values['shippinginfo'] = $d['shippingaddress'];
    -            $values['billinginfo'] = $d['billingaddress'];
    -            $values['order_total'] = $order_total;
    +            $values['order_number']   = $order_number;
    +            $values['order_tax']      = $d['order_tax'];
    +            $values['shippinginfo']   = $d['shippingaddress'];
    +            $values['billinginfo']    = $d['billingaddress'];
    +            $values['order_total']    = $order_total;
                 $values['order_subtotal'] = $order_subtotal;
    -            $values["order_id"] = $app->input->get('order_id', 0);
    +            $values["order_id"]       = $app->input->get('order_id', 0);
                 $values['payment_plugin'] = $paymentMethod->element;
    -            $values['odiscount'] = $odiscount;
    -            $paymentResponses = $dispatcher->trigger('onPrePayment_' . $values['payment_plugin'], array($values['payment_plugin'], $values));
    -            $paymentResponse = $paymentResponses[0];
    +            $values['odiscount']      = $odiscount;
    +            $paymentResponses         = $dispatcher->trigger(
    +                'onPrePayment_' . $values['payment_plugin'],
    +                array($values['payment_plugin'], $values)
    +            );
    +            $paymentResponse          = $paymentResponses[0];
     
                 if ($paymentResponse->responsestatus == "Success") {
                     $d ["order_payment_trans_id"] = $paymentResponse->transaction_id;
    -                $order_status_log = $paymentResponse->message;
    +                $order_status_log             = $paymentResponse->message;
     
                     if (!isset($paymentResponse->status)) {
                         $paymentResponse->status = 'C';
    @@ -428,54 +436,54 @@ public function orderplace()
             // Start code to track duplicate order number checking
             $order_number = RedshopHelperOrder::generateOrderNumber();
     
    -        $random_gen_enc_key = \Redshop\Crypto\Helper\Encrypt::generateCustomRandomEncryptKey(35);
    -        $userInfoIds = $billingAddresses->users_info_id;
    -        $row->user_id = $userId;
    -        $row->order_number = $order_number;
    -        $row->user_info_id = $userInfoIds;
    -        $row->order_total = $order_total;
    -        $row->order_subtotal = $order_subtotal;
    -        $row->order_tax = $order_tax;
    +        $random_gen_enc_key      = \Redshop\Crypto\Helper\Encrypt::generateCustomRandomEncryptKey(35);
    +        $userInfoIds             = $billingAddresses->users_info_id;
    +        $row->user_id            = $userId;
    +        $row->order_number       = $order_number;
    +        $row->user_info_id       = $userInfoIds;
    +        $row->order_total        = $order_total;
    +        $row->order_subtotal     = $order_subtotal;
    +        $row->order_tax          = $order_tax;
             $row->tax_after_discount = $tax_after_discount;
    -        $row->order_tax_details = '';
    -        $row->analytics_status = 0;
    -        $row->order_shipping = $order_shipping [3];
    +        $row->order_tax_details  = '';
    +        $row->analytics_status   = 0;
    +        $row->order_shipping     = $order_shipping [3];
             $row->order_shipping_tax = $shippingVatRate;
    -        $row->coupon_discount = $cdiscount;
    -        $row->shop_id = $shop_id;
    -        $row->customer_message = $customer_message;
    -        $row->referral_code = $referral_code;
    -        $db = JFactory::getDbo();
    +        $row->coupon_discount    = $cdiscount;
    +        $row->shop_id            = $shop_id;
    +        $row->customer_message   = $customer_message;
    +        $row->referral_code      = $referral_code;
    +        $db                      = JFactory::getDbo();
     
             if ($order_total <= 0) {
    -            $order_status = $paymentMethod->params->get('verify_status', '');
    +            $order_status       = $paymentMethod->params->get('verify_status', '');
                 $orderPaymentStatus = 'Paid';
             }
     
             if (Redshop::getConfig()->get('USE_AS_CATALOG')) {
    -            $order_status = 'P';
    +            $order_status       = 'P';
                 $orderPaymentStatus = 'Unpaid';
             }
     
             $dispatcher->trigger('onOrderStatusChange', array($post, &$order_status));
     
             // For barcode generation
    -        $row->order_discount = $odiscount;
    -        $row->order_discount_vat = $odiscount_vat;
    -        $row->payment_discount = $payment_amount;
    -        $row->payment_oprand = $payment_oprand;
    -        $row->order_status = $order_status;
    +        $row->order_discount       = $odiscount;
    +        $row->order_discount_vat   = $odiscount_vat;
    +        $row->payment_discount     = $payment_amount;
    +        $row->payment_oprand       = $payment_oprand;
    +        $row->order_status         = $order_status;
             $row->order_payment_status = $orderPaymentStatus;
    -        $row->cdate = $timestamp;
    -        $row->mdate = $timestamp;
    -        $row->ship_method_id = $shipping_rate_id;
    -        $row->customer_note = $post['customer_note'];
    -        $row->requisition_number = $post['requisition_number'];
    -        $row->ip_address = $ip;
    -        $row->encr_key = $random_gen_enc_key;
    -        $row->discount_type = $this->discount_type;
    -        $row->order_id = $app->input->getInt('order_id', 0);
    -        $row->barcode = null;
    +        $row->cdate                = $timestamp;
    +        $row->mdate                = $timestamp;
    +        $row->ship_method_id       = $shipping_rate_id;
    +        $row->customer_note        = $post['customer_note'];
    +        $row->requisition_number   = $post['requisition_number'];
    +        $row->ip_address           = $ip;
    +        $row->encr_key             = $random_gen_enc_key;
    +        $row->discount_type        = $this->discount_type;
    +        $row->order_id             = $app->input->getInt('order_id', 0);
    +        $row->barcode              = null;
     
             if (!$row->store()) {
                 /** @scrutinizer ignore-deprecated */
    @@ -503,15 +511,19 @@ public function orderplace()
     
             $query = $db->getQuery(true);
             $query->update($db->qn('#__redshop_orders'))
    -            ->set([
    -                $db->qn('discount_type') . ' = ' . $db->q($this->discount_type)
    -            ])
    +            ->set(
    +                [
    +                    $db->qn('discount_type') . ' = ' . $db->q($this->discount_type)
    +                ]
    +            )
                 ->where($db->qn('order_id') . ' = ' . $db->q((int)$orderId));
     
             $db->setQuery($query);
             $db->execute();
     
    -        if (Redshop::getConfig()->get('SHOW_TERMS_AND_CONDITIONS') == 1 && isset($post['termscondition']) && $post['termscondition'] == 1) {
    +        if (Redshop::getConfig()->get(
    +                'SHOW_TERMS_AND_CONDITIONS'
    +            ) == 1 && isset($post['termscondition']) && $post['termscondition'] == 1) {
                 RedshopHelperUser::updateUserTermsCondition($userInfoIds, 1);
             }
     
    @@ -523,10 +535,10 @@ public function orderplace()
             $session->set('order_id', $orderId);
     
             // Add order status log
    -        $rowOrderStatus = $this->getTable('order_status_log');
    -        $rowOrderStatus->order_id = $orderId;
    -        $rowOrderStatus->order_status = $order_status;
    -        $rowOrderStatus->date_changed = time();
    +        $rowOrderStatus                = $this->getTable('order_status_log');
    +        $rowOrderStatus->order_id      = $orderId;
    +        $rowOrderStatus->order_status  = $order_status;
    +        $rowOrderStatus->date_changed  = time();
             $rowOrderStatus->customer_note = $order_status_log;
             $rowOrderStatus->store();
     
    @@ -544,8 +556,8 @@ public function orderplace()
     
             for ($i = 0; $i < $idx; $i++) {
                 $isGiftCard = 0;
    -            $productId = $cart [$i] ['product_id'];
    -            $product = \Redshop\Product\Product::getProductById($productId);
    +            $productId  = $cart [$i] ['product_id'];
    +            $product    = \Redshop\Product\Product::getProductById($productId);
     
                 /** @var Tableorder_item_detail $rowItem */
                 $rowItem = $this->getTable('order_item_detail');
    @@ -565,10 +577,13 @@ public function orderplace()
     
                 // Product stockroom update
                 if (!$isGiftCard) {
    -                $updateStock = RedshopHelperStockroom::updateStockroomQuantity($productId, $cart [$i] ['quantity']);
    -                $stockroom_id_list = $updateStock['stockroom_list'];
    -                $stockroom_quantity_list = $updateStock['stockroom_quantity_list'];
    -                $rowItem->stockroom_id = $stockroom_id_list;
    +                $updateStock                 = RedshopHelperStockroom::updateStockroomQuantity(
    +                    $productId,
    +                    $cart [$i] ['quantity']
    +                );
    +                $stockroom_id_list           = $updateStock['stockroom_list'];
    +                $stockroom_quantity_list     = $updateStock['stockroom_quantity_list'];
    +                $rowItem->stockroom_id       = $stockroom_id_list;
                     $rowItem->stockroom_quantity = $stockroom_quantity_list;
                 }
     
    @@ -576,10 +591,12 @@ public function orderplace()
     
                 $values = explode('product_attributes/', $cart[$i]['hidden_attribute_cartimage']);
     
    -            if (!empty($cart[$i]['attributeImage']) && file_exists(JPATH_ROOT . '/components/com_redshop/assets/images/mergeImages/' . $cart[$i]['attributeImage'])) {
    +            if (!empty($cart[$i]['attributeImage']) && file_exists(
    +                    JPATH_ROOT . '/components/com_redshop/assets/images/mergeImages/' . $cart[$i]['attributeImage']
    +                )) {
                     $rowItem->attribute_image = $orderId . $cart[$i]['attributeImage'];
    -                $oldMedia = JPATH_ROOT . '/components/com_redshop/assets/images/mergeImages/' . $cart[$i]['attributeImage'];
    -                $newMedia = JPATH_ROOT . '/components/com_redshop/assets/images/orderMergeImages/' . $rowItem->attribute_image;
    +                $oldMedia                 = JPATH_ROOT . '/components/com_redshop/assets/images/mergeImages/' . $cart[$i]['attributeImage'];
    +                $newMedia                 = JPATH_ROOT . '/components/com_redshop/assets/images/orderMergeImages/' . $rowItem->attribute_image;
                     copy($oldMedia, $newMedia);
                 } elseif (!empty($values[1])) {
                     $rowItem->attribute_image = $values[1];
    @@ -592,26 +609,33 @@ public function orderplace()
                 }
     
                 if ($isGiftCard == 1) {
    -                $giftCardData = RedshopEntityGiftcard::getInstance($cart[$i]['giftcard_id'])->getItem();
    -                $rowItem->product_id = $cart [$i] ['giftcard_id'];
    -                $rowItem->order_item_name = $giftCardData->giftcard_name;
    +                $giftCardData                    = RedshopEntityGiftcard::getInstance(
    +                    $cart[$i]['giftcard_id']
    +                )->getItem();
    +                $rowItem->product_id             = $cart [$i] ['giftcard_id'];
    +                $rowItem->order_item_name        = $giftCardData->giftcard_name;
                     $rowItem->product_item_old_price = $cart[$i]['product_price'];
                 } else {
    -                $rowItem->product_id = $productId;
    +                $rowItem->product_id             = $productId;
                     $rowItem->product_item_old_price = $cart[$i]['product_old_price'];
    -                $rowItem->supplier_id = $product->manufacturer_id;
    -                $rowItem->order_item_sku = $product->product_number;
    -                $rowItem->order_item_name = $product->product_name;
    +                $rowItem->supplier_id            = $product->manufacturer_id;
    +                $rowItem->order_item_sku         = $product->product_number;
    +                $rowItem->order_item_name        = $product->product_name;
                 }
     
    -            $rowItem->product_item_price = $cart[$i]['product_price'];
    -            $rowItem->product_quantity = $cart[$i]['quantity'];
    +            $rowItem->product_item_price          = $cart[$i]['product_price'];
    +            $rowItem->product_quantity            = $cart[$i]['quantity'];
                 $rowItem->product_item_price_excl_vat = $cart[$i]['product_price_excl_vat'];
    -            $rowItem->product_final_price = ($cart[$i]['product_price'] * $cart[$i]['quantity']);
    -            $rowItem->is_giftcard = $isGiftCard;
    -
    -            $retAttArr = RedshopHelperProduct::makeAttributeCart($cart[$i]['cart_attribute'], $productId,
    -                0, 0, $cart[$i]['quantity']);
    +            $rowItem->product_final_price         = ($cart[$i]['product_price'] * $cart[$i]['quantity']);
    +            $rowItem->is_giftcard                 = $isGiftCard;
    +
    +            $retAttArr     = RedshopHelperProduct::makeAttributeCart(
    +                $cart[$i]['cart_attribute'],
    +                $productId,
    +                0,
    +                0,
    +                $cart[$i]['quantity']
    +            );
                 $cartAttribute = $retAttArr[0];
     
                 // For discount calc data
    @@ -621,18 +645,21 @@ public function orderplace()
                     $cartCalcData = $cart[$i]['discount_calc_output'];
                 }
     
    -            $retAccArr = RedshopHelperProduct::makeAccessoryCart($cart[$i]['cart_accessory'], $productId);
    -            $cartAccessory = $retAccArr[0];
    -            $rowItem->order_id = $orderId;
    -            $rowItem->user_info_id = $userInfoIds;
    +            $retAccArr                    = RedshopHelperProduct::makeAccessoryCart(
    +                $cart[$i]['cart_accessory'],
    +                $productId
    +            );
    +            $cartAccessory                = $retAccArr[0];
    +            $rowItem->order_id            = $orderId;
    +            $rowItem->user_info_id        = $userInfoIds;
                 $rowItem->order_item_currency = Redshop::getConfig()->get('REDCURRENCY_SYMBOL');
    -            $rowItem->order_status = $order_status;
    -            $rowItem->cdate = $timestamp;
    -            $rowItem->mdate = $timestamp;
    -            $rowItem->product_attribute = $cartAttribute;
    -            $rowItem->discount_calc_data = $cartCalcData;
    -            $rowItem->product_accessory = $cartAccessory;
    -            $rowItem->wrapper_price = $wrapperPrice;
    +            $rowItem->order_status        = $order_status;
    +            $rowItem->cdate               = $timestamp;
    +            $rowItem->mdate               = $timestamp;
    +            $rowItem->product_attribute   = $cartAttribute;
    +            $rowItem->discount_calc_data  = $cartCalcData;
    +            $rowItem->product_accessory   = $cartAccessory;
    +            $rowItem->wrapper_price       = $wrapperPrice;
     
                 if (!empty($cart[$i]['wrapper_id'])) {
                     $rowItem->wrapper_id = $cart[$i]['wrapper_id'];
    @@ -651,7 +678,13 @@ public function orderplace()
     
                     for ($j = 0, $jn = count($mediaName); $j < $jn; $j++) {
                         $product_serial_number = RedshopHelperProduct::getProdcutSerialNumber($rowItem->product_id);
    -                    RedshopHelperProduct::insertProductDownload($rowItem->product_id, $user->id, $rowItem->order_id, $mediaName[$j]->media_name, $product_serial_number->serial_number);
    +                    RedshopHelperProduct::insertProductDownload(
    +                        $rowItem->product_id,
    +                        $user->id,
    +                        $rowItem->order_id,
    +                        $mediaName[$j]->media_name,
    +                        $product_serial_number->serial_number
    +                    );
                     }
                 }
     
    @@ -681,46 +714,48 @@ public function orderplace()
     
                 // My accessory save in table start
                 if (count($cart [$i] ['cart_accessory']) > 0) {
    -                $setPropEqual = true;
    +                $setPropEqual    = true;
                     $setSubpropEqual = true;
    -                $attArr = $cart [$i] ['cart_accessory'];
    +                $attArr          = $cart [$i] ['cart_accessory'];
     
                     for ($a = 0, $an = count($attArr); $a < $an; $a++) {
                         $accessory_vat_price = 0;
                         $accessory_attribute = "";
     
    -                    $accessoryId = $attArr[$a]['accessory_id'];
    -                    $accessory_name = $attArr[$a]['accessory_name'];
    -                    $accessory_price = $attArr[$a]['accessory_price'];
    -                    $accessory_quantity = $attArr[$a]['accessory_quantity'];
    +                    $accessoryId         = $attArr[$a]['accessory_id'];
    +                    $accessory_name      = $attArr[$a]['accessory_name'];
    +                    $accessory_price     = $attArr[$a]['accessory_price'];
    +                    $accessory_quantity  = $attArr[$a]['accessory_quantity'];
                         $accessory_org_price = $accessory_price;
     
                         if ($accessory_price > 0) {
    -                        $accessory_vat_price = RedshopHelperProduct::getProductTax($rowItem->product_id, $accessory_price);
    +                        $accessory_vat_price = RedshopHelperProduct::getProductTax(
    +                            $rowItem->product_id,
    +                            $accessory_price
    +                        );
                         }
     
                         $attchildArr = $attArr[$a]['accessory_childs'];
     
                         for ($j = 0, $jn = count($attchildArr); $j < $jn; $j++) {
                             $prooprand = array();
    -                        $proprice = array();
    +                        $proprice  = array();
     
    -                        $propArr = $attchildArr[$j]['attribute_childs'];
    +                        $propArr       = $attchildArr[$j]['attribute_childs'];
                             $totalProperty = count($propArr);
     
                             if ($totalProperty) {
    -
    -                            $attributeId = $attchildArr[$j]['attribute_id'];
    +                            $attributeId         = $attchildArr[$j]['attribute_id'];
                                 $accessory_attribute .= urldecode($attchildArr[$j]['attribute_name']) . ":
    "; - $rowattitem = $this->getTable('order_attribute_item'); + $rowattitem = $this->getTable('order_attribute_item'); $rowattitem->order_att_item_id = 0; - $rowattitem->order_item_id = $rowItem->order_item_id; - $rowattitem->section_id = $attributeId; - $rowattitem->section = "attribute"; + $rowattitem->order_item_id = $rowItem->order_item_id; + $rowattitem->section_id = $attributeId; + $rowattitem->section = "attribute"; $rowattitem->parent_section_id = $accessoryId; - $rowattitem->section_name = $attchildArr[$j]['attribute_name']; - $rowattitem->is_accessory_att = 1; + $rowattitem->section_name = $attchildArr[$j]['attribute_name']; + $rowattitem->is_accessory_att = 1; if ($attributeId > 0) { if (!$rowattitem->store()) { @@ -734,27 +769,34 @@ public function orderplace() for ($k = 0; $k < $totalProperty; $k++) { $prooprand[$k] = $propArr[$k]['property_oprand']; - $proprice[$k] = $propArr[$k]['property_price']; - $section_vat = 0; + $proprice[$k] = $propArr[$k]['property_price']; + $section_vat = 0; if ($propArr[$k]['property_price'] > 0) { - $section_vat = RedshopHelperProduct::getProductTax($rowItem->product_id, $propArr[$k]['property_price']); + $section_vat = RedshopHelperProduct::getProductTax( + $rowItem->product_id, + $propArr[$k]['property_price'] + ); } - $propertyId = $propArr[$k]['property_id']; - $accessory_attribute .= urldecode($propArr[$k]['property_name']) . " (" . $propArr[$k]['property_oprand'] . RedshopHelperProductPrice::formattedPrice($propArr[$k]['property_price'] + $section_vat) . ")
    "; - $subpropArr = $propArr[$k]['property_childs']; - $rowattitem = $this->getTable('order_attribute_item'); + $propertyId = $propArr[$k]['property_id']; + $accessory_attribute .= urldecode( + $propArr[$k]['property_name'] + ) . " (" . $propArr[$k]['property_oprand'] . RedshopHelperProductPrice::formattedPrice( + $propArr[$k]['property_price'] + $section_vat + ) . ")
    "; + $subpropArr = $propArr[$k]['property_childs']; + $rowattitem = $this->getTable('order_attribute_item'); $rowattitem->order_att_item_id = 0; - $rowattitem->order_item_id = $rowItem->order_item_id; - $rowattitem->section_id = $propertyId; - $rowattitem->section = "property"; + $rowattitem->order_item_id = $rowItem->order_item_id; + $rowattitem->section_id = $propertyId; + $rowattitem->section = "property"; $rowattitem->parent_section_id = $attributeId; - $rowattitem->section_name = $propArr[$k]['property_name']; - $rowattitem->section_price = $propArr[$k]['property_price']; - $rowattitem->section_vat = $section_vat; - $rowattitem->section_oprand = $propArr[$k]['property_oprand']; - $rowattitem->is_accessory_att = 1; + $rowattitem->section_name = $propArr[$k]['property_name']; + $rowattitem->section_price = $propArr[$k]['property_price']; + $rowattitem->section_vat = $section_vat; + $rowattitem->section_oprand = $propArr[$k]['property_oprand']; + $rowattitem->is_accessory_att = 1; if ($propertyId > 0) { if (!$rowattitem->store()) { @@ -769,27 +811,36 @@ public function orderplace() $section_vat = 0; if ($subpropArr[$l]['subproperty_price'] > 0) { - $section_vat = RedshopHelperProduct::getProductTax($rowItem->product_id, $subpropArr[$l]['subproperty_price']); + $section_vat = RedshopHelperProduct::getProductTax( + $rowItem->product_id, + $subpropArr[$l]['subproperty_price'] + ); } - $subPropertyId = $subpropArr[$l]['subproperty_id']; - $accessory_attribute .= urldecode($subpropArr[$l]['subproperty_name']) . " (" . $subpropArr[$l]['subproperty_oprand'] . RedshopHelperProductPrice::formattedPrice($subpropArr[$l]['subproperty_price'] + $section_vat) . ")
    "; - $rowattitem = $this->getTable('order_attribute_item'); + $subPropertyId = $subpropArr[$l]['subproperty_id']; + $accessory_attribute .= urldecode( + $subpropArr[$l]['subproperty_name'] + ) . " (" . $subpropArr[$l]['subproperty_oprand'] . RedshopHelperProductPrice::formattedPrice( + $subpropArr[$l]['subproperty_price'] + $section_vat + ) . ")
    "; + $rowattitem = $this->getTable('order_attribute_item'); $rowattitem->order_att_item_id = 0; - $rowattitem->order_item_id = $rowItem->order_item_id; - $rowattitem->section_id = $subPropertyId; - $rowattitem->section = "subproperty"; + $rowattitem->order_item_id = $rowItem->order_item_id; + $rowattitem->section_id = $subPropertyId; + $rowattitem->section = "subproperty"; $rowattitem->parent_section_id = $propertyId; - $rowattitem->section_name = $subpropArr[$l]['subproperty_name']; - $rowattitem->section_price = $subpropArr[$l]['subproperty_price']; - $rowattitem->section_vat = $section_vat; - $rowattitem->section_oprand = $subpropArr[$l]['subproperty_oprand']; - $rowattitem->is_accessory_att = 1; + $rowattitem->section_name = $subpropArr[$l]['subproperty_name']; + $rowattitem->section_price = $subpropArr[$l]['subproperty_price']; + $rowattitem->section_vat = $section_vat; + $rowattitem->section_oprand = $subpropArr[$l]['subproperty_oprand']; + $rowattitem->is_accessory_att = 1; if ($subPropertyId > 0) { if (!$rowattitem->store()) { /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + $this->setError( + /** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg() + ); return false; } @@ -799,25 +850,33 @@ public function orderplace() // FOR ACCESSORY PROPERTY AND SUBPROPERTY PRICE CALCULATION if ($setPropEqual && $setSubpropEqual) { - $accessory_priceArr = RedshopHelperProduct::makeTotalPriceByOprand($accessory_price, $prooprand, $proprice); - $setPropEqual = $accessory_priceArr[0]; - $accessory_price = $accessory_priceArr[1]; + $accessory_priceArr = RedshopHelperProduct::makeTotalPriceByOprand( + $accessory_price, + $prooprand, + $proprice + ); + $setPropEqual = $accessory_priceArr[0]; + $accessory_price = $accessory_priceArr[1]; } for ($t = 0, $countProperty = count($propArr), $tn = $countProperty; $t < $tn; $t++) { - $subprooprand = array(); - $subproprice = array(); + $subprooprand = array(); + $subproprice = array(); $subElementArr = $propArr[$t]['property_childs']; for ($tp = 0, $countElement = count($subElementArr); $tp < $countElement; $tp++) { $subprooprand[$tp] = $subElementArr[$tp]['subproperty_oprand']; - $subproprice[$tp] = $subElementArr[$tp]['subproperty_price']; + $subproprice[$tp] = $subElementArr[$tp]['subproperty_price']; } if ($setPropEqual && $setSubpropEqual) { - $accessory_priceArr = RedshopHelperProduct::makeTotalPriceByOprand($accessory_price, $subprooprand, $subproprice); - $setSubpropEqual = $accessory_priceArr[0]; - $accessory_price = $accessory_priceArr[1]; + $accessory_priceArr = RedshopHelperProduct::makeTotalPriceByOprand( + $accessory_price, + $subprooprand, + $subproprice + ); + $setSubpropEqual = $accessory_priceArr[0]; + $accessory_price = $accessory_priceArr[1]; } } } @@ -828,19 +887,21 @@ public function orderplace() $accdata->load($accessoryId); } - $accProductinfo = \Redshop\Product\Product::getProductById($accdata->child_product_id); - $rowaccitem = $this->getTable('order_acc_item'); - $rowaccitem->order_item_acc_id = 0; - $rowaccitem->order_item_id = $rowItem->order_item_id; - $rowaccitem->product_id = $accessoryId; - $rowaccitem->order_acc_item_sku = $accProductinfo->product_number; - $rowaccitem->order_acc_item_name = $accessory_name; - $rowaccitem->order_acc_price = $accessory_org_price; - $rowaccitem->order_acc_vat = $accessory_vat_price; - $rowaccitem->product_quantity = $accessory_quantity; - $rowaccitem->product_acc_item_price = $accessory_price; + $accProductinfo = \Redshop\Product\Product::getProductById( + $accdata->child_product_id + ); + $rowaccitem = $this->getTable('order_acc_item'); + $rowaccitem->order_item_acc_id = 0; + $rowaccitem->order_item_id = $rowItem->order_item_id; + $rowaccitem->product_id = $accessoryId; + $rowaccitem->order_acc_item_sku = $accProductinfo->product_number; + $rowaccitem->order_acc_item_name = $accessory_name; + $rowaccitem->order_acc_price = $accessory_org_price; + $rowaccitem->order_acc_vat = $accessory_vat_price; + $rowaccitem->product_quantity = $accessory_quantity; + $rowaccitem->product_acc_item_price = $accessory_price; $rowaccitem->product_acc_final_price = ($accessory_price * $accessory_quantity); - $rowaccitem->product_attribute = $accessory_attribute; + $rowaccitem->product_attribute = $accessory_attribute; if ($accessoryId > 0) { if (!$rowaccitem->store()) { @@ -858,19 +919,19 @@ public function orderplace() $attchildArr = $cart [$i] ['cart_attribute']; for ($j = 0, $jn = count($attchildArr); $j < $jn; $j++) { - $propArr = $attchildArr[$j]['attribute_childs']; + $propArr = $attchildArr[$j]['attribute_childs']; $totalProperty = count($propArr); if ($totalProperty > 0) { - $attributeId = $attchildArr[$j]['attribute_id']; - $rowattitem = $this->getTable('order_attribute_item'); + $attributeId = $attchildArr[$j]['attribute_id']; + $rowattitem = $this->getTable('order_attribute_item'); $rowattitem->order_att_item_id = 0; - $rowattitem->order_item_id = $rowItem->order_item_id; - $rowattitem->section_id = $attributeId; - $rowattitem->section = "attribute"; + $rowattitem->order_item_id = $rowItem->order_item_id; + $rowattitem->section_id = $attributeId; + $rowattitem->section = "attribute"; $rowattitem->parent_section_id = $rowItem->product_id; - $rowattitem->section_name = $attchildArr[$j]['attribute_name']; - $rowattitem->is_accessory_att = 0; + $rowattitem->section_name = $attchildArr[$j]['attribute_name']; + $rowattitem->is_accessory_att = 0; if ($attributeId > 0) { if (!$rowattitem->store()) { @@ -885,28 +946,36 @@ public function orderplace() $section_vat = 0; if ($propArr[$k]['property_price'] > 0) { - $section_vat = RedshopHelperProduct::getProductTax($rowItem->product_id, $propArr[$k]['property_price']); + $section_vat = RedshopHelperProduct::getProductTax( + $rowItem->product_id, + $propArr[$k]['property_price'] + ); } $propertyId = $propArr[$k]['property_id']; // Product property STOCKROOM update start - $updateStock_att = RedshopHelperStockroom::updateStockroomQuantity($propertyId, $cart [$i] ['quantity'], "property", $productId); - $stockroom_att_id_list = $updateStock_att['stockroom_list']; + $updateStock_att = RedshopHelperStockroom::updateStockroomQuantity( + $propertyId, + $cart [$i] ['quantity'], + "property", + $productId + ); + $stockroom_att_id_list = $updateStock_att['stockroom_list']; $stockroom_att_quantity_list = $updateStock_att['stockroom_quantity_list']; - $rowattitem = $this->getTable('order_attribute_item'); - $rowattitem->order_att_item_id = 0; - $rowattitem->order_item_id = $rowItem->order_item_id; - $rowattitem->section_id = $propertyId; - $rowattitem->section = "property"; - $rowattitem->parent_section_id = $attributeId; - $rowattitem->section_name = $propArr[$k]['property_name']; - $rowattitem->section_price = $propArr[$k]['property_price']; - $rowattitem->section_vat = $section_vat; - $rowattitem->section_oprand = $propArr[$k]['property_oprand']; - $rowattitem->is_accessory_att = 0; - $rowattitem->stockroom_id = $stockroom_att_id_list; + $rowattitem = $this->getTable('order_attribute_item'); + $rowattitem->order_att_item_id = 0; + $rowattitem->order_item_id = $rowItem->order_item_id; + $rowattitem->section_id = $propertyId; + $rowattitem->section = "property"; + $rowattitem->parent_section_id = $attributeId; + $rowattitem->section_name = $propArr[$k]['property_name']; + $rowattitem->section_price = $propArr[$k]['property_price']; + $rowattitem->section_vat = $section_vat; + $rowattitem->section_oprand = $propArr[$k]['property_oprand']; + $rowattitem->is_accessory_att = 0; + $rowattitem->stockroom_id = $stockroom_att_id_list; $rowattitem->stockroom_quantity = $stockroom_att_quantity_list; if ($propertyId > 0) { @@ -924,34 +993,44 @@ public function orderplace() $section_vat = 0; if ($subpropArr[$l]['subproperty_price'] > 0) { - $section_vat = RedshopHelperProduct::getProductTax($rowItem->product_id, $subpropArr[$l]['subproperty_price']); + $section_vat = RedshopHelperProduct::getProductTax( + $rowItem->product_id, + $subpropArr[$l]['subproperty_price'] + ); } $subPropertyId = $subpropArr[$l]['subproperty_id']; // Product subproperty STOCKROOM update start - $updateStock_subatt = RedshopHelperStockroom::updateStockroomQuantity($subPropertyId, $cart [$i] ['quantity'], "subproperty", $productId); - $stockroom_subatt_id_list = $updateStock_subatt['stockroom_list']; + $updateStock_subatt = RedshopHelperStockroom::updateStockroomQuantity( + $subPropertyId, + $cart [$i] ['quantity'], + "subproperty", + $productId + ); + $stockroom_subatt_id_list = $updateStock_subatt['stockroom_list']; $stockroom_subatt_quantity_list = $updateStock_subatt['stockroom_quantity_list']; - $rowattitem = $this->getTable('order_attribute_item'); - $rowattitem->order_att_item_id = 0; - $rowattitem->order_item_id = $rowItem->order_item_id; - $rowattitem->section_id = $subPropertyId; - $rowattitem->section = "subproperty"; - $rowattitem->parent_section_id = $propertyId; - $rowattitem->section_name = $subpropArr[$l]['subproperty_name']; - $rowattitem->section_price = $subpropArr[$l]['subproperty_price']; - $rowattitem->section_vat = $section_vat; - $rowattitem->section_oprand = $subpropArr[$l]['subproperty_oprand']; - $rowattitem->is_accessory_att = 0; - $rowattitem->stockroom_id = $stockroom_subatt_id_list; + $rowattitem = $this->getTable('order_attribute_item'); + $rowattitem->order_att_item_id = 0; + $rowattitem->order_item_id = $rowItem->order_item_id; + $rowattitem->section_id = $subPropertyId; + $rowattitem->section = "subproperty"; + $rowattitem->parent_section_id = $propertyId; + $rowattitem->section_name = $subpropArr[$l]['subproperty_name']; + $rowattitem->section_price = $subpropArr[$l]['subproperty_price']; + $rowattitem->section_vat = $section_vat; + $rowattitem->section_oprand = $subpropArr[$l]['subproperty_oprand']; + $rowattitem->is_accessory_att = 0; + $rowattitem->stockroom_id = $stockroom_subatt_id_list; $rowattitem->stockroom_quantity = $stockroom_subatt_quantity_list; if ($subPropertyId > 0) { if (!$rowattitem->store()) { /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + $this->setError( + /** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg() + ); return false; } @@ -964,19 +1043,29 @@ public function orderplace() // Store user product subscription detail if ($product->product_type == 'subscription') { - $subscribe = $this->getTable('product_subscribe_detail'); - $subscription_detail = RedshopHelperProduct::getProductSubscriptionDetail($productId, $cart[$i]['subscription_id']); - - $add_day = $subscription_detail->period_type == 'days' ? $subscription_detail->subscription_period : 0; - $add_month = $subscription_detail->period_type == 'month' ? $subscription_detail->subscription_period : 0; - $add_year = $subscription_detail->period_type == 'year' ? $subscription_detail->subscription_period : 0; - $subscribe->order_id = $orderId; - $subscribe->order_item_id = $rowItem->order_item_id; - $subscribe->product_id = $productId; + $subscribe = $this->getTable('product_subscribe_detail'); + $subscription_detail = RedshopHelperProduct::getProductSubscriptionDetail( + $productId, + $cart[$i]['subscription_id'] + ); + + $add_day = $subscription_detail->period_type == 'days' ? $subscription_detail->subscription_period : 0; + $add_month = $subscription_detail->period_type == 'month' ? $subscription_detail->subscription_period : 0; + $add_year = $subscription_detail->period_type == 'year' ? $subscription_detail->subscription_period : 0; + $subscribe->order_id = $orderId; + $subscribe->order_item_id = $rowItem->order_item_id; + $subscribe->product_id = $productId; $subscribe->subscription_id = $cart[$i]['subscription_id']; - $subscribe->user_id = $user->id; - $subscribe->start_date = time(); - $subscribe->end_date = mktime(0, 0, 0, date('m') + $add_month, date('d') + $add_day, date('Y') + $add_year); + $subscribe->user_id = $user->id; + $subscribe->start_date = time(); + $subscribe->end_date = mktime( + 0, + 0, + 0, + date('m') + $add_month, + date('d') + $add_day, + date('Y') + $add_year + ); if (!$subscribe->store()) { /** @scrutinizer ignore-deprecated */ @@ -997,7 +1086,7 @@ public function orderplace() return false; } - $rowpayment->order_id = $orderId; + $rowpayment->order_id = $orderId; $rowpayment->payment_method_id = $payment_method_id; $creditCardData = $session->get('ccdata'); @@ -1018,18 +1107,18 @@ public function orderplace() $creditCardData['order_payment_expire_year'] = 0; } - $rowpayment->order_payment_code = $creditCardData['creditcard_code']; + $rowpayment->order_payment_code = $creditCardData['creditcard_code']; $rowpayment->order_payment_cardname = base64_encode($creditCardData['order_payment_name']); - $rowpayment->order_payment_number = base64_encode($creditCardData['order_payment_number']); + $rowpayment->order_payment_number = base64_encode($creditCardData['order_payment_number']); // This is ccv code - $rowpayment->order_payment_ccv = base64_encode($creditCardData['credit_card_code']); - $rowpayment->order_payment_amount = $order_total; - $rowpayment->order_payment_expire = $creditCardData['order_payment_expire_month'] . $creditCardData['order_payment_expire_year']; - $rowpayment->order_payment_name = $paymentMethod->name; - $rowpayment->payment_method_class = $paymentMethod->element; + $rowpayment->order_payment_ccv = base64_encode($creditCardData['credit_card_code']); + $rowpayment->order_payment_amount = $order_total; + $rowpayment->order_payment_expire = $creditCardData['order_payment_expire_month'] . $creditCardData['order_payment_expire_year']; + $rowpayment->order_payment_name = $paymentMethod->name; + $rowpayment->payment_method_class = $paymentMethod->element; $rowpayment->order_payment_trans_id = $d ["order_payment_trans_id"]; - $rowpayment->authorize_status = ""; + $rowpayment->authorize_status = ""; if (!$rowpayment->store()) { /** @scrutinizer ignore-deprecated */ @@ -1040,13 +1129,16 @@ public function orderplace() // For authorize status JPluginHelper::importPlugin('redshop_payment'); - JDispatcher::getInstance()->trigger('onAuthorizeStatus_' . $paymentMethod->element, array($paymentMethod->element, $orderId)); + JDispatcher::getInstance()->trigger( + 'onAuthorizeStatus_' . $paymentMethod->element, + array($paymentMethod->element, $orderId) + ); // Add billing Info $userrow = $this->getTable('user_detail'); $userrow->load($billingAddresses->users_info_id); $userrow->thirdparty_email = $post['thirdparty_email']; - $orderuserrow = $this->getTable('order_user_detail'); + $orderuserrow = $this->getTable('order_user_detail'); if (!$orderuserrow->bind($userrow)) { /** @scrutinizer ignore-deprecated */ @@ -1055,7 +1147,7 @@ public function orderplace() return false; } - $orderuserrow->order_id = $orderId; + $orderuserrow->order_id = $orderId; $orderuserrow->address_type = 'BT'; JPluginHelper::importPlugin('redshop_shipping'); @@ -1088,7 +1180,7 @@ public function orderplace() return false; } - $orderuserrow->order_id = $orderId; + $orderuserrow->order_id = $orderId; $orderuserrow->address_type = 'ST'; $dispatcher->trigger('onBeforeUserShippingStore', array(&$orderuserrow)); @@ -1114,12 +1206,14 @@ public function orderplace() RedshopHelperStockroom::deleteCartAfterEmpty(); // Economic Integration start for invoice generate and book current invoice - if (Redshop::getConfig()->get('ECONOMIC_INTEGRATION') == 1 && Redshop::getConfig()->get('ECONOMIC_INVOICE_DRAFT') != 2) { + if (Redshop::getConfig()->get('ECONOMIC_INTEGRATION') == 1 && Redshop::getConfig()->get( + 'ECONOMIC_INVOICE_DRAFT' + ) != 2) { $economicdata['economic_payment_terms_id'] = $economic_payment_terms_id; - $economicdata['economic_design_layout'] = $economic_design_layout; - $economicdata['economic_is_creditcard'] = $is_creditcard; - $payment_name = $paymentMethod->element; - $paymentArr = explode("rs_payment_", $paymentMethod->element); + $economicdata['economic_design_layout'] = $economic_design_layout; + $economicdata['economic_is_creditcard'] = $is_creditcard; + $payment_name = $paymentMethod->element; + $paymentArr = explode("rs_payment_", $paymentMethod->element); if (count($paymentArr) > 0) { $payment_name = $paymentArr[1]; @@ -1140,7 +1234,9 @@ public function orderplace() } // Send the Order mail before payment - if (!Redshop::getConfig()->get('ORDER_MAIL_AFTER') || (Redshop::getConfig()->get('ORDER_MAIL_AFTER') && $row->order_payment_status == "Paid")) { + if (!Redshop::getConfig()->get('ORDER_MAIL_AFTER') || (Redshop::getConfig()->get( + 'ORDER_MAIL_AFTER' + ) && $row->order_payment_status == "Paid")) { Redshop\Mail\Order::sendMail($row->order_id); } elseif (Redshop::getConfig()->get('ORDER_MAIL_AFTER') == 1) { // If Order mail set to send after payment then send mail to administrator only. @@ -1154,18 +1250,15 @@ public function orderplace() return $row; } - /** - * Method for send giftcard email to customer. - * - * @param int $orderId ID of order. - * - * @return void - * - * @throws Exception - */ - public function sendGiftCard($orderId) + public function shipaddress($userInfoId) { - \Redshop\Mail\Giftcard::sendMail($orderId); + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from('#__redshop_users_info') + ->where($db->quoteName('users_info_id') . ' = ' . (int)$userInfoId); + + return $db->setQuery($query)->loadObject(); } /** @@ -1175,9 +1268,9 @@ public function sendGiftCard($orderId) */ public function billingaddresses() { - $user = JFactory::getUser(); - $session = JFactory::getSession(); - $auth = $session->get('auth'); + $user = JFactory::getUser(); + $session = JFactory::getSession(); + $auth = $session->get('auth'); $billingAddress = new stdClass; if ($user->id) { @@ -1193,22 +1286,190 @@ public function billingaddresses() return $billingAddress; } - public function shipaddress($userInfoId) + /** + * @param string $shippingRateId Shipping rate + * + * @return array + * + * @since 2.1.0 + * + * @deprecated + */ + public function calculateShipping($shippingRateId) { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from('#__redshop_users_info') - ->where($db->quoteName('users_info_id') . ' = ' . (int)$userInfoId); + return Redshop\Helper\Shipping::calculateShipping($shippingRateId); + } - return $db->setQuery($query)->loadObject(); + /** + * Delete order number track + * + * @return boolean + * + * @since 2.1.0 + */ + public function deleteOrdernumberTrack() + { + $db = JFactory::getDbo(); + $query = 'TRUNCATE TABLE ' . $db->quoteName('#__redshop_ordernumber_track'); + + if (!$db->setQuery($query)->execute()) { + $msg = /** @scrutinizer ignore-deprecated */ + $db->getErrorMsg(); + /** @scrutinizer ignore-deprecated */ + $this->setError($msg); + + return false; + } + + return true; + } + + public function coupon($cart) + { + $user = JFactory::getUser(); + $db = JFactory::getDbo(); + $couponType = array(); + + if (isset($cart['coupon'])) { + if ($this->discount_type) { + $this->discount_type .= '@'; + } + + foreach ($cart['coupon'] as $coupon) { + $coupon_id = $coupon['coupon_id']; + $coupon_volume = $coupon['used_coupon']; + $transaction_coupon_id = 0; + $couponType[] = 'c:' . $coupon['coupon_code']; + + $sql = "UPDATE " . $this->_table_prefix . "coupons SET amount_left = amount_left - " . (int)$coupon_volume . " " + . "WHERE id = " . (int)$coupon_id; + $db->setQuery($sql)->execute(); + + if ($coupon['remaining_coupon_discount'] <= 0) { + continue; + } + + $rowcoupon = $this->getTable('transaction_coupon_detail'); + + if (!$rowcoupon->bind($cart)) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + } + + if ($coupon['transaction_coupon_id']) { + $transaction_coupon_id = $coupon['transaction_coupon_id']; + } + + $rowcoupon->transaction_coupon_id = $transaction_coupon_id; + $rowcoupon->coupon_value = $coupon['remaining_coupon_discount']; + $rowcoupon->coupon_code = $coupon['coupon_code']; + $rowcoupon->userid = $user->id; + $rowcoupon->coupon_id = $coupon_id; + $rowcoupon->trancation_date = mktime(0, 0, 0, date('m'), date('d'), date('Y')); + $rowcoupon->published = 1; + + if (!$rowcoupon->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + } + + $this->discount_type = implode('@', $couponType); + } + + return true; + } + + public function voucher($cart, $order_id) + { + if (!isset($cart['voucher'])) { + return; + } + + if ($this->discount_type) { + $this->discount_type .= '@'; + } + + $user = JFactory::getUser(); + $voucherType = array(); + + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + foreach ($cart['voucher'] as $voucher) { + $voucherId = $voucher['voucher_id']; + $voucherVolume = $voucher['used_voucher']; + $transactionVoucherId = 0; + $voucherType[] = 'v:' . $voucher['voucher_code']; + + $query->clear(); + $query->update($db->quoteName('#__redshop_voucher')) + ->set( + $db->quoteName('voucher_left') . ' = ' . $db->quoteName( + 'voucher_left' + ) . ' - ' . (int)$voucherVolume + ) + ->where($db->quoteName('id') . ' = ' . (int)$voucherId); + + $db->setQuery($query)->execute(); + + if ($voucher['remaining_voucher_discount'] <= 0) { + continue; + } + + $table = $this->getTable('transaction_voucher_detail'); + + if (!$table->bind($cart)) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + } + + if ($voucher['transaction_voucher_id']) { + $transactionVoucherId = $voucher['transaction_voucher_id']; + } + + $table->transaction_voucher_id = $transactionVoucherId; + $table->amount = $voucher['remaining_voucher_discount']; + $table->voucher_code = $voucher['voucher_code']; + $table->user_id = $user->id; + $table->order_id = $order_id; + $table->voucher_id = $voucherId; + $table->trancation_date = mktime(0, 0, 0, date('m'), date('d'), date('Y')); + $table->product_id = $voucher['product_id']; + $table->published = 1; + + if (!$table->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + } + + $this->discount_type .= implode('@', $voucherType); + } + + /** + * Method for send giftcard email to customer. + * + * @param int $orderId ID of order. + * + * @return void + * + * @throws Exception + */ + public function sendGiftCard($orderId) + { + \Redshop\Mail\Giftcard::sendMail($orderId); } public function shippingaddresses() { - $user = JFactory::getUser(); + $user = JFactory::getUser(); $session = JFactory::getSession(); - $auth = $session->get('auth'); + $auth = $session->get('auth'); if ($user->id) { return RedshopHelperOrder::getShippingAddress($user->id); @@ -1221,9 +1482,9 @@ public function shippingaddresses() public function getpaymentmethod() { - $user = JFactory::getUser(); + $user = JFactory::getUser(); $shopper_group = RedshopHelperOrder::getBillingAddress($user->id); - $query = "SELECT * FROM " . $this->_table_prefix . "payment_method WHERE published = '1' AND (FIND_IN_SET('" . (int)$shopper_group->shopper_group_id . "', shopper_group) OR shopper_group = '') ORDER BY ordering ASC"; + $query = "SELECT * FROM " . $this->_table_prefix . "payment_method WHERE published = '1' AND (FIND_IN_SET('" . (int)$shopper_group->shopper_group_id . "', shopper_group) OR shopper_group = '') ORDER BY ordering ASC"; $this->_db->setQuery($query); return $this->_db->loadObjectlist(); @@ -1234,7 +1495,7 @@ public function getpaymentmethod() */ public function validatePaymentCreditCardInfo() { - $session = JFactory::getSession(); + $session = JFactory::getSession(); $creditCardData = $session->get('ccdata'); $validPayment [0] = 1; @@ -1284,12 +1545,15 @@ public function validatePaymentCreditCardInfo() return $validPayment; } - $creditCardError = ''; + $creditCardError = ''; $creditCardErrorText = ''; - if (!$this->checkCreditCard($creditCardData['order_payment_number'], + if (!$this->checkCreditCard( + $creditCardData['order_payment_number'], $creditCardData['creditcard_code'], - $creditCardError, $creditCardErrorText)) { + $creditCardError, + $creditCardErrorText + )) { $validPayment [0] = 0; $validPayment [1] = $creditCardErrorText; @@ -1316,85 +1580,85 @@ public function checkCreditCard($cardnumber, $cardname, &$errornumber, &$errorte // American Express array( - 'name' => 'amex', - 'length' => '15', - 'prefixes' => '34,37', + 'name' => 'amex', + 'length' => '15', + 'prefixes' => '34,37', 'checkdigit' => true ), array( - 'name' => 'Diners Club Carte Blanche', - 'length' => '14', - 'prefixes' => '300,301,302,303,304,305', + 'name' => 'Diners Club Carte Blanche', + 'length' => '14', + 'prefixes' => '300,301,302,303,304,305', 'checkdigit' => true ), // Diners Club array( - 'name' => 'diners', - 'length' => '14,16', - 'prefixes' => '36,54,55', + 'name' => 'diners', + 'length' => '14,16', + 'prefixes' => '36,54,55', 'checkdigit' => true ), array( - 'name' => 'Discover', - 'length' => '16', - 'prefixes' => '6011,622,64,65', + 'name' => 'Discover', + 'length' => '16', + 'prefixes' => '6011,622,64,65', 'checkdigit' => true ), array( - 'name' => 'Diners Club Enroute', - 'length' => '15', - 'prefixes' => '2014,2149', + 'name' => 'Diners Club Enroute', + 'length' => '15', + 'prefixes' => '2014,2149', 'checkdigit' => true ), array( - 'name' => 'JCB', - 'length' => '16', - 'prefixes' => '35', + 'name' => 'JCB', + 'length' => '16', + 'prefixes' => '35', 'checkdigit' => true ), array( - 'name' => 'Maestro', - 'length' => '12,13,14,15,16,18,19', - 'prefixes' => '5018,5020,5038,6304,6759,6761', + 'name' => 'Maestro', + 'length' => '12,13,14,15,16,18,19', + 'prefixes' => '5018,5020,5038,6304,6759,6761', 'checkdigit' => true ), // MasterCard array( - 'name' => 'MC', - 'length' => '16', - 'prefixes' => '51,52,53,54,55', + 'name' => 'MC', + 'length' => '16', + 'prefixes' => '51,52,53,54,55', 'checkdigit' => true ), array( - 'name' => 'Solo', - 'length' => '16,18,19', - 'prefixes' => '6334,6767', + 'name' => 'Solo', + 'length' => '16,18,19', + 'prefixes' => '6334,6767', 'checkdigit' => true ), array( - 'name' => 'Switch', - 'length' => '16,18,19', - 'prefixes' => '4903,4905,4911,4936,564182,633110,6333,6759', + 'name' => 'Switch', + 'length' => '16,18,19', + 'prefixes' => '4903,4905,4911,4936,564182,633110,6333,6759', 'checkdigit' => true ), array( - 'name' => 'Visa', - 'length' => '13,16', - 'prefixes' => '4', + 'name' => 'Visa', + 'length' => '13,16', + 'prefixes' => '4', 'checkdigit' => true ), array( - 'name' => 'Visa Electron', - 'length' => '16', - 'prefixes' => '417500,4917,4913,4508,4844', + 'name' => 'Visa Electron', + 'length' => '16', + 'prefixes' => '417500,4917,4913,4508,4844', 'checkdigit' => true ), array( - 'name' => 'LaserCard', - 'length' => '16,17,18,19', - 'prefixes' => '6304,6706,6771,6709', + 'name' => 'LaserCard', + 'length' => '16,17,18,19', + 'prefixes' => '6304,6706,6771,6709', 'checkdigit' => true ) ); @@ -1419,7 +1683,7 @@ public function checkCreditCard($cardnumber, $cardname, &$errornumber, &$errorte // If card type not found, report an error if ($cardType == -1) { $errornumber = 0; - $errortext = $creditCardErrors [$errornumber]; + $errortext = $creditCardErrors [$errornumber]; return false; } @@ -1427,7 +1691,7 @@ public function checkCreditCard($cardnumber, $cardname, &$errornumber, &$errorte // Ensure that the user has provided a credit card number if (strlen($cardnumber) == 0) { $errornumber = 1; - $errortext = $creditCardErrors [$errornumber]; + $errortext = $creditCardErrors [$errornumber]; return false; } @@ -1438,7 +1702,7 @@ public function checkCreditCard($cardnumber, $cardname, &$errornumber, &$errorte // Check that the number is numeric and of the right sort of length. if (!preg_match("/^[0-9]{13,19}$/i", $cardNo)) { $errornumber = 2; - $errortext = $creditCardErrors [$errornumber]; + $errortext = $creditCardErrors [$errornumber]; return false; } @@ -1481,7 +1745,7 @@ public function checkCreditCard($cardnumber, $cardname, &$errornumber, &$errorte // If not, report an error. if ($checksum % 10 != 0) { $errornumber = 3; - $errortext = $creditCardErrors [$errornumber]; + $errortext = $creditCardErrors [$errornumber]; return false; } @@ -1508,14 +1772,14 @@ public function checkCreditCard($cardnumber, $cardname, &$errornumber, &$errorte // If it isn't a valid prefix there's no point at looking at the length if (!$PrefixValid) { $errornumber = 3; - $errortext = $creditCardErrors [$errornumber]; + $errortext = $creditCardErrors [$errornumber]; return false; } // See if the length is valid for this card $LengthValid = false; - $lengths = explode(',', $cards[$cardType]['length']); + $lengths = explode(',', $cards[$cardType]['length']); for ($j = 0, $jn = count($lengths); $j < $jn; $j++) { if (strlen($cardNo) == $lengths [$j]) { @@ -1527,7 +1791,7 @@ public function checkCreditCard($cardnumber, $cardname, &$errornumber, &$errorte // See if all is OK by seeing if the length was valid. if (!$LengthValid) { $errornumber = 4; - $errortext = $creditCardErrors [$errornumber]; + $errortext = $creditCardErrors [$errornumber]; return false; } @@ -1537,8 +1801,8 @@ public function checkCreditCard($cardnumber, $cardname, &$errornumber, &$errorte } /** - * @param string $creditcardNumber Credit card number - * @param string $type Type + * @param string $creditcardNumber Credit card number + * @param string $type Type * * @since 2.1.0 */ @@ -1572,11 +1836,13 @@ public function getCouponPrice() public function getCategoryNameByProductId($pid) { - $db = JFactory::getDbo(); + $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select($db->qn('c.name')) ->from($db->qn('#__redshop_product_category_xref', 'pcx')) - ->leftjoin($db->qn('#__redshop_category', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('pcx.category_id')) + ->leftjoin( + $db->qn('#__redshop_category', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('pcx.category_id') + ) ->where($db->qn('pcx.product_id') . ' = ' . $db->q((int)$pid)) ->where($db->qn('c.name') . ' IS NOT NULL') ->order($db->qn('c.id') . ' ASC') @@ -1585,165 +1851,36 @@ public function getCategoryNameByProductId($pid) return $db->setQuery($query)->loadResult(); } - public function voucher($cart, $order_id) - { - if (!isset($cart['voucher'])) { - return; - } - - if ($this->discount_type) { - $this->discount_type .= '@'; - } - - $user = JFactory::getUser(); - $voucherType = array(); - - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - foreach ($cart['voucher'] as $voucher) { - $voucherId = $voucher['voucher_id']; - $voucherVolume = $voucher['used_voucher']; - $transactionVoucherId = 0; - $voucherType[] = 'v:' . $voucher['voucher_code']; - - $query->clear(); - $query->update($db->quoteName('#__redshop_voucher')) - ->set($db->quoteName('voucher_left') . ' = ' . $db->quoteName('voucher_left') . ' - ' . (int)$voucherVolume) - ->where($db->quoteName('id') . ' = ' . (int)$voucherId); - - $db->setQuery($query)->execute(); - - if ($voucher['remaining_voucher_discount'] <= 0) { - continue; - } - - $table = $this->getTable('transaction_voucher_detail'); - - if (!$table->bind($cart)) { - /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - } - - if ($voucher['transaction_voucher_id']) { - $transactionVoucherId = $voucher['transaction_voucher_id']; - } - - $table->transaction_voucher_id = $transactionVoucherId; - $table->amount = $voucher['remaining_voucher_discount']; - $table->voucher_code = $voucher['voucher_code']; - $table->user_id = $user->id; - $table->order_id = $order_id; - $table->voucher_id = $voucherId; - $table->trancation_date = mktime(0, 0, 0, date('m'), date('d'), date('Y')); - $table->product_id = $voucher['product_id']; - $table->published = 1; - - if (!$table->store()) { - /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - } - - $this->discount_type .= implode('@', $voucherType); - } - - public function coupon($cart) - { - $user = JFactory::getUser(); - $db = JFactory::getDbo(); - $couponType = array(); - - if (isset($cart['coupon'])) { - if ($this->discount_type) { - $this->discount_type .= '@'; - } - - foreach ($cart['coupon'] as $coupon) { - $coupon_id = $coupon['coupon_id']; - $coupon_volume = $coupon['used_coupon']; - $transaction_coupon_id = 0; - $couponType[] = 'c:' . $coupon['coupon_code']; - - $sql = "UPDATE " . $this->_table_prefix . "coupons SET amount_left = amount_left - " . (int)$coupon_volume . " " - . "WHERE id = " . (int)$coupon_id; - $db->setQuery($sql)->execute(); - - if ($coupon['remaining_coupon_discount'] <= 0) { - continue; - } - - $rowcoupon = $this->getTable('transaction_coupon_detail'); - - if (!$rowcoupon->bind($cart)) { - /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - } - - if ($coupon['transaction_coupon_id']) { - $transaction_coupon_id = $coupon['transaction_coupon_id']; - } - - $rowcoupon->transaction_coupon_id = $transaction_coupon_id; - $rowcoupon->coupon_value = $coupon['remaining_coupon_discount']; - $rowcoupon->coupon_code = $coupon['coupon_code']; - $rowcoupon->userid = $user->id; - $rowcoupon->coupon_id = $coupon_id; - $rowcoupon->trancation_date = mktime(0, 0, 0, date('m'), date('d'), date('Y')); - $rowcoupon->published = 1; - - if (!$rowcoupon->store()) { - /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - } - - $this->discount_type = implode('@', $couponType); - } - - return true; - } - /** - * @param string $shippingRateId Shipping rate - * - * @return array - * - * @since 2.1.0 - * - * @deprecated - */ - public function calculateShipping($shippingRateId) - { - return Redshop\Helper\Shipping::calculateShipping($shippingRateId); - } - - /** - * Delete order number track + * Get Unique order number * - * @return boolean + * @return integer * * @since 2.1.0 */ - public function deleteOrdernumberTrack() + public function getOrdernumber() { - $db = JFactory::getDbo(); - $query = 'TRUNCATE TABLE ' . $db->quoteName('#__redshop_ordernumber_track'); + $trackIdTime = $this->getOrdernumberTrack(); - if (!$db->setQuery($query)->execute()) { - $msg = /** @scrutinizer ignore-deprecated */ - $db->getErrorMsg(); - /** @scrutinizer ignore-deprecated */ - $this->setError($msg); + if (!empty($trackIdTime)) { + $toTime = strtotime(date('Y-m-d H:i:s')); + $fromTime = strtotime($trackIdTime); + $totalMinutes = round(abs($toTime - $fromTime) / 60, 2); - return false; + if ($totalMinutes > 1) { + $this->deleteOrdernumberTrack(); + $trackIdTime = ""; + } } - return true; + if (!empty($trackIdTime)) { + return $this->getOrdernumber(); + } + + $this->insertOrdernumberTrack(); + $order_number = RedshopHelperOrder::generateOrderNumber(); + + return $order_number; } /** @@ -1755,7 +1892,7 @@ public function deleteOrdernumberTrack() */ public function getOrdernumberTrack() { - $db = JFactory::getDbo(); + $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select($db->quoteName('trackdatetime')) ->where($db->quoteName('#__redshop_ordernumber_track')); @@ -1772,7 +1909,7 @@ public function getOrdernumberTrack() */ public function insertOrdernumberTrack() { - $db = JFactory::getDbo(); + $db = JFactory::getDbo(); $query = $db->getQuery(true) ->insert($db->quoteName('#__redshop_ordernumber_track')) ->columns($db->quoteName('trackdatetime')) @@ -1790,36 +1927,4 @@ public function insertOrdernumberTrack() return true; } - - /** - * Get Unique order number - * - * @return integer - * - * @since 2.1.0 - */ - public function getOrdernumber() - { - $trackIdTime = $this->getOrdernumberTrack(); - - if (!empty($trackIdTime)) { - $toTime = strtotime(date('Y-m-d H:i:s')); - $fromTime = strtotime($trackIdTime); - $totalMinutes = round(abs($toTime - $fromTime) / 60, 2); - - if ($totalMinutes > 1) { - $this->deleteOrdernumberTrack(); - $trackIdTime = ""; - } - } - - if (!empty($trackIdTime)) { - return $this->getOrdernumber(); - } - - $this->insertOrdernumberTrack(); - $order_number = RedshopHelperOrder::generateOrderNumber(); - - return $order_number; - } } diff --git a/component/site/models/giftcard.php b/component/site/models/giftcard.php index f96805bc6b3..1c46f94f5d3 100644 --- a/component/site/models/giftcard.php +++ b/component/site/models/giftcard.php @@ -19,75 +19,70 @@ */ class RedshopModelGiftcard extends RedshopModel { - public $_id = null; + public $_id = null; - public $_data = null; + public $_data = null; - /** - * Product data - */ - public $_product = null; + /** + * Product data + */ + public $_product = null; - public $_table_prefix = null; + public $_table_prefix = null; - public $_template = null; + public $_template = null; - public $_limit = null; + public $_limit = null; - public function __construct() - { - parent::__construct(); + public function __construct() + { + parent::__construct(); - $this->_table_prefix = '#__redshop_'; - $Id = JFactory::getApplication()->input->getInt('gid', 0); + $this->_table_prefix = '#__redshop_'; + $Id = JFactory::getApplication()->input->getInt('gid', 0); - $this->setId((int) $Id); - } + $this->setId((int)$Id); + } - public function setId($id) - { - $this->_id = $id; - $this->_data = null; - } + public function setId($id) + { + $this->_id = $id; + $this->_data = null; + } - public function _buildQuery() - { - $and = ""; + public function getData() + { + if (empty ($this->_data)) { + $query = $this->_buildQuery(); + $this->_data = $this->_getList($query); + } - if ($this->_id) - { - $and .= "AND giftcard_id = " . (int) $this->_id . " "; - } + return $this->_data; + } - $query = "SELECT * FROM " . $this->_table_prefix . "giftcard " - . "WHERE published = 1 " - . $and; + public function _buildQuery() + { + $and = ""; - return $query; - } + if ($this->_id) { + $and .= "AND giftcard_id = " . (int)$this->_id . " "; + } - public function getData() - { - if (empty ($this->_data)) - { - $query = $this->_buildQuery(); - $this->_data = $this->_getList($query); - } + $query = "SELECT * FROM " . $this->_table_prefix . "giftcard " + . "WHERE published = 1 " + . $and; - return $this->_data; - } + return $query; + } - public function getGiftcardTemplate() - { - if (!$this->_id) - { - $carttemplate = RedshopHelperTemplate::getTemplate("giftcard_list"); - } - else - { - $carttemplate = RedshopHelperTemplate::getTemplate("giftcard"); - } + public function getGiftcardTemplate() + { + if (!$this->_id) { + $carttemplate = RedshopHelperTemplate::getTemplate("giftcard_list"); + } else { + $carttemplate = RedshopHelperTemplate::getTemplate("giftcard"); + } - return $carttemplate; - } + return $carttemplate; + } } diff --git a/component/site/models/login.php b/component/site/models/login.php index 1406c1907a5..9ba1412119c 100644 --- a/component/site/models/login.php +++ b/component/site/models/login.php @@ -19,58 +19,58 @@ */ class RedshopModelLogin extends RedshopModel { - public function __construct() - { - parent::__construct(); - } + public function __construct() + { + parent::__construct(); + } - public function setlogin($username, $password) - { - $app = JFactory::getApplication(); + public function setlogin($username, $password) + { + $app = JFactory::getApplication(); - $credentials = array(); - $credentials['username'] = $username; - $credentials['password'] = $password; + $credentials = array(); + $credentials['username'] = $username; + $credentials['password'] = $password; - // Perform the login action - $error = $app->login($credentials); + // Perform the login action + $error = $app->login($credentials); - if ($error instanceof JException && !empty($error->getMessage())) - { - $msg = "" . JText::_('COM_REDSHOP_FORGOT_PWD_LINK') . ""; - $app->enqueueMessage($msg); - } + if ($error instanceof JException && !empty($error->getMessage())) { + $msg = "" . JText::_( + 'COM_REDSHOP_FORGOT_PWD_LINK' + ) . ""; + $app->enqueueMessage($msg); + } - return $error; - } + return $error; + } - public function ShopperGroupDetail($sid = 0) - { - $user = JFactory::getUser(); + public function ShopperGroupDetail($sid = 0) + { + $user = JFactory::getUser(); - if ($sid == 0) - { - $query = "SELECT sg.* FROM #__redshop_shopper_group as sg " - . " LEFT JOIN #__redshop_users_info as ui on sg.`shopper_group_id`= ui.shopper_group_id WHERE ui.user_id = " . (int) $user->id; - } - else - { - $query = "SELECT sg.* FROM #__redshop_shopper_group as sg WHERE sg.`shopper_group_id`= " . (int) $sid; - } + if ($sid == 0) { + $query = "SELECT sg.* FROM #__redshop_shopper_group as sg " + . " LEFT JOIN #__redshop_users_info as ui on sg.`shopper_group_id`= ui.shopper_group_id WHERE ui.user_id = " . (int)$user->id; + } else { + $query = "SELECT sg.* FROM #__redshop_shopper_group as sg WHERE sg.`shopper_group_id`= " . (int)$sid; + } - $this->_db->setQuery($query); + $this->_db->setQuery($query); - return $this->_db->loadObjectList(); - } + return $this->_db->loadObjectList(); + } - public function CheckShopperGroup($username, $shoppergroupid) - { - $db = JFactory::getDbo(); - $query = "SELECT sg.`shopper_group_id` FROM (`#__redshop_shopper_group` as sg " - . " LEFT JOIN #__redshop_users_info as ui on sg.`shopper_group_id`= ui.shopper_group_id) LEFT JOIN #__users as u on ui.user_id = u.id WHERE u.username = " - . $db->quote($username) . " AND ui.shopper_group_id =" . (int) $shoppergroupid . " AND sg.shopper_group_portal = 1"; - $db->setQuery($query); + public function CheckShopperGroup($username, $shoppergroupid) + { + $db = JFactory::getDbo(); + $query = "SELECT sg.`shopper_group_id` FROM (`#__redshop_shopper_group` as sg " + . " LEFT JOIN #__redshop_users_info as ui on sg.`shopper_group_id`= ui.shopper_group_id) LEFT JOIN #__users as u on ui.user_id = u.id WHERE u.username = " + . $db->quote( + $username + ) . " AND ui.shopper_group_id =" . (int)$shoppergroupid . " AND sg.shopper_group_portal = 1"; + $db->setQuery($query); - return $db->loadResult(); - } + return $db->loadResult(); + } } diff --git a/component/site/models/manufacturers.php b/component/site/models/manufacturers.php index 2e322d8bcfc..f92146830a1 100644 --- a/component/site/models/manufacturers.php +++ b/component/site/models/manufacturers.php @@ -22,344 +22,358 @@ */ class RedshopModelManufacturers extends RedshopModel { - public $_id = null; - - public $_data = null; - - public $_productlimit = null; - - public $_table_prefix = null; - - public $_template = null; - - public $filter_fields_products = null; - - public $filter_fields_manufacturer = null; - - public function __construct() - { - $app = JFactory::getApplication(); - - $this->context = 'com_redshop.' . $app->input->getCmd('view') . '.' . $app->input->getCmd('layout', 'default'); - - // @ToDo In fearure, when class Manufacturers extends RedshopModelList, replace filter_fields in constructor - - $this->filter_fields_products = array( - 'p.product_name ASC', 'product_name ASC', - 'p.product_name DESC', 'product_name DESC', - 'p.product_price ASC', 'product_price ASC', - 'p.product_price DESC', 'product_price DESC', - 'p.product_number ASC', 'product_number ASC', - 'p.product_number DESC', 'product_number DESC', - 'p.product_id DESC', 'product_id DESC', - 'pc.ordering ASC', 'ordering ASC', - 'pc.ordering DESC', 'ordering DESC' - ); - - $this->filter_fields_manufacturer = array( - 'mn.name ASC', 'manufacturer_name ASC', - 'mn.id DESC', 'manufacturer_id DESC', - 'mn.ordering ASC', 'ordering ASC' - ); - - parent::__construct(); - - $this->_table_prefix = '#__redshop_'; - $params = $app->getParams('com_redshop'); - - if ($params->get('manufacturerid') != "") - { - $manid = $params->get('manufacturerid'); - } - else - { - $manid = (int) $app->input->getInt('mid', 0); - } - - $this->setId($manid); - - $limit = $app->getUserStateFromRequest($this->context . 'limit', 'limit', $params->get('maxmanufacturer'), 5); - - $limitstart = $app->input->getInt('limitstart', 0); - - // In case limit has been changed, adjust it - $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0); - - $this->setState($this->context . 'limit', $limit); - $this->setState($this->context . 'limitstart', $limitstart); - } - - public function setId($id) - { - $this->_id = $id; - $this->_data = null; - } - - public function setProductLimit($limit) - { - $this->_productlimit = $limit; - } - - public function getProductLimit() - { - return $this->_productlimit; - } - - public function _buildQuery() - { - $orderby = $this->_buildContentOrderBy(); - $and = ""; - - // Shopper group - choose from manufactures Start - $shopper_group_manufactures = RedshopHelperShopper_Group::getShopperGroupManufacturers(); - - if (!empty($shopper_group_manufactures)) - { - $shopper_group_manufactures = explode(',', $shopper_group_manufactures); - $shopper_group_manufactures = \Joomla\Utilities\ArrayHelper::toInteger($shopper_group_manufactures); - $shopper_group_manufactures = implode(',', $shopper_group_manufactures); - $and .= " AND mn.id IN (" . $shopper_group_manufactures . ") "; - } - - // Shopper group - choose from manufactures End - - if ($this->_id) - { - $and .= " AND mn.id = " . (int) $this->_id . " "; - } - - $query = "SELECT mn.* FROM " . $this->_table_prefix . "manufacturer AS mn " - . "WHERE mn.published = 1 " - . $and - . $orderby; - - return $query; - } - - public function getTotal() - { - if (empty($this->_total)) - { - $query = $this->_buildQuery(); - $this->_total = $this->_getListCount($query); - } - - return $this->_total; - } - - public function getData() - { - $layout = JFactory::getApplication()->input->getCmd('layout'); - $query = $this->_buildQuery(); - - if ($layout == "detail") - { - $this->_data = $this->_getList($query); - } - else - { - $this->_data = $this->_getList($query, $this->getState($this->context . 'limitstart'), $this->getState($this->context . 'limit')); - } - - return $this->_data; - } - - public function _buildContentOrderBy() - { - $db = JFactory::getDbo(); - $app = JFactory::getApplication(); - $layout = $app->input->getCmd('layout', ''); - $params = $app->getParams('com_redshop'); - - if ($app->input->getString('order_by', '') != null) - { - $order_by = urldecode($app->input->getString('order_by', '')); - $app->setUserState('com_redshop.manufacturers.default.order_state', $order_by); - } - elseif ($app->getUserState('com_redshop.manufacturers.default.order_state') != null) - { - $order_by = $app->getUserState('com_redshop.manufacturers.default.order_state'); - } - else - { - $order_by = $params->get('order_by', Redshop::getConfig()->get('DEFAULT_MANUFACTURER_ORDERING_METHOD')); - } - - if ($layout == 'products') - { - $filter_order = 'mn.id'; - } - else - { - if (in_array($order_by, $this->filter_fields_manufacturer)) - { - $filter_order = $order_by; - } - - // User can get not allowed order_by, when url contain Itemid from another view, so it need check here - elseif (in_array($params->get('order_by', Redshop::getConfig()->get('DEFAULT_MANUFACTURER_ORDERING_METHOD')), $this->filter_fields_manufacturer)) - { - $filter_order = $params->get('order_by', Redshop::getConfig()->get('DEFAULT_MANUFACTURER_ORDERING_METHOD')); - } - else - { - $filter_order = Redshop::getConfig()->get('DEFAULT_MANUFACTURER_ORDERING_METHOD'); - } - } - - $orderby = " ORDER BY " . $db->escape($filter_order) . ' '; - - return $orderby; - } - - public function getPagination() - { - if (empty($this->_pagination)) - { - $this->_pagination = new JPagination($this->getTotal(), $this->getState($this->context . 'limitstart'), $this->getState($this->context . 'limit')); - } - - return $this->_pagination; - } - - public function getCategoryList() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('c.id', 'value')) - ->select($db->qn('c.name', 'text')) - ->from($db->qn('#__redshop_category', 'c')) - ->leftjoin($db->qn('#__redshop_product_category_xref', 'pcx') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('pcx.category_id')) - ->leftjoin($db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('pcx.product_id')) - ->where($db->qn('p.manufacturer_id') . ' = ' . $db->q((int) $this->_id)) - ->where($db->qn('c.published') . ' = 1') - ->order($db->qn('c.name') . ' ASC'); - - return $db->setQuery($query)->loadObjectlist(); - } - - public function getManufacturerProducts($template_data = '') - { - $limit = $this->getProductLimit(); - $limitstart = JFactory::getApplication()->input->getInt('limitstart', 0); - $query = $this->_buildProductQuery($template_data); - $this->products = $this->_getList($query, $limitstart, $limit); - - return $this->products; - } - - /** - * @param string $template_data Template content - * - * @return JDatabaseQuery - */ - public function _buildProductQuery($template_data = '') - { - $filterBy = JFactory::getApplication()->input->get('filter_by', 0); - $orderBy = $this->_buildProductOrderBy($template_data); - - // Shopper group - choose from manufactures Start - $shopperGroupManufactures = RedshopHelperShopper_Group::getShopperGroupManufacturers(); - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('p.*') - ->select($db->qn('c.id')) - ->select($db->qn('c.name')) - ->from($db->qn('#__redshop_product', 'p')) - ->leftjoin($db->qn('#__redshop_product_category_xref', 'pcx') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('pcx.product_id')) - ->leftjoin($db->qn('#__redshop_category', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('pcx.category_id')) - ->where($db->qn('p.manufacturer_id') . ' = ' . $db->q((int) $this->_id)) - ->where($db->qn('p.published') . ' = 1') - ->where($db->qn('p.expired') . ' = 0') - ->where($db->qn('p.product_parent_id') . ' = 0') - ->order($orderBy) - ->group($db->qn('p.product_id')); - - if (!empty($shopperGroupManufactures)) - { - $shopperGroupManufactures = explode(',', $shopperGroupManufactures); - $shopperGroupManufactures = ArrayHelper::toInteger($shopperGroupManufactures); - $shopperGroupManufactures = implode(',', $shopperGroupManufactures); - $query->where($db->qn('p.manufacturer_id') . ' IN (' . $shopperGroupManufactures . ')'); - } - - if ($filterBy != '0') - { - $query->where($db->qn('c.id') . ' = ' . $db->q((int) $filterBy)); - } - - // Filter cids by menu configuration - $app = JFactory::getApplication(); - $menu = $app->getMenu(); - $active = $menu->getActive(); - $itemId = isset($active->id) ? $active->id : null; - $menuParams = $menu->getParams($itemId); - $cid = $menuParams->get('cid'); - - if ($cid) - { - $tmpCategories = RedshopHelperCategory::getCategoryTree($cid); - $categoriesIds = array($cid); - - if (!empty($tmpCategories)) - { - foreach ($tmpCategories as $child) - { - $categoriesIds[] = $child->id; - } - } - $query->where($db->qn('c.id') . ' IN ( ' . implode(',', $categoriesIds) . ' )'); - } - - /** - * you modify query for get product - * - * @since 3.0 - */ - JPluginHelper::importPlugin('redshop_product'); - RedshopHelperUtility::getDispatcher()->trigger('onAfterQueryManufacturerProduct', array(&$query)); - - return $query; - } - - public function getProductTotal() - { - $query = $this->_buildProductQuery(); - $total = $this->_getListCount($query); - - return $total; - } - - public function getProductPagination() - { - $limit = $this->getProductLimit(); - $limitstart = JFactory::getApplication()->input->getInt('limitstart', 0); - $productpagination = new JPagination($this->getProductTotal(), $limitstart, $limit); - - return $productpagination; - } - - public function _buildProductOrderBy($template_data = '') - { - $orderByObj = RedshopHelperUtility::prepareOrderBy( - urldecode( - JFactory::getApplication()->input->getString('order_by', Redshop::getConfig()->get('DEFAULT_MANUFACTURER_PRODUCT_ORDERING_METHOD')) - ) - ); - $orderBy = $orderByObj->ordering . ' ' . $orderByObj->direction; - $filterOrder = 'pc.ordering'; - - if (in_array($orderBy, $this->filter_fields_products)) - { - $filterOrder = $orderBy; - } - - if (strstr($template_data, '{category_name}')) - { - $filterOrder = "c.ordering, c.id, " . $filterOrder; - } - - return JFactory::getDbo()->escape($filterOrder) . ' '; - } + public $_id = null; + + public $_data = null; + + public $_productlimit = null; + + public $_table_prefix = null; + + public $_template = null; + + public $filter_fields_products = null; + + public $filter_fields_manufacturer = null; + + public function __construct() + { + $app = JFactory::getApplication(); + + $this->context = 'com_redshop.' . $app->input->getCmd('view') . '.' . $app->input->getCmd('layout', 'default'); + + // @ToDo In fearure, when class Manufacturers extends RedshopModelList, replace filter_fields in constructor + + $this->filter_fields_products = array( + 'p.product_name ASC', + 'product_name ASC', + 'p.product_name DESC', + 'product_name DESC', + 'p.product_price ASC', + 'product_price ASC', + 'p.product_price DESC', + 'product_price DESC', + 'p.product_number ASC', + 'product_number ASC', + 'p.product_number DESC', + 'product_number DESC', + 'p.product_id DESC', + 'product_id DESC', + 'pc.ordering ASC', + 'ordering ASC', + 'pc.ordering DESC', + 'ordering DESC' + ); + + $this->filter_fields_manufacturer = array( + 'mn.name ASC', + 'manufacturer_name ASC', + 'mn.id DESC', + 'manufacturer_id DESC', + 'mn.ordering ASC', + 'ordering ASC' + ); + + parent::__construct(); + + $this->_table_prefix = '#__redshop_'; + $params = $app->getParams('com_redshop'); + + if ($params->get('manufacturerid') != "") { + $manid = $params->get('manufacturerid'); + } else { + $manid = (int)$app->input->getInt('mid', 0); + } + + $this->setId($manid); + + $limit = $app->getUserStateFromRequest($this->context . 'limit', 'limit', $params->get('maxmanufacturer'), 5); + + $limitstart = $app->input->getInt('limitstart', 0); + + // In case limit has been changed, adjust it + $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0); + + $this->setState($this->context . 'limit', $limit); + $this->setState($this->context . 'limitstart', $limitstart); + } + + public function setId($id) + { + $this->_id = $id; + $this->_data = null; + } + + public function getData() + { + $layout = JFactory::getApplication()->input->getCmd('layout'); + $query = $this->_buildQuery(); + + if ($layout == "detail") { + $this->_data = $this->_getList($query); + } else { + $this->_data = $this->_getList( + $query, + $this->getState($this->context . 'limitstart'), + $this->getState($this->context . 'limit') + ); + } + + return $this->_data; + } + + public function _buildQuery() + { + $orderby = $this->_buildContentOrderBy(); + $and = ""; + + // Shopper group - choose from manufactures Start + $shopper_group_manufactures = RedshopHelperShopper_Group::getShopperGroupManufacturers(); + + if (!empty($shopper_group_manufactures)) { + $shopper_group_manufactures = explode(',', $shopper_group_manufactures); + $shopper_group_manufactures = \Joomla\Utilities\ArrayHelper::toInteger($shopper_group_manufactures); + $shopper_group_manufactures = implode(',', $shopper_group_manufactures); + $and .= " AND mn.id IN (" . $shopper_group_manufactures . ") "; + } + + // Shopper group - choose from manufactures End + + if ($this->_id) { + $and .= " AND mn.id = " . (int)$this->_id . " "; + } + + $query = "SELECT mn.* FROM " . $this->_table_prefix . "manufacturer AS mn " + . "WHERE mn.published = 1 " + . $and + . $orderby; + + return $query; + } + + public function _buildContentOrderBy() + { + $db = JFactory::getDbo(); + $app = JFactory::getApplication(); + $layout = $app->input->getCmd('layout', ''); + $params = $app->getParams('com_redshop'); + + if ($app->input->getString('order_by', '') != null) { + $order_by = urldecode($app->input->getString('order_by', '')); + $app->setUserState('com_redshop.manufacturers.default.order_state', $order_by); + } elseif ($app->getUserState('com_redshop.manufacturers.default.order_state') != null) { + $order_by = $app->getUserState('com_redshop.manufacturers.default.order_state'); + } else { + $order_by = $params->get('order_by', Redshop::getConfig()->get('DEFAULT_MANUFACTURER_ORDERING_METHOD')); + } + + if ($layout == 'products') { + $filter_order = 'mn.id'; + } else { + if (in_array($order_by, $this->filter_fields_manufacturer)) { + $filter_order = $order_by; + } // User can get not allowed order_by, when url contain Itemid from another view, so it need check here + elseif (in_array( + $params->get('order_by', Redshop::getConfig()->get('DEFAULT_MANUFACTURER_ORDERING_METHOD')), + $this->filter_fields_manufacturer + )) { + $filter_order = $params->get( + 'order_by', + Redshop::getConfig()->get('DEFAULT_MANUFACTURER_ORDERING_METHOD') + ); + } else { + $filter_order = Redshop::getConfig()->get('DEFAULT_MANUFACTURER_ORDERING_METHOD'); + } + } + + $orderby = " ORDER BY " . $db->escape($filter_order) . ' '; + + return $orderby; + } + + public function getPagination() + { + if (empty($this->_pagination)) { + $this->_pagination = new JPagination( + $this->getTotal(), + $this->getState($this->context . 'limitstart'), + $this->getState($this->context . 'limit') + ); + } + + return $this->_pagination; + } + + public function getTotal() + { + if (empty($this->_total)) { + $query = $this->_buildQuery(); + $this->_total = $this->_getListCount($query); + } + + return $this->_total; + } + + public function getCategoryList() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('c.id', 'value')) + ->select($db->qn('c.name', 'text')) + ->from($db->qn('#__redshop_category', 'c')) + ->leftjoin( + $db->qn('#__redshop_product_category_xref', 'pcx') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn( + 'pcx.category_id' + ) + ) + ->leftjoin( + $db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn( + 'pcx.product_id' + ) + ) + ->where($db->qn('p.manufacturer_id') . ' = ' . $db->q((int)$this->_id)) + ->where($db->qn('c.published') . ' = 1') + ->order($db->qn('c.name') . ' ASC'); + + return $db->setQuery($query)->loadObjectlist(); + } + + public function getManufacturerProducts($template_data = '') + { + $limit = $this->getProductLimit(); + $limitstart = JFactory::getApplication()->input->getInt('limitstart', 0); + $query = $this->_buildProductQuery($template_data); + $this->products = $this->_getList($query, $limitstart, $limit); + + return $this->products; + } + + public function getProductLimit() + { + return $this->_productlimit; + } + + public function setProductLimit($limit) + { + $this->_productlimit = $limit; + } + + /** + * @param string $template_data Template content + * + * @return JDatabaseQuery + */ + public function _buildProductQuery($template_data = '') + { + $filterBy = JFactory::getApplication()->input->get('filter_by', 0); + $orderBy = $this->_buildProductOrderBy($template_data); + + // Shopper group - choose from manufactures Start + $shopperGroupManufactures = RedshopHelperShopper_Group::getShopperGroupManufacturers(); + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('p.*') + ->select($db->qn('c.id')) + ->select($db->qn('c.name')) + ->from($db->qn('#__redshop_product', 'p')) + ->leftjoin( + $db->qn('#__redshop_product_category_xref', 'pcx') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn( + 'pcx.product_id' + ) + ) + ->leftjoin( + $db->qn('#__redshop_category', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('pcx.category_id') + ) + ->where($db->qn('p.manufacturer_id') . ' = ' . $db->q((int)$this->_id)) + ->where($db->qn('p.published') . ' = 1') + ->where($db->qn('p.expired') . ' = 0') + ->where($db->qn('p.product_parent_id') . ' = 0') + ->order($orderBy) + ->group($db->qn('p.product_id')); + + if (!empty($shopperGroupManufactures)) { + $shopperGroupManufactures = explode(',', $shopperGroupManufactures); + $shopperGroupManufactures = ArrayHelper::toInteger($shopperGroupManufactures); + $shopperGroupManufactures = implode(',', $shopperGroupManufactures); + $query->where($db->qn('p.manufacturer_id') . ' IN (' . $shopperGroupManufactures . ')'); + } + + if ($filterBy != '0') { + $query->where($db->qn('c.id') . ' = ' . $db->q((int)$filterBy)); + } + + // Filter cids by menu configuration + $app = JFactory::getApplication(); + $menu = $app->getMenu(); + $active = $menu->getActive(); + $itemId = isset($active->id) ? $active->id : null; + $menuParams = $menu->getParams($itemId); + $cid = $menuParams->get('cid'); + + if ($cid) { + $tmpCategories = RedshopHelperCategory::getCategoryTree($cid); + $categoriesIds = array($cid); + + if (!empty($tmpCategories)) { + foreach ($tmpCategories as $child) { + $categoriesIds[] = $child->id; + } + } + $query->where($db->qn('c.id') . ' IN ( ' . implode(',', $categoriesIds) . ' )'); + } + + /** + * you modify query for get product + * + * @since 3.0 + */ + JPluginHelper::importPlugin('redshop_product'); + RedshopHelperUtility::getDispatcher()->trigger('onAfterQueryManufacturerProduct', array(&$query)); + + return $query; + } + + public function _buildProductOrderBy($template_data = '') + { + $orderByObj = RedshopHelperUtility::prepareOrderBy( + urldecode( + JFactory::getApplication()->input->getString( + 'order_by', + Redshop::getConfig()->get( + 'DEFAULT_MANUFACTURER_PRODUCT_ORDERING_METHOD' + ) + ) + ) + ); + $orderBy = $orderByObj->ordering . ' ' . $orderByObj->direction; + $filterOrder = 'pc.ordering'; + + if (in_array($orderBy, $this->filter_fields_products)) { + $filterOrder = $orderBy; + } + + if (strstr($template_data, '{category_name}')) { + $filterOrder = "c.ordering, c.id, " . $filterOrder; + } + + return JFactory::getDbo()->escape($filterOrder) . ' '; + } + + public function getProductPagination() + { + $limit = $this->getProductLimit(); + $limitstart = JFactory::getApplication()->input->getInt('limitstart', 0); + $productpagination = new JPagination($this->getProductTotal(), $limitstart, $limit); + + return $productpagination; + } + + public function getProductTotal() + { + $query = $this->_buildProductQuery(); + $total = $this->_getListCount($query); + + return $total; + } } diff --git a/component/site/models/newsletter.php b/component/site/models/newsletter.php index cde982c8e47..a4209b65100 100644 --- a/component/site/models/newsletter.php +++ b/component/site/models/newsletter.php @@ -19,105 +19,101 @@ */ class RedshopModelNewsletter extends RedshopModel { - /** - * @var null|string - */ - public $_table_prefix = null; - - /** - * @var JDatabaseDriver|null - */ - public $_db = null; - - /** - * Constructor - * - * @throws Exception - */ - public function __construct() - { - parent::__construct(); - - $this->_db = JFactory::getDbo(); - $this->_table_prefix = '#__redshop_'; - $subId = JFactory::getApplication()->input->getInt('sid', ''); - - if ($subId) - { - $this->confirmSubscribe($subId); - } - } - - /** - * Check is email is subscription - * - * @param string $email Email - * - * @return boolean - * @throws Exception - */ - public function checkSubscriptionByEmail($email) - { - $app = JFactory::getApplication(); - $db = $this->getDbo(); - $link = JUri::root() . 'index.php?option=com_redshop&view=newsletter'; - - $query = $db->getQuery(true) - ->select('COUNT(*)') - ->from($db->qn('#__redshop_newsletter')); - $count = (int) $db->setQuery($query)->loadResult(); - - if (!$count) - { - // If there are no newsletter, redirect with message. - $app->redirect(JRoute::_($link), JText::_('COM_REDSHOP_NEWSLETTER_NOT_AVAILABLE')); - } - - $user = JFactory::getUser(); - - if ($user->id) - { - $email = $user->email; - } - - $query->clear() - ->select($db->qn('subscription_id')) - ->from($db->qn('#__redshop_newsletter_subscription')) - ->where($db->qn('email') . ' = ' . $db->quote($email)) - ->where($db->qn('newsletter_id') . ' = ' . Redshop::getConfig()->getInt('DEFAULT_NEWSLETTER')) - ->where($db->qn('user_id') . ' = ' . $user->id); - - $hasSubscribed = $db->setQuery($query)->loadResult(); - - if ($hasSubscribed) - { - return true; - } - - return false; - } - - /** - * Check is email is subscription - * - * @param integer $subscriptionId Subscribe ID - * - * @return void - * @throws Exception - */ - public function confirmSubscribe($subscriptionId) - { - $app = JFactory::getApplication(); - $db = $this->getDbo(); - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_newsletter_subscription')) - ->set($db->qn('published') . ' = 1') - ->where($db->qn('subscription_id') . ' = ' . (int) $subscriptionId); - $db->setQuery($query)->execute(); - - $app->redirect( - JRoute::_(JUri::root() . 'index.php?option=com_redshop&view=newsletter'), - JText::_('COM_REDSHOP_MESSAGE_CONFIRMED_SUBSCRIBE') - ); - } + /** + * @var null|string + */ + public $_table_prefix = null; + + /** + * @var JDatabaseDriver|null + */ + public $_db = null; + + /** + * Constructor + * + * @throws Exception + */ + public function __construct() + { + parent::__construct(); + + $this->_db = JFactory::getDbo(); + $this->_table_prefix = '#__redshop_'; + $subId = JFactory::getApplication()->input->getInt('sid', ''); + + if ($subId) { + $this->confirmSubscribe($subId); + } + } + + /** + * Check is email is subscription + * + * @param integer $subscriptionId Subscribe ID + * + * @return void + * @throws Exception + */ + public function confirmSubscribe($subscriptionId) + { + $app = JFactory::getApplication(); + $db = $this->getDbo(); + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_newsletter_subscription')) + ->set($db->qn('published') . ' = 1') + ->where($db->qn('subscription_id') . ' = ' . (int)$subscriptionId); + $db->setQuery($query)->execute(); + + $app->redirect( + JRoute::_(JUri::root() . 'index.php?option=com_redshop&view=newsletter'), + JText::_('COM_REDSHOP_MESSAGE_CONFIRMED_SUBSCRIBE') + ); + } + + /** + * Check is email is subscription + * + * @param string $email Email + * + * @return boolean + * @throws Exception + */ + public function checkSubscriptionByEmail($email) + { + $app = JFactory::getApplication(); + $db = $this->getDbo(); + $link = JUri::root() . 'index.php?option=com_redshop&view=newsletter'; + + $query = $db->getQuery(true) + ->select('COUNT(*)') + ->from($db->qn('#__redshop_newsletter')); + $count = (int)$db->setQuery($query)->loadResult(); + + if (!$count) { + // If there are no newsletter, redirect with message. + $app->redirect(JRoute::_($link), JText::_('COM_REDSHOP_NEWSLETTER_NOT_AVAILABLE')); + } + + $user = JFactory::getUser(); + + if ($user->id) { + $email = $user->email; + } + + $query->clear() + ->select($db->qn('subscription_id')) + ->from($db->qn('#__redshop_newsletter_subscription')) + ->where($db->qn('email') . ' = ' . $db->quote($email)) + ->where($db->qn('newsletter_id') . ' = ' . Redshop::getConfig()->getInt('DEFAULT_NEWSLETTER')) + ->where($db->qn('user_id') . ' = ' . $user->id); + + $hasSubscribed = $db->setQuery($query)->loadResult(); + + if ($hasSubscribed) { + return true; + } + + return false; + } } diff --git a/component/site/models/order_detail.php b/component/site/models/order_detail.php index 437d6294ac1..8fe91f2fc65 100644 --- a/component/site/models/order_detail.php +++ b/component/site/models/order_detail.php @@ -18,172 +18,165 @@ */ class RedshopModelOrder_detail extends RedshopModel { - public $_id = null; - - public $_data = null; - - public $_table_prefix = null; - - /** - * Constructor - */ - public function __construct() - { - parent::__construct(); - $this->_table_prefix = '#__redshop_'; - } - - /** - * Check Order Information Access Token - * - * @param integer $oid Order Id - * @param string $encr Encryped String - Token - * - * @return integer User Info id - redSHOP User Id if validate. - */ - public function checkauthorization($oid, $encr, $setUser = true) - { - // Initialize variables. - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - // Create the base select statement. - $query->select('user_info_id') - ->from($db->qn('#__redshop_orders')) - ->where($db->qn('order_id') . ' = ' . (int) $oid) - ->where($db->qn('encr_key') . ' = ' . $db->q($encr)); - - // Set the query and load the result. - $db->setQuery($query); - - try - { - $userInfoIdEncr = $db->loadResult(); - } - catch (RuntimeException $e) - { - throw new RuntimeException($e->getMessage(), $e->getCode()); - } - - if ($userInfoIdEncr && $setUser) - { - $session = JFactory::getSession(); - $auth['users_info_id'] = $userInfoIdEncr; - - $session->set('auth', $auth); - } - - return $userInfoIdEncr; - } - - /** - * Update analytic status - * - * @return boolean - */ - public function UpdateAnalytics_status($oid) - { - $query = "UPDATE " . $this->_table_prefix . "orders SET `analytics_status` = 1 WHERE order_id = " . (int) $oid; - $this->_db->setQuery($query); - - if (!$this->_db->execute()) - { - return false; - } - - return true; - } - - /** - * Get Billing Addresses - * - * @return object - */ - public function billingaddresses() - { - $user = JFactory::getUser(); - $session = JFactory::getSession(); - $auth = $session->get('auth'); - $billingAddress = new stdClass; - - if ($user->id) - { - $billingAddress = RedshopHelperOrder::getBillingAddress($user->id); - } - elseif ($auth['users_info_id']) - { - $uid = -$auth['users_info_id']; - $billingAddress = RedshopHelperOrder::getBillingAddress($uid); - } - - if ($billingAddress === false || $billingAddress === null) - { - return new stdClass; - } - - return $billingAddress; - } - - /** - * Get category name from Product Id - * - * @return string - */ - public function getCategoryNameByProductId($pid) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('c.name')) - ->from($db->qn('#__redshop_product_category_xref', 'pcx')) - ->leftjoin($db->qn('#__redshop_category', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('pcx.category_id')) - ->where($db->qn('pcx.product_id') . ' = ' . $db->q((int) $pid)) - ->where($db->qn('c.name') . ' IS NOT NULL') - ->order($db->qn('c.id') . ' ASC'); - - return $db->setQuery($query, 0, 1)->loadResult(); - } - - /** - * @return void - * - * @since 2.0.7 - */ - public function resetcart() - { - RedshopHelperCartSession::reset(); - $session = JFactory::getSession(); - $session->set('ccdata', null); - $session->set('issplit', null); - $session->set('userfield', null); - - unset($_SESSION ['ccdata']); - } - - public function update_ccdata($order_id, $payment_transaction_id) - { - $db = JFactory::getDbo(); - - $session = JFactory::getSession(); - $ccdata = $session->get('ccdata'); - - $order_payment_code = $ccdata['creditcard_code']; - $order_payment_cardname = base64_encode($ccdata['order_payment_name']); - $order_payment_number = base64_encode($ccdata['order_payment_number']); - - // This is ccv code - $order_payment_ccv = base64_encode($ccdata['credit_card_code']); - $order_payment_expire = $ccdata['order_payment_expire_month'] . $ccdata['order_payment_expire_year']; - $order_payment_trans_id = $payment_transaction_id; - - $payment_update = "UPDATE " . $this->_table_prefix . "order_payment " - . " SET order_payment_code = " . $db->quote($order_payment_code) . ", " - . " order_payment_cardname = " . $db->quote($order_payment_cardname) . ", " - . " order_payment_number = " . $db->quote($order_payment_number) . ", " - . " order_payment_ccv = " . $db->quote($order_payment_ccv) . ", " - . " order_payment_expire = " . $db->quote($order_payment_expire) . ", " - . " order_payment_trans_id = " . $db->quote($payment_transaction_id) . " " - . " WHERE order_id = " . (int) $order_id; - - return $db->setQuery($payment_update)->execute(); - } + public $_id = null; + + public $_data = null; + + public $_table_prefix = null; + + /** + * Constructor + */ + public function __construct() + { + parent::__construct(); + $this->_table_prefix = '#__redshop_'; + } + + /** + * Check Order Information Access Token + * + * @param integer $oid Order Id + * @param string $encr Encryped String - Token + * + * @return integer User Info id - redSHOP User Id if validate. + */ + public function checkauthorization($oid, $encr, $setUser = true) + { + // Initialize variables. + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + // Create the base select statement. + $query->select('user_info_id') + ->from($db->qn('#__redshop_orders')) + ->where($db->qn('order_id') . ' = ' . (int)$oid) + ->where($db->qn('encr_key') . ' = ' . $db->q($encr)); + + // Set the query and load the result. + $db->setQuery($query); + + try { + $userInfoIdEncr = $db->loadResult(); + } catch (RuntimeException $e) { + throw new RuntimeException($e->getMessage(), $e->getCode()); + } + + if ($userInfoIdEncr && $setUser) { + $session = JFactory::getSession(); + $auth['users_info_id'] = $userInfoIdEncr; + + $session->set('auth', $auth); + } + + return $userInfoIdEncr; + } + + /** + * Update analytic status + * + * @return boolean + */ + public function UpdateAnalytics_status($oid) + { + $query = "UPDATE " . $this->_table_prefix . "orders SET `analytics_status` = 1 WHERE order_id = " . (int)$oid; + $this->_db->setQuery($query); + + if (!$this->_db->execute()) { + return false; + } + + return true; + } + + /** + * Get Billing Addresses + * + * @return object + */ + public function billingaddresses() + { + $user = JFactory::getUser(); + $session = JFactory::getSession(); + $auth = $session->get('auth'); + $billingAddress = new stdClass; + + if ($user->id) { + $billingAddress = RedshopHelperOrder::getBillingAddress($user->id); + } elseif ($auth['users_info_id']) { + $uid = -$auth['users_info_id']; + $billingAddress = RedshopHelperOrder::getBillingAddress($uid); + } + + if ($billingAddress === false || $billingAddress === null) { + return new stdClass; + } + + return $billingAddress; + } + + /** + * Get category name from Product Id + * + * @return string + */ + public function getCategoryNameByProductId($pid) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('c.name')) + ->from($db->qn('#__redshop_product_category_xref', 'pcx')) + ->leftjoin( + $db->qn('#__redshop_category', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('pcx.category_id') + ) + ->where($db->qn('pcx.product_id') . ' = ' . $db->q((int)$pid)) + ->where($db->qn('c.name') . ' IS NOT NULL') + ->order($db->qn('c.id') . ' ASC'); + + return $db->setQuery($query, 0, 1)->loadResult(); + } + + /** + * @return void + * + * @since 2.0.7 + */ + public function resetcart() + { + RedshopHelperCartSession::reset(); + $session = JFactory::getSession(); + $session->set('ccdata', null); + $session->set('issplit', null); + $session->set('userfield', null); + + unset($_SESSION ['ccdata']); + } + + public function update_ccdata($order_id, $payment_transaction_id) + { + $db = JFactory::getDbo(); + + $session = JFactory::getSession(); + $ccdata = $session->get('ccdata'); + + $order_payment_code = $ccdata['creditcard_code']; + $order_payment_cardname = base64_encode($ccdata['order_payment_name']); + $order_payment_number = base64_encode($ccdata['order_payment_number']); + + // This is ccv code + $order_payment_ccv = base64_encode($ccdata['credit_card_code']); + $order_payment_expire = $ccdata['order_payment_expire_month'] . $ccdata['order_payment_expire_year']; + $order_payment_trans_id = $payment_transaction_id; + + $payment_update = "UPDATE " . $this->_table_prefix . "order_payment " + . " SET order_payment_code = " . $db->quote($order_payment_code) . ", " + . " order_payment_cardname = " . $db->quote($order_payment_cardname) . ", " + . " order_payment_number = " . $db->quote($order_payment_number) . ", " + . " order_payment_ccv = " . $db->quote($order_payment_ccv) . ", " + . " order_payment_expire = " . $db->quote($order_payment_expire) . ", " + . " order_payment_trans_id = " . $db->quote($payment_transaction_id) . " " + . " WHERE order_id = " . (int)$order_id; + + return $db->setQuery($payment_update)->execute(); + } } diff --git a/component/site/models/orders.php b/component/site/models/orders.php index 5916a82a623..576a06d05c9 100644 --- a/component/site/models/orders.php +++ b/component/site/models/orders.php @@ -19,72 +19,70 @@ */ class RedshopModelOrders extends RedshopModel { - public $_id = null; + public $_id = null; - public $_data = null; + public $_data = null; - public $_table_prefix = null; + public $_table_prefix = null; - public $_template = null; + public $_template = null; - public $_limitstart = null; + public $_limitstart = null; - public $_limit = null; + public $_limit = null; - public function __construct() - { - global $context; + public function __construct() + { + global $context; - parent::__construct(); + parent::__construct(); - $app = JFactory::getApplication(); + $app = JFactory::getApplication(); - $this->_table_prefix = '#__redshop_'; - $this->_limitstart = $app->input->get('limitstart', 0); - $this->_limit = $app->getUserStateFromRequest($context . 'limit', 'limit', 10, 'int'); - } + $this->_table_prefix = '#__redshop_'; + $this->_limitstart = $app->input->get('limitstart', 0); + $this->_limit = $app->getUserStateFromRequest($context . 'limit', 'limit', 10, 'int'); + } - public function _buildQuery() - { - $user = JFactory::getUser(); - $db = $this->getDbo(); - $query = $db->getQuery(true); + public function getData() + { + $query = $this->_buildQuery(); + $this->_data = $this->_getList($query, $this->_limitstart, $this->_limit); - $query->select('*'); - $query->from($this->_table_prefix . "orders"); - $query->where('user_id = ' . (int) $user->id); - $query->order('cdate DESC'); + return $this->_data; + } - return $query; - } + public function _buildQuery() + { + $user = JFactory::getUser(); + $db = $this->getDbo(); + $query = $db->getQuery(true); - public function getData() - { - $query = $this->_buildQuery(); - $this->_data = $this->_getList($query, $this->_limitstart, $this->_limit); + $query->select('*'); + $query->from($this->_table_prefix . "orders"); + $query->where('user_id = ' . (int)$user->id); + $query->order('cdate DESC'); - return $this->_data; - } + return $query; + } - public function getPagination() - { - if (empty($this->_pagination)) - { - JLoader::import('joomla.html.pagination'); - $this->_pagination = new JPagination($this->getTotal(), $this->_limitstart, $this->_limit); - } + public function getPagination() + { + if (empty($this->_pagination)) { + JLoader::import('joomla.html.pagination'); + $this->_pagination = new JPagination($this->getTotal(), $this->_limitstart, $this->_limit); + } - return $this->_pagination; - } + return $this->_pagination; + } - public function getTotal() - { - if (empty($this->_total)) - { - $query = $this->_buildQuery(); - $this->_total = $this->_getListCount($query); - } + public function getTotal() + { + if (empty($this->_total)) { + $query = $this->_buildQuery(); + $this->_total = $this->_getListCount($query); + } - return $this->_total; - } + return $this->_total; + } } diff --git a/component/site/models/ordertracker.php b/component/site/models/ordertracker.php index b1f770ccff6..c90d9e7410b 100644 --- a/component/site/models/ordertracker.php +++ b/component/site/models/ordertracker.php @@ -18,18 +18,18 @@ */ class RedshopModelOrdertracker extends RedshopModel { - public $_id = null; + public $_id = null; - public $_data = null; + public $_data = null; - public $_table_prefix = null; + public $_table_prefix = null; - public $_template = null; + public $_template = null; - public function __construct() - { - parent::__construct(); + public function __construct() + { + parent::__construct(); - $this->_table_prefix = '#__redshop_'; - } + $this->_table_prefix = '#__redshop_'; + } } diff --git a/component/site/models/price_filter.php b/component/site/models/price_filter.php index 2e2f05974fb..34fb9f6bf6a 100644 --- a/component/site/models/price_filter.php +++ b/component/site/models/price_filter.php @@ -19,28 +19,27 @@ */ class RedshopModelPrice_Filter extends RedshopModel { - /** - * Method to get an array of data items. - * - * @return mixed An array of data items on success, false on failure. - * - * @since 1.5 - */ - public function getData() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('DISTINCT(p.product_id), p.*') - ->from($db->qn('#__redshop_product', 'p')) - ->where('p.published = 1') - ->order('p.product_price'); + /** + * Method to get an array of data items. + * + * @return mixed An array of data items on success, false on failure. + * + * @since 1.5 + */ + public function getData() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('DISTINCT(p.product_id), p.*') + ->from($db->qn('#__redshop_product', 'p')) + ->where('p.published = 1') + ->order('p.product_price'); - if ($category = JFactory::getApplication()->input->getString('category', 0)) - { - $query->leftJoin($db->qn('#__redshop_product_category_xref', 'cx') . ' ON cx.product_id = p.product_id') - ->where($db->qn('cx.category_id') . ' IN ('. $category .')'); - } + if ($category = JFactory::getApplication()->input->getString('category', 0)) { + $query->leftJoin($db->qn('#__redshop_product_category_xref', 'cx') . ' ON cx.product_id = p.product_id') + ->where($db->qn('cx.category_id') . ' IN (' . $category . ')'); + } - return $db->setQuery($query)->loadObjectList(); - } + return $db->setQuery($query)->loadObjectList(); + } } diff --git a/component/site/models/product.php b/component/site/models/product.php index 68d8884b926..35f87562674 100644 --- a/component/site/models/product.php +++ b/component/site/models/product.php @@ -21,533 +21,533 @@ */ class RedshopModelProduct extends RedshopModel { - /** - * @var null - */ - public $_id = null; - - public $_data = null; - - /** - * Product data - */ - public $_product = null; - - public $_table_prefix = null; - - public $_template = null; - - public $_catid = null; - - protected $input; - - public function __construct() - { - parent::__construct(); - - $this->input = JFactory::getApplication()->input; - - $this->_table_prefix = '#__redshop_'; - $pid = $this->input->getInt('pid', 0); - - $GLOBALS['childproductlist'] = array(); - - $this->setId((int)$pid); - $this->_catid = $this->input->getInt('cid', 0); - } - - public function setId($id) - { - $this->_id = $id; - $this->_data = null; - } - - public function getData() - { - if (empty($this->_data)) { - $this->_db->setQuery($this->_buildQuery(), 0, 1); - $this->_data = $this->_db->loadObject(); - } - - if (is_object($this->_data)) { - $this->_data->product_s_desc = RedshopHelperTemplate::parseRedshopPlugin($this->_data->product_s_desc); - $this->_data->product_desc = RedshopHelperTemplate::parseRedshopPlugin($this->_data->product_desc); - } - - return $this->_data; - } - - public function _buildQuery() - { - // Shopper group - choose from manufactures Start - $shopperGroupManufactures = RedshopHelperShopper_Group::getShopperGroupManufacturers(); - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('p.*') - ->select($db->qn('c.id', 'category_id')) - ->select($db->qn('c.name', 'category_name')) - ->select($db->qn('c.category_full_image')) - ->select($db->qn('c.category_back_full_image')) - ->select($db->qn('m.name', 'manufacturer_name')) - ->select($db->qn('pcx.ordering')) - ->select($db->qn('ppx.payment_id')) - ->from($db->qn('#__redshop_product', 'p')) - ->leftjoin( - $db->qn('#__redshop_product_category_xref', 'pcx') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn( - 'pcx.product_id' - ) - ) - ->leftjoin( - $db->qn('#__redshop_manufacturer', 'm') . ' ON ' . $db->qn('m.id') . ' = ' . $db->qn( - 'p.manufacturer_id' - ) - ) - ->leftjoin( - $db->qn('#__redshop_category', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('pcx.category_id') - ) - ->leftjoin( - $db->qn('#__redshop_product_payment_xref', 'ppx') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn( - 'ppx.product_id' - ) - ) - ->where($db->qn('p.product_id') . ' = ' . $db->q((int)$this->_id)); - - if (!empty($shopperGroupManufactures)) { - $shopperGroupManufactures = explode(',', $shopperGroupManufactures); - $shopperGroupManufactures = ArrayHelper::toInteger($shopperGroupManufactures); - $shopperGroupManufactures = implode(',', $shopperGroupManufactures); - $query->where($db->qn('p.manufacturer_id') . ' IN (' . $shopperGroupManufactures . ')'); - } - - // Shopper group - choose from manufactures End - - return $query; - } - - public function getProductTemplate() - { - if (empty($this->_template)) { - $this->_template = RedshopHelperTemplate::getTemplate("product", $this->_data->product_template); - $this->_template = $this->_template[0]; - } - - return $this->_template; - } - - /** - * get next or previous product using ordering. - * - * @param int $productId current product id - * @param int $category_id current product category id - * @param int $dirn to indicate next or previous product - * - * @return mixed - * @deprecated use Redshop\Product\Product::getPrevNextproduct - */ - public function getPrevNextproduct($productId, $category_id, $dirn) - { - return Redshop\Product\Product::getPrevNextproduct($productId, $category_id, $dirn); - } - - public function checkReview($email) - { - $db = JFactory::getDbo(); - $query = "SELECT email from " . $this->_table_prefix . "product_rating WHERE email = " . $db->quote( - $email - ) . " AND email != '' AND product_id = " . (int)$productId . " limit 0,1 "; - $db->setQuery($query); - $chkemail = $db->loadResult(); - - if ($chkemail) { - return true; - } - - return false; - } - - public function sendMailForReview($data) - { - $user = JFactory::getUser(); - $data['userid'] = $user->id; - - $data['user_rating'] = $data['user_rating']; - $data['username'] = $data['username']; - $data['title'] = $data['title']; - $data['comment'] = $data['comment']; - $data['product_id'] = $data['product_id']; - $data['published'] = 0; - $data['time'] = $data['time']; - - $row = $this->getTable('rating_detail'); - - if (!$row->bind($data)) { - /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - if (!$row->store()) { - /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - $user = JFactory::getUser(); - - $url = JURI::base(); - $Itemid = $this->input->get('Itemid'); - $mailbcc = null; - $fromname = $data['username']; - $from = $user->email; - $subject = ""; - $message = $data['title']; - $comment = $data['comment']; - $username = $data['username']; - $productId = $data['product_id']; - - $mailbody = Redshop\Mail\Helper::getTemplate(0, "review_mail"); - - $data_add = $message; - - if (count($mailbody) > 0) { - $data_add = $mailbody[0]->mail_body; - $subject = $mailbody[0]->mail_subject; - - if (trim($mailbody[0]->mail_bcc) != "") { - $mailbcc = explode(",", $mailbody[0]->mail_bcc); - } - } - - $product = \Redshop\Product\Product::getProductById($productId); - - $link = JRoute::_( - $url . "index.php?option=com_redshop&view=product&pid=" . $productId . '&Itemid=' . $Itemid - ); - $product_url = "" . $product->product_name . ""; - $data_add = str_replace("{product_link}", $product_url, $data_add); - $data_add = str_replace("{product_name}", $product->product_name, $data_add); - $data_add = str_replace("{title}", $message, $data_add); - $data_add = str_replace("{comment}", $comment, $data_add); - $data_add = str_replace("{username}", $username, $data_add); - - Redshop\Mail\Helper::imgInMail($data_add); - - if (Redshop::getConfig()->get('ADMINISTRATOR_EMAIL') != "") { - $sendto = explode(",", Redshop::getConfig()->get('ADMINISTRATOR_EMAIL')); - - if (JFactory::getMailer()->sendMail( - $from, - $fromname, - $sendto, - $subject, - $data_add, - $mode = 1, - null, - $mailbcc - )) { - return true; - } else { - return false; - } - } - } - - /** - * Product Tags Functions - */ - public function getProductTags($tagname, $productid) - { - $query = "SELECT pt.*,ptx.product_id,ptx.users_id " - . "FROM " . $this->_table_prefix . "product_tags AS pt " - . "LEFT JOIN " . $this->_table_prefix . "product_tags_xref AS ptx ON pt.tags_id=ptx.tags_id " - . "WHERE pt.tags_name LIKE " . /** @scrutinizer ignore-type */ - $this->_db->quote($tagname) . " "; - $this->_db->setQuery($query); - $list = $this->_db->loadObjectlist(); - - return $list; - } - - public function updateVisited($productId) - { - $query = "UPDATE " . $this->_table_prefix . "product " - . "SET visited=visited + 1 " - . "WHERE product_id = " . (int)$productId; - $this->_db->setQuery($query); - $this->_db->execute(); - } - - public function addProductTags($data) - { - $tags = $this->getTable('product_tags'); - - if (!$tags->bind($data)) { - /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - if (!$tags->store()) { - /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - return $tags; - } - - public function addtowishlist($data) - { - $row = $this->getTable('wishlist'); - - if (!$row->bind($data)) { - /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - if (!$row->store()) { - /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - return $row; - } - - /** - * Method for store wishlist in session. - * - * @param array $data List of data. - * - * @return bool True on success. False otherwise. - */ - public function addtowishlist2session($data) - { - $attributes = null; - $properties = null; - $subAttributes = null; - $session = JFactory::getSession(); - - if (array_key_exists('attribute_id', $data)) { - $attributes = explode('##', $data['attribute_id']); - } - - if (array_key_exists('property_id', $data)) { - $properties = explode('##', $data['property_id']); - } - - if (array_key_exists('subattribute_id', $data)) { - $subAttributes = explode('##', $data['subattribute_id']); - } - - ob_clean(); - $section = 12; - $row_data = RedshopHelperExtrafields::getSectionFieldList($section); - $wishlistSession = $session->get('wishlist'); - - if (!empty($wishlistData) && !Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE')) { - $wishlistSession[$data['product_id']] = null; - } - - $wishlist = new stdClass; - $wishlist->product_id = $data['product_id']; - $wishlist->comment = isset($data ['comment']) ? $data ['comment'] : ""; - $wishlist->cdate = $data['cdate']; - - for ($k = 0, $kn = count($row_data); $k < $kn; $k++) { - $field = "productuserfield_" . $k; - $wishlist->{$field} = $data['productuserfield_' . $k]; - } - - if (!$attributes || !Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE')) { - $wishlistSession[$data['product_id']] = $wishlist; - $session->set('wishlist', $wishlistSession); - - return true; - } - - if (empty($wishlistSession[$data['product_id']]) || !is_array($wishlistSession[$data['product_id']])) { - $wishlistSession[$data['product_id']] = array(); - } - - $wishlist->product_items = array(); - - foreach ($attributes as $index => $attribute) { - $item = new stdClass; - $item->attribute_id = $attribute; - - if (isset($properties[$index])) { - $item->property_id = $properties[$index]; - } - - if (isset($subAttributes[$index])) { - $item->subattribute_id = $subAttributes[$index]; - } - - $wishlist->product_items = $item; - } - - if (!empty($wishlistSession[$data['product_id']])) { - foreach ($wishlistSession[$data['product_id']] as $wishlistItem) { - if ($wishlistItem->product_items == $wishlist->product_items) { - return true; - } - } - } - - $wishlistSession[$data['product_id']][] = $wishlist; - $session->set('wishlist', $wishlistSession); - - return true; - } - - public function addProductTagsXref($post, $tags) - { - $user = JFactory::getUser(); - $query = "INSERT INTO " . $this->_table_prefix . "product_tags_xref " - . "VALUES('" . (int)$tags->tags_id . "','" . (int)$post['product_id'] . "','" . (int)$user->id . "')"; - $this->_db->setQuery($query); - $this->_db->execute(); - - return true; - } - - public function checkProductTags($tagname, $productid) - { - $user = JFactory::getUser(); - $query = "SELECT pt.*,ptx.product_id,ptx.users_id FROM " . $this->_table_prefix . "product_tags AS pt " - . "LEFT JOIN " . $this->_table_prefix . "product_tags_xref AS ptx ON pt.tags_id=ptx.tags_id " - . "WHERE pt.tags_name LIKE " . /** @scrutinizer ignore-type */ - $this->_db->quote($tagname) . " " - . "AND ptx.product_id = " . (int)$productid . " " - . "AND ptx.users_id = " . (int)$user->id; - $this->_db->setQuery($query); - $list = $this->_db->loadObject(); - - return $list; - } - - public function checkWishlist($productId) - { - $user = JFactory::getUser(); - $query = "SELECT * FROM " . $this->_table_prefix . "wishlist " - . "WHERE product_id = " . (int)$productId . " " - . "AND user_id = " . (int)$user->id; - $this->_db->setQuery($query); - $list = $this->_db->loadObject(); - - return $list; - } - - /** - * Get Download product info - * - * @param string $downloadId Download id - * - * @return mixed - */ - public function downloadProduct($downloadId) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_product_download', 'pd')) - ->leftJoin($db->qn('#__redshop_media', 'm') . ' ON m.media_name = pd.file_name') - ->where('pd.download_id = ' . $db->q($downloadId)); - - return $db->setQuery($query)->loadObject(); - } - - public function AdditionaldownloadProduct($mid = 0, $id = 0, $media = 0) - { - $where = ""; - - if ($mid != 0) { - $where .= "AND media_id = " . (int)$mid . " "; - } - - if ($id != 0) { - $where .= "AND id = " . (int)$id . " "; - } - - if ($media != 0) { - $tablename = "media "; - } else { - $tablename = "media_download "; - } - - $query = "SELECT * FROM " . $this->_table_prefix . $tablename - . "WHERE 1=1 " - . $where; - $list = $this->_getList($query); - - return $list; - } - - public function setDownloadLimit($did) - { - $query = "UPDATE " . $this->_table_prefix . "product_download " - . "SET download_max=(download_max - 1) " - . "WHERE download_id = " . (int)$did; - $this->_db->setQuery($query); - $ret = $this->_db->execute(); - - if ($ret) { - return true; - } - - return false; - } - - /** - * Method get all child product - * - * @param integer $childid - * @param integer $parentid - * - * @return mixed - * @deprecated use Redshop\Product\Product::getAllChildProductArrayList - */ - public function getAllChildProductArrayList($childid = 0, $parentid = 0) - { - return Redshop\Product\Product::getAllChildProductArrayList($childid, $parentid); - } - - public function addNotifystock($productId, $propertyId, $subPropertyId, $email_not_login = null) - { - ob_clean(); - $user = JFactory::getUser(); - $user_id = $user->id; - $data = array(); - $data['product_id'] = $productId; - $data['property_id'] = $propertyId; - $data['subproperty_id'] = $subPropertyId; - $data['user_id'] = $user_id; - $data['email_not_login'] = $email_not_login; - $row = $this->getTable('notifystock_user'); - - if (!$row->bind($data)) { - /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - if (!$row->store()) { - /** @scrutinizer ignore-deprecated */ - $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - return true; - } + /** + * @var null + */ + public $_id = null; + + public $_data = null; + + /** + * Product data + */ + public $_product = null; + + public $_table_prefix = null; + + public $_template = null; + + public $_catid = null; + + protected $input; + + public function __construct() + { + parent::__construct(); + + $this->input = JFactory::getApplication()->input; + + $this->_table_prefix = '#__redshop_'; + $pid = $this->input->getInt('pid', 0); + + $GLOBALS['childproductlist'] = array(); + + $this->setId((int)$pid); + $this->_catid = $this->input->getInt('cid', 0); + } + + public function setId($id) + { + $this->_id = $id; + $this->_data = null; + } + + public function getData() + { + if (empty($this->_data)) { + $this->_db->setQuery($this->_buildQuery(), 0, 1); + $this->_data = $this->_db->loadObject(); + } + + if (is_object($this->_data)) { + $this->_data->product_s_desc = RedshopHelperTemplate::parseRedshopPlugin($this->_data->product_s_desc); + $this->_data->product_desc = RedshopHelperTemplate::parseRedshopPlugin($this->_data->product_desc); + } + + return $this->_data; + } + + public function _buildQuery() + { + // Shopper group - choose from manufactures Start + $shopperGroupManufactures = RedshopHelperShopper_Group::getShopperGroupManufacturers(); + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('p.*') + ->select($db->qn('c.id', 'category_id')) + ->select($db->qn('c.name', 'category_name')) + ->select($db->qn('c.category_full_image')) + ->select($db->qn('c.category_back_full_image')) + ->select($db->qn('m.name', 'manufacturer_name')) + ->select($db->qn('pcx.ordering')) + ->select($db->qn('ppx.payment_id')) + ->from($db->qn('#__redshop_product', 'p')) + ->leftjoin( + $db->qn('#__redshop_product_category_xref', 'pcx') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn( + 'pcx.product_id' + ) + ) + ->leftjoin( + $db->qn('#__redshop_manufacturer', 'm') . ' ON ' . $db->qn('m.id') . ' = ' . $db->qn( + 'p.manufacturer_id' + ) + ) + ->leftjoin( + $db->qn('#__redshop_category', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('pcx.category_id') + ) + ->leftjoin( + $db->qn('#__redshop_product_payment_xref', 'ppx') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn( + 'ppx.product_id' + ) + ) + ->where($db->qn('p.product_id') . ' = ' . $db->q((int)$this->_id)); + + if (!empty($shopperGroupManufactures)) { + $shopperGroupManufactures = explode(',', $shopperGroupManufactures); + $shopperGroupManufactures = ArrayHelper::toInteger($shopperGroupManufactures); + $shopperGroupManufactures = implode(',', $shopperGroupManufactures); + $query->where($db->qn('p.manufacturer_id') . ' IN (' . $shopperGroupManufactures . ')'); + } + + // Shopper group - choose from manufactures End + + return $query; + } + + public function getProductTemplate() + { + if (empty($this->_template)) { + $this->_template = RedshopHelperTemplate::getTemplate("product", $this->_data->product_template); + $this->_template = $this->_template[0]; + } + + return $this->_template; + } + + /** + * get next or previous product using ordering. + * + * @param int $productId current product id + * @param int $category_id current product category id + * @param int $dirn to indicate next or previous product + * + * @return mixed + * @deprecated use Redshop\Product\Product::getPrevNextproduct + */ + public function getPrevNextproduct($productId, $category_id, $dirn) + { + return Redshop\Product\Product::getPrevNextproduct($productId, $category_id, $dirn); + } + + public function checkReview($email) + { + $db = JFactory::getDbo(); + $query = "SELECT email from " . $this->_table_prefix . "product_rating WHERE email = " . $db->quote( + $email + ) . " AND email != '' AND product_id = " . (int)$productId . " limit 0,1 "; + $db->setQuery($query); + $chkemail = $db->loadResult(); + + if ($chkemail) { + return true; + } + + return false; + } + + public function sendMailForReview($data) + { + $user = JFactory::getUser(); + $data['userid'] = $user->id; + + $data['user_rating'] = $data['user_rating']; + $data['username'] = $data['username']; + $data['title'] = $data['title']; + $data['comment'] = $data['comment']; + $data['product_id'] = $data['product_id']; + $data['published'] = 0; + $data['time'] = $data['time']; + + $row = $this->getTable('rating_detail'); + + if (!$row->bind($data)) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + if (!$row->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + $user = JFactory::getUser(); + + $url = JURI::base(); + $Itemid = $this->input->get('Itemid'); + $mailbcc = null; + $fromname = $data['username']; + $from = $user->email; + $subject = ""; + $message = $data['title']; + $comment = $data['comment']; + $username = $data['username']; + $productId = $data['product_id']; + + $mailbody = Redshop\Mail\Helper::getTemplate(0, "review_mail"); + + $data_add = $message; + + if (count($mailbody) > 0) { + $data_add = $mailbody[0]->mail_body; + $subject = $mailbody[0]->mail_subject; + + if (trim($mailbody[0]->mail_bcc) != "") { + $mailbcc = explode(",", $mailbody[0]->mail_bcc); + } + } + + $product = \Redshop\Product\Product::getProductById($productId); + + $link = JRoute::_( + $url . "index.php?option=com_redshop&view=product&pid=" . $productId . '&Itemid=' . $Itemid + ); + $product_url = "" . $product->product_name . ""; + $data_add = str_replace("{product_link}", $product_url, $data_add); + $data_add = str_replace("{product_name}", $product->product_name, $data_add); + $data_add = str_replace("{title}", $message, $data_add); + $data_add = str_replace("{comment}", $comment, $data_add); + $data_add = str_replace("{username}", $username, $data_add); + + Redshop\Mail\Helper::imgInMail($data_add); + + if (Redshop::getConfig()->get('ADMINISTRATOR_EMAIL') != "") { + $sendto = explode(",", Redshop::getConfig()->get('ADMINISTRATOR_EMAIL')); + + if (JFactory::getMailer()->sendMail( + $from, + $fromname, + $sendto, + $subject, + $data_add, + $mode = 1, + null, + $mailbcc + )) { + return true; + } else { + return false; + } + } + } + + /** + * Product Tags Functions + */ + public function getProductTags($tagname, $productid) + { + $query = "SELECT pt.*,ptx.product_id,ptx.users_id " + . "FROM " . $this->_table_prefix . "product_tags AS pt " + . "LEFT JOIN " . $this->_table_prefix . "product_tags_xref AS ptx ON pt.tags_id=ptx.tags_id " + . "WHERE pt.tags_name LIKE " . /** @scrutinizer ignore-type */ + $this->_db->quote($tagname) . " "; + $this->_db->setQuery($query); + $list = $this->_db->loadObjectlist(); + + return $list; + } + + public function updateVisited($productId) + { + $query = "UPDATE " . $this->_table_prefix . "product " + . "SET visited=visited + 1 " + . "WHERE product_id = " . (int)$productId; + $this->_db->setQuery($query); + $this->_db->execute(); + } + + public function addProductTags($data) + { + $tags = $this->getTable('product_tags'); + + if (!$tags->bind($data)) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + if (!$tags->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + return $tags; + } + + public function addtowishlist($data) + { + $row = $this->getTable('wishlist'); + + if (!$row->bind($data)) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + if (!$row->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + return $row; + } + + /** + * Method for store wishlist in session. + * + * @param array $data List of data. + * + * @return bool True on success. False otherwise. + */ + public function addtowishlist2session($data) + { + $attributes = null; + $properties = null; + $subAttributes = null; + $session = JFactory::getSession(); + + if (array_key_exists('attribute_id', $data)) { + $attributes = explode('##', $data['attribute_id']); + } + + if (array_key_exists('property_id', $data)) { + $properties = explode('##', $data['property_id']); + } + + if (array_key_exists('subattribute_id', $data)) { + $subAttributes = explode('##', $data['subattribute_id']); + } + + ob_clean(); + $section = 12; + $row_data = RedshopHelperExtrafields::getSectionFieldList($section); + $wishlistSession = $session->get('wishlist'); + + if (!empty($wishlistData) && !Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE')) { + $wishlistSession[$data['product_id']] = null; + } + + $wishlist = new stdClass; + $wishlist->product_id = $data['product_id']; + $wishlist->comment = isset($data ['comment']) ? $data ['comment'] : ""; + $wishlist->cdate = $data['cdate']; + + for ($k = 0, $kn = count($row_data); $k < $kn; $k++) { + $field = "productuserfield_" . $k; + $wishlist->{$field} = $data['productuserfield_' . $k]; + } + + if (!$attributes || !Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE')) { + $wishlistSession[$data['product_id']] = $wishlist; + $session->set('wishlist', $wishlistSession); + + return true; + } + + if (empty($wishlistSession[$data['product_id']]) || !is_array($wishlistSession[$data['product_id']])) { + $wishlistSession[$data['product_id']] = array(); + } + + $wishlist->product_items = array(); + + foreach ($attributes as $index => $attribute) { + $item = new stdClass; + $item->attribute_id = $attribute; + + if (isset($properties[$index])) { + $item->property_id = $properties[$index]; + } + + if (isset($subAttributes[$index])) { + $item->subattribute_id = $subAttributes[$index]; + } + + $wishlist->product_items = $item; + } + + if (!empty($wishlistSession[$data['product_id']])) { + foreach ($wishlistSession[$data['product_id']] as $wishlistItem) { + if ($wishlistItem->product_items == $wishlist->product_items) { + return true; + } + } + } + + $wishlistSession[$data['product_id']][] = $wishlist; + $session->set('wishlist', $wishlistSession); + + return true; + } + + public function addProductTagsXref($post, $tags) + { + $user = JFactory::getUser(); + $query = "INSERT INTO " . $this->_table_prefix . "product_tags_xref " + . "VALUES('" . (int)$tags->tags_id . "','" . (int)$post['product_id'] . "','" . (int)$user->id . "')"; + $this->_db->setQuery($query); + $this->_db->execute(); + + return true; + } + + public function checkProductTags($tagname, $productid) + { + $user = JFactory::getUser(); + $query = "SELECT pt.*,ptx.product_id,ptx.users_id FROM " . $this->_table_prefix . "product_tags AS pt " + . "LEFT JOIN " . $this->_table_prefix . "product_tags_xref AS ptx ON pt.tags_id=ptx.tags_id " + . "WHERE pt.tags_name LIKE " . /** @scrutinizer ignore-type */ + $this->_db->quote($tagname) . " " + . "AND ptx.product_id = " . (int)$productid . " " + . "AND ptx.users_id = " . (int)$user->id; + $this->_db->setQuery($query); + $list = $this->_db->loadObject(); + + return $list; + } + + public function checkWishlist($productId) + { + $user = JFactory::getUser(); + $query = "SELECT * FROM " . $this->_table_prefix . "wishlist " + . "WHERE product_id = " . (int)$productId . " " + . "AND user_id = " . (int)$user->id; + $this->_db->setQuery($query); + $list = $this->_db->loadObject(); + + return $list; + } + + /** + * Get Download product info + * + * @param string $downloadId Download id + * + * @return mixed + */ + public function downloadProduct($downloadId) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_product_download', 'pd')) + ->leftJoin($db->qn('#__redshop_media', 'm') . ' ON m.media_name = pd.file_name') + ->where('pd.download_id = ' . $db->q($downloadId)); + + return $db->setQuery($query)->loadObject(); + } + + public function AdditionaldownloadProduct($mid = 0, $id = 0, $media = 0) + { + $where = ""; + + if ($mid != 0) { + $where .= "AND media_id = " . (int)$mid . " "; + } + + if ($id != 0) { + $where .= "AND id = " . (int)$id . " "; + } + + if ($media != 0) { + $tablename = "media "; + } else { + $tablename = "media_download "; + } + + $query = "SELECT * FROM " . $this->_table_prefix . $tablename + . "WHERE 1=1 " + . $where; + $list = $this->_getList($query); + + return $list; + } + + public function setDownloadLimit($did) + { + $query = "UPDATE " . $this->_table_prefix . "product_download " + . "SET download_max=(download_max - 1) " + . "WHERE download_id = " . (int)$did; + $this->_db->setQuery($query); + $ret = $this->_db->execute(); + + if ($ret) { + return true; + } + + return false; + } + + /** + * Method get all child product + * + * @param integer $childid + * @param integer $parentid + * + * @return mixed + * @deprecated use Redshop\Product\Product::getAllChildProductArrayList + */ + public function getAllChildProductArrayList($childid = 0, $parentid = 0) + { + return Redshop\Product\Product::getAllChildProductArrayList($childid, $parentid); + } + + public function addNotifystock($productId, $propertyId, $subPropertyId, $email_not_login = null) + { + ob_clean(); + $user = JFactory::getUser(); + $user_id = $user->id; + $data = array(); + $data['product_id'] = $productId; + $data['property_id'] = $propertyId; + $data['subproperty_id'] = $subPropertyId; + $data['user_id'] = $user_id; + $data['email_not_login'] = $email_not_login; + $row = $this->getTable('notifystock_user'); + + if (!$row->bind($data)) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + if (!$row->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + return true; + } } diff --git a/component/site/models/product_mini.php b/component/site/models/product_mini.php index 2ff870f6716..5788d0cdcc4 100644 --- a/component/site/models/product_mini.php +++ b/component/site/models/product_mini.php @@ -34,10 +34,10 @@ public function __construct() global $context; parent::__construct(); - $app = \JFactory::getApplication(); + $app = \JFactory::getApplication(); $context = 'p.product_id'; - $limit = $app->getUserStateFromRequest($context . 'limit', 'limit', $app->getCfg('list_limit'), 0); + $limit = $app->getUserStateFromRequest($context . 'limit', 'limit', $app->getCfg('list_limit'), 0); $limitStart = $app->getUserStateFromRequest($context . 'limitstart', 'limitstart', 0); $this->setState('limit', $limit); @@ -51,7 +51,7 @@ public function __construct() public function getData() { if (empty($this->_data)) { - $query = $this->_buildQuery(); + $query = $this->_buildQuery(); $this->_data = $this->_getList($query); } @@ -59,22 +59,44 @@ public function getData() } /** - * @return int|mixed|null + * @return JDatabaseQuery|string|null * @throws Exception */ - public function getTotal() + public function _buildQuery() { global $context; - $app = \JFactory::getApplication(); + $app = JFactory::getApplication(); + + $orderBy = $this->_buildContentOrderBy(); $searchField = $app->getUserStateFromRequest($context . 'search_field', 'search_field', ''); - $keyword = $app->getUserStateFromRequest($context . 'keyword', 'keyword', ''); - $categoryId = $app->getUserStateFromRequest($context . 'category_id', 'category_id', 0); + $keyword = $app->getUserStateFromRequest($context . 'keyword', 'keyword', ''); + $categoryId = $app->getUserStateFromRequest($context . 'category_id', 'category_id', 0); + $limit = $this->getState('limit'); - if (empty($this->_total)) { - $this->_total = \Redshop\Product\Mini::getCountDistinctProduct($keyword, $categoryId, $searchField); + return \Redshop\Product\Mini::getQueryObject($keyword, $categoryId, $searchField, $limit, $orderBy); + } + + /** + * @return string + * @throws Exception + */ + public function _buildContentOrderBy() + { + global $context; + $app = \JFactory::getApplication(); + $db = \JFactory::getDbo(); + $filterOrder = urldecode( + $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'p.product_id') + ); + $filterOrderDir = urldecode( + $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', '') + ); + + if ($filterOrder == 'product_id') { + $filterOrder = 'p.product_id'; } - return $this->_total; + return $db->escape($filterOrder . ' ' . $filterOrderDir); } /** @@ -83,47 +105,31 @@ public function getTotal() public function getPagination() { if (empty($this->_pagination)) { - $this->_pagination = new \JPagination($this->getTotal(), - $this->getState('limitstart'), $this->getState('limit')); + $this->_pagination = new \JPagination( + $this->getTotal(), + $this->getState('limitstart'), $this->getState('limit') + ); } return $this->_pagination; } /** - * @return JDatabaseQuery|string|null + * @return int|mixed|null * @throws Exception */ - public function _buildQuery() + public function getTotal() { global $context; - $app = JFactory::getApplication(); - - $orderBy = $this->_buildContentOrderBy(); + $app = \JFactory::getApplication(); $searchField = $app->getUserStateFromRequest($context . 'search_field', 'search_field', ''); - $keyword = $app->getUserStateFromRequest($context . 'keyword', 'keyword', ''); - $categoryId = $app->getUserStateFromRequest($context . 'category_id', 'category_id', 0); - $limit = $this->getState('limit'); + $keyword = $app->getUserStateFromRequest($context . 'keyword', 'keyword', ''); + $categoryId = $app->getUserStateFromRequest($context . 'category_id', 'category_id', 0); - return \Redshop\Product\Mini::getQueryObject($keyword, $categoryId, $searchField, $limit, $orderBy); - } - - /** - * @return string - * @throws Exception - */ - public function _buildContentOrderBy() - { - global $context; - $app = \JFactory::getApplication(); - $db = \JFactory::getDbo(); - $filterOrder = urldecode($app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'p.product_id')); - $filterOrderDir = urldecode($app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', '')); - - if ($filterOrder == 'product_id') { - $filterOrder = 'p.product_id'; + if (empty($this->_total)) { + $this->_total = \Redshop\Product\Mini::getCountDistinctProduct($keyword, $categoryId, $searchField); } - return $db->escape($filterOrder . ' ' . $filterOrderDir); + return $this->_total; } } diff --git a/component/site/models/product_rating.php b/component/site/models/product_rating.php index 63c5dd3201f..f1899e71239 100644 --- a/component/site/models/product_rating.php +++ b/component/site/models/product_rating.php @@ -18,174 +18,181 @@ */ class RedshopModelProduct_Rating extends RedshopModelForm { - /** - * Constructor. - * - * @param array $config Configuration array - * - * @throws RuntimeException - */ - public function __construct($config = array()) - { - parent::__construct($config); - - if (array_key_exists('context', $config)) - { - $this->context = $config['context']; - } - else - { - $this->context = $this->context . '.' . JFactory::getApplication()->input->getInt('product_id', 0); - } - } - - /** - * Method to get the record form. - * - * @param array $data Data for the form. - * @param boolean $loadData True if the form is to load its own data (default case), false if not. - * - * @return mixed A JForm object on success, false on failure - * - * @since 1.5 - */ - public function getForm($data = array(), $loadData = true) - { - // Get the form. - $form = $this->loadForm($this->context . '.' . $this->formName, $this->formName, array('control' => 'jform', 'load_data' => $loadData)); - - if (empty($form)) - { - return false; - } - - return $form; - } - - /** - * Method to get the data that should be injected in the form. - * - * @return array The default data is an empty array. - * - * @since 1.5 - */ - protected function loadFormData() - { - $data = (array) JFactory::getApplication()->getUserState($this->context . '.data', array()); - - return $data; - } - - /** - * Method to store the records - * - * @param array $data array of data - * - * @return bool - */ - public function store($data) - { - $row = $this->getTable('rating_detail'); - - if (!$row->bind($data)) - { - $this->setError($this->_db->getErrorMsg()); - - return false; - } - - if (!$row->store()) - { - $this->setError($this->_db->getErrorMsg()); - - return false; - } - - return true; - } - - /** - * Send Mail For Ask Review - * - * @param array $data Review data - * - * @return boolean - */ - public function sendMailForReview($data) - { - if (!$this->store($data)) - { - return false; - } - - $mailbcc = null; - $subject = ""; - $mailbody = Redshop\Mail\Helper::getTemplate(0, "review_mail"); - $data_add = $data['title']; - - if (count($mailbody) > 0) - { - $data_add = $mailbody[0]->mail_body; - $subject = $mailbody[0]->mail_subject; - - if (trim($mailbody[0]->mail_bcc) != "") - { - $mailbcc = explode(",", $mailbody[0]->mail_bcc); - } - } - - $product = \Redshop\Product\Product::getProductById($data['product_id']); - $link = JRoute::_(JURI::base() . "index.php?option=com_redshop&view=product&pid=" . $data['product_id'] . '&Itemid=' . $data['Itemid'], false); - $data_add = str_replace("{product_link}", "" . $product->product_name . "", $data_add); - $data_add = str_replace("{product_name}", $product->product_name, $data_add); - $data_add = str_replace("{title}", $data['title'], $data_add); - $data_add = str_replace("{comment}", $data['comment'], $data_add); - $data_add = str_replace("{username}", $data['username'], $data_add); - - Redshop\Mail\Helper::imgInMail($data_add); - - if (Redshop::getConfig()->get('ADMINISTRATOR_EMAIL') != "") - { - $sendto = explode(",", Redshop::getConfig()->get('ADMINISTRATOR_EMAIL')); - - if (JFactory::getMailer()->sendMail($data['email'], $data['username'], $sendto, $subject, $data_add, $mode = 1, null, $mailbcc)) - { - return true; - } - else - { - $this->setError(JText::_('COM_REDSHOP_EMAIL_HAS_NOT_BEEN_SENT_SUCCESSFULLY')); - - return false; - } - } - - return true; - } - - /** - * Check Rated Product - * - * @param int $pid Product id - * @param int $uid User id - * @param string $email User mail - * - * @return mixed - */ - public function checkRatedProduct($pid, $uid = 0, $email = '') - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('COUNT(rating_id)') - ->from($db->qn('#__redshop_product_rating')) - ->where('product_id = ' . (int) $pid) - ->where('userid = ' . (int) $uid); - - if ($email) - { - $query->where('email = ' . $db->q($email)); - } - - return $db->setQuery($query)->loadResult(); - } + /** + * Constructor. + * + * @param array $config Configuration array + * + * @throws RuntimeException + */ + public function __construct($config = array()) + { + parent::__construct($config); + + if (array_key_exists('context', $config)) { + $this->context = $config['context']; + } else { + $this->context = $this->context . '.' . JFactory::getApplication()->input->getInt('product_id', 0); + } + } + + /** + * Method to get the record form. + * + * @param array $data Data for the form. + * @param boolean $loadData True if the form is to load its own data (default case), false if not. + * + * @return mixed A JForm object on success, false on failure + * + * @since 1.5 + */ + public function getForm($data = array(), $loadData = true) + { + // Get the form. + $form = $this->loadForm( + $this->context . '.' . $this->formName, + $this->formName, + array('control' => 'jform', 'load_data' => $loadData) + ); + + if (empty($form)) { + return false; + } + + return $form; + } + + /** + * Send Mail For Ask Review + * + * @param array $data Review data + * + * @return boolean + */ + public function sendMailForReview($data) + { + if (!$this->store($data)) { + return false; + } + + $mailbcc = null; + $subject = ""; + $mailbody = Redshop\Mail\Helper::getTemplate(0, "review_mail"); + $data_add = $data['title']; + + if (count($mailbody) > 0) { + $data_add = $mailbody[0]->mail_body; + $subject = $mailbody[0]->mail_subject; + + if (trim($mailbody[0]->mail_bcc) != "") { + $mailbcc = explode(",", $mailbody[0]->mail_bcc); + } + } + + $product = \Redshop\Product\Product::getProductById($data['product_id']); + $link = JRoute::_( + JURI::base( + ) . "index.php?option=com_redshop&view=product&pid=" . $data['product_id'] . '&Itemid=' . $data['Itemid'], + false + ); + $data_add = str_replace( + "{product_link}", + "" . $product->product_name . "", + $data_add + ); + $data_add = str_replace("{product_name}", $product->product_name, $data_add); + $data_add = str_replace("{title}", $data['title'], $data_add); + $data_add = str_replace("{comment}", $data['comment'], $data_add); + $data_add = str_replace("{username}", $data['username'], $data_add); + + Redshop\Mail\Helper::imgInMail($data_add); + + if (Redshop::getConfig()->get('ADMINISTRATOR_EMAIL') != "") { + $sendto = explode(",", Redshop::getConfig()->get('ADMINISTRATOR_EMAIL')); + + if (JFactory::getMailer()->sendMail( + $data['email'], + $data['username'], + $sendto, + $subject, + $data_add, + $mode = 1, + null, + $mailbcc + )) { + return true; + } else { + $this->setError(JText::_('COM_REDSHOP_EMAIL_HAS_NOT_BEEN_SENT_SUCCESSFULLY')); + + return false; + } + } + + return true; + } + + /** + * Method to store the records + * + * @param array $data array of data + * + * @return bool + */ + public function store($data) + { + $row = $this->getTable('rating_detail'); + + if (!$row->bind($data)) { + $this->setError($this->_db->getErrorMsg()); + + return false; + } + + if (!$row->store()) { + $this->setError($this->_db->getErrorMsg()); + + return false; + } + + return true; + } + + /** + * Check Rated Product + * + * @param int $pid Product id + * @param int $uid User id + * @param string $email User mail + * + * @return mixed + */ + public function checkRatedProduct($pid, $uid = 0, $email = '') + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('COUNT(rating_id)') + ->from($db->qn('#__redshop_product_rating')) + ->where('product_id = ' . (int)$pid) + ->where('userid = ' . (int)$uid); + + if ($email) { + $query->where('email = ' . $db->q($email)); + } + + return $db->setQuery($query)->loadResult(); + } + + /** + * Method to get the data that should be injected in the form. + * + * @return array The default data is an empty array. + * + * @since 1.5 + */ + protected function loadFormData() + { + $data = (array)JFactory::getApplication()->getUserState($this->context . '.data', array()); + + return $data; + } } diff --git a/component/site/models/quotation.php b/component/site/models/quotation.php index 73e2737f5f4..94aa51ae2d0 100644 --- a/component/site/models/quotation.php +++ b/component/site/models/quotation.php @@ -18,639 +18,634 @@ */ class RedshopModelQuotation extends RedshopModel { - public $_id = null; - - public $_data = null; - - public $_table_prefix = null; - - public function __construct() - { - parent::__construct(); - - $this->_table_prefix = '#__redshop_'; - } - - public function &getData() - { - if (!$this->_loadData()) - { - $this->_initData(); - } - - return $this->_data; - } - - public function _loadData() - { - $user = JFactory::getUser(); - - if ($user->id) - { - $this->_data = RedshopHelperOrder::getBillingAddress($user->id); - $this->_data->user_info_id = $this->_data->users_info_id; - - return true; - } - - return false; - } - - public function _initData() - { - $detail = new stdClass; - $detail->user_info_id = 0; - $detail->user_id = 0; - $detail->firstname = null; - $detail->lastname = null; - $detail->address = null; - $detail->zipcode = null; - $detail->city = null; - $detail->country_code = null; - $detail->state_code = null; - $detail->phone = null; - $detail->user_email = null; - $detail->is_company = null; - $detail->vat_number = null; - $detail->requesting_tax_exempt = 0; - $detail->tax_exempt = null; - $this->_data = $detail; - } - - public function store($data, $post) - { - $this->_loadData(); - $user = JFactory::getUser(); - $user_id = 0; - $user_info_id = 0; - $user_email = $post['user_email']; - - if ($user->id) - { - $user_id = $user->id; - $user_info_id = $this->_data->user_info_id; - $user_email = $user->email; - } - - $res = $this->getUserIdByEmail($user_email); - - if ($res > 0) - { - $user_id = $res->user_id; - $user_info_id = $res->users_info_id; - } - - $data['quotation_number'] = RedshopHelperQuotation::generateQuotationNumber(); - $data['user_id'] = $user_id; - $data['user_info_id'] = $user_info_id; - $data['user_email'] = $user_email; - $data['quotation_total'] = $data['total']; - $data['quotation_subtotal'] = $data['subtotal']; - $data['quotation_tax'] = $data['tax']; - $data['quotation_status'] = 1; - $data['quotation_cdate'] = time(); - $data['quotation_mdate'] = time(); - $data['quotation_note'] = $data['quotation_note']; - $data['quotation_ipaddress'] = $_SERVER ['REMOTE_ADDR']; - $data['quotation_encrkey'] = RedshopHelperQuotation::randomQuotationEncryptKey(); - $data['quotation_discount'] = (isset($data['discount2'])) ? $data['discount2'] : 0; - - $totalitem = $data['idx']; - $quotation_item = array(); - - $row = $this->getTable('quotation_detail'); - - if (!$row->bind($data)) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - if (!$row->store()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - for ($i = 0; $i < $totalitem; $i++) - { - $rowitem = $this->getTable('quotation_item_detail'); - $quotation_item[$i] = new stdClass; - $quotation_item[$i]->quotation_id = $row->quotation_id; - - if (isset($data[$i]['giftcard_id']) && $data[$i]['giftcard_id'] != 0) - { - $quotation_item[$i]->product_id = $data[$i]['giftcard_id']; - - $giftcardData = RedshopEntityGiftcard::getInstance($data[$i]['giftcard_id'])->getItem(); - - $quotation_item[$i]->is_giftcard = 1; - $quotation_item[$i]->product_name = $giftcardData->giftcard_name; - $section = 13; - } - else - { - $product = \Redshop\Product\Product::getProductById($data[$i]['product_id']); - - $retAttArr = RedshopHelperProduct::makeAttributeCart($data[$i]['cart_attribute'], $data[$i]['product_id'], 0, 0, $data[$i]['quantity']); - $cart_attribute = $retAttArr[0]; - - $retAccArr = RedshopHelperProduct::makeAccessoryCart($data[$i]['cart_accessory'], $data[$i]['product_id']); - $cart_accessory = $retAccArr[0]; - - $quotation_item[$i]->product_id = $data[$i]['product_id']; - $quotation_item[$i]->is_giftcard = 0; - $quotation_item[$i]->product_name = $product->product_name; - $quotation_item[$i]->actualitem_price = $data[$i]['product_price']; - $quotation_item[$i]->product_price = $data[$i]['product_price']; - $quotation_item[$i]->product_excl_price = $data[$i]['product_price_excl_vat']; - $quotation_item[$i]->product_final_price = $data[$i]['product_price'] * $data[$i]['quantity']; - $quotation_item[$i]->product_attribute = $cart_attribute; - $quotation_item[$i]->product_accessory = $cart_accessory; - $quotation_item[$i]->product_wrapperid = $data[$i]['wrapper_id']; - $quotation_item[$i]->wrapper_price = $data[$i]['wrapper_price']; - - $section = 12; - } - - $quotation_item[$i]->product_quantity = $data[$i]['quantity']; - - if (!$rowitem->bind($quotation_item[$i])) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - if (!$rowitem->store()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - /** my accessory save in table start */ - if (count($data[$i]['cart_accessory']) > 0) - { - $attArr = $data [$i] ['cart_accessory']; - - for ($a = 0, $an = count($attArr); $a < $an; $a++) - { - $accessory_vat_price = 0; - $accessory_attribute = ""; - $accessoryId = $attArr[$a]['accessory_id']; - $accessory_name = $attArr[$a]['accessory_name']; - $accessory_price = $attArr[$a]['accessory_price']; - $accessory_org_price = $accessory_price; - - if ($accessory_price > 0) - { - $accessory_vat_price = RedshopHelperProduct::getProductTax($rowitem->product_id, $accessory_price); - } - - $attchildArr = $attArr[$a]['accessory_childs']; - - for ($j = 0, $jn = count($attchildArr); $j < $jn; $j++) - { - $attributeId = $attchildArr[$j]['attribute_id']; - $accessory_attribute .= urldecode($attchildArr[$j]['attribute_name']) . ":
    "; - - $rowattitem = $this->getTable('quotation_attribute_item'); - $rowattitem->quotation_att_item_id = 0; - $rowattitem->quotation_item_id = $rowitem->quotation_item_id; - $rowattitem->section_id = $attributeId; - $rowattitem->section = "attribute"; - $rowattitem->parent_section_id = $accessoryId; - $rowattitem->section_name = $attchildArr[$j]['attribute_name']; - $rowattitem->is_accessory_att = 1; - - if ($attributeId > 0) - { - if (!$rowattitem->store()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - } - - - $propArr = $attchildArr[$j]['attribute_childs']; - - for ($k = 0, $kn = count($propArr); $k < $kn; $k++) - { - $section_vat = RedshopHelperProduct::getProductTax($rowitem->product_id, $propArr[$k]['property_price']); - $propertyId = $propArr[$k]['property_id']; - $accessory_attribute .= urldecode($propArr[$k]['property_name']) - . " (" . $propArr[$k]['property_oprand'] - . RedshopHelperProductPrice::formattedPrice($propArr[$k]['property_price'] + $section_vat) - . ")
    "; - $subpropArr = $propArr[$k]['property_childs']; - - $rowattitem = $this->getTable('quotation_attribute_item'); - $rowattitem->quotation_att_item_id = 0; - $rowattitem->quotation_item_id = $rowitem->quotation_item_id; - $rowattitem->section_id = $propertyId; - $rowattitem->section = "property"; - $rowattitem->parent_section_id = $attributeId; - $rowattitem->section_name = $propArr[$k]['property_name']; - $rowattitem->section_price = $propArr[$k]['property_price']; - $rowattitem->section_vat = $section_vat; - $rowattitem->section_oprand = $propArr[$k]['property_oprand']; - $rowattitem->is_accessory_att = 1; - - if ($propertyId > 0) - { - if (!$rowattitem->store()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - } - - for ($l = 0, $ln = count($subpropArr); $l < $ln; $l++) - { - $section_vat = RedshopHelperProduct::getProductTax($rowitem->product_id, $subpropArr[$l]['subproperty_price']); - $subPropertyId = $subpropArr[$l]['subproperty_id']; - $accessory_attribute .= urldecode($subpropArr[$l]['subproperty_name']) - . " (" . $subpropArr[$l]['subproperty_oprand'] - . RedshopHelperProductPrice::formattedPrice($subpropArr[$l]['subproperty_price'] + $section_vat) . ")
    "; - - $rowattitem = $this->getTable('quotation_attribute_item'); - $rowattitem->quotation_att_item_id = 0; - $rowattitem->quotation_item_id = $rowitem->quotation_item_id; - $rowattitem->section_id = $subPropertyId; - $rowattitem->section = "subproperty"; - $rowattitem->parent_section_id = $propertyId; - $rowattitem->section_name = $subpropArr[$l]['subproperty_name']; - $rowattitem->section_price = $subpropArr[$l]['subproperty_price']; - $rowattitem->section_vat = $section_vat; - $rowattitem->section_oprand = $subpropArr[$l]['subproperty_oprand']; - $rowattitem->is_accessory_att = 1; - - if ($subPropertyId > 0) - { - if (!$rowattitem->store()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - } - } - } - } - - $accdata = $this->getTable('accessory_detail'); - - if ($accessoryId > 0) - { - $accdata->load($accessoryId); - } - - $accProductinfo = \Redshop\Product\Product::getProductById($accdata->child_product_id); - $rowaccitem = $this->getTable('quotation_accessory_item'); - $rowaccitem->quotation_item_acc_id = 0; - $rowaccitem->quotation_item_id = $rowitem->quotation_item_id; - $rowaccitem->accessory_id = $accessoryId; - $rowaccitem->accessory_item_sku = $accProductinfo->product_number; - $rowaccitem->accessory_item_name = $accessory_name; - $rowaccitem->accessory_price = $accessory_org_price; - $rowaccitem->accessory_vat = $accessory_vat_price; - $rowaccitem->accessory_quantity = $rowitem->product_quantity; - $rowaccitem->accessory_item_price = $accessory_price; - $rowaccitem->accessory_final_price = ($accessory_price * $rowitem->product_quantity); - $rowaccitem->accessory_attribute = $accessory_attribute; - - if ($accessoryId > 0) - { - if (!$rowaccitem->store()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - } - } - } - - // My attribute save in table start - if (count($data[$i]['cart_attribute']) > 0) - { - $attArr = $data [$i] ['cart_attribute']; - - for ($j = 0, $jn = count($attArr); $j < $jn; $j++) - { - $attributeId = $attArr[$j]['attribute_id']; - - $rowattitem = $this->getTable('quotation_attribute_item'); - $rowattitem->quotation_att_item_id = 0; - $rowattitem->quotation_item_id = $rowitem->quotation_item_id; - $rowattitem->section_id = $attributeId; - $rowattitem->section = "attribute"; - $rowattitem->parent_section_id = $rowitem->product_id; - $rowattitem->section_name = $attArr[$j]['attribute_name']; - $rowattitem->is_accessory_att = 0; - - if ($attributeId > 0) - { - if (!$rowattitem->store()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - } - - $propArr = $attArr[$j]['attribute_childs']; - - for ($k = 0, $kn = count($propArr); $k < $kn; $k++) - { - $section_vat = RedshopHelperProduct::getProductTax($rowitem->product_id, $propArr[$k]['property_price']); - $propertyId = $propArr[$k]['property_id']; - - $rowattitem = $this->getTable('quotation_attribute_item'); - $rowattitem->quotation_att_item_id = 0; - $rowattitem->quotation_item_id = $rowitem->quotation_item_id; - $rowattitem->section_id = $propertyId; - $rowattitem->section = "property"; - $rowattitem->parent_section_id = $attributeId; - $rowattitem->section_name = $propArr[$k]['property_name']; - $rowattitem->section_price = $propArr[$k]['property_price']; - $rowattitem->section_vat = $section_vat; - $rowattitem->section_oprand = $propArr[$k]['property_oprand']; - $rowattitem->is_accessory_att = 0; - - if ($propertyId > 0) - { - if (!$rowattitem->store()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - } - - $subpropArr = $propArr[$k]['property_childs']; - - for ($l = 0, $ln = count($subpropArr); $l < $ln; $l++) - { - $section_vat = RedshopHelperProduct::getProductTax($rowitem->product_id, $subpropArr[$l]['subproperty_price']); - $subPropertyId = $subpropArr[$l]['subproperty_id']; - - $rowattitem = $this->getTable('quotation_attribute_item'); - $rowattitem->quotation_att_item_id = 0; - $rowattitem->quotation_item_id = $rowitem->quotation_item_id; - $rowattitem->section_id = $subPropertyId; - $rowattitem->section = "subproperty"; - $rowattitem->parent_section_id = $propertyId; - $rowattitem->section_name = $subpropArr[$l]['subproperty_name']; - $rowattitem->section_price = $subpropArr[$l]['subproperty_price']; - $rowattitem->section_vat = $section_vat; - $rowattitem->section_oprand = $subpropArr[$l]['subproperty_oprand']; - $rowattitem->is_accessory_att = 0; - - if ($subPropertyId > 0) - { - if (!$rowattitem->store()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - } - } - } - } - } - - RedshopHelperQuotation::manageQuotationUserField($data[$i], $rowitem->quotation_item_id, $section); - } - - return $row; - } - - public function usercreate($data) - { - $app = JFactory::getApplication(); - - // Get required system objects - $user = clone(JFactory::getUser()); - $authorize = JFactory::getACL(); - - $MailFrom = $app->get('mailfrom'); - $FromName = $app->get('fromname'); - - $usersConfig = JComponentHelper::getParams('com_users'); - $usersConfig->set('allowUserRegistration', 1); - - if ($usersConfig->get('allowUserRegistration') == '0') - { - /** @scrutinizer ignore-deprecated */ JError::raiseError(403, JText::_('COM_REDSHOP_ACCESS_FORBIDDEN')); - - return; - } - - // Initialize new usertype setting - $newUsertype = $usersConfig->get('new_usertype'); - - if (!$newUsertype) - { - $newUsertype = 'Registered'; - } - - // Bind the post array to the user object - if (!$user->bind($app->input->post->getArray(), 'usertype')) - { - /** @scrutinizer ignore-deprecated */ JError::raiseError(500, /** @scrutinizer ignore-deprecated */ $user->getError()); - } - - // Set some initial user values - $user->set('id', 0); - $user->set('usertype', 'Registered'); - $user->set('gid', $authorize->get_group_id('', $newUsertype, 'ARO')); - - $date = JFactory::getDate(); - $user->set('registerDate', $date->toSql()); - - $useractivation = $usersConfig->get('useractivation'); - - if ($useractivation == '1') - { - JLoader::import('joomla.user.helper'); - - $user->set('block', '0'); - } - - if ($data['is_company'] == 1) - { - $tmp = @explode(" ", $data['contact_person']); - $name = @ $tmp[0] . ' ' . $tmp[1]; - $name = $app->input->get('username'); - } - else - { - $name = $app->input->get('firstname') . ' ' . $app->input->get('lastname'); - } - - $email = $app->input->get('email'); - - $password = \Redshop\Crypto\Helper\Encrypt::generateCustomRandomEncryptKey(12); - - // Disallow control chars in the email - $password = preg_replace('/[\x00-\x1F\x7F]/', '', $password); - - $user->password = md5($password); - $user->set('name', $name); - $user->name = $name; - - // If there was an error with registration, set the message and display form - if (!$user->save()) - { - /** @scrutinizer ignore-deprecated */ JError::raiseWarning('', JText::_(/** @scrutinizer ignore-deprecated */ $user->getError())); - - return false; - } - - $user_id = $user->id; - $user->set('id', 0); - - if ($useractivation == 1) - { - $message = JText::_('COM_REDSHOP_REG_COMPLETE_ACTIVATE'); - } - else - { - $message = JText::_('COM_REDSHOP_REG_COMPLETE'); - } - - // Creating Joomla user end - $row = $this->getTable('user_detail'); - $row->user_id = $user_id; - - if (!$row->bind($data)) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - if ($data['is_company'] == 1) - { - if (Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_COMPANY') != 0) - { - $row->shopper_group_id = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_COMPANY'); - } - else - { - $row->shopper_group_id = 2; - } - } - else - { - if (Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_PRIVATE') != 0) - { - $row->shopper_group_id = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_PRIVATE'); - } - else - { - $row->shopper_group_id = 1; - } - } - - if ($data['is_company'] == 1) - { - $tmp = explode(" ", $data['contact_person']); - $row->firstname = $tmp[0]; - $row->lastname = $tmp[1]; - } - - $row->user_email = $user->email; - $row->address_type = 'BT'; - - if (!$row->store()) - { - /** @scrutinizer ignore-deprecated */ $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); - - return false; - } - - $email = $user->email; - - $session = JFactory::getSession(); - $cart = $session->get('cart'); - - $cart['user_id'] = $user_id; - $user_data = RedshopHelperUser::getUserInformation($user_id); - $cart['user_info_id'] = $user_data->users_info_id; - $quotationDetail = $this->store($cart); - - $quotation_id = $quotationDetail->quotation_id; - $quotationdetailurl = JURI::root() . 'index.php?option=com_redshop&view=quotation_detail&quoid=' . $quotation_id . '&encr=' . $quotationDetail->quotation_encrkey; - - $mailbody = ''; - $mailbody .= ''; - $mailbody .= ''; - $mailbody .= ''; - $mailbody .= '
    ' . JText::_('COM_REDSHOP_USERNAME') . ' : ' . $data['username'] . '
    ' . JText::_('COM_REDSHOP_PASSWORD') . ' : ' . $password . '
    ' . JText::_('COM_REDSHOP_QUOTATION_DETAILS') . ' : ' . JText::_("COM_REDSHOP_QUOTATION_DETAILS") . '
    '; - $mailsubject = 'Register'; - $mailbcc = null; - $mailinfo = Redshop\Mail\Helper::getTemplate(0, "quotation_user_register"); - - if (count($mailinfo) > 0) - { - $mailbody = $mailinfo[0]->mail_body; - $mailsubject = $mailinfo[0]->mail_subject; - - if (trim($mailinfo[0]->mail_bcc) != "") - { - $mailbcc = explode(",", $mailinfo[0]->mail_bcc); - } - } - - $this->sendQuotationMail($quotationDetail->quotation_id); - - $link = "" . JText::_("COM_REDSHOP_QUOTATION_DETAILS") . ""; - - $mailbody = str_replace('{link}', $link, $mailbody); - $mailbody = str_replace('{username}', $name, $mailbody); - $mailbody = str_replace('{password}', $name, $mailbody); - Redshop\Mail\Helper::imgInMail($mailbody); - - JFactory::getMailer()->sendMail($MailFrom, $FromName, $email, $mailsubject, $mailbody, 1, null, $mailbcc); - - $session = JFactory::getSession(); - \Redshop\Cart\Helper::setCart(null); - $session->set('ccdata', null); - $session->set('issplit', null); - $session->set('userfield', null); - unset ($_SESSION ['ccdata']); - - return; - } - - public function sendQuotationMail($quotationId) - { - return Redshop\Mail\Quotation::sendMail($quotationId); - } - - /** - * @param string $email Email - * - * @return null|stdClass - */ - public function getUserIdByEmail($email) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query->select('*') - ->from($db->quoteName('#__redshop_users_info')) - ->where($db->quoteName('user_email') . ' = ' . $db->quote($email)) - ->where($db->quoteName('address_type') . ' = ' . $db->quote('BT')); - - return $db->setQuery($query)->loadObject(); - } + public $_id = null; + + public $_data = null; + + public $_table_prefix = null; + + public function __construct() + { + parent::__construct(); + + $this->_table_prefix = '#__redshop_'; + } + + public function &getData() + { + if (!$this->_loadData()) { + $this->_initData(); + } + + return $this->_data; + } + + public function _loadData() + { + $user = JFactory::getUser(); + + if ($user->id) { + $this->_data = RedshopHelperOrder::getBillingAddress($user->id); + $this->_data->user_info_id = $this->_data->users_info_id; + + return true; + } + + return false; + } + + public function _initData() + { + $detail = new stdClass; + $detail->user_info_id = 0; + $detail->user_id = 0; + $detail->firstname = null; + $detail->lastname = null; + $detail->address = null; + $detail->zipcode = null; + $detail->city = null; + $detail->country_code = null; + $detail->state_code = null; + $detail->phone = null; + $detail->user_email = null; + $detail->is_company = null; + $detail->vat_number = null; + $detail->requesting_tax_exempt = 0; + $detail->tax_exempt = null; + $this->_data = $detail; + } + + public function usercreate($data) + { + $app = JFactory::getApplication(); + + // Get required system objects + $user = clone(JFactory::getUser()); + $authorize = JFactory::getACL(); + + $MailFrom = $app->get('mailfrom'); + $FromName = $app->get('fromname'); + + $usersConfig = JComponentHelper::getParams('com_users'); + $usersConfig->set('allowUserRegistration', 1); + + if ($usersConfig->get('allowUserRegistration') == '0') { + /** @scrutinizer ignore-deprecated */ + JError::raiseError(403, JText::_('COM_REDSHOP_ACCESS_FORBIDDEN')); + + return; + } + + // Initialize new usertype setting + $newUsertype = $usersConfig->get('new_usertype'); + + if (!$newUsertype) { + $newUsertype = 'Registered'; + } + + // Bind the post array to the user object + if (!$user->bind($app->input->post->getArray(), 'usertype')) { + /** @scrutinizer ignore-deprecated */ + JError::raiseError(500, /** @scrutinizer ignore-deprecated */ $user->getError()); + } + + // Set some initial user values + $user->set('id', 0); + $user->set('usertype', 'Registered'); + $user->set('gid', $authorize->get_group_id('', $newUsertype, 'ARO')); + + $date = JFactory::getDate(); + $user->set('registerDate', $date->toSql()); + + $useractivation = $usersConfig->get('useractivation'); + + if ($useractivation == '1') { + JLoader::import('joomla.user.helper'); + + $user->set('block', '0'); + } + + if ($data['is_company'] == 1) { + $tmp = @explode(" ", $data['contact_person']); + $name = @ $tmp[0] . ' ' . $tmp[1]; + $name = $app->input->get('username'); + } else { + $name = $app->input->get('firstname') . ' ' . $app->input->get('lastname'); + } + + $email = $app->input->get('email'); + + $password = \Redshop\Crypto\Helper\Encrypt::generateCustomRandomEncryptKey(12); + + // Disallow control chars in the email + $password = preg_replace('/[\x00-\x1F\x7F]/', '', $password); + + $user->password = md5($password); + $user->set('name', $name); + $user->name = $name; + + // If there was an error with registration, set the message and display form + if (!$user->save()) { + /** @scrutinizer ignore-deprecated */ + JError::raiseWarning('', JText::_(/** @scrutinizer ignore-deprecated */ $user->getError())); + + return false; + } + + $user_id = $user->id; + $user->set('id', 0); + + if ($useractivation == 1) { + $message = JText::_('COM_REDSHOP_REG_COMPLETE_ACTIVATE'); + } else { + $message = JText::_('COM_REDSHOP_REG_COMPLETE'); + } + + // Creating Joomla user end + $row = $this->getTable('user_detail'); + $row->user_id = $user_id; + + if (!$row->bind($data)) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + if ($data['is_company'] == 1) { + if (Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_COMPANY') != 0) { + $row->shopper_group_id = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_COMPANY'); + } else { + $row->shopper_group_id = 2; + } + } else { + if (Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_PRIVATE') != 0) { + $row->shopper_group_id = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_PRIVATE'); + } else { + $row->shopper_group_id = 1; + } + } + + if ($data['is_company'] == 1) { + $tmp = explode(" ", $data['contact_person']); + $row->firstname = $tmp[0]; + $row->lastname = $tmp[1]; + } + + $row->user_email = $user->email; + $row->address_type = 'BT'; + + if (!$row->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + $email = $user->email; + + $session = JFactory::getSession(); + $cart = $session->get('cart'); + + $cart['user_id'] = $user_id; + $user_data = RedshopHelperUser::getUserInformation($user_id); + $cart['user_info_id'] = $user_data->users_info_id; + $quotationDetail = $this->store($cart); + + $quotation_id = $quotationDetail->quotation_id; + $quotationdetailurl = JURI::root( + ) . 'index.php?option=com_redshop&view=quotation_detail&quoid=' . $quotation_id . '&encr=' . $quotationDetail->quotation_encrkey; + + $mailbody = ''; + $mailbody .= ''; + $mailbody .= ''; + $mailbody .= ''; + $mailbody .= '
    ' . JText::_( + 'COM_REDSHOP_USERNAME' + ) . ' : ' . $data['username'] . '
    ' . JText::_( + 'COM_REDSHOP_PASSWORD' + ) . ' : ' . $password . '
    ' . JText::_( + 'COM_REDSHOP_QUOTATION_DETAILS' + ) . ' : ' . JText::_( + "COM_REDSHOP_QUOTATION_DETAILS" + ) . '
    '; + $mailsubject = 'Register'; + $mailbcc = null; + $mailinfo = Redshop\Mail\Helper::getTemplate(0, "quotation_user_register"); + + if (count($mailinfo) > 0) { + $mailbody = $mailinfo[0]->mail_body; + $mailsubject = $mailinfo[0]->mail_subject; + + if (trim($mailinfo[0]->mail_bcc) != "") { + $mailbcc = explode(",", $mailinfo[0]->mail_bcc); + } + } + + $this->sendQuotationMail($quotationDetail->quotation_id); + + $link = "" . JText::_("COM_REDSHOP_QUOTATION_DETAILS") . ""; + + $mailbody = str_replace('{link}', $link, $mailbody); + $mailbody = str_replace('{username}', $name, $mailbody); + $mailbody = str_replace('{password}', $name, $mailbody); + Redshop\Mail\Helper::imgInMail($mailbody); + + JFactory::getMailer()->sendMail($MailFrom, $FromName, $email, $mailsubject, $mailbody, 1, null, $mailbcc); + + $session = JFactory::getSession(); + \Redshop\Cart\Helper::setCart(null); + $session->set('ccdata', null); + $session->set('issplit', null); + $session->set('userfield', null); + unset ($_SESSION ['ccdata']); + + return; + } + + public function store($data, $post) + { + $this->_loadData(); + $user = JFactory::getUser(); + $user_id = 0; + $user_info_id = 0; + $user_email = $post['user_email']; + + if ($user->id) { + $user_id = $user->id; + $user_info_id = $this->_data->user_info_id; + $user_email = $user->email; + } + + $res = $this->getUserIdByEmail($user_email); + + if ($res > 0) { + $user_id = $res->user_id; + $user_info_id = $res->users_info_id; + } + + $data['quotation_number'] = RedshopHelperQuotation::generateQuotationNumber(); + $data['user_id'] = $user_id; + $data['user_info_id'] = $user_info_id; + $data['user_email'] = $user_email; + $data['quotation_total'] = $data['total']; + $data['quotation_subtotal'] = $data['subtotal']; + $data['quotation_tax'] = $data['tax']; + $data['quotation_status'] = 1; + $data['quotation_cdate'] = time(); + $data['quotation_mdate'] = time(); + $data['quotation_note'] = $data['quotation_note']; + $data['quotation_ipaddress'] = $_SERVER ['REMOTE_ADDR']; + $data['quotation_encrkey'] = RedshopHelperQuotation::randomQuotationEncryptKey(); + $data['quotation_discount'] = (isset($data['discount2'])) ? $data['discount2'] : 0; + + $totalitem = $data['idx']; + $quotation_item = array(); + + $row = $this->getTable('quotation_detail'); + + if (!$row->bind($data)) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + if (!$row->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + for ($i = 0; $i < $totalitem; $i++) { + $rowitem = $this->getTable('quotation_item_detail'); + $quotation_item[$i] = new stdClass; + $quotation_item[$i]->quotation_id = $row->quotation_id; + + if (isset($data[$i]['giftcard_id']) && $data[$i]['giftcard_id'] != 0) { + $quotation_item[$i]->product_id = $data[$i]['giftcard_id']; + + $giftcardData = RedshopEntityGiftcard::getInstance($data[$i]['giftcard_id'])->getItem(); + + $quotation_item[$i]->is_giftcard = 1; + $quotation_item[$i]->product_name = $giftcardData->giftcard_name; + $section = 13; + } else { + $product = \Redshop\Product\Product::getProductById($data[$i]['product_id']); + + $retAttArr = RedshopHelperProduct::makeAttributeCart( + $data[$i]['cart_attribute'], + $data[$i]['product_id'], + 0, + 0, + $data[$i]['quantity'] + ); + $cart_attribute = $retAttArr[0]; + + $retAccArr = RedshopHelperProduct::makeAccessoryCart( + $data[$i]['cart_accessory'], + $data[$i]['product_id'] + ); + $cart_accessory = $retAccArr[0]; + + $quotation_item[$i]->product_id = $data[$i]['product_id']; + $quotation_item[$i]->is_giftcard = 0; + $quotation_item[$i]->product_name = $product->product_name; + $quotation_item[$i]->actualitem_price = $data[$i]['product_price']; + $quotation_item[$i]->product_price = $data[$i]['product_price']; + $quotation_item[$i]->product_excl_price = $data[$i]['product_price_excl_vat']; + $quotation_item[$i]->product_final_price = $data[$i]['product_price'] * $data[$i]['quantity']; + $quotation_item[$i]->product_attribute = $cart_attribute; + $quotation_item[$i]->product_accessory = $cart_accessory; + $quotation_item[$i]->product_wrapperid = $data[$i]['wrapper_id']; + $quotation_item[$i]->wrapper_price = $data[$i]['wrapper_price']; + + $section = 12; + } + + $quotation_item[$i]->product_quantity = $data[$i]['quantity']; + + if (!$rowitem->bind($quotation_item[$i])) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + if (!$rowitem->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + + /** my accessory save in table start */ + if (count($data[$i]['cart_accessory']) > 0) { + $attArr = $data [$i] ['cart_accessory']; + + for ($a = 0, $an = count($attArr); $a < $an; $a++) { + $accessory_vat_price = 0; + $accessory_attribute = ""; + $accessoryId = $attArr[$a]['accessory_id']; + $accessory_name = $attArr[$a]['accessory_name']; + $accessory_price = $attArr[$a]['accessory_price']; + $accessory_org_price = $accessory_price; + + if ($accessory_price > 0) { + $accessory_vat_price = RedshopHelperProduct::getProductTax( + $rowitem->product_id, + $accessory_price + ); + } + + $attchildArr = $attArr[$a]['accessory_childs']; + + for ($j = 0, $jn = count($attchildArr); $j < $jn; $j++) { + $attributeId = $attchildArr[$j]['attribute_id']; + $accessory_attribute .= urldecode($attchildArr[$j]['attribute_name']) . ":
    "; + + $rowattitem = $this->getTable('quotation_attribute_item'); + $rowattitem->quotation_att_item_id = 0; + $rowattitem->quotation_item_id = $rowitem->quotation_item_id; + $rowattitem->section_id = $attributeId; + $rowattitem->section = "attribute"; + $rowattitem->parent_section_id = $accessoryId; + $rowattitem->section_name = $attchildArr[$j]['attribute_name']; + $rowattitem->is_accessory_att = 1; + + if ($attributeId > 0) { + if (!$rowattitem->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + } + + + $propArr = $attchildArr[$j]['attribute_childs']; + + for ($k = 0, $kn = count($propArr); $k < $kn; $k++) { + $section_vat = RedshopHelperProduct::getProductTax( + $rowitem->product_id, + $propArr[$k]['property_price'] + ); + $propertyId = $propArr[$k]['property_id']; + $accessory_attribute .= urldecode($propArr[$k]['property_name']) + . " (" . $propArr[$k]['property_oprand'] + . RedshopHelperProductPrice::formattedPrice( + $propArr[$k]['property_price'] + $section_vat + ) + . ")
    "; + $subpropArr = $propArr[$k]['property_childs']; + + $rowattitem = $this->getTable('quotation_attribute_item'); + $rowattitem->quotation_att_item_id = 0; + $rowattitem->quotation_item_id = $rowitem->quotation_item_id; + $rowattitem->section_id = $propertyId; + $rowattitem->section = "property"; + $rowattitem->parent_section_id = $attributeId; + $rowattitem->section_name = $propArr[$k]['property_name']; + $rowattitem->section_price = $propArr[$k]['property_price']; + $rowattitem->section_vat = $section_vat; + $rowattitem->section_oprand = $propArr[$k]['property_oprand']; + $rowattitem->is_accessory_att = 1; + + if ($propertyId > 0) { + if (!$rowattitem->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + } + + for ($l = 0, $ln = count($subpropArr); $l < $ln; $l++) { + $section_vat = RedshopHelperProduct::getProductTax( + $rowitem->product_id, + $subpropArr[$l]['subproperty_price'] + ); + $subPropertyId = $subpropArr[$l]['subproperty_id']; + $accessory_attribute .= urldecode($subpropArr[$l]['subproperty_name']) + . " (" . $subpropArr[$l]['subproperty_oprand'] + . RedshopHelperProductPrice::formattedPrice( + $subpropArr[$l]['subproperty_price'] + $section_vat + ) . ")
    "; + + $rowattitem = $this->getTable('quotation_attribute_item'); + $rowattitem->quotation_att_item_id = 0; + $rowattitem->quotation_item_id = $rowitem->quotation_item_id; + $rowattitem->section_id = $subPropertyId; + $rowattitem->section = "subproperty"; + $rowattitem->parent_section_id = $propertyId; + $rowattitem->section_name = $subpropArr[$l]['subproperty_name']; + $rowattitem->section_price = $subpropArr[$l]['subproperty_price']; + $rowattitem->section_vat = $section_vat; + $rowattitem->section_oprand = $subpropArr[$l]['subproperty_oprand']; + $rowattitem->is_accessory_att = 1; + + if ($subPropertyId > 0) { + if (!$rowattitem->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError( + /** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg() + ); + + return false; + } + } + } + } + } + + $accdata = $this->getTable('accessory_detail'); + + if ($accessoryId > 0) { + $accdata->load($accessoryId); + } + + $accProductinfo = \Redshop\Product\Product::getProductById( + $accdata->child_product_id + ); + $rowaccitem = $this->getTable('quotation_accessory_item'); + $rowaccitem->quotation_item_acc_id = 0; + $rowaccitem->quotation_item_id = $rowitem->quotation_item_id; + $rowaccitem->accessory_id = $accessoryId; + $rowaccitem->accessory_item_sku = $accProductinfo->product_number; + $rowaccitem->accessory_item_name = $accessory_name; + $rowaccitem->accessory_price = $accessory_org_price; + $rowaccitem->accessory_vat = $accessory_vat_price; + $rowaccitem->accessory_quantity = $rowitem->product_quantity; + $rowaccitem->accessory_item_price = $accessory_price; + $rowaccitem->accessory_final_price = ($accessory_price * $rowitem->product_quantity); + $rowaccitem->accessory_attribute = $accessory_attribute; + + if ($accessoryId > 0) { + if (!$rowaccitem->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + } + } + } + + // My attribute save in table start + if (count($data[$i]['cart_attribute']) > 0) { + $attArr = $data [$i] ['cart_attribute']; + + for ($j = 0, $jn = count($attArr); $j < $jn; $j++) { + $attributeId = $attArr[$j]['attribute_id']; + + $rowattitem = $this->getTable('quotation_attribute_item'); + $rowattitem->quotation_att_item_id = 0; + $rowattitem->quotation_item_id = $rowitem->quotation_item_id; + $rowattitem->section_id = $attributeId; + $rowattitem->section = "attribute"; + $rowattitem->parent_section_id = $rowitem->product_id; + $rowattitem->section_name = $attArr[$j]['attribute_name']; + $rowattitem->is_accessory_att = 0; + + if ($attributeId > 0) { + if (!$rowattitem->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + } + + $propArr = $attArr[$j]['attribute_childs']; + + for ($k = 0, $kn = count($propArr); $k < $kn; $k++) { + $section_vat = RedshopHelperProduct::getProductTax( + $rowitem->product_id, + $propArr[$k]['property_price'] + ); + $propertyId = $propArr[$k]['property_id']; + + $rowattitem = $this->getTable('quotation_attribute_item'); + $rowattitem->quotation_att_item_id = 0; + $rowattitem->quotation_item_id = $rowitem->quotation_item_id; + $rowattitem->section_id = $propertyId; + $rowattitem->section = "property"; + $rowattitem->parent_section_id = $attributeId; + $rowattitem->section_name = $propArr[$k]['property_name']; + $rowattitem->section_price = $propArr[$k]['property_price']; + $rowattitem->section_vat = $section_vat; + $rowattitem->section_oprand = $propArr[$k]['property_oprand']; + $rowattitem->is_accessory_att = 0; + + if ($propertyId > 0) { + if (!$rowattitem->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + } + + $subpropArr = $propArr[$k]['property_childs']; + + for ($l = 0, $ln = count($subpropArr); $l < $ln; $l++) { + $section_vat = RedshopHelperProduct::getProductTax( + $rowitem->product_id, + $subpropArr[$l]['subproperty_price'] + ); + $subPropertyId = $subpropArr[$l]['subproperty_id']; + + $rowattitem = $this->getTable('quotation_attribute_item'); + $rowattitem->quotation_att_item_id = 0; + $rowattitem->quotation_item_id = $rowitem->quotation_item_id; + $rowattitem->section_id = $subPropertyId; + $rowattitem->section = "subproperty"; + $rowattitem->parent_section_id = $propertyId; + $rowattitem->section_name = $subpropArr[$l]['subproperty_name']; + $rowattitem->section_price = $subpropArr[$l]['subproperty_price']; + $rowattitem->section_vat = $section_vat; + $rowattitem->section_oprand = $subpropArr[$l]['subproperty_oprand']; + $rowattitem->is_accessory_att = 0; + + if ($subPropertyId > 0) { + if (!$rowattitem->store()) { + /** @scrutinizer ignore-deprecated */ + $this->setError(/** @scrutinizer ignore-deprecated */ $this->_db->getErrorMsg()); + + return false; + } + } + } + } + } + } + + RedshopHelperQuotation::manageQuotationUserField($data[$i], $rowitem->quotation_item_id, $section); + } + + return $row; + } + + /** + * @param string $email Email + * + * @return null|stdClass + */ + public function getUserIdByEmail($email) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->select('*') + ->from($db->quoteName('#__redshop_users_info')) + ->where($db->quoteName('user_email') . ' = ' . $db->quote($email)) + ->where($db->quoteName('address_type') . ' = ' . $db->quote('BT')); + + return $db->setQuery($query)->loadObject(); + } + + public function sendQuotationMail($quotationId) + { + return Redshop\Mail\Quotation::sendMail($quotationId); + } } diff --git a/component/site/models/quotation_detail.php b/component/site/models/quotation_detail.php index 45c4e0f6273..37281b48199 100644 --- a/component/site/models/quotation_detail.php +++ b/component/site/models/quotation_detail.php @@ -19,228 +19,244 @@ */ class RedshopModelQuotation_detail extends RedshopModel { - public $_id = null; - - public $_data = null; - - public $_table_prefix = null; - - public function __construct() - { - parent::__construct(); - $this->_table_prefix = '#__redshop_'; - } - - public function checkAuthorization($quoid, $encr) - { - $query = "SELECT COUNT(quotation_id) FROM " . $this->_table_prefix . "quotation " - . "WHERE quotation_id = " . (int) $quoid . " " - . "AND quotation_encrkey LIKE " . $this->_db->quote($encr); - $this->_db->setQuery($query); - $record = $this->_db->loadResult(); - - return $record; - } - - public function addtocart($data = array()) - { - $session = JFactory::getSession(); - - $cart = $session->get('cart'); - - $idx = (int) ($cart['idx']); - - $row_data = RedshopHelperQuotation::getQuotationUserField($data->quotation_item_id); - $quotation_acc_data = RedshopHelperQuotation::getQuotationItemAccessoryDetail($data->quotation_item_id); - $quotation_att_data = RedshopHelperQuotation::getQuotationItemAttributeDetail($data->quotation_item_id, 0, "attribute", $data->product_id); - - // Set session for giftcard - if ($data->is_giftcard == 1) - { - if (\Redshop\Helper\Utility::rsRecursiveArraySearch($cart, $data->product_id)) - { - $cart[$idx]['quantity'] += 1; - \Redshop\Cart\Helper::setCart($cart); - - return; - } - else - { - $cart[$idx]['quantity'] = 1; - } - - $cart[$idx]['quantity'] = $data->product_quantity; - $cart[$idx]['giftcard_id'] = $data->product_id; - $cart[$idx]['product_price'] = $data->product_price; - $cart[$idx]['product_vat'] = 0; - $cart[$idx]['product_id'] = ''; - $cart['discount_type'] = 0; - $cart['discount'] = 0; - $cart['discount2'] = 0; - $cart['reciver_email'] = ''; - $cart['reciver_name'] = ''; - - for ($i = 0, $in = count($row_data); $i < $in; $i++) - { - $field_name = $row_data[$i]->field_name; - $cart[$idx][$field_name] = $row_data[$i]->data_txt; - } - - $cart['idx'] = $idx + 1; - \Redshop\Cart\Helper::setCart($cart); - - return; - } - - $cart[$idx]['product_id'] = $data->product_id; - $cart[$idx]['product_price'] = $data->product_price; - $cart[$idx]['quantity'] = $data->product_quantity; - - if ($data->product_excl_price) - { - $getprotax = RedshopHelperProduct::getProductTax($cart[$idx]['product_id'], $data->product_excl_price); - $cart[$idx]['product_price'] = $data->product_excl_price + $getprotax; - $cart[$idx]['product_price'] += $data->wrapper_price; - $cart[$idx]['product_subtotal'] = $cart[$idx]['quantity'] * $cart[$idx]['product_price']; - } - - $generateAccessoryCart = array(); - - for ($i = 0, $in = count($quotation_acc_data); $i < $in; $i++) - { - $generateAccessoryCart[$i]['accessory_id'] = $quotation_acc_data[$i]->accessory_id; - $generateAccessoryCart[$i]['accessory_name'] = $quotation_acc_data[$i]->accessory_item_name; - $generateAccessoryCart[$i]['accessory_oprand'] = "+"; - $generateAccessoryCart[$i]['accessory_price'] = $quotation_acc_data[$i]->accessory_price; - - $acc_att_data = RedshopHelperQuotation::getQuotationItemAttributeDetail($data->quotation_item_id, 1, "attribute", $quotation_acc_data[$i]->accessory_id); - - $accAttributeCart = array(); - - for ($ia = 0, $countAccessoryAttribute = count($acc_att_data); $ia < $countAccessoryAttribute; $ia++) - { - $accPropertyCart = array(); - $accAttributeCart[$ia]['attribute_id'] = $acc_att_data[$ia]->section_id; - $accAttributeCart[$ia]['attribute_name'] = $acc_att_data[$ia]->section_name; - - $acc_prop_data = RedshopHelperQuotation::getQuotationItemAttributeDetail($data->quotation_item_id, 1, "property", $acc_att_data[$ia]->section_id); - - for ($ip = 0, $countAccessoryProperty = count($acc_prop_data); $ip < $countAccessoryProperty; $ip++) - { - $accSubpropertyCart = array(); - $accPropertyCart[$ip]['property_id'] = $acc_prop_data[$ip]->section_id; - $accPropertyCart[$ip]['property_name'] = $acc_prop_data[$ip]->section_name; - $accPropertyCart[$ip]['property_oprand'] = $acc_prop_data[$ip]->section_oprand; - - $acc_subpro_data = RedshopHelperQuotation::getQuotationItemAttributeDetail($data->quotation_item_id, 1, "subproperty", $acc_prop_data[$ip]->section_id); - $countAccessorySubroperty = count($acc_subpro_data); - - for ($isp = 0; $isp < $countAccessorySubroperty; $isp++) - { - $accSubpropertyCart[$isp]['subproperty_id'] = $acc_subpro_data[$isp]->section_id; - $accSubpropertyCart[$isp]['subproperty_name'] = $acc_subpro_data[$isp]->section_name; - $accSubpropertyCart[$isp]['subproperty_oprand'] = $acc_subpro_data[$isp]->section_oprand; - } - - $accPropertyCart[$ip]['property_childs'] = $accSubpropertyCart; - } - - $accAttributeCart[$ia]['attribute_childs'] = $accPropertyCart; - } - - $generateAccessoryCart[$i]['accessory_childs'] = $accAttributeCart; - } - - $generateAttributeCart = array(); - - for ($ia = 0, $countQuotationAtrribute = count($quotation_att_data); $ia < $countQuotationAtrribute; $ia++) - { - $accPropertyCart = array(); - $generateAttributeCart[$ia]['attribute_id'] = $quotation_att_data[$ia]->section_id; - $generateAttributeCart[$ia]['attribute_name'] = $quotation_att_data[$ia]->section_name; - - $acc_prop_data = RedshopHelperQuotation::getQuotationItemAttributeDetail($data->quotation_item_id, 0, "property", $quotation_att_data[$ia]->section_id); - $countQuotationProperty = count($acc_prop_data); - - for ($ip = 0; $ip < $countQuotationProperty; $ip++) - { - $accSubpropertyCart = array(); - $accPropertyCart[$ip]['property_id'] = $acc_prop_data[$ip]->section_id; - $accPropertyCart[$ip]['property_name'] = $acc_prop_data[$ip]->section_name; - $accPropertyCart[$ip]['property_oprand'] = $acc_prop_data[$ip]->section_oprand; - - $acc_subpro_data = RedshopHelperQuotation::getQuotationItemAttributeDetail($data->quotation_item_id, 0, "subproperty", $acc_prop_data[$ip]->section_id); - $countQuotationSubproperty = count($acc_subpro_data); - - for ($isp = 0; $isp < $countQuotationSubproperty; $isp++) - { - $accSubpropertyCart[$isp]['subproperty_id'] = $acc_subpro_data[$isp]->section_id; - $accSubpropertyCart[$isp]['subproperty_name'] = $acc_subpro_data[$isp]->section_name; - $accSubpropertyCart[$isp]['subproperty_oprand'] = $acc_subpro_data[$isp]->section_oprand; - } - - $accPropertyCart[$ip]['property_childs'] = $accSubpropertyCart; - } - - $generateAttributeCart[$ia]['attribute_childs'] = $accPropertyCart; - } - - $cart[$idx]['cart_attribute'] = $generateAttributeCart; - $cart[$idx]['cart_accessory'] = $generateAccessoryCart; - $cart[$idx]['wrapper_id'] = $data->product_wrapperid; - $cart[$idx]['wrapper_price'] = $data->wrapper_price; - $cart[$idx]['product_price_excl_vat'] = $data->product_excl_price; - - $cart['idx'] = $idx + 1; - - for ($i = 0, $in = count($row_data); $i < $in; $i++) - { - $field_name = $row_data[$i]->field_name; - $cart[$idx][$field_name] = $row_data[$i]->data_txt; - } - - \Redshop\Cart\Helper::setCart($cart); - } - - public function modifyQuotation($user_id = 0) - { - $session = JFactory::getSession(); - $cart = $session->get('cart'); - - $cart = \Redshop\Cart\Cart::modify($cart, $user_id); - - \Redshop\Cart\Helper::setCart($cart); + public $_id = null; + + public $_data = null; + + public $_table_prefix = null; + + public function __construct() + { + parent::__construct(); + $this->_table_prefix = '#__redshop_'; + } + + public function checkAuthorization($quoid, $encr) + { + $query = "SELECT COUNT(quotation_id) FROM " . $this->_table_prefix . "quotation " + . "WHERE quotation_id = " . (int)$quoid . " " + . "AND quotation_encrkey LIKE " . $this->_db->quote($encr); + $this->_db->setQuery($query); + $record = $this->_db->loadResult(); + + return $record; + } + + public function addtocart($data = array()) + { + $session = JFactory::getSession(); + + $cart = $session->get('cart'); + + $idx = (int)($cart['idx']); + + $row_data = RedshopHelperQuotation::getQuotationUserField($data->quotation_item_id); + $quotation_acc_data = RedshopHelperQuotation::getQuotationItemAccessoryDetail($data->quotation_item_id); + $quotation_att_data = RedshopHelperQuotation::getQuotationItemAttributeDetail( + $data->quotation_item_id, + 0, + "attribute", + $data->product_id + ); + + // Set session for giftcard + if ($data->is_giftcard == 1) { + if (\Redshop\Helper\Utility::rsRecursiveArraySearch($cart, $data->product_id)) { + $cart[$idx]['quantity'] += 1; + \Redshop\Cart\Helper::setCart($cart); + + return; + } else { + $cart[$idx]['quantity'] = 1; + } + + $cart[$idx]['quantity'] = $data->product_quantity; + $cart[$idx]['giftcard_id'] = $data->product_id; + $cart[$idx]['product_price'] = $data->product_price; + $cart[$idx]['product_vat'] = 0; + $cart[$idx]['product_id'] = ''; + $cart['discount_type'] = 0; + $cart['discount'] = 0; + $cart['discount2'] = 0; + $cart['reciver_email'] = ''; + $cart['reciver_name'] = ''; + + for ($i = 0, $in = count($row_data); $i < $in; $i++) { + $field_name = $row_data[$i]->field_name; + $cart[$idx][$field_name] = $row_data[$i]->data_txt; + } + + $cart['idx'] = $idx + 1; + \Redshop\Cart\Helper::setCart($cart); + + return; + } + + $cart[$idx]['product_id'] = $data->product_id; + $cart[$idx]['product_price'] = $data->product_price; + $cart[$idx]['quantity'] = $data->product_quantity; + + if ($data->product_excl_price) { + $getprotax = RedshopHelperProduct::getProductTax( + $cart[$idx]['product_id'], + $data->product_excl_price + ); + $cart[$idx]['product_price'] = $data->product_excl_price + $getprotax; + $cart[$idx]['product_price'] += $data->wrapper_price; + $cart[$idx]['product_subtotal'] = $cart[$idx]['quantity'] * $cart[$idx]['product_price']; + } + + $generateAccessoryCart = array(); + + for ($i = 0, $in = count($quotation_acc_data); $i < $in; $i++) { + $generateAccessoryCart[$i]['accessory_id'] = $quotation_acc_data[$i]->accessory_id; + $generateAccessoryCart[$i]['accessory_name'] = $quotation_acc_data[$i]->accessory_item_name; + $generateAccessoryCart[$i]['accessory_oprand'] = "+"; + $generateAccessoryCart[$i]['accessory_price'] = $quotation_acc_data[$i]->accessory_price; + + $acc_att_data = RedshopHelperQuotation::getQuotationItemAttributeDetail( + $data->quotation_item_id, + 1, + "attribute", + $quotation_acc_data[$i]->accessory_id + ); + + $accAttributeCart = array(); + + for ($ia = 0, $countAccessoryAttribute = count($acc_att_data); $ia < $countAccessoryAttribute; $ia++) { + $accPropertyCart = array(); + $accAttributeCart[$ia]['attribute_id'] = $acc_att_data[$ia]->section_id; + $accAttributeCart[$ia]['attribute_name'] = $acc_att_data[$ia]->section_name; + + $acc_prop_data = RedshopHelperQuotation::getQuotationItemAttributeDetail( + $data->quotation_item_id, + 1, + "property", + $acc_att_data[$ia]->section_id + ); + + for ($ip = 0, $countAccessoryProperty = count($acc_prop_data); $ip < $countAccessoryProperty; $ip++) { + $accSubpropertyCart = array(); + $accPropertyCart[$ip]['property_id'] = $acc_prop_data[$ip]->section_id; + $accPropertyCart[$ip]['property_name'] = $acc_prop_data[$ip]->section_name; + $accPropertyCart[$ip]['property_oprand'] = $acc_prop_data[$ip]->section_oprand; + + $acc_subpro_data = RedshopHelperQuotation::getQuotationItemAttributeDetail( + $data->quotation_item_id, + 1, + "subproperty", + $acc_prop_data[$ip]->section_id + ); + $countAccessorySubroperty = count($acc_subpro_data); + + for ($isp = 0; $isp < $countAccessorySubroperty; $isp++) { + $accSubpropertyCart[$isp]['subproperty_id'] = $acc_subpro_data[$isp]->section_id; + $accSubpropertyCart[$isp]['subproperty_name'] = $acc_subpro_data[$isp]->section_name; + $accSubpropertyCart[$isp]['subproperty_oprand'] = $acc_subpro_data[$isp]->section_oprand; + } + + $accPropertyCart[$ip]['property_childs'] = $accSubpropertyCart; + } + + $accAttributeCart[$ia]['attribute_childs'] = $accPropertyCart; + } + + $generateAccessoryCart[$i]['accessory_childs'] = $accAttributeCart; + } + + $generateAttributeCart = array(); + + for ($ia = 0, $countQuotationAtrribute = count($quotation_att_data); $ia < $countQuotationAtrribute; $ia++) { + $accPropertyCart = array(); + $generateAttributeCart[$ia]['attribute_id'] = $quotation_att_data[$ia]->section_id; + $generateAttributeCart[$ia]['attribute_name'] = $quotation_att_data[$ia]->section_name; + + $acc_prop_data = RedshopHelperQuotation::getQuotationItemAttributeDetail( + $data->quotation_item_id, + 0, + "property", + $quotation_att_data[$ia]->section_id + ); + $countQuotationProperty = count($acc_prop_data); + + for ($ip = 0; $ip < $countQuotationProperty; $ip++) { + $accSubpropertyCart = array(); + $accPropertyCart[$ip]['property_id'] = $acc_prop_data[$ip]->section_id; + $accPropertyCart[$ip]['property_name'] = $acc_prop_data[$ip]->section_name; + $accPropertyCart[$ip]['property_oprand'] = $acc_prop_data[$ip]->section_oprand; + + $acc_subpro_data = RedshopHelperQuotation::getQuotationItemAttributeDetail( + $data->quotation_item_id, + 0, + "subproperty", + $acc_prop_data[$ip]->section_id + ); + $countQuotationSubproperty = count($acc_subpro_data); + + for ($isp = 0; $isp < $countQuotationSubproperty; $isp++) { + $accSubpropertyCart[$isp]['subproperty_id'] = $acc_subpro_data[$isp]->section_id; + $accSubpropertyCart[$isp]['subproperty_name'] = $acc_subpro_data[$isp]->section_name; + $accSubpropertyCart[$isp]['subproperty_oprand'] = $acc_subpro_data[$isp]->section_oprand; + } + + $accPropertyCart[$ip]['property_childs'] = $accSubpropertyCart; + } + + $generateAttributeCart[$ia]['attribute_childs'] = $accPropertyCart; + } + + $cart[$idx]['cart_attribute'] = $generateAttributeCart; + $cart[$idx]['cart_accessory'] = $generateAccessoryCart; + $cart[$idx]['wrapper_id'] = $data->product_wrapperid; + $cart[$idx]['wrapper_price'] = $data->wrapper_price; + $cart[$idx]['product_price_excl_vat'] = $data->product_excl_price; + + $cart['idx'] = $idx + 1; + + for ($i = 0, $in = count($row_data); $i < $in; $i++) { + $field_name = $row_data[$i]->field_name; + $cart[$idx][$field_name] = $row_data[$i]->data_txt; + } + + \Redshop\Cart\Helper::setCart($cart); + } + + public function modifyQuotation($user_id = 0) + { + $session = JFactory::getSession(); + $cart = $session->get('cart'); + + $cart = \Redshop\Cart\Cart::modify($cart, $user_id); + + \Redshop\Cart\Helper::setCart($cart); RedshopHelperCart::cartFinalCalculation(false); - } - - /** - * Add Quotation Detail Customer note - * - * @param array $data Quotation Detail Post Data - * - * @return void - */ - public function addQuotationCustomerNote($data) - { - // Initialize variables. - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - // Create the base update statement. - $query->update($db->quoteName('#__redshop_quotation')) - ->set($db->quoteName('quotation_customer_note') . ' = ' . $db->quote($data['quotation_customer_note'])) - ->where($db->quoteName('quotation_id') . ' = ' . (int) $data['quotation_id']); - - // Set the query and execute the update. - $db->setQuery($query); - - try - { - $db->execute(); - } - catch (RuntimeException $e) - { - throw new RuntimeException($e->getMessage(), $e->getCode()); - } - } + } + + /** + * Add Quotation Detail Customer note + * + * @param array $data Quotation Detail Post Data + * + * @return void + */ + public function addQuotationCustomerNote($data) + { + // Initialize variables. + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + // Create the base update statement. + $query->update($db->quoteName('#__redshop_quotation')) + ->set($db->quoteName('quotation_customer_note') . ' = ' . $db->quote($data['quotation_customer_note'])) + ->where($db->quoteName('quotation_id') . ' = ' . (int)$data['quotation_id']); + + // Set the query and execute the update. + $db->setQuery($query); + + try { + $db->execute(); + } catch (RuntimeException $e) { + throw new RuntimeException($e->getMessage(), $e->getCode()); + } + } } diff --git a/component/site/models/ratings.php b/component/site/models/ratings.php index 4853d103650..0e48f421e78 100644 --- a/component/site/models/ratings.php +++ b/component/site/models/ratings.php @@ -19,88 +19,89 @@ */ class RedshopModelRatings extends RedshopModel { - public $_id = null; - - public $_data = null; - - public $_table_prefix = null; - - public function __construct() - { - $app = JFactory::getApplication(); - parent::__construct(); - $this->_table_prefix = '#__redshop_'; - - $limit = $app->getUserStateFromRequest('limit', 'limit', $app->getCfg('list_limit'), 0); - $limitstart = $app->getUserStateFromRequest('limitstart', 'limitstart', 0); - $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0); - $this->setState('limit', $limit); - $this->setState('limitstart', $limitstart); - } - - public function _buildQuery() - { - $query = "SELECT distinct(p.product_id),p.product_name FROM " . $this->_table_prefix . "product p" - . ", " . $this->_table_prefix . "product_rating AS r " - . "WHERE p.published=1 AND r.published=1 AND p.product_id=r.product_id "; - - return $query; - } - - public function getData() - { - if (empty($this->_data)) - { - $query = $this->_buildQuery(); - $this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit')); - } - - return $this->_data; - } - - public function getTotal() - { - if (empty($this->_total)) - { - $query = $this->_buildQuery(); - $this->_total = $this->_getListCount($query); - } - - return $this->_total; - } - - public function getPagination() - { - if (empty($this->_pagination)) - { - JLoader::import('joomla.html.pagination'); - $this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit')); - } - - return $this->_pagination; - } - - public function getProductreviews($pid) - { - $db = $this->_db; - - $query = $db->getQuery(true) - ->select('pr.*', 'uf.firstname', 'uf.lastname') - ->from($db->qn('#__redshop_product_rating', 'pr')) - ->leftJoin($db->qn('#__redshop_users_info', 'uf') . 'ON pr.userid = uf.user_id') - ->where( - $db->qn('published') . ' = 1' .' AND ' . - $db->qn('product_id') . ' = ' . $db->q($pid) . ' AND ' . - $db->qn('uf.address_type') . ' LIKE ' . $db->q('BT') - ) - ->orWhere( - $db->qn('product_id') . ' = ' . $db->q($pid) . ' AND ' . - $db->qn('userid') . ' = ' . $db->q(0) - ); - - $this->_db->setQuery($query); - $this->_data = $this->_db->loadObjectlist(); - - return $this->_data; - } + public $_id = null; + + public $_data = null; + + public $_table_prefix = null; + + public function __construct() + { + $app = JFactory::getApplication(); + parent::__construct(); + $this->_table_prefix = '#__redshop_'; + + $limit = $app->getUserStateFromRequest('limit', 'limit', $app->getCfg('list_limit'), 0); + $limitstart = $app->getUserStateFromRequest('limitstart', 'limitstart', 0); + $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0); + $this->setState('limit', $limit); + $this->setState('limitstart', $limitstart); + } + + public function getData() + { + if (empty($this->_data)) { + $query = $this->_buildQuery(); + $this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit')); + } + + return $this->_data; + } + + public function _buildQuery() + { + $query = "SELECT distinct(p.product_id),p.product_name FROM " . $this->_table_prefix . "product p" + . ", " . $this->_table_prefix . "product_rating AS r " + . "WHERE p.published=1 AND r.published=1 AND p.product_id=r.product_id "; + + return $query; + } + + public function getPagination() + { + if (empty($this->_pagination)) { + JLoader::import('joomla.html.pagination'); + $this->_pagination = new JPagination( + $this->getTotal(), + $this->getState('limitstart'), + $this->getState('limit') + ); + } + + return $this->_pagination; + } + + public function getTotal() + { + if (empty($this->_total)) { + $query = $this->_buildQuery(); + $this->_total = $this->_getListCount($query); + } + + return $this->_total; + } + + public function getProductreviews($pid) + { + $db = $this->_db; + + $query = $db->getQuery(true) + ->select('pr.*', 'uf.firstname', 'uf.lastname') + ->from($db->qn('#__redshop_product_rating', 'pr')) + ->leftJoin($db->qn('#__redshop_users_info', 'uf') . 'ON pr.userid = uf.user_id') + ->where( + $db->qn('published') . ' = 1' . ' AND ' . + $db->qn('product_id') . ' = ' . $db->q($pid) . ' AND ' . + $db->qn('uf.address_type') . ' LIKE ' . $db->q('BT') + ) + ->orWhere( + $db->qn('product_id') . ' = ' . $db->q($pid) . ' AND ' . + $db->qn('userid') . ' = ' . $db->q(0) + ); + + $this->_db->setQuery($query); + $this->_data = $this->_db->loadObjectlist(); + + return $this->_data; + } } diff --git a/component/site/models/registration.php b/component/site/models/registration.php index a1c880ddac3..88f927ee6b5 100644 --- a/component/site/models/registration.php +++ b/component/site/models/registration.php @@ -10,7 +10,6 @@ defined('_JEXEC') or die; - /** * Class registrationModelregistration * @@ -20,52 +19,48 @@ */ class RedshopModelRegistration extends RedshopModel { - public $_id = null; + public $_id = null; - public $_data = null; + public $_data = null; - public $_table_prefix = null; + public $_table_prefix = null; - public function __construct() - { - parent::__construct(); + public function __construct() + { + parent::__construct(); - $this->_table_prefix = '#__redshop_'; - } + $this->_table_prefix = '#__redshop_'; + } - public function store(&$data) - { - $plugin = \JPluginHelper::getPlugin('captcha','recaptcha'); + public function store(&$data) + { + $plugin = \JPluginHelper::getPlugin('captcha', 'recaptcha'); $dataCaptcha = $data; - if ($plugin) - { - $params = new \Joomla\Registry\Registry($plugin->params); + if ($plugin) { + $params = new \Joomla\Registry\Registry($plugin->params); - if ($params->get('version', '') === '2.0') - { + if ($params->get('version', '') === '2.0') { $dataCaptcha = null; } } - $captcha = \Redshop\Helper\Utility::checkCaptcha($dataCaptcha); + $captcha = \Redshop\Helper\Utility::checkCaptcha($dataCaptcha); - if (!$captcha) - { - return false; - } + if (!$captcha) { + return false; + } - $joomlauser = \RedshopHelperJoomla::createJoomlaUser($data, 1); + $joomlauser = \RedshopHelperJoomla::createJoomlaUser($data, 1); - if (!$joomlauser) - { - return false; - } + if (!$joomlauser) { + return false; + } - $data['billisship'] = 1; - $reduser = \RedshopHelperUser::storeRedshopUser($data, $joomlauser->id); + $data['billisship'] = 1; + $reduser = \RedshopHelperUser::storeRedshopUser($data, $joomlauser->id); - return $reduser; - } + return $reduser; + } } diff --git a/component/site/models/search.php b/component/site/models/search.php index 267ba44b5ea..1a7e5cd22c3 100644 --- a/component/site/models/search.php +++ b/component/site/models/search.php @@ -22,1393 +22,1474 @@ */ class RedshopModelSearch extends RedshopModel { - /** - * @var JPagination - */ - public $pagination; - - // @ToDo In feature, when class Search extends RedshopModelList, replace filter_fields in constructor - public $filter_fields = array( - 'p.product_name ASC', 'product_name ASC', - 'p.product_price ASC', 'product_price ASC', - 'p.product_price DESC', 'product_price DESC', - 'p.product_number ASC', 'product_number ASC', - 'p.product_id DESC', 'product_id DESC', - 'pc.ordering ASC', 'ordering ASC' - ); - - /** - * Method to auto-populate the model state. - * - * This method should only be called once per instantiation and is designed - * to be called on the first call to the getState() method unless the model - * configuration flag to ignore the request is set. - * - * @param string $ordering An optional ordering field. - * @param string $direction An optional direction (asc|desc). - * - * @return void - * - * @note Calling getState in this method will result in recursion. - */ - protected function populateState($ordering = null, $direction = null) - { - parent::populateState($ordering, $direction); - - $app = JFactory::getApplication(); - $params = JComponentHelper::getParams('com_redshop'); - $menu = $app->getMenu(); - $item = $menu->getActive(); - $layout = $app->getUserStateFromRequest($this->context . '.layout', 'layout', 'default'); - $this->setState('layout', $layout); - - $templateid = $app->getUserStateFromRequest($this->context . '.templateid', 'templateid', ''); - - $cid = 0; - - if ($layout == 'newproduct') { - $result = $item->query['template_id']; - - if ($result != 0) { - $templateid = $result; - } else { - $cid = $item->query['categorytemplate']; - } - } elseif ($layout == 'productonsale') { - $cid = $item->params->get('categorytemplate'); - } - - if ($layout == 'productonsale' || $layout == 'featuredproduct') { - $result = $item->params->get('template_id'); - - if ($result != 0) { - $templateid = $result; - $cid = 0; - } - } - - if ($templateid == "" && JModuleHelper::isEnabled('redPRODUCTFILTER')) { - $module = JModuleHelper::getModule('redPRODUCTFILTER'); - $module_params = new Registry($module->params); - - if ($module_params->get('filtertemplate') != "") { - $templateid = $module_params->get('filtertemplate'); - } - } - - $this->setState('templateid', $templateid); - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('c.template AS category_template, t.*') - ->from($db->qn('#__redshop_template', 't')) - ->leftJoin($db->qn('#__redshop_category', 'c') . ' ON t.id = c.template') - ->where('t.section = ' . $db->q('category')) - ->where('t.published = 1'); - - if ($cid != 0) { - $query->where('c.id = ' . (int) $cid); - } - - if ($templateid != 0) { - $query->where('t.id = ' . (int) $templateid); - } - - $templateDesc = null; - - if ($template = $db->setQuery($query)->loadObject()) { - $templateDesc = RedshopHelperTemplate::readTemplateFile($template->section, $template->file_name); - } - - $this->setState('templateDesc', $templateDesc); - $limit = 0; - - if ($module = JModuleHelper::getModule('redshop_search')) { - $module_params = new Registry($module->params); - $perpageproduct = $module_params->get('productperpage', 5); - } else { - $perpageproduct = 5; - } - - if ( - !strstr($templateDesc, "{show_all_products_in_category}") - && strstr($templateDesc, "{pagination}") - && strstr($templateDesc, "perpagelimit:") - ) { - $perpage = explode('{perpagelimit:', $templateDesc); - $perpage = explode('}', $perpage[1]); - $limit = intval($perpage[0]); - } else { - $limit = $app->getUserStateFromRequest($this->context . '.limit', 'limit', $limit, 'int'); - - if (!$limit && $perpageproduct != 0 && $perpageproduct != '' && $layout == 'default') { - $limit = $perpageproduct; - } elseif (!$limit && $layout == 'productonsale') { - $limit = $params->get('productlimit', 5); - } elseif (!$limit) { - $limit = Redshop::getConfig()->get('MAXCATEGORY'); - } - } - - $productlimit = 0; - - if (isset($item->query['productlimit'])) { - $productlimit = $item->query['productlimit']; - } - - $filter = $app->input->post->get('redform', array(), 'filter'); - $this->setState('filter.data', $filter); - - $orderBy = $app->input->getString('order_by', ''); - $this->setState('order_by', $orderBy); - $this->setState('template_id', isset($filter['template_id']) ? $filter['template_id'] : null); - - $this->setState('productperpage', $perpageproduct); - $this->setState('list.limit', $limit); - $productlimit = $app->getUserStateFromRequest($this->context . '.productlimit', 'productlimit', $productlimit, 8); - $this->setState('productlimit', $productlimit); - - $value = $app->input->get('limitstart', 0, 'int'); - $limitstart = ($limit != 0 ? (floor($value / $limit) * $limit) : 0); - $this->setState('list.start', $limitstart); - - $keyword = $app->getUserStateFromRequest($this->context . '.keyword', 'keyword', ''); - $this->setState('keyword', $keyword); - } - - /** - * Method to get a store id based on the model configuration state. - * - * This is necessary because the model is used by the component and - * different modules that might need different sets of data or different - * ordering requirements. - * - * @param string $id An identifier string to generate the store id. - * - * @return string A store id. - * - * @since 1.5 - */ - protected function getStoreId($id = '') - { - // Add the list state to the store id. - $id .= ':' . $this->getState('productperpage'); - $id .= ':' . $this->getState('productlimit'); - $id .= ':' . $this->getState('templateid'); - $id .= ':' . $this->getState('keyword'); - $id .= ':' . $this->getState('layout'); - - return md5($this->context . ':' . $id); - } - - /** - * Method to get the starting number of items for the data set. - * - * @return integer The starting number of items available in the data set. - * - * @since 1.5 - */ - public function getStart() - { - $store = $this->getStoreId('getstart'); - - // Try to load the data from internal storage. - if (isset($this->cache[$store])) { - return $this->cache[$store]; - } - - $start = $this->getState('list.start'); - $limit = $this->getState('list.limit'); - $total = $this->getTotal(); - - if ($start > $total - $limit) { - $start = max(0, (int) (ceil($total / $limit) - 1) * $limit); - } - - // Add the total to the internal cache. - $this->cache[$store] = $start; - - return $this->cache[$store]; - } - - /** - * Method to get an array of data items. - * - * @return mixed An array of data items on success, false on failure. - * - * @since 1.5 - */ - public function getData() - { - // Get a storage key. - $store = $this->getStoreId(); - - // Try to load the data from internal storage. - if (isset($this->cache[$store])) { - return $this->cache[$store]; - } - - $post = JFactory::getApplication()->input->post->getArray(); - $db = JFactory::getDbo(); - $items = array(); - $query = $this->_buildQuery($post); - $templateDesc = $this->getState('templateDesc'); - - if ($templateDesc) { - if (strstr($templateDesc, "{show_all_products_in_category}")) { - $db->setQuery($query); - } elseif (strstr($templateDesc, "{pagination}") || $this->getState('productlimit') > 0) { - $db->setQuery($query, $this->getStart(), $this->getState('list.limit')); - } else { - $db->setQuery($query); - } - } else { - $db->setQuery($query); - } - - if ($productIds = $db->loadColumn()) { - // Third steep get all product relate info - $query->clear() - ->where('p.product_id IN (' . implode(',', $productIds) . ')') - ->order('FIELD(p.product_id, ' . implode(',', $productIds) . ')'); - - $user = JFactory::getUser(); - $query = \Redshop\Product\Product::getMainProductQuery($query, $user->id) - ->select( - array( - 'pc.ordering', 'c.*', 'm.*', - 'CONCAT_WS(' . $db->q('.') . ', p.product_id, ' . (int) $user->id . ') AS concat_id' - ) - ) - ->select($db->qn('c.id', 'category_id')) - ->select($db->qn('c.name', 'category_name')) - ->leftJoin('#__redshop_category AS c ON c.id = pc.category_id') - ->leftJoin('#__redshop_manufacturer AS m ON m.id = p.manufacturer_id'); - - if ($products = $db->setQuery($query)->loadObjectList('concat_id')) { - \Redshop\Product\Product::setProduct($products); - $items = array_values($products); - } - } - - $this->preprocessData($this->context, $items); - - // Add the items to the internal cache. - $this->cache[$store] = $items; - - return $this->cache[$store]; - } - - /** - * Method to get the total number of items for the data set. - * - * @return integer The total number of items available in the data set. - * - * @since 1.5 - */ - public function getTotal() - { - // Get a storage key. - $store = $this->getStoreId('getTotal'); - - // Try to load the data from internal storage. - if (isset($this->cache[$store])) { - return $this->cache[$store]; - } - - $productlimit = $this->getState('productlimit'); - $layout = $this->getState('layout', 'default'); - - $db = JFactory::getDbo(); - $total = $db->setQuery($this->_buildQuery(0, true)) - ->loadResult(); - - if ($layout == 'newproduct' || $layout == 'productonsale') { - if ($total > $productlimit && $productlimit != "") { - $total = $productlimit; - } - } - - // Add the total to the internal cache. - $this->cache[$store] = $total; - - return $this->cache[$store]; - } - - /** - * Get Search Condition - * - * @param array|string $fields Fields - * @param array|string $condition Condition - * @param string $glue Glue - * - * @return string - */ - public function getSearchCondition($fields, $condition, $glue = 'OR') - { - $condition = trim($condition); - - if (empty($condition)) { - return '1 = 1'; - } - - $where = array(); - $db = JFactory::getDbo(); - $conditions = explode(' ', trim($condition)); - - if (!is_array($fields)) { - $fields = array($fields, 'fds.data_txt'); - } else { - $fields[] = 'fds.data_txt'; - } - - foreach ((array) $fields as $field) { - $glueOneField = array(); - - foreach ((array) $conditions as $con) { - $con = trim($con); - - if ($con != '') { - $glueOneField[] = $db->qn($field) . ' LIKE ' . $db->quote($con . '%'); - } - } - - $where[] = '(' . implode(' AND ', $glueOneField) . ')'; - - // Full condition - $where[] = $db->qn($field) . ' LIKE ' . $db->quote('%' . $condition . '%'); - } - - if (!empty($where)) { - return '(' . implode(' ' . $glue . ' ', $where) . ')'; - } else { - return '1 = 1'; - } - } - - public function getSearchableProductCustomfields() - { - $db = JFactory::getDbo(); - - $subQuery = $db->getQuery(true) - ->select($db->qn('id')) - ->from($db->qn('#__redshop_fields')) - ->where($db->qn('published') . ' = 1') - ->where($db->qn('section') . ' = 1') // product section - ->where($db->qn('type') . ' IN(1,2)') // text input or text area - ->where($db->qn('is_searchable') . ' = 1'); - - return $db->setQuery($subQuery)->loadColumn(); - } - - /** - * Build query - * - * @param int|array $manudata Post request - * @param bool $getTotal Get total product(true) or product data(false) - * - * @return JDatabaseQuery - */ - public function _buildQuery($manudata = 0, $getTotal = false) - { - $app = JFactory::getApplication(); - $input = $app->input; - $db = JFactory::getDbo(); - - $orderByMethod = $input->getString( - 'order_by', - $app->getParams()->get('order_by', Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD')) - ); - $orderByObj = RedshopHelperUtility::prepareOrderBy(urldecode($orderByMethod)); - $orderBy = $orderByObj->ordering . ' ' . $orderByObj->direction; - - if ($getTotal) { - $query = $db->getQuery(true) - ->select('COUNT(DISTINCT(p.product_id))'); - } else { - $query = $db->getQuery(true) - ->select('DISTINCT(p.product_id)') - ->leftJoin($db->qn('#__redshop_manufacturer', 'm') . ' ON m.id = p.manufacturer_id') - ->order($db->escape($orderBy)); - } - - $query->from($db->qn('#__redshop_product', 'p')) - ->leftJoin($db->qn('#__redshop_product_category_xref', 'pc') . ' ON pc.product_id = p.product_id') - ->where('p.published = 1'); - - $layout = $input->getString('layout', 'default'); - $manufacture_id = $input->getInt('manufacture_id', 0); - $cat_group = array(); - $customField = $input->get('custom_field', array(), 'array'); - - if ($category_id = $input->get('category_id', 0)) { - $cat = RedshopHelperCategory::getCategoryListArray(0, $category_id); - - if (is_array($cat) && count($cat) > 0) { - for ($j = 0, $countCat = count($cat); $j < $countCat; $j++) { - $cat_group[$j] = $cat[$j]->category_id; - - if ($j == count($cat) - 1) { - $cat_group[$j + 1] = $category_id; - } - } - } - - $cat_group = ArrayHelper::toInteger($cat_group); - - if (!empty($cat_group)) { - $cat_group = join(',', $cat_group); - } else { - $cat_group = $category_id; - } - } - - $menu = $app->getMenu(); - $item = $menu->getActive(); - $days = isset($item->query['newproduct']) ? $item->query['newproduct'] : 0; - $today = date('Y-m-d H:i:s', time()); - $days_before = date('Y-m-d H:i:s', time() - ($days * 60 * 60 * 24)); - $aclProducts = RedshopHelperProduct::loadAclProducts(); - - // Shopper group - choose from manufactures Start - $shopper_group_manufactures = RedshopHelperShopper_Group::getShopperGroupManufacturers(); - - if ($shopper_group_manufactures != "") { - // Sanitize ids - $manufacturerIds = explode(',', $shopper_group_manufactures); - $manufacturerIds = ArrayHelper::toInteger($manufacturerIds); - - $query->where('p.manufacturer_id IN (' . implode(',', $manufacturerIds) . ')'); - } - - if (!empty($customField)) { - $key = 0; - $subQuery = array(); - - foreach ($customField as $fieldId => $fieldValue) { - if (empty($fieldValue)) { - continue; - } - - $subQuery[] = 'FIND_IN_SET("' . $fieldValue . '", ' . $db->qn('fd' . $key . '.data_txt') . ')'; - - $query->leftJoin( - $db->qn('#__redshop_fields_data', 'fd' . $key) - . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('fd' . $key . '.itemid') - ) - ->where($db->qn('fd' . $key . '.fieldid') . ' = ' . $db->q((int) $fieldId)); - $key++; - } - - if (!empty($subQuery)) { - $query->where('(' . implode(' OR ', $subQuery) . ')'); - } - } - - // Shopper group - choose from manufactures End - if ($aclProducts != "") { - // Sanitize ids - $productIds = explode(',', $aclProducts); - $productIds = ArrayHelper::toInteger($productIds); - - $query->where('p.product_id IN (' . implode(',', $productIds) . ')'); - } - - $excludeCategories = $app->input->getString('excludeCategories', ''); - - if (!empty($excludeCategories)) { - $excludeCategories = explode(',', $excludeCategories); - $excludeCategories = ArrayHelper::toInteger($excludeCategories); - $query->where('pc.category_id NOT IN (' . implode(',', $excludeCategories) . ')'); - } - - if ($layout == 'productonsale') { - $categoryid = $item->params->get('categorytemplate'); - - if ($categoryid) { - $catMain = RedshopHelperCategory::getCategoryTree($categoryid); - $catGroupMain = array(); - - foreach ($catMain as $row) { - $catGroupMain[] = $row->id; - } - - $catGroupMain[] = $categoryid; - $catGroupMain = ArrayHelper::toInteger($catGroupMain); - - $query->where('pc.category_id IN (' . implode(',', $catGroupMain) . ')'); - } - - $query->where( - array( - 'p.product_on_sale = 1', - 'p.expired = 0', - 'p.product_parent_id = 0', - 'UNIX_TIMESTAMP() BETWEEN p.discount_stratdate AND p.discount_enddate', - 'p.discount_price > 0' - ) - ); - } elseif ($layout == 'featuredproduct') { - $query->where('p.product_special = 1'); - } elseif ($layout == 'newproduct') { - $categoryid = $item->params->get('categorytemplate'); - - if ($categoryid) { - $catMain = RedshopHelperCategory::getCategoryTree($categoryid); - $catGroupMain = array(); - - foreach ($catMain as $row) { - $catGroupMain[] = $row->id; - } - - $catGroupMain[] = $categoryid; - $catGroupMain = ArrayHelper::toInteger($catGroupMain); - - $query->where('pc.category_id IN (' . implode(',', $catGroupMain) . ')'); - } - - $query->where('p.publish_date BETWEEN ' . $db->quote($days_before) . ' AND ' . $db->quote($today)) - ->where('p.expired = 0') - ->where('p.product_parent_id = 0'); - } elseif ($layout == 'redfilter') { - $query->where('p.expired = 0'); - - // Get products for filtering - if ($products = $this->getRedFilterProduct()) { - // Sanitize ids - $productIds = explode(',', $products); - $productIds = ArrayHelper::toInteger($productIds); - - $query->where('p.product_id IN ( ' . implode(',', $productIds) . ')'); - } - } else { - $keyword = $this->getState('keyword'); - - $fieldSearchable = $this->getSearchableProductCustomfields(); - $joinSearchable = !$fieldSearchable ? '' : (' AND ' . $db->qn('fds.fieldid') . ' IN (' - . implode(",", $fieldSearchable) . ')'); - $query->leftJoin($db->qn('#__redshop_fields_data', 'fds') . ' ON p.product_id = fds.itemid' - . $joinSearchable); - - $defaultSearchType = $app->input->getCmd('search_type', 'product_name'); - - if (!empty($manudata['search_type'])) { - $defaultSearchType = $manudata['search_type']; - } - - if ($defaultSearchType == "name_number_desc" || $defaultSearchType == "virtual_product_num") { - $query->leftJoin($db->qn('#__redshop_product_attribute', 'a') . ' ON a.product_id = p.product_id') - ->leftJoin($db->qn('#__redshop_product_attribute_property', 'pap') . ' ON pap.attribute_id = a.attribute_id') - ->leftJoin($db->qn('#__redshop_product_subattribute_color', 'ps') . ' ON ps.subattribute_id = pap.property_id'); - } - - $columnsCondition = array(); - - switch ($defaultSearchType) { - case 'name_number': - $columnsCondition = array('p.product_name', 'p.product_number'); - break; - case 'name_desc': - $columnsCondition = array('p.product_name', 'p.product_desc', 'p.product_s_desc'); - break; - case 'virtual_product_num': - $columnsCondition = array('pap.property_number', 'ps.subattribute_color_number'); - break; - case 'name_number_desc': - $columnsCondition = array( - 'p.product_name', 'p.product_number', 'p.product_desc', 'p.product_s_desc', 'pap.property_number', - 'ps.subattribute_color_number' - ); - break; - case 'product_desc': - $columnsCondition = array('p.product_s_desc', 'p.product_desc'); - break; - case 'product_name': - $columnsCondition = array('p.product_name'); - break; - case 'product_number': - $columnsCondition = array('p.product_number'); - break; - } - - if ($input->getString('searchProductByCategoryName') == 'yes') { - $query->leftJoin($db->qn('#__redshop_category', 'c') . ' ON pc.category_id = c.id'); - $columnsCondition[] = 'c.name'; - } - - $query->where($this->getSearchCondition($columnsCondition, $keyword)); - - if ($manufacture_id == 0) { - if (!empty($manudata['manufacturer_id'])) { - $manufacture_id = $manudata['manufacturer_id']; - } - } - - $query->where('p.expired = 0'); - - if ($category_id != 0) { - // Sanitize ids - $cat_group = explode(',', $cat_group); - $cat_group = ArrayHelper::toInteger($cat_group); - - $query->where('pc.category_id IN (' . implode(',', $cat_group) . ')'); - } - - if ($manufacture_id != 0) { - $query->where('p.manufacturer_id = ' . (int) $manufacture_id); - } - } - - JPluginHelper::importPlugin('redshop_product'); - JDispatcher::getInstance()->trigger('onFilterProduct', array(&$query, 0)); - - return $query; - } - - /** - * Red Product Filter - */ - public function getRedFilterProduct($remove = 0) - { - // Get seeion filter data - - $session = JSession::getInstance('none', array()); - - // Get filter types and tags - $getredfilter = $session->get('redfilter'); - - $app = JFactory::getApplication(); - - $type_id_main = explode('.', $app->input->get('tagid')); - - // Initialise variables - $lstproduct_id = array(); - $products = ""; - - if (!empty($getredfilter)) { - $main_sal_sp = array(); - $main_sal_type = array(); - $main_sal_tag = array(); - - if ($app->input->get('main_sel') != "") { - $main_sal_sp = explode(",", $app->input->get('main_sel')); - - for ($f = 0, $fn = count($main_sal_sp); $f < $fn; $f++) { - if ($main_sal_sp[$f] != "") { - $main_typeid = explode(".", $main_sal_sp[$f]); - $main_sal_type[] = $main_typeid[1]; - $main_sal_tag[] = $main_typeid[0]; - } - } - } - - $q = "SELECT a.product_id + /** + * @var JPagination + */ + public $pagination; + + // @ToDo In feature, when class Search extends RedshopModelList, replace filter_fields in constructor + public $filter_fields = array( + 'p.product_name ASC', + 'product_name ASC', + 'p.product_price ASC', + 'product_price ASC', + 'p.product_price DESC', + 'product_price DESC', + 'p.product_number ASC', + 'product_number ASC', + 'p.product_id DESC', + 'product_id DESC', + 'pc.ordering ASC', + 'ordering ASC' + ); + + /** + * Method to get an array of data items. + * + * @return mixed An array of data items on success, false on failure. + * + * @since 1.5 + */ + public function getData() + { + // Get a storage key. + $store = $this->getStoreId(); + + // Try to load the data from internal storage. + if (isset($this->cache[$store])) { + return $this->cache[$store]; + } + + $post = JFactory::getApplication()->input->post->getArray(); + $db = JFactory::getDbo(); + $items = array(); + $query = $this->_buildQuery($post); + $templateDesc = $this->getState('templateDesc'); + + if ($templateDesc) { + if (strstr($templateDesc, "{show_all_products_in_category}")) { + $db->setQuery($query); + } elseif (strstr($templateDesc, "{pagination}") || $this->getState('productlimit') > 0) { + $db->setQuery($query, $this->getStart(), $this->getState('list.limit')); + } else { + $db->setQuery($query); + } + } else { + $db->setQuery($query); + } + + if ($productIds = $db->loadColumn()) { + // Third steep get all product relate info + $query->clear() + ->where('p.product_id IN (' . implode(',', $productIds) . ')') + ->order('FIELD(p.product_id, ' . implode(',', $productIds) . ')'); + + $user = JFactory::getUser(); + $query = \Redshop\Product\Product::getMainProductQuery($query, $user->id) + ->select( + array( + 'pc.ordering', + 'c.*', + 'm.*', + 'CONCAT_WS(' . $db->q('.') . ', p.product_id, ' . (int)$user->id . ') AS concat_id' + ) + ) + ->select($db->qn('c.id', 'category_id')) + ->select($db->qn('c.name', 'category_name')) + ->leftJoin('#__redshop_category AS c ON c.id = pc.category_id') + ->leftJoin('#__redshop_manufacturer AS m ON m.id = p.manufacturer_id'); + + if ($products = $db->setQuery($query)->loadObjectList('concat_id')) { + \Redshop\Product\Product::setProduct($products); + $items = array_values($products); + } + } + + $this->preprocessData($this->context, $items); + + // Add the items to the internal cache. + $this->cache[$store] = $items; + + return $this->cache[$store]; + } + + /** + * Method to get a store id based on the model configuration state. + * + * This is necessary because the model is used by the component and + * different modules that might need different sets of data or different + * ordering requirements. + * + * @param string $id An identifier string to generate the store id. + * + * @return string A store id. + * + * @since 1.5 + */ + protected function getStoreId($id = '') + { + // Add the list state to the store id. + $id .= ':' . $this->getState('productperpage'); + $id .= ':' . $this->getState('productlimit'); + $id .= ':' . $this->getState('templateid'); + $id .= ':' . $this->getState('keyword'); + $id .= ':' . $this->getState('layout'); + + return md5($this->context . ':' . $id); + } + + /** + * Build query + * + * @param int|array $manudata Post request + * @param bool $getTotal Get total product(true) or product data(false) + * + * @return JDatabaseQuery + */ + public function _buildQuery($manudata = 0, $getTotal = false) + { + $app = JFactory::getApplication(); + $input = $app->input; + $db = JFactory::getDbo(); + + $orderByMethod = $input->getString( + 'order_by', + $app->getParams()->get('order_by', Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD')) + ); + $orderByObj = RedshopHelperUtility::prepareOrderBy(urldecode($orderByMethod)); + $orderBy = $orderByObj->ordering . ' ' . $orderByObj->direction; + + if ($getTotal) { + $query = $db->getQuery(true) + ->select('COUNT(DISTINCT(p.product_id))'); + } else { + $query = $db->getQuery(true) + ->select('DISTINCT(p.product_id)') + ->leftJoin($db->qn('#__redshop_manufacturer', 'm') . ' ON m.id = p.manufacturer_id') + ->order($db->escape($orderBy)); + } + + $query->from($db->qn('#__redshop_product', 'p')) + ->leftJoin($db->qn('#__redshop_product_category_xref', 'pc') . ' ON pc.product_id = p.product_id') + ->where('p.published = 1'); + + $layout = $input->getString('layout', 'default'); + $manufacture_id = $input->getInt('manufacture_id', 0); + $cat_group = array(); + $customField = $input->get('custom_field', array(), 'array'); + + if ($category_id = $input->get('category_id', 0)) { + $cat = RedshopHelperCategory::getCategoryListArray(0, $category_id); + + if (is_array($cat) && count($cat) > 0) { + for ($j = 0, $countCat = count($cat); $j < $countCat; $j++) { + $cat_group[$j] = $cat[$j]->category_id; + + if ($j == count($cat) - 1) { + $cat_group[$j + 1] = $category_id; + } + } + } + + $cat_group = ArrayHelper::toInteger($cat_group); + + if (!empty($cat_group)) { + $cat_group = join(',', $cat_group); + } else { + $cat_group = $category_id; + } + } + + $menu = $app->getMenu(); + $item = $menu->getActive(); + $days = isset($item->query['newproduct']) ? $item->query['newproduct'] : 0; + $today = date('Y-m-d H:i:s', time()); + $days_before = date('Y-m-d H:i:s', time() - ($days * 60 * 60 * 24)); + $aclProducts = RedshopHelperProduct::loadAclProducts(); + + // Shopper group - choose from manufactures Start + $shopper_group_manufactures = RedshopHelperShopper_Group::getShopperGroupManufacturers(); + + if ($shopper_group_manufactures != "") { + // Sanitize ids + $manufacturerIds = explode(',', $shopper_group_manufactures); + $manufacturerIds = ArrayHelper::toInteger($manufacturerIds); + + $query->where('p.manufacturer_id IN (' . implode(',', $manufacturerIds) . ')'); + } + + if (!empty($customField)) { + $key = 0; + $subQuery = array(); + + foreach ($customField as $fieldId => $fieldValue) { + if (empty($fieldValue)) { + continue; + } + + $subQuery[] = 'FIND_IN_SET("' . $fieldValue . '", ' . $db->qn('fd' . $key . '.data_txt') . ')'; + + $query->leftJoin( + $db->qn('#__redshop_fields_data', 'fd' . $key) + . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('fd' . $key . '.itemid') + ) + ->where($db->qn('fd' . $key . '.fieldid') . ' = ' . $db->q((int)$fieldId)); + $key++; + } + + if (!empty($subQuery)) { + $query->where('(' . implode(' OR ', $subQuery) . ')'); + } + } + + // Shopper group - choose from manufactures End + if ($aclProducts != "") { + // Sanitize ids + $productIds = explode(',', $aclProducts); + $productIds = ArrayHelper::toInteger($productIds); + + $query->where('p.product_id IN (' . implode(',', $productIds) . ')'); + } + + $excludeCategories = $app->input->getString('excludeCategories', ''); + + if (!empty($excludeCategories)) { + $excludeCategories = explode(',', $excludeCategories); + $excludeCategories = ArrayHelper::toInteger($excludeCategories); + $query->where('pc.category_id NOT IN (' . implode(',', $excludeCategories) . ')'); + } + + if ($layout == 'productonsale') { + $categoryid = $item->params->get('categorytemplate'); + + if ($categoryid) { + $catMain = RedshopHelperCategory::getCategoryTree($categoryid); + $catGroupMain = array(); + + foreach ($catMain as $row) { + $catGroupMain[] = $row->id; + } + + $catGroupMain[] = $categoryid; + $catGroupMain = ArrayHelper::toInteger($catGroupMain); + + $query->where('pc.category_id IN (' . implode(',', $catGroupMain) . ')'); + } + + $query->where( + array( + 'p.product_on_sale = 1', + 'p.expired = 0', + 'p.product_parent_id = 0', + 'UNIX_TIMESTAMP() BETWEEN p.discount_stratdate AND p.discount_enddate', + 'p.discount_price > 0' + ) + ); + } elseif ($layout == 'featuredproduct') { + $query->where('p.product_special = 1'); + } elseif ($layout == 'newproduct') { + $categoryid = $item->params->get('categorytemplate'); + + if ($categoryid) { + $catMain = RedshopHelperCategory::getCategoryTree($categoryid); + $catGroupMain = array(); + + foreach ($catMain as $row) { + $catGroupMain[] = $row->id; + } + + $catGroupMain[] = $categoryid; + $catGroupMain = ArrayHelper::toInteger($catGroupMain); + + $query->where('pc.category_id IN (' . implode(',', $catGroupMain) . ')'); + } + + $query->where('p.publish_date BETWEEN ' . $db->quote($days_before) . ' AND ' . $db->quote($today)) + ->where('p.expired = 0') + ->where('p.product_parent_id = 0'); + } elseif ($layout == 'redfilter') { + $query->where('p.expired = 0'); + + // Get products for filtering + if ($products = $this->getRedFilterProduct()) { + // Sanitize ids + $productIds = explode(',', $products); + $productIds = ArrayHelper::toInteger($productIds); + + $query->where('p.product_id IN ( ' . implode(',', $productIds) . ')'); + } + } else { + $keyword = $this->getState('keyword'); + + $fieldSearchable = $this->getSearchableProductCustomfields(); + $joinSearchable = !$fieldSearchable ? '' : (' AND ' . $db->qn('fds.fieldid') . ' IN (' + . implode(",", $fieldSearchable) . ')'); + $query->leftJoin( + $db->qn('#__redshop_fields_data', 'fds') . ' ON p.product_id = fds.itemid' + . $joinSearchable + ); + + $defaultSearchType = $app->input->getCmd('search_type', 'product_name'); + + if (!empty($manudata['search_type'])) { + $defaultSearchType = $manudata['search_type']; + } + + if ($defaultSearchType == "name_number_desc" || $defaultSearchType == "virtual_product_num") { + $query->leftJoin($db->qn('#__redshop_product_attribute', 'a') . ' ON a.product_id = p.product_id') + ->leftJoin( + $db->qn( + '#__redshop_product_attribute_property', + 'pap' + ) . ' ON pap.attribute_id = a.attribute_id' + ) + ->leftJoin( + $db->qn( + '#__redshop_product_subattribute_color', + 'ps' + ) . ' ON ps.subattribute_id = pap.property_id' + ); + } + + $columnsCondition = array(); + + switch ($defaultSearchType) { + case 'name_number': + $columnsCondition = array('p.product_name', 'p.product_number'); + break; + case 'name_desc': + $columnsCondition = array('p.product_name', 'p.product_desc', 'p.product_s_desc'); + break; + case 'virtual_product_num': + $columnsCondition = array('pap.property_number', 'ps.subattribute_color_number'); + break; + case 'name_number_desc': + $columnsCondition = array( + 'p.product_name', + 'p.product_number', + 'p.product_desc', + 'p.product_s_desc', + 'pap.property_number', + 'ps.subattribute_color_number' + ); + break; + case 'product_desc': + $columnsCondition = array('p.product_s_desc', 'p.product_desc'); + break; + case 'product_name': + $columnsCondition = array('p.product_name'); + break; + case 'product_number': + $columnsCondition = array('p.product_number'); + break; + } + + if ($input->getString('searchProductByCategoryName') == 'yes') { + $query->leftJoin($db->qn('#__redshop_category', 'c') . ' ON pc.category_id = c.id'); + $columnsCondition[] = 'c.name'; + } + + $query->where($this->getSearchCondition($columnsCondition, $keyword)); + + if ($manufacture_id == 0) { + if (!empty($manudata['manufacturer_id'])) { + $manufacture_id = $manudata['manufacturer_id']; + } + } + + $query->where('p.expired = 0'); + + if ($category_id != 0) { + // Sanitize ids + $cat_group = explode(',', $cat_group); + $cat_group = ArrayHelper::toInteger($cat_group); + + $query->where('pc.category_id IN (' . implode(',', $cat_group) . ')'); + } + + if ($manufacture_id != 0) { + $query->where('p.manufacturer_id = ' . (int)$manufacture_id); + } + } + + JPluginHelper::importPlugin('redshop_product'); + JDispatcher::getInstance()->trigger('onFilterProduct', array(&$query, 0)); + + return $query; + } + + /** + * Red Product Filter + */ + public function getRedFilterProduct($remove = 0) + { + // Get seeion filter data + + $session = JSession::getInstance('none', array()); + + // Get filter types and tags + $getredfilter = $session->get('redfilter'); + + $app = JFactory::getApplication(); + + $type_id_main = explode('.', $app->input->get('tagid')); + + // Initialise variables + $lstproduct_id = array(); + $products = ""; + + if (!empty($getredfilter)) { + $main_sal_sp = array(); + $main_sal_type = array(); + $main_sal_tag = array(); + + if ($app->input->get('main_sel') != "") { + $main_sal_sp = explode(",", $app->input->get('main_sel')); + + for ($f = 0, $fn = count($main_sal_sp); $f < $fn; $f++) { + if ($main_sal_sp[$f] != "") { + $main_typeid = explode(".", $main_sal_sp[$f]); + $main_sal_type[] = $main_typeid[1]; + $main_sal_tag[] = $main_typeid[0]; + } + } + } + + $q = "SELECT a.product_id FROM #__redproductfinder_association_tag AS ta LEFT JOIN #__redproductfinder_associations AS a ON a.id = ta.association_id LEFT JOIN #__redshop_product AS p ON p.product_id = a.product_id LEFT JOIN #__redshop_product_category_xref x ON x.product_id = a.product_id "; - for ($i = 0, $in = count($main_sal_type); $i < $in; $i++) { - if ($i != 0) { - $q .= " LEFT JOIN #__redproductfinder_association_tag AS t" . $i . " ON t" . $i . ".association_id=ta.association_id "; - } - } - - $q .= "where ( "; - $dep_cond = array(); - - for ($i = 0, $in = count($main_sal_type); $i < $in; $i++) { - $chk_q = ""; - - // Search for checkboxes - if ($i != 0) { - $chk_q .= "t" . $i . ".tag_id='" . (int) $main_sal_tag[$i] . "' "; - } else { - $chk_q .= "ta.tag_id='" . (int) $main_sal_tag[$i] . "' "; - } - - if ($chk_q != "") { - $dep_cond[] = " ( " . $chk_q . " ) "; - } - } - - if (count($dep_cond) <= 0) { - $dep_cond[] = "1=1"; - } - - $q .= implode(" AND ", $dep_cond); - - $q .= ") AND p.published = '1' AND x.category_id = " . (int) JRequest::getInt('cid', 0) . " order by p.product_name "; - $product = $this->_getList($q); - - for ($i = 0, $in = count($product); $i < $in; $i++) { - $lstproduct_id[] = $product[$i]->product_id; - } - - $products = implode(",", $lstproduct_id); - } else { - $session->set('redfilterproduct', array()); - } - - return $products; - } - - public function mod_redProductfilter($Itemid) - { - $db = JFactory::getDbo(); - $query = "SELECT t.*, f.formname AS form_name FROM #__redproductfinder_types t + for ($i = 0, $in = count($main_sal_type); $i < $in; $i++) { + if ($i != 0) { + $q .= " LEFT JOIN #__redproductfinder_association_tag AS t" . $i . " ON t" . $i . ".association_id=ta.association_id "; + } + } + + $q .= "where ( "; + $dep_cond = array(); + + for ($i = 0, $in = count($main_sal_type); $i < $in; $i++) { + $chk_q = ""; + + // Search for checkboxes + if ($i != 0) { + $chk_q .= "t" . $i . ".tag_id='" . (int)$main_sal_tag[$i] . "' "; + } else { + $chk_q .= "ta.tag_id='" . (int)$main_sal_tag[$i] . "' "; + } + + if ($chk_q != "") { + $dep_cond[] = " ( " . $chk_q . " ) "; + } + } + + if (count($dep_cond) <= 0) { + $dep_cond[] = "1=1"; + } + + $q .= implode(" AND ", $dep_cond); + + $q .= ") AND p.published = '1' AND x.category_id = " . (int)JRequest::getInt( + 'cid', + 0 + ) . " order by p.product_name "; + $product = $this->_getList($q); + + for ($i = 0, $in = count($product); $i < $in; $i++) { + $lstproduct_id[] = $product[$i]->product_id; + } + + $products = implode(",", $lstproduct_id); + } else { + $session->set('redfilterproduct', array()); + } + + return $products; + } + + public function getSearchableProductCustomfields() + { + $db = JFactory::getDbo(); + + $subQuery = $db->getQuery(true) + ->select($db->qn('id')) + ->from($db->qn('#__redshop_fields')) + ->where($db->qn('published') . ' = 1') + ->where($db->qn('section') . ' = 1') // product section + ->where($db->qn('type') . ' IN(1,2)') // text input or text area + ->where($db->qn('is_searchable') . ' = 1'); + + return $db->setQuery($subQuery)->loadColumn(); + } + + /** + * Get Search Condition + * + * @param array|string $fields Fields + * @param array|string $condition Condition + * @param string $glue Glue + * + * @return string + */ + public function getSearchCondition($fields, $condition, $glue = 'OR') + { + $condition = trim($condition); + + if (empty($condition)) { + return '1 = 1'; + } + + $where = array(); + $db = JFactory::getDbo(); + $conditions = explode(' ', trim($condition)); + + if (!is_array($fields)) { + $fields = array($fields, 'fds.data_txt'); + } else { + $fields[] = 'fds.data_txt'; + } + + foreach ((array)$fields as $field) { + $glueOneField = array(); + + foreach ((array)$conditions as $con) { + $con = trim($con); + + if ($con != '') { + $glueOneField[] = $db->qn($field) . ' LIKE ' . $db->quote($con . '%'); + } + } + + $where[] = '(' . implode(' AND ', $glueOneField) . ')'; + + // Full condition + $where[] = $db->qn($field) . ' LIKE ' . $db->quote('%' . $condition . '%'); + } + + if (!empty($where)) { + return '(' . implode(' ' . $glue . ' ', $where) . ')'; + } else { + return '1 = 1'; + } + } + + /** + * Method to get the starting number of items for the data set. + * + * @return integer The starting number of items available in the data set. + * + * @since 1.5 + */ + public function getStart() + { + $store = $this->getStoreId('getstart'); + + // Try to load the data from internal storage. + if (isset($this->cache[$store])) { + return $this->cache[$store]; + } + + $start = $this->getState('list.start'); + $limit = $this->getState('list.limit'); + $total = $this->getTotal(); + + if ($start > $total - $limit) { + $start = max(0, (int)(ceil($total / $limit) - 1) * $limit); + } + + // Add the total to the internal cache. + $this->cache[$store] = $start; + + return $this->cache[$store]; + } + + /** + * Method to get the total number of items for the data set. + * + * @return integer The total number of items available in the data set. + * + * @since 1.5 + */ + public function getTotal() + { + // Get a storage key. + $store = $this->getStoreId('getTotal'); + + // Try to load the data from internal storage. + if (isset($this->cache[$store])) { + return $this->cache[$store]; + } + + $productlimit = $this->getState('productlimit'); + $layout = $this->getState('layout', 'default'); + + $db = JFactory::getDbo(); + $total = $db->setQuery($this->_buildQuery(0, true)) + ->loadResult(); + + if ($layout == 'newproduct' || $layout == 'productonsale') { + if ($total > $productlimit && $productlimit != "") { + $total = $productlimit; + } + } + + // Add the total to the internal cache. + $this->cache[$store] = $total; + + return $this->cache[$store]; + } + + public function mod_redProductfilter($Itemid) + { + $db = JFactory::getDbo(); + $query = "SELECT t.*, f.formname AS form_name FROM #__redproductfinder_types t LEFT JOIN #__redproductfinder_forms f ON t.form_id = f.id ORDER BY ordering"; - $types = $this->_getList($query); - $session = JSession::getInstance('none', array()); + $types = $this->_getList($query); + $session = JSession::getInstance('none', array()); - $getredfilter = $session->get('redfilter'); + $getredfilter = $session->get('redfilter'); - $redfilterproduct = $session->get('redfilterproduct'); + $redfilterproduct = $session->get('redfilterproduct'); - $redproducttotal = count($redfilterproduct); + $redproducttotal = count($redfilterproduct); - foreach ($types as $key => $type) { - if (@!array_key_exists($type->id, $getredfilter)) { - $str = htmlentities($type->type_name, ENT_COMPAT, "UTF-8"); - $str = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde|elig|slash|ring);/', '$1', $str); - $str = str_replace(' ', '', $str); - $types[$key]->type_name_css = html_entity_decode($str); + foreach ($types as $key => $type) { + if (@!array_key_exists($type->id, $getredfilter)) { + $str = htmlentities($type->type_name, ENT_COMPAT, "UTF-8"); + $str = preg_replace( + '/&([a-zA-Z])(uml|acute|grave|circ|tilde|elig|slash|ring);/', + '$1', + $str + ); + $str = str_replace(' ', '', $str); + $types[$key]->type_name_css = html_entity_decode($str); - $id = $type->id; - $all = 1; - $productids = ""; + $id = $type->id; + $all = 1; + $productids = ""; - if (count($getredfilter) > 0 && $all == 1) { - $type_id = array(); - $tag_id = array(); + if (count($getredfilter) > 0 && $all == 1) { + $type_id = array(); + $tag_id = array(); - $k = 0; + $k = 0; - foreach ($getredfilter as $typeid => $tags) { - $type_id[] = $typeid; - $tags = explode(".", $tags); - $tag_id[] = $tags[0]; + foreach ($getredfilter as $typeid => $tags) { + $type_id[] = $typeid; + $tags = explode(".", $tags); + $tag_id[] = $tags[0]; - if (count($getredfilter) - 1 == $k) { - $lasttypeid = $typeid; - $lasttagid = $tags[0]; - } + if (count($getredfilter) - 1 == $k) { + $lasttypeid = $typeid; + $lasttagid = $tags[0]; + } - $k++; - } + $k++; + } - $typeids = implode(",", $type_id); - $tagids = implode(",", $tag_id); + $typeids = implode(",", $type_id); + $tagids = implode(",", $tag_id); - $query = "SELECT ra.product_id FROM `#__redproductfinder_association_tag` as rat + $query = "SELECT ra.product_id FROM `#__redproductfinder_association_tag` as rat LEFT JOIN #__redproductfinder_associations as ra ON rat.`association_id` = ra.id WHERE rat.`type_id` = " . $db->quote($lasttypeid) . " "; - $query .= "AND rat.`tag_id` = " . $db->quote($lasttagid) . " "; + $query .= "AND rat.`tag_id` = " . $db->quote($lasttagid) . " "; - $product = $this->_getList($query); + $product = $this->_getList($query); - $products = array(); + $products = array(); - for ($i = 0, $in = count($product); $i < $in; $i++) { - $products[] = $product[$i]->product_id; - } + for ($i = 0, $in = count($product); $i < $in; $i++) { + $products[] = $product[$i]->product_id; + } - $products = ArrayHelper::toInteger($products); - $productids = implode(",", $products); - } + $products = ArrayHelper::toInteger($products); + $productids = implode(",", $products); + } - $q = "SELECT DISTINCT j.tag_id as tagid ,ra.product_id,count(ra.product_id) as ptotal ,CONCAT(j.tag_id,'.',j.type_id) AS tag_id, t.tag_name + $q = "SELECT DISTINCT j.tag_id as tagid ,ra.product_id,count(ra.product_id) as ptotal ,CONCAT(j.tag_id,'.',j.type_id) AS tag_id, t.tag_name FROM ((#__redproductfinder_tag_type j, #__redproductfinder_tags t ) LEFT JOIN #__redproductfinder_association_tag as rat ON t.`id` = rat.`tag_id`) LEFT JOIN #__redproductfinder_associations as ra ON ra.id = rat.association_id WHERE j.tag_id = t.id - AND j.type_id = " . (int) $id . " "; + AND j.type_id = " . (int)$id . " "; - if ($productids != "") { - // Sanitize ids - $productIds = explode(',', $productids); - $productIds = ArrayHelper::toInteger($productIds); + if ($productids != "") { + // Sanitize ids + $productIds = explode(',', $productids); + $productIds = ArrayHelper::toInteger($productIds); - $q .= " AND ra.product_id IN ( " . implode(',', $productIds) . " ) "; - } - $q .= " GROUP BY t.id ORDER BY t.ordering "; + $q .= " AND ra.product_id IN ( " . implode(',', $productIds) . " ) "; + } + $q .= " GROUP BY t.id ORDER BY t.ordering "; - $tags = $this->_getList($q); + $tags = $this->_getList($q); - $tagname = ""; + $tagname = ""; - // Only show if the type has tags - if (count($tags) > 0) { - // Create the selection boxes - for ($t = 0, $tn = count($tags); $t < $tn; $t++) { - $type_id = explode('.', $tags[$t]->tag_id); + // Only show if the type has tags + if (count($tags) > 0) { + // Create the selection boxes + for ($t = 0, $tn = count($tags); $t < $tn; $t++) { + $type_id = explode('.', $tags[$t]->tag_id); - $query = "SELECT count(*) as count FROM #__redproductfinder_association_tag as ra + $query = "SELECT count(*) as count FROM #__redproductfinder_association_tag as ra left join #__redproductfinder_associations as a on ra.association_id = a.id left join #__redshop_product as rp on rp.product_id = a.product_id - WHERE type_id = " . $db->quote($type_id[1]) . " AND tag_id = " . $db->quote($type_id[0]) . " AND rp.published = 1"; - - $published = $this->_getList($query); - - if ($published[0]->count > $redproducttotal && $redproducttotal > 0) { - $finalcount = $redproducttotal; - } else { - $finalcount = $published[0]->count; - } - - if ($finalcount > 0) { - $tagname .= "  id . '&tagid=' . $tags[$t]->tag_id . '&Itemid=' . $Itemid) . "' title='" . $tags[$t]->tag_name . "' >" . $tags[$t]->tag_name . " ( " . $finalcount . " )
    "; - } - } - - if ($tagname != "") { - $lists['type' . $key] = $tagname; - } - } else { - unset($types[$key]); - } - } - } - - if (count($getredfilter) != 0) { - foreach ($getredfilter as $typeid => $tag_id) { - foreach ($types as $key => $type) { - if ($typeid == $type->id) { - $str = htmlentities($type->type_name, ENT_COMPAT, "UTF-8"); - $str = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde|elig|slash|ring);/', '$1', $str); - $str = str_replace(' ', '', $str); - $types[$key]->type_name_css = html_entity_decode($str); - - $tags = $this->getTagsDetail($type->id, 0); - - $tagname = ""; - - // Only show if the type has tags - if (count($tags) > 0) { - // Create the selection boxes - for ($t = 0, $tn = count($tags); $t < $tn; $t++) { - if ($tags[$t]->tagid == $tag_id) { - $tagname .= "  " . $tags[$t]->tag_name . "" . JText::_('COM_REDSHOP_DELETE') . "
    "; - } - } - - if ($tagname != "") { - $filteredlists['type' . $key] = $tagname; - } - } else { - unset($types[$key]); - } - } - } - } - } - - if (count($getredfilter) != 0) { -?> -
    - -
    - $tag_id) { - foreach ($types as $key => $type) { - if ($typeid == $type->id) { - ?> -
    - type_name; ?> - tooltip) > 0) { - echo ' ' . JHtml::tooltip($type->tooltip, $type->type_name, 'tooltip.png', '', '', false); - } ?> -
    -
    -
    -
    - - -
    - - -
    -
     _________________________
    - 0) { - ?> -
    - -
    - $type) { - if (@!array_key_exists($type->id, $getredfilter) && @array_key_exists('type' . $key, $lists)) { - ?> -
    - type_name; ?> - tooltip) > 0) { - echo ' ' . JHtml::tooltip($type->tooltip, $type->type_name, 'tooltip.png', '', '', false); - } ?> -
    -
    -
    -
    -get('redfilter'); - $db = JFactory::getDbo(); - $products = array(); - - if (count($getredfilter) > 0 && $all == 1) { - $type_id = array(); - $tag_id = array(); - $k = 0; - - foreach ($getredfilter as $typeid => $tags) { - $type_id[] = $typeid; - $tags = explode(".", $tags); - $tag_id[] = $tags[0]; - - if (count($getredfilter) - 1 == $k) { - $lasttypeid = $typeid; - $lasttagid = $tags[0]; - } - - $k++; - } - - $typeids = implode(",", $type_id); - $tagids = implode(",", $tag_id); - - $query = "SELECT ra.product_id FROM #__redproductfinder_association_tag AS rat " - . "LEFT JOIN #__redproductfinder_associations AS ra ON rat.association_id = ra.id " - . "WHERE rat.type_id = " . $db->quote($lasttypeid) . " " - . "AND rat.tag_id = " . $db->quote($lasttagid) . " "; - $db->setQuery($query); - $product = $db->loadObjectList(); - - for ($i = 0, $in = count($product); $i < $in; $i++) { - $products[] = $product[$i]->product_id; - } - } - - $q = "SELECT DISTINCT j.tag_id AS tagid,ra.product_id,count(ra.product_id) AS ptotal, " - . "CONCAT(j.tag_id,'.',j.type_id) AS tag_id, t.tag_name " - . "FROM ((#__redproductfinder_tag_type j, #__redproductfinder_tags t ) " - . "LEFT JOIN #__redproductfinder_association_tag as rat ON t.`id` = rat.`tag_id`) " - . "LEFT JOIN #__redproductfinder_associations as ra ON ra.id = rat.association_id " - . "WHERE j.tag_id = t.id " - . "AND j.type_id = " . (int) $id . " "; - - if (!empty($products)) { - // Sanitize ids - $products = ArrayHelper::toInteger($products); - - $q .= " AND ra.product_id IN (" . implode(",", $products) . ") "; - } - - $q .= " GROUP BY t.id ORDER BY t.ordering "; - $db->setQuery($q); - - return $db->loadObjectList(); - } - - /** - * Get Category products selected in search Module - */ - public function loadCatProductsManufacturer($cid) - { - $db = JFactory::getDbo(); - $query = "SELECT p.product_id, p.manufacturer_id FROM #__redshop_product_category_xref AS cx " - . ", #__redshop_product AS p " - . "WHERE cx.category_id = " . (int) $cid . " " - . "AND p.product_id=cx.product_id "; - $db->setQuery($query); - $manufacturer = $db->loadObjectList(); - - $mids = array(); - - for ($i = 0, $countManuf = count($manufacturer); $i < $countManuf; $i++) { - if ($manufacturer[$i]->manufacturer_id > 0) { - $mids[] = $manufacturer[$i]->manufacturer_id; - } - } - - // Sanitize ids - $mids = ArrayHelper::toInteger($mids); - - $query = "SELECT id AS value,name AS text FROM #__redshop_manufacturer " - . "WHERE id IN ('" . implode(",", $mids) . "')"; - $db->setQuery($query); - - return $db->loadObjectList(); - } - - /** - * Get ajax Data - * - * @return array|null - * - * @throws Exception - */ - public function getajaxData() - { - JLoader::import('joomla.application.module.helper'); - $module = JModuleHelper::getModule('redshop_search'); - $params = new JRegistry($module->params); - $limit = $params->get('noofsearchresults'); - $app = JFactory::getApplication(); - $keyword = $app->input->getString('keyword', ''); - $search_type = $app->input->getCmd('search_type', ''); - $search_product_by_category_name = $params->get('searchProductByCategoryName'); - $category_id = $app->input->getInt('category_id', 0); - $manufacture_id = $app->input->getInt('manufacture_id', 0); - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('p.product_id AS id, p.product_name AS value, p.cat_in_sefurl') - ->from($db->qn('#__redshop_product', 'p')) - ->leftJoin($db->qn('#__redshop_product_category_xref', 'x') . ' ON x.product_id = p.product_id') - ->leftJoin($db->qn('#__redshop_category', 'c') . ' ON x.category_id = c.id') - ->where('p.published = 1') - ->where('p.expired = 0') - ->group('p.product_id'); - - $columnsCondition = array(); - - switch ($search_type) { - case 'product_name': - $columnsCondition = array('p.product_name'); - break; - case 'product_number': - $columnsCondition = array('p.product_number'); - break; - case 'name_number': - $columnsCondition = array('p.product_name', 'p.product_number'); - break; - case 'product_desc': - $columnsCondition = array('p.product_s_desc', 'p.product_desc'); - break; - case 'name_desc': - $columnsCondition = array('p.product_name', 'p.product_s_desc', 'p.product_desc'); - break; - case 'virtual_product_num': - $columnsCondition = array('pap.property_number', 'ps.subattribute_color_number'); - break; - case 'name_number_desc': - $columnsCondition = array( - 'p.product_name', 'p.product_number', 'p.product_desc', 'p.product_s_desc', - 'pap.property_number', 'ps.subattribute_color_number' - ); - break; - } - - $fieldSearchable = $this->getSearchableProductCustomfields(); - $joinSearchable = !$fieldSearchable ? '' : (' AND ' . $db->qn('fds.fieldid') . ' IN (' - . implode(",", $fieldSearchable) . ')'); - $query->leftJoin($db->qn('#__redshop_fields_data', 'fds') . ' ON p.product_id = fds.itemid' - . $joinSearchable); - - if ($search_product_by_category_name == 'yes') { - $columnsCondition[] = 'c.name'; - } - - $query->where($this->getSearchCondition($columnsCondition, $keyword)); - - if ($search_type == "name_number_desc" || $search_type == "virtual_product_num") { - $query->leftJoin($db->qn('#__redshop_product_attribute', 'a') . ' ON a.product_id = p.product_id') - ->leftJoin($db->qn('#__redshop_product_attribute_property', 'pap') . ' ON pap.attribute_id = a.attribute_id') - ->leftJoin($db->qn('#__redshop_product_subattribute_color', 'ps') . ' ON ps.subattribute_id = pap.property_id'); - } - - if ($category_id != "0") { - $query->where('c.id = ' . (int) $category_id); - } - - if ($manufacture_id != "0") { - $query->where('p.manufacturer_id = ' . (int) $manufacture_id); - } - - $excludeCategories = $app->input->getString('excludeCategories', ''); - - if (!empty($excludeCategories)) { - $excludeCategories = explode(',', $excludeCategories); - $excludeCategories = ArrayHelper::toInteger($excludeCategories); - - $query->where('x.category_id NOT IN (' . implode(',', $excludeCategories) . ')'); - } - - $pk = array( - 'keyword' => $keyword - ); - - JPluginHelper::importPlugin('redshop_product'); - JDispatcher::getInstance()->trigger('onFilterProduct', array(&$query, $pk)); - - $data = $db->setQuery($query, 0, $limit)->loadObjectList(); - - if ($data) { - foreach ($data as &$row) { - if (empty($category_id)) { - $category_id = (int) $row->cat_in_sefurl; - } - - $pItemid = RedshopHelperRouter::getItemId($row->id, $category_id); - - $row->link = JRoute::_( - 'index.php?option=com_redshop' . - '&view=product&pid=' . $row->id . - '&cid=' . $row->cat_in_sefurl . - '&Itemid=' . $pItemid, - false - ); - - //get product image - $row->product_image = Redshop\Product\Image\Image::getImage( - $row->id, - $row->link, - Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_3', 80), - Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_3', 40) - ); - - //get product price - $row->product_price = RedshopHelperProductPrice::formattedPrice(Redshop\Product\Price::getPrice($row->id, false, 0)); - } - } - - $this->preprocessData($this->context, $data); - - return $data; - } - - /** - * Get List from product - * - * @return JDatabaseQuery - */ - public function getListQuery() - { - $pk = $this->getState('filter.data', array()); - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn("p.product_id")) - ->from($db->qn("#__redshop_product", "p")) - ->leftJoin( - $db->qn("#__redshop_product_category_xref", "pc") . " ON " - . $db->qn('p.product_id') . " = " - . $db->qn('pc.product_id') - ) - ->where($db->qn('p.published') . ' = 1') - ->where($db->qn('p.expired') . ' = 0') - ->group($db->qn('p.product_id')); - - $productOnSale = !empty($pk['product_on_sale']) ? $pk['product_on_sale'] : 0; - $cid = !empty($pk['cid']) ? $pk['cid'] : 0; - $mid = !empty($pk['mid']) ? $pk['mid'] : 0; - $rootCategory = !empty($pk['root_category']) ? $pk['root_category'] : 0; - $categoryForSale = !empty($pk['category_for_sale']) ? $pk['category_for_sale'] : array(); - $categories = !empty($pk['category']) ? $pk['category'] : array(); - $manufacturers = !empty($pk['manufacturer']) ? $pk['manufacturer'] : array(); - $keyword = !empty($pk['keyword']) ? $pk['keyword'] : ""; - $customField = !empty($pk['custom_field']) ? $pk['custom_field'] : ""; - - if (isset($pk["filterprice"])) { - $min = $pk["filterprice"]['min']; - $max = $pk["filterprice"]['max']; - } - - if (!empty($categories)) { - if (in_array($rootCategory, $categories)) { - $key = array_search($rootCategory, $categories); - unset($categories[$key]); - } - - $categoryList = implode(',', $categories); - } elseif (!empty($cid)) { - $catList = RedshopHelperCategory::getCategoryListArray($cid); - - if (!empty($catList)) { - foreach ($catList as $key => $cat) { - $list[] = $cat->id; - } - - array_push($list, $cid); - - $categoryList = implode(',', $list); - } else { - $categoryList = $cid; - } - } else { - $categoryList = $cid; - } - - $orderBy = $this->getState('order_by'); - - if ($orderBy == 'pc.ordering ASC' || $orderBy == 'c.ordering ASC') { - $orderBy = 'p.product_id DESC'; - } - - if (!empty($pk["filterprice"])) { - $comparePrice = $db->qn('p.product_price') . ' >= ' . $db->q($min) . ' AND ' . $db->qn('p.product_price') . ' <= ' . $db->q(($max)); - $compareDiscountPrice = $db->qn('p.discount_price') . ' >= ' . $db->q($min) . ' AND ' . $db->qn('p.discount_price') . ' <= ' . $db->q(($max)); - $saleTime = $db->qn('p.discount_stratdate') . ' AND ' . $db->qn('p.discount_enddate'); - $query->where( - '( CASE WHEN( ' . $db->qn('p.product_on_sale') . ' = 1 AND UNIX_TIMESTAMP() BETWEEN ' - . $saleTime . ') THEN (' - . $compareDiscountPrice . ') ELSE (' - . $comparePrice . ') END )' - ); - } - - if (!empty($keyword)) { - $search = $db->q('%' . $db->escape(trim($keyword, true) . '%')); - $query->leftJoin( - $db->qn('#__redshop_manufacturer', 'm') . ' ON ' - . $db->qn('m.id') . ' = ' . $db->qn('p.manufacturer_id') - ) - ->where('(' . $db->qn('p.product_name') . ' LIKE ' . $search . ' OR ' . $db->qn('m.name') . ' LIKE ' . $search . ')'); - } - - $catList = RedshopHelperCategory::getCategoryListArray($categoryForSale); - $childCat = array($categoryForSale); - - foreach ($catList as $key => $value) { - $childCat[] = $value->id; - } - - if (!empty($customField)) { - $key = 0; - $subQuery = array(); - - foreach ($customField as $fieldId => $fieldValues) { - $fieldValues = array_filter($fieldValues); - - if (empty($fieldValues)) { - continue; - } - - foreach ($fieldValues as $value) { - $subQuery[] = 'FIND_IN_SET("' . $value . '", ' . $db->qn('fd' . $key . '.data_txt') . ')'; - } - - $query->leftJoin($db->qn('#__redshop_fields_data', 'fd' . $key) . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('fd' . $key . '.itemid')) - ->where($db->qn('fd' . $key . '.fieldid') . ' = ' . $db->q((int) $fieldId)); - $key++; - } - - if (!empty($subQuery)) { - $query->where('(' . implode(' OR ', $subQuery) . ')'); - } - } - - if (!empty($categoryForSale) && in_array($cid, $childCat)) { - if (!empty($categories)) { - foreach ($categories as $key => $value) { - $query->leftJoin( - $db->qn('#__redshop_product_category_xref', 'pc' . $key) . ' ON ' - . $db->qn('p.product_id') . ' = ' - . $db->qn('pc' . $key . '.product_id') - ) - ->where($db->qn('pc' . $key . '.category_id') . ' = ' . $db->q((int) $value)) - ->where($db->qn("pc.category_id") . " = " . $db->q((int) $cid)); - } - } elseif (!empty($cid) || !empty($categories)) { - $query->where($db->qn("pc.category_id") . " IN (" . $categoryList . ')'); - } - } elseif (!empty($cid) || !empty($categories)) { - $query->where($db->qn("pc.category_id") . " IN (" . $categoryList . ')'); - } - - if (!empty($manufacturers)) { - $query->where($db->qn("p.manufacturer_id") . " IN (" . implode(',', $manufacturers) . ')'); - } elseif ($mid) { - $query->where($db->qn("p.manufacturer_id") . "=" . $db->q((int) $mid)); - } - - if (!empty($productOnSale)) { - $query->where($db->qn('p.product_on_sale') . ' = ' . $db->q((int) $productOnSale)); - } - - if ($orderBy) { - $query->order($db->escape($orderBy)); - } - - JPluginHelper::importPlugin('redshop_product'); - JDispatcher::getInstance()->trigger('onFilterProduct', array(&$query, $pk)); - - return $query; - } - - /** - * Get Items - * - * @return array - */ - public function getItem() - { - $query = $this->getListQuery(); - $db = JFactory::getDbo(); - $start = $this->getState('list.start'); - $limit = $this->getState('list.limit'); - $templateId = $this->getState('template_id'); - - $templateArr = RedshopHelperTemplate::getTemplate("category", $templateId); - $templateDesc = $templateArr[0]->template_desc; - - if ($templateDesc) { - if (strstr($templateDesc, "{pagination}")) { - $db->setQuery($query, $start, $limit); - } else { - $db->setQuery($query); - } - } else { - $db->setQuery($query); - } - - return $db->loadColumn(); - } - - /** - * Get pagination. - * - * @return JPagination - */ - public function getFilterPagination() - { - $endlimit = $this->getState('list.limit'); - $limitstart = $this->getState('list.start'); - $this->pagination = new JPagination($this->getFilterTotal(), $limitstart, $endlimit); - - return $this->pagination; - } - - /** - * Get total. - * - * @return integer - */ - public function getFilterTotal() - { - $query = $this->getListQuery(); - $this->total = $this->_getListCount($query); - - return $this->total; - } + WHERE type_id = " . $db->quote($type_id[1]) . " AND tag_id = " . $db->quote( + $type_id[0] + ) . " AND rp.published = 1"; + + $published = $this->_getList($query); + + if ($published[0]->count > $redproducttotal && $redproducttotal > 0) { + $finalcount = $redproducttotal; + } else { + $finalcount = $published[0]->count; + } + + if ($finalcount > 0) { + $tagname .= "  id . '&tagid=' . $tags[$t]->tag_id . '&Itemid=' . $Itemid + ) . "' title='" . $tags[$t]->tag_name . "' >" . $tags[$t]->tag_name . " ( " . $finalcount . " )
    "; + } + } + + if ($tagname != "") { + $lists['type' . $key] = $tagname; + } + } else { + unset($types[$key]); + } + } + } + + if (count($getredfilter) != 0) { + foreach ($getredfilter as $typeid => $tag_id) { + foreach ($types as $key => $type) { + if ($typeid == $type->id) { + $str = htmlentities($type->type_name, ENT_COMPAT, "UTF-8"); + $str = preg_replace( + '/&([a-zA-Z])(uml|acute|grave|circ|tilde|elig|slash|ring);/', + '$1', + $str + ); + $str = str_replace(' ', '', $str); + $types[$key]->type_name_css = html_entity_decode($str); + + $tags = $this->getTagsDetail($type->id, 0); + + $tagname = ""; + + // Only show if the type has tags + if (count($tags) > 0) { + // Create the selection boxes + for ($t = 0, $tn = count($tags); $t < $tn; $t++) { + if ($tags[$t]->tagid == $tag_id) { + $tagname .= "  " . $tags[$t]->tag_name . "" . JText::_('COM_REDSHOP_DELETE') . "
    "; + } + } + + if ($tagname != "") { + $filteredlists['type' . $key] = $tagname; + } + } else { + unset($types[$key]); + } + } + } + } + } + + if (count($getredfilter) != 0) { + ?> +
    + +
    + $tag_id) { + foreach ($types as $key => $type) { + if ($typeid == $type->id) { + ?> +
    + type_name; ?> + tooltip) > 0) { + echo ' ' . JHtml::tooltip( + $type->tooltip, + $type->type_name, + 'tooltip.png', + '', + '', + false + ); + } ?> +
    +
    +
    +
    + + +
    + + +
    +
     _________________________
    + 0) { + ?> +
    + +
    + $type) { + if (@!array_key_exists($type->id, $getredfilter) && @array_key_exists('type' . $key, $lists)) { + ?> +
    + type_name; ?> + tooltip) > 0) { + echo ' ' . JHtml::tooltip($type->tooltip, $type->type_name, 'tooltip.png', '', '', false); + } ?> +
    +
    +
    +
    + get('redfilter'); + $db = JFactory::getDbo(); + $products = array(); + + if (count($getredfilter) > 0 && $all == 1) { + $type_id = array(); + $tag_id = array(); + $k = 0; + + foreach ($getredfilter as $typeid => $tags) { + $type_id[] = $typeid; + $tags = explode(".", $tags); + $tag_id[] = $tags[0]; + + if (count($getredfilter) - 1 == $k) { + $lasttypeid = $typeid; + $lasttagid = $tags[0]; + } + + $k++; + } + + $typeids = implode(",", $type_id); + $tagids = implode(",", $tag_id); + + $query = "SELECT ra.product_id FROM #__redproductfinder_association_tag AS rat " + . "LEFT JOIN #__redproductfinder_associations AS ra ON rat.association_id = ra.id " + . "WHERE rat.type_id = " . $db->quote($lasttypeid) . " " + . "AND rat.tag_id = " . $db->quote($lasttagid) . " "; + $db->setQuery($query); + $product = $db->loadObjectList(); + + for ($i = 0, $in = count($product); $i < $in; $i++) { + $products[] = $product[$i]->product_id; + } + } + + $q = "SELECT DISTINCT j.tag_id AS tagid,ra.product_id,count(ra.product_id) AS ptotal, " + . "CONCAT(j.tag_id,'.',j.type_id) AS tag_id, t.tag_name " + . "FROM ((#__redproductfinder_tag_type j, #__redproductfinder_tags t ) " + . "LEFT JOIN #__redproductfinder_association_tag as rat ON t.`id` = rat.`tag_id`) " + . "LEFT JOIN #__redproductfinder_associations as ra ON ra.id = rat.association_id " + . "WHERE j.tag_id = t.id " + . "AND j.type_id = " . (int)$id . " "; + + if (!empty($products)) { + // Sanitize ids + $products = ArrayHelper::toInteger($products); + + $q .= " AND ra.product_id IN (" . implode(",", $products) . ") "; + } + + $q .= " GROUP BY t.id ORDER BY t.ordering "; + $db->setQuery($q); + + return $db->loadObjectList(); + } + + /** + * Get Category products selected in search Module + */ + public function loadCatProductsManufacturer($cid) + { + $db = JFactory::getDbo(); + $query = "SELECT p.product_id, p.manufacturer_id FROM #__redshop_product_category_xref AS cx " + . ", #__redshop_product AS p " + . "WHERE cx.category_id = " . (int)$cid . " " + . "AND p.product_id=cx.product_id "; + $db->setQuery($query); + $manufacturer = $db->loadObjectList(); + + $mids = array(); + + for ($i = 0, $countManuf = count($manufacturer); $i < $countManuf; $i++) { + if ($manufacturer[$i]->manufacturer_id > 0) { + $mids[] = $manufacturer[$i]->manufacturer_id; + } + } + + // Sanitize ids + $mids = ArrayHelper::toInteger($mids); + + $query = "SELECT id AS value,name AS text FROM #__redshop_manufacturer " + . "WHERE id IN ('" . implode(",", $mids) . "')"; + $db->setQuery($query); + + return $db->loadObjectList(); + } + + /** + * Get ajax Data + * + * @return array|null + * + * @throws Exception + */ + public function getajaxData() + { + JLoader::import('joomla.application.module.helper'); + $module = JModuleHelper::getModule('redshop_search'); + $params = new JRegistry($module->params); + $limit = $params->get('noofsearchresults'); + $app = JFactory::getApplication(); + $keyword = $app->input->getString('keyword', ''); + $search_type = $app->input->getCmd('search_type', ''); + $search_product_by_category_name = $params->get('searchProductByCategoryName'); + $category_id = $app->input->getInt('category_id', 0); + $manufacture_id = $app->input->getInt('manufacture_id', 0); + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('p.product_id AS id, p.product_name AS value, p.cat_in_sefurl') + ->from($db->qn('#__redshop_product', 'p')) + ->leftJoin($db->qn('#__redshop_product_category_xref', 'x') . ' ON x.product_id = p.product_id') + ->leftJoin($db->qn('#__redshop_category', 'c') . ' ON x.category_id = c.id') + ->where('p.published = 1') + ->where('p.expired = 0') + ->group('p.product_id'); + + $columnsCondition = array(); + + switch ($search_type) { + case 'product_name': + $columnsCondition = array('p.product_name'); + break; + case 'product_number': + $columnsCondition = array('p.product_number'); + break; + case 'name_number': + $columnsCondition = array('p.product_name', 'p.product_number'); + break; + case 'product_desc': + $columnsCondition = array('p.product_s_desc', 'p.product_desc'); + break; + case 'name_desc': + $columnsCondition = array('p.product_name', 'p.product_s_desc', 'p.product_desc'); + break; + case 'virtual_product_num': + $columnsCondition = array('pap.property_number', 'ps.subattribute_color_number'); + break; + case 'name_number_desc': + $columnsCondition = array( + 'p.product_name', + 'p.product_number', + 'p.product_desc', + 'p.product_s_desc', + 'pap.property_number', + 'ps.subattribute_color_number' + ); + break; + } + + $fieldSearchable = $this->getSearchableProductCustomfields(); + $joinSearchable = !$fieldSearchable ? '' : (' AND ' . $db->qn('fds.fieldid') . ' IN (' + . implode(",", $fieldSearchable) . ')'); + $query->leftJoin( + $db->qn('#__redshop_fields_data', 'fds') . ' ON p.product_id = fds.itemid' + . $joinSearchable + ); + + if ($search_product_by_category_name == 'yes') { + $columnsCondition[] = 'c.name'; + } + + $query->where($this->getSearchCondition($columnsCondition, $keyword)); + + if ($search_type == "name_number_desc" || $search_type == "virtual_product_num") { + $query->leftJoin($db->qn('#__redshop_product_attribute', 'a') . ' ON a.product_id = p.product_id') + ->leftJoin( + $db->qn('#__redshop_product_attribute_property', 'pap') . ' ON pap.attribute_id = a.attribute_id' + ) + ->leftJoin( + $db->qn('#__redshop_product_subattribute_color', 'ps') . ' ON ps.subattribute_id = pap.property_id' + ); + } + + if ($category_id != "0") { + $query->where('c.id = ' . (int)$category_id); + } + + if ($manufacture_id != "0") { + $query->where('p.manufacturer_id = ' . (int)$manufacture_id); + } + + $excludeCategories = $app->input->getString('excludeCategories', ''); + + if (!empty($excludeCategories)) { + $excludeCategories = explode(',', $excludeCategories); + $excludeCategories = ArrayHelper::toInteger($excludeCategories); + + $query->where('x.category_id NOT IN (' . implode(',', $excludeCategories) . ')'); + } + + $pk = array( + 'keyword' => $keyword + ); + + JPluginHelper::importPlugin('redshop_product'); + JDispatcher::getInstance()->trigger('onFilterProduct', array(&$query, $pk)); + + $data = $db->setQuery($query, 0, $limit)->loadObjectList(); + + if ($data) { + foreach ($data as &$row) { + if (empty($category_id)) { + $category_id = (int)$row->cat_in_sefurl; + } + + $pItemid = RedshopHelperRouter::getItemId($row->id, $category_id); + + $row->link = JRoute::_( + 'index.php?option=com_redshop' . + '&view=product&pid=' . $row->id . + '&cid=' . $row->cat_in_sefurl . + '&Itemid=' . $pItemid, + false + ); + + //get product image + $row->product_image = Redshop\Product\Image\Image::getImage( + $row->id, + $row->link, + Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_3', 80), + Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_3', 40) + ); + + //get product price + $row->product_price = RedshopHelperProductPrice::formattedPrice( + Redshop\Product\Price::getPrice($row->id, false, 0) + ); + } + } + + $this->preprocessData($this->context, $data); + + return $data; + } + + /** + * Get Items + * + * @return array + */ + public function getItem() + { + $query = $this->getListQuery(); + $db = JFactory::getDbo(); + $start = $this->getState('list.start'); + $limit = $this->getState('list.limit'); + $templateId = $this->getState('template_id'); + + $templateArr = RedshopHelperTemplate::getTemplate("category", $templateId); + $templateDesc = $templateArr[0]->template_desc; + + if ($templateDesc) { + if (strstr($templateDesc, "{pagination}")) { + $db->setQuery($query, $start, $limit); + } else { + $db->setQuery($query); + } + } else { + $db->setQuery($query); + } + + return $db->loadColumn(); + } + + /** + * Get List from product + * + * @return JDatabaseQuery + */ + public function getListQuery() + { + $pk = $this->getState('filter.data', array()); + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn("p.product_id")) + ->from($db->qn("#__redshop_product", "p")) + ->leftJoin( + $db->qn("#__redshop_product_category_xref", "pc") . " ON " + . $db->qn('p.product_id') . " = " + . $db->qn('pc.product_id') + ) + ->where($db->qn('p.published') . ' = 1') + ->where($db->qn('p.expired') . ' = 0') + ->group($db->qn('p.product_id')); + + $productOnSale = !empty($pk['product_on_sale']) ? $pk['product_on_sale'] : 0; + $cid = !empty($pk['cid']) ? $pk['cid'] : 0; + $mid = !empty($pk['mid']) ? $pk['mid'] : 0; + $rootCategory = !empty($pk['root_category']) ? $pk['root_category'] : 0; + $categoryForSale = !empty($pk['category_for_sale']) ? $pk['category_for_sale'] : array(); + $categories = !empty($pk['category']) ? $pk['category'] : array(); + $manufacturers = !empty($pk['manufacturer']) ? $pk['manufacturer'] : array(); + $keyword = !empty($pk['keyword']) ? $pk['keyword'] : ""; + $customField = !empty($pk['custom_field']) ? $pk['custom_field'] : ""; + + if (isset($pk["filterprice"])) { + $min = $pk["filterprice"]['min']; + $max = $pk["filterprice"]['max']; + } + + if (!empty($categories)) { + if (in_array($rootCategory, $categories)) { + $key = array_search($rootCategory, $categories); + unset($categories[$key]); + } + + $categoryList = implode(',', $categories); + } elseif (!empty($cid)) { + $catList = RedshopHelperCategory::getCategoryListArray($cid); + + if (!empty($catList)) { + foreach ($catList as $key => $cat) { + $list[] = $cat->id; + } + + array_push($list, $cid); + + $categoryList = implode(',', $list); + } else { + $categoryList = $cid; + } + } else { + $categoryList = $cid; + } + + $orderBy = $this->getState('order_by'); + + if ($orderBy == 'pc.ordering ASC' || $orderBy == 'c.ordering ASC') { + $orderBy = 'p.product_id DESC'; + } + + if (!empty($pk["filterprice"])) { + $comparePrice = $db->qn('p.product_price') . ' >= ' . $db->q($min) . ' AND ' . $db->qn( + 'p.product_price' + ) . ' <= ' . $db->q(($max)); + $compareDiscountPrice = $db->qn('p.discount_price') . ' >= ' . $db->q($min) . ' AND ' . $db->qn( + 'p.discount_price' + ) . ' <= ' . $db->q(($max)); + $saleTime = $db->qn('p.discount_stratdate') . ' AND ' . $db->qn('p.discount_enddate'); + $query->where( + '( CASE WHEN( ' . $db->qn('p.product_on_sale') . ' = 1 AND UNIX_TIMESTAMP() BETWEEN ' + . $saleTime . ') THEN (' + . $compareDiscountPrice . ') ELSE (' + . $comparePrice . ') END )' + ); + } + + if (!empty($keyword)) { + $search = $db->q('%' . $db->escape(trim($keyword, true) . '%')); + $query->leftJoin( + $db->qn('#__redshop_manufacturer', 'm') . ' ON ' + . $db->qn('m.id') . ' = ' . $db->qn('p.manufacturer_id') + ) + ->where( + '(' . $db->qn('p.product_name') . ' LIKE ' . $search . ' OR ' . $db->qn( + 'm.name' + ) . ' LIKE ' . $search . ')' + ); + } + + $catList = RedshopHelperCategory::getCategoryListArray($categoryForSale); + $childCat = array($categoryForSale); + + foreach ($catList as $key => $value) { + $childCat[] = $value->id; + } + + if (!empty($customField)) { + $key = 0; + $subQuery = array(); + + foreach ($customField as $fieldId => $fieldValues) { + $fieldValues = array_filter($fieldValues); + + if (empty($fieldValues)) { + continue; + } + + foreach ($fieldValues as $value) { + $subQuery[] = 'FIND_IN_SET("' . $value . '", ' . $db->qn('fd' . $key . '.data_txt') . ')'; + } + + $query->leftJoin( + $db->qn('#__redshop_fields_data', 'fd' . $key) . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn( + 'fd' . $key . '.itemid' + ) + ) + ->where($db->qn('fd' . $key . '.fieldid') . ' = ' . $db->q((int)$fieldId)); + $key++; + } + + if (!empty($subQuery)) { + $query->where('(' . implode(' OR ', $subQuery) . ')'); + } + } + + if (!empty($categoryForSale) && in_array($cid, $childCat)) { + if (!empty($categories)) { + foreach ($categories as $key => $value) { + $query->leftJoin( + $db->qn('#__redshop_product_category_xref', 'pc' . $key) . ' ON ' + . $db->qn('p.product_id') . ' = ' + . $db->qn('pc' . $key . '.product_id') + ) + ->where($db->qn('pc' . $key . '.category_id') . ' = ' . $db->q((int)$value)) + ->where($db->qn("pc.category_id") . " = " . $db->q((int)$cid)); + } + } elseif (!empty($cid) || !empty($categories)) { + $query->where($db->qn("pc.category_id") . " IN (" . $categoryList . ')'); + } + } elseif (!empty($cid) || !empty($categories)) { + $query->where($db->qn("pc.category_id") . " IN (" . $categoryList . ')'); + } + + if (!empty($manufacturers)) { + $query->where($db->qn("p.manufacturer_id") . " IN (" . implode(',', $manufacturers) . ')'); + } elseif ($mid) { + $query->where($db->qn("p.manufacturer_id") . "=" . $db->q((int)$mid)); + } + + if (!empty($productOnSale)) { + $query->where($db->qn('p.product_on_sale') . ' = ' . $db->q((int)$productOnSale)); + } + + if ($orderBy) { + $query->order($db->escape($orderBy)); + } + + JPluginHelper::importPlugin('redshop_product'); + JDispatcher::getInstance()->trigger('onFilterProduct', array(&$query, $pk)); + + return $query; + } + + /** + * Get pagination. + * + * @return JPagination + */ + public function getFilterPagination() + { + $endlimit = $this->getState('list.limit'); + $limitstart = $this->getState('list.start'); + $this->pagination = new JPagination($this->getFilterTotal(), $limitstart, $endlimit); + + return $this->pagination; + } + + /** + * Get total. + * + * @return integer + */ + public function getFilterTotal() + { + $query = $this->getListQuery(); + $this->total = $this->_getListCount($query); + + return $this->total; + } + + /** + * Method to auto-populate the model state. + * + * This method should only be called once per instantiation and is designed + * to be called on the first call to the getState() method unless the model + * configuration flag to ignore the request is set. + * + * @param string $ordering An optional ordering field. + * @param string $direction An optional direction (asc|desc). + * + * @return void + * + * @note Calling getState in this method will result in recursion. + */ + protected function populateState($ordering = null, $direction = null) + { + parent::populateState($ordering, $direction); + + $app = JFactory::getApplication(); + $params = JComponentHelper::getParams('com_redshop'); + $menu = $app->getMenu(); + $item = $menu->getActive(); + $layout = $app->getUserStateFromRequest($this->context . '.layout', 'layout', 'default'); + $this->setState('layout', $layout); + + $templateid = $app->getUserStateFromRequest($this->context . '.templateid', 'templateid', ''); + + $cid = 0; + + if ($layout == 'newproduct') { + $result = $item->query['template_id']; + + if ($result != 0) { + $templateid = $result; + } else { + $cid = $item->query['categorytemplate']; + } + } elseif ($layout == 'productonsale') { + $cid = $item->params->get('categorytemplate'); + } + + if ($layout == 'productonsale' || $layout == 'featuredproduct') { + $result = $item->params->get('template_id'); + + if ($result != 0) { + $templateid = $result; + $cid = 0; + } + } + + if ($templateid == "" && JModuleHelper::isEnabled('redPRODUCTFILTER')) { + $module = JModuleHelper::getModule('redPRODUCTFILTER'); + $module_params = new Registry($module->params); + + if ($module_params->get('filtertemplate') != "") { + $templateid = $module_params->get('filtertemplate'); + } + } + + $this->setState('templateid', $templateid); + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('c.template AS category_template, t.*') + ->from($db->qn('#__redshop_template', 't')) + ->leftJoin($db->qn('#__redshop_category', 'c') . ' ON t.id = c.template') + ->where('t.section = ' . $db->q('category')) + ->where('t.published = 1'); + + if ($cid != 0) { + $query->where('c.id = ' . (int)$cid); + } + + if ($templateid != 0) { + $query->where('t.id = ' . (int)$templateid); + } + + $templateDesc = null; + + if ($template = $db->setQuery($query)->loadObject()) { + $templateDesc = RedshopHelperTemplate::readTemplateFile($template->section, $template->file_name); + } + + $this->setState('templateDesc', $templateDesc); + $limit = 0; + + if ($module = JModuleHelper::getModule('redshop_search')) { + $module_params = new Registry($module->params); + $perpageproduct = $module_params->get('productperpage', 5); + } else { + $perpageproduct = 5; + } + + if ( + !strstr($templateDesc, "{show_all_products_in_category}") + && strstr($templateDesc, "{pagination}") + && strstr($templateDesc, "perpagelimit:") + ) { + $perpage = explode('{perpagelimit:', $templateDesc); + $perpage = explode('}', $perpage[1]); + $limit = intval($perpage[0]); + } else { + $limit = $app->getUserStateFromRequest($this->context . '.limit', 'limit', $limit, 'int'); + + if (!$limit && $perpageproduct != 0 && $perpageproduct != '' && $layout == 'default') { + $limit = $perpageproduct; + } elseif (!$limit && $layout == 'productonsale') { + $limit = $params->get('productlimit', 5); + } elseif (!$limit) { + $limit = Redshop::getConfig()->get('MAXCATEGORY'); + } + } + + $productlimit = 0; + + if (isset($item->query['productlimit'])) { + $productlimit = $item->query['productlimit']; + } + + $filter = $app->input->post->get('redform', array(), 'filter'); + $this->setState('filter.data', $filter); + + $orderBy = $app->input->getString('order_by', ''); + $this->setState('order_by', $orderBy); + $this->setState('template_id', isset($filter['template_id']) ? $filter['template_id'] : null); + + $this->setState('productperpage', $perpageproduct); + $this->setState('list.limit', $limit); + $productlimit = $app->getUserStateFromRequest( + $this->context . '.productlimit', + 'productlimit', + $productlimit, + 8 + ); + $this->setState('productlimit', $productlimit); + + $value = $app->input->get('limitstart', 0, 'int'); + $limitstart = ($limit != 0 ? (floor($value / $limit) * $limit) : 0); + $this->setState('list.start', $limitstart); + + $keyword = $app->getUserStateFromRequest($this->context . '.keyword', 'keyword', ''); + $this->setState('keyword', $keyword); + } } diff --git a/component/site/models/send_friend.php b/component/site/models/send_friend.php index b61c1130024..30c46473a65 100644 --- a/component/site/models/send_friend.php +++ b/component/site/models/send_friend.php @@ -18,121 +18,117 @@ */ class RedshopModelSend_Friend extends RedshopModel { - /** - * @var integer - */ - public $_id = null; - - /** - * @var null - */ - public $_data = null; - - /** - * @var null - */ - public $_product = null; - - /** - * @var string - */ - public $_table_prefix = null; - - /** - * @var null - */ - public $_template = null; - - /** - * RedshopModelSend_Friend constructor. - * - * @throws Exception - */ - public function __construct() - { - parent::__construct(); - - $this->_table_prefix = '#__redshop_'; - - $this->setId(JFactory::getApplication()->input->getInt('pid', 0)); - } - - /** - * Method for set ID - * - * @param integer $id ID - * - * @return void - */ - public function setId($id) - { - $this->_id = $id; - $this->_data = null; - } - - /** - * Method for send mail to friend - * - * @param string $yourName Your name - * @param string $friendName Friend name - * @param integer $productId Product ID - * @param string $email Friend email - * - * @return void - * @throws Exception - */ - public function sendProductMailToFriend($yourName, $friendName, $productId, $email) - { - $mailTemplate = Redshop\Mail\Helper::getTemplate(0, "product"); - $mailBcc = null; - - if (!empty($mailTemplate)) - { - $mailBody = $mailTemplate[0]->mail_body; - $subject = $mailTemplate[0]->mail_subject; - - if (trim($mailTemplate[0]->mail_bcc) != "") - { - $mailBcc = explode(",", $mailTemplate[0]->mail_bcc); - } - } - else - { - $mailBody = "

    Hi {friend_name} ,

    \r\n

    New Product : {product_name}

    \r\n" - . "

    {product_desc} Please check this link : {product_url}

    \r\n

    \r\n

    "; - $subject = "Send to friend"; - } - - $mailBody = str_replace("{friend_name}", $friendName, $mailBody); - $mailBody = str_replace("{your_name}", $yourName, $mailBody); - - $product = \Redshop\Product\Product::getProductById($productId); - - $mailBody = str_replace("{product_name}", $product->product_name, $mailBody); - $mailBody = str_replace("{product_desc}", $product->product_desc, $mailBody); - - $productLink = JRoute::_(JUri::base() . 'index.php?option=com_redshop&view=product&pid=' . $productId, false); - $productLink = "" . $productLink . ""; - $mailBody = str_replace("{product_url}", $productLink, $mailBody); - Redshop\Mail\Helper::imgInMail($mailBody); - - $config = JFactory::getConfig(); - $from = (string) $config->get('mailfrom'); - $fromName = (string) $config->get('fromname'); - - $subject = str_replace("{product_name}", $product->product_name, $subject); - $subject = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $subject); - - if (!empty($email)) - { - if (JFactory::getMailer()->sendMail($from, $fromName, $email, $subject, $mailBody, 1, null, $mailBcc)) - { - echo "
    " . JText::_('COM_REDSHOP_EMAIL_HAS_BEEN_SENT_SUCCESSFULLY') . "
    "; - } - else - { - echo "
    " . JText::_('COM_REDSHOP_EMAIL_HAS_NOT_BEEN_SENT_SUCCESSFULLY') . "
    "; - } - } - } + /** + * @var integer + */ + public $_id = null; + + /** + * @var null + */ + public $_data = null; + + /** + * @var null + */ + public $_product = null; + + /** + * @var string + */ + public $_table_prefix = null; + + /** + * @var null + */ + public $_template = null; + + /** + * RedshopModelSend_Friend constructor. + * + * @throws Exception + */ + public function __construct() + { + parent::__construct(); + + $this->_table_prefix = '#__redshop_'; + + $this->setId(JFactory::getApplication()->input->getInt('pid', 0)); + } + + /** + * Method for set ID + * + * @param integer $id ID + * + * @return void + */ + public function setId($id) + { + $this->_id = $id; + $this->_data = null; + } + + /** + * Method for send mail to friend + * + * @param string $yourName Your name + * @param string $friendName Friend name + * @param integer $productId Product ID + * @param string $email Friend email + * + * @return void + * @throws Exception + */ + public function sendProductMailToFriend($yourName, $friendName, $productId, $email) + { + $mailTemplate = Redshop\Mail\Helper::getTemplate(0, "product"); + $mailBcc = null; + + if (!empty($mailTemplate)) { + $mailBody = $mailTemplate[0]->mail_body; + $subject = $mailTemplate[0]->mail_subject; + + if (trim($mailTemplate[0]->mail_bcc) != "") { + $mailBcc = explode(",", $mailTemplate[0]->mail_bcc); + } + } else { + $mailBody = "

    Hi {friend_name} ,

    \r\n

    New Product : {product_name}

    \r\n" + . "

    {product_desc} Please check this link : {product_url}

    \r\n

    \r\n

    "; + $subject = "Send to friend"; + } + + $mailBody = str_replace("{friend_name}", $friendName, $mailBody); + $mailBody = str_replace("{your_name}", $yourName, $mailBody); + + $product = \Redshop\Product\Product::getProductById($productId); + + $mailBody = str_replace("{product_name}", $product->product_name, $mailBody); + $mailBody = str_replace("{product_desc}", $product->product_desc, $mailBody); + + $productLink = JRoute::_(JUri::base() . 'index.php?option=com_redshop&view=product&pid=' . $productId, false); + $productLink = "" . $productLink . ""; + $mailBody = str_replace("{product_url}", $productLink, $mailBody); + Redshop\Mail\Helper::imgInMail($mailBody); + + $config = JFactory::getConfig(); + $from = (string)$config->get('mailfrom'); + $fromName = (string)$config->get('fromname'); + + $subject = str_replace("{product_name}", $product->product_name, $subject); + $subject = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $subject); + + if (!empty($email)) { + if (JFactory::getMailer()->sendMail($from, $fromName, $email, $subject, $mailBody, 1, null, $mailBcc)) { + echo "
    " . JText::_( + 'COM_REDSHOP_EMAIL_HAS_BEEN_SENT_SUCCESSFULLY' + ) . "
    "; + } else { + echo "
    " . JText::_( + 'COM_REDSHOP_EMAIL_HAS_NOT_BEEN_SENT_SUCCESSFULLY' + ) . "
    "; + } + } + } } diff --git a/component/site/models/wishlist.php b/component/site/models/wishlist.php index e02aa7cda04..2b4818f0931 100644 --- a/component/site/models/wishlist.php +++ b/component/site/models/wishlist.php @@ -21,504 +21,474 @@ */ class RedshopModelWishlist extends RedshopModel { - public $_id = null; - - public $_name = null; - - // Product data - public $_userid = null; - - public $_comment = null; - - public $_cdate = null; - - /** - * Method for get User Wishlist - * - * @return bool|mixed - * - * @deprecated 2.0.3 Use RedshopHelperWishlist::getUserWishlist() instead. - */ - public function getUserWishlist() - { - return RedshopHelperWishlist::getUserWishlist(); - } - - /** - * - * @return array|mixed - */ - public function getWishlistProduct() - { - $user = JFactory::getUser(); - $db = JFactory::getDbo(); - $session = JFactory::getSession(); - - if ($user->id) - { - $wishlists = $this->getUserWishlist(); - $wishProducts = array(); - - foreach ($wishlists as $key => $wishlist) - { - $query = $db->getQuery(true) - ->select('DISTINCT wp.*, p.*') - ->from($db->qn('#__redshop_product', 'p')) - ->leftJoin($db->qn('#__redshop_wishlist_product', 'wp') . ' ON ' . $db->qn('wp.product_id') . ' = ' . $db->qn('p.product_id')) - ->where($db->qn('wp.wishlist_id') . ' = ' . $db->q((int) $wishlist->wishlist_id)); - - $wishProducts[$wishlist->wishlist_id] = $db->setQuery($query)->loadObjectList(); - } - - return $wishProducts; - } - - $numberProduct = $session->get('no_of_prod'); - - if (!isset($numberProduct)) - { - return array(); - } - - $productIds = array(); - - for ($add = 1; $add <= $numberProduct; $add++) - { - if (!isset($session->get('wish_' . $add)->product_id)) - { - continue; - } - - $productIds[] = (int) $session->get('wish_' . $add)->product_id; - } - - if (empty($productIds)) - { - return array(); - } - - $query = $db->getQuery(true) - ->select('DISTINCT *') - ->from($db->qn('#__redshop_product')) - ->where($db->qn('product_id') . ' IN (' . implode(',', ArrayHelper::toInteger($productIds)) . ')'); - - return $db->setQuery($query)->loadObjectList(); - } - - public function getWishlistProductFromSession() - { - $db = JFactory::getDbo(); - $session = JFactory::getSession(); - $wishlist = $session->get('wishlist'); - $productIds = array(); - - if (empty($wishlist)) - { - return array(); - } - - foreach ($wishlist as $productId => $wish) - { - $productIds[] = $productId; - } - - if (empty($productIds)) - { - return array(); - } - - $query = $db->getQuery(true) - ->select($db->qn('p.product_id', 'index')) - ->select('p.*') - ->select($db->qn('pcx.category_id')) - ->from($db->qn('#__redshop_product', 'p')) - ->leftJoin($db->qn('#__redshop_product_category_xref', 'pcx') . ' ON ' . $db->qn('pcx.product_id') . ' = ' . $db->qn('p.product_id')) - ->where($db->qn('p.product_id') . ' IN (' . implode(',', ArrayHelper::toInteger($productIds)) . ')') - ->group($db->qn('index')); - - $products = $db->setQuery($query)->loadObjectList('index'); - - if (empty($products)) - { - return array(); - } - - if (!Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE')) - { - $products = array_filter($products); - - return $products; - } - - $rows = array(); - - foreach ($wishlist as $productId => $wishes) - { - foreach ($wishes as $wish) - { - $newWish = clone $products[$productId]; - $newWish->product_items = $wish->product_items ?? ''; - - $rows[] = $newWish; - } - } - - return $rows; - } - - public function store($data) - { - $row = $this->getTable(); - - if (!$row->bind($data)) - { - $this->setError($this->_db->getErrorMsg()); - - return false; - } - - if (!$row->store()) - { - $this->setError($this->_db->getErrorMsg()); - - return false; - } - - $session = JFactory::getSession(); - $numberProduct = $session->get('no_of_prod'); - $db = JFactory::getDbo(); - $productId = $data['product_id']; - - if ($productId) - { - $columns = array('wishlist_id', 'product_id', 'cdate'); - $values = array($row->wishlist_id, $productId, $db->q(time())); - $query = $db->getQuery(true) - ->insert($db->qn('#__redshop_wishlist_product')) - ->columns($db->qn($columns)) - ->values(implode(',', $values)); - - return (bool) $db->setQuery($query)->execute(); - } - - if ($numberProduct) - { - ob_clean(); - $rowData = RedshopHelperExtrafields::getSectionFieldList(12); - $totalRowData = count($rowData); - - for ($si = 1; $si <= $numberProduct; $si++) - { - $data = $session->get('wish_' . $si); - - for ($k = 0, $kn = $totalRowData; $k < $kn; $k++) - { - $field = "productuserfield_" . $k; - - if (empty($data->{$field})) - { - continue; - } - - $values = array($row->wishlist_id, (int) $data->product_id, $db->q($data->{$field})); - - $query = $db->getQuery(true) - ->insert($db->qn('#__redshop_wishlist_userfielddata')) - ->columns($db->qn(array('wishlist_id', 'product_id', 'userfielddata'))) - ->values(implode(',', $values)); - $db->setQuery($query)->execute(); - } - - $values = array($row->wishlist_id, (int) $data->product_id, $db->q($data->cdate)); - $query = $db->getQuery(true) - ->insert($db->qn('#__redshop_wishlist_product')) - ->columns($db->qn(array('wishlist_id', 'product_id', 'cdate'))) - ->values(implode(',', $values)); - $db->setQuery($query)->execute(); - - $session->clear('wish_' . $si); - } - - $session->clear('no_of_prod'); - } - - return true; - } - - /** - * Method for save wishlist. - * - * @param array $data List of data - * - * @return boolean True if success. False otherwise. - * - * @throws Exception - */ - public function savewishlist($data) - { - if (empty($data)) - { - $input = JFactory::getApplication()->input; - - $wishlistIds = $input->get('wishlist_id', array(), 'Array'); - $productIds = $input->getString('product_id', ''); - $attributeIds = $input->getString('attribute_id', 0); - $propertyIds = $input->getString('property_id', 0); - $subAttributeIds = $input->getString('subattribute_id', 0); - } - else - { - $wishlistIds = isset($data['wishlist_id']) ? $data['wishlist_id'] : array(); - $productIds = isset($data['product_id']) ? $data['product_id'] : ''; - $attributeIds = isset($data['attribute_id']) ? $data['attribute_id'] : ''; - $propertyIds = isset($data['property_id']) ? $data['property_id'] : ''; - $subAttributeIds = isset($data['subattribute_id']) ? $data['subattribute_id'] : ''; - } - - $productIds = explode(',', $productIds); - $productIds = array_filter($productIds); - - if (empty($wishlistIds)) - { - return false; - } - - JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/tables'); - - foreach ($wishlistIds as $wishlistId) - { - foreach ($productIds as $productId) - { - /** @var RedshopTableWishlist_Product $table */ - $wishlistProductTable = JTable::getInstance('Wishlist_Product', 'RedshopTable'); - - $tmpData = array( - 'wishlist_id' => $wishlistId, - 'product_id' => $productId - ); - - /* - * Check: If there are already has product in this wishlist. Continue with: - * 1. In case "Add to cart per product" -> Skip this process. - * 2. In case "Add to cart per attribute" -> Check on product attributes exist. If not, start create new wishlist item. - */ - if ($wishlistProductTable->load($tmpData) - && (Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE') == 0 - || $this->isProductDataExist($wishlistId, $productId, $attributeIds, $propertyIds, $subAttributeIds))) - { - continue; - } - - $attributeIds = explode('##', $attributeIds); - $attributeIds = ArrayHelper::toInteger($attributeIds); - $propertyIds = explode('##', $propertyIds); - $propertyIds = ArrayHelper::toInteger($propertyIds); - $subAttributeIds = explode('##', $subAttributeIds); - $subAttributeIds = ArrayHelper::toInteger($subAttributeIds); - - $wishlistProductTable->reset(); - $wishlistProductTable->set('wishlist_product_id', null); - $wishlistProductTable->set('wishlist_id', $wishlistId); - $wishlistProductTable->set('product_id', $productId); - $wishlistProductTable->set('cdate', time()); - - if (!$wishlistProductTable->store()) - { - throw new Exception($wishlistProductTable->getError()); - } - - $attributeIds = array_filter($attributeIds); - - // If there are not attribute with product. - if (empty($attributeIds)) - { - continue; - } - - foreach ($attributeIds as $index => $attributeId) - { - /** @var RedshopTableWishlist_Product_Item $table */ - $wishlistProductItemTable = JTable::getInstance('Wishlist_Product_Item', 'RedshopTable'); - - $tmpData = array( - 'ref_id' => (int) $wishlistProductTable->get('wishlist_product_id'), - 'attribute_id' => $attributeId - ); - - if (!empty($propertyIds[$index])) - { - $tmpData['property_id'] = (int) $propertyIds[$index]; - } - - if (!empty($subAttributeIds[$index])) - { - $tmpData['subattribute_id'] = (int) $subAttributeIds[$index]; - } - - // If wishlist product item has already exist. Skip it. - if ($wishlistProductItemTable->load($tmpData)) - { - continue; - } - - if (!$wishlistProductItemTable->save($tmpData)) - { - throw new Exception($wishlistProductItemTable->getError()); - } - } - } - } - - return true; - } - - public function check_user_wishlist_authority($userId, $wishlistId) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->quoteName('wishlist_id')) - ->from($db->quoteName('#__redshop_wishlist')) - ->where($db->quoteName('user_id') . ' = ' . (int) $userId) - ->where($db->quoteName('wishlist_id') . ' = ' . (int) $wishlistId); - - if ($db->setQuery($query)->loadResult()) - { - return true; - } - - return false; - } - - public function delwishlist($userId, $wishlistId) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->delete($db->quoteName('#__redshop_wishlist_product')) - ->where($db->quoteName('wishlist_id') . ' = ' . (int) $wishlistId); - $db->setQuery($query)->execute(); - - $query->clear() - ->delete($db->quoteName('#__redshop_wishlist_userfielddata')) - ->where($db->quoteName('wishlist_id') . ' = ' . (int) $wishlistId); - - if (!$db->setQuery($query)->execute()) - { - return false; - } - - $query->clear() - ->delete($db->quoteName('#__redshop_wishlist')) - ->where($db->quoteName('wishlist_id') . ' = ' . (int) $wishlistId) - ->where($db->quoteName('user_id') . ' = ' . (int) $userId); - - if ($db->setQuery($query)->execute()) - { - return true; - } - - return false; - } - - public function mysessdelwishlist($data) - { - if (is_int($data)) - { - $productId = (int) $data; - } - else - { - $productId = isset($data['wishlist_id']) ? (int) $data['wishlist_id'] : 0; - $attributeId = isset($data['attribute_id']) ? (int) $data['attribute_id'] : 0; - $propertyId = isset($data['property_id']) ? (int) $data['property_id'] : 0; - $subAttributeId = isset($data['subattribute_id']) ? (int) $data['subattribute_id'] : 0; - } - - $session = JFactory::getSession(); - $wishlist = $session->get('wishlist'); - - if (empty($wishlist) || !isset($wishlist[$productId])) - { - return true; - } - - if (!Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE')) - { - if (isset($wishlist[$productId])) - { - unset($wishlist[$productId]); - } - - $session->set('wishlist', $wishlist); - - return true; - } - - $checkObject = new stdClass; - $checkObject->attribute_id = $attributeId; - $checkObject->property_id = $propertyId; - $checkObject->subattribute_id = $subAttributeId; - - foreach ($wishlist[$productId] as $key => $wish) - { - if ($wish->product_items == $checkObject) - { - unset($wishlist[$productId][$key]); - } - } - - $wishlist[$productId] = array_values($wishlist[$productId]); - $session->set('wishlist', $wishlist); - - return true; - } - - /** - * Method for check if product data has been exist. - * - * @param int $wishlistId Wishlist ID. - * @param int $productId Product ID. - * @param array $attributes Attributes data. - * @param array $properties Properties data. - * @param array $subAttributes Sub-properties data. - * - * @return boolean True on exist. False otherwise. - * - * @since 2.0.3 - */ - public function isProductDataExist($wishlistId, $productId, $attributes = null, $properties = null, $subAttributes = null) - { - if (!$wishlistId || !$productId) - { - return false; - } - - $wishlistData = RedshopHelperWishlist::getWishlist($wishlistId); - - // Check: If this product is not exist in this wishlist. - // Or this product is exist but new product doesn't have attribute data. - if (!isset($wishlistData->products[$productId]) || !$attributes) - { - return false; - } - - $attributes = !is_array($attributes) ? array($attributes) : $attributes; - $properties = !is_array($properties) ? array($properties) : $properties; - $subAttributes = !is_array($subAttributes) ? array($subAttributes) : $subAttributes; - - foreach ($wishlistData->products[$productId] as $wishlistProduct) - { - /* Check: If attributes has different. - Or properties has different. - Or sub-attributes has different. - */ - if (!empty(array_diff($attributes, $wishlistProduct->attributes)) - || !empty(array_diff($properties, $wishlistProduct->properties)) - || !empty(array_diff($subAttributes, $wishlistProduct->subAttributes))) - { - return false; - } - } - - return true; - } + public $_id = null; + + public $_name = null; + + // Product data + public $_userid = null; + + public $_comment = null; + + public $_cdate = null; + + /** + * + * @return array|mixed + */ + public function getWishlistProduct() + { + $user = JFactory::getUser(); + $db = JFactory::getDbo(); + $session = JFactory::getSession(); + + if ($user->id) { + $wishlists = $this->getUserWishlist(); + $wishProducts = array(); + + foreach ($wishlists as $key => $wishlist) { + $query = $db->getQuery(true) + ->select('DISTINCT wp.*, p.*') + ->from($db->qn('#__redshop_product', 'p')) + ->leftJoin( + $db->qn('#__redshop_wishlist_product', 'wp') . ' ON ' . $db->qn( + 'wp.product_id' + ) . ' = ' . $db->qn('p.product_id') + ) + ->where($db->qn('wp.wishlist_id') . ' = ' . $db->q((int)$wishlist->wishlist_id)); + + $wishProducts[$wishlist->wishlist_id] = $db->setQuery($query)->loadObjectList(); + } + + return $wishProducts; + } + + $numberProduct = $session->get('no_of_prod'); + + if (!isset($numberProduct)) { + return array(); + } + + $productIds = array(); + + for ($add = 1; $add <= $numberProduct; $add++) { + if (!isset($session->get('wish_' . $add)->product_id)) { + continue; + } + + $productIds[] = (int)$session->get('wish_' . $add)->product_id; + } + + if (empty($productIds)) { + return array(); + } + + $query = $db->getQuery(true) + ->select('DISTINCT *') + ->from($db->qn('#__redshop_product')) + ->where($db->qn('product_id') . ' IN (' . implode(',', ArrayHelper::toInteger($productIds)) . ')'); + + return $db->setQuery($query)->loadObjectList(); + } + + /** + * Method for get User Wishlist + * + * @return bool|mixed + * + * @deprecated 2.0.3 Use RedshopHelperWishlist::getUserWishlist() instead. + */ + public function getUserWishlist() + { + return RedshopHelperWishlist::getUserWishlist(); + } + + public function getWishlistProductFromSession() + { + $db = JFactory::getDbo(); + $session = JFactory::getSession(); + $wishlist = $session->get('wishlist'); + $productIds = array(); + + if (empty($wishlist)) { + return array(); + } + + foreach ($wishlist as $productId => $wish) { + $productIds[] = $productId; + } + + if (empty($productIds)) { + return array(); + } + + $query = $db->getQuery(true) + ->select($db->qn('p.product_id', 'index')) + ->select('p.*') + ->select($db->qn('pcx.category_id')) + ->from($db->qn('#__redshop_product', 'p')) + ->leftJoin( + $db->qn('#__redshop_product_category_xref', 'pcx') . ' ON ' . $db->qn( + 'pcx.product_id' + ) . ' = ' . $db->qn('p.product_id') + ) + ->where($db->qn('p.product_id') . ' IN (' . implode(',', ArrayHelper::toInteger($productIds)) . ')') + ->group($db->qn('index')); + + $products = $db->setQuery($query)->loadObjectList('index'); + + if (empty($products)) { + return array(); + } + + if (!Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE')) { + $products = array_filter($products); + + return $products; + } + + $rows = array(); + + foreach ($wishlist as $productId => $wishes) { + foreach ($wishes as $wish) { + $newWish = clone $products[$productId]; + $newWish->product_items = $wish->product_items ?? ''; + + $rows[] = $newWish; + } + } + + return $rows; + } + + public function store($data) + { + $row = $this->getTable(); + + if (!$row->bind($data)) { + $this->setError($this->_db->getErrorMsg()); + + return false; + } + + if (!$row->store()) { + $this->setError($this->_db->getErrorMsg()); + + return false; + } + + $session = JFactory::getSession(); + $numberProduct = $session->get('no_of_prod'); + $db = JFactory::getDbo(); + $productId = $data['product_id']; + + if ($productId) { + $columns = array('wishlist_id', 'product_id', 'cdate'); + $values = array($row->wishlist_id, $productId, $db->q(time())); + $query = $db->getQuery(true) + ->insert($db->qn('#__redshop_wishlist_product')) + ->columns($db->qn($columns)) + ->values(implode(',', $values)); + + return (bool)$db->setQuery($query)->execute(); + } + + if ($numberProduct) { + ob_clean(); + $rowData = RedshopHelperExtrafields::getSectionFieldList(12); + $totalRowData = count($rowData); + + for ($si = 1; $si <= $numberProduct; $si++) { + $data = $session->get('wish_' . $si); + + for ($k = 0, $kn = $totalRowData; $k < $kn; $k++) { + $field = "productuserfield_" . $k; + + if (empty($data->{$field})) { + continue; + } + + $values = array($row->wishlist_id, (int)$data->product_id, $db->q($data->{$field})); + + $query = $db->getQuery(true) + ->insert($db->qn('#__redshop_wishlist_userfielddata')) + ->columns($db->qn(array('wishlist_id', 'product_id', 'userfielddata'))) + ->values(implode(',', $values)); + $db->setQuery($query)->execute(); + } + + $values = array($row->wishlist_id, (int)$data->product_id, $db->q($data->cdate)); + $query = $db->getQuery(true) + ->insert($db->qn('#__redshop_wishlist_product')) + ->columns($db->qn(array('wishlist_id', 'product_id', 'cdate'))) + ->values(implode(',', $values)); + $db->setQuery($query)->execute(); + + $session->clear('wish_' . $si); + } + + $session->clear('no_of_prod'); + } + + return true; + } + + /** + * Method for save wishlist. + * + * @param array $data List of data + * + * @return boolean True if success. False otherwise. + * + * @throws Exception + */ + public function savewishlist($data) + { + if (empty($data)) { + $input = JFactory::getApplication()->input; + + $wishlistIds = $input->get('wishlist_id', array(), 'Array'); + $productIds = $input->getString('product_id', ''); + $attributeIds = $input->getString('attribute_id', 0); + $propertyIds = $input->getString('property_id', 0); + $subAttributeIds = $input->getString('subattribute_id', 0); + } else { + $wishlistIds = isset($data['wishlist_id']) ? $data['wishlist_id'] : array(); + $productIds = isset($data['product_id']) ? $data['product_id'] : ''; + $attributeIds = isset($data['attribute_id']) ? $data['attribute_id'] : ''; + $propertyIds = isset($data['property_id']) ? $data['property_id'] : ''; + $subAttributeIds = isset($data['subattribute_id']) ? $data['subattribute_id'] : ''; + } + + $productIds = explode(',', $productIds); + $productIds = array_filter($productIds); + + if (empty($wishlistIds)) { + return false; + } + + JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/tables'); + + foreach ($wishlistIds as $wishlistId) { + foreach ($productIds as $productId) { + /** @var RedshopTableWishlist_Product $table */ + $wishlistProductTable = JTable::getInstance('Wishlist_Product', 'RedshopTable'); + + $tmpData = array( + 'wishlist_id' => $wishlistId, + 'product_id' => $productId + ); + + /* + * Check: If there are already has product in this wishlist. Continue with: + * 1. In case "Add to cart per product" -> Skip this process. + * 2. In case "Add to cart per attribute" -> Check on product attributes exist. If not, start create new wishlist item. + */ + if ($wishlistProductTable->load($tmpData) + && (Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE') == 0 + || $this->isProductDataExist( + $wishlistId, + $productId, + $attributeIds, + $propertyIds, + $subAttributeIds + ))) { + continue; + } + + $attributeIds = explode('##', $attributeIds); + $attributeIds = ArrayHelper::toInteger($attributeIds); + $propertyIds = explode('##', $propertyIds); + $propertyIds = ArrayHelper::toInteger($propertyIds); + $subAttributeIds = explode('##', $subAttributeIds); + $subAttributeIds = ArrayHelper::toInteger($subAttributeIds); + + $wishlistProductTable->reset(); + $wishlistProductTable->set('wishlist_product_id', null); + $wishlistProductTable->set('wishlist_id', $wishlistId); + $wishlistProductTable->set('product_id', $productId); + $wishlistProductTable->set('cdate', time()); + + if (!$wishlistProductTable->store()) { + throw new Exception($wishlistProductTable->getError()); + } + + $attributeIds = array_filter($attributeIds); + + // If there are not attribute with product. + if (empty($attributeIds)) { + continue; + } + + foreach ($attributeIds as $index => $attributeId) { + /** @var RedshopTableWishlist_Product_Item $table */ + $wishlistProductItemTable = JTable::getInstance('Wishlist_Product_Item', 'RedshopTable'); + + $tmpData = array( + 'ref_id' => (int)$wishlistProductTable->get('wishlist_product_id'), + 'attribute_id' => $attributeId + ); + + if (!empty($propertyIds[$index])) { + $tmpData['property_id'] = (int)$propertyIds[$index]; + } + + if (!empty($subAttributeIds[$index])) { + $tmpData['subattribute_id'] = (int)$subAttributeIds[$index]; + } + + // If wishlist product item has already exist. Skip it. + if ($wishlistProductItemTable->load($tmpData)) { + continue; + } + + if (!$wishlistProductItemTable->save($tmpData)) { + throw new Exception($wishlistProductItemTable->getError()); + } + } + } + } + + return true; + } + + /** + * Method for check if product data has been exist. + * + * @param int $wishlistId Wishlist ID. + * @param int $productId Product ID. + * @param array $attributes Attributes data. + * @param array $properties Properties data. + * @param array $subAttributes Sub-properties data. + * + * @return boolean True on exist. False otherwise. + * + * @since 2.0.3 + */ + public function isProductDataExist( + $wishlistId, + $productId, + $attributes = null, + $properties = null, + $subAttributes = null + ) { + if (!$wishlistId || !$productId) { + return false; + } + + $wishlistData = RedshopHelperWishlist::getWishlist($wishlistId); + + // Check: If this product is not exist in this wishlist. + // Or this product is exist but new product doesn't have attribute data. + if (!isset($wishlistData->products[$productId]) || !$attributes) { + return false; + } + + $attributes = !is_array($attributes) ? array($attributes) : $attributes; + $properties = !is_array($properties) ? array($properties) : $properties; + $subAttributes = !is_array($subAttributes) ? array($subAttributes) : $subAttributes; + + foreach ($wishlistData->products[$productId] as $wishlistProduct) { + /* Check: If attributes has different. + Or properties has different. + Or sub-attributes has different. + */ + if (!empty(array_diff($attributes, $wishlistProduct->attributes)) + || !empty(array_diff($properties, $wishlistProduct->properties)) + || !empty(array_diff($subAttributes, $wishlistProduct->subAttributes))) { + return false; + } + } + + return true; + } + + public function check_user_wishlist_authority($userId, $wishlistId) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->quoteName('wishlist_id')) + ->from($db->quoteName('#__redshop_wishlist')) + ->where($db->quoteName('user_id') . ' = ' . (int)$userId) + ->where($db->quoteName('wishlist_id') . ' = ' . (int)$wishlistId); + + if ($db->setQuery($query)->loadResult()) { + return true; + } + + return false; + } + + public function delwishlist($userId, $wishlistId) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->delete($db->quoteName('#__redshop_wishlist_product')) + ->where($db->quoteName('wishlist_id') . ' = ' . (int)$wishlistId); + $db->setQuery($query)->execute(); + + $query->clear() + ->delete($db->quoteName('#__redshop_wishlist_userfielddata')) + ->where($db->quoteName('wishlist_id') . ' = ' . (int)$wishlistId); + + if (!$db->setQuery($query)->execute()) { + return false; + } + + $query->clear() + ->delete($db->quoteName('#__redshop_wishlist')) + ->where($db->quoteName('wishlist_id') . ' = ' . (int)$wishlistId) + ->where($db->quoteName('user_id') . ' = ' . (int)$userId); + + if ($db->setQuery($query)->execute()) { + return true; + } + + return false; + } + + public function mysessdelwishlist($data) + { + if (is_int($data)) { + $productId = (int)$data; + } else { + $productId = isset($data['wishlist_id']) ? (int)$data['wishlist_id'] : 0; + $attributeId = isset($data['attribute_id']) ? (int)$data['attribute_id'] : 0; + $propertyId = isset($data['property_id']) ? (int)$data['property_id'] : 0; + $subAttributeId = isset($data['subattribute_id']) ? (int)$data['subattribute_id'] : 0; + } + + $session = JFactory::getSession(); + $wishlist = $session->get('wishlist'); + + if (empty($wishlist) || !isset($wishlist[$productId])) { + return true; + } + + if (!Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE')) { + if (isset($wishlist[$productId])) { + unset($wishlist[$productId]); + } + + $session->set('wishlist', $wishlist); + + return true; + } + + $checkObject = new stdClass; + $checkObject->attribute_id = $attributeId; + $checkObject->property_id = $propertyId; + $checkObject->subattribute_id = $subAttributeId; + + foreach ($wishlist[$productId] as $key => $wish) { + if ($wish->product_items == $checkObject) { + unset($wishlist[$productId][$key]); + } + } + + $wishlist[$productId] = array_values($wishlist[$productId]); + $session->set('wishlist', $wishlist); + + return true; + } } diff --git a/component/site/redshop.php b/component/site/redshop.php index 32666de4536..1ff9875e6bd 100644 --- a/component/site/redshop.php +++ b/component/site/redshop.php @@ -34,122 +34,97 @@ // Add product in cart from db RedshopHelperUtility::databaseToCart(); -if (!empty($shopperGroupPortal)) -{ - $portal = $shopperGroupPortal->shopper_group_portal; +if (!empty($shopperGroupPortal)) { + $portal = $shopperGroupPortal->shopper_group_portal; } -if (Redshop::getConfig()->get('PORTAL_SHOP') == 1) -{ - if ($vName == 'product' && $productId > 0) - { - $checkProductPermission = RedshopHelperAccess::checkPortalProductPermission($productId); - - if (!$checkProductPermission) - { - $vName = 'login'; - $app->input->set('view', 'login'); - $app->input->set('layout', 'portal'); - $app->enqueuemessage(JText::_('COM_REDSHOP_AUTHENTICATIONFAIL')); - } - } - elseif ($vName == 'category' && $categoryId > 0) - { - $checkCategoryPermission = RedshopHelperAccess::checkPortalCategoryPermission($categoryId); - - if (!$checkCategoryPermission) - { - $vName = 'login'; - $app->input->set('view', 'login'); - $app->input->set('layout', 'portal'); - $app->enqueuemessage(JText::_('COM_REDSHOP_AUTHENTICATIONFAIL')); - } - } -} -else -{ - if ($vName == 'product' && $productId > 0 && $portal == 1) - { - $checkProductPermission = RedshopHelperAccess::checkPortalProductPermission($productId); - - if (!$checkProductPermission) - { - $vName = 'login'; - $app->input->set('view', 'login'); - $app->input->set('layout', 'portal'); - $app->enqueuemessage(JText::_('COM_REDSHOP_AUTHENTICATIONFAIL')); - } - } - - if ($vName == 'category' && $categoryId > 0 && $portal == 1) - { - $checkCategoryPermission = RedshopHelperAccess::checkPortalCategoryPermission($categoryId); - - if (!$checkCategoryPermission) - { - $vName = 'login'; - $app->input->set('view', 'login'); - $app->input->set('layout', 'portal'); - $app->enqueuemessage(JText::_('COM_REDSHOP_AUTHENTICATIONFAIL')); - } - } - - if ($vName == 'redshop') - { - $vName = 'category'; - $app->input->set('view', 'category'); - } - else - { - $app->input->set('view', $vName); - } +if (Redshop::getConfig()->get('PORTAL_SHOP') == 1) { + if ($vName == 'product' && $productId > 0) { + $checkProductPermission = RedshopHelperAccess::checkPortalProductPermission($productId); + + if (!$checkProductPermission) { + $vName = 'login'; + $app->input->set('view', 'login'); + $app->input->set('layout', 'portal'); + $app->enqueuemessage(JText::_('COM_REDSHOP_AUTHENTICATIONFAIL')); + } + } elseif ($vName == 'category' && $categoryId > 0) { + $checkCategoryPermission = RedshopHelperAccess::checkPortalCategoryPermission($categoryId); + + if (!$checkCategoryPermission) { + $vName = 'login'; + $app->input->set('view', 'login'); + $app->input->set('layout', 'portal'); + $app->enqueuemessage(JText::_('COM_REDSHOP_AUTHENTICATIONFAIL')); + } + } +} else { + if ($vName == 'product' && $productId > 0 && $portal == 1) { + $checkProductPermission = RedshopHelperAccess::checkPortalProductPermission($productId); + + if (!$checkProductPermission) { + $vName = 'login'; + $app->input->set('view', 'login'); + $app->input->set('layout', 'portal'); + $app->enqueuemessage(JText::_('COM_REDSHOP_AUTHENTICATIONFAIL')); + } + } + + if ($vName == 'category' && $categoryId > 0 && $portal == 1) { + $checkCategoryPermission = RedshopHelperAccess::checkPortalCategoryPermission($categoryId); + + if (!$checkCategoryPermission) { + $vName = 'login'; + $app->input->set('view', 'login'); + $app->input->set('layout', 'portal'); + $app->enqueuemessage(JText::_('COM_REDSHOP_AUTHENTICATIONFAIL')); + } + } + + if ($vName == 'redshop') { + $vName = 'category'; + $app->input->set('view', 'category'); + } else { + $app->input->set('view', $vName); + } } // Don't create div for AJAX call and GA code. -if ('component' !== $app->input->getCmd('tmpl') && 'html' == $format) -{ - // Container CSS class definition - if (version_compare(JVERSION, '3.0', '<')) - { - $redSHOPCSSContainerClass = ' isJ25'; - } - else - { - $redSHOPCSSContainerClass = ' isJ30'; - } - - echo '
    '; +if ('component' !== $app->input->getCmd('tmpl') && 'html' == $format) { + // Container CSS class definition + if (version_compare(JVERSION, '3.0', '<')) { + $redSHOPCSSContainerClass = ' isJ25'; + } else { + $redSHOPCSSContainerClass = ' isJ30'; + } + + echo '
    '; } // Check for array format. $filter = JFilterInput::getInstance(); $task = $app->input->getCmd('task', 'display'); -if (is_array($task)) -{ - $command = $filter->clean(array_pop(array_keys($task)), 'cmd'); -} -else -{ - $command = $filter->clean($task, 'cmd'); +if (is_array($task)) { + $command = $filter->clean(array_pop(array_keys($task)), 'cmd'); +} else { + $command = $filter->clean($task, 'cmd'); } // Check for a not controller.task command. -if (strpos($command, '.') === false) -{ - $app->input->set('task', $vName . '.' . $command); +if (strpos($command, '.') === false) { + $app->input->set('task', $vName . '.' . $command); } // Perform the Request task $controller = JControllerLegacy::getInstance('Redshop'); -if (version_compare(JVERSION, '3.0', '<')) -{ - $task = $app->input->getCmd('task'); -} -else -{ - $task = $app->input->get('task', ''); +if (version_compare(JVERSION, '3.0', '<')) { + $task = $app->input->getCmd('task'); +} else { + $task = $app->input->get('task', ''); } $controller->execute($task); diff --git a/component/site/router.php b/component/site/router.php index 4870134e01b..6dd1323be92 100644 --- a/component/site/router.php +++ b/component/site/router.php @@ -20,962 +20,806 @@ */ class RedshopRouter extends JComponentRouterBase { - /** - * Build the route for the com_reditem component - * - * @param array $query An array of URL arguments - * - * @return array The URL arguments to use to assemble the subsequent URL. - * @throws Exception - */ - public function build(&$query) - { - $segments = array(); - $db = JFactory::getDbo(); - $app = JFactory::getApplication(); - $menu = $app->getMenu(); - - $menuItem = empty($query['Itemid']) ? $menu->getActive() : $menu->getItem($query['Itemid']); - - $itemId = is_object($menuItem) ? $menuItem->id : 101; - - $view = null; - - if (isset($query['view'])) - { - $view = $query['view']; - unset($query['view']); - } - - $pid = null; - - if (isset($query['pid'])) - { - $pid = $query['pid']; - unset($query['pid']); - } - - $cid = null; - - if (isset($query['cid'])) - { - $cid = $query['cid']; - unset($query['cid']); - } - - $manufacturerId = null; - - if (isset($query['manufacturer_id'])) - { - $manufacturerId = $query['manufacturer_id']; - unset($query['manufacturer_id']); - } - - $categoryId = null; - - if (isset($query['category_id'])) - { - $categoryId = $query['category_id']; - unset($query['category_id']); - } - - $categoryTemplate = null; - - if (isset($query['category_template'])) - { - $categoryTemplate = $query['category_template']; - unset($query['category_template']); - } - - $gid = null; - - if (isset($query['gid'])) - { - $gid = $query['gid']; - unset($query['gid']); - } - - $layout = null; - - if (isset($query['layout'])) - { - $layout = $query['layout']; - unset($query['layout']); - } - - $mid = null; - - if (isset($query['mid'])) - { - $mid = $query['mid']; - unset($query['mid']); - } - - $task = null; - - if (isset($query['task'])) - { - $task = $query['task']; - unset($query['task']); - } - - $inforId = null; - - if (isset($query['infoid'])) - { - $inforId = $query['infoid']; - unset($query['infoid']); - } - - $oid = null; - - if (isset($query['oid'])) - { - $oid = $query['oid']; - unset($query['oid']); - } - - $orderId = null; - - if (isset($query['order_id'])) - { - $orderId = $query['order_id']; - unset($query['order_id']); - } - - $quotationId = null; - - if (isset($query['quoid'])) - { - $quotationId = $query['quoid']; - unset($query['quoid']); - } - - // Tag id - $tagId = null; - - if (isset($query['tagid'])) - { - $tagId = $query['tagid']; - unset($query['tagid']); - } - - $edit = null; - - if (isset($query['edit'])) - { - $edit = $query['edit']; - unset($query['edit']); - } - - // Remove flag - $remove = null; - - if (isset($query['remove'])) - { - $remove = $query['remove']; - unset($query['remove']); - } - - $wishlistId = null; - - if (isset($query['wishlist_id'])) - { - $wishlistId = $query['wishlist_id']; - unset($query['wishlist_id']); - } - - if (is_object($menuItem)) - { - $myParams = new Registry($menuItem->params); - } - else - { - $menuItem = new stdClass; - $menuItem->title = ''; - $myParams = new Registry; - } - - // Special char for replace - $specialChars = array('.', ' '); - - switch ($view) - { - case 'wishlist': - $segments[] = 'wishlist'; - - if (!empty($task)) - { - $segments[] = $task; - - if (in_array($task, array('delwishlist', 'mysessdelwishlist'))) - { - $segments[] = $wishlistId; - } - } - elseif (!empty($layout)) - { - $segments[] = $layout; - } - - break; - - case 'cart': - $segments[] = 'cart'; - - break; - - case 'search': - $segments[] = 'search'; - - if (!empty($layout)) - { - $segments[] = $layout; - } - - if (!empty($categoryId)) - { - $segments[] = $categoryId; - } - - break; - - case 'password': - $segments[] = 'password'; - break; - - case 'registration': - $segments[] = 'registration'; - break; - - case 'login': - $segments[] = 'login'; - break; - - case 'checkout': - $segments[] = 'checkout'; - break; - - case 'account_billto': - $segments[] = 'account_billto'; - break; - - case 'giftcard': - $segments[] = 'giftcard'; - - if (isset($gid)) - { - $segments[] = $gid; - - $entity = RedshopEntityGiftcard::getInstance($gid); - - if ($entity->isValid()) - { - $segments[] = RedshopHelperUtility::convertToNonSymbol($entity->get('giftcard_name')); - } - } - - break; - - case 'account_shipto': - $segments[] = 'account_shipto'; - - if ($task == 'addshipping' || $task == 'remove') - { - $segments[] = $task; - - if ($inforId > 0) - { - $segments[] = $inforId; - } - } - - break; - - case 'orders': - $segments[] = 'orders'; - - break; - - case 'order_detail': - $segments[] = 'order_detail'; - - if ($oid != '') - { - $segments[] = $oid; - } - elseif ($orderId != '') - { - $segments[] = $orderId; - } - - if ($layout != '') - { - $segments[] = $layout; - } - - if ($task == 'reorder') - { - $segments[] = $task; - } - - break; - - case 'category': - - if (!Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) - { - if ($cid > 0) - { - $segments[] = $cid; - } - - $segments[] = $itemId; - $segments[] = $manufacturerId; - } - - if ($cid) - { - $url = RedshopEntityCategory::getInstance($cid); - - if (empty($url->get('sef_url'))) - { - $categoriesReverse = RedshopHelperCategory::getCategoryListReverseArray($cid); - - if (count($categoriesReverse) > 0) - { - $categoriesReverse = array_reverse($categoriesReverse); - - foreach ($categoriesReverse as $categoryReverse) - { - if ($categoryReverse->parent_id === 0) - { - continue; - } - - $segments[] = RedshopHelperUtility::convertToNonSymbol($categoryReverse->name); - } - } - - if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) - { - $segments[] = $cid . '-' . RedshopHelperUtility::convertToNonSymbol($url->get('name')); - } - else - { - $segments[] = RedshopHelperUtility::convertToNonSymbol($url->get('name')); - } - } - else - { - if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) - { - $segments[] = $cid . '-' . RedshopHelperUtility::convertToNonSymbol($url->sef_url); - } - else - { - $segments[] = RedshopHelperUtility::convertToNonSymbol($url->sef_url); - } - } - } - elseif ($menuItem->title !== '') - { - $segments[] = RedshopHelperUtility::convertToNonSymbol($menuItem->title); - } - - if ($layout !== 'detail' && $layout !== '') - { - $segments[] = $layout; - } - - break; - - case 'product': - - if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME') && $layout != '') - { - $segments[] = $layout; - } - else - { - if ($layout != '') - { - $segments[] = $layout; - } - elseif ($pid) - { - $segments[] = $pid; - } - - $segments[] = $itemId; - } - - $segments[] = $task; - $product = \Redshop\Product\Product::getProductById($pid); - - if ($pid && $product) - { - $url = $product->sef_url; - $showCategoryInSefUrl = $product->cat_in_sefurl; - - if ($url == '') - { - // Get cid from request for consistency - $categoryId = $showCategoryInSefUrl; - - // If cid is not set than find cid - if (!$categoryId) - { - $categoryId = $product->category_id; - } - - if ($categoriesReverse = RedshopHelperCategory::getCategoryListReverseArray($categoryId)) - { - $categoriesReverse = array_reverse($categoriesReverse); - - foreach ($categoriesReverse as $cat) - { - if ($cat->parent_id == 0) - { - continue; - } - - $segments[] = RedshopHelperUtility::convertToNonSymbol($cat->name); - } - } - - $categoryData = RedshopEntityCategory::getInstance($categoryId); - - // Attach category id with name for consistency - if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) - { - $segments[] = $categoryId . '-' . RedshopHelperUtility::convertToNonSymbol($categoryData->get('name')); - } - else - { - $segments[] = RedshopHelperUtility::convertToNonSymbol($categoryData->get('name')); - } - - // Add product number if config is enabled - if (Redshop::getConfig()->get('ENABLE_SEF_PRODUCT_NUMBER')) - { - $segments[] = RedshopHelperUtility::convertToNonSymbol($product->product_number); - } - - // Config option to generate sef using name : add product id to get parse in parseroute function - if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) - { - $segments[] = 'P' . $pid . '-' . RedshopHelperUtility::convertToNonSymbol($product->product_name); - } - else - { - $segments[] = 'P-' . RedshopHelperUtility::convertToNonSymbol($product->product_name); - } - } - else - { - // Config option to generate sef using name : add product id to get parse in parseroute function - if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) - { - $segments[] = 'P' . $pid . '-' . RedshopHelperUtility::convertToNonSymbol($url); - } - else - { - $segments[] = 'P-' . RedshopHelperUtility::convertToNonSymbol($url); - } - } - } - - break; - - case 'manufacturers': - - if (!$mid) - { - $mid = $myParams->get('manufacturer'); - } - - $segments[] = 'manufacturers'; - - if ($mid) - { - $segments[] = $mid; - - $manufacturer = RedshopEntityManufacturer::getInstance($mid); - - if ($manufacturer->isValid()) - { - if (!empty($manufacturer->get('sef_url'))) - { - $segments[] = str_replace($specialChars, '-', $manufacturer->get('sef_url')); - } - else - { - $segments[] = str_replace($specialChars, '-', $manufacturer->get('name')); - } - } - } - - if (!$mid) - { - if (!empty($menuItem->title)) - { - $segments[] = str_replace($specialChars, '-', $menuItem->title); - } - else - { - $segments[] = 'manufactures'; - } - } - - if ($layout !== 'detail' && $layout !== '') - { - $segments[] = $layout; - } - - break; - - case 'account': - - $segments[] = 'account'; - - if (!empty($task)) - { - $segments[] = $task; - } - else - { - if ($layout == 'mytags') - { - $segments[] = $layout; - - if ($tagId) - { - $segments[] = $tagId; - - $tag = RedshopEntityProduct_Tag::getInstance($tagId); - $segments[] = str_replace($specialChars, '-', $tag->get('tags_name')); - - if ($tagId && isset($edit)) - { - $segments[] = 'edit'; - } - - if ($tagId && isset($remove)) - { - $segments[] = 'remove'; - } - } - } - elseif ($layout == 'mywishlist') - { - $segments[] = $layout; - - if (isset($wishlistId)) - { - $segments[] = $wishlistId; - } - - if (isset($remove) && isset($pid)) - { - $segments[] = $pid; - $segments[] = 'delete'; - } - } - elseif ($layout == 'compare') - { - $segments[] = $layout; - - if (isset($remove) && isset($pid)) - { - $segments[] = $pid; - $segments[] = 'delete'; - } - } - } - - break; - - case 'quotation': - $segments[] = 'quotation'; - - break; - - case 'quotation_detail': - $segments[] = 'quotation_detail'; - $segments[] = $quotationId; - - break; - - default: - break; - } - - return $segments; - } - - /** - * Parse the segments of a URL. - * - * @param array $segments The segments of the URL to parse. - * - * @return array The URL attributes to be used by the application. - */ - public function parse(&$segments) - { - $vars = array(); - $firstSegment = $segments[0]; - - switch ($firstSegment) - { - case 'giftcard': - $vars['view'] = 'giftcard'; - - if (isset($segments[1])) - { - $vars['gid'] = $segments[1]; - } - - break; - - case 'cart': - $vars['view'] = 'cart'; - break; - - case 'search': - $vars['view'] = 'search'; - - if (isset($segments[1])) - { - $vars['layout'] = $segments[1]; - } - - if (isset($segments[2])) - { - $vars['category_id'] = $segments[2]; - } - break; - - case 'password': - $vars['view'] = 'password'; - break; - - case 'registration': - $vars['view'] = 'registration'; - break; - - case 'checkout': - $vars['view'] = 'checkout'; - break; - - case 'login': - $vars['view'] = 'login'; - break; - - case 'account_billto': - $vars['view'] = 'account_billto'; - break; - - case 'account_shipto': - $vars['view'] = 'account_shipto'; - - if (isset($segments[1])) - { - $vars['task'] = $segments[1]; - } - - if (isset($segments[2])) - { - $vars['infoid'] = $segments[2]; - } - - break; - - case 'manufacturers': - $vars['view'] = 'manufacturers'; - - if (isset($segments[1])) - { - $vars['mid'] = $segments[1]; - $vars['layout'] = 'detail'; - } - - if (isset($segments[3])) - { - $vars['layout'] = $segments[3]; - } - - break; - - case 'orders': - $vars['view'] = 'orders'; - - break; - - case 'order_detail': - $vars['view'] = 'order_detail'; - - if (isset($segments[1])) - { - $vars['oid'] = $segments[1]; - } - - if (isset($segments[2]) && $segments[2] == 'reorder') - { - $vars['task'] = $segments[2]; - $vars['order_id'] = $segments[1]; - } - elseif (isset($segments[2])) - { - $vars['layout'] = $segments[2]; - } - - break; - - case 'wishlist': - $vars['view'] = 'wishlist'; - - if (isset($segments[1])) - { - $vars['task'] = $segments[1]; - } - - if (isset($segments[2])) - { - $vars['wishlist_id'] = $segments[2]; - } - - break; - - case 'account': - $vars['view'] = 'account'; - - if (isset($segments[1])) - { - if ($segments[1] == 'deleteAccount') - { - $vars['task'] = $segments[1]; - } - else - { - $vars['layout'] = $segments[1]; - - if ($segments[1] == 'mytags') - { - if (isset($segments[2])) - { - $vars['tagid'] = $segments[2]; - - if (isset($segments[4])) - { - if ($segments[4] == 'edit') - { - $vars['edit'] = 1; - } - else - { - $vars['remove'] = 1; - } - } - } - } - elseif ($segments[1] == 'mywishlist') - { - if (isset($segments[2])) - { - $vars['wishlist_id'] = $segments[2]; - } - - if (isset($segments[3])) - { - $vars['pid'] = $segments[3]; - } - - if (isset($segments[4])) - { - $vars['remove'] = 1; - } - } - elseif ($segments[1] == 'compare') - { - if (isset($segments[2])) - { - $vars['pid'] = $segments[2]; - } - - if (isset($segments[3])) - { - $vars['remove'] = 1; - } - } - } - } - - break; - - case 'quotation': - $vars['view'] = 'quotation'; - - break; - - case 'quotation_detail': - $vars['view'] = 'quotation_detail'; - $vars['quoid'] = $segments[1]; - - break; - - default: - $last = count($segments) - 1; - $secondLast = $last - 1; - $main = explode(':', $segments[$last]); - - if (isset($segments[$last])) - { - if ($main[0][0] != 'P' && $segments[0] != 'compare') - { - if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) - { - $vars['view'] = 'category'; - - if (isset($segments[$last])) - { - // Fetch category id - $categories = explode(':', $segments[$last]); - $categoryId = $categories[0]; - $vars['cid'] = $categoryId; - - if (isset($categories[2])) - { - $manufacturerId = $categories[2]; - $vars['manufacturer_id'] = $manufacturerId; - } - - $menu = JFactory::getApplication()->getMenu(); - $item = $menu->getActive(); - $vars['Itemid'] = $item->id; - } - } - else - { - $vars['view'] = 'category'; - - $menu = JFactory::getApplication()->getMenu(); - $item = $menu->getActive(); - - $vars['Itemid'] = ''; - $itemId = ''; - - if (!empty($item)) - { - $vars['Itemid'] = $item->id; - $itemId = $item->id; - } - - if (isset($segments[0]) && $segments[0] != $itemId) - { - $vars['cid'] = $segments[0]; - } - - if (isset($segments[2]) && !isset($vars['cid'])) - { - $vars['manufacturer_id'] = $segments[2]; - } - } - } - else - { - if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) - { - $vars['view'] = 'product'; - - if (isset($segments[0])) - { - $categories = explode(':', $segments[0]); - $categoryId = $categories[0]; - $vars['cid'] = $categoryId; - } - - if (isset($segments[0]) && $segments[0] == 'compare') - { - $vars['layout'] = $segments[0]; - $vars['task'] = $segments[1]; - } - - if (isset($segments[$last])) - { - $products = explode(':', $segments[$last]); - $productId = substr($products[0], 1); - $vars['pid'] = $productId; - } - - $menu = JFactory::getApplication()->getMenu(); - $item = $menu->getActive(); - $vars['Itemid'] = $item->id; - } - else - { - $vars['view'] = 'product'; - - if (isset($segments[0]) && $segments[0] == 'compare') - { - $vars['layout'] = $segments[0]; - $vars['task'] = isset($segments[2]) ? $segments[2] : ''; - } - else - { - $vars['pid'] = $segments[0]; - } - - if (isset($segments[1])) - { - $vars['Itemid'] = $segments[1]; - } - - if (isset($segments[$secondLast])) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('id')) - ->from($db->qn('#__redshop_category')) - ->where($db->qn('name') . ' = ' . $db->q($segments[$secondLast])); - - $vars['cid'] = $db->setQuery($query)->loadResult(); - } - } - } - } - - break; - } - - return $vars; - } + /** + * Build the route for the com_reditem component + * + * @param array $query An array of URL arguments + * + * @return array The URL arguments to use to assemble the subsequent URL. + * @throws Exception + */ + public function build(&$query) + { + $segments = array(); + $db = JFactory::getDbo(); + $app = JFactory::getApplication(); + $menu = $app->getMenu(); + + $menuItem = empty($query['Itemid']) ? $menu->getActive() : $menu->getItem($query['Itemid']); + + $itemId = is_object($menuItem) ? $menuItem->id : 101; + + $view = null; + + if (isset($query['view'])) { + $view = $query['view']; + unset($query['view']); + } + + $pid = null; + + if (isset($query['pid'])) { + $pid = $query['pid']; + unset($query['pid']); + } + + $cid = null; + + if (isset($query['cid'])) { + $cid = $query['cid']; + unset($query['cid']); + } + + $manufacturerId = null; + + if (isset($query['manufacturer_id'])) { + $manufacturerId = $query['manufacturer_id']; + unset($query['manufacturer_id']); + } + + $categoryId = null; + + if (isset($query['category_id'])) { + $categoryId = $query['category_id']; + unset($query['category_id']); + } + + $categoryTemplate = null; + + if (isset($query['category_template'])) { + $categoryTemplate = $query['category_template']; + unset($query['category_template']); + } + + $gid = null; + + if (isset($query['gid'])) { + $gid = $query['gid']; + unset($query['gid']); + } + + $layout = null; + + if (isset($query['layout'])) { + $layout = $query['layout']; + unset($query['layout']); + } + + $mid = null; + + if (isset($query['mid'])) { + $mid = $query['mid']; + unset($query['mid']); + } + + $task = null; + + if (isset($query['task'])) { + $task = $query['task']; + unset($query['task']); + } + + $inforId = null; + + if (isset($query['infoid'])) { + $inforId = $query['infoid']; + unset($query['infoid']); + } + + $oid = null; + + if (isset($query['oid'])) { + $oid = $query['oid']; + unset($query['oid']); + } + + $orderId = null; + + if (isset($query['order_id'])) { + $orderId = $query['order_id']; + unset($query['order_id']); + } + + $quotationId = null; + + if (isset($query['quoid'])) { + $quotationId = $query['quoid']; + unset($query['quoid']); + } + + // Tag id + $tagId = null; + + if (isset($query['tagid'])) { + $tagId = $query['tagid']; + unset($query['tagid']); + } + + $edit = null; + + if (isset($query['edit'])) { + $edit = $query['edit']; + unset($query['edit']); + } + + // Remove flag + $remove = null; + + if (isset($query['remove'])) { + $remove = $query['remove']; + unset($query['remove']); + } + + $wishlistId = null; + + if (isset($query['wishlist_id'])) { + $wishlistId = $query['wishlist_id']; + unset($query['wishlist_id']); + } + + if (is_object($menuItem)) { + $myParams = new Registry($menuItem->params); + } else { + $menuItem = new stdClass; + $menuItem->title = ''; + $myParams = new Registry; + } + + // Special char for replace + $specialChars = array('.', ' '); + + switch ($view) { + case 'wishlist': + $segments[] = 'wishlist'; + + if (!empty($task)) { + $segments[] = $task; + + if (in_array($task, array('delwishlist', 'mysessdelwishlist'))) { + $segments[] = $wishlistId; + } + } elseif (!empty($layout)) { + $segments[] = $layout; + } + + break; + + case 'cart': + $segments[] = 'cart'; + + break; + + case 'search': + $segments[] = 'search'; + + if (!empty($layout)) { + $segments[] = $layout; + } + + if (!empty($categoryId)) { + $segments[] = $categoryId; + } + + break; + + case 'password': + $segments[] = 'password'; + break; + + case 'registration': + $segments[] = 'registration'; + break; + + case 'login': + $segments[] = 'login'; + break; + + case 'checkout': + $segments[] = 'checkout'; + break; + + case 'account_billto': + $segments[] = 'account_billto'; + break; + + case 'giftcard': + $segments[] = 'giftcard'; + + if (isset($gid)) { + $segments[] = $gid; + + $entity = RedshopEntityGiftcard::getInstance($gid); + + if ($entity->isValid()) { + $segments[] = RedshopHelperUtility::convertToNonSymbol($entity->get('giftcard_name')); + } + } + + break; + + case 'account_shipto': + $segments[] = 'account_shipto'; + + if ($task == 'addshipping' || $task == 'remove') { + $segments[] = $task; + + if ($inforId > 0) { + $segments[] = $inforId; + } + } + + break; + + case 'orders': + $segments[] = 'orders'; + + break; + + case 'order_detail': + $segments[] = 'order_detail'; + + if ($oid != '') { + $segments[] = $oid; + } elseif ($orderId != '') { + $segments[] = $orderId; + } + + if ($layout != '') { + $segments[] = $layout; + } + + if ($task == 'reorder') { + $segments[] = $task; + } + + break; + + case 'category': + + if (!Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) { + if ($cid > 0) { + $segments[] = $cid; + } + + $segments[] = $itemId; + $segments[] = $manufacturerId; + } + + if ($cid) { + $url = RedshopEntityCategory::getInstance($cid); + + if (empty($url->get('sef_url'))) { + $categoriesReverse = RedshopHelperCategory::getCategoryListReverseArray($cid); + + if (count($categoriesReverse) > 0) { + $categoriesReverse = array_reverse($categoriesReverse); + + foreach ($categoriesReverse as $categoryReverse) { + if ($categoryReverse->parent_id === 0) { + continue; + } + + $segments[] = RedshopHelperUtility::convertToNonSymbol($categoryReverse->name); + } + } + + if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) { + $segments[] = $cid . '-' . RedshopHelperUtility::convertToNonSymbol($url->get('name')); + } else { + $segments[] = RedshopHelperUtility::convertToNonSymbol($url->get('name')); + } + } else { + if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) { + $segments[] = $cid . '-' . RedshopHelperUtility::convertToNonSymbol($url->sef_url); + } else { + $segments[] = RedshopHelperUtility::convertToNonSymbol($url->sef_url); + } + } + } elseif ($menuItem->title !== '') { + $segments[] = RedshopHelperUtility::convertToNonSymbol($menuItem->title); + } + + if ($layout !== 'detail' && $layout !== '') { + $segments[] = $layout; + } + + break; + + case 'product': + + if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME') && $layout != '') { + $segments[] = $layout; + } else { + if ($layout != '') { + $segments[] = $layout; + } elseif ($pid) { + $segments[] = $pid; + } + + $segments[] = $itemId; + } + + $segments[] = $task; + $product = \Redshop\Product\Product::getProductById($pid); + + if ($pid && $product) { + $url = $product->sef_url; + $showCategoryInSefUrl = $product->cat_in_sefurl; + + if ($url == '') { + // Get cid from request for consistency + $categoryId = $showCategoryInSefUrl; + + // If cid is not set than find cid + if (!$categoryId) { + $categoryId = $product->category_id; + } + + if ($categoriesReverse = RedshopHelperCategory::getCategoryListReverseArray($categoryId)) { + $categoriesReverse = array_reverse($categoriesReverse); + + foreach ($categoriesReverse as $cat) { + if ($cat->parent_id == 0) { + continue; + } + + $segments[] = RedshopHelperUtility::convertToNonSymbol($cat->name); + } + } + + $categoryData = RedshopEntityCategory::getInstance($categoryId); + + // Attach category id with name for consistency + if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) { + $segments[] = $categoryId . '-' . RedshopHelperUtility::convertToNonSymbol( + $categoryData->get('name') + ); + } else { + $segments[] = RedshopHelperUtility::convertToNonSymbol($categoryData->get('name')); + } + + // Add product number if config is enabled + if (Redshop::getConfig()->get('ENABLE_SEF_PRODUCT_NUMBER')) { + $segments[] = RedshopHelperUtility::convertToNonSymbol($product->product_number); + } + + // Config option to generate sef using name : add product id to get parse in parseroute function + if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) { + $segments[] = 'P' . $pid . '-' . RedshopHelperUtility::convertToNonSymbol( + $product->product_name + ); + } else { + $segments[] = 'P-' . RedshopHelperUtility::convertToNonSymbol($product->product_name); + } + } else { + // Config option to generate sef using name : add product id to get parse in parseroute function + if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) { + $segments[] = 'P' . $pid . '-' . RedshopHelperUtility::convertToNonSymbol($url); + } else { + $segments[] = 'P-' . RedshopHelperUtility::convertToNonSymbol($url); + } + } + } + + break; + + case 'manufacturers': + + if (!$mid) { + $mid = $myParams->get('manufacturer'); + } + + $segments[] = 'manufacturers'; + + if ($mid) { + $segments[] = $mid; + + $manufacturer = RedshopEntityManufacturer::getInstance($mid); + + if ($manufacturer->isValid()) { + if (!empty($manufacturer->get('sef_url'))) { + $segments[] = str_replace($specialChars, '-', $manufacturer->get('sef_url')); + } else { + $segments[] = str_replace($specialChars, '-', $manufacturer->get('name')); + } + } + } + + if (!$mid) { + if (!empty($menuItem->title)) { + $segments[] = str_replace($specialChars, '-', $menuItem->title); + } else { + $segments[] = 'manufactures'; + } + } + + if ($layout !== 'detail' && $layout !== '') { + $segments[] = $layout; + } + + break; + + case 'account': + + $segments[] = 'account'; + + if (!empty($task)) { + $segments[] = $task; + } else { + if ($layout == 'mytags') { + $segments[] = $layout; + + if ($tagId) { + $segments[] = $tagId; + + $tag = RedshopEntityProduct_Tag::getInstance($tagId); + $segments[] = str_replace($specialChars, '-', $tag->get('tags_name')); + + if ($tagId && isset($edit)) { + $segments[] = 'edit'; + } + + if ($tagId && isset($remove)) { + $segments[] = 'remove'; + } + } + } elseif ($layout == 'mywishlist') { + $segments[] = $layout; + + if (isset($wishlistId)) { + $segments[] = $wishlistId; + } + + if (isset($remove) && isset($pid)) { + $segments[] = $pid; + $segments[] = 'delete'; + } + } elseif ($layout == 'compare') { + $segments[] = $layout; + + if (isset($remove) && isset($pid)) { + $segments[] = $pid; + $segments[] = 'delete'; + } + } + } + + break; + + case 'quotation': + $segments[] = 'quotation'; + + break; + + case 'quotation_detail': + $segments[] = 'quotation_detail'; + $segments[] = $quotationId; + + break; + + default: + break; + } + + return $segments; + } + + /** + * Parse the segments of a URL. + * + * @param array $segments The segments of the URL to parse. + * + * @return array The URL attributes to be used by the application. + */ + public function parse(&$segments) + { + $vars = array(); + $firstSegment = $segments[0]; + + switch ($firstSegment) { + case 'giftcard': + $vars['view'] = 'giftcard'; + + if (isset($segments[1])) { + $vars['gid'] = $segments[1]; + } + + break; + + case 'cart': + $vars['view'] = 'cart'; + break; + + case 'search': + $vars['view'] = 'search'; + + if (isset($segments[1])) { + $vars['layout'] = $segments[1]; + } + + if (isset($segments[2])) { + $vars['category_id'] = $segments[2]; + } + break; + + case 'password': + $vars['view'] = 'password'; + break; + + case 'registration': + $vars['view'] = 'registration'; + break; + + case 'checkout': + $vars['view'] = 'checkout'; + break; + + case 'login': + $vars['view'] = 'login'; + break; + + case 'account_billto': + $vars['view'] = 'account_billto'; + break; + + case 'account_shipto': + $vars['view'] = 'account_shipto'; + + if (isset($segments[1])) { + $vars['task'] = $segments[1]; + } + + if (isset($segments[2])) { + $vars['infoid'] = $segments[2]; + } + + break; + + case 'manufacturers': + $vars['view'] = 'manufacturers'; + + if (isset($segments[1])) { + $vars['mid'] = $segments[1]; + $vars['layout'] = 'detail'; + } + + if (isset($segments[3])) { + $vars['layout'] = $segments[3]; + } + + break; + + case 'orders': + $vars['view'] = 'orders'; + + break; + + case 'order_detail': + $vars['view'] = 'order_detail'; + + if (isset($segments[1])) { + $vars['oid'] = $segments[1]; + } + + if (isset($segments[2]) && $segments[2] == 'reorder') { + $vars['task'] = $segments[2]; + $vars['order_id'] = $segments[1]; + } elseif (isset($segments[2])) { + $vars['layout'] = $segments[2]; + } + + break; + + case 'wishlist': + $vars['view'] = 'wishlist'; + + if (isset($segments[1])) { + $vars['task'] = $segments[1]; + } + + if (isset($segments[2])) { + $vars['wishlist_id'] = $segments[2]; + } + + break; + + case 'account': + $vars['view'] = 'account'; + + if (isset($segments[1])) { + if ($segments[1] == 'deleteAccount') { + $vars['task'] = $segments[1]; + } else { + $vars['layout'] = $segments[1]; + + if ($segments[1] == 'mytags') { + if (isset($segments[2])) { + $vars['tagid'] = $segments[2]; + + if (isset($segments[4])) { + if ($segments[4] == 'edit') { + $vars['edit'] = 1; + } else { + $vars['remove'] = 1; + } + } + } + } elseif ($segments[1] == 'mywishlist') { + if (isset($segments[2])) { + $vars['wishlist_id'] = $segments[2]; + } + + if (isset($segments[3])) { + $vars['pid'] = $segments[3]; + } + + if (isset($segments[4])) { + $vars['remove'] = 1; + } + } elseif ($segments[1] == 'compare') { + if (isset($segments[2])) { + $vars['pid'] = $segments[2]; + } + + if (isset($segments[3])) { + $vars['remove'] = 1; + } + } + } + } + + break; + + case 'quotation': + $vars['view'] = 'quotation'; + + break; + + case 'quotation_detail': + $vars['view'] = 'quotation_detail'; + $vars['quoid'] = $segments[1]; + + break; + + default: + $last = count($segments) - 1; + $secondLast = $last - 1; + $main = explode(':', $segments[$last]); + + if (isset($segments[$last])) { + if ($main[0][0] != 'P' && $segments[0] != 'compare') { + if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) { + $vars['view'] = 'category'; + + if (isset($segments[$last])) { + // Fetch category id + $categories = explode(':', $segments[$last]); + $categoryId = $categories[0]; + $vars['cid'] = $categoryId; + + if (isset($categories[2])) { + $manufacturerId = $categories[2]; + $vars['manufacturer_id'] = $manufacturerId; + } + + $menu = JFactory::getApplication()->getMenu(); + $item = $menu->getActive(); + $vars['Itemid'] = $item->id; + } + } else { + $vars['view'] = 'category'; + + $menu = JFactory::getApplication()->getMenu(); + $item = $menu->getActive(); + + $vars['Itemid'] = ''; + $itemId = ''; + + if (!empty($item)) { + $vars['Itemid'] = $item->id; + $itemId = $item->id; + } + + if (isset($segments[0]) && $segments[0] != $itemId) { + $vars['cid'] = $segments[0]; + } + + if (isset($segments[2]) && !isset($vars['cid'])) { + $vars['manufacturer_id'] = $segments[2]; + } + } + } else { + if (Redshop::getConfig()->get('ENABLE_SEF_NUMBER_NAME')) { + $vars['view'] = 'product'; + + if (isset($segments[0])) { + $categories = explode(':', $segments[0]); + $categoryId = $categories[0]; + $vars['cid'] = $categoryId; + } + + if (isset($segments[0]) && $segments[0] == 'compare') { + $vars['layout'] = $segments[0]; + $vars['task'] = $segments[1]; + } + + if (isset($segments[$last])) { + $products = explode(':', $segments[$last]); + $productId = substr($products[0], 1); + $vars['pid'] = $productId; + } + + $menu = JFactory::getApplication()->getMenu(); + $item = $menu->getActive(); + $vars['Itemid'] = $item->id; + } else { + $vars['view'] = 'product'; + + if (isset($segments[0]) && $segments[0] == 'compare') { + $vars['layout'] = $segments[0]; + $vars['task'] = isset($segments[2]) ? $segments[2] : ''; + } else { + $vars['pid'] = $segments[0]; + } + + if (isset($segments[1])) { + $vars['Itemid'] = $segments[1]; + } + + if (isset($segments[$secondLast])) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('id')) + ->from($db->qn('#__redshop_category')) + ->where($db->qn('name') . ' = ' . $db->q($segments[$secondLast])); + + $vars['cid'] = $db->setQuery($query)->loadResult(); + } + } + } + } + + break; + } + + return $vars; + } } /** * Build URL routes for redSHOP * - * @param array $query Request variables + * @param array $query Request variables * * @return array */ function redshopBuildRoute(&$query) { - $router = new RedshopRouter; + $router = new RedshopRouter; - return $router->build($query); + return $router->build($query); } /** * Parse redSHOP sef url * - * @param array $segments Sef Url segments + * @param array $segments Sef Url segments * * @return array */ function redshopParseRoute($segments) { - $router = new RedshopRouter; + $router = new RedshopRouter; - return $router->parse($segments); + return $router->parse($segments); } diff --git a/component/site/views/account/tmpl/cards.xml b/component/site/views/account/tmpl/cards.xml index 902d1060563..0b3c22f434c 100644 --- a/component/site/views/account/tmpl/cards.xml +++ b/component/site/views/account/tmpl/cards.xml @@ -1,8 +1,8 @@ - - - - - + + + + + diff --git a/component/site/views/account/tmpl/default.xml b/component/site/views/account/tmpl/default.xml index cb1928c4023..315567ec5c7 100644 --- a/component/site/views/account/tmpl/default.xml +++ b/component/site/views/account/tmpl/default.xml @@ -12,7 +12,7 @@ disable="separator" label="COM_REDSHOP_LOGOUT_REDIRECTION_PAGE" description="COM_REDSHOP_PARAMLOGOUTREDIRECTURL" - /> + />
    diff --git a/component/site/views/account/tmpl/mytags.html.twig b/component/site/views/account/tmpl/mytags.html.twig index 1dda1ef04da..ecca51ae46d 100644 --- a/component/site/views/account/tmpl/mytags.html.twig +++ b/component/site/views/account/tmpl/mytags.html.twig @@ -1,173 +1,173 @@ {% if (params.get('show_page_heading') == 1) %} -

    - {{ pageTitle }} -

    +

    + {{ pageTitle }} +

    {% endif %} {% if user.id != 0 %} - {% if tagId != 0 %} - {% if edit != 0 %} - {% set link = jroute('index.php?option=com_redshop&view=account&Itemid=' ~ itemId) %} -
     
    -
    - - - - - - -
    {{ jtext('COM_REDSHOP_TAG_NAME') }} - - - - - -
    -
    -
     
    - - {% else %} - {% set myTags = model.getMyDetail() %} - {% set linkEdit = jroute('index.php?option=com_redshop&view=account&layout=mytags&edit=1&tagid=' ~ tagid ~ '&Itemid=' ~ itemId) %} - {% set linkRemove = jroute('index.php?option=com_redshop&view=account&layout=mytags&remove=1&tagid=' ~ tagid ~ '&Itemid=' ~ itemId) %} - + {% if tagId != 0 %} + {% if edit != 0 %} + {% set link = jroute('index.php?option=com_redshop&view=account&Itemid=' ~ itemId) %} +
     
    +
    + + + + + + +
    {{ jtext('COM_REDSHOP_TAG_NAME') }} + + + + + +
    +
    +
     
    + + {% else %} + {% set myTags = model.getMyDetail() %} + {% set linkEdit = jroute('index.php?option=com_redshop&view=account&layout=mytags&edit=1&tagid=' ~ tagid ~ '&Itemid=' ~ itemId) %} + {% set linkRemove = jroute('index.php?option=com_redshop&view=account&layout=mytags&remove=1&tagid=' ~ tagid ~ '&Itemid=' ~ itemId) %} + - - - + +
    + + + - -
    {{ jtext('COM_REDSHOP_EDIT_TAG') }} | - {{ jtext('COM_REDSHOP_REMOVE_TAG') }} -
    -
     
    - - - + +
    - {% set i = 0 %} - {% if myTags|length > 0 %} - {% for row in myTags %} - {% set dataAdd = '
    ' %} - {% set thumbImage = "" %} - {% set pname = row.product_name %} - {% set link = jroute('index.php?option=com_redshop&view=product&pid=' ~ row.product_id ~ '&Itemid=' ~ itemid) %} - {% if row.product_full_image is defined %} - {% set thumbUrl = redSHOPCall('RedshopHelperMedia', 'getImagePath', [ - row.product_full_image, - '', - 'thumb', - 'product', - 'THUMB_WIDTH'|redconfig, - 'THUMB_HEIGHT'|redconfig, - 'USE_IMAGE_SIZE_SWAPPING'|redconfig - ]) %} - {% set thumbImage = ' + style="text-decoration: none;">{{ jtext('COM_REDSHOP_EDIT_TAG') }} | + {{ jtext('COM_REDSHOP_REMOVE_TAG') }} +
    +
     
    + + + - -
    + {% set i = 0 %} + {% if myTags|length > 0 %} + {% for row in myTags %} + {% set dataAdd = '
    ' %} + {% set thumbImage = "" %} + {% set pname = row.product_name %} + {% set link = jroute('index.php?option=com_redshop&view=product&pid=' ~ row.product_id ~ '&Itemid=' ~ itemid) %} + {% if row.product_full_image is defined %} + {% set thumbUrl = redSHOPCall('RedshopHelperMedia', 'getImagePath', [ + row.product_full_image, + '', + 'thumb', + 'product', + 'THUMB_WIDTH'|redconfig, + 'THUMB_HEIGHT'|redconfig, + 'USE_IMAGE_SIZE_SWAPPING'|redconfig + ]) %} + {% set thumbImage = '
    ' %} - {% set dataAdd = dataAdd ~ thumbImage %} - {% endif %} + {% set dataAdd = dataAdd ~ thumbImage %} + {% endif %} - {% set pname = "" %} - {% set dataAdd = dataAdd ~ pname %} - {% set priceAdd = '' ~ redSHOPCall('RedshopHelperProductPrice', 'formattedPrice', [row.product_price]) ~ '' %} - {% set taxAmount = redSHOPCall('RedshopHelperProduct', 'getProductTax', [row.product_id]) %} + {% set pname = "" %} + {% set dataAdd = dataAdd ~ pname %} + {% set priceAdd = '' ~ redSHOPCall('RedshopHelperProductPrice', 'formattedPrice', [row.product_price]) ~ '' %} + {% set taxAmount = redSHOPCall('RedshopHelperProduct', 'getProductTax', [row.product_id]) %} - {% if taxAmount == 0 %} - {% set dataAdd = dataAdd ~ '
    ' ~ priceAdd ~ '
    ' %} - {% else %} - {% set dataAdd = dataAdd ~ '
    ' ~ redSHOPCall('RedshopHelperProductPrice', 'formattedPrice', [taxAmount]) ~ '
    ' %} - {% endif %} + {% if taxAmount == 0 %} + {% set dataAdd = dataAdd ~ '
    ' ~ priceAdd ~ '
    ' %} + {% else %} + {% set dataAdd = dataAdd ~ '
    ' ~ redSHOPCall('RedshopHelperProductPrice', 'formattedPrice', [taxAmount]) ~ '
    ' %} + {% endif %} - {% if taxAmount == 0 %} - {% set productPrice = row.product_price %} - {% else %} - {% set productPrice = taxAmount %} - {% endif %} + {% if taxAmount == 0 %} + {% set productPrice = row.product_price %} + {% else %} + {% set productPrice = taxAmount %} + {% endif %} - {% set dataAdd = dataAdd ~ redSHOPCall('RedshopLayoutHelper', 'render', [ - 'tags.addtocart.addtocartscroll', - { - 'i': i, - 'row': row, - 'productPrice': productPrice - }, - '', - { - 'component': 'com_redshop', - 'layoutType': 'Twig', - 'layoutOf': 'library' - } - ]) %} - {% set i = i + 1 %} - {% set dataAdd = dataAdd ~ '
    ' %} - {{ dataAdd }} - {% endfor %} - {% else %} -
    {{ jtext('COM_REDSHOP_NO_PRODUCTS_IN_TAGS') }}
    - {% endif %} -
    -
     
    - - - - - - - - -
    - - - {{ pagination.getPagesLinks() }} -

    -
    - {{ pagination.getPagesCounter() }} -
    -
     
    - {% endif %} - {% else %} - {% set myTags = model.getMyDetail() %} -
    - {{ jtext('COM_REDSHOP_AVAILABLE_TAGS') }} - - - + +
    - {% if myTags|length > 0 %} - {% for myTag in myTags %} - + {% set dataAdd = dataAdd ~ redSHOPCall('RedshopLayoutHelper', 'render', [ + 'tags.addtocart.addtocartscroll', + { + 'i': i, + 'row': row, + 'productPrice': productPrice + }, + '', + { + 'component': 'com_redshop', + 'layoutType': 'Twig', + 'layoutOf': 'library' + } + ]) %} + {% set i = i + 1 %} + {% set dataAdd = dataAdd ~ '' %} + {{ dataAdd }} + {% endfor %} + {% else %} +
    {{ jtext('COM_REDSHOP_NO_PRODUCTS_IN_TAGS') }}
    + {% endif %} +
    +
     
    + + + + + + + + +
    + + + {{ pagination.getPagesLinks() }} +

    +
    + {{ pagination.getPagesCounter() }} +
    +
     
    + {% endif %} + {% else %} + {% set myTags = model.getMyDetail() %} +
    + {{ jtext('COM_REDSHOP_AVAILABLE_TAGS') }} + + + - -
    + {% if myTags|length > 0 %} + {% for myTag in myTags %} + {{ myTag.tags_name }} - {% endfor %} - {% endif %} -
    -
    -
     
    - - {% endif %} + {% endfor %} + {% endif %} +
    + +
     
    + + {% endif %} {% endif %} \ No newline at end of file diff --git a/component/site/views/account/tmpl/mywishlist.html.twig b/component/site/views/account/tmpl/mywishlist.html.twig index 5b6b9ceb475..01dc19d4cc1 100644 --- a/component/site/views/account/tmpl/mywishlist.html.twig +++ b/component/site/views/account/tmpl/mywishlist.html.twig @@ -1,25 +1,25 @@ {{ window }} {% if window == 1 %} - + {% endif %} {% if params.get('show_page_heading', 1) %} - {{ redSHOPCall( - 'RedshopLayoutHelper', - 'render', - [ - 'tags.common.pageheading', - { - 'params': params, - 'pageheading': jtext('COM_REDSHOP_MY_WISHLIST'), - 'class': 'mywishlist' - }, - '', - { - 'component': 'com_redshop', - 'layoutType': 'Twig', - 'layoutOf': 'library' - } - ] - ) }} + {{ redSHOPCall( + 'RedshopLayoutHelper', + 'render', + [ + 'tags.common.pageheading', + { + 'params': params, + 'pageheading': jtext('COM_REDSHOP_MY_WISHLIST'), + 'class': 'mywishlist' + }, + '', + { + 'component': 'com_redshop', + 'layoutType': 'Twig', + 'layoutOf': 'library' + } + ] + ) }} {% endif %} {{ disPlayWishlist }} diff --git a/component/site/views/account/view.html.php b/component/site/views/account/view.html.php index c1d4ccc2d1b..1a04bf62999 100644 --- a/component/site/views/account/view.html.php +++ b/component/site/views/account/view.html.php @@ -18,327 +18,327 @@ */ class RedshopViewAccount extends RedshopView { - /** - * @var JPagination - */ - public $pagination; - - /** - * @var JUser - */ - public $user; - - /** - * @var mixed - */ - public $userdata; - - /** - * @var Joomla\Registry\Registry - */ - public $params; - - /** - * @var \JModelLegacy - */ - public $model; - - /** - * Execute and display a template script. - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return mixed A string if successful, otherwise a JError object. - * @throws Exception - */ - public function display($tpl = null) - { - $this->params = $this->app->getParams('com_redshop'); - $this->user = JFactory::getUser(); - $twigParams = [ - 'url' => \JURI::base(), - 'app' => $this->app, - 'itemId' => $this->app->input->getInt('Itemid'), - 'tagId' => $this->app->input->getInt('tagid'), - 'edit' => $this->app->input->getInt('edit'), - 'user' => $this->user, - 'params' => $this->params - ]; - - RedshopHelperBreadcrumb::generate(); - - $itemId = $this->input->getInt('Itemid'); - $layout = $this->input->getString('layout'); - - /** @var RedshopModelAccount $this */ - $this->model = $this->getModel(); - - $this->userdata = $this->model->getUserAccountInfo($this->user->id); - - if (empty($this->userdata) && $layout != 'mywishlist') { - $this->app->redirect( - JRoute::_("index.php?option=com_redshop&view=account_billto&Itemid=" . $itemId), - JText::_('COM_REDSHOP_LOGIN_USER_IS_NOT_REDSHOP_USER') - ); - } - - $layout = $this->input->getString('layout', 'default'); - $mail = $this->input->getInt('mail'); - - // Preform security checks. Give permission to send wishlist while not logged in - if (($this->user->id == 0 && $layout !== 'mywishlist') || ($this->user->id == 0 && $layout === 'mywishlist' && !isset($mail))) { - $this->app->redirect(JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . $itemId, false)); - } - - switch ($layout) { - case 'cards': - $twigParams = array_merge($twigParams, $this->layoutCards()); - break; - case 'mytags': - $twigParams = array_merge($twigParams, $this->layoutMytags()); - break; - case 'mywishlist': - $twigParams = array_merge($twigParams, $this->layoutMyWishlist()); - break; - default: - $twigParams = array_merge($twigParams, $this->layoutDefault()); - } - - $twigParams = array_merge( - $twigParams, - [ - 'userData' => $this->userdata, - ] - ); - - print \RedshopLayoutHelper::render( - $layout, - $twigParams, - '', - array( - 'component' => 'com_redshop', - 'layoutType' => 'Twig', - 'layoutOf' => 'component', - 'prefix' => 'com_redshop/account' - ) - ); - } - - /** - * Layout my tags - * - * @return mixed - * - * @since 3.0.1 - */ - private function layoutMytags() - { - /** @var RedshopModelAccount $this ->model */ - $this->model = $this->getModel('account'); - - JLoader::import('joomla.html.pagination'); - $this->setLayout('mytags'); - - $remove = $this->input->getInt('remove', 0); - - if ($remove == 1) { - $this->model->removeTag(); - } - - $maxcategory = $this->params->get('maxcategory', 5); - $limit = $this->app->getUserStateFromRequest( - $this->model->context . 'limit', - 'limit', - $maxcategory, - 5 - ); - - $limitstart = $this->input->getInt('limitstart', 0, '', 'int'); - $total = $this->get('total'); - $pagination = new JPagination($total, $limitstart, $limit); - $this->pagination = $pagination; - - $twigParams = [ - 'model' => $this->getModel('account'), - 'pageTitle' => \JText::_('COM_REDSHOP_MY_TAGS'), - 'maxCategory' => $maxcategory, - 'limit' => $limit, - 'total' => $total, - 'pagination' => $pagination - ]; - - return $twigParams; - } - - /** - * Layout my wishlist - * - * @return mixed - * - * @since 3.0.1 - */ - private function layoutMyWishlist() - { - $wishlistId = $this->input->getInt('wishlist_id'); - $mail = $this->input->getInt('mail', 0); - $window = $this->input->getInt('window'); - - if ($wishlistId == 0 && !Redshop::getConfig()->get('WISHLIST_LIST')) { - $usersWishlist = RedshopHelperWishlist::getUserWishlist(); - $usersWishlist = reset($usersWishlist); - - $this->app->redirect( - JRoute::_( - "index.php?option=com_redshop&view=account&layout=mywishlist&wishlist_id=" - . $usersWishlist->wishlist_id . "&Itemid=" . $itemId, - false - ) - ); - } - - // If wishlist Id is not set then redirect to it's main page - if ($wishlistId == 0) { - $this->app->redirect( - JRoute::_("index.php?option=com_redshop&view=wishlist&layout=viewwishlist&Itemid=" . $itemId) - ); - } - - JLoader::import('joomla.html.pagination'); - - $this->setLayout('mywishlist'); - - $remove = $this->input->getInt('remove', 0); - - if ($remove == 1) { - $this->model->removeWishlistProduct(); - } - - $maxcategory = $this->params->get('maxcategory', 5); - $limit = $this->app->getUserStateFromRequest( - $this->model->context . 'limit', - 'limit', - $maxcategory, - 5 - ); - - $limitstart = $this->input->getInt('limitstart', 0, '', 'int'); - $total = $this->get('total'); - $pagination = new JPagination($total, $limitstart, $limit); - $this->pagination = $pagination; - $displayWishlist = $mail == 0 ? $this->wishlistTemplate() : $this->wishlistMailTemplate(); - - return [ - 'wishlistId' => $wishlistId, - 'mail' => $mail, - 'window' => $window, - 'disPlayWishlist' => $displayWishlist - ]; - } - - /** - * Wishlist template - * - * @return string - * - * @since 3.0.1 - */ - private function wishlistTemplate() - { - $wishlist = $this->model->getMyDetail(); - $template = RedshopHelperTemplate::getTemplate("wishlist_template"); - - if (count($template) > 0 && $template[0]->template_desc != "") { - $templateDesc = $template[0]->template_desc; - } else { - $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('wishlist_template'); - } - - return \RedshopTagsReplacer::_( - 'wishlist', - $templateDesc, - array( - 'wishlist' => $wishlist - ) - ); - } - - /** - * Wishlist mail template - * - * @return string - * - * @since 3.0.1 - */ - private function wishlistMailTemplate() - { - $mailTemplate = RedshopHelperTemplate::getTemplate("wishlist_mail_template"); - - if (count($mailTemplate) > 0 && $mailTemplate[0]->template_desc != "") { - $templateDesc = $mailTemplate[0]->template_desc; - } else { - $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('wishlist_mail_template'); - } - - return \RedshopTagsReplacer::_( - 'wishlistmail', - $templateDesc, - array( - 'user' => $this->user, - 'itemId' => $this->app->input->getInt('Itemid'), - 'wishlistId' => $this->input->getInt('wishlist_id') - ) - ); - } - - /** - * Layout default - * - * @return mixed - * - * @since 3.0.1 - */ - private function layoutDefault() - { - $template = RedshopHelperTemplate::getTemplate("account_template"); - - if (count($template) > 0 && $template[0]->template_desc != "") { - $templateDesc = $template[0]->template_desc; - } else { - $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('account_template'); - } - - return [ - 'displayTemplate' => RedshopTagsReplacer::_( - 'account', - $templateDesc, - [ - 'params' => $this->params, - 'userData' => $this->userdata - ] - ) - ]; - } - - /** - * Layout cards - * - * @return mixed - * - * @since 3.0.1 - */ - private function layoutCards() - { - JPluginHelper::importPlugin('redshop_payment'); - $dispatcher = \RedshopHelperUtility::getDispatcher(); - $cards = $dispatcher->trigger('onListCreditCards', array()); - - if (empty($cards)) { - JFactory::getApplication()->enqueueMessage( - JText::_('COM_REDSHOP_PAYMENT_NO_CREDIT_CARDS_PLUGIN_LIST_FOUND'), - 'warning' - ); - } - - return ['cards' => $cards]; - } + /** + * @var JPagination + */ + public $pagination; + + /** + * @var JUser + */ + public $user; + + /** + * @var mixed + */ + public $userdata; + + /** + * @var Joomla\Registry\Registry + */ + public $params; + + /** + * @var \JModelLegacy + */ + public $model; + + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise a JError object. + * @throws Exception + */ + public function display($tpl = null) + { + $this->params = $this->app->getParams('com_redshop'); + $this->user = JFactory::getUser(); + $twigParams = [ + 'url' => \JURI::base(), + 'app' => $this->app, + 'itemId' => $this->app->input->getInt('Itemid'), + 'tagId' => $this->app->input->getInt('tagid'), + 'edit' => $this->app->input->getInt('edit'), + 'user' => $this->user, + 'params' => $this->params + ]; + + RedshopHelperBreadcrumb::generate(); + + $itemId = $this->input->getInt('Itemid'); + $layout = $this->input->getString('layout'); + + /** @var RedshopModelAccount $this */ + $this->model = $this->getModel(); + + $this->userdata = $this->model->getUserAccountInfo($this->user->id); + + if (empty($this->userdata) && $layout != 'mywishlist') { + $this->app->redirect( + JRoute::_("index.php?option=com_redshop&view=account_billto&Itemid=" . $itemId), + JText::_('COM_REDSHOP_LOGIN_USER_IS_NOT_REDSHOP_USER') + ); + } + + $layout = $this->input->getString('layout', 'default'); + $mail = $this->input->getInt('mail'); + + // Preform security checks. Give permission to send wishlist while not logged in + if (($this->user->id == 0 && $layout !== 'mywishlist') || ($this->user->id == 0 && $layout === 'mywishlist' && !isset($mail))) { + $this->app->redirect(JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . $itemId, false)); + } + + switch ($layout) { + case 'cards': + $twigParams = array_merge($twigParams, $this->layoutCards()); + break; + case 'mytags': + $twigParams = array_merge($twigParams, $this->layoutMytags()); + break; + case 'mywishlist': + $twigParams = array_merge($twigParams, $this->layoutMyWishlist()); + break; + default: + $twigParams = array_merge($twigParams, $this->layoutDefault()); + } + + $twigParams = array_merge( + $twigParams, + [ + 'userData' => $this->userdata, + ] + ); + + print \RedshopLayoutHelper::render( + $layout, + $twigParams, + '', + array( + 'component' => 'com_redshop', + 'layoutType' => 'Twig', + 'layoutOf' => 'component', + 'prefix' => 'com_redshop/account' + ) + ); + } + + /** + * Layout cards + * + * @return mixed + * + * @since 3.0.1 + */ + private function layoutCards() + { + JPluginHelper::importPlugin('redshop_payment'); + $dispatcher = \RedshopHelperUtility::getDispatcher(); + $cards = $dispatcher->trigger('onListCreditCards', array()); + + if (empty($cards)) { + JFactory::getApplication()->enqueueMessage( + JText::_('COM_REDSHOP_PAYMENT_NO_CREDIT_CARDS_PLUGIN_LIST_FOUND'), + 'warning' + ); + } + + return ['cards' => $cards]; + } + + /** + * Layout my tags + * + * @return mixed + * + * @since 3.0.1 + */ + private function layoutMytags() + { + /** @var RedshopModelAccount $this ->model */ + $this->model = $this->getModel('account'); + + JLoader::import('joomla.html.pagination'); + $this->setLayout('mytags'); + + $remove = $this->input->getInt('remove', 0); + + if ($remove == 1) { + $this->model->removeTag(); + } + + $maxcategory = $this->params->get('maxcategory', 5); + $limit = $this->app->getUserStateFromRequest( + $this->model->context . 'limit', + 'limit', + $maxcategory, + 5 + ); + + $limitstart = $this->input->getInt('limitstart', 0, '', 'int'); + $total = $this->get('total'); + $pagination = new JPagination($total, $limitstart, $limit); + $this->pagination = $pagination; + + $twigParams = [ + 'model' => $this->getModel('account'), + 'pageTitle' => \JText::_('COM_REDSHOP_MY_TAGS'), + 'maxCategory' => $maxcategory, + 'limit' => $limit, + 'total' => $total, + 'pagination' => $pagination + ]; + + return $twigParams; + } + + /** + * Layout my wishlist + * + * @return mixed + * + * @since 3.0.1 + */ + private function layoutMyWishlist() + { + $wishlistId = $this->input->getInt('wishlist_id'); + $mail = $this->input->getInt('mail', 0); + $window = $this->input->getInt('window'); + + if ($wishlistId == 0 && !Redshop::getConfig()->get('WISHLIST_LIST')) { + $usersWishlist = RedshopHelperWishlist::getUserWishlist(); + $usersWishlist = reset($usersWishlist); + + $this->app->redirect( + JRoute::_( + "index.php?option=com_redshop&view=account&layout=mywishlist&wishlist_id=" + . $usersWishlist->wishlist_id . "&Itemid=" . $itemId, + false + ) + ); + } + + // If wishlist Id is not set then redirect to it's main page + if ($wishlistId == 0) { + $this->app->redirect( + JRoute::_("index.php?option=com_redshop&view=wishlist&layout=viewwishlist&Itemid=" . $itemId) + ); + } + + JLoader::import('joomla.html.pagination'); + + $this->setLayout('mywishlist'); + + $remove = $this->input->getInt('remove', 0); + + if ($remove == 1) { + $this->model->removeWishlistProduct(); + } + + $maxcategory = $this->params->get('maxcategory', 5); + $limit = $this->app->getUserStateFromRequest( + $this->model->context . 'limit', + 'limit', + $maxcategory, + 5 + ); + + $limitstart = $this->input->getInt('limitstart', 0, '', 'int'); + $total = $this->get('total'); + $pagination = new JPagination($total, $limitstart, $limit); + $this->pagination = $pagination; + $displayWishlist = $mail == 0 ? $this->wishlistTemplate() : $this->wishlistMailTemplate(); + + return [ + 'wishlistId' => $wishlistId, + 'mail' => $mail, + 'window' => $window, + 'disPlayWishlist' => $displayWishlist + ]; + } + + /** + * Wishlist template + * + * @return string + * + * @since 3.0.1 + */ + private function wishlistTemplate() + { + $wishlist = $this->model->getMyDetail(); + $template = RedshopHelperTemplate::getTemplate("wishlist_template"); + + if (count($template) > 0 && $template[0]->template_desc != "") { + $templateDesc = $template[0]->template_desc; + } else { + $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('wishlist_template'); + } + + return \RedshopTagsReplacer::_( + 'wishlist', + $templateDesc, + array( + 'wishlist' => $wishlist + ) + ); + } + + /** + * Wishlist mail template + * + * @return string + * + * @since 3.0.1 + */ + private function wishlistMailTemplate() + { + $mailTemplate = RedshopHelperTemplate::getTemplate("wishlist_mail_template"); + + if (count($mailTemplate) > 0 && $mailTemplate[0]->template_desc != "") { + $templateDesc = $mailTemplate[0]->template_desc; + } else { + $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('wishlist_mail_template'); + } + + return \RedshopTagsReplacer::_( + 'wishlistmail', + $templateDesc, + array( + 'user' => $this->user, + 'itemId' => $this->app->input->getInt('Itemid'), + 'wishlistId' => $this->input->getInt('wishlist_id') + ) + ); + } + + /** + * Layout default + * + * @return mixed + * + * @since 3.0.1 + */ + private function layoutDefault() + { + $template = RedshopHelperTemplate::getTemplate("account_template"); + + if (count($template) > 0 && $template[0]->template_desc != "") { + $templateDesc = $template[0]->template_desc; + } else { + $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('account_template'); + } + + return [ + 'displayTemplate' => RedshopTagsReplacer::_( + 'account', + $templateDesc, + [ + 'params' => $this->params, + 'userData' => $this->userdata + ] + ) + ]; + } } \ No newline at end of file diff --git a/component/site/views/account_billto/tmpl/default.html.twig b/component/site/views/account_billto/tmpl/default.html.twig index ee94ed4ddb4..a28e7ba78ac 100644 --- a/component/site/views/account_billto/tmpl/default.html.twig +++ b/component/site/views/account_billto/tmpl/default.html.twig @@ -1,42 +1,42 @@ {% if params.get('show_page_heading', 1) %} -

    - {{ jtext('COM_REDSHOP_BILLING_ADDRESS_INFORMATION_LBL') }} -

    +

    + {{ jtext('COM_REDSHOP_BILLING_ADDRESS_INFORMATION_LBL') }} +

    {% endif %}
    -
    - {{ jtext('COM_REDSHOP_CUSTOMER_INFORMATION') }} - {{ redSHOPCall( - 'RedshopHelperBilling', - 'render', - [ - post, billingaddresses.is_company, lists, 0, 0, createAccount - ] - ) }} - - - - - -
    - -
    -
    - - - - - - - +
    + {{ jtext('COM_REDSHOP_CUSTOMER_INFORMATION') }} + {{ redSHOPCall( + 'RedshopHelperBilling', + 'render', + [ + post, billingaddresses.is_company, lists, 0, 0, createAccount + ] + ) }} + + + + + +
    + +
    +
    + + + + + + +
    diff --git a/component/site/views/account_billto/view.html.php b/component/site/views/account_billto/view.html.php index 28c628cbdfa..07bd4cf8ac9 100644 --- a/component/site/views/account_billto/view.html.php +++ b/component/site/views/account_billto/view.html.php @@ -18,127 +18,127 @@ */ class RedshopViewAccount_Billto extends RedshopView { - /** - * Execute and display a template script. - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return mixed A string if successful, otherwise a JError object. - * @throws Exception - */ - public function display($tpl = null) - { - /** @var JApplicationSite $app */ - $app = JFactory::getApplication(); - $params = $app->getParams('com_redshop'); - $input = JFactory::getApplication()->input; - $user = JFactory::getUser(); - $itemId = $input->getInt('Itemid', 0); - $isEdit = $input->getInt('is_edit', 0); - $return = $input->getString('return', ""); - - $billingAddresses = Redshop\User\Billing\Billing::getGlobal(); - - if (empty($billingAddresses) || $billingAddresses == new stdClass) { - /** @var RedshopModelAccount_Billto $model */ - $model = $this->getModel('account_billto'); - - $billingAddresses = $model->_initData(); - } - - $uri = JUri::getInstance(); - $session = JFactory::getSession(); - $auth = $session->get('auth'); - - if (!is_array($auth)) { - $auth['users_info_id'] = 0; - $session->set('auth', $auth); - $auth = $session->get('auth'); - } - - $link = JRoute::_('index.php?option=com_redshop&view=' . $return . '&Itemid=' . $itemId, false); - - $accountBilltoJs = ['isEdit' => $isEdit, 'link' => $link]; - $document = JFactory::getDocument(); - $document->addScriptOptions('account_billto', $accountBilltoJs); - - JHtml::_('behavior.framework'); - JHtml::_('redshopjquery.framework'); - JHtml::_('script', 'com_redshop/jquery.validate.min.js', false, true); - JHtml::_('script', 'com_redshop/redshop.common.min.js', false, true); - JHtml::_('script', 'com_redshop/redshop.registration.min.js', false, true); - JHtml::_('script', 'com_redshop/account/billto.js', false, true); - /** @scrutinizer ignore-deprecated */ - JHtml::stylesheet('com_redshop/redshop.validation.min.css', array(), true); - - // Preform security checks - if ($user->id == 0 && $auth['users_info_id'] == 0) { - $app->redirect(JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . JRequest::getInt('Itemid'))); - $app->close(); - } - - $lists = array( - 'requesting_tax_exempt' => JHtml::_( - 'select.booleanlist', - 'requesting_tax_exempt', - 'class="inputbox"', - $billingAddresses->requesting_tax_exempt - ) - ); - - if ($billingAddresses->is_company) { - $lists['extra_field_company'] = Redshop\Fields\SiteHelper::renderFields( - RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS, - $billingAddresses->users_info_id - ); - } else { - $lists['extra_field_user'] = Redshop\Fields\SiteHelper::renderFields( - RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS, - $billingAddresses->users_info_id - ); - } - - $requestUrl = $uri->toString(); - JFilterOutput::cleanText($requestUrl); - JPluginHelper::importPlugin('redshop_shipping'); - $dispatcher = RedshopHelperUtility::getDispatcher(); - $dispatcher->trigger('onRenderCustomField', array($billingAddresses)); - $post = (array)$billingAddresses; - - $post["email1"] = $post["email"] = $post["user_email"]; - - if ($user->username) { - $post["username"] = $user->username; - } - - $createAccount = 1; - - if ($post["user_id"] < 0) { - $createAccount = 0; - } - - $twigParams = [ - 'billingAddresses' => $billingAddresses, - 'params' => $params, - 'requestUrl' => $requestUrl, - 'createAccount' => $createAccount, - 'isEdit' => $isEdit, - 'post' => $post, - 'itemId' => $itemId, - 'dispatcher' => $dispatcher, - 'lists' => $lists - ]; - - print \RedshopLayoutHelper::render( - 'default', - $twigParams, - '', - array( - 'component' => 'com_redshop', - 'layoutType' => 'Twig', - 'layoutOf' => 'component', - 'prefix' => 'com_redshop/account_billto' - ) - ); - } + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise a JError object. + * @throws Exception + */ + public function display($tpl = null) + { + /** @var JApplicationSite $app */ + $app = JFactory::getApplication(); + $params = $app->getParams('com_redshop'); + $input = JFactory::getApplication()->input; + $user = JFactory::getUser(); + $itemId = $input->getInt('Itemid', 0); + $isEdit = $input->getInt('is_edit', 0); + $return = $input->getString('return', ""); + + $billingAddresses = Redshop\User\Billing\Billing::getGlobal(); + + if (empty($billingAddresses) || $billingAddresses == new stdClass) { + /** @var RedshopModelAccount_Billto $model */ + $model = $this->getModel('account_billto'); + + $billingAddresses = $model->_initData(); + } + + $uri = JUri::getInstance(); + $session = JFactory::getSession(); + $auth = $session->get('auth'); + + if (!is_array($auth)) { + $auth['users_info_id'] = 0; + $session->set('auth', $auth); + $auth = $session->get('auth'); + } + + $link = JRoute::_('index.php?option=com_redshop&view=' . $return . '&Itemid=' . $itemId, false); + + $accountBilltoJs = ['isEdit' => $isEdit, 'link' => $link]; + $document = JFactory::getDocument(); + $document->addScriptOptions('account_billto', $accountBilltoJs); + + JHtml::_('behavior.framework'); + JHtml::_('redshopjquery.framework'); + JHtml::_('script', 'com_redshop/jquery.validate.min.js', false, true); + JHtml::_('script', 'com_redshop/redshop.common.min.js', false, true); + JHtml::_('script', 'com_redshop/redshop.registration.min.js', false, true); + JHtml::_('script', 'com_redshop/account/billto.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::stylesheet('com_redshop/redshop.validation.min.css', array(), true); + + // Preform security checks + if ($user->id == 0 && $auth['users_info_id'] == 0) { + $app->redirect(JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . JRequest::getInt('Itemid'))); + $app->close(); + } + + $lists = array( + 'requesting_tax_exempt' => JHtml::_( + 'select.booleanlist', + 'requesting_tax_exempt', + 'class="inputbox"', + $billingAddresses->requesting_tax_exempt + ) + ); + + if ($billingAddresses->is_company) { + $lists['extra_field_company'] = Redshop\Fields\SiteHelper::renderFields( + RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS, + $billingAddresses->users_info_id + ); + } else { + $lists['extra_field_user'] = Redshop\Fields\SiteHelper::renderFields( + RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS, + $billingAddresses->users_info_id + ); + } + + $requestUrl = $uri->toString(); + JFilterOutput::cleanText($requestUrl); + JPluginHelper::importPlugin('redshop_shipping'); + $dispatcher = RedshopHelperUtility::getDispatcher(); + $dispatcher->trigger('onRenderCustomField', array($billingAddresses)); + $post = (array)$billingAddresses; + + $post["email1"] = $post["email"] = $post["user_email"]; + + if ($user->username) { + $post["username"] = $user->username; + } + + $createAccount = 1; + + if ($post["user_id"] < 0) { + $createAccount = 0; + } + + $twigParams = [ + 'billingAddresses' => $billingAddresses, + 'params' => $params, + 'requestUrl' => $requestUrl, + 'createAccount' => $createAccount, + 'isEdit' => $isEdit, + 'post' => $post, + 'itemId' => $itemId, + 'dispatcher' => $dispatcher, + 'lists' => $lists + ]; + + print \RedshopLayoutHelper::render( + 'default', + $twigParams, + '', + array( + 'component' => 'com_redshop', + 'layoutType' => 'Twig', + 'layoutOf' => 'component', + 'prefix' => 'com_redshop/account_billto' + ) + ); + } } diff --git a/component/site/views/account_shipto/tmpl/default.php b/component/site/views/account_shipto/tmpl/default.php index 538bb57aa90..c3f30dff02b 100755 --- a/component/site/views/account_shipto/tmpl/default.php +++ b/component/site/views/account_shipto/tmpl/default.php @@ -19,64 +19,73 @@ ?> params->get('show_page_heading', 1)): ?> - params->get('page_title') != $pageTitle): ?> -

    - escape(JText::_('COM_REDSHOP_SHIPPING_ADDRESS_INFO_LBL')); ?> -

    - -

    -

    - + params->get('page_title') != $pageTitle): ?> +

    + escape(JText::_('COM_REDSHOP_SHIPPING_ADDRESS_INFO_LBL')); ?> +

    + +

    +

    +
    - - - get('OPTIONAL_SHIPPING_ADDRESS')): ?> - - - - + +
    -
    + get('OPTIONAL_SHIPPING_ADDRESS')): ?> + + + + - shippingAddresses)): ?> - - shippingAddresses); $i++): ?> - shippingAddresses[$i]->users_info_id . "&Itemid=" . $itemId; ?> - shippingAddresses[$i]->users_info_id . "&Itemid=" . $itemId; ?> + shippingAddresses)): ?> + + shippingAddresses); $i++): ?> + shippingAddresses[$i]->users_info_id . "&Itemid=" . $itemId; ?> + shippingAddresses[$i]->users_info_id . "&Itemid=" . $itemId; ?> - - - shippingAddresses); $i++): ?> + + + shippingAddresses); $i++): ?> - - - - + + + + @@ -88,6 +97,6 @@ - -
    -
    - - " . $this->shippingAddresses[$i]->text . ""; ?> + - " . $this->shippingAddresses[$i]->text . ""; ?> - +
    - shippingAddresses[$i]->text; ?>
    + +
    diff --git a/component/site/views/account_shipto/tmpl/form.php b/component/site/views/account_shipto/tmpl/form.php index 0f83ec9c9b4..1dbaaa0ad47 100644 --- a/component/site/views/account_shipto/tmpl/form.php +++ b/component/site/views/account_shipto/tmpl/form.php @@ -18,7 +18,7 @@ $infoId = $input->getInt('infoid', 0); $dispatcher->trigger('onRenderCustomField', array($infoId)); -$post = (array) $this->shippingAddresses; +$post = (array)$this->shippingAddresses; $post['firstname_ST'] = $post['firstname']; $post['lastname_ST'] = $post['lastname']; @@ -30,109 +30,113 @@ $post['state_code_ST'] = $post['state_code']; ?>
    -
    -
    - - $post, - 'isCompany' => $this->billingAddresses->is_company, - 'lists' => $this->lists - ) - ); - ?> - - - - - -
    - onclick="javascript:cancelForm(this.form);"> - value="">
    -
    -
    - - - - - - - - - - - - - - - +
    +
    + + $post, + 'isCompany' => $this->billingAddresses->is_company, + 'lists' => $this->lists + ) + ); + ?> + + + + + +
    + onclick="javascript:cancelForm(this.form);"> + value="">
    +
    +
    + + + + + + + + + + + + + + +
    diff --git a/component/site/views/account_shipto/view.html.php b/component/site/views/account_shipto/view.html.php index c75b0e46a9e..acb3cf309d2 100644 --- a/component/site/views/account_shipto/view.html.php +++ b/component/site/views/account_shipto/view.html.php @@ -20,120 +20,112 @@ */ class RedshopViewAccount_Shipto extends RedshopView { - /** - * @var array - */ - public $shippingAddresses; - - /** - * @var array - */ - public $lists; - - /** - * @var object - */ - public $billingAddresses; - - /** - * @var Registry - */ - public $params; - - /** - * @var string - */ - public $request_url; - - /** - * Execute and display a template script. - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return mixed A string if successful, otherwise an Error object. - * @throws Exception - * - * @see JViewLegacy::loadTemplate() - * @since 12.2 - */ - public function display($tpl = null) - { - /** @var JApplicationSite $app */ - $app = JFactory::getApplication(); - $task = $app->input->getCmd('task'); - $user = JFactory::getUser(); - - // Preform security checks - $session = JFactory::getSession(); - $auth = $session->get('auth'); - $lists = array(); - $billingAddress = new stdClass; - - if ($user->id) - { - $billingAddress = RedshopHelperOrder::getBillingAddress($user->id); - } - elseif (isset($auth['users_info_id']) && $auth['users_info_id']) - { - $model = $this->getModel('account_shipto'); - $billingAddress = $model->_loadData($auth['users_info_id']); - } - else - { - $app->redirect(JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . $app->input->getInt('Itemid', 0))); - $app->close(); - } - - if ($task == 'addshipping') - { - JHtml::_('redshopjquery.framework'); - /** @scrutinizer ignore-deprecated */ - JHtml::script('com_redshop/jquery.validate.min.js', false, true); - /** @scrutinizer ignore-deprecated */ - JHtml::script('com_redshop/redshop.common.min.js', false, true); - /** @scrutinizer ignore-deprecated */ - JHtml::script('com_redshop/redshop.registration.min.js', false, true); - /** @scrutinizer ignore-deprecated */ - JHtml::stylesheet('com_redshop/redshop.validation.min.css', array(), true); - - $shippingAddresses = $this->get('Data'); - - if ($shippingAddresses->users_info_id > 0 && $shippingAddresses->user_id != $billingAddress->user_id) - { - echo JText::_('COM_REDSHOP_ALERTNOTAUTH'); - - return; - } - - $lists['shipping_customer_field'] = Redshop\Fields\SiteHelper::renderFields( - RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS, $shippingAddresses->users_info_id - ); - $lists['shipping_company_field'] = Redshop\Fields\SiteHelper::renderFields( - RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS, $shippingAddresses->users_info_id - ); - - $this->setLayout('form'); - } - else - { - if ($user->id) - { - $shippingAddresses = RedshopHelperOrder::getShippingAddress($user->id); - } - else - { - $shippingAddresses = RedshopHelperOrder::getShippingAddress(-$auth['users_info_id']); - } - } - - $this->lists = $lists; - $this->shippingAddresses = $shippingAddresses; - $this->billingAddresses = $billingAddress; - $this->request_url = JUri::getInstance()->toString(); - - JFilterOutput::cleanText($this->request_url); - $this->params = $app->getParams(); - - parent::display($tpl); - } + /** + * @var array + */ + public $shippingAddresses; + + /** + * @var array + */ + public $lists; + + /** + * @var object + */ + public $billingAddresses; + + /** + * @var Registry + */ + public $params; + + /** + * @var string + */ + public $request_url; + + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise an Error object. + * @throws Exception + * + * @see JViewLegacy::loadTemplate() + * @since 12.2 + */ + public function display($tpl = null) + { + /** @var JApplicationSite $app */ + $app = JFactory::getApplication(); + $task = $app->input->getCmd('task'); + $user = JFactory::getUser(); + + // Preform security checks + $session = JFactory::getSession(); + $auth = $session->get('auth'); + $lists = array(); + $billingAddress = new stdClass; + + if ($user->id) { + $billingAddress = RedshopHelperOrder::getBillingAddress($user->id); + } elseif (isset($auth['users_info_id']) && $auth['users_info_id']) { + $model = $this->getModel('account_shipto'); + $billingAddress = $model->_loadData($auth['users_info_id']); + } else { + $app->redirect( + JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . $app->input->getInt('Itemid', 0)) + ); + $app->close(); + } + + if ($task == 'addshipping') { + JHtml::_('redshopjquery.framework'); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/jquery.validate.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.common.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.registration.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::stylesheet('com_redshop/redshop.validation.min.css', array(), true); + + $shippingAddresses = $this->get('Data'); + + if ($shippingAddresses->users_info_id > 0 && $shippingAddresses->user_id != $billingAddress->user_id) { + echo JText::_('COM_REDSHOP_ALERTNOTAUTH'); + + return; + } + + $lists['shipping_customer_field'] = Redshop\Fields\SiteHelper::renderFields( + RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS, + $shippingAddresses->users_info_id + ); + $lists['shipping_company_field'] = Redshop\Fields\SiteHelper::renderFields( + RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS, + $shippingAddresses->users_info_id + ); + + $this->setLayout('form'); + } else { + if ($user->id) { + $shippingAddresses = RedshopHelperOrder::getShippingAddress($user->id); + } else { + $shippingAddresses = RedshopHelperOrder::getShippingAddress(-$auth['users_info_id']); + } + } + + $this->lists = $lists; + $this->shippingAddresses = $shippingAddresses; + $this->billingAddresses = $billingAddress; + $this->request_url = JUri::getInstance()->toString(); + + JFilterOutput::cleanText($this->request_url); + $this->params = $app->getParams(); + + parent::display($tpl); + } } diff --git a/component/site/views/ask_question/tmpl/default.php b/component/site/views/ask_question/tmpl/default.php index c9e6650e40e..0987c5c8028 100644 --- a/component/site/views/ask_question/tmpl/default.php +++ b/component/site/views/ask_question/tmpl/default.php @@ -11,22 +11,19 @@ $app = JFactory::getApplication(); -if (!$app->input->getInt('questionSend', 0)) -{ - echo RedshopTagsReplacer::_( - 'askquestion', - '', - array( - 'form' => $this->form, - 'ask' => $app->input->getInt('ask', 0) - ) - ); -} -else -{ - ?> - -input->getInt('questionSend', 0)) { + echo RedshopTagsReplacer::_( + 'askquestion', + '', + array( + 'form' => $this->form, + 'ask' => $app->input->getInt('ask', 0) + ) + ); +} else { + ?> + + state = $this->get('State'); - $this->form = $this->get('Form'); + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise a Error object. + */ + public function display($tpl = null) + { + $this->state = $this->get('State'); + $this->form = $this->get('Form'); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/site/views/cart/tmpl/change_attribute.php b/component/site/views/cart/tmpl/change_attribute.php index c238c9e633c..bb9e7862a2b 100644 --- a/component/site/views/cart/tmpl/change_attribute.php +++ b/component/site/views/cart/tmpl/change_attribute.php @@ -16,50 +16,44 @@ ?> 0 && $cartAttribute[0]->template_desc) -{ - $templateDesc = $cartAttribute[0]->template_desc; -} -else -{ - $templateDesc = RedshopHelperTemplate::getTemplate("change_cart_attribute"); +if (count($cartAttribute) > 0 && $cartAttribute[0]->template_desc) { + $templateDesc = $cartAttribute[0]->template_desc; +} else { + $templateDesc = RedshopHelperTemplate::getTemplate("change_cart_attribute"); } $templateDesc = RedshopTagsReplacer::_( - 'changecartattribute', - $templateDesc, - array( - 'cart' => $cart, - 'cartIndex' => $cartIndex, - 'productId' => $productId - ) + 'changecartattribute', + $templateDesc, + array( + 'cart' => $cart, + 'cartIndex' => $cartIndex, + 'productId' => $productId + ) ); echo eval("?>" . $templateDesc . "input->getCmd('layout'); - $itemId = $app->input->getInt('Itemid'); + $layout = $app->input->getCmd('layout'); + $itemId = $app->input->getInt('Itemid'); - if ($app->input->getString('quotemsg') != "") - { - $app->redirect( - JRoute::_('index.php?option=com_redshop&view=cart&Itemid=' . $itemId, false), - $app->input->getString('quotemsg') - ); - } + if ($app->input->getString('quotemsg') != "") { + $app->redirect( + JRoute::_('index.php?option=com_redshop&view=cart&Itemid=' . $itemId, false), + $app->input->getString('quotemsg') + ); + } - JHtml::_('redshopjquery.framework'); - /** @scrutinizer ignore-deprecated */ - \JHtml::script('com_redshop/redshop.common.min.js', false, true); + JHtml::_('redshopjquery.framework'); + /** @scrutinizer ignore-deprecated */ + \JHtml::script('com_redshop/redshop.common.min.js', false, true); - if (!array_key_exists("idx", $cart) || (array_key_exists("idx", $cart) && $cart['idx'] < 1)) - { - $cartData = RedshopHelperTemplate::getTemplate("empty_cart"); + if (!array_key_exists("idx", $cart) || (array_key_exists("idx", $cart) && $cart['idx'] < 1)) { + $cartData = RedshopHelperTemplate::getTemplate("empty_cart"); - if (count($cartData) > 0 && $cartData[0]->template_desc != "") - { - $cartTemplate = $cartData[0]->template_desc; - } - else - { - $cartTemplate = JText::_("COM_REDSHOP_EMPTY_CART"); - } + if (count($cartData) > 0 && $cartData[0]->template_desc != "") { + $cartTemplate = $cartData[0]->template_desc; + } else { + $cartTemplate = JText::_("COM_REDSHOP_EMPTY_CART"); + } - echo eval ("?>" . $cartTemplate . "" . $cartTemplate . "get('data'); + $data = $this->get('data'); - if ($layout == 'change_attribute') - { - $this->setLayout('change_attribute'); - } + if ($layout == 'change_attribute') { + $this->setLayout('change_attribute'); + } - $this->cart = $cart; - $this->data = $data; + $this->cart = $cart; + $this->data = $data; - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/site/views/catalog/tmpl/default.php b/component/site/views/catalog/tmpl/default.php index 51a830ea402..117ab5d2633 100644 --- a/component/site/views/catalog/tmpl/default.php +++ b/component/site/views/catalog/tmpl/default.php @@ -20,33 +20,28 @@ $template = RedshopHelperTemplate::getTemplate("catalog"); -if (count($template) > 0 && $template[0]->template_desc != "") -{ - $templateDesc = $template[0]->template_desc; -} -else -{ - $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent("catalog"); +if (count($template) > 0 && $template[0]->template_desc != "") { + $templateDesc = $template[0]->template_desc; +} else { + $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent("catalog"); } -if ($this->params->get('show_page_heading', 1)) -{ - if ($this->params->get('page_title')) - { - ?> +if ($this->params->get('show_page_heading', 1)) { + if ($this->params->get('page_title')) { + ?>

    - escape($this->params->get('page_title')); ?> + escape($this->params->get('page_title')); ?>

    $Itemid - ) + 'catalog', + $templateDesc, + array( + 'itemId' => $Itemid + ) ); echo $catalogTemplateWapper; - ?> \ No newline at end of file +?> \ No newline at end of file diff --git a/component/site/views/catalog/tmpl/sample.php b/component/site/views/catalog/tmpl/sample.php index c05a4284709..2539ce92ff7 100644 --- a/component/site/views/catalog/tmpl/sample.php +++ b/component/site/views/catalog/tmpl/sample.php @@ -12,16 +12,16 @@ $template = RedshopHelperTemplate::getTemplate("product_sample"); if (count($template) > 0 && $template[0]->template_desc != "") { - $templateDesc = $template[0]->template_desc; + $templateDesc = $template[0]->template_desc; } else { - $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('product_sample'); + $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('product_sample'); } echo RedshopTagsReplacer::_( - 'productsample', - $templateDesc, - [ - 'params' => $this->params - ] + 'productsample', + $templateDesc, + [ + 'params' => $this->params + ] ); diff --git a/component/site/views/catalog/view.html.php b/component/site/views/catalog/view.html.php index f5cf797a2e1..f521809f7ab 100644 --- a/component/site/views/catalog/view.html.php +++ b/component/site/views/catalog/view.html.php @@ -18,34 +18,33 @@ */ class RedshopViewCatalog extends RedshopView { - /** - * @var Joomla\Registry\Registry - */ - public $params; + /** + * @var Joomla\Registry\Registry + */ + public $params; - /** - * Execute and display a template script. - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return mixed A string if successful, otherwise a JError object. - * @throws Exception - */ - public function display($tpl = null) - { - /** @var JApplicationSite $app */ - $app = JFactory::getApplication(); + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise a JError object. + * @throws Exception + */ + public function display($tpl = null) + { + /** @var JApplicationSite $app */ + $app = JFactory::getApplication(); - $params = $app->getParams('com_redshop'); - $layout = $app->input->getCmd('layout'); + $params = $app->getParams('com_redshop'); + $layout = $app->input->getCmd('layout'); - if ($layout == "sample") - { - $this->setLayout('sample'); - } + if ($layout == "sample") { + $this->setLayout('sample'); + } - $this->params = $params; + $this->params = $params; - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/site/views/category/tmpl/categoryproduct.php b/component/site/views/category/tmpl/categoryproduct.php index 63b24b88212..ee65002d9b5 100644 --- a/component/site/views/category/tmpl/categoryproduct.php +++ b/component/site/views/category/tmpl/categoryproduct.php @@ -13,27 +13,24 @@ $categoryTemplate = RedshopHelperTemplate::getTemplate('categoryproduct'); -if (isset($categoryTemplate[0]->template_desc) && !empty(trim($categoryTemplate[0]->template_desc))) -{ - $templateHtml = $categoryTemplate[0]->template_desc; -} -else -{ - $templateHtml = RedshopHelperTemplate::getDefaultTemplateContent('categoryproduct'); +if (isset($categoryTemplate[0]->template_desc) && !empty(trim($categoryTemplate[0]->template_desc))) { + $templateHtml = $categoryTemplate[0]->template_desc; +} else { + $templateHtml = RedshopHelperTemplate::getDefaultTemplateContent('categoryproduct'); } echo RedshopTagsReplacer::_( - 'categoryproduct', - $templateHtml, - [ - 'params' => $this->params, - 'catId' => $this->catid, - 'detail' => $this->detail, - 'model' => $this->getModel('category'), - 'pageHeadingTag' =>$this->pageheadingtag, - 'orderBySelect' => $this->order_by_select, - 'manufacturerId' => $this->manufacturer_id, - 'lists' => $this->lists - ] + 'categoryproduct', + $templateHtml, + [ + 'params' => $this->params, + 'catId' => $this->catid, + 'detail' => $this->detail, + 'model' => $this->getModel('category'), + 'pageHeadingTag' => $this->pageheadingtag, + 'orderBySelect' => $this->order_by_select, + 'manufacturerId' => $this->manufacturer_id, + 'lists' => $this->lists + ] ); diff --git a/component/site/views/category/tmpl/categoryproduct.xml b/component/site/views/category/tmpl/categoryproduct.xml index 212b49917b8..f70f1d44fbd 100644 --- a/component/site/views/category/tmpl/categoryproduct.xml +++ b/component/site/views/category/tmpl/categoryproduct.xml @@ -9,22 +9,22 @@
    + label="COM_REDSHOP_HOW_MANY_CATEGROY_TO_DISPLAY_PER_PAGE_LBL" + description="COM_REDSHOP_HOW_MANY_CATEGROY_TO_DISPLAY_PER_PAGE"/> + label="COM_REDSHOP_HOW_MANY_PRODUCTS_TO_DISPLAY_PER_CATEGROY_LBL" + description="COM_REDSHOP_HOW_MANY_PRODUCTS_TO_DISPLAY_PER_CATEGROY"/> - + description="COM_REDSHOP_SELECT_PRODUCT_SORTING"/> +
    + addfieldpath="/libraries/redshop/form/fields"> + description="COM_REDSHOP_DISPLAYS_THE_SELECTED_CATEGORY_PRODUCT"/>
    diff --git a/component/site/views/category/tmpl/default.php b/component/site/views/category/tmpl/default.php index 9c3be19d882..f4740a50b9d 100644 --- a/component/site/views/category/tmpl/default.php +++ b/component/site/views/category/tmpl/default.php @@ -11,8 +11,8 @@ JHTML::_('behavior.modal'); -$config = Redconfiguration::getInstance(); -$redTemplate = Redtemplate::getInstance(); +$config = Redconfiguration::getInstance(); +$redTemplate = Redtemplate::getInstance(); $url = JURI::base(); @@ -20,56 +20,45 @@ $model = $this->getModel('category'); $loadCategorytemplate = $this->loadCategorytemplate; -if (!empty($loadCategorytemplate) && $loadCategorytemplate[0]->template_desc != "") -{ - $templateDesc = $loadCategorytemplate[0]->template_desc; -} -else -{ - $templateDesc = "
    {print}

    {category_frontpage_introtext}

    "; - $templateDesc .= "\r\n{category_frontpage_loop_start}
    \r\n"; - $templateDesc .= "
    {category_thumb_image}
    \r\n"; - $templateDesc .= "

    {category_name}

    \r\n
    {category_frontpage_loop_end}"; +if (!empty($loadCategorytemplate) && $loadCategorytemplate[0]->template_desc != "") { + $templateDesc = $loadCategorytemplate[0]->template_desc; +} else { + $templateDesc = "
    {print}

    {category_frontpage_introtext}

    "; + $templateDesc .= "\r\n{category_frontpage_loop_start}
    \r\n"; + $templateDesc .= "
    {category_thumb_image}
    \r\n"; + $templateDesc .= "

    {category_name}

    \r\n
    {category_frontpage_loop_end}"; } -if ($this->params->get('show_page_heading', 0)) -{ - if (!$this->catid) - { - echo '
    '; - } - else - { - echo '
    '; - } +if ($this->params->get('show_page_heading', 0)) { + if (!$this->catid) { + echo '
    '; + } else { + echo '
    '; + } - if (!$this->catid) - { - echo '

    '; + if (!$this->catid) { + echo '

    '; - if ($this->params->get('page_title') != $this->pageheadingtag) - { - echo $this->escape($this->params->get('page_title')); - } - else - { - echo $this->pageheadingtag; - } + if ($this->params->get('page_title') != $this->pageheadingtag) { + echo $this->escape($this->params->get('page_title')); + } else { + echo $this->pageheadingtag; + } - echo '

    '; - } + echo ''; + } - echo '
    '; + echo '
    '; } $categoryTemplateWapper = \RedshopTagsReplacer::_( - 'categoryfrontpage', - $templateDesc ?? '', - array( - 'category' => $this->detail, - 'print' => $this->print, - 'model' => $model - ) + 'categoryfrontpage', + $templateDesc ?? '', + array( + 'category' => $this->detail, + 'print' => $this->print, + 'model' => $model + ) ); echo $categoryTemplateWapper; \ No newline at end of file diff --git a/component/site/views/category/tmpl/default.xml b/component/site/views/category/tmpl/default.xml index 4fbb3b96584..171510ca04d 100644 --- a/component/site/views/category/tmpl/default.xml +++ b/component/site/views/category/tmpl/default.xml @@ -9,7 +9,7 @@
    + description="COM_REDSHOP_DISPLAYS_THE_SELECTED_MANUFACTURER_DETAIL_PAGE"/>
    diff --git a/component/site/views/category/tmpl/detail.php b/component/site/views/category/tmpl/detail.php index 0cb4a5eb461..142cbd716af 100644 --- a/component/site/views/category/tmpl/detail.php +++ b/component/site/views/category/tmpl/detail.php @@ -17,94 +17,86 @@ $loadCategoryTemplate = $this->loadCategorytemplate; -if (!empty($loadCategoryTemplate) && $loadCategoryTemplate[0]->template_desc != "") -{ - $templateDesc = $loadCategoryTemplate[0]->template_desc; -} -else -{ - $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('category'); +if (!empty($loadCategoryTemplate) && $loadCategoryTemplate[0]->template_desc != "") { + $templateDesc = $loadCategoryTemplate[0]->template_desc; +} else { + $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('category'); } -$categoryItemId = (int) RedshopHelperRouter::getCategoryItemid($this->catid); +$categoryItemId = (int)RedshopHelperRouter::getCategoryItemid($this->catid); $mainItemId = !$categoryItemId ? $this->itemid : $categoryItemId; $excludedTags = array(); // New tags replacement for category template section $templateDesc = RedshopTagsReplacer::_( - 'category', - $templateDesc, - array( - 'category' => $this->maincat, - 'subCategories' => $this->detail, - 'manufacturerId' => $this->manufacturer_id, - 'itemId' => $mainItemId, - 'excludedTags' => $excludedTags - ) + 'category', + $templateDesc, + array( + 'category' => $this->maincat, + 'subCategories' => $this->detail, + 'manufacturerId' => $this->manufacturer_id, + 'itemId' => $mainItemId, + 'excludedTags' => $excludedTags + ) ); $templateDesc = RedshopTagsReplacer::_( - 'categorydetail', - $templateDesc, - array( - 'maincat' => $this->maincat, - 'detail' => $this->detail, - 'manufacturer_id' => $this->manufacturer_id, - 'mainItemId' => $mainItemId, - 'excludedTags' => $excludedTags, - 'params' => $this->params, - 'pageheadingtag' => $this->pageheadingtag, - 'print' => $this->print, - 'catid' => $this->catid, - 'itemid' => $this->itemid, - 'state' => $this->state, - 'model' => $this->getModel('category'), - 'order_by_select' => $this->order_by_select, - 'category_template_id' => $this->category_template_id, - 'option' => $this->option, - 'product' => $this->product, - 'productPriceSliderEnable' => $this->productPriceSliderEnable, - 'lists' => $this->lists, - 'category_id' => $this->category_id - ) + 'categorydetail', + $templateDesc, + array( + 'maincat' => $this->maincat, + 'detail' => $this->detail, + 'manufacturer_id' => $this->manufacturer_id, + 'mainItemId' => $mainItemId, + 'excludedTags' => $excludedTags, + 'params' => $this->params, + 'pageheadingtag' => $this->pageheadingtag, + 'print' => $this->print, + 'catid' => $this->catid, + 'itemid' => $this->itemid, + 'state' => $this->state, + 'model' => $this->getModel('category'), + 'order_by_select' => $this->order_by_select, + 'category_template_id' => $this->category_template_id, + 'option' => $this->option, + 'product' => $this->product, + 'productPriceSliderEnable' => $this->productPriceSliderEnable, + 'lists' => $this->lists, + 'category_id' => $this->category_id + ) ); // Replace redproductfinder filter tag -if (strpos($templateDesc, "{redproductfinderfilter:") !== false) -{ - if (file_exists(JPATH_SITE . '/components/com_redproductfinder/helpers/redproductfinder_helper.php')) - { - include_once JPATH_SITE . "/components/com_redproductfinder/helpers/redproductfinder_helper.php"; - $redProductFinderHelper = new redproductfinder_helper; - - $hdnFields = array( - 'texpricemin' => '0', - 'texpricemax' => '0', - 'manufacturer_id' => $filterBy, - 'category_template' => $categoryTemplate - ); - - $hideFilterFlag = false; - - if ($this->catid) - { - $productOfCat = RedshopHelperProduct::getProductCategory($this->catid); - - if (empty($productOfCat)) - { - $hideFilterFlag = true; - } - } - - $templateDesc = $redProductFinderHelper->replaceProductfinder_tag($templateDesc, $hdnFields, $hideFilterFlag); - } +if (strpos($templateDesc, "{redproductfinderfilter:") !== false) { + if (file_exists(JPATH_SITE . '/components/com_redproductfinder/helpers/redproductfinder_helper.php')) { + include_once JPATH_SITE . "/components/com_redproductfinder/helpers/redproductfinder_helper.php"; + $redProductFinderHelper = new redproductfinder_helper; + + $hdnFields = array( + 'texpricemin' => '0', + 'texpricemax' => '0', + 'manufacturer_id' => $filterBy, + 'category_template' => $categoryTemplate + ); + + $hideFilterFlag = false; + + if ($this->catid) { + $productOfCat = RedshopHelperProduct::getProductCategory($this->catid); + + if (empty($productOfCat)) { + $hideFilterFlag = true; + } + } + + $templateDesc = $redProductFinderHelper->replaceProductfinder_tag($templateDesc, $hdnFields, $hideFilterFlag); + } } $templateDesc = RedshopHelperTemplate::parseRedshopPlugin($templateDesc); $templateDesc = RedshopHelperText::replaceTexts($templateDesc); echo eval("?>" . $templateDesc . "close(); +if ($slide) { + JFactory::getApplication()->close(); } diff --git a/component/site/views/category/tmpl/detail.xml b/component/site/views/category/tmpl/detail.xml index 1e75fe4b08f..7f6ba7c6621 100644 --- a/component/site/views/category/tmpl/detail.xml +++ b/component/site/views/category/tmpl/detail.xml @@ -1,31 +1,31 @@ - - - - - + + + + + - -
    - - -
    -
    + +
    + + +
    +
    - -
    - - - -
    -
    + +
    + + + +
    +
    diff --git a/component/site/views/category/tmpl/notfound.php b/component/site/views/category/tmpl/notfound.php index 4f0a3cc3a73..b89e9f755cb 100644 --- a/component/site/views/category/tmpl/notfound.php +++ b/component/site/views/category/tmpl/notfound.php @@ -10,5 +10,5 @@ defined('_JEXEC') or die; ?>
    - maincat->name, $this->maincat->id) ?> + maincat->name, $this->maincat->id) ?>
    diff --git a/component/site/views/category/view.html.php b/component/site/views/category/view.html.php index 1ceb0e517f9..1581c3159a2 100644 --- a/component/site/views/category/view.html.php +++ b/component/site/views/category/view.html.php @@ -19,494 +19,480 @@ */ class RedshopViewCategory extends RedshopView { - public $app; - - public $input; - - public $state = null; - - public $productPriceSliderEnable = false; - - public $category_id; - - /** - * Execute and display a template script. - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return mixed A string if successful, otherwise a JError object. - * - * @see fetch() - * @since 11.1 - * - * @throws Exception - */ - public function display($tpl = null) - { - $this->app = JFactory::getApplication(); - $this->input = $this->app->input; - - // Request variables - $this->option = $this->input->getString('option', 'com_redshop'); - $this->itemid = $this->input->getInt('Itemid', null); - $this->catid = $this->input->getInt('cid', 0); - $layout = $this->input->getString('layout', ''); - $this->print = $this->input->getBool('print', false); - - /** @scrutinizer ignore-call */ - $params = $this->app->getParams('com_redshop'); - /** @var RedshopModelCategory $model */ - $model = $this->getModel('category'); - $this->state = $model->get('state'); - - JPluginHelper::importPlugin('redshop_product'); - JPluginHelper::importPlugin('redshop_product_type'); - $this->dispatcher = RedshopHelperUtility::getDispatcher(); - - $menu_meta_keywords = $params->get('menu-meta_keywords'); - $menu_robots = $params->get('robots'); - $menu_meta_description = $params->get('menu-meta_description'); - - if (!$this->catid && $layout == 'detail') - { - $this->catid = $params->get('cid'); - - if (!$this->catid) - { - throw new InvalidArgumentException(JText::_('COM_REDSHOP_CATEGORY_NOT_FOUND'), 404); - } - - $this->setLayout('detail'); - } - - if (empty($layout) && $this->catid > 0) - { - $this->setLayout('detail'); - } - - $document = JFactory::getDocument(); - JHtml::stylesheet('com_redshop/redshop.priceslider.min.css', array(), true); - - $lists = array(); - $minmax = array(0, 0); - $product = array(); - - $maincat = $model->_loadCategory(); - - $categoryTemplateId = $model->getState('category_template'); - $allCategoryTemplate = $model->getCategoryTemplate(); - $orderData = RedshopHelperUtility::getOrderByList(); - $manufacturers = $model->getManufacturer(); - $loadCategorytemplate = $model->loadCategoryTemplate($categoryTemplateId); - $detail = $model->getdata(); - - if (!empty($maincat) && !empty($maincat->canonical_url)) - { - $main_url = JUri::root() . $maincat->canonical_url; - $canonical = ''; - $document->addCustomTag($canonical); - } - - $pageheadingtag = ''; - - if ($this->catid) - { - // Restrict category if category not published - if ($maincat->published == 0) - { - $this->setLayout('notfound'); - } - - $registry = new JRegistry; - $filterParams = $registry->loadString($maincat->product_filter_params); - - $isSlider = false; - - if ((!empty($loadCategorytemplate) && strpos($loadCategorytemplate[0]->template_desc, "{include_product_in_sub_cat}") !== false) - || ($filterParams->get('enable') == 1 && $filterParams->get('category_enable') == 1) - ) - { - $model->setState('include_sub_categories_products', true); - $loadCategorytemplate[0]->template_desc = str_replace("{include_product_in_sub_cat}", '', $loadCategorytemplate[0]->template_desc); - } - - if (!empty($loadCategorytemplate) && strpos($loadCategorytemplate[0]->template_desc, "{product_price_slider}") !== false) - { - $model->getCategoryProduct(1); - $minmax[0] = $model->getState('minprice'); - $minmax[1] = $model->getState('maxprice'); - - $isSlider = true; - $texpricemin = $this->input->getInt('texpricemin', $minmax[0]); - $texpricemax = $this->input->getInt('texpricemax', $minmax[1]); - $model->setMaxMinProductPrice(array($texpricemin, $texpricemax)); - } - - $product = $model->getCategoryProduct(0, $isSlider); - - $document->setMetaData('keywords', $maincat->metakey); - $document->setMetaData('description', $maincat->metadesc); - $document->setMetaData('robots', $maincat->metarobot_info); - - // For page title - $pagetitletag = Redshop::getConfig()->get('SEO_PAGE_TITLE_CATEGORY'); - $parentcat = ""; - $parentid = RedshopHelperProduct::getParentCategory($maincat->id); - - while ($parentid != 0) - { - $parentdetail = RedshopEntityCategory::getInstance($parentid)->getItem(); - $parentcat = $parentdetail->name . " " . $parentcat; - $parentid = RedshopHelperProduct::getParentCategory($parentdetail->id); - } - - $pagetitletag = str_replace("{parentcategoryloop}", $parentcat, $pagetitletag); - $pagetitletag = str_replace("{categoryname}", $maincat->name, $pagetitletag); - $pagetitletag = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $pagetitletag); - $pagetitletag = str_replace("{categoryshortdesc}", strip_tags($maincat->short_description), $pagetitletag); - - if ($maincat->pagetitle != "" && RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_TITLE_CATEGORY') != '') - { - if ($maincat->append_to_global_seo == 'append') - { - $pagetitletag = $pagetitletag . $maincat->pagetitle; - $document->setTitle($pagetitletag); - } - elseif ($maincat->append_to_global_seo == 'prepend') - { - $pagetitletag = $maincat->pagetitle . $pagetitletag; - $document->setTitle($pagetitletag); - } - elseif ($maincat->append_to_global_seo == 'replace') - { - $document->setTitle($maincat->pagetitle); - } - } - elseif ($maincat->pagetitle != "") - { - $document->setTitle($maincat->pagetitle); - } - elseif (RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_TITLE_CATEGORY') != '') - { - $document->setTitle($pagetitletag); - } - else - { - $document->setTitle($this->app->getCfg('sitename')); - } - - $pagekeywordstag = ''; - - if (RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_KEYWORDS_CATEGORY') != '') - { - $pagekeywordstag = Redshop::getConfig()->get('SEO_PAGE_KEYWORDS_CATEGORY'); - $pagekeywordstag = str_replace("{categoryname}", $maincat->name, $pagekeywordstag); - $pagekeywordstag = str_replace("{categoryshortdesc}", strip_tags($maincat->short_description), $pagekeywordstag); - $pagekeywordstag = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $pagekeywordstag); - $document->setMetaData('keywords', $pagekeywordstag); - } - - if (trim($maincat->metakey) != '' - && RedShop::getConfig()->get('AUTOGENERATED_SEO') - && Redshop::getConfig()->get('SEO_PAGE_KEYWORDS_CATEGORY') != '') - { - if ($maincat->append_to_global_seo == 'append') - { - $pagekeywordstag .= "," . trim($maincat->metakey); - $document->setMetaData('keywords', $pagekeywordstag); - } - elseif ($maincat->append_to_global_seo == 'prepend') - { - $pagekeywordstag = trim($maincat->metakey) . $pagekeywordstag; - $document->setMetaData('keywords', $pagekeywordstag); - } - elseif ($maincat->append_to_global_seo == 'replace') - { - $document->setMetaData('keywords', $maincat->metakey); - } - } - else - { - if ($maincat->metakey != '') - { - $document->setMetaData('keywords', $maincat->metakey); - } - else - { - if (RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_KEYWORDS_CATEGORY') != '') - { - $document->setMetaData('keywords', $pagekeywordstag); - } - else - { - $document->setMetaData('keywords', $maincat->name); - } - } - } - - $pagedesctag = ''; - - // For custom + auto generated description - if (RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_DESCRIPTION_CATEGORY') != '') - { - $pagedesctag = Redshop::getConfig()->get('SEO_PAGE_DESCRIPTION_CATEGORY'); - $pagedesctag = str_replace("{categoryname}", $maincat->name, $pagedesctag); - $pagedesctag = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $pagedesctag); - $pagedesctag = str_replace("{categoryshortdesc}", strip_tags($maincat->short_description), $pagedesctag); - $pagedesctag = str_replace("{categorydesc}", strip_tags($maincat->description), $pagedesctag); - } - - if ($maincat->metadesc != '' && RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_DESCRIPTION_CATEGORY') != '') - { - if ($maincat->append_to_global_seo == 'append') - { - $pagedesctag .= $maincat->metadesc; - $document->setMetaData('description', $pagedesctag); - } - elseif ($maincat->append_to_global_seo == 'prepend') - { - $pagedesctag = trim($maincat->metadesc) . $pagedesctag; - $document->setMetaData('description', $pagedesctag); - } - elseif ($maincat->append_to_global_seo == 'replace') - { - $document->setMetaData('description', $maincat->metadesc); - } - } - elseif ($maincat->metadesc != '') - { - $document->setMetaData('description', $maincat->metadesc); - } - else - { - if (RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_DESCRIPTION_CATEGORY') != '') - { - $document->setMetaData('description', $pagedesctag); - } - else - { - $document->setMetaData('description', $maincat->name); - } - } - - // For metarobot - if ($maincat->metarobot_info != '') - { - $document->setMetaData('robots', $maincat->metarobot_info); - } - else - { - if (RedShop::getConfig()->get('AUTOGENERATED_SEO') && JFactory::getConfig()->get('robots') != '') - { - $document->setMetaData('robots', JFactory::getConfig()->get('robots')); - } - else - { - $document->setMetaData('robots', "INDEX,FOLLOW"); - } - } - - $pageheadingtag = str_replace("{categoryname}", $maincat->name, Redshop::getConfig()->get('SEO_PAGE_HEADING_CATEGORY')); - - if ($maincat->pageheading != "" && RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_HEADING_CATEGORY') != '') - { - $pageheadingtag = $pageheadingtag . $maincat->pageheading; - } - elseif ($maincat->pageheading != "") - { - $pageheadingtag = $maincat->pageheading; - } - else - { - $pageheadingtag = $this->app->getCfg('sitename'); - } - } - else - { - if ($menu_meta_keywords != "") - { - $document->setMetaData('keywords', $menu_meta_keywords); - } - else - { - $document->setMetaData('keywords', $this->app->getCfg('sitename')); - } - - if ($menu_meta_description != "") - { - $document->setMetaData('description', $menu_meta_description); - } - else - { - $document->setMetaData('description', $this->app->getCfg('sitename')); - } - - if ($menu_robots != "") - { - $document->setMetaData('robots', $menu_robots); - } - else - { - $document->setMetaData('robots', $this->app->getCfg('sitename')); - } - } - - // Breadcrumbs - RedshopHelperBreadcrumb::generate($this->catid); - $disabled = ""; - - if ($this->print) - { - $disabled = "disabled"; - } - - $manufacturerId = $model->getState('manufacturer_id'); - - $lists['category_template'] = ""; - $lists['manufacturer'] = ""; - - if (!empty($manufacturers)) - { - $temps = array( - (object) array( - 'id' => 0, - 'name' => JText::_('COM_REDSHOP_SELECT_MANUFACTURE') - ) - ); - $manufacturers = array_merge($temps, $manufacturers); - $lists['manufacturer'] = JHtml::_( - 'select.genericlist', - $manufacturers, - 'manufacturer_id', - 'class="inputbox" onchange="javascript:setSliderMinMaxForManufactur();" ' . $disabled . ' ', - 'id', - 'name', - $manufacturerId - ); - } - - $categories = new RedshopEntitiesCollection; - - if ($model->getState('include_sub_categories_products', false)) - { - $categories = RedshopEntityCategory::getInstance($this->catid)->getChildCategories(); - $lists['categories'] = ''; - $this->category_id = $model->getState('category_id'); - - $categoryList = array( - (object) array( - 'id' => 0, - 'name' => JText::_('COM_REDSHOP_SELECT_CATEGORY') - ) - ); - - if (!empty($categories)) - { - foreach ($categories as $category) - { - array_push($categoryList, $category->getItem()); - } - } - - if (count($categoryList) > 1) - { - $lists['categories'] = JHtml::_( - 'select.genericlist', - $categoryList, - 'category_id', - 'class="inputbox" onchange="javascript:setSliderMinMaxForManufactur();" ' . $disabled . ' ', - 'id', - 'name', - $this->category_id - ); - } - } - - if (count($allCategoryTemplate) > 1) - { - $lists['category_template'] = JHtml::_( - 'select.genericlist', - $allCategoryTemplate, - 'category_template', - 'class="inputbox" size="1" onchange="javascript:setSliderMinMaxForTemplate();" ' . $disabled . ' ', - 'id', - 'name', - $categoryTemplateId - ); - } - - $orderByMethod = $this->app->getUserStateFromRequest($model->context . '.order_by', 'order_by'); - $lists['order_by'] = JHtml::_( - 'select.genericlist', - $orderData, - 'order_by', - 'class="inputbox" size="1" onChange="javascript:setSliderMinMax();" ' . $disabled . ' ', - 'value', - 'text', - $orderByMethod - ); - - if ($this->catid && count($loadCategorytemplate) > 0) - { - if (strpos($loadCategorytemplate[0]->template_desc, "{product_price_slider}") !== false) - { - $ajaxSlide = $this->input->getBool('ajaxslide', false); - - if (!$ajaxSlide) - { - $strToInsert = "
    {show_all_products_in_category}
    "; - $loadCategorytemplate[0]->template_desc = str_replace("{show_all_products_in_category}", $strToInsert, $loadCategorytemplate[0]->template_desc); - - $strToInsert = "
    {pagination}
    "; - $loadCategorytemplate[0]->template_desc = str_replace("{pagination}", $strToInsert, $loadCategorytemplate[0]->template_desc); - - $strToInsert = '{product_display_limit}'; - $loadCategorytemplate[0]->template_desc = str_replace("{product_display_limit}", $strToInsert, $loadCategorytemplate[0]->template_desc); - } - - if (!empty($product)) - { - $this->productPriceSliderEnable = true; - - // Start Code for fixes IE9 issue - JHtml::_('redshopjquery.ui'); - - // End Code for fixes IE9 issue - require_once JPATH_ROOT . '/media/com_redshop/js/catprice_filter.php'; - } - else - { - $loadCategorytemplate[0]->template_desc = str_replace("{product_price_slider}", "", $loadCategorytemplate[0]->template_desc); - $loadCategorytemplate[0]->template_desc = str_replace("{pagination}", "", $loadCategorytemplate[0]->template_desc); - } - } - } - - if ((!count($product) && !$model->getState('include_sub_categories_products', false)) || - ($model->getState('include_sub_categories_products', false) && !$categories->count())) - { - if (isset($loadCategorytemplate[0]->template_desc)) { - $loadCategorytemplate[0]->template_desc = str_replace("{order_by_lbl}", "", $loadCategorytemplate[0]->template_desc); - $loadCategorytemplate[0]->template_desc = str_replace("{order_by}", "", $loadCategorytemplate[0]->template_desc); + public $app; + + public $input; + + public $state = null; + + public $productPriceSliderEnable = false; + + public $category_id; + + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise a JError object. + * + * @throws Exception + * @since 11.1 + * + * @see fetch() + */ + public function display($tpl = null) + { + $this->app = JFactory::getApplication(); + $this->input = $this->app->input; + + // Request variables + $this->option = $this->input->getString('option', 'com_redshop'); + $this->itemid = $this->input->getInt('Itemid', null); + $this->catid = $this->input->getInt('cid', 0); + $layout = $this->input->getString('layout', ''); + $this->print = $this->input->getBool('print', false); + + /** @scrutinizer ignore-call */ + $params = $this->app->getParams('com_redshop'); + /** @var RedshopModelCategory $model */ + $model = $this->getModel('category'); + $this->state = $model->get('state'); + + JPluginHelper::importPlugin('redshop_product'); + JPluginHelper::importPlugin('redshop_product_type'); + $this->dispatcher = RedshopHelperUtility::getDispatcher(); + + $menu_meta_keywords = $params->get('menu-meta_keywords'); + $menu_robots = $params->get('robots'); + $menu_meta_description = $params->get('menu-meta_description'); + + if (!$this->catid && $layout == 'detail') { + $this->catid = $params->get('cid'); + + if (!$this->catid) { + throw new InvalidArgumentException(JText::_('COM_REDSHOP_CATEGORY_NOT_FOUND'), 404); + } + + $this->setLayout('detail'); + } + + if (empty($layout) && $this->catid > 0) { + $this->setLayout('detail'); + } + + $document = JFactory::getDocument(); + JHtml::stylesheet('com_redshop/redshop.priceslider.min.css', array(), true); + + $lists = array(); + $minmax = array(0, 0); + $product = array(); + + $maincat = $model->_loadCategory(); + + $categoryTemplateId = $model->getState('category_template'); + $allCategoryTemplate = $model->getCategoryTemplate(); + $orderData = RedshopHelperUtility::getOrderByList(); + $manufacturers = $model->getManufacturer(); + $loadCategorytemplate = $model->loadCategoryTemplate($categoryTemplateId); + $detail = $model->getdata(); + + if (!empty($maincat) && !empty($maincat->canonical_url)) { + $main_url = JUri::root() . $maincat->canonical_url; + $canonical = ''; + $document->addCustomTag($canonical); + } + + $pageheadingtag = ''; + + if ($this->catid) { + // Restrict category if category not published + if ($maincat->published == 0) { + $this->setLayout('notfound'); + } + + $registry = new JRegistry; + $filterParams = $registry->loadString($maincat->product_filter_params); + + $isSlider = false; + + if ((!empty($loadCategorytemplate) && strpos( + $loadCategorytemplate[0]->template_desc, + "{include_product_in_sub_cat}" + ) !== false) + || ($filterParams->get('enable') == 1 && $filterParams->get('category_enable') == 1) + ) { + $model->setState('include_sub_categories_products', true); + $loadCategorytemplate[0]->template_desc = str_replace( + "{include_product_in_sub_cat}", + '', + $loadCategorytemplate[0]->template_desc + ); + } + + if (!empty($loadCategorytemplate) && strpos( + $loadCategorytemplate[0]->template_desc, + "{product_price_slider}" + ) !== false) { + $model->getCategoryProduct(1); + $minmax[0] = $model->getState('minprice'); + $minmax[1] = $model->getState('maxprice'); + + $isSlider = true; + $texpricemin = $this->input->getInt('texpricemin', $minmax[0]); + $texpricemax = $this->input->getInt('texpricemax', $minmax[1]); + $model->setMaxMinProductPrice(array($texpricemin, $texpricemax)); + } + + $product = $model->getCategoryProduct(0, $isSlider); + + $document->setMetaData('keywords', $maincat->metakey); + $document->setMetaData('description', $maincat->metadesc); + $document->setMetaData('robots', $maincat->metarobot_info); + + // For page title + $pagetitletag = Redshop::getConfig()->get('SEO_PAGE_TITLE_CATEGORY'); + $parentcat = ""; + $parentid = RedshopHelperProduct::getParentCategory($maincat->id); + + while ($parentid != 0) { + $parentdetail = RedshopEntityCategory::getInstance($parentid)->getItem(); + $parentcat = $parentdetail->name . " " . $parentcat; + $parentid = RedshopHelperProduct::getParentCategory($parentdetail->id); + } + + $pagetitletag = str_replace("{parentcategoryloop}", $parentcat, $pagetitletag); + $pagetitletag = str_replace("{categoryname}", $maincat->name, $pagetitletag); + $pagetitletag = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $pagetitletag); + $pagetitletag = str_replace("{categoryshortdesc}", strip_tags($maincat->short_description), $pagetitletag); + + if ($maincat->pagetitle != "" && RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig( + )->get('SEO_PAGE_TITLE_CATEGORY') != '') { + if ($maincat->append_to_global_seo == 'append') { + $pagetitletag = $pagetitletag . $maincat->pagetitle; + $document->setTitle($pagetitletag); + } elseif ($maincat->append_to_global_seo == 'prepend') { + $pagetitletag = $maincat->pagetitle . $pagetitletag; + $document->setTitle($pagetitletag); + } elseif ($maincat->append_to_global_seo == 'replace') { + $document->setTitle($maincat->pagetitle); + } + } elseif ($maincat->pagetitle != "") { + $document->setTitle($maincat->pagetitle); + } elseif (RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_TITLE_CATEGORY' + ) != '') { + $document->setTitle($pagetitletag); + } else { + $document->setTitle($this->app->getCfg('sitename')); + } + + $pagekeywordstag = ''; + + if (RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_KEYWORDS_CATEGORY' + ) != '') { + $pagekeywordstag = Redshop::getConfig()->get('SEO_PAGE_KEYWORDS_CATEGORY'); + $pagekeywordstag = str_replace("{categoryname}", $maincat->name, $pagekeywordstag); + $pagekeywordstag = str_replace( + "{categoryshortdesc}", + strip_tags($maincat->short_description), + $pagekeywordstag + ); + $pagekeywordstag = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $pagekeywordstag); + $document->setMetaData('keywords', $pagekeywordstag); + } + + if (trim($maincat->metakey) != '' + && RedShop::getConfig()->get('AUTOGENERATED_SEO') + && Redshop::getConfig()->get('SEO_PAGE_KEYWORDS_CATEGORY') != '') { + if ($maincat->append_to_global_seo == 'append') { + $pagekeywordstag .= "," . trim($maincat->metakey); + $document->setMetaData('keywords', $pagekeywordstag); + } elseif ($maincat->append_to_global_seo == 'prepend') { + $pagekeywordstag = trim($maincat->metakey) . $pagekeywordstag; + $document->setMetaData('keywords', $pagekeywordstag); + } elseif ($maincat->append_to_global_seo == 'replace') { + $document->setMetaData('keywords', $maincat->metakey); + } + } else { + if ($maincat->metakey != '') { + $document->setMetaData('keywords', $maincat->metakey); + } else { + if (RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_KEYWORDS_CATEGORY' + ) != '') { + $document->setMetaData('keywords', $pagekeywordstag); + } else { + $document->setMetaData('keywords', $maincat->name); + } + } + } + + $pagedesctag = ''; + + // For custom + auto generated description + if (RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_DESCRIPTION_CATEGORY' + ) != '') { + $pagedesctag = Redshop::getConfig()->get('SEO_PAGE_DESCRIPTION_CATEGORY'); + $pagedesctag = str_replace("{categoryname}", $maincat->name, $pagedesctag); + $pagedesctag = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $pagedesctag); + $pagedesctag = str_replace( + "{categoryshortdesc}", + strip_tags($maincat->short_description), + $pagedesctag + ); + $pagedesctag = str_replace("{categorydesc}", strip_tags($maincat->description), $pagedesctag); + } + + if ($maincat->metadesc != '' && RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_DESCRIPTION_CATEGORY' + ) != '') { + if ($maincat->append_to_global_seo == 'append') { + $pagedesctag .= $maincat->metadesc; + $document->setMetaData('description', $pagedesctag); + } elseif ($maincat->append_to_global_seo == 'prepend') { + $pagedesctag = trim($maincat->metadesc) . $pagedesctag; + $document->setMetaData('description', $pagedesctag); + } elseif ($maincat->append_to_global_seo == 'replace') { + $document->setMetaData('description', $maincat->metadesc); + } + } elseif ($maincat->metadesc != '') { + $document->setMetaData('description', $maincat->metadesc); + } else { + if (RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_DESCRIPTION_CATEGORY' + ) != '') { + $document->setMetaData('description', $pagedesctag); + } else { + $document->setMetaData('description', $maincat->name); + } + } + + // For metarobot + if ($maincat->metarobot_info != '') { + $document->setMetaData('robots', $maincat->metarobot_info); + } else { + if (RedShop::getConfig()->get('AUTOGENERATED_SEO') && JFactory::getConfig()->get('robots') != '') { + $document->setMetaData('robots', JFactory::getConfig()->get('robots')); + } else { + $document->setMetaData('robots', "INDEX,FOLLOW"); + } + } + + $pageheadingtag = str_replace( + "{categoryname}", + $maincat->name, + Redshop::getConfig()->get('SEO_PAGE_HEADING_CATEGORY') + ); + + if ($maincat->pageheading != "" && RedShop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig( + )->get('SEO_PAGE_HEADING_CATEGORY') != '') { + $pageheadingtag = $pageheadingtag . $maincat->pageheading; + } elseif ($maincat->pageheading != "") { + $pageheadingtag = $maincat->pageheading; + } else { + $pageheadingtag = $this->app->getCfg('sitename'); + } + } else { + if ($menu_meta_keywords != "") { + $document->setMetaData('keywords', $menu_meta_keywords); + } else { + $document->setMetaData('keywords', $this->app->getCfg('sitename')); + } + + if ($menu_meta_description != "") { + $document->setMetaData('description', $menu_meta_description); + } else { + $document->setMetaData('description', $this->app->getCfg('sitename')); + } + + if ($menu_robots != "") { + $document->setMetaData('robots', $menu_robots); + } else { + $document->setMetaData('robots', $this->app->getCfg('sitename')); + } + } + + // Breadcrumbs + RedshopHelperBreadcrumb::generate($this->catid); + $disabled = ""; + + if ($this->print) { + $disabled = "disabled"; + } + + $manufacturerId = $model->getState('manufacturer_id'); + + $lists['category_template'] = ""; + $lists['manufacturer'] = ""; + + if (!empty($manufacturers)) { + $temps = array( + (object)array( + 'id' => 0, + 'name' => JText::_('COM_REDSHOP_SELECT_MANUFACTURE') + ) + ); + $manufacturers = array_merge($temps, $manufacturers); + $lists['manufacturer'] = JHtml::_( + 'select.genericlist', + $manufacturers, + 'manufacturer_id', + 'class="inputbox" onchange="javascript:setSliderMinMaxForManufactur();" ' . $disabled . ' ', + 'id', + 'name', + $manufacturerId + ); + } + + $categories = new RedshopEntitiesCollection; + + if ($model->getState('include_sub_categories_products', false)) { + $categories = RedshopEntityCategory::getInstance($this->catid)->getChildCategories(); + $lists['categories'] = ''; + $this->category_id = $model->getState('category_id'); + + $categoryList = array( + (object)array( + 'id' => 0, + 'name' => JText::_('COM_REDSHOP_SELECT_CATEGORY') + ) + ); + + if (!empty($categories)) { + foreach ($categories as $category) { + array_push($categoryList, $category->getItem()); + } + } + + if (count($categoryList) > 1) { + $lists['categories'] = JHtml::_( + 'select.genericlist', + $categoryList, + 'category_id', + 'class="inputbox" onchange="javascript:setSliderMinMaxForManufactur();" ' . $disabled . ' ', + 'id', + 'name', + $this->category_id + ); + } + } + + if (count($allCategoryTemplate) > 1) { + $lists['category_template'] = JHtml::_( + 'select.genericlist', + $allCategoryTemplate, + 'category_template', + 'class="inputbox" size="1" onchange="javascript:setSliderMinMaxForTemplate();" ' . $disabled . ' ', + 'id', + 'name', + $categoryTemplateId + ); + } + + $orderByMethod = $this->app->getUserStateFromRequest($model->context . '.order_by', 'order_by'); + $lists['order_by'] = JHtml::_( + 'select.genericlist', + $orderData, + 'order_by', + 'class="inputbox" size="1" onChange="javascript:setSliderMinMax();" ' . $disabled . ' ', + 'value', + 'text', + $orderByMethod + ); + + if ($this->catid && count($loadCategorytemplate) > 0) { + if (strpos($loadCategorytemplate[0]->template_desc, "{product_price_slider}") !== false) { + $ajaxSlide = $this->input->getBool('ajaxslide', false); + + if (!$ajaxSlide) { + $strToInsert = "
    {show_all_products_in_category}
    "; + $loadCategorytemplate[0]->template_desc = str_replace( + "{show_all_products_in_category}", + $strToInsert, + $loadCategorytemplate[0]->template_desc + ); + + $strToInsert = "
    {pagination}
    "; + $loadCategorytemplate[0]->template_desc = str_replace( + "{pagination}", + $strToInsert, + $loadCategorytemplate[0]->template_desc + ); + + $strToInsert = '{product_display_limit}'; + $loadCategorytemplate[0]->template_desc = str_replace( + "{product_display_limit}", + $strToInsert, + $loadCategorytemplate[0]->template_desc + ); + } + + if (!empty($product)) { + $this->productPriceSliderEnable = true; + + // Start Code for fixes IE9 issue + JHtml::_('redshopjquery.ui'); + + // End Code for fixes IE9 issue + require_once JPATH_ROOT . '/media/com_redshop/js/catprice_filter.php'; + } else { + $loadCategorytemplate[0]->template_desc = str_replace( + "{product_price_slider}", + "", + $loadCategorytemplate[0]->template_desc + ); + $loadCategorytemplate[0]->template_desc = str_replace( + "{pagination}", + "", + $loadCategorytemplate[0]->template_desc + ); + } + } + } + + if ((!count($product) && !$model->getState('include_sub_categories_products', false)) || + ($model->getState('include_sub_categories_products', false) && !$categories->count())) { + if (isset($loadCategorytemplate[0]->template_desc)) { + $loadCategorytemplate[0]->template_desc = str_replace( + "{order_by_lbl}", + "", + $loadCategorytemplate[0]->template_desc + ); + $loadCategorytemplate[0]->template_desc = str_replace( + "{order_by}", + "", + $loadCategorytemplate[0]->template_desc + ); if (!$manufacturerId) { - $loadCategorytemplate[0]->template_desc = str_replace("{filter_by_lbl}", "", $loadCategorytemplate[0]->template_desc); - $loadCategorytemplate[0]->template_desc = str_replace("{filter_by}", "", $loadCategorytemplate[0]->template_desc); + $loadCategorytemplate[0]->template_desc = str_replace( + "{filter_by_lbl}", + "", + $loadCategorytemplate[0]->template_desc + ); + $loadCategorytemplate[0]->template_desc = str_replace( + "{filter_by}", + "", + $loadCategorytemplate[0]->template_desc + ); } } - } - - $this->detail = $detail; - $this->lists = $lists; - $this->product = $product; - $this->pageheadingtag = $pageheadingtag; - $this->params = $params; - $this->maincat = $maincat; - $this->category_template_id = $categoryTemplateId; - $this->order_by_select = $orderByMethod; - $this->manufacturer_id = $manufacturerId; - $this->loadCategorytemplate = $loadCategorytemplate; - - parent::display($tpl); - } + } + + $this->detail = $detail; + $this->lists = $lists; + $this->product = $product; + $this->pageheadingtag = $pageheadingtag; + $this->params = $params; + $this->maincat = $maincat; + $this->category_template_id = $categoryTemplateId; + $this->order_by_select = $orderByMethod; + $this->manufacturer_id = $manufacturerId; + $this->loadCategorytemplate = $loadCategorytemplate; + + parent::display($tpl); + } } diff --git a/component/site/views/checkout/tmpl/default.php b/component/site/views/checkout/tmpl/default.php index 5327bdd4dce..e9d906e4cd5 100644 --- a/component/site/views/checkout/tmpl/default.php +++ b/component/site/views/checkout/tmpl/default.php @@ -43,162 +43,169 @@ $loginTemplate = RedshopHelperTemplate::getTemplate("login"); -if (count($loginTemplate) > 0 && $loginTemplate[0]->template_desc) -{ - $loginTemplateDesc = $loginTemplate[0]->template_desc; -} -else -{ - $loginTemplateDesc = RedshopHelperTemplate::getDefaultTemplateContent('login'); +if (count($loginTemplate) > 0 && $loginTemplate[0]->template_desc) { + $loginTemplateDesc = $loginTemplate[0]->template_desc; +} else { + $loginTemplateDesc = RedshopHelperTemplate::getDefaultTemplateContent('login'); } -if (!Redshop::getConfig()->get('ONESTEP_CHECKOUT_ENABLE')) -{ - echo JLayoutHelper::render('cart.wizard', array('step' => '1')); +if (!Redshop::getConfig()->get('ONESTEP_CHECKOUT_ENABLE')) { + echo JLayoutHelper::render('cart.wizard', array('step' => '1')); } $returnUrl = JRoute::_($url . 'index.php?option=com_redshop&view=checkout', false); $returnUrl = base64_encode($returnUrl); -if ($user->id || (isset($auth['users_info_id']) && $auth['users_info_id'] > 0)) -{ - echo $this->loadTemplate('address'); -} -else -{ - if (!$user->id && Redshop::getConfig()->get('REGISTER_METHOD') != 1) - { - $showLogin = 1; - $openToMystretchermy = 0; - } - else - { - $showLogin = 0; - $openToMystretchermy = 1; - } - - if (Redshop::getConfig()->get('NEW_CUSTOMER_SELECTION') || (isset($post['createaccount']) && $post['createaccount'] == 1)) - { - $openToMystretchermy = 1; - } - - if ($showLogin) - { - echo '
    '; - echo JHtml::_(Redshop::getConfig()->get('CHECKOUT_LOGIN_REGISTER_SWITCHER') . '.start', 'signInPane', array('startOffset' => $openToMystretchermy)); - echo JHtml::_(Redshop::getConfig()->get('CHECKOUT_LOGIN_REGISTER_SWITCHER') . '.panel', JText::_('COM_REDSHOP_RETURNING_CUSTOMERS'), 'login'); - - $loginTemplateDesc = RedshopTagsReplacer::_( - 'login', - $loginTemplateDesc, - array( - 'returnUrl' => $returnUrl, - 'Itemid' => $itemId - ) - ); - - echo eval("?>" . $loginTemplateDesc . "get('CHECKOUT_LOGIN_REGISTER_SWITCHER') . '.panel', JText::_('COM_REDSHOP_NEW_CUSTOMERS'), 'registration'); - } - - $allowCustomer = $this->lists['allowCustomer']; - $allowCompany = $this->lists['allowCompany']; - $isCompany = $this->lists['is_company']; - ?> +if ($user->id || (isset($auth['users_info_id']) && $auth['users_info_id'] > 0)) { + echo $this->loadTemplate('address'); +} else { + if (!$user->id && Redshop::getConfig()->get('REGISTER_METHOD') != 1) { + $showLogin = 1; + $openToMystretchermy = 0; + } else { + $showLogin = 0; + $openToMystretchermy = 1; + } + + if (Redshop::getConfig()->get( + 'NEW_CUSTOMER_SELECTION' + ) || (isset($post['createaccount']) && $post['createaccount'] == 1)) { + $openToMystretchermy = 1; + } + + if ($showLogin) { + echo '
    '; + echo JHtml::_( + Redshop::getConfig()->get('CHECKOUT_LOGIN_REGISTER_SWITCHER') . '.start', + 'signInPane', + array('startOffset' => $openToMystretchermy) + ); + echo JHtml::_( + Redshop::getConfig()->get('CHECKOUT_LOGIN_REGISTER_SWITCHER') . '.panel', + JText::_('COM_REDSHOP_RETURNING_CUSTOMERS'), + 'login' + ); + + $loginTemplateDesc = RedshopTagsReplacer::_( + 'login', + $loginTemplateDesc, + array( + 'returnUrl' => $returnUrl, + 'Itemid' => $itemId + ) + ); + + echo eval("?>" . $loginTemplateDesc . "get('CHECKOUT_LOGIN_REGISTER_SWITCHER') . '.panel', + JText::_('COM_REDSHOP_NEW_CUSTOMERS'), + 'registration' + ); + } + + $allowCustomer = $this->lists['allowCustomer']; + $allowCompany = $this->lists['allowCompany']; + $isCompany = $this->lists['is_company']; + ?>
    - 0 && $teleSearch[0]->enabled) : ?> + 0 && $teleSearch[0]->enabled) : ?> -
    +
    - -
    + +
    - - + +
    - get('REGISTER_METHOD') == 2) : - $checked_style = (Redshop::getConfig()->get('CREATE_ACCOUNT_CHECKBOX') == 1) ? 'checked="checked"' : "''"; - ?> + get('REGISTER_METHOD') == 2) : + $checked_style = (Redshop::getConfig()->get( + 'CREATE_ACCOUNT_CHECKBOX' + ) == 1) ? 'checked="checked"' : "''"; + ?>
    - +
    - lists, Redshop::getConfig()->get('OPTIONAL_SHIPPING_ADDRESS'), 1, Redshop::getConfig()->get('CREATE_ACCOUNT_CHECKBOX')); ?> + lists, + Redshop::getConfig()->get('OPTIONAL_SHIPPING_ADDRESS'), + 1, + Redshop::getConfig()->get('CREATE_ACCOUNT_CHECKBOX') + ); ?>
    - get('SHIPPING_METHOD_ENABLE')) : ?> - - 0) - { - if (isset($post['billisship']) && $post['billisship'] == 1) - { - $billingIsShipping = "style='display:none'"; - } - } - elseif (Redshop::getConfig()->get('OPTIONAL_SHIPPING_ADDRESS')) - { - $billingIsShipping = "style='display:none'"; - } - ?> - -
    > -
    - - $post, - 'isCompany' => $isCompany, - 'lists' => $this->lists - ) - ); - ?> -
    -
    - - - - + get('SHIPPING_METHOD_ENABLE')) : ?> + + 0) { + if (isset($post['billisship']) && $post['billisship'] == 1) { + $billingIsShipping = "style='display:none'"; + } + } elseif (Redshop::getConfig()->get('OPTIONAL_SHIPPING_ADDRESS')) { + $billingIsShipping = "style='display:none'"; + } + ?> + +
    > +
    + + $post, + 'isCompany' => $isCompany, + 'lists' => $this->lists + ) + ); + ?> +
    +
    + + + +
    - get('CHECKOUT_LOGIN_REGISTER_SWITCHER') . '.end'); - echo '
    '; - } + get('CHECKOUT_LOGIN_REGISTER_SWITCHER') . '.end'); + echo '
    '; + } } ?> diff --git a/component/site/views/giftcard/view.html.php b/component/site/views/giftcard/view.html.php index a95666cdd6f..459a8721398 100644 --- a/component/site/views/giftcard/view.html.php +++ b/component/site/views/giftcard/view.html.php @@ -15,24 +15,25 @@ class RedshopViewGiftcard extends RedshopView { /** - * @param null $tpl + * @param null $tpl + * * @return mixed|void * @throws Exception */ - public function display($tpl = null) - { - $app = JFactory::getApplication(); + public function display($tpl = null) + { + $app = JFactory::getApplication(); - // Request variables - $params = $app->getParams('com_redshop'); - $pageHeadingTag = JText::_('COM_REDSHOP_REDSHOP'); - $model = $this->getModel('giftcard'); - $giftCardTemplate = $model->getGiftcardTemplate(); - $detail = $this->get('data'); - $this->detail = $detail; - $this->template = $giftCardTemplate; - $this->pageheadingtag = $pageHeadingTag; - $this->params = $params; - parent::display($tpl); - } + // Request variables + $params = $app->getParams('com_redshop'); + $pageHeadingTag = JText::_('COM_REDSHOP_REDSHOP'); + $model = $this->getModel('giftcard'); + $giftCardTemplate = $model->getGiftcardTemplate(); + $detail = $this->get('data'); + $this->detail = $detail; + $this->template = $giftCardTemplate; + $this->pageheadingtag = $pageHeadingTag; + $this->params = $params; + parent::display($tpl); + } } diff --git a/component/site/views/login/tmpl/default.php b/component/site/views/login/tmpl/default.php index 80a015f1928..3cbea04383c 100644 --- a/component/site/views/login/tmpl/default.php +++ b/component/site/views/login/tmpl/default.php @@ -14,13 +14,10 @@ $loginlink = 'index.php?option=com_redshop&view=login&Itemid=' . $Itemid; $mywishlist = $app->input->getString('wishlist'); -if ($mywishlist != '') -{ - $newuser_link = 'index.php?wishlist=' . $mywishlist . '&option=com_redshop&view=registration&Itemid=' . $Itemid; -} -else -{ - $newuser_link = 'index.php?option=com_redshop&view=registration&Itemid=' . $Itemid; +if ($mywishlist != '') { + $newuser_link = 'index.php?wishlist=' . $mywishlist . '&option=com_redshop&view=registration&Itemid=' . $Itemid; +} else { + $newuser_link = 'index.php?option=com_redshop&view=registration&Itemid=' . $Itemid; } $params = $app->getParams('com_redshop'); @@ -28,37 +25,38 @@ ?> - - - - - - - + + + + + + + diff --git a/component/site/views/login/tmpl/default.xml b/component/site/views/login/tmpl/default.xml index beb09c251d4..23bb815c3da 100644 --- a/component/site/views/login/tmpl/default.xml +++ b/component/site/views/login/tmpl/default.xml @@ -9,10 +9,10 @@
    + label="COM_REDSHOP_LOGIN_REDIRECTION_PAGE" description="COM_REDSHOP_PARAMLOGINREDIRECTURL"/> + label="COM_REDSHOP_LOGOUT_REDIRECTION_PAGE" + description="COM_REDSHOP_PARAMLOGOUTREDIRECTURL"/>
    \ No newline at end of file diff --git a/component/site/views/login/tmpl/logout.php b/component/site/views/login/tmpl/logout.php index 1aac1663c47..46ae0a07925 100644 --- a/component/site/views/login/tmpl/logout.php +++ b/component/site/views/login/tmpl/logout.php @@ -18,25 +18,26 @@ $returnitemid = $params->get('logout', $Itemid); ?>
    - - - - - id > 0) : ?> - - - - -
    -

    id > 0) - echo JText::_('COM_REDSHOP_LOGOUT_DESCRIPTION'); - else - echo JText::_('COM_REDSHOP_LOGOUT_SUCCESS'); - ?>

    -
    + + + + + id > 0) : ?> + + + + +
    +

    id > 0) { + echo JText::_('COM_REDSHOP_LOGOUT_DESCRIPTION'); + } else { + echo JText::_('COM_REDSHOP_LOGOUT_SUCCESS'); + } + ?>

    +
    - - + +
    diff --git a/component/site/views/login/tmpl/portal.php b/component/site/views/login/tmpl/portal.php index 0965adf1fed..093da042584 100644 --- a/component/site/views/login/tmpl/portal.php +++ b/component/site/views/login/tmpl/portal.php @@ -17,89 +17,86 @@ $returnitemid = $Itemid; -if (Redshop::getConfig()->get('PORTAL_LOGIN_ITEMID')) -{ - $returnitemid = Redshop::getConfig()->get('PORTAL_LOGIN_ITEMID'); +if (Redshop::getConfig()->get('PORTAL_LOGIN_ITEMID')) { + $returnitemid = Redshop::getConfig()->get('PORTAL_LOGIN_ITEMID'); } $portallogofile = REDSHOP_FRONT_IMAGES_RELPATH . 'shopperlogo/' . Redshop::getConfig()->get('DEFAULT_PORTAL_LOGO'); -$portallogo = RedshopHelperMedia::getImagePath( - Redshop::getConfig()->get('DEFAULT_PORTAL_LOGO'), - '', - 'thumb', - 'shopperlogo', - Redshop::getConfig()->get('THUMB_WIDTH'), - Redshop::getConfig()->get('THUMB_HEIGHT'), - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') - ); -$portalname = Redshop::getConfig()->get('DEFAULT_PORTAL_NAME'); +$portallogo = RedshopHelperMedia::getImagePath( + Redshop::getConfig()->get('DEFAULT_PORTAL_LOGO'), + '', + 'thumb', + 'shopperlogo', + Redshop::getConfig()->get('THUMB_WIDTH'), + Redshop::getConfig()->get('THUMB_HEIGHT'), + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') +); +$portalname = Redshop::getConfig()->get('DEFAULT_PORTAL_NAME'); $portalintro = ""; -if ($shoppergroupid != 0) -{ - $portallogo = RedshopHelperMedia::getImagePath( - $this->ShopperGroupDetail[0]->shopper_group_logo, - '', - 'thumb', - 'shopperlogo', - Redshop::getConfig()->get('THUMB_WIDTH'), - Redshop::getConfig()->get('THUMB_HEIGHT'), - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') - ); - $portalname = $this->ShopperGroupDetail[0]->shopper_group_name; - $portalintro = $this->ShopperGroupDetail[0]->shopper_group_introtext; +if ($shoppergroupid != 0) { + $portallogo = RedshopHelperMedia::getImagePath( + $this->ShopperGroupDetail[0]->shopper_group_logo, + '', + 'thumb', + 'shopperlogo', + Redshop::getConfig()->get('THUMB_WIDTH'), + Redshop::getConfig()->get('THUMB_HEIGHT'), + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') + ); + $portalname = $this->ShopperGroupDetail[0]->shopper_group_name; + $portalintro = $this->ShopperGroupDetail[0]->shopper_group_introtext; } ?>
    - - - - - - - - - - - - - - - - - - - -
    - - - -
    - -
    - -
    - - -
    - - -
    - - - - + + + + + + + + + + + + + + + + + + + +
    + + + +
    + +
    + +
    + + +
    + + +
    + + + +
     
    diff --git a/component/site/views/login/tmpl/portals.php b/component/site/views/login/tmpl/portals.php index 06c54c5c01c..060eb7a8e8b 100644 --- a/component/site/views/login/tmpl/portals.php +++ b/component/site/views/login/tmpl/portals.php @@ -13,7 +13,7 @@ $app = JFactory::getApplication(); -$user = JFactory::getUser(); +$user = JFactory::getUser(); $params = $app->getParams('com_redshop'); $Itemid = $app->input->getInt('Itemid'); @@ -21,39 +21,38 @@ $returnitemid = $params->get('logout', $Itemid); // Get redshop login module -if ($module = JModuleHelper::getModule('redshop_login')) -{ - // Get redshop login module params - if ($module->params != "") - { - $moduleparams = new JRegistry($module->params); - - // Set return Itemid for logout - $returnitemid = $moduleparams->get('logout', $returnitemid); - } +if ($module = JModuleHelper::getModule('redshop_login')) { + // Get redshop login module params + if ($module->params != "") { + $moduleparams = new JRegistry($module->params); + + // Set return Itemid for logout + $returnitemid = $moduleparams->get('logout', $returnitemid); + } } ?>
    - - ShopperGroupDetail[0])) : ?> - - - - - - - - - - -
    -

    ShopperGroupDetail[0]->shopper_group_name; ?>

    -
    - ShopperGroupDetail[0]->shopper_group_introtext; ?> -
    -
    - - + + ShopperGroupDetail[0])) : ?> + + + + + + + + + + +
    +

    ShopperGroupDetail[0]->shopper_group_name; ?>

    +
    + ShopperGroupDetail[0]->shopper_group_introtext; ?> +
    +
    + +
    diff --git a/component/site/views/login/view.html.php b/component/site/views/login/view.html.php index 3c6890f1ded..c23a7708b15 100644 --- a/component/site/views/login/view.html.php +++ b/component/site/views/login/view.html.php @@ -12,52 +12,42 @@ class RedshopViewLogin extends RedshopView { - public function display($tpl = null) - { - $app = JFactory::getApplication(); - $user = JFactory::getUser(); - - $model = $this->getModel(); - - $shoppergroupid = $app->input->getInt('protalid', 0); - - $ShopperGroupDetail = $model->ShopperGroupDetail($shoppergroupid); - - $layout = $app->input->getCmd('layout', ''); - - $check = $model->CheckShopperGroup($user->username, $shoppergroupid); - - if ($layout == 'portal' || Redshop::getConfig()->get('PORTAL_SHOP') == 1) - { - isset($ShopperGroupDetail[0]->shopper_group_portal) ? $portal = $ShopperGroupDetail[0]->shopper_group_portal : $portal = 0; - - if ($portal == 1 || Redshop::getConfig()->get('PORTAL_SHOP') == 1) - { - if ($user->id != "") - { - $this->setLayout('portals'); - } - else - { - $this->setLayout('portal'); - } - } - else - { - $app->enqueuemessage(JText::_('COM_REDSHOP_SHOPPER_GROUP_PORTAL_IS_DISABLE')); - $app->redirect(JRoute::_('index.php?option=com_redshop')); - } - } - else - { - if ($user->id != "") - { - $this->setLayout('logout'); - } - } - - $this->ShopperGroupDetail = $ShopperGroupDetail; - $this->check = $check; - parent::display($tpl); - } + public function display($tpl = null) + { + $app = JFactory::getApplication(); + $user = JFactory::getUser(); + + $model = $this->getModel(); + + $shoppergroupid = $app->input->getInt('protalid', 0); + + $ShopperGroupDetail = $model->ShopperGroupDetail($shoppergroupid); + + $layout = $app->input->getCmd('layout', ''); + + $check = $model->CheckShopperGroup($user->username, $shoppergroupid); + + if ($layout == 'portal' || Redshop::getConfig()->get('PORTAL_SHOP') == 1) { + isset($ShopperGroupDetail[0]->shopper_group_portal) ? $portal = $ShopperGroupDetail[0]->shopper_group_portal : $portal = 0; + + if ($portal == 1 || Redshop::getConfig()->get('PORTAL_SHOP') == 1) { + if ($user->id != "") { + $this->setLayout('portals'); + } else { + $this->setLayout('portal'); + } + } else { + $app->enqueuemessage(JText::_('COM_REDSHOP_SHOPPER_GROUP_PORTAL_IS_DISABLE')); + $app->redirect(JRoute::_('index.php?option=com_redshop')); + } + } else { + if ($user->id != "") { + $this->setLayout('logout'); + } + } + + $this->ShopperGroupDetail = $ShopperGroupDetail; + $this->check = $check; + parent::display($tpl); + } } diff --git a/component/site/views/manufacturers/tmpl/default.php b/component/site/views/manufacturers/tmpl/default.php index 0638937556e..8c35124dad1 100644 --- a/component/site/views/manufacturers/tmpl/default.php +++ b/component/site/views/manufacturers/tmpl/default.php @@ -13,46 +13,38 @@ // Page Title Start $pageTitle = JText::_('COM_REDSHOP_MANUFACTURER'); -if ($this->pageheadingtag != '') -{ - $pageTitle = $this->pageheadingtag; +if ($this->pageheadingtag != '') { + $pageTitle = $this->pageheadingtag; } ?> -

    - params->get('show_page_heading', 1)) - { - if ($this->params->get('page_title') != $pageTitle) - { - echo $this->escape($this->params->get('page_title')); - } - else - { - echo $pageTitle; - } - } ?> -

    +

    + params->get('show_page_heading', 1)) { + if ($this->params->get('page_title') != $pageTitle) { + echo $this->escape($this->params->get('page_title')); + } else { + echo $pageTitle; + } + } ?> +

    0 && $manufacturersTemplate[0]->template_desc != "") -{ - $templateDesc = $manufacturersTemplate[0]->template_desc; -} -else -{ - $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('manufacturer'); +if (count($manufacturersTemplate) > 0 && $manufacturersTemplate[0]->template_desc != "") { + $templateDesc = $manufacturersTemplate[0]->template_desc; +} else { + $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('manufacturer'); } $templateDesc = RedshopTagsReplacer::_( - 'manufacturer', - $templateDesc, - array( - 'detail' => $this->detail, - 'pagination' => $this->pagination, - 'params' => $this->params, - 'lists' => $this->lists - ) + 'manufacturer', + $templateDesc, + array( + 'detail' => $this->detail, + 'pagination' => $this->pagination, + 'params' => $this->params, + 'lists' => $this->lists + ) ); diff --git a/component/site/views/manufacturers/tmpl/detail.php b/component/site/views/manufacturers/tmpl/detail.php index 187faa5a993..fbb8968d703 100644 --- a/component/site/views/manufacturers/tmpl/detail.php +++ b/component/site/views/manufacturers/tmpl/detail.php @@ -14,19 +14,19 @@ $manufacturerTemplate = RedshopHelperTemplate::getTemplate('manufacturer_detail'); if (count($manufacturerTemplate) > 0 && $manufacturerTemplate[0]->template_desc != "") { - $templateHtml = $manufacturerTemplate[0]->template_desc; - $templateId = $manufacturerTemplate[0]->id; + $templateHtml = $manufacturerTemplate[0]->template_desc; + $templateId = $manufacturerTemplate[0]->id; } else { - $templateHtml = RedshopHelperTemplate::getDefaultTemplateContent('manufacturer_detail'); - $templateId = 0; + $templateHtml = RedshopHelperTemplate::getDefaultTemplateContent('manufacturer_detail'); + $templateId = 0; } echo RedshopTagsReplacer::_( - 'manufacturerdetail', - $templateHtml, - [ - 'params' => $this->params, - 'pageHeadingTag' => $this->pageheadingtag, - 'detail' => $this->detail - ] + 'manufacturerdetail', + $templateHtml, + [ + 'params' => $this->params, + 'pageHeadingTag' => $this->pageheadingtag, + 'detail' => $this->detail + ] ); diff --git a/component/site/views/manufacturers/tmpl/detail.xml b/component/site/views/manufacturers/tmpl/detail.xml index 3cdf97f2f0c..e8984048028 100644 --- a/component/site/views/manufacturers/tmpl/detail.xml +++ b/component/site/views/manufacturers/tmpl/detail.xml @@ -10,7 +10,7 @@
    - template_id); if (count($manufacturerTemplate) > 0 && $manufacturerTemplate[0]->template_desc) { - $templateDesc = $manufacturerTemplate[0]->template_desc; - $templateId = $manufacturerTemplate[0]->id; + $templateDesc = $manufacturerTemplate[0]->template_desc; + $templateId = $manufacturerTemplate[0]->id; } else { - $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('manufacturer_products'); - $templateId = 0; + $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('manufacturer_products'); + $templateId = 0; } @@ -27,13 +27,13 @@ $model = $this->getModel('manufacturers'); echo RedshopTagsReplacer::_( - 'manufacturerproduct', - $templateDesc, - [ - 'params' => $this->params, - 'manufacturerProducts' => $model->getManufacturerProducts($templateDesc), - 'manufacturer' => $manufacturer, - 'pagination' => $model->getProductPagination(), - 'lists' => $this->lists - ] + 'manufacturerproduct', + $templateDesc, + [ + 'params' => $this->params, + 'manufacturerProducts' => $model->getManufacturerProducts($templateDesc), + 'manufacturer' => $manufacturer, + 'pagination' => $model->getProductPagination(), + 'lists' => $this->lists + ] ); diff --git a/component/site/views/manufacturers/tmpl/products.xml b/component/site/views/manufacturers/tmpl/products.xml index d90193642dc..5b7884d102c 100644 --- a/component/site/views/manufacturers/tmpl/products.xml +++ b/component/site/views/manufacturers/tmpl/products.xml @@ -8,13 +8,13 @@
    - - - + + +
    diff --git a/component/site/views/manufacturers/view.html.php b/component/site/views/manufacturers/view.html.php index ded4ac6b1ed..29ac83a5b13 100644 --- a/component/site/views/manufacturers/view.html.php +++ b/component/site/views/manufacturers/view.html.php @@ -16,275 +16,266 @@ */ class RedshopViewManufacturers extends RedshopView { - /** - * Display - * - * @param string $tpl Template - * - * @return void - * @throws Exception - */ - public function display($tpl = null) - { - $app = JFactory::getApplication(); - $document = JFactory::getDocument(); - $print = $app->input->getInt('print'); - $layout = $app->input->getCmd('layout', 'default'); - $params = $app->getParams('com_redshop'); - $itemId = $app->input->getInt('itemid', null); - - $mid = 0; - $lists = array(); - - /** @var RedshopModelManufacturers $model */ - $model = $this->getModel('manufacturers'); - $detail = $this->get('data'); - $limit = $params->get('maxproduct'); - - $detail = array_filter(array_values($detail)); - - if (!$limit && !empty($detail)) - { - $limit = $detail[0]->product_per_page; - } - - $model->setProductLimit($limit); - $pageheadingtag = ''; - $disabled = ""; - - if ($print) - { - $disabled = "disabled"; - } - - if ($layout != 'default') - { - $manufacturer = !empty($detail) && !empty($detail[0]) ? $detail[0] : null; - - if (null !== $manufacturer && $manufacturer->id) - { - $mid = $manufacturer->id; - - $document->setMetaData('robots', $manufacturer->metarobot_info); - - // For page title - - if (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_TITLE_MANUFACTUR') != '') - { - $pagetitletag = Redshop::getConfig()->get('SEO_PAGE_TITLE_MANUFACTUR'); - $pagetitletag = str_replace("{manufacturer}", $manufacturer->name, $pagetitletag); - $pagetitletag = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $pagetitletag); - } - - if ($manufacturer->pagetitle != '' - && Redshop::getConfig()->get('AUTOGENERATED_SEO') - && Redshop::getConfig()->get('SEO_PAGE_TITLE_MANUFACTUR') != '') - { - $pagetitletag = $pagetitletag . " " . $manufacturer->pagetitle; - $document->setTitle($pagetitletag); - } - else - { - if ($manufacturer->pagetitle != '') - { - $pagetitletag = $manufacturer->pagetitle; - $document->setTitle($manufacturer->pagetitle); - } - elseif (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_TITLE_MANUFACTUR') != '') - { - $document->setTitle($pagetitletag); - } - else - { - $pagetitletag = $app->getCfg('sitename'); - $document->setTitle($app->getCfg('sitename')); - } - } - - $template = RedshopEntityTemplate::getInstance($detail[0]->template_id)->getItem(); - $layout = $template->section == 'manufacturer_products' ? 'products' : $layout; - - if ($layout == 'products') - { - $pagetitletag = JText::_("COM_REDSHOP_MANUFACTURER_PRODUCT") . " " . $pagetitletag; - $document->setTitle($pagetitletag); - } - - // For meta keyword - if (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_KEYWORDS_MANUFACTUR') != '') - { - $pagekeywordstag = Redshop::getConfig()->get('SEO_PAGE_KEYWORDS_MANUFACTUR'); - $pagekeywordstag = str_replace("{manufacturer}", $manufacturer->name, $pagekeywordstag); - $pagekeywordstag = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $pagekeywordstag); - } - - if ($manufacturer->metakey != '' - && Redshop::getConfig()->get('AUTOGENERATED_SEO') - && Redshop::getConfig()->get('SEO_PAGE_KEYWORDS_MANUFACTUR') != '') - { - $pagekeywordstag = $pagekeywordstag . ", " . $manufacturer->metakey; - $document->setMetaData('keywords', $pagekeywordstag); - } - else - { - if ($manufacturer->metakey != '') - { - $document->setMetaData('keywords', $manufacturer->metakey); - } - elseif (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_KEYWORDS_MANUFACTUR') != '') - { - $document->setMetaData('keywords', $pagekeywordstag); - } - else - { - $document->setMetaData('keywords', $manufacturer->name); - } - } - - // For meta description - if (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_DESCRIPTION_MANUFACTUR') != '') - { - $pagedesctag = Redshop::getConfig()->get('SEO_PAGE_DESCRIPTION_MANUFACTUR'); - $pagedesctag = str_replace("{manufacturer}", $manufacturer->name, $pagedesctag); - $pagedesctag = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $pagedesctag); - } - - if ($manufacturer->metadesc != '' - && Redshop::getConfig()->get('AUTOGENERATED_SEO') - && Redshop::getConfig()->get('SEO_PAGE_DESCRIPTION_MANUFACTUR') != '') - { - $pagedesctag = $pagedesctag . " " . $manufacturer->metadesc; - $document->setMetaData('description', $pagedesctag); - } - else - { - if ($manufacturer->metadesc != '') - { - $document->setMetaData('description', $manufacturer->metadesc); - } - elseif (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_DESCRIPTION_MANUFACTUR') != '') - { - $document->setMetaData('description', $pagedesctag); - } - else - { - $document->setMetaData('description', $manufacturer->name); - } - } - - if ($manufacturer->metarobot_info != '') - { - $document->setMetaData('robots', $manufacturer->metarobot_info); - } - else - { - if (Redshop::getConfig()->get('AUTOGENERATED_SEO') && JFactory::getConfig()->get('robots') != '') - { - $document->setMetaData('robots', JFactory::getConfig()->get('robots')); - } - else - { - $document->setMetaData('robots', "INDEX,FOLLOW"); - } - } - - // For page heading - if (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_HEADING_MANUFACTUR') != '') - { - $pageheadingtag = Redshop::getConfig()->get('SEO_PAGE_HEADING_MANUFACTUR'); - $pageheadingtag = str_replace("{manufacturer}", $manufacturer->name, $pageheadingtag); - } - - if (trim($manufacturer->pageheading) != '' - && Redshop::getConfig()->get('AUTOGENERATED_SEO') - && Redshop::getConfig()->get('SEO_PAGE_HEADING_MANUFACTUR') != '') - { - $pageheadingtag = $pageheadingtag . " " . $manufacturer->pageheading; - } - else - { - if (trim($manufacturer->pageheading) != '') - { - $pageheadingtag = $manufacturer->pageheading; - } - elseif (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_HEADING_MANUFACTUR') != '') - { - $pageheadingtag = $pageheadingtag; - } - } - - // FOr Canonical In Manufacturer Page - if (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get('SEO_PAGE_CANONICAL_MANUFACTUR') != '' && $layout != "products") - { - $canonicalurl = Redshop::getConfig()->get('SEO_PAGE_CANONICAL_MANUFACTUR'); - - $manufacturer_products_url = substr_replace(JURI::root(), "", -1) - . JRoute::_('index.php?option=com_redshop&view=manufacturers&layout=products&mid=' . $manufacturer->id . '&Itemid=' . $itemId); - $canonicalurl_content = ''; - $canonicalurl = str_replace("{manufacturerproductslink}", $canonicalurl_content, $canonicalurl); - $document->addCustomTag($canonicalurl); - } - } - else - { - $document->setMetaData('keywords', $app->getCfg('sitename')); - $document->setMetaData('description', $app->getCfg('sitename')); - $document->setMetaData('robots', $app->getCfg('sitename')); - } - - $this->setLayout($layout); - } - - // Breadcrumbs - RedshopHelperBreadcrumb::generate($mid); - - // Breadcrumbs end - - if ($layout == "products") - { - $filter_order = $params->get('order_by', Redshop::getConfig()->get('DEFAULT_MANUFACTURER_PRODUCT_ORDERING_METHOD')); - $order_by_select = $app->input->getString('order_by', $filter_order); - $order_data = RedshopHelperUtility::getOrderByList(); - } - else - { - $filter_order = $params->get('order_by', Redshop::getConfig()->get('DEFAULT_MANUFACTURER_ORDERING_METHOD')); - - if ($app->input->getString('order_by', '') != null) - { - $order_by_select = $app->input->getString('order_by', ''); - } - elseif ($app->getUserState('com_redshop.manufacturers.default.order_state') != null) - { - $order_by_select = $app->getUserState('com_redshop.manufacturers.default.order_state'); - } - else - { - $order_by_select = $filter_order; - } - - $order_data = RedshopHelperUtility::getManufacturerOrderByList(); - } - - $lists['order_select'] = JHTML::_('select.genericlist', $order_data, 'order_by', 'class="inputbox" size="1" onchange="document.orderby_form.submit();" ' . $disabled . ' ', 'value', 'text', $order_by_select); - - $categorylist = $model->getCategoryList(); - - $temps = array(); - $temps[0] = new StdClass; - $temps[0]->value = "0"; - $temps[0]->text = JText::_('COM_REDSHOP_SELECT'); - $categorylist = array_merge($temps, $categorylist); - $filter_by_select = $app->input->getString('filter_by', 0); - $lists['filter_select'] = JHTML::_('select.genericlist', $categorylist, 'filter_by', 'class="inputbox" size="1" onchange="document.filter_form.submit();" ' . $disabled . ' ', 'value', 'text', $filter_by_select); - - $pagination = $this->get('Pagination'); - - $this->detail = $detail; - $this->lists = $lists; - $this->pagination = $pagination; - $this->pageheadingtag = $pageheadingtag; - $this->params = $params; - parent::display($tpl); - } + /** + * Display + * + * @param string $tpl Template + * + * @return void + * @throws Exception + */ + public function display($tpl = null) + { + $app = JFactory::getApplication(); + $document = JFactory::getDocument(); + $print = $app->input->getInt('print'); + $layout = $app->input->getCmd('layout', 'default'); + $params = $app->getParams('com_redshop'); + $itemId = $app->input->getInt('itemid', null); + + $mid = 0; + $lists = array(); + + /** @var RedshopModelManufacturers $model */ + $model = $this->getModel('manufacturers'); + $detail = $this->get('data'); + $limit = $params->get('maxproduct'); + + $detail = array_filter(array_values($detail)); + + if (!$limit && !empty($detail)) { + $limit = $detail[0]->product_per_page; + } + + $model->setProductLimit($limit); + $pageheadingtag = ''; + $disabled = ""; + + if ($print) { + $disabled = "disabled"; + } + + if ($layout != 'default') { + $manufacturer = !empty($detail) && !empty($detail[0]) ? $detail[0] : null; + + if (null !== $manufacturer && $manufacturer->id) { + $mid = $manufacturer->id; + + $document->setMetaData('robots', $manufacturer->metarobot_info); + + // For page title + + if (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_TITLE_MANUFACTUR' + ) != '') { + $pagetitletag = Redshop::getConfig()->get('SEO_PAGE_TITLE_MANUFACTUR'); + $pagetitletag = str_replace("{manufacturer}", $manufacturer->name, $pagetitletag); + $pagetitletag = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $pagetitletag); + } + + if ($manufacturer->pagetitle != '' + && Redshop::getConfig()->get('AUTOGENERATED_SEO') + && Redshop::getConfig()->get('SEO_PAGE_TITLE_MANUFACTUR') != '') { + $pagetitletag = $pagetitletag . " " . $manufacturer->pagetitle; + $document->setTitle($pagetitletag); + } else { + if ($manufacturer->pagetitle != '') { + $pagetitletag = $manufacturer->pagetitle; + $document->setTitle($manufacturer->pagetitle); + } elseif (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_TITLE_MANUFACTUR' + ) != '') { + $document->setTitle($pagetitletag); + } else { + $pagetitletag = $app->getCfg('sitename'); + $document->setTitle($app->getCfg('sitename')); + } + } + + $template = RedshopEntityTemplate::getInstance($detail[0]->template_id)->getItem(); + $layout = $template->section == 'manufacturer_products' ? 'products' : $layout; + + if ($layout == 'products') { + $pagetitletag = JText::_("COM_REDSHOP_MANUFACTURER_PRODUCT") . " " . $pagetitletag; + $document->setTitle($pagetitletag); + } + + // For meta keyword + if (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_KEYWORDS_MANUFACTUR' + ) != '') { + $pagekeywordstag = Redshop::getConfig()->get('SEO_PAGE_KEYWORDS_MANUFACTUR'); + $pagekeywordstag = str_replace("{manufacturer}", $manufacturer->name, $pagekeywordstag); + $pagekeywordstag = str_replace( + "{shopname}", + Redshop::getConfig()->get('SHOP_NAME'), + $pagekeywordstag + ); + } + + if ($manufacturer->metakey != '' + && Redshop::getConfig()->get('AUTOGENERATED_SEO') + && Redshop::getConfig()->get('SEO_PAGE_KEYWORDS_MANUFACTUR') != '') { + $pagekeywordstag = $pagekeywordstag . ", " . $manufacturer->metakey; + $document->setMetaData('keywords', $pagekeywordstag); + } else { + if ($manufacturer->metakey != '') { + $document->setMetaData('keywords', $manufacturer->metakey); + } elseif (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_KEYWORDS_MANUFACTUR' + ) != '') { + $document->setMetaData('keywords', $pagekeywordstag); + } else { + $document->setMetaData('keywords', $manufacturer->name); + } + } + + // For meta description + if (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_DESCRIPTION_MANUFACTUR' + ) != '') { + $pagedesctag = Redshop::getConfig()->get('SEO_PAGE_DESCRIPTION_MANUFACTUR'); + $pagedesctag = str_replace("{manufacturer}", $manufacturer->name, $pagedesctag); + $pagedesctag = str_replace("{shopname}", Redshop::getConfig()->get('SHOP_NAME'), $pagedesctag); + } + + if ($manufacturer->metadesc != '' + && Redshop::getConfig()->get('AUTOGENERATED_SEO') + && Redshop::getConfig()->get('SEO_PAGE_DESCRIPTION_MANUFACTUR') != '') { + $pagedesctag = $pagedesctag . " " . $manufacturer->metadesc; + $document->setMetaData('description', $pagedesctag); + } else { + if ($manufacturer->metadesc != '') { + $document->setMetaData('description', $manufacturer->metadesc); + } elseif (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_DESCRIPTION_MANUFACTUR' + ) != '') { + $document->setMetaData('description', $pagedesctag); + } else { + $document->setMetaData('description', $manufacturer->name); + } + } + + if ($manufacturer->metarobot_info != '') { + $document->setMetaData('robots', $manufacturer->metarobot_info); + } else { + if (Redshop::getConfig()->get('AUTOGENERATED_SEO') && JFactory::getConfig()->get('robots') != '') { + $document->setMetaData('robots', JFactory::getConfig()->get('robots')); + } else { + $document->setMetaData('robots', "INDEX,FOLLOW"); + } + } + + // For page heading + if (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_HEADING_MANUFACTUR' + ) != '') { + $pageheadingtag = Redshop::getConfig()->get('SEO_PAGE_HEADING_MANUFACTUR'); + $pageheadingtag = str_replace("{manufacturer}", $manufacturer->name, $pageheadingtag); + } + + if (trim($manufacturer->pageheading) != '' + && Redshop::getConfig()->get('AUTOGENERATED_SEO') + && Redshop::getConfig()->get('SEO_PAGE_HEADING_MANUFACTUR') != '') { + $pageheadingtag = $pageheadingtag . " " . $manufacturer->pageheading; + } else { + if (trim($manufacturer->pageheading) != '') { + $pageheadingtag = $manufacturer->pageheading; + } elseif (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_HEADING_MANUFACTUR' + ) != '') { + $pageheadingtag = $pageheadingtag; + } + } + + // FOr Canonical In Manufacturer Page + if (Redshop::getConfig()->get('AUTOGENERATED_SEO') && Redshop::getConfig()->get( + 'SEO_PAGE_CANONICAL_MANUFACTUR' + ) != '' && $layout != "products") { + $canonicalurl = Redshop::getConfig()->get('SEO_PAGE_CANONICAL_MANUFACTUR'); + + $manufacturer_products_url = substr_replace(JURI::root(), "", -1) + . JRoute::_( + 'index.php?option=com_redshop&view=manufacturers&layout=products&mid=' . $manufacturer->id . '&Itemid=' . $itemId + ); + $canonicalurl_content = ''; + $canonicalurl = str_replace( + "{manufacturerproductslink}", + $canonicalurl_content, + $canonicalurl + ); + $document->addCustomTag($canonicalurl); + } + } else { + $document->setMetaData('keywords', $app->getCfg('sitename')); + $document->setMetaData('description', $app->getCfg('sitename')); + $document->setMetaData('robots', $app->getCfg('sitename')); + } + + $this->setLayout($layout); + } + + // Breadcrumbs + RedshopHelperBreadcrumb::generate($mid); + + // Breadcrumbs end + + if ($layout == "products") { + $filter_order = $params->get( + 'order_by', + Redshop::getConfig()->get('DEFAULT_MANUFACTURER_PRODUCT_ORDERING_METHOD') + ); + $order_by_select = $app->input->getString('order_by', $filter_order); + $order_data = RedshopHelperUtility::getOrderByList(); + } else { + $filter_order = $params->get('order_by', Redshop::getConfig()->get('DEFAULT_MANUFACTURER_ORDERING_METHOD')); + + if ($app->input->getString('order_by', '') != null) { + $order_by_select = $app->input->getString('order_by', ''); + } elseif ($app->getUserState('com_redshop.manufacturers.default.order_state') != null) { + $order_by_select = $app->getUserState('com_redshop.manufacturers.default.order_state'); + } else { + $order_by_select = $filter_order; + } + + $order_data = RedshopHelperUtility::getManufacturerOrderByList(); + } + + $lists['order_select'] = JHTML::_( + 'select.genericlist', + $order_data, + 'order_by', + 'class="inputbox" size="1" onchange="document.orderby_form.submit();" ' . $disabled . ' ', + 'value', + 'text', + $order_by_select + ); + + $categorylist = $model->getCategoryList(); + + $temps = array(); + $temps[0] = new StdClass; + $temps[0]->value = "0"; + $temps[0]->text = JText::_('COM_REDSHOP_SELECT'); + $categorylist = array_merge($temps, $categorylist); + $filter_by_select = $app->input->getString('filter_by', 0); + $lists['filter_select'] = JHTML::_( + 'select.genericlist', + $categorylist, + 'filter_by', + 'class="inputbox" size="1" onchange="document.filter_form.submit();" ' . $disabled . ' ', + 'value', + 'text', + $filter_by_select + ); + + $pagination = $this->get('Pagination'); + + $this->detail = $detail; + $this->lists = $lists; + $this->pagination = $pagination; + $this->pageheadingtag = $pageheadingtag; + $this->params = $params; + parent::display($tpl); + } } diff --git a/component/site/views/newsletter/tmpl/default.php b/component/site/views/newsletter/tmpl/default.php index 9776220d2a5..8f473c41a05 100644 --- a/component/site/views/newsletter/tmpl/default.php +++ b/component/site/views/newsletter/tmpl/default.php @@ -15,67 +15,64 @@ $name = $app->input->getString('name'); $Itemid = $app->input->getInt('Itemid'); -if ($user->id != "") -{ - $email = $user->email; - $name = $user->name; +if ($user->id != "") { + $email = $user->email; + $name = $user->name; } -if ($this->params->get('show_page_heading', 1)) -{ - ?> -
    - escape($this->params->get('page_title')); ?> -
    - +if ($this->params->get('show_page_heading', 1)) { + ?> +
    + escape($this->params->get('page_title')); ?> +
    +
    -
    -
    - -
    -
    - - -
    -
    - - -
    -
    - class="redshop_newsletter_tilmeld"/> - -
    -
    - - - - - +
    +
    + +
    +
    + + +
    +
    + + +
    +
    + class="redshop_newsletter_tilmeld"/> + +
    +
    + + + + +
    diff --git a/component/site/views/newsletter/view.html.php b/component/site/views/newsletter/view.html.php index c412408aebb..f492f2cf298 100644 --- a/component/site/views/newsletter/view.html.php +++ b/component/site/views/newsletter/view.html.php @@ -18,48 +18,47 @@ */ class RedshopViewNewsletter extends RedshopView { - /** - * @var JUser - */ - public $user; + /** + * @var JUser + */ + public $user; - /** - * @var string - */ - public $userdata; + /** + * @var string + */ + public $userdata; - /** - * @var \Joomla\Registry\Registry - */ - public $params; + /** + * @var \Joomla\Registry\Registry + */ + public $params; - /** - * Execute and display a template script. - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return mixed A string if successful, otherwise a JError object. - * @throws Exception - */ - public function display($tpl = null) - { - /** @var JApplicationSite $app */ - $app = JFactory::getApplication(); + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise a JError object. + * @throws Exception + */ + public function display($tpl = null) + { + /** @var JApplicationSite $app */ + $app = JFactory::getApplication(); - $pathway = $app->getPathway(); - $pathway->addItem(JText::_('COM_REDSHOP_NEWSLETTER_SUBSCRIPTION'), ''); + $pathway = $app->getPathway(); + $pathway->addItem(JText::_('COM_REDSHOP_NEWSLETTER_SUBSCRIPTION'), ''); - $layout = $app->input->getCmd('layout'); + $layout = $app->input->getCmd('layout'); - $this->user = JFactory::getUser(); - $this->userdata = $app->input->getString('userdata'); - $this->params = $app->getParams('com_redshop'); + $this->user = JFactory::getUser(); + $this->userdata = $app->input->getString('userdata'); + $this->params = $app->getParams('com_redshop'); - if ($layout == 'thankyou') - { - $this->setLayout('thankyou'); - } + if ($layout == 'thankyou') { + $this->setLayout('thankyou'); + } - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/site/views/order_detail/tmpl/checkout_final.php b/component/site/views/order_detail/tmpl/checkout_final.php index c92ba490db2..6bd7449cbd4 100644 --- a/component/site/views/order_detail/tmpl/checkout_final.php +++ b/component/site/views/order_detail/tmpl/checkout_final.php @@ -12,116 +12,115 @@ $configobj = Redconfiguration::getInstance(); $order_functions = order_functions::getInstance(); -$url = JURI::base(); -$Itemid = RedshopHelperRouter::getCheckoutItemId(); +$url = JURI::base(); +$Itemid = RedshopHelperRouter::getCheckoutItemId(); $order_id = JFactory::getApplication()->input->getInt('oid'); $order = RedshopEntityOrder::getInstance($order_id)->getItem(); $orderitem = RedshopHelperOrder::getOrderItemDetail($order_id); -if ($order->order_total > 0 && !Redshop::getConfig()->get('USE_AS_CATALOG')) -{ - $paymentmethod = $order_functions->getOrderPaymentDetail($order_id); - $paymentmethod = RedshopHelperOrder::getPaymentMethodInfo($paymentmethod[0]->payment_method_class); - $paymentmethod = $paymentmethod[0]; - - $paymentpath = JPATH_SITE . '/plugins/redshop_payment/' . $paymentmethod->element . '/' . $paymentmethod->element . '.xml'; - $paymentparams = new JRegistry($paymentmethod->params); - - echo '
    '; - - $is_creditcard = $paymentparams->get('is_creditcard', ''); - $is_redirected = $paymentparams->get('is_redirected', 0); - - if (!$is_creditcard || $is_redirected == 1) - { - $adminpath = JPATH_ADMINISTRATOR . '/components/com_redshop'; - $invalid_elements = $paymentparams->get('invalid_elements', ''); - - $billingAddresses = RedshopHelperOrder::getOrderBillingUserInfo($order->order_id); - - if (isset($billingAddresses)) - { - if (isset($billingAddresses->country_code)) - { - $billingAddresses->country_2_code = RedshopHelperWorld::getCountryCode2($billingAddresses->country_code); - } - - if (isset($billingAddresses->state_code)) - { - $billingAddresses->state_2_code = $billingAddresses->state_code; - } - } - - $shippingaddresses = RedshopHelperOrder::getOrderShippingUserInfo($order->order_id); - - if (isset($shippingaddresses)) - { - if (isset($shippingaddresses->country_code)) - { - $shippingaddresses->country_2_code = RedshopHelperWorld::getCountryCode2($shippingaddresses->country_code); - } - - if (isset($shippingaddresses->state_code)) - { - $shippingaddresses->state_2_code = $shippingaddresses->state_code; - } - } - - $cart_quantity = 0; - - for ($i = 0, $in = count($orderitem); $i < $in; $i++) - { - $cart_quantity += $orderitem[$i]->product_quantity; - } - - $values['shippinginfo'] = $shippingaddresses; - $values['billinginfo'] = $billingAddresses; - $values['carttotal'] = $order->order_total; - $values['order_subtotal'] = $order->order_subtotal; - $values["order_id"] = $order_id; - $values["order_quantity"] = $cart_quantity; - $values['payment_plugin'] = $paymentmethod->element; - $values['odiscount'] = $order->order_discount; - $values['order'] = $order; - - if ($values['payment_plugin'] == "rs_payment_epayrelay") - { - $epay_url = "https://relay.ditonlinebetalingssystem.dk/relay/v2/relay.cgi/"; - $actionurl = $url . 'index.php?option=com_redshop&view=epayrelay&oid=' . $order_id . '&Itemid=' . $Itemid; - $results = "
    "; - $results .= ""; - $results .= "
    "; - $results .= ""; - $results .= "
    "; - echo $results; - - ?> - - trigger('onPrePayment', array($values['payment_plugin'], $values)); - - $key = array_search(true, $results); - - if (is_array($results) && $key !== false) - { - $app = JFactory::getApplication(); - $app->redirect(JRoute::_('index.php?option=com_redshop&view=order_detail&layout=receipt&oid=' . $order_id . '&Itemid=' . $Itemid, false)); - } - } - } -} -else -{ - $app = JFactory::getApplication(); - $app->redirect(JRoute::_('index.php?option=com_redshop&view=order_detail&layout=receipt&oid=' . $order_id . '&Itemid=' . $Itemid, false)); +if ($order->order_total > 0 && !Redshop::getConfig()->get('USE_AS_CATALOG')) { + $paymentmethod = $order_functions->getOrderPaymentDetail($order_id); + $paymentmethod = RedshopHelperOrder::getPaymentMethodInfo($paymentmethod[0]->payment_method_class); + $paymentmethod = $paymentmethod[0]; + + $paymentpath = JPATH_SITE . '/plugins/redshop_payment/' . $paymentmethod->element . '/' . $paymentmethod->element . '.xml'; + $paymentparams = new JRegistry($paymentmethod->params); + + echo '
    '; + + $is_creditcard = $paymentparams->get('is_creditcard', ''); + $is_redirected = $paymentparams->get('is_redirected', 0); + + if (!$is_creditcard || $is_redirected == 1) { + $adminpath = JPATH_ADMINISTRATOR . '/components/com_redshop'; + $invalid_elements = $paymentparams->get('invalid_elements', ''); + + $billingAddresses = RedshopHelperOrder::getOrderBillingUserInfo($order->order_id); + + if (isset($billingAddresses)) { + if (isset($billingAddresses->country_code)) { + $billingAddresses->country_2_code = RedshopHelperWorld::getCountryCode2( + $billingAddresses->country_code + ); + } + + if (isset($billingAddresses->state_code)) { + $billingAddresses->state_2_code = $billingAddresses->state_code; + } + } + + $shippingaddresses = RedshopHelperOrder::getOrderShippingUserInfo($order->order_id); + + if (isset($shippingaddresses)) { + if (isset($shippingaddresses->country_code)) { + $shippingaddresses->country_2_code = RedshopHelperWorld::getCountryCode2( + $shippingaddresses->country_code + ); + } + + if (isset($shippingaddresses->state_code)) { + $shippingaddresses->state_2_code = $shippingaddresses->state_code; + } + } + + $cart_quantity = 0; + + for ($i = 0, $in = count($orderitem); $i < $in; $i++) { + $cart_quantity += $orderitem[$i]->product_quantity; + } + + $values['shippinginfo'] = $shippingaddresses; + $values['billinginfo'] = $billingAddresses; + $values['carttotal'] = $order->order_total; + $values['order_subtotal'] = $order->order_subtotal; + $values["order_id"] = $order_id; + $values["order_quantity"] = $cart_quantity; + $values['payment_plugin'] = $paymentmethod->element; + $values['odiscount'] = $order->order_discount; + $values['order'] = $order; + + if ($values['payment_plugin'] == "rs_payment_epayrelay") { + $epay_url = "https://relay.ditonlinebetalingssystem.dk/relay/v2/relay.cgi/"; + $actionurl = $url . 'index.php?option=com_redshop&view=epayrelay&oid=' . $order_id . '&Itemid=' . $Itemid; + $results = "
    "; + $results .= ""; + $results .= "
    "; + $results .= ""; + $results .= "
    "; + echo $results; + + ?> + + trigger('onPrePayment', array($values['payment_plugin'], $values)); + + $key = array_search(true, $results); + + if (is_array($results) && $key !== false) { + $app = JFactory::getApplication(); + $app->redirect( + JRoute::_( + 'index.php?option=com_redshop&view=order_detail&layout=receipt&oid=' . $order_id . '&Itemid=' . $Itemid, + false + ) + ); + } + } + } +} else { + $app = JFactory::getApplication(); + $app->redirect( + JRoute::_( + 'index.php?option=com_redshop&view=order_detail&layout=receipt&oid=' . $order_id . '&Itemid=' . $Itemid, + false + ) + ); } ?>
    diff --git a/component/site/views/order_detail/tmpl/default.php b/component/site/views/order_detail/tmpl/default.php index 5d0757dfad4..54ffc029aaf 100644 --- a/component/site/views/order_detail/tmpl/default.php +++ b/component/site/views/order_detail/tmpl/default.php @@ -8,54 +8,47 @@ */ defined('_JEXEC') or die; -$uri = JURI::getInstance(); +$uri = JURI::getInstance(); $getShm = $uri->getScheme(); $config = JFactory::getConfig(); $forceSsl = $config->get('force_ssl'); -if ($getShm == 'https' && $forceSsl > 2) -{ - $uri->setScheme('http'); +if ($getShm == 'https' && $forceSsl > 2) { + $uri->setScheme('http'); } if ($this->params->get('show_page_heading', 1)) : ?>

    - escape(JText::_('COM_REDSHOP_ORDER_DETAILS')); ?> + escape(JText::_('COM_REDSHOP_ORDER_DETAILS')); ?>

    OrdersDetail; +$ordersDetail = $this->OrdersDetail; // Get order Payment method information -if (Redshop::getConfig()->get('USE_AS_CATALOG')) -{ - $ordersListTemplate = RedshopHelperTemplate::getTemplate("catalogue_order_detail"); - $ordersListTemplate = $ordersListTemplate[0]->template_desc; -} -else -{ - $ordersListTemplate = RedshopHelperTemplate::getTemplate("order_detail"); - - if (count($ordersListTemplate) > 0 && $ordersListTemplate[0]->template_desc) - { - $ordersListTemplate = $ordersListTemplate[0]->template_desc; - } - else - { - $ordersListTemplate = RedshopHelperTemplate::getDefaultTemplateContent('order_detail'); - } +if (Redshop::getConfig()->get('USE_AS_CATALOG')) { + $ordersListTemplate = RedshopHelperTemplate::getTemplate("catalogue_order_detail"); + $ordersListTemplate = $ordersListTemplate[0]->template_desc; +} else { + $ordersListTemplate = RedshopHelperTemplate::getTemplate("order_detail"); + + if (count($ordersListTemplate) > 0 && $ordersListTemplate[0]->template_desc) { + $ordersListTemplate = $ordersListTemplate[0]->template_desc; + } else { + $ordersListTemplate = RedshopHelperTemplate::getDefaultTemplateContent('order_detail'); + } } // Replace Reorder Button $this->replaceReorderButton($ordersListTemplate); $message = RedshopTagsReplacer::_( - 'orderdetail', - $ordersListTemplate, - array( - 'ordersDetail' => $ordersDetail - ) + 'orderdetail', + $ordersListTemplate, + array( + 'ordersDetail' => $ordersDetail + ) ); $message = RedshopHelperTemplate::parseRedshopPlugin($message); diff --git a/component/site/views/order_detail/tmpl/receipt.php b/component/site/views/order_detail/tmpl/receipt.php index 6e578089e96..f986d327666 100644 --- a/component/site/views/order_detail/tmpl/receipt.php +++ b/component/site/views/order_detail/tmpl/receipt.php @@ -7,11 +7,9 @@ * @license GNU General Public License version 2 or later; see LICENSE */ -use Redshop\Order\Template; - defined('_JEXEC') or die; -$document = JFactory::getDocument(); +$document = JFactory::getDocument(); // For barcode $model = $this->getModel('order_detail'); @@ -19,48 +17,40 @@ $document->setTitle(JText::_('COM_REDSHOP_ORDER_RECEIPT_TITLE')); ?> params->get('show_page_title', 1)) -{ - ?> +if ($this->params->get('show_page_title', 1)) { + ?>

    - escape(JText::_('COM_REDSHOP_ORDER_RECEIPT')); ?> + escape(JText::_('COM_REDSHOP_ORDER_RECEIPT')); ?>

    - get('ONESTEP_CHECKOUT_ENABLE')) -{ - echo JLayoutHelper::render('cart.wizard', array('step' => '3')); +if (!Redshop::getConfig()->get('ONESTEP_CHECKOUT_ENABLE')) { + echo JLayoutHelper::render('cart.wizard', array('step' => '3')); } -if (Redshop::getConfig()->get('USE_AS_CATALOG')) -{ - $receiptTemplate = RedshopHelperTemplate::getTemplate("catalogue_order_receipt"); - $receiptTemplate = $receiptTemplate[0]->template_desc; -} -else -{ - $receiptTemplate = RedshopHelperTemplate::getTemplate("order_receipt"); +if (Redshop::getConfig()->get('USE_AS_CATALOG')) { + $receiptTemplate = RedshopHelperTemplate::getTemplate("catalogue_order_receipt"); + $receiptTemplate = $receiptTemplate[0]->template_desc; +} else { + $receiptTemplate = RedshopHelperTemplate::getTemplate("order_receipt"); - if (count($receiptTemplate) > 0 && $receiptTemplate[0]->template_desc) - { - $receiptTemplate = $receiptTemplate[0]->template_desc; - } - else - { - $receiptTemplate = RedshopHelperTemplate::getDefaultTemplateContent('order_receipt'); - } + if (count($receiptTemplate) > 0 && $receiptTemplate[0]->template_desc) { + $receiptTemplate = $receiptTemplate[0]->template_desc; + } else { + $receiptTemplate = RedshopHelperTemplate::getDefaultTemplateContent('order_receipt'); + } } // Replace Reorder Button $this->replaceReorderButton($receiptTemplate); $receiptTemplate = RedshopTagsReplacer::_( - 'orderreceipt', - $receiptTemplate, - array( - 'order' => $order - ) + 'orderreceipt', + $receiptTemplate, + array( + 'order' => $order + ) ); echo eval("?>" . $receiptTemplate . "get('issplit'); -if ($isSplit) -{ - $splitAmount = ($order->order_total) / 2; - $order->order_total = $splitAmount; +if ($isSplit) { + $splitAmount = ($order->order_total) / 2; + $order->order_total = $splitAmount; } // End $model->billingaddresses(); -if ($order->analytics_status == 0) -{ - $model->UpdateAnalytics_status($order->order_id); +if ($order->analytics_status == 0) { + $model->UpdateAnalytics_status($order->order_id); } \ No newline at end of file diff --git a/component/site/views/order_detail/view.html.php b/component/site/views/order_detail/view.html.php index 0a5b0a38547..46987ab8152 100644 --- a/component/site/views/order_detail/view.html.php +++ b/component/site/views/order_detail/view.html.php @@ -18,150 +18,143 @@ */ class RedshopViewOrder_Detail extends RedshopView { - /** - * @var object - */ + /** + * @var object + */ public $OrdersDetail; - /** - * Execute and display a template script. - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return void A string if successful, otherwise a Error object. - * - * @throws \Exception - */ - public function display($tpl = null) - { - $app = JFactory::getApplication(); - - $orderFunctions = order_functions::getInstance(); - - $print = $app->input->getInt('print', 0); - - if ($print) - { - ?> + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return void A string if successful, otherwise a Error object. + * + * @throws \Exception + */ + public function display($tpl = null) + { + $app = JFactory::getApplication(); + + $orderFunctions = order_functions::getInstance(); + + $print = $app->input->getInt('print', 0); + + if ($print) { + ?> - get('auth'); - $orderId = $app->input->getInt('oid', $session->get('order_id')); - $encr = $app->input->getString('encr', null); - $orderPayment = $orderFunctions->getOrderPaymentDetail($orderId); - - if ($orderPayment && count($orderPayment)) - { - // Load payment language file - $language = JFactory::getLanguage(); - $base_dir = JPATH_ADMINISTRATOR; - $language_tag = $language->getTag(); - $extension = 'plg_redshop_payment_' . ($orderPayment[0]->payment_method_class); - - $language->load($extension, $base_dir, $language_tag, true); - } - - /** @var RedshopModelOrder_detail $model */ - $model = $this->getModel('order_detail'); - - $orderDetail = RedshopHelperOrder::getOrderDetails($orderId); - - if ($orderDetail === null) - { - throw new Exception(JText::_('JERROR_PAGE_NOT_FOUND'), 404); - } - - if ($user->id) - { - $rUser = RedshopHelperUser::getUserInformation(0,'', $orderDetail->user_info_id, false, true); - - if ($rUser->user_email != $user->email) - { - $app->redirect(JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . $app->input->getInt('Itemid'), false)); - } - } - else - { - if ($encr) - { - // Preform security checks - $authorization = $model->checkauthorization($orderId, $encr, false); - - if (empty($authorization)) - { - throw new Exception(JText::_('JERROR_PAGE_NOT_FOUND'), 404); - } - } - elseif ((int) $orderDetail->user_id > 0) - { - $app->redirect(JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . $app->input->getInt('Itemid'), false)); - } - elseif ((int) $auth['users_info_id'] !== (int) $orderDetail->user_info_id) - { - throw new Exception(JText::_('JERROR_PAGE_NOT_FOUND'), 404); - } - } - - JPluginHelper::importPlugin('system'); - RedshopHelperUtility::getDispatcher()->trigger('onDisplayOrderReceipt', array(&$orderDetail)); - - $this->OrdersDetail = $orderDetail; - $this->user = $user; - $this->params = /** @scrutinizer ignore-call */ $app->getParams('com_redshop'); - - parent::display($tpl); - } - - /** - * Replace Reorder Button - * - * @param string &$template Template Data - * - * @return void - */ - public function replaceReorderButton(&$template) - { - $app = JFactory::getApplication(); - $orderId = $app->input->getInt('oid', 0); - $print = $app->input->getInt('print', 0); - $order = RedshopEntityOrder::getInstance($orderId)->getItem(); - - if ($order->order_status != 'C' && $order->order_status != 'S' && $order->order_status != 'PR' && $order->order_status != 'APP' && $print != 1 && $order->order_payment_status != 'Paid') - { - $reorder = "
    + get('auth'); + $orderId = $app->input->getInt('oid', $session->get('order_id')); + $encr = $app->input->getString('encr', null); + $orderPayment = $orderFunctions->getOrderPaymentDetail($orderId); + + if ($orderPayment && count($orderPayment)) { + // Load payment language file + $language = JFactory::getLanguage(); + $base_dir = JPATH_ADMINISTRATOR; + $language_tag = $language->getTag(); + $extension = 'plg_redshop_payment_' . ($orderPayment[0]->payment_method_class); + + $language->load($extension, $base_dir, $language_tag, true); + } + + /** @var RedshopModelOrder_detail $model */ + $model = $this->getModel('order_detail'); + + $orderDetail = RedshopHelperOrder::getOrderDetails($orderId); + + if ($orderDetail === null) { + throw new Exception(JText::_('JERROR_PAGE_NOT_FOUND'), 404); + } + + if ($user->id) { + $rUser = RedshopHelperUser::getUserInformation(0, '', $orderDetail->user_info_id, false, true); + + if ($rUser->user_email != $user->email) { + $app->redirect( + JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . $app->input->getInt('Itemid'), false) + ); + } + } else { + if ($encr) { + // Preform security checks + $authorization = $model->checkauthorization($orderId, $encr, false); + + if (empty($authorization)) { + throw new Exception(JText::_('JERROR_PAGE_NOT_FOUND'), 404); + } + } elseif ((int)$orderDetail->user_id > 0) { + $app->redirect( + JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . $app->input->getInt('Itemid'), false) + ); + } elseif ((int)$auth['users_info_id'] !== (int)$orderDetail->user_info_id) { + throw new Exception(JText::_('JERROR_PAGE_NOT_FOUND'), 404); + } + } + + JPluginHelper::importPlugin('system'); + RedshopHelperUtility::getDispatcher()->trigger('onDisplayOrderReceipt', array(&$orderDetail)); + + $this->OrdersDetail = $orderDetail; + $this->user = $user; + $this->params = /** @scrutinizer ignore-call */ + $app->getParams('com_redshop'); + + parent::display($tpl); + } + + /** + * Replace Reorder Button + * + * @param string &$template Template Data + * + * @return void + */ + public function replaceReorderButton(&$template) + { + $app = JFactory::getApplication(); + $orderId = $app->input->getInt('oid', 0); + $print = $app->input->getInt('print', 0); + $order = RedshopEntityOrder::getInstance($orderId)->getItem(); + + if ($order->order_status != 'C' && $order->order_status != 'S' && $order->order_status != 'PR' && $order->order_status != 'APP' && $print != 1 && $order->order_payment_status != 'Paid') { + $reorder = "
    "; - } - else - { - JFactory::getDocument()->addScriptDeclaration(' + } else { + JFactory::getDocument()->addScriptDeclaration( + ' function submitReorder() { if (!confirm("' . JText::_('COM_REDSHOP_CONFIRM_CART_EMPTY') . '")) { return false; } return true; } - '); - $reorder = "
    "; - $reorder .= ""; - $reorder .= ""; - $reorder .= ""; - $reorder .= ""; - $reorder .= "
    "; - } - - $template = str_replace("{reorder_button}", $reorder, $template); - } + ' + ); + $reorder = "
    "; + $reorder .= ""; + $reorder .= ""; + $reorder .= ""; + $reorder .= ""; + $reorder .= "
    "; + } + + $template = str_replace("{reorder_button}", $reorder, $template); + } } diff --git a/component/site/views/orders/tmpl/default.php b/component/site/views/orders/tmpl/default.php index be7cb091f3b..6359e3d8bac 100644 --- a/component/site/views/orders/tmpl/default.php +++ b/component/site/views/orders/tmpl/default.php @@ -14,18 +14,18 @@ $ordersListTemplate = RedshopHelperTemplate::getTemplate("order_list", $this->params->get('template_id')); if (isset($ordersListTemplate[0]->template_desc) && !empty(trim($ordersListTemplate[0]->template_desc))) { - $templateDesc = $ordersListTemplate[0]->template_desc; + $templateDesc = $ordersListTemplate[0]->template_desc; } else { - $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('order_list'); + $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('order_list'); } echo RedshopTagsReplacer::_( - 'orderlist', - $templateDesc, - [ - 'pagination' => $this->pagination, - 'detail' => $this->detail, - 'params' => $this->params - ] + 'orderlist', + $templateDesc, + [ + 'pagination' => $this->pagination, + 'detail' => $this->detail, + 'params' => $this->params + ] ); diff --git a/component/site/views/orders/tmpl/default.xml b/component/site/views/orders/tmpl/default.xml index c336c429741..4643267477c 100644 --- a/component/site/views/orders/tmpl/default.xml +++ b/component/site/views/orders/tmpl/default.xml @@ -9,8 +9,8 @@
    + label="COM_REDSHOP_SELECT_ORDERLIST_TEMPLATE" + description="COM_REDSHOP_SELECT_ORDERLIST_TEMPLATE"/>
    diff --git a/component/site/views/orders/view.html.php b/component/site/views/orders/view.html.php index 6f0ca066f7b..0c50ab421ae 100644 --- a/component/site/views/orders/view.html.php +++ b/component/site/views/orders/view.html.php @@ -12,33 +12,32 @@ class RedshopViewOrders extends RedshopView { - public function display($tpl = null) - { - $app = JFactory::getApplication(); - $user = JFactory::getUser(); - - // Preform security checks - if ($user->id == 0) - { - $app->redirect(JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . JRequest::getInt('Itemid'))); - $app->close(); - } - - $layout = $app->input->getCmd('layout', 'default'); - $this->setLayout($layout); - - $params = $app->getParams('com_redshop'); - RedshopHelperBreadcrumb::generate(); - - // Request variables - $limit = $app->getUserStateFromRequest('com_redshop' . 'limit', 'limit', 10, 'int'); - $limitstart = $app->input->getInt('limitstart', 0, '', 'int'); - - $detail = $this->get('data'); - $this->pagination = $this->get('Pagination'); - - $this->detail = $detail; - $this->params = $params; - parent::display($tpl); - } + public function display($tpl = null) + { + $app = JFactory::getApplication(); + $user = JFactory::getUser(); + + // Preform security checks + if ($user->id == 0) { + $app->redirect(JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . JRequest::getInt('Itemid'))); + $app->close(); + } + + $layout = $app->input->getCmd('layout', 'default'); + $this->setLayout($layout); + + $params = $app->getParams('com_redshop'); + RedshopHelperBreadcrumb::generate(); + + // Request variables + $limit = $app->getUserStateFromRequest('com_redshop' . 'limit', 'limit', 10, 'int'); + $limitstart = $app->input->getInt('limitstart', 0, '', 'int'); + + $detail = $this->get('data'); + $this->pagination = $this->get('Pagination'); + + $this->detail = $detail; + $this->params = $params; + parent::display($tpl); + } } diff --git a/component/site/views/ordertracker/tmpl/default.php b/component/site/views/ordertracker/tmpl/default.php index 6b8a1392275..01ca6cd8a7d 100644 --- a/component/site/views/ordertracker/tmpl/default.php +++ b/component/site/views/ordertracker/tmpl/default.php @@ -21,84 +21,79 @@ $order_detail = array(); $OrderProducts = array(); -if ($order_id != 0) -{ - $order_detail = RedshopEntityOrder::getInstance($order_id)->getItem(); - $OrderProducts = RedshopHelperOrder::getOrderItemDetail($order_id); +if ($order_id != 0) { + $order_detail = RedshopEntityOrder::getInstance($order_id)->getItem(); + $OrderProducts = RedshopHelperOrder::getOrderItemDetail($order_id); } -if ($this->params->get('show_page_heading', 1)) -{ - ?> -
    - params->get('show_page_heading', 1) && $this->params->get('page_title')) - { - echo $this->escape($this->params->get('page_title')); - } ?> -
    -params->get('show_page_heading', 1)) { + ?> +
    + params->get('show_page_heading', 1) && $this->params->get('page_title')) { + echo $this->escape($this->params->get('page_title')); + } ?> +
    +
    - - - - - - -
    - : - - -
    - - + + + + + + +
    + : + + +
    + +
    - - 0) - { - ?> - - - - - - - - - + 0) + { + ?> + + + + + + + + + order_item_name; - } + for ($j = 0, $jn = count($OrderProducts); $j < $jn; $j++) { + $order_item_name[$j] = $OrderProducts[$j]->order_item_name; + } - $itemlist = implode(',
    ', $order_item_name); - $statusname = RedshopHelperOrder::getOrderStatusTitle($order_detail->order_status); - $orderdetailurl = JRoute::_('index.php?option=com_redshop&view=order_detail&oid=' . $order_id); ?> - - - - - - + $itemlist = implode(',
    ', $order_item_name); + $statusname = RedshopHelperOrder::getOrderStatusTitle($order_detail->order_status); + $orderdetailurl = JRoute::_('index.php?option=com_redshop&view=order_detail&oid=' . $order_id); ?> + + + + + + - - - - - - - + + + + + + +
    order_number;?>order_total);?>convertDateFormat($order_detail->cdate); ?>
    order_number; ?>order_total); ?>convertDateFormat($order_detail->cdate); ?> -
    +
    diff --git a/component/site/views/ordertracker/view.html.php b/component/site/views/ordertracker/view.html.php index 76f9292787a..0ec4e787c21 100644 --- a/component/site/views/ordertracker/view.html.php +++ b/component/site/views/ordertracker/view.html.php @@ -12,14 +12,14 @@ class RedshopViewOrdertracker extends RedshopView { - public function display($tpl = null) - { - $app = JFactory::getApplication(); + public function display($tpl = null) + { + $app = JFactory::getApplication(); - $params = $app->getParams('com_redshop'); + $params = $app->getParams('com_redshop'); - // Request variables - $this->params = $params; - parent::display($tpl); - } + // Request variables + $this->params = $params; + parent::display($tpl); + } } diff --git a/component/site/views/plugin/tmpl/default.php b/component/site/views/plugin/tmpl/default.php index 82f2dfec094..37bb0775d78 100644 --- a/component/site/views/plugin/tmpl/default.php +++ b/component/site/views/plugin/tmpl/default.php @@ -18,7 +18,7 @@ // Group $type = $app->input->getCmd('type'); -$post = $app->input->getArray(); +$post = $app->input->getArray(); JPluginHelper::importPlugin($type); diff --git a/component/site/views/plugin/view.html.php b/component/site/views/plugin/view.html.php index ad97294f2db..cb9b7d08387 100644 --- a/component/site/views/plugin/view.html.php +++ b/component/site/views/plugin/view.html.php @@ -12,11 +12,11 @@ class RedshopViewPlugin extends RedshopView { - public function display($tpl = null) - { - ob_clean(); + public function display($tpl = null) + { + ob_clean(); - // Flush(); - parent::display($tpl); - } + // Flush(); + parent::display($tpl); + } } diff --git a/component/site/views/price_filter/tmpl/default.php b/component/site/views/price_filter/tmpl/default.php index 38c55dff3d2..f3f5933e81f 100644 --- a/component/site/views/price_filter/tmpl/default.php +++ b/component/site/views/price_filter/tmpl/default.php @@ -25,113 +25,108 @@ $show_addtocart = $app->input->getBool('show_addtocart'); $show_discountpricelayout = $app->input->getBool('show_discountpricelayout'); -$k = 0; +$k = 0; $configobj = Redconfiguration::getInstance(); ?> - prdlist); $i < $countPrdList; $i++) - { - $row = $this->prdlist[$i]; - - $link = JRoute::_('index.php?option=com_redshop&view=product&pid=' . $row->product_id); - $pricetext = ''; - $product_price = Redshop\Product\Price::getPrice($row->product_id); - $tmpprcie = $product_price; - - if ($product_price >= $texpricemin && $product_price <= $texpricemax && $count > 0) - { - $k++; - $count--;?> - - - - "; - } ?> + prdlist); $i < $countPrdList; $i++) { + $row = $this->prdlist[$i]; + + $link = JRoute::_('index.php?option=com_redshop&view=product&pid=' . $row->product_id); + $pricetext = ''; + $product_price = Redshop\Product\Price::getPrice($row->product_id); + $tmpprcie = $product_price; + + if ($product_price >= $texpricemin && $product_price <= $texpricemax && $count > 0) { + $k++; + $count--; ?> + + + + "; + } ?>
    - product_id, $link, $thumbwidth, $thumbheight); - echo "
    "; - - if ($image) - { - echo $thum_image . "
    "; - } - - echo "" . $row->product_name . "
    "; - - $productArr = RedshopHelperProductPrice::getNetPrice($row->product_id); - $product_price_discount = $productArr['productPrice'] + $productArr['productVat']; - - $taxexempt_addtocart = RedshopHelperCart::taxExemptAddToCart(); - - if (!$row->not_for_sale && $show_price && $taxexempt_addtocart) - { - if (Redshop::getConfig()->get('SHOW_PRICE') && (!Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') && SHOW_QUOTATION_PRICE))) - { - if (!$product_price) - { - $product_price_dis = RedshopHelperProductPrice::priceReplacement($product_price); - } - else - { - $product_price_dis = RedshopHelperProductPrice::formattedPrice($product_price); - } - - $pricetext = ""; - $disply_text = "
    " . $product_price_dis . "
    "; - - if ($row->product_on_sale && $product_price_discount > 0) - { - if ($product_price > $product_price_discount) - { - $disply_text = ""; - $s_price = $product_price - $product_price_discount; - $tmpprcie = $product_price_discount; - - if ($show_discountpricelayout) - { - $pricetext = "
    "; - $pricetext .= "" . RedshopHelperProductPrice::formattedPrice($product_price) . "
    "; - $pricetext .= "
    " . RedshopHelperProductPrice::formattedPrice($product_price_discount) . "
    "; - $pricetext .= "
    " . JText::_('COM_REDSHOP_PRODCUT_PRICE_YOU_SAVED') . ' ' . RedshopHelperProductPrice::formattedPrice($s_price) . "
    "; - } - else - { - $pricetext = "
    " . RedshopHelperProductPrice::formattedPrice($product_price) . "
    "; - } - } - } - - echo $pricetext . $disply_text; - } - else - { - $product_price_dis = RedshopHelperProductPrice::priceReplacement($product_price); - echo "
    " . $product_price_dis . "
    "; - } - } - - if ($show_readmore) - { - echo "
    " . JText::_('COM_REDSHOP_READ_MORE') . " "; - } - - if ($show_addtocart) - { - $addtocartform = Redshop\Cart\Render::replace($row->product_id); - echo "
    " . $addtocartform . "
    "; - } - - echo "
    "; ?> -
    " . JText::_('COM_REDSHOP_NO_PRODUCT_FOUND') . "
    + product_id, + $link, + $thumbwidth, + $thumbheight + ); + echo "
    "; + + if ($image) { + echo $thum_image . "
    "; + } + + echo "" . $row->product_name . "
    "; + + $productArr = RedshopHelperProductPrice::getNetPrice($row->product_id); + $product_price_discount = $productArr['productPrice'] + $productArr['productVat']; + + $taxexempt_addtocart = RedshopHelperCart::taxExemptAddToCart(); + + if (!$row->not_for_sale && $show_price && $taxexempt_addtocart) { + if (Redshop::getConfig()->get('SHOW_PRICE') && (!Redshop::getConfig()->get( + 'DEFAULT_QUOTATION_MODE' + ) || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') && SHOW_QUOTATION_PRICE))) { + if (!$product_price) { + $product_price_dis = RedshopHelperProductPrice::priceReplacement($product_price); + } else { + $product_price_dis = RedshopHelperProductPrice::formattedPrice($product_price); + } + + $pricetext = ""; + $disply_text = "
    " . $product_price_dis . "
    "; + + if ($row->product_on_sale && $product_price_discount > 0) { + if ($product_price > $product_price_discount) { + $disply_text = ""; + $s_price = $product_price - $product_price_discount; + $tmpprcie = $product_price_discount; + + if ($show_discountpricelayout) { + $pricetext = "
    "; + $pricetext .= "" . RedshopHelperProductPrice::formattedPrice( + $product_price + ) . "
    "; + $pricetext .= "
    " . RedshopHelperProductPrice::formattedPrice( + $product_price_discount + ) . "
    "; + $pricetext .= "
    " . JText::_( + 'COM_REDSHOP_PRODCUT_PRICE_YOU_SAVED' + ) . ' ' . RedshopHelperProductPrice::formattedPrice($s_price) . "
    "; + } else { + $pricetext = "
    " . RedshopHelperProductPrice::formattedPrice( + $product_price + ) . "
    "; + } + } + } + + echo $pricetext . $disply_text; + } else { + $product_price_dis = RedshopHelperProductPrice::priceReplacement($product_price); + echo "
    " . $product_price_dis . "
    "; + } + } + + if ($show_readmore) { + echo "
    " . JText::_('COM_REDSHOP_READ_MORE') . " "; + } + + if ($show_addtocart) { + $addtocartform = Redshop\Cart\Render::replace($row->product_id); + echo "
    " . $addtocartform . "
    "; + } + + echo "
    "; ?> +
    " . JText::_('COM_REDSHOP_NO_PRODUCT_FOUND') . "
    diff --git a/component/site/views/price_filter/view.raw.php b/component/site/views/price_filter/view.raw.php index dff439f44cd..d5a1a05763a 100644 --- a/component/site/views/price_filter/view.raw.php +++ b/component/site/views/price_filter/view.raw.php @@ -11,12 +11,12 @@ class RedshopViewPrice_filter extends RedshopView { - public function display($tpl = null) - { - $prdlist = $this->get('Data'); + public function display($tpl = null) + { + $prdlist = $this->get('Data'); - $this->prdlist = $prdlist; + $this->prdlist = $prdlist; - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/site/views/product/tmpl/compare.php b/component/site/views/product/tmpl/compare.php index 5af893f9e40..b3656e3d795 100644 --- a/component/site/views/product/tmpl/compare.php +++ b/component/site/views/product/tmpl/compare.php @@ -18,35 +18,34 @@ $compare = new RedshopProductCompare; $compareCategoryId = $compare->getCategoryId(); -if (Redshop::getConfig()->get('PRODUCT_COMPARISON_TYPE') == 'category') -{ - $compareTemplate = $this->redTemplate->getTemplate( - 'compare_product', - Redshop\Product\Compare::getCategoryCompareTemplate($compareCategoryId) - ); -} -else -{ - $compareTemplate = $this->redTemplate->getTemplate("compare_product", Redshop::getConfig()->get('COMPARE_TEMPLATE_ID')); +if (Redshop::getConfig()->get('PRODUCT_COMPARISON_TYPE') == 'category') { + $compareTemplate = $this->redTemplate->getTemplate( + 'compare_product', + Redshop\Product\Compare::getCategoryCompareTemplate($compareCategoryId) + ); +} else { + $compareTemplate = $this->redTemplate->getTemplate( + "compare_product", + Redshop::getConfig()->get('COMPARE_TEMPLATE_ID') + ); } $template = RedshopHelperTemplate::getDefaultTemplateContent('compare_product'); -if (!empty($compareTemplate) && $compareTemplate[0]->template_desc != "") -{ - $template = $compareTemplate[0]->template_desc; +if (!empty($compareTemplate) && $compareTemplate[0]->template_desc != "") { + $template = $compareTemplate[0]->template_desc; } $template = RedshopTagsReplacer::_( - 'compareproduct', - $template, - array( - 'compare' => $compare, - 'compareCategoryId' => $compareCategoryId, - 'itemId' => $this->itemId, - 'print' => $this->input->getBool('print', false), - 'redTemplate' => $this->redTemplate - ) + 'compareproduct', + $template, + array( + 'compare' => $compare, + 'compareCategoryId' => $compareCategoryId, + 'itemId' => $this->itemId, + 'print' => $this->input->getBool('print', false), + 'redTemplate' => $this->redTemplate + ) ); echo eval("?>" . $template . "session->get('watched_product', array()); if (in_array($this->pid, $watched) == 0) { - array_push($watched, $this->pid); - $this->session->set('watched_product', $watched); + array_push($watched, $this->pid); + $this->session->set('watched_product', $watched); } $template = $this->template; if (!empty($template) && !empty($template->template_desc)) { - $templateDesc = $template->template_desc; + $templateDesc = $template->template_desc; } else { - $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('product'); + $templateDesc = RedshopHelperTemplate::getDefaultTemplateContent('product'); } echo $templateDesc = \RedshopTagsReplacer::_( - 'product', - $templateDesc, - [ - 'data' => $this->data, - 'pageHeadingTag' => $this->pageheadingtag, - 'isViewProduct' => true, - 'params' => $this->params, - 'calculatorTemplate' => $this->loadTemplate('calculator') - ] + 'product', + $templateDesc, + [ + 'data' => $this->data, + 'pageHeadingTag' => $this->pageheadingtag, + 'isViewProduct' => true, + 'params' => $this->params, + 'calculatorTemplate' => $this->loadTemplate('calculator') + ] ); /** diff --git a/component/site/views/product/tmpl/default_calculator.php b/component/site/views/product/tmpl/default_calculator.php index e8982edf1b2..a8ed1ebc4cc 100644 --- a/component/site/views/product/tmpl/default_calculator.php +++ b/component/site/views/product/tmpl/default_calculator.php @@ -9,7 +9,7 @@ defined('_JEXEC') or die; -$url = JURI::base(); +$url = JURI::base(); // Check that we need to use discount calculator @@ -26,56 +26,74 @@ $calcoption[] = JHTML::_('select.option', 'mm', JText::_('COM_REDSHOP_MILLIMETER')); $calcoption[] = JHTML::_('select.option', 'cm', JText::_('COM_REDSHOP_CENTIMETER')); $calcoption[] = JHTML::_('select.option', 'm', JText::_('COM_REDSHOP_METER')); -$discount_calc_unit = JHTML::_('select.genericlist', $calcoption, 'discount_calc_unit', 'class="inputbox" size="1" ', 'value', 'text', Redshop::getConfig()->get('DEFAULT_VOLUME_UNIT')); +$discount_calc_unit = JHTML::_( + 'select.genericlist', + $calcoption, + 'discount_calc_unit', + 'class="inputbox" size="1" ', + 'value', + 'text', + Redshop::getConfig()->get('DEFAULT_VOLUME_UNIT') +); unset($calcoption); -$height = ""; -$width = ""; -$depth = ""; -$radius = ""; +$height = ""; +$width = ""; +$depth = ""; +$radius = ""; $calculate = " "; -$calculate .= ''; +$calculate .= ''; $hiddenVar = " "; $calc_output = ""; -$calc_output .= ""; - -switch ($calcMethod) -{ - case "volume": - $calc_output .= $height; - $calc_output .= $width; - $calc_output .= $depth; - break; - - case "area": - $calc_output .= $depth; - $calc_output .= $width; - break; - - case "circumference": - $calc_output .= $radius; - break; +$calc_output .= ""; + +switch ($calcMethod) { + case "volume": + $calc_output .= $height; + $calc_output .= $width; + $calc_output .= $depth; + break; + + case "area": + $calc_output .= $depth; + $calc_output .= $width; + break; + + case "circumference": + $calc_output .= $radius; + break; } $pdc_extra_output = ""; $pdc_extra_datas = \Redshop\Promotion\Discount::getDiscountCalcDataExtra("", $this->data->product_id); -for ($p = 0, $pn = count($pdc_extra_datas); $p < $pn; $p++) -{ - $pdc_extra_data = $pdc_extra_datas[$p]; - $option_name = $pdc_extra_data->option_name; - $pdcextra_id = $pdc_extra_data->pdcextra_id; - $pdcprice = $pdc_extra_data->price; - $pdcoprand = $pdc_extra_data->oprand; +for ($p = 0, $pn = count($pdc_extra_datas); $p < $pn; $p++) { + $pdc_extra_data = $pdc_extra_datas[$p]; + $option_name = $pdc_extra_data->option_name; + $pdcextra_id = $pdc_extra_data->pdcextra_id; + $pdcprice = $pdc_extra_data->price; + $pdcoprand = $pdc_extra_data->oprand; - $pdcstring = $option_name . ' (' . $pdcoprand . ' ' . $pdcprice . ' )'; + $pdcstring = $option_name . ' (' . $pdcoprand . ' ' . $pdcprice . ' )'; - $pdc_extra_output .= ""; - $pdc_extra_output .= ''; - $pdc_extra_output .= ""; + $pdc_extra_output .= ""; + $pdc_extra_output .= ''; + $pdc_extra_output .= ""; } $calc_output .= $pdc_extra_output . $calculate . $hiddenVar; diff --git a/component/site/views/product/tmpl/default_cartbox.php b/component/site/views/product/tmpl/default_cartbox.php index 2775e92a72e..7533d9a898b 100644 --- a/component/site/views/product/tmpl/default_cartbox.php +++ b/component/site/views/product/tmpl/default_cartbox.php @@ -12,20 +12,17 @@ $cartTemplate = ""; $ajaxTemplate = $this->redTemplate->getTemplate("ajax_cart_box"); -if (count($ajaxTemplate) > 0 && $ajaxTemplate[0]->template_desc) -{ - $cartTemplate = $ajaxTemplate[0]->template_desc; -} -else -{ - $cartTemplate = RedshopHelperTemplate::getDefaultTemplateContent('ajax_cart_box'); +if (count($ajaxTemplate) > 0 && $ajaxTemplate[0]->template_desc) { + $cartTemplate = $ajaxTemplate[0]->template_desc; +} else { + $cartTemplate = RedshopHelperTemplate::getDefaultTemplateContent('ajax_cart_box'); } $cartTemplate = RedshopTagsReplacer::_( - 'ajaxcartbox', - $cartTemplate, - array() - ); + 'ajaxcartbox', + $cartTemplate, + array() +); echo eval("?>" . $cartTemplate . "close(); diff --git a/component/site/views/product/tmpl/default_related.php b/component/site/views/product/tmpl/default_related.php index c833a6716f2..cc8e249dfe2 100644 --- a/component/site/views/product/tmpl/default_related.php +++ b/component/site/views/product/tmpl/default_related.php @@ -9,19 +9,19 @@ defined('_JEXEC') or die; -$template = $this->input->getString('template', ''); -$relPTemplate = RedshopHelperTemplate::getTemplate("related_product", 0, $template); +$template = $this->input->getString('template', ''); +$relPTemplate = RedshopHelperTemplate::getTemplate("related_product", 0, $template); if (isset($relPTemplate[0]->template_desc) && !empty(trim($relPTemplate[0]->template_desc))) { - $relatedTemplate = $relPTemplate[0]->template_desc; + $relatedTemplate = $relPTemplate[0]->template_desc; } else { - $relatedTemplate = RedshopHelperTemplate::getDefaultTemplateContent('related_product'); + $relatedTemplate = RedshopHelperTemplate::getDefaultTemplateContent('related_product'); } echo RedshopTagsReplacer::_( - 'relatedproduct', - $relatedTemplate, - [ - 'product' => $this->data - ] + 'relatedproduct', + $relatedTemplate, + [ + 'product' => $this->data + ] ); diff --git a/component/site/views/product/tmpl/downloadproduct.php b/component/site/views/product/tmpl/downloadproduct.php index 85b1c60cfd5..0264fe7c333 100644 --- a/component/site/views/product/tmpl/downloadproduct.php +++ b/component/site/views/product/tmpl/downloadproduct.php @@ -12,134 +12,131 @@ JHTMLBehavior::modal(); JLoader::import('joomla.filesystem.file'); -$tid = $this->input->get('tid', null); -$model = $this->getModel(); +$tid = $this->input->get('tid', null); +$model = $this->getModel(); ?> - -
    - -
    -
    " . $discount_calc_unit . "
    " . $discount_calc_unit . "
    ' . $pdcstring . '
    ' . $pdcstring . '
    - - - - - - - - -
    - -
    - - - - -
    - -
    + +
    + +
    + + + + + + + + + +
    + +
    + + + + +
    +
    +
    downloadProduct($tid); - - ?> -
    - - 0 && $downloaddata->media_id != null) - { - ?> - -
    -
    - - media_id; - $name = $downloaddata->file_name; - $addtional_downloaddata = $model->AdditionaldownloadProduct($mid); - - $filetype = strtolower(JFile::getExt($name)); - - $downloadname = substr(basename($name), 11); - ?> - - - - - id; - $additionalname = $addtional_downloaddata [$i]->name; - - $additionalfiletype = strtolower(JFile::getExt($additionalname)); - - $additionaldownloadname = substr(basename($additionalname), 11); - - ?> - - - - - - - - - - -
    - -
    - -
    - - - - - - -
    -
    -
    -
    - - -
    -downloadProduct($tid); + + ?> +
    + + 0 && $downloaddata->media_id != null) { + ?> + +
    +
    + + media_id; + $name = $downloaddata->file_name; + $addtional_downloaddata = $model->AdditionaldownloadProduct($mid); + + $filetype = strtolower(JFile::getExt($name)); + + $downloadname = substr(basename($name), 11); + ?> + + + + + id; + $additionalname = $addtional_downloaddata [$i]->name; + + $additionalfiletype = strtolower(JFile::getExt($additionalname)); + + $additionaldownloadname = substr(basename($additionalname), 11); + + ?> + + + + + + + + + + +
    + +
    + +
    + + + + + + +
    +
    +
    +
    + + +
    + input->getString('layout', ''); -$relatedprdId = $this->input->getInt('relatedprd_id', 0); +$layout = $this->input->getString('layout', ''); +$relatedprdId = $this->input->getInt('relatedprd_id', 0); $ajaxdetalTemplate = \Redshop\Template\Helper::getAjaxDetailBox($this->data); -if (null !== $ajaxdetalTemplate) -{ - $dataAdd = RedshopTagsReplacer::_( - 'ajaxcartdetailbox', - $ajaxdetalTemplate->template_desc, - array('product' => $this->data) - ); +if (null !== $ajaxdetalTemplate) { + $dataAdd = RedshopTagsReplacer::_( + 'ajaxcartdetailbox', + $ajaxdetalTemplate->template_desc, + array('product' => $this->data) + ); - echo eval("?>" . $dataAdd . "" . $dataAdd . "wishlists; +$url = JURI::base(); +$wishlists = $this->wishlists; $productId = $this->input->getInt('product_id'); -$user = JFactory::getUser(); - -if (!$user->id) -{ - $rows = $this->wish_products; - echo "
    "; - - if (count($rows) > 0) - { - // Send mail link - $mlink = JURI::root() . "index.php?option=com_redshop&view=account&layout=mywishlist&mail=1&tmpl=component"; - echo $mail_link = '
    '; - display_products($rows); - $reglink = JURI::root() . "index.php?option=com_redshop&view=registration"; - echo "
    "; - } - else - { - echo "
    " . JText::_('COM_REDSHOP_NO_PRODUCTS_IN_WISHLIST') . "
    "; - } - - echo "
    "; -} -else // If user logged in than display this code. +$user = JFactory::getUser(); + +if (!$user->id) { + $rows = $this->wish_products; + echo "
    "; + + if (count($rows) > 0) { + // Send mail link + $mlink = JURI::root() . "index.php?option=com_redshop&view=account&layout=mywishlist&mail=1&tmpl=component"; + echo $mail_link = '
    '; + display_products($rows); + $reglink = JURI::root() . "index.php?option=com_redshop&view=registration"; + echo "
    "; + } else { + echo "
    " . JText::_('COM_REDSHOP_NO_PRODUCTS_IN_WISHLIST') . "
    "; + } + + echo "
    "; +} else // If user logged in than display this code. { - echo "
    "; - - if (count($this->wish_session) > 0) - { - $mlink = JURI::root() . "index.php?option=com_redshop&view=account&layout=mywishlist&mail=1&tmpl=component"; - echo $mail_link = '
    '; - display_products($this->wish_session); - echo "
    "; - $mywishlist_link = "index.php?option=com_redshop&view=wishlist&task=addtowishlist&tmpl=component"; - echo ""; - echo "

    "; - } - - if (count($wishlists) > 0) - { - $wish_products = $this->wish_products; - - // Send mail link - for ($j = 0, $jn = count($wishlists); $j < $jn; $j++) - { - $rows = $wish_products[$wishlists[$j]->wishlist_id]; - $mlink = JURI::root() . "index.php?option=com_redshop&view=account&layout=mywishlist&mail=1&tmpl=component&wishlist_id=" . $wishlists[$j]->wishlist_id; - echo $mail_link = ''; - - display_products($rows); - echo "
    "; - } - } - else - { - echo "
    " . JText::_('COM_REDSHOP_NO_PRODUCTS_IN_WISHLIST') . "
    "; - } - - echo "
    "; + echo "
    "; + + if (count($this->wish_session) > 0) { + $mlink = JURI::root() . "index.php?option=com_redshop&view=account&layout=mywishlist&mail=1&tmpl=component"; + echo $mail_link = '
    '; + display_products($this->wish_session); + echo "
    "; + $mywishlist_link = "index.php?option=com_redshop&view=wishlist&task=addtowishlist&tmpl=component"; + echo ""; + echo "

    "; + } + + if (count($wishlists) > 0) { + $wish_products = $this->wish_products; + + // Send mail link + for ($j = 0, $jn = count($wishlists); $j < $jn; $j++) { + $rows = $wish_products[$wishlists[$j]->wishlist_id]; + $mlink = JURI::root( + ) . "index.php?option=com_redshop&view=account&layout=mywishlist&mail=1&tmpl=component&wishlist_id=" . $wishlists[$j]->wishlist_id; + echo $mail_link = ''; + + display_products($rows); + echo "
    "; + } + } else { + echo "
    " . JText::_('COM_REDSHOP_NO_PRODUCTS_IN_WISHLIST') . "
    "; + } + + echo "
    "; } function display_products($rows) { - - for ($i = 0, $in = count($rows); $i < $in; $i++) - { - $row = $rows[$i]; - $Itemid = $this->redHelper->getItemid($row->product_id); - $link = JRoute::_('index.php?option=com_redshop&view=product&pid=' . $row->product_id . '&Itemid=' . $Itemid); - $product_price = Redshop\Product\Price::getPrice($row->product_id); - - $productArr = RedshopHelperProductPrice::getNetPrice($row->product_id); - $product_price_discount = $productArr['productPrice'] + $productArr['productVat']; - - if ($row->product_full_image) - { - echo "
    " - . Redshop\Product\Image\Image::getImage($row->product_id, $link, "100", "100") . '
    '; - } - - echo "" . $row->product_name . "
    "; - - if ($row->product_on_sale && $product_price_discount > 0) - { - if ($product_price > $product_price_discount) - { - $s_price = $product_price - $product_price_discount; - - if ($this->show_discountpricelayout) - { - echo "
    " . RedshopHelperProductPrice::formattedPrice($product_price) . "
    "; - $product_price = $product_price_discount; - echo "
    " . RedshopHelperProductPrice::formattedPrice($product_price_discount) . "
    "; - echo "
    " . JText::_('COM_REDSHOP_PRODCUT_PRICE_YOU_SAVED') . ' ' . RedshopHelperProductPrice::formattedPrice($s_price) . "
    "; - } - else - { - $product_price = $product_price_discount; - echo "
    " . RedshopHelperProductPrice::formattedPrice($product_price) . "
    "; - } - } - else - { - echo "
    " . RedshopHelperProductPrice::formattedPrice($product_price) . "
    "; - } - } - else - { - echo "
    " . RedshopHelperProductPrice::formattedPrice($product_price) . "
    "; - } - - echo "
    " . JText::_('COM_REDSHOP_READ_MORE') . " "; - - echo $addtocartdata = Redshop\Cart\Render::replace($row->product_id); - - echo "
    " . $addtocartdata . "
    "; - } + for ($i = 0, $in = count($rows); $i < $in; $i++) { + $row = $rows[$i]; + $Itemid = $this->redHelper->getItemid($row->product_id); + $link = JRoute::_( + 'index.php?option=com_redshop&view=product&pid=' . $row->product_id . '&Itemid=' . $Itemid + ); + $product_price = Redshop\Product\Price::getPrice($row->product_id); + + $productArr = RedshopHelperProductPrice::getNetPrice($row->product_id); + $product_price_discount = $productArr['productPrice'] + $productArr['productVat']; + + if ($row->product_full_image) { + echo "
    " + . Redshop\Product\Image\Image::getImage($row->product_id, $link, "100", "100") . '
    '; + } + + echo "" . $row->product_name . "
    "; + + if ($row->product_on_sale && $product_price_discount > 0) { + if ($product_price > $product_price_discount) { + $s_price = $product_price - $product_price_discount; + + if ($this->show_discountpricelayout) { + echo "
    " . RedshopHelperProductPrice::formattedPrice( + $product_price + ) . "
    "; + $product_price = $product_price_discount; + echo "
    " . RedshopHelperProductPrice::formattedPrice( + $product_price_discount + ) . "
    "; + echo "
    " . JText::_( + 'COM_REDSHOP_PRODCUT_PRICE_YOU_SAVED' + ) . ' ' . RedshopHelperProductPrice::formattedPrice($s_price) . "
    "; + } else { + $product_price = $product_price_discount; + echo "
    " . RedshopHelperProductPrice::formattedPrice( + $product_price + ) . "
    "; + } + } else { + echo "
    " . RedshopHelperProductPrice::formattedPrice( + $product_price + ) . "
    "; + } + } else { + echo "
    " . RedshopHelperProductPrice::formattedPrice( + $product_price + ) . "
    "; + } + + echo "
    " . JText::_('COM_REDSHOP_READ_MORE') . " "; + + echo $addtocartdata = Redshop\Cart\Render::replace($row->product_id); + + echo "
    " . $addtocartdata . "
    "; + } } diff --git a/component/site/views/product_mini/tmpl/default.php b/component/site/views/product_mini/tmpl/default.php index a15a7e263ca..c1192d30f18 100644 --- a/component/site/views/product_mini/tmpl/default.php +++ b/component/site/views/product_mini/tmpl/default.php @@ -52,10 +52,22 @@ - lists['order_Dir'], $this->lists['order']); ?> + lists['order_Dir'], + $this->lists['order'] + ); ?> - lists['order_Dir'], $this->lists['order']); ?> + lists['order_Dir'], + $this->lists['order'] + ); ?> @@ -66,8 +78,10 @@ for ($i = 0, $n = count($this->products); $i < $n; $i++) { $row = $this->products[$i]; $row->id = $row->product_id ?? null; - $link = JRoute::_('index.php?option=com_redshop&view=product_detail&task=edit&cid[]=' - . $row->id); + $link = JRoute::_( + 'index.php?option=com_redshop&view=product_detail&task=edit&cid[]=' + . $row->id + ); $published = \JHtml::_('jgrid.published', ($row->published ?? null), $i, '', 1); diff --git a/component/site/views/product_mini/view.html.php b/component/site/views/product_mini/view.html.php index 0aa9e854b82..1253c6ba7c4 100644 --- a/component/site/views/product_mini/view.html.php +++ b/component/site/views/product_mini/view.html.php @@ -12,48 +12,56 @@ class RedshopViewProduct_mini extends RedshopView { - public function display($tpl = null) - { - global $context; + public function display($tpl = null) + { + global $context; - $app = JFactory::getApplication(); - $document = JFactory::getDocument(); - $document->setTitle(JText::_('COM_REDSHOP_PRODUCT')); + $app = JFactory::getApplication(); + $document = JFactory::getDocument(); + $document->setTitle(JText::_('COM_REDSHOP_PRODUCT')); - $uri = JFactory::getURI(); + $uri = JFactory::getURI(); - $filterOrder = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'p.product_id'); - $filterOrderDir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', ''); + $filterOrder = $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'p.product_id'); + $filterOrderDir = $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', ''); - $searchField = $app->getUserStateFromRequest($context . 'search_field', 'search_field', ''); - $keyword = $app->getUserStateFromRequest($context . 'keyword', 'keyword', ''); - $category_id = $app->getUserStateFromRequest($context . 'category_id', 'category_id', ''); + $searchField = $app->getUserStateFromRequest($context . 'search_field', 'search_field', ''); + $keyword = $app->getUserStateFromRequest($context . 'keyword', 'keyword', ''); + $category_id = $app->getUserStateFromRequest($context . 'category_id', 'category_id', ''); - $categories = RedshopHelperCategory::getCategoryListArray(); + $categories = RedshopHelperCategory::getCategoryListArray(); - $temps = [new \stdClass]; - $temps[0]->id = "0"; - $temps[0]->name = JText::_('COM_REDSHOP_SELECT'); - $categories = @array_merge($temps, $categories); + $temps = [new \stdClass]; + $temps[0]->id = "0"; + $temps[0]->name = JText::_('COM_REDSHOP_SELECT'); + $categories = @array_merge($temps, $categories); - $lists['category'] = JHTML::_('select.genericlist', $categories, 'category_id', 'class="inputbox" onchange="document.adminForm2.submit();" ', 'category_id', 'category_name', $category_id); + $lists['category'] = JHTML::_( + 'select.genericlist', + $categories, + 'category_id', + 'class="inputbox" onchange="document.adminForm2.submit();" ', + 'category_id', + 'category_name', + $category_id + ); - $lists['order'] = $filterOrder; - $lists['order_Dir'] = $filterOrderDir; - $total = $this->get('Total'); - $products = $this->get('Data'); + $lists['order'] = $filterOrder; + $lists['order_Dir'] = $filterOrderDir; + $total = $this->get('Total'); + $products = $this->get('Data'); - $pagination = $this->get('Pagination'); + $pagination = $this->get('Pagination'); - $this->keyword = $keyword; - $this->search_field = $searchField; - $this->user = JFactory::getUser(); - $this->lists = $lists; - $this->products = $products; - $this->pagination = $pagination; - $this->request_url = $uri->toString(); - JFilterOutput::cleanText($this->request_url); + $this->keyword = $keyword; + $this->search_field = $searchField; + $this->user = JFactory::getUser(); + $this->lists = $lists; + $this->products = $products; + $this->pagination = $pagination; + $this->request_url = $uri->toString(); + JFilterOutput::cleanText($this->request_url); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/site/views/product_rating/tmpl/default.php b/component/site/views/product_rating/tmpl/default.php index 392ae88288e..3864ea97fcc 100644 --- a/component/site/views/product_rating/tmpl/default.php +++ b/component/site/views/product_rating/tmpl/default.php @@ -12,21 +12,21 @@ $app = JFactory::getApplication(); ?> input->getInt('rate', 0)) : ?> - params->get('show_page_heading', 1)) : ?> -
    - escape($this->productInfo->product_name); ?> -
    - - $this->form, - 'modal' => 1, - 'productId' => $this->productId - ); - echo RedshopLayoutHelper::render('product.product_rating', $displayData); - ?> + params->get('show_page_heading', 1)) : ?> +
    + escape($this->productInfo->product_name); ?> +
    + + $this->form, + 'modal' => 1, + 'productId' => $this->productId + ); + echo RedshopLayoutHelper::render('product.product_rating', $displayData); + ?> - + diff --git a/component/site/views/product_rating/view.html.php b/component/site/views/product_rating/view.html.php index 122a784a907..fae0cf66b54 100644 --- a/component/site/views/product_rating/view.html.php +++ b/component/site/views/product_rating/view.html.php @@ -17,45 +17,43 @@ */ class RedshopViewProduct_Rating extends RedshopView { - protected $state; - - protected $form; - - /** - * Execute and display a template script. - * - * @param string $tpl The name of the template file to parse; automatically searches through the template paths. - * - * @return mixed A string if successful, otherwise a Error object. - */ - public function display ($tpl = null) - { - $this->state = $this->get('State'); - $this->form = $this->get('Form'); - - $app = JFactory::getApplication(); - $user = JFactory::getUser(); - - // Preform security checks - if (!$user->id && Redshop::getConfig()->get('RATING_REVIEW_LOGIN_REQUIRED')) - { - $app->enqueueMessage(JText::_('COM_REDSHOP_ALERTNOTAUTH_REVIEW'), 'warning'); - - return; - } - - $this->params = $app->getParams('com_redshop'); - $model = $this->getModel('product_rating'); - $this->productId = $app->input->getInt('product_id', 0); - $rate = $app->input->getInt('rate', 0); - $this->productInfo = \Redshop\Product\Product::getProductById($this->productId); - - if (!$rate && $user->id && $model->checkRatedProduct($this->productId, $user->id)) - { - $app->input->set('rate', 1); - $app->enqueueMessage(JText::_('COM_REDSHOP_YOU_CAN_NOT_REVIEW_SAME_PRODUCT_AGAIN'), 'warning'); - } - - parent::display($tpl); - } + protected $state; + + protected $form; + + /** + * Execute and display a template script. + * + * @param string $tpl The name of the template file to parse; automatically searches through the template paths. + * + * @return mixed A string if successful, otherwise a Error object. + */ + public function display($tpl = null) + { + $this->state = $this->get('State'); + $this->form = $this->get('Form'); + + $app = JFactory::getApplication(); + $user = JFactory::getUser(); + + // Preform security checks + if (!$user->id && Redshop::getConfig()->get('RATING_REVIEW_LOGIN_REQUIRED')) { + $app->enqueueMessage(JText::_('COM_REDSHOP_ALERTNOTAUTH_REVIEW'), 'warning'); + + return; + } + + $this->params = $app->getParams('com_redshop'); + $model = $this->getModel('product_rating'); + $this->productId = $app->input->getInt('product_id', 0); + $rate = $app->input->getInt('rate', 0); + $this->productInfo = \Redshop\Product\Product::getProductById($this->productId); + + if (!$rate && $user->id && $model->checkRatedProduct($this->productId, $user->id)) { + $app->input->set('rate', 1); + $app->enqueueMessage(JText::_('COM_REDSHOP_YOU_CAN_NOT_REVIEW_SAME_PRODUCT_AGAIN'), 'warning'); + } + + parent::display($tpl); + } } diff --git a/component/site/views/quotation/tmpl/default_user.php b/component/site/views/quotation/tmpl/default_user.php index 8b5943e9dd8..1b4f711d4f6 100644 --- a/component/site/views/quotation/tmpl/default_user.php +++ b/component/site/views/quotation/tmpl/default_user.php @@ -21,141 +21,137 @@ $post = $app->input->post->getArray(); $detail = $this->detail; -$firstname = $detail->firstname; -$lastname = $detail->lastname; -$address = $detail->address; -$zipcode = $detail->zipcode; -$city = $detail->city; -$country = JText::_(RedshopHelperOrder::getCountryName($detail->country_code)); -$state = RedshopHelperOrder::getStateName($detail->state_code, $detail->country_code); -$phone = $detail->phone; +$firstname = $detail->firstname; +$lastname = $detail->lastname; +$address = $detail->address; +$zipcode = $detail->zipcode; +$city = $detail->city; +$country = JText::_(RedshopHelperOrder::getCountryName($detail->country_code)); +$state = RedshopHelperOrder::getStateName($detail->state_code, $detail->country_code); +$phone = $detail->phone; $user_email = $detail->user_email; $field = extra_field::getInstance(); -if (Redshop::getConfig()->get('DEFAULT_CUSTOMER_REGISTER_TYPE') == 1 || !Redshop::getConfig()->get('DEFAULT_CUSTOMER_REGISTER_TYPE')) -{ - $regtype = 0; -} -else -{ - $regtype = 1; +if (Redshop::getConfig()->get('DEFAULT_CUSTOMER_REGISTER_TYPE') == 1 || !Redshop::getConfig()->get( + 'DEFAULT_CUSTOMER_REGISTER_TYPE' + )) { + $regtype = 0; +} else { + $regtype = 1; } $link = 'index.php?option=com_redshop&view=cart&Itemid=' . $Itemid; ?>
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    :'/>
    :'/>
    :'/>
    :'/>
    :
    - " - onclick="javascript:document.adminForm.task.value='cancel';"/>
    -
    - - - - - - +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    :'/>
    :'/>
    :'/>
    :'/>
    :
    + " + onclick="javascript:document.adminForm.task.value='cancel';"/>
    +
    + + + + + +
    diff --git a/component/site/views/quotation/view.html.php b/component/site/views/quotation/view.html.php index b1d326a328d..5bf9f194f37 100644 --- a/component/site/views/quotation/view.html.php +++ b/component/site/views/quotation/view.html.php @@ -12,36 +12,35 @@ class RedshopViewQuotation extends RedshopView { - public function display($tpl = null) - { - $app = JFactory::getApplication(); + public function display($tpl = null) + { + $app = JFactory::getApplication(); - $redconfig = Redconfiguration::getInstance(); - $uri = JFactory::getURI(); + $redconfig = Redconfiguration::getInstance(); + $uri = JFactory::getURI(); - $Itemid = $app->input->getInt('Itemid'); - $session = JFactory::getSession(); - $cart = $session->get('cart'); - $return = $app->input->getString('return'); + $Itemid = $app->input->getInt('Itemid'); + $session = JFactory::getSession(); + $cart = $session->get('cart'); + $return = $app->input->getString('return'); - if (!$return) - { - if ($cart['idx'] < 1) - { - $app->redirect(JRoute::_('index.php?option=com_redshop&view=cart&Itemid=' . $Itemid)); - } - } + if (!$return) { + if ($cart['idx'] < 1) { + $app->redirect(JRoute::_('index.php?option=com_redshop&view=cart&Itemid=' . $Itemid)); + } + } - /** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/redshop.validation.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.validation.min.js', false, true); - $model = $this->getModel('quotation'); + $model = $this->getModel('quotation'); - $detail = $model->getData(); + $detail = $model->getData(); - $this->detail = $detail; - $this->request_url = $uri->toString(); - JFilterOutput::cleanText($this->request_url); + $this->detail = $detail; + $this->request_url = $uri->toString(); + JFilterOutput::cleanText($this->request_url); - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/site/views/quotation_detail/tmpl/default.php b/component/site/views/quotation_detail/tmpl/default.php index 5492c92f5fc..213cdbfc2d6 100644 --- a/component/site/views/quotation_detail/tmpl/default.php +++ b/component/site/views/quotation_detail/tmpl/default.php @@ -12,14 +12,14 @@ $template = RedshopHelperTemplate::getTemplate("quotation_detail"); if (isset($template[0]->template_desc) && !empty(trim($template[0]->template_desc))) { - $quotationTemplate = $template[0]->template_desc; + $quotationTemplate = $template[0]->template_desc; } else { - $quotationTemplate = RedshopHelperTemplate::getDefaultTemplateContent('quotation_detail'); + $quotationTemplate = RedshopHelperTemplate::getDefaultTemplateContent('quotation_detail'); } echo RedshopTagsReplacer::_( - 'quotationdetail', - $quotationTemplate, - [] + 'quotationdetail', + $quotationTemplate, + [] ); diff --git a/component/site/views/quotation_detail/view.html.php b/component/site/views/quotation_detail/view.html.php index 99a7b4f6c9b..e2caa55beed 100644 --- a/component/site/views/quotation_detail/view.html.php +++ b/component/site/views/quotation_detail/view.html.php @@ -16,79 +16,70 @@ */ class RedshopViewQuotation_Detail extends RedshopView { - /** - * @param null $tpl - * - * @return mixed|void - * @throws Exception - */ - public function display($tpl = null) - { - $app = JFactory::getApplication(); - $print = $app->input->getInt('print'); + /** + * @param null $tpl + * + * @return mixed|void + * @throws Exception + */ + public function display($tpl = null) + { + $app = JFactory::getApplication(); + $print = $app->input->getInt('print'); - if ($print) - { - ?> - - + + input->getInt('Itemid'); - $quoid = $app->input->getInt('quoid'); - $encr = $app->input->getString('encr'); + $user = JFactory::getUser(); + $itemId = $app->input->getInt('Itemid'); + $quoid = $app->input->getInt('quoid'); + $encr = $app->input->getString('encr'); - if (!$quoid) - { - $app->redirect(JRoute::_('index.php?option=com_redshop&view=account&Itemid=' . $itemId, false)); - } + if (!$quoid) { + $app->redirect(JRoute::_('index.php?option=com_redshop&view=account&Itemid=' . $itemId, false)); + } - $quotationDetail = RedshopHelperQuotation::getQuotationDetail($quoid); + $quotationDetail = RedshopHelperQuotation::getQuotationDetail($quoid); - if (empty($quotationDetail)) - { - JError::raiseWarning(404, JText::_('COM_REDSHOP_NOACCESS_QUOTATION')); - echo JText::_('COM_REDSHOP_NOACCESS_QUOTATION'); + if (empty($quotationDetail)) { + JError::raiseWarning(404, JText::_('COM_REDSHOP_NOACCESS_QUOTATION')); + echo JText::_('COM_REDSHOP_NOACCESS_QUOTATION'); - return; - } + return; + } - if (!$user->id) - { - if (isset($encr)) - { - $model = $this->getModel('quotation_detail'); - $authorization = $model->checkAuthorization($quoid, $encr); + if (!$user->id) { + if (isset($encr)) { + $model = $this->getModel('quotation_detail'); + $authorization = $model->checkAuthorization($quoid, $encr); - if (!$authorization) - { - JError::raiseWarning(404, JText::_('COM_REDSHOP_QUOTATION_ENCKEY_FAILURE')); - echo JText::_('COM_REDSHOP_QUOTATION_ENCKEY_FAILURE'); + if (!$authorization) { + JError::raiseWarning(404, JText::_('COM_REDSHOP_QUOTATION_ENCKEY_FAILURE')); + echo JText::_('COM_REDSHOP_QUOTATION_ENCKEY_FAILURE'); - return false; - } - } - else - { - $app->redirect(JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . $app->input->getInt('Itemid'))); + return false; + } + } else { + $app->redirect( + JRoute::_('index.php?option=com_redshop&view=login&Itemid=' . $app->input->getInt('Itemid')) + ); - return; - } - } - else - { - if (isset($quotationDetail->user_id) && $quotationDetail->user_id != $user->id) - { - JError::raiseWarning(404, JText::_('COM_REDSHOP_NOACCESS_QUOTATION')); - echo JText::_('COM_REDSHOP_NOACCESS_QUOTATION'); + return; + } + } else { + if (isset($quotationDetail->user_id) && $quotationDetail->user_id != $user->id) { + JError::raiseWarning(404, JText::_('COM_REDSHOP_NOACCESS_QUOTATION')); + echo JText::_('COM_REDSHOP_NOACCESS_QUOTATION'); - return; - } - } + return; + } + } - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/component/site/views/ratings/tmpl/default.php b/component/site/views/ratings/tmpl/default.php index 93e80263148..cfd1389441a 100644 --- a/component/site/views/ratings/tmpl/default.php +++ b/component/site/views/ratings/tmpl/default.php @@ -11,36 +11,31 @@ $mainTemplate = RedshopHelperTemplate::getTemplate("review"); -if (count($mainTemplate) > 0 && $mainTemplate[0]->template_desc) -{ - $mainTemplate = $mainTemplate[0]->template_desc; -} -else -{ - $mainTemplate = RedshopHelperTemplate::getDefaultTemplateContent('review'); +if (count($mainTemplate) > 0 && $mainTemplate[0]->template_desc) { + $mainTemplate = $mainTemplate[0]->template_desc; +} else { + $mainTemplate = RedshopHelperTemplate::getDefaultTemplateContent('review'); } -if ($this->params->get('show_page_heading', 1)) -{ - if ($this->params->get('page_title')) - { - ?> -

    - escape($this->params->get('page_title')); ?> -

    - params->get('show_page_heading', 1)) { + if ($this->params->get('page_title')) { + ?> +

    + escape($this->params->get('page_title')); ?> +

    + $this->detail, - 'model' => $this->getModel('ratings'), - 'params' => $this->params - ) + 'reviews', + $mainTemplate, + array( + 'products' => $this->detail, + 'model' => $this->getModel('ratings'), + 'params' => $this->params + ) ); echo eval("?>" . $mainTemplate . "getParams('com_redshop'); + $params = $app->getParams('com_redshop'); - $detail = $this->get('data'); - $pagination = $this->get('pagination'); + $detail = $this->get('data'); + $pagination = $this->get('pagination'); - $this->detail = $detail; - $this->pagination = $pagination; - $this->params = $params; - parent::display($tpl); - } + $this->detail = $detail; + $this->pagination = $pagination; + $this->params = $params; + parent::display($tpl); + } } diff --git a/component/site/views/registration/tmpl/default.php b/component/site/views/registration/tmpl/default.php index e5effb57646..4045cb6964b 100644 --- a/component/site/views/registration/tmpl/default.php +++ b/component/site/views/registration/tmpl/default.php @@ -16,70 +16,71 @@ $isCompany = $this->lists['is_company']; -if ($this->params->get('show_page_heading', 1)) -{ - if ($this->params->get('page_title')) - { - ?> -

    - -

    - +if ($this->params->get('show_page_heading', 1)) { + if ($this->params->get('page_title')) { + ?> +

    + +

    +
    - lists['showCustomerdesc'];?>> + lists['showCustomerdesc']; ?>> - lists['showCompanydesc']; ?>> + lists['showCompanydesc']; ?>>
    - - + +
    -
    - +
    + - lists, 0, 1, 1); + lists, 0, 1, 1); - echo RedshopLayoutHelper::render('registration.captcha'); + echo RedshopLayoutHelper::render('registration.captcha'); - if (Redshop::getConfig()->get('SHOW_TERMS_AND_CONDITIONS') == 1) - { - echo \Redshop\Terms\Tag::replaceTermsConditions("{terms_and_conditions}"); - } + if (Redshop::getConfig()->get('SHOW_TERMS_AND_CONDITIONS') == 1) { + echo \Redshop\Terms\Tag::replaceTermsConditions("{terms_and_conditions}"); + } - ?> + ?> - + -
    +
    - - - - - - - - - - - - -
    + + + + + + + + + + + + +
    diff --git a/component/site/views/registration/tmpl/default.xml b/component/site/views/registration/tmpl/default.xml index 63ec382dcf8..ed9efa6a9f5 100644 --- a/component/site/views/registration/tmpl/default.xml +++ b/component/site/views/registration/tmpl/default.xml @@ -9,8 +9,8 @@
    + label="COM_REDSHOP_REGISTRATION_REDIRECTION_PAGE" + description="COM_REDSHOP_REGISTRATION_REDIRECTION_PAGE_DESC"/>
    \ No newline at end of file diff --git a/component/site/views/registration/view.html.php b/component/site/views/registration/view.html.php index d0b2e16ff23..2dfac631252 100644 --- a/component/site/views/registration/view.html.php +++ b/component/site/views/registration/view.html.php @@ -12,79 +12,75 @@ class RedshopViewRegistration extends RedshopView { - public function display($tpl = null) - { - $app = JFactory::getApplication(); - - $Itemid = $app->input->getInt('Itemid'); - - $user = JFactory::getUser(); - $session = JFactory::getSession(); - $auth = $session->get('auth'); - - if ($user->id || (isset($auth['users_info_id']) && $auth['users_info_id'] > 0)) - { - $app->redirect(JRoute::_('index.php?option=com_redshop&view=account&Itemid=' . $Itemid)); - } - - $params = $app->getParams('com_redshop'); - JHtml::_('redshopjquery.framework'); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/jquery.validate.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/redshop.common.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/jquery.metadata.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/redshop.registration.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::stylesheet('com_redshop/redshop.validation.min.css', array(), true); - - JPluginHelper::importPlugin('redshop_vies_registration'); - - $jInput = JFactory::getApplication()->input; - $openToStretcher = 0; - $isCompany = $jInput->getInt('is_company', 0); - - if ($isCompany == 1 || Redshop::getConfig()->get('DEFAULT_CUSTOMER_REGISTER_TYPE') == 2) - { - $openToStretcher = 1; - } - - // Allow registration type settings - $lists['allowCustomer'] = ""; - $lists['allowCompany'] = ""; - $lists['showCustomerdesc'] = ""; - $lists['showCompanydesc'] = "style='display:none;'"; - - if (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 1) - { - $lists['allowCompany'] = "style='display:none;'"; - $openToStretcher = 0; - } - elseif (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 2) - { - $lists['allowCustomer'] = "style='display:none;'"; - $lists['showCustomerdesc'] = "style='display:none;'"; - $openToStretcher = 1; - } - - if (Redshop::getConfig()->get('DEFAULT_CUSTOMER_REGISTER_TYPE') == 2) - { - $lists['showCompanydesc'] = ''; - $lists['showCustomerdesc'] = "style='display:none;'"; - } - - $lists['is_company'] = ($openToStretcher == 1 || ($isCompany == 1)) ? 1 : 0; - - if ($lists['is_company']) - { - // Field_section 8 : Company Address - $lists['extra_field_company'] = Redshop\Fields\SiteHelper::renderFields(8); - } - else - { - // Field_section 7 : Customer Registration - $lists['extra_field_user'] = Redshop\Fields\SiteHelper::renderFields(7); - } - - $this->lists = $lists; - $this->params = $params; - parent::display($tpl); - } + public function display($tpl = null) + { + $app = JFactory::getApplication(); + + $Itemid = $app->input->getInt('Itemid'); + + $user = JFactory::getUser(); + $session = JFactory::getSession(); + $auth = $session->get('auth'); + + if ($user->id || (isset($auth['users_info_id']) && $auth['users_info_id'] > 0)) { + $app->redirect(JRoute::_('index.php?option=com_redshop&view=account&Itemid=' . $Itemid)); + } + + $params = $app->getParams('com_redshop'); + JHtml::_('redshopjquery.framework'); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/jquery.validate.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.common.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/jquery.metadata.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.registration.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::stylesheet('com_redshop/redshop.validation.min.css', array(), true); + + JPluginHelper::importPlugin('redshop_vies_registration'); + + $jInput = JFactory::getApplication()->input; + $openToStretcher = 0; + $isCompany = $jInput->getInt('is_company', 0); + + if ($isCompany == 1 || Redshop::getConfig()->get('DEFAULT_CUSTOMER_REGISTER_TYPE') == 2) { + $openToStretcher = 1; + } + + // Allow registration type settings + $lists['allowCustomer'] = ""; + $lists['allowCompany'] = ""; + $lists['showCustomerdesc'] = ""; + $lists['showCompanydesc'] = "style='display:none;'"; + + if (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 1) { + $lists['allowCompany'] = "style='display:none;'"; + $openToStretcher = 0; + } elseif (Redshop::getConfig()->get('ALLOW_CUSTOMER_REGISTER_TYPE') == 2) { + $lists['allowCustomer'] = "style='display:none;'"; + $lists['showCustomerdesc'] = "style='display:none;'"; + $openToStretcher = 1; + } + + if (Redshop::getConfig()->get('DEFAULT_CUSTOMER_REGISTER_TYPE') == 2) { + $lists['showCompanydesc'] = ''; + $lists['showCustomerdesc'] = "style='display:none;'"; + } + + $lists['is_company'] = ($openToStretcher == 1 || ($isCompany == 1)) ? 1 : 0; + + if ($lists['is_company']) { + // Field_section 8 : Company Address + $lists['extra_field_company'] = Redshop\Fields\SiteHelper::renderFields(8); + } else { + // Field_section 7 : Customer Registration + $lists['extra_field_user'] = Redshop\Fields\SiteHelper::renderFields(7); + } + + $this->lists = $lists; + $this->params = $params; + parent::display($tpl); + } } diff --git a/component/site/views/search/tmpl/default.php b/component/site/views/search/tmpl/default.php index 58986c56f46..55bf4c51845 100644 --- a/component/site/views/search/tmpl/default.php +++ b/component/site/views/search/tmpl/default.php @@ -9,741 +9,798 @@ defined('_JEXEC') or die; -if (count($this->search) > 0) -{ - JPluginHelper::importPlugin('redshop_product'); - - $app = JFactory::getApplication(); - $input = JFactory::getApplication()->input; - $input->set('order_by', $app->getUserState('order_by')); - - $dispatcher = RedshopHelperUtility::getDispatcher(); - - $Itemid = $app->input->getInt('Itemid'); - $search_type = $app->input->getCmd('search_type'); - $cid = $app->input->getInt('category_id'); - $manufacture_id = $app->input->getInt('manufacture_id'); - - $templateid = $app->input->getInt('templateid'); - - // Cmd removes space between to words - $keyword = $app->input->getString('keyword'); - $layout = $app->input->getCmd('layout', 'default'); - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('name')) - ->from($db->qn('#__redshop_category')) - ->where($db->qn('id') . ' = ' . $db->q((int) $input->getInt('cid', 0))); - - $cat_name = $db->setQuery($query)->loadResult(); - - $model = $this->getModel('search'); - $total = $model->getTotal(); - - JHTML::_('behavior.modal'); - $url = JURI::base(); - - if ($this->params->get('page_title') != "") - { - $pagetitle = $this->params->get('page_title'); - } - else - { - $pagetitle = JText::_('COM_REDSHOP_SEARCH'); - } - - if ($this->params->get('show_page_heading', 1)) - { - echo '

    '; - echo $pagetitle; - echo '

    '; - } - - echo '
    '; - $category_tmpl = ""; - - if ($this->templatedata != "") - { - $templateDesc = $this->templatedata; - } - else - { - $templateDesc = "
    {print}
    \r\n
    \r\n
    {category_main_description}
    \r\n

    {if subcats} {category_loop_start}

    \r\n
    \r\n
    \r\n
    {category_thumb_image}
    \r\n
    \r\n

    {category_name}

    \r\n{category_description}
    \r\n
    \r\n
    \r\n

    {category_loop_end} {subcats end if}

    \r\n
    \r\n
    \r\n
    {order_by}
    \r\n
    \r\n
    {product_loop_start}\r\n
    \r\n
    \r\n
    {product_thumb_image}
    \r\n
    \r\n

    {product_name}

    \r\n
    \r\n
    {product_price}
    \r\n
    {read_more}
    \r\n
    {product_rating_summary}
    \r\n
    {form_addtocart:add_to_cart1}
    \r\n
    \r\n
    \r\n{product_loop_end}\r\n
    \r\n
    \r\n
    {pagination}
    "; - } - - $template_org = $templateDesc; - $template_d1 = explode("{category_loop_start}", $template_org); - - if (count($template_d1) > 1) - { - $template_d2 = explode("{category_loop_end}", $template_d1[1]); - - if (count($template_d2) > 0) - { - $category_tmpl = $template_d2[0]; - } - } - - $template_org = str_replace($category_tmpl, "", $template_org); - $template_org = str_replace("{category_loop_start}", "", $template_org); - $template_org = str_replace("{category_loop_end}", "", $template_org); - $print = $app->input->getInt('print'); - $p_url = @ explode('?', $app->input->server->get('REQUEST_URI', '', 'raw')); - $print_tag = ''; - - if ($print) - { - $print_tag = "" . JText::_("; - } - else - { - $print_url = $url . "index.php?option=com_redshop&view=search&print=1&tmpl=component"; - $print_tag = "" . JText::_("; - } - - if (strstr($template_org, '{compare_product_div}')) - { - $compareProductDiv = ''; - - if (Redshop::getConfig()->get('PRODUCT_COMPARISON_TYPE') != '') - { - $compareProductDiv = RedshopLayoutHelper::render('product.compare_product'); - } - - $template_org = str_replace('{compare_product_div}', $compareProductDiv, $template_org); - } - - // Skip html if nosubcategory - if (strstr($template_org, "{if subcats}")) - { - $template_d1 = explode("{if subcats}", $template_org); - $template_d2 = explode("{subcats end if}", $template_d1[1]); - $template_org = $template_d1[0] . $template_d2[1]; - } - - // End skip html if nosubcategory - $template_org = str_replace("{print}", $print_tag, $template_org); - $template_org = str_replace("{product_price_slider}", '', $template_org); - $template_org = str_replace("{filter_by}", '', $template_org); - $template_org = str_replace("{template_selector_category_lbl}", '', $template_org); - $template_org = str_replace("{template_selector_category}", '', $template_org); - $template_org = str_replace("{category_main_name}", $cat_name, $template_org); - $template_org = str_replace("{category_main_description}", '', $template_org); - $template_org = str_replace("{category_description}", '', $template_org); - $template_org = str_replace("{category_short_desc}", '', $template_org); - $template_org = str_replace("{if subcats}", '', $template_org); - $template_org = str_replace("{subcats end if}", '', $template_org); - $template_org = str_replace("{category_main_thumb_image_3}", '', $template_org); - $template_org = str_replace("{category_main_short_desc}", '', $template_org); - $template_org = str_replace("{category_main_thumb_image_2}", '', $template_org); - $template_org = str_replace("{category_main_thumb_image_1}", '', $template_org); - $template_org = str_replace("{category_main_thumb_image}", '', $template_org); - $template_org = str_replace("{attribute_price_without_vat}", '', $template_org); - $template_org = str_replace("{redproductfinderfilter_formstart}", '', $template_org); - $template_org = str_replace("{redproductfinderfilter:rp_myfilter}", '', $template_org); - $template_org = str_replace("{redproductfinderfilter_formend}", '', $template_org); - $template_org = str_replace("{total_product}", $total, $template_org); - $template_org = str_replace("{total_product_lbl}", JText::_('COM_REDSHOP_TOTAL_PRODUCT'), $template_org); - - // Replace redproductfilder filter tag - if (strstr($template_org, "{redproductfinderfilter:")) - { - $redProductFinerHelper = JPATH_SITE . "/components/com_redproductfinder/helpers/redproductfinder_helper.php"; - if (file_exists($redProductFinerHelper)) - { - include_once $redProductFinerHelper; - $redproductfinder_helper = new redproductfinder_helper; - $hdnFields = array('texpricemin' => '0', 'texpricemax' => '0', 'manufacturer_id' => $filter_by, 'category_template' => $templateid); - $hide_filter_flag = false; - - if ($this->_id) - { - $prodctofcat = RedshopHelperProduct::getProductCategory($this->_id); - - if (empty($prodctofcat)) - $hide_filter_flag = true; - } - - $template_org = $redproductfinder_helper->replaceProductfinder_tag($template_org, $hdnFields, $hide_filter_flag); - } - } - - // Replace redproductfilder filter tag end here - $template_d1 = explode("{product_loop_start}", $template_org); - $template_d2 = explode("{product_loop_end}", $template_d1[1]); - $template_tmp_desc = $template_d2[0]; - $templateDesc = $template_d2[0]; - - // Order By - $order_by = ""; - $orderby_form = "
    "; - $orderby_form .= $this->lists['order_select']; - $orderby_form .= " +if (count($this->search) > 0) { + JPluginHelper::importPlugin('redshop_product'); + + $app = JFactory::getApplication(); + $input = JFactory::getApplication()->input; + $input->set('order_by', $app->getUserState('order_by')); + + $dispatcher = RedshopHelperUtility::getDispatcher(); + + $Itemid = $app->input->getInt('Itemid'); + $search_type = $app->input->getCmd('search_type'); + $cid = $app->input->getInt('category_id'); + $manufacture_id = $app->input->getInt('manufacture_id'); + + $templateid = $app->input->getInt('templateid'); + + // Cmd removes space between to words + $keyword = $app->input->getString('keyword'); + $layout = $app->input->getCmd('layout', 'default'); + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('name')) + ->from($db->qn('#__redshop_category')) + ->where($db->qn('id') . ' = ' . $db->q((int)$input->getInt('cid', 0))); + + $cat_name = $db->setQuery($query)->loadResult(); + + $model = $this->getModel('search'); + $total = $model->getTotal(); + + JHTML::_('behavior.modal'); + $url = JURI::base(); + + if ($this->params->get('page_title') != "") { + $pagetitle = $this->params->get('page_title'); + } else { + $pagetitle = JText::_('COM_REDSHOP_SEARCH'); + } + + if ($this->params->get('show_page_heading', 1)) { + echo '

    '; + echo $pagetitle; + echo '

    '; + } + + echo '
    '; + $category_tmpl = ""; + + if ($this->templatedata != "") { + $templateDesc = $this->templatedata; + } else { + $templateDesc = "
    {print}
    \r\n
    \r\n
    {category_main_description}
    \r\n

    {if subcats} {category_loop_start}

    \r\n
    \r\n
    \r\n
    {category_thumb_image}
    \r\n
    \r\n

    {category_name}

    \r\n{category_description}
    \r\n
    \r\n
    \r\n

    {category_loop_end} {subcats end if}

    \r\n
    \r\n
    \r\n
    {order_by}
    \r\n
    \r\n
    {product_loop_start}\r\n
    \r\n
    \r\n
    {product_thumb_image}
    \r\n
    \r\n

    {product_name}

    \r\n
    \r\n
    {product_price}
    \r\n
    {read_more}
    \r\n
    {product_rating_summary}
    \r\n
    {form_addtocart:add_to_cart1}
    \r\n
    \r\n
    \r\n{product_loop_end}\r\n
    \r\n
    \r\n
    {pagination}
    "; + } + + $template_org = $templateDesc; + $template_d1 = explode("{category_loop_start}", $template_org); + + if (count($template_d1) > 1) { + $template_d2 = explode("{category_loop_end}", $template_d1[1]); + + if (count($template_d2) > 0) { + $category_tmpl = $template_d2[0]; + } + } + + $template_org = str_replace($category_tmpl, "", $template_org); + $template_org = str_replace("{category_loop_start}", "", $template_org); + $template_org = str_replace("{category_loop_end}", "", $template_org); + $print = $app->input->getInt('print'); + $p_url = @ explode('?', $app->input->server->get('REQUEST_URI', '', 'raw')); + $print_tag = ''; + + if ($print) { + $print_tag = "" . JText::_(
+                "; + } else { + $print_url = $url . "index.php?option=com_redshop&view=search&print=1&tmpl=component"; + $print_tag = "" . JText::_(
+                "; + } + + if (strstr($template_org, '{compare_product_div}')) { + $compareProductDiv = ''; + + if (Redshop::getConfig()->get('PRODUCT_COMPARISON_TYPE') != '') { + $compareProductDiv = RedshopLayoutHelper::render('product.compare_product'); + } + + $template_org = str_replace('{compare_product_div}', $compareProductDiv, $template_org); + } + + // Skip html if nosubcategory + if (strstr($template_org, "{if subcats}")) { + $template_d1 = explode("{if subcats}", $template_org); + $template_d2 = explode("{subcats end if}", $template_d1[1]); + $template_org = $template_d1[0] . $template_d2[1]; + } + + // End skip html if nosubcategory + $template_org = str_replace("{print}", $print_tag, $template_org); + $template_org = str_replace("{product_price_slider}", '', $template_org); + $template_org = str_replace("{filter_by}", '', $template_org); + $template_org = str_replace("{template_selector_category_lbl}", '', $template_org); + $template_org = str_replace("{template_selector_category}", '', $template_org); + $template_org = str_replace("{category_main_name}", $cat_name, $template_org); + $template_org = str_replace("{category_main_description}", '', $template_org); + $template_org = str_replace("{category_description}", '', $template_org); + $template_org = str_replace("{category_short_desc}", '', $template_org); + $template_org = str_replace("{if subcats}", '', $template_org); + $template_org = str_replace("{subcats end if}", '', $template_org); + $template_org = str_replace("{category_main_thumb_image_3}", '', $template_org); + $template_org = str_replace("{category_main_short_desc}", '', $template_org); + $template_org = str_replace("{category_main_thumb_image_2}", '', $template_org); + $template_org = str_replace("{category_main_thumb_image_1}", '', $template_org); + $template_org = str_replace("{category_main_thumb_image}", '', $template_org); + $template_org = str_replace("{attribute_price_without_vat}", '', $template_org); + $template_org = str_replace("{redproductfinderfilter_formstart}", '', $template_org); + $template_org = str_replace("{redproductfinderfilter:rp_myfilter}", '', $template_org); + $template_org = str_replace("{redproductfinderfilter_formend}", '', $template_org); + $template_org = str_replace("{total_product}", $total, $template_org); + $template_org = str_replace("{total_product_lbl}", JText::_('COM_REDSHOP_TOTAL_PRODUCT'), $template_org); + + // Replace redproductfilder filter tag + if (strstr($template_org, "{redproductfinderfilter:")) { + $redProductFinerHelper = JPATH_SITE . "/components/com_redproductfinder/helpers/redproductfinder_helper.php"; + if (file_exists($redProductFinerHelper)) { + include_once $redProductFinerHelper; + $redproductfinder_helper = new redproductfinder_helper; + $hdnFields = array( + 'texpricemin' => '0', + 'texpricemax' => '0', + 'manufacturer_id' => $filter_by, + 'category_template' => $templateid + ); + $hide_filter_flag = false; + + if ($this->_id) { + $prodctofcat = RedshopHelperProduct::getProductCategory($this->_id); + + if (empty($prodctofcat)) { + $hide_filter_flag = true; + } + } + + $template_org = $redproductfinder_helper->replaceProductfinder_tag( + $template_org, + $hdnFields, + $hide_filter_flag + ); + } + } + + // Replace redproductfilder filter tag end here + $template_d1 = explode("{product_loop_start}", $template_org); + $template_d2 = explode("{product_loop_end}", $template_d1[1]); + $template_tmp_desc = $template_d2[0]; + $templateDesc = $template_d2[0]; + + // Order By + $order_by = ""; + $orderby_form = ""; + $orderby_form .= $this->lists['order_select']; + $orderby_form .= "
    "; - if (strstr($templateDesc, '{order_by}')) - { - $order_by = $orderby_form; - } - - $extraFieldName = Redshop\Helper\ExtraFields::getSectionFieldNames(1, 1, 1); - $extraFieldsForCurrentTemplate = RedshopHelperTemplate::getExtraFieldsForCurrentTemplate($extraFieldName, $templateDesc, 1); - $attribute_template = \Redshop\Template\Helper::getAttribute($templateDesc); - - $total_product = $model->getTotal(); - $endlimit = $model->getState('list.limit'); - $start = $model->getState('list.start'); - - $tagarray = RedshopHelperText::getTextLibraryTagArray(); - $data = ""; - $count_no_user_field = 0; - $fieldArray = RedshopHelperExtrafields::getSectionFieldList(17, 0, 0); - - for ($i = 0, $countSearch = count($this->search); $i < $countSearch; $i++) - { - $this->search[$i]->stockroom = RedshopHelperStockroom::getStockroomTotalAmount($this->search[$i]->product_id); - $this->search[$i]->product_related = RedshopHelperProduct::getRelatedProduct($this->search[$i]->product_id); - $this->search[$i]->count_product_related = count($this->search[$i]->product_related); - - $data_add = $templateDesc; - - // RedSHOP Product Plugin - $params = array(); - $dispatcher->trigger('onPrepareProduct', array(&$data_add, &$params, $this->search[$i])); - - $thum_image = ""; - $pname = RedshopHelperUtility::maxChars($this->search[$i]->product_name, Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_MAX_CHARS'), Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_END_SUFFIX')); - - if ($search_type == 'product_number') - { - $product_number = preg_replace("/($keyword)/i", "$1", $this->search[$i]->product_number); - $pro_s_desc = $this->search[$i]->product_s_desc; - $pro_desc = $this->search[$i]->product_desc; - } - else - { - $product_number = $this->search[$i]->product_number; - $pro_s_desc = $this->search[$i]->product_s_desc; - $pro_desc = $this->search[$i]->product_desc; - - if (!empty($keyword) && !in_array($keyword, $tagarray)) - { - $regex = "/" . preg_quote($keyword, "/") . "(?![^<]*>)/"; - $pname = preg_replace($regex, "" . $keyword . "", $pname); - $product_number = preg_replace($regex, "" . $keyword . "", $product_number); - $pro_s_desc = preg_replace($regex, "" . $keyword . "", $pro_s_desc); - $pro_desc = preg_replace($regex, "" . $keyword . "", $pro_desc); - } - } - - $pro_s_desc = RedshopHelperUtility::maxChars($pro_s_desc, Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_MAX_CHARS'), Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_END_SUFFIX')); - - $ItemData = RedshopHelperProduct::getMenuInformation(0, 0, '', 'product&pid=' . $this->search[$i]->product_id); - - if (!empty($ItemData)) - { - $pItemid = $ItemData->id; - } - else - { - $pItemid = RedshopHelperRouter::getItemId($this->search[$i]->product_id, $this->search[$i]->category_id); - } - - $link = JRoute::_('index.php?option=com_redshop&view=product&pid=' . $this->search[$i]->product_id . '&cid=' . $this->search[$i]->cat_in_sefurl . '&Itemid=' . $pItemid); - - if (strstr($data_add, '{product_name}')) - { - $pname = "" . $pname . ""; - $data_add = str_replace("{product_name}", $pname, $data_add); - } - - if (strstr($data_add, '{product_name_nolink}')) - { - $data_add = str_replace("{product_name_nolink}", $pname, $data_add); - } - - $readmore = "" . JText::_('COM_REDSHOP_READ_MORE') . ""; - $data_add = str_replace("{read_more}", $readmore, $data_add); - $data_add = str_replace("{read_more_link}", $link, $data_add); - - if (strstr($data_add, "{product_delivery_time}")) - { - $product_delivery_time = RedshopHelperProduct::getProductMinDeliveryTime($this->search[$i]->product_id); - - if ($product_delivery_time != "") - { - $data_add = str_replace("{delivery_time_lbl}", JText::_('DELIVERY_TIME'), $data_add); - $data_add = str_replace("{product_delivery_time}", $product_delivery_time, $data_add); - } - else - { - $data_add = str_replace("{delivery_time_lbl}", "", $data_add); - $data_add = str_replace("{product_delivery_time}", "", $data_add); - } - } - - // Product Review/Rating - // Fetching reviews - $final_avgreview_data = Redshop\Product\Rating::getRating($this->search[$i]->product_id); - - // Attribute ajax chage - $data_add = str_replace("{product_rating_summary}", $final_avgreview_data, $data_add); - $data_add = RedshopHelperProduct::getJcommentEditor($this->search[$i], $data_add); - - if ($extraFieldsForCurrentTemplate) - { - $data_add = Redshop\Helper\ExtraFields::displayExtraFields(1, $this->search[$i]->product_id, $extraFieldsForCurrentTemplate, $data_add, true); - } - - $data_add = str_replace("{product_s_desc}", $pro_s_desc, $data_add); - $data_add = str_replace("{product_desc}", $pro_desc, $data_add); - $data_add = str_replace("{product_id_lbl}", JText::_('COM_REDSHOP_PRODUCT_ID_LBL'), $data_add); - $data_add = str_replace("{product_id}", $this->search[$i]->product_id, $data_add); - $data_add = str_replace("{product_number_lbl}", JText::_('COM_REDSHOP_PRODUCT_NUMBER_LBL'), $data_add); - $data_add = str_replace("{product_number}", $product_number, $data_add); - - // Product category tags - $data_add = str_replace("{returntocategory_name}", $this->search[$i]->category_name, $data_add); - - if (strstr($data_add, "{returntoparent_category_name}")) - { - $parentCategoryId = RedshopHelperProduct::getParentCategory($this->search[$i]->category_id); - - if ($parentCategoryId != 0) - { - $parentCategory = RedshopEntityCategory::getInstance($parentCategoryId)->getItem(); - $data_add = str_replace("{returntoparent_category_name}", $parentCategory->category_name, $data_add); - } - else - { - $data_add = str_replace("{returntoparent_category_name}", '', $data_add); - } - } - - /** - * related Product List in Lightbox - * Tag Format = {related_product_lightbox:[:width][:height]} - */ - if (strstr($data_add, '{related_product_lightbox:')) - { - $related_product = RedshopHelperProduct::getRelatedProduct($this->search[$i]->product_id); - $rtlnone = explode("{related_product_lightbox:", $data_add); - $rtlntwo = explode("}", $rtlnone[1]); - $rtlnthree = explode(":", $rtlntwo[0]); - $rtln = $rtlnthree[0]; - $rtlnfwidth = (isset($rtlnthree[1])) ? $rtlnthree[1] : "900"; - $rtlnwidthtag = (isset($rtlnthree[1])) ? ":" . $rtlnthree[1] : ""; - - $rtlnfheight = (isset($rtlnthree[2])) ? $rtlnthree[2] : "600"; - $rtlnheighttag = (isset($rtlnthree[2])) ? ":" . $rtlnthree[2] : ""; - - $rtlntag = "{related_product_lightbox:$rtln$rtlnwidthtag$rtlnheighttag}"; - - if (count($related_product) > 0) - { - $linktortln = JURI::root() . "index.php?option=com_redshop&view=product&pid=" . $this->search[$i]->product_id . "&tmpl=component&template=" . $rtln . "&for=rtln"; - $rtlna = '' . JText::_('COM_REDSHOP_RELATED_PRODUCT_LIST_IN_LIGHTBOX') . ''; - } - else - { - $rtlna = ""; - } - - $data_add = str_replace($rtlntag, $rtlna, $data_add); - } - - $data_add = RedshopHelperTax::replaceVatInformation($data_add); - - /************************************ - * Conditional tag - * if product on discount : Yes - * {if product_on_sale} This product is on sale {product_on_sale end if} // OUTPUT : This product is on sale - * NO : // OUTPUT : Display blank - ************************************/ - - /* count product related start */ - if(isset($this->search[$i]->count_product_related) && $this->search[$i]->count_product_related) - { - $data_add = str_replace("{countrelated}","
  • " . $this->search[$i]->count_product_related . ' ' . JText::_('COM_REDSHOP_COUNT_RELATED') . "" . "
  • ", $data_add); - } - else - { - $data_add = str_replace("{countrelated}",'', $data_add); - } - /* count product related end */ - - /* stock room number start */ - $lang = JFactory::getLanguage(); - - if(isset($this->search[$i]->stockroom) && $this->search[$i]->stockroom == 0) - { - $data_add = str_replace("{stockroom}",'', $data_add); - } - else - { - $data_add = str_replace("{stockroom}","
  • " . - JText::sprintf('COM_REDSHOP_STOCK_AMOUNT_LEFT', $this->search[$i]->stockroom) . - "
  • " , $data_add); - } - /* stock room number end */ - - /*custom enddate discount start*/ - if(isset($this->search[$i]->discount_enddate) && $this->search[$i]->discount_enddate) - { - $data_add = str_replace("{discount_end_date}", date('d/m',$this->search[$i]->discount_enddate), $data_add); - } - else - { - $data_add = str_replace("{discount_end_date}", '', $data_add); - } - /*custom enddate discount end*/ - - $data_add = RedshopHelperProduct::getProductOnSaleComment($this->search[$i], $data_add); - - $data_add = RedshopHelperStockroom::replaceStockroomAmountDetail($data_add, $this->search[$i]->product_id); - - if (strstr($data_add, "{product_thumb_image_3}")) - { - $cimg_tag = '{product_thumb_image_3}'; - $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_3'); - $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_3'); - } - elseif (strstr($data_add, "{product_thumb_image_2}")) - { - $cimg_tag = '{product_thumb_image_2}'; - $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_2'); - $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_2'); - } - elseif (strstr($data_add, "{product_thumb_image_1}")) - { - $cimg_tag = '{product_thumb_image_1}'; - $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); - $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); - } - else - { - $cimg_tag = '{product_thumb_image}'; - $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); - $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); - } - - $hidden_thumb_image = ""; - $thum_image = Redshop\Product\Image\Image::getImage($this->search[$i]->product_id, $link, $cw_thumb, $ch_thumb); - $data_add = str_replace($cimg_tag, $thum_image . $hidden_thumb_image, $data_add); - - // More documents - if (strstr($data_add, "{more_documents}")) - { - $media_documents = RedshopHelperMedia::getAdditionMediaImage($this->search[$i]->product_id, "product", "document"); - $more_doc = ''; - - for ($m = 0, $countMedia = count($media_documents); $m < $countMedia; $m++) - { - $alttext = RedshopHelperMedia::getAlternativeText( - "product", $media_documents[$m]->section_id, "", $media_documents[$m]->media_id, "document" - ); - - if (!$alttext) - { - $alttext = $media_documents[$m]->media_name; - } - - if (JFile::exists(REDSHOP_FRONT_DOCUMENT_RELPATH . "product/" . $media_documents[$m]->media_name)) - { - $downlink = JURI::root() . 'index.php?tmpl=component&option=com_redshop&view=product&pid=' . $this->search[$i]->product_id . '&task=downloadDocument&fname=' . $media_documents[$m]->media_name . '&Itemid=' . $Itemid; - $more_doc .= ""; - } - } - - $data_add = str_replace("{more_documents}", "" . $more_doc . "", $data_add); - } - - // More documents end - - /************************************************ user fields*******************************************************/ - $hidden_userfield = ""; - $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($data_add); - $template_userfield = $returnArr[0]; - $userfieldArr = $returnArr[1]; - $count_no_user_field = 0; - - if ($template_userfield != "") - { - $ufield = ""; - - for ($ui = 0, $countUserField = count($userfieldArr); $ui < $countUserField; $ui++) - { - $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields($userfieldArr[$ui], 12, '', '', 0, $this->search[$i]->product_id); - $ufield .= $productUserFields[1]; - - if ($productUserFields[1] != "") - { - $count_no_user_field++; - } - - $data_add = str_replace('{' . $userfieldArr[$ui] . '_lbl}', $productUserFields[0], $data_add); - $data_add = str_replace('{' . $userfieldArr[$ui] . '}', $productUserFields[1], $data_add); - } - - $productUserFieldsForm = "
    "; - - if ($ufield != "") - { - $data_add = str_replace("{if product_userfield}", $productUserFieldsForm, $data_add); - $data_add = str_replace("{product_userfield end if}", "
    ", $data_add); - } - else - { - $data_add = str_replace("{if product_userfield}", "", $data_add); - $data_add = str_replace("{product_userfield end if}", "", $data_add); - } - } - elseif (Redshop::getConfig()->get('AJAX_CART_BOX')) - { - $ajax_detail_template_desc = ""; - $ajax_detail_template = \Redshop\Template\Helper::getAjaxDetailBox($this->search[$i]); - - if (null !== $ajax_detail_template) - { - $ajax_detail_template_desc = $ajax_detail_template->template_desc; - } - - $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($ajax_detail_template_desc); - $template_userfield = $returnArr[0]; - $userfieldArr = $returnArr[1]; - - if ($template_userfield != "") - { - $ufield = ""; - - for ($ui = 0, $countUserField = count($userfieldArr); $ui < $countUserField; $ui++) - { - $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields($userfieldArr[$ui], 12, '', '', 0, $this->search[$i]->product_id); - $ufield .= $productUserFields[1]; - - if ($productUserFields[1] != "") - { - $count_no_user_field++; - } - - $template_userfield = str_replace('{' . $userfieldArr[$ui] . '_lbl}', $productUserFields[0], $template_userfield); - $template_userfield = str_replace('{' . $userfieldArr[$ui] . '}', $productUserFields[1], $template_userfield); - } - - if ($ufield != "") - { - $hidden_userfield = "
    " . $template_userfield . "
    "; - } - } - } - - $data_add = $data_add . $hidden_userfield; - - /*************** end user fields ***************/ - - // ProductFinderDatepicker Extra Field Start - - $data_add = RedshopHelperProduct::getProductFinderDatepickerValue($data_add, $this->search[$i]->product_id, $fieldArray); - - // ProductFinderDatepicker Extra Field End - - /* - * manufacturer data - */ - $manufacturer_id = $this->search[$i]->id; - - if ($manufacturer_id != 0) - { - $manufacturer_link_href = JRoute::_('index.php?option=com_redshop&view=manufacturers&layout=detail&mid=' . $manufacturer_id . '&Itemid=' . $Itemid); - $manufacturer_name = $this->search[$i]->name; - $manufacturer_link = '' . $manufacturer_name . ''; - - if (strstr($data_add, "{manufacturer_link}")) - { - $data_add = str_replace("{manufacturer_name}", "", $data_add); - } - else - { - $data_add = str_replace("{manufacturer_name}", $manufacturer_name, $data_add); - } - - $data_add = str_replace("{manufacturer_link}", $manufacturer_link, $data_add); - } - else - { - $data_add = str_replace("{manufacturer_link}", "", $data_add); - $data_add = str_replace("{manufacturer_name}", "", $data_add); - } - - if (strpos($data_add, "{category_name}") !== false) - { - $category = RedshopEntityCategory::getInstance($this->search[$i]->cat_in_sefurl)->getItem(); - $title = " title='" . $category->name . "' "; - $linkCat = JRoute::_( - 'index.php?option=com_redshop'. - '&view=category&cid=' . $category->id . - '&manufacturer_id=' . $manufacturer_id . - '&layout=detail&Itemid=' . $mainItemid - ); - - $categoryName = '' . $category->name . ''; - $data_add = str_replace('{category_name}', $categoryName, $data_add); - } - - // End - - // Replace wishlistbutton - $data_add = RedshopHelperWishlist::replaceWishlistTag($this->search[$i]->product_id, $data_add); - - // Replace compare product button - $data_add = Redshop\Product\Compare::replaceCompareProductsButton($this->search[$i]->product_id, 0, $data_add); - - // Checking for child products - if ($this->search[$i]->count_child_products > 0) - { - $isChilds = true; - $attributes = array(); - } - else - { - $isChilds = false; - - // Get attributes - $attributes_set = array(); - - if ($this->search[$i]->attribute_set_id > 0) - { - $attributes_set = \Redshop\Product\Attribute::getProductAttribute(0, $this->search[$i]->attribute_set_id, 0, 1); - } - - $attributes = \Redshop\Product\Attribute::getProductAttribute($this->search[$i]->product_id); - $attributes = array_merge($attributes, $attributes_set); - } - - // Product attribute Start - $totalatt = count($attributes); - - // Check product for not for sale - $data_add = RedshopHelperProduct::getProductNotForSaleComment($this->search[$i], $data_add, $attributes); - - $data_add = Redshop\Product\Stock::replaceInStock($this->search[$i]->product_id, $data_add, $attributes, $attribute_template); - - $data_add = RedshopHelperAttribute::replaceAttributeData($this->search[$i]->product_id, 0, 0, $attributes, $data_add, $attribute_template, $isChilds); - - // Cart Template - $data_add = Redshop\Cart\Render::replace($this->search[$i]->product_id, 0, 0, 0, $data_add, $isChilds, $userfieldArr, $totalatt, 0, $count_no_user_field); - - $data_add = RedshopHelperProductTag::getExtraSectionTag($extraFieldName, $this->search[$i]->product_id, "1", $data_add); - - $productAvailabilityDate = strstr($data_add, "{product_availability_date}"); - $stockNotifyFlag = strstr($data_add, "{stock_notify_flag}"); - $stockStatus = strstr($data_add, "{stock_status"); - - $attributeproductStockStatus = array(); - - if ($productAvailabilityDate || $stockNotifyFlag || $stockStatus) - { - $attributeproductStockStatus = RedshopHelperProduct::getproductStockStatus($this->search[$i]->product_id, $totalatt); - } - - $data_add = \Redshop\Helper\Stockroom::replaceProductStockData( - $this->search[$i]->product_id, - 0, - 0, - $data_add, - $attributeproductStockStatus - ); - - $dispatcher->trigger('onAfterDisplayProduct', array(&$data_add, array(), $this->search[$i])); - - $data .= $data_add; - } - - $app = JFactory::getApplication(); - $router = $app->getRouter(); - - $getorderby = $app->input->get('order_by', Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD')); - - $vars = array( - 'option' => 'com_redshop', - 'view' => 'search', - 'layout' => $layout, - 'keyword' => $keyword, - 'manufacture_id' => $manufacture_id, - 'order_by' => $getorderby, - 'category_id' => $cid, - 'Itemid' => $Itemid, - 'search_type' => $search_type - ); - $router->setVars($vars); - unset($vars); - - if (strstr($template_org, "{show_all_products_in_category}")) - { - $template_org = str_replace("{show_all_products_in_category}", "", $template_org); - $template_org = str_replace("{pagination}", "", $template_org); - } - - $pagination = new JPagination($total_product, $start, $endlimit); - - if (strstr($template_org, "{pagination}")) - { - $template_org = str_replace("{pagination}", $pagination->getPagesLinks(), $template_org); - } - - $usePerPageLimit = false; - - if (strstr($template_org, "perpagelimit:")) - { - $usePerPageLimit = true; - $perpage = explode('{perpagelimit:', $template_org); - $perpage = explode('}', $perpage[1]); - $template_org = str_replace("{perpagelimit:" . intval($perpage[0]) . "}", "", $template_org); - } - - if (strstr($template_org, "{product_display_limit}")) - { - if ($usePerPageLimit) - { - $limitBox = ''; - } - else - { - $limitBox = "
    + if (strstr($templateDesc, '{order_by}')) { + $order_by = $orderby_form; + } + + $extraFieldName = Redshop\Helper\ExtraFields::getSectionFieldNames(1, 1, 1); + $extraFieldsForCurrentTemplate = RedshopHelperTemplate::getExtraFieldsForCurrentTemplate( + $extraFieldName, + $templateDesc, + 1 + ); + $attribute_template = \Redshop\Template\Helper::getAttribute($templateDesc); + + $total_product = $model->getTotal(); + $endlimit = $model->getState('list.limit'); + $start = $model->getState('list.start'); + + $tagarray = RedshopHelperText::getTextLibraryTagArray(); + $data = ""; + $count_no_user_field = 0; + $fieldArray = RedshopHelperExtrafields::getSectionFieldList(17, 0, 0); + + for ($i = 0, $countSearch = count($this->search); $i < $countSearch; $i++) { + $this->search[$i]->stockroom = RedshopHelperStockroom::getStockroomTotalAmount( + $this->search[$i]->product_id + ); + $this->search[$i]->product_related = RedshopHelperProduct::getRelatedProduct( + $this->search[$i]->product_id + ); + $this->search[$i]->count_product_related = count($this->search[$i]->product_related); + + $data_add = $templateDesc; + + // RedSHOP Product Plugin + $params = array(); + $dispatcher->trigger('onPrepareProduct', array(&$data_add, &$params, $this->search[$i])); + + $thum_image = ""; + $pname = RedshopHelperUtility::maxChars( + $this->search[$i]->product_name, + Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_MAX_CHARS'), + Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_END_SUFFIX') + ); + + if ($search_type == 'product_number') { + $product_number = preg_replace( + "/($keyword)/i", + "$1", + $this->search[$i]->product_number + ); + $pro_s_desc = $this->search[$i]->product_s_desc; + $pro_desc = $this->search[$i]->product_desc; + } else { + $product_number = $this->search[$i]->product_number; + $pro_s_desc = $this->search[$i]->product_s_desc; + $pro_desc = $this->search[$i]->product_desc; + + if (!empty($keyword) && !in_array($keyword, $tagarray)) { + $regex = "/" . preg_quote($keyword, "/") . "(?![^<]*>)/"; + $pname = preg_replace($regex, "" . $keyword . "", $pname); + $product_number = preg_replace( + $regex, + "" . $keyword . "", + $product_number + ); + $pro_s_desc = preg_replace( + $regex, + "" . $keyword . "", + $pro_s_desc + ); + $pro_desc = preg_replace($regex, "" . $keyword . "", $pro_desc); + } + } + + $pro_s_desc = RedshopHelperUtility::maxChars( + $pro_s_desc, + Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_MAX_CHARS'), + Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_END_SUFFIX') + ); + + $ItemData = RedshopHelperProduct::getMenuInformation(0, 0, '', 'product&pid=' . $this->search[$i]->product_id); + + if (!empty($ItemData)) { + $pItemid = $ItemData->id; + } else { + $pItemid = RedshopHelperRouter::getItemId($this->search[$i]->product_id, $this->search[$i]->category_id); + } + + $link = JRoute::_( + 'index.php?option=com_redshop&view=product&pid=' . $this->search[$i]->product_id . '&cid=' . $this->search[$i]->cat_in_sefurl . '&Itemid=' . $pItemid + ); + + if (strstr($data_add, '{product_name}')) { + $pname = "" . $pname . ""; + $data_add = str_replace("{product_name}", $pname, $data_add); + } + + if (strstr($data_add, '{product_name_nolink}')) { + $data_add = str_replace("{product_name_nolink}", $pname, $data_add); + } + + $readmore = "" . JText::_('COM_REDSHOP_READ_MORE') . ""; + $data_add = str_replace("{read_more}", $readmore, $data_add); + $data_add = str_replace("{read_more_link}", $link, $data_add); + + if (strstr($data_add, "{product_delivery_time}")) { + $product_delivery_time = RedshopHelperProduct::getProductMinDeliveryTime($this->search[$i]->product_id); + + if ($product_delivery_time != "") { + $data_add = str_replace("{delivery_time_lbl}", JText::_('DELIVERY_TIME'), $data_add); + $data_add = str_replace("{product_delivery_time}", $product_delivery_time, $data_add); + } else { + $data_add = str_replace("{delivery_time_lbl}", "", $data_add); + $data_add = str_replace("{product_delivery_time}", "", $data_add); + } + } + + // Product Review/Rating + // Fetching reviews + $final_avgreview_data = Redshop\Product\Rating::getRating($this->search[$i]->product_id); + + // Attribute ajax chage + $data_add = str_replace("{product_rating_summary}", $final_avgreview_data, $data_add); + $data_add = RedshopHelperProduct::getJcommentEditor($this->search[$i], $data_add); + + if ($extraFieldsForCurrentTemplate) { + $data_add = Redshop\Helper\ExtraFields::displayExtraFields( + 1, + $this->search[$i]->product_id, + $extraFieldsForCurrentTemplate, + $data_add, + true + ); + } + + $data_add = str_replace("{product_s_desc}", $pro_s_desc, $data_add); + $data_add = str_replace("{product_desc}", $pro_desc, $data_add); + $data_add = str_replace("{product_id_lbl}", JText::_('COM_REDSHOP_PRODUCT_ID_LBL'), $data_add); + $data_add = str_replace("{product_id}", $this->search[$i]->product_id, $data_add); + $data_add = str_replace("{product_number_lbl}", JText::_('COM_REDSHOP_PRODUCT_NUMBER_LBL'), $data_add); + $data_add = str_replace("{product_number}", $product_number, $data_add); + + // Product category tags + $data_add = str_replace("{returntocategory_name}", $this->search[$i]->category_name, $data_add); + + if (strstr($data_add, "{returntoparent_category_name}")) { + $parentCategoryId = RedshopHelperProduct::getParentCategory($this->search[$i]->category_id); + + if ($parentCategoryId != 0) { + $parentCategory = RedshopEntityCategory::getInstance($parentCategoryId)->getItem(); + $data_add = str_replace( + "{returntoparent_category_name}", + $parentCategory->category_name, + $data_add + ); + } else { + $data_add = str_replace("{returntoparent_category_name}", '', $data_add); + } + } + + /** + * related Product List in Lightbox + * Tag Format = {related_product_lightbox:[:width][:height]} + */ + if (strstr($data_add, '{related_product_lightbox:')) { + $related_product = RedshopHelperProduct::getRelatedProduct($this->search[$i]->product_id); + $rtlnone = explode("{related_product_lightbox:", $data_add); + $rtlntwo = explode("}", $rtlnone[1]); + $rtlnthree = explode(":", $rtlntwo[0]); + $rtln = $rtlnthree[0]; + $rtlnfwidth = (isset($rtlnthree[1])) ? $rtlnthree[1] : "900"; + $rtlnwidthtag = (isset($rtlnthree[1])) ? ":" . $rtlnthree[1] : ""; + + $rtlnfheight = (isset($rtlnthree[2])) ? $rtlnthree[2] : "600"; + $rtlnheighttag = (isset($rtlnthree[2])) ? ":" . $rtlnthree[2] : ""; + + $rtlntag = "{related_product_lightbox:$rtln$rtlnwidthtag$rtlnheighttag}"; + + if (count($related_product) > 0) { + $linktortln = JURI::root( + ) . "index.php?option=com_redshop&view=product&pid=" . $this->search[$i]->product_id . "&tmpl=component&template=" . $rtln . "&for=rtln"; + $rtlna = '' . JText::_( + 'COM_REDSHOP_RELATED_PRODUCT_LIST_IN_LIGHTBOX' + ) . ''; + } else { + $rtlna = ""; + } + + $data_add = str_replace($rtlntag, $rtlna, $data_add); + } + + $data_add = RedshopHelperTax::replaceVatInformation($data_add); + + /************************************ + * Conditional tag + * if product on discount : Yes + * {if product_on_sale} This product is on sale {product_on_sale end if} // OUTPUT : This product is on sale + * NO : // OUTPUT : Display blank + ************************************/ + + /* count product related start */ + if (isset($this->search[$i]->count_product_related) && $this->search[$i]->count_product_related) { + $data_add = str_replace( + "{countrelated}", + "
  • " . $this->search[$i]->count_product_related . ' ' . JText::_( + 'COM_REDSHOP_COUNT_RELATED' + ) . "" . "
  • ", + $data_add + ); + } else { + $data_add = str_replace("{countrelated}", '', $data_add); + } + /* count product related end */ + + /* stock room number start */ + $lang = JFactory::getLanguage(); + + if (isset($this->search[$i]->stockroom) && $this->search[$i]->stockroom == 0) { + $data_add = str_replace("{stockroom}", '', $data_add); + } else { + $data_add = str_replace( + "{stockroom}", + "
  • " . + JText::sprintf('COM_REDSHOP_STOCK_AMOUNT_LEFT', $this->search[$i]->stockroom) . + "
  • ", + $data_add + ); + } + /* stock room number end */ + + /*custom enddate discount start*/ + if (isset($this->search[$i]->discount_enddate) && $this->search[$i]->discount_enddate) { + $data_add = str_replace("{discount_end_date}", date('d/m', $this->search[$i]->discount_enddate), $data_add); + } else { + $data_add = str_replace("{discount_end_date}", '', $data_add); + } + /*custom enddate discount end*/ + + $data_add = RedshopHelperProduct::getProductOnSaleComment($this->search[$i], $data_add); + + $data_add = RedshopHelperStockroom::replaceStockroomAmountDetail($data_add, $this->search[$i]->product_id); + + if (strstr($data_add, "{product_thumb_image_3}")) { + $cimg_tag = '{product_thumb_image_3}'; + $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_3'); + $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_3'); + } elseif (strstr($data_add, "{product_thumb_image_2}")) { + $cimg_tag = '{product_thumb_image_2}'; + $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_2'); + $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_2'); + } elseif (strstr($data_add, "{product_thumb_image_1}")) { + $cimg_tag = '{product_thumb_image_1}'; + $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); + $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); + } else { + $cimg_tag = '{product_thumb_image}'; + $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); + $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); + } + + $hidden_thumb_image = ""; + $thum_image = Redshop\Product\Image\Image::getImage( + $this->search[$i]->product_id, + $link, + $cw_thumb, + $ch_thumb + ); + $data_add = str_replace($cimg_tag, $thum_image . $hidden_thumb_image, $data_add); + + // More documents + if (strstr($data_add, "{more_documents}")) { + $media_documents = RedshopHelperMedia::getAdditionMediaImage( + $this->search[$i]->product_id, + "product", + "document" + ); + $more_doc = ''; + + for ($m = 0, $countMedia = count($media_documents); $m < $countMedia; $m++) { + $alttext = RedshopHelperMedia::getAlternativeText( + "product", + $media_documents[$m]->section_id, + "", + $media_documents[$m]->media_id, + "document" + ); + + if (!$alttext) { + $alttext = $media_documents[$m]->media_name; + } + + if (JFile::exists(REDSHOP_FRONT_DOCUMENT_RELPATH . "product/" . $media_documents[$m]->media_name)) { + $downlink = JURI::root( + ) . 'index.php?tmpl=component&option=com_redshop&view=product&pid=' . $this->search[$i]->product_id . '&task=downloadDocument&fname=' . $media_documents[$m]->media_name . '&Itemid=' . $Itemid; + $more_doc .= ""; + } + } + + $data_add = str_replace( + "{more_documents}", + "" . $more_doc . "", + $data_add + ); + } + + // More documents end + + /************************************************ user fields*******************************************************/ + $hidden_userfield = ""; + $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($data_add); + $template_userfield = $returnArr[0]; + $userfieldArr = $returnArr[1]; + $count_no_user_field = 0; + + if ($template_userfield != "") { + $ufield = ""; + + for ($ui = 0, $countUserField = count($userfieldArr); $ui < $countUserField; $ui++) { + $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields( + $userfieldArr[$ui], + 12, + '', + '', + 0, + $this->search[$i]->product_id + ); + $ufield .= $productUserFields[1]; + + if ($productUserFields[1] != "") { + $count_no_user_field++; + } + + $data_add = str_replace('{' . $userfieldArr[$ui] . '_lbl}', $productUserFields[0], $data_add); + $data_add = str_replace('{' . $userfieldArr[$ui] . '}', $productUserFields[1], $data_add); + } + + $productUserFieldsForm = ""; + + if ($ufield != "") { + $data_add = str_replace("{if product_userfield}", $productUserFieldsForm, $data_add); + $data_add = str_replace("{product_userfield end if}", "", $data_add); + } else { + $data_add = str_replace("{if product_userfield}", "", $data_add); + $data_add = str_replace("{product_userfield end if}", "", $data_add); + } + } elseif (Redshop::getConfig()->get('AJAX_CART_BOX')) { + $ajax_detail_template_desc = ""; + $ajax_detail_template = \Redshop\Template\Helper::getAjaxDetailBox($this->search[$i]); + + if (null !== $ajax_detail_template) { + $ajax_detail_template_desc = $ajax_detail_template->template_desc; + } + + $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($ajax_detail_template_desc); + $template_userfield = $returnArr[0]; + $userfieldArr = $returnArr[1]; + + if ($template_userfield != "") { + $ufield = ""; + + for ($ui = 0, $countUserField = count($userfieldArr); $ui < $countUserField; $ui++) { + $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields( + $userfieldArr[$ui], + 12, + '', + '', + 0, + $this->search[$i]->product_id + ); + $ufield .= $productUserFields[1]; + + if ($productUserFields[1] != "") { + $count_no_user_field++; + } + + $template_userfield = str_replace( + '{' . $userfieldArr[$ui] . '_lbl}', + $productUserFields[0], + $template_userfield + ); + $template_userfield = str_replace( + '{' . $userfieldArr[$ui] . '}', + $productUserFields[1], + $template_userfield + ); + } + + if ($ufield != "") { + $hidden_userfield = "
    " . $template_userfield . "
    "; + } + } + } + + $data_add = $data_add . $hidden_userfield; + + /*************** end user fields ***************/ + + // ProductFinderDatepicker Extra Field Start + + $data_add = RedshopHelperProduct::getProductFinderDatepickerValue( + $data_add, + $this->search[$i]->product_id, + $fieldArray + ); + + // ProductFinderDatepicker Extra Field End + + /* + * manufacturer data + */ + $manufacturer_id = $this->search[$i]->id; + + if ($manufacturer_id != 0) { + $manufacturer_link_href = JRoute::_( + 'index.php?option=com_redshop&view=manufacturers&layout=detail&mid=' . $manufacturer_id . '&Itemid=' . $Itemid + ); + $manufacturer_name = $this->search[$i]->name; + $manufacturer_link = '' . $manufacturer_name . ''; + + if (strstr($data_add, "{manufacturer_link}")) { + $data_add = str_replace("{manufacturer_name}", "", $data_add); + } else { + $data_add = str_replace("{manufacturer_name}", $manufacturer_name, $data_add); + } + + $data_add = str_replace("{manufacturer_link}", $manufacturer_link, $data_add); + } else { + $data_add = str_replace("{manufacturer_link}", "", $data_add); + $data_add = str_replace("{manufacturer_name}", "", $data_add); + } + + if (strpos($data_add, "{category_name}") !== false) { + $category = RedshopEntityCategory::getInstance($this->search[$i]->cat_in_sefurl)->getItem(); + $title = " title='" . $category->name . "' "; + $linkCat = JRoute::_( + 'index.php?option=com_redshop' . + '&view=category&cid=' . $category->id . + '&manufacturer_id=' . $manufacturer_id . + '&layout=detail&Itemid=' . $mainItemid + ); + + $categoryName = '' . $category->name . ''; + $data_add = str_replace('{category_name}', $categoryName, $data_add); + } + + // End + + // Replace wishlistbutton + $data_add = RedshopHelperWishlist::replaceWishlistTag($this->search[$i]->product_id, $data_add); + + // Replace compare product button + $data_add = Redshop\Product\Compare::replaceCompareProductsButton($this->search[$i]->product_id, 0, $data_add); + + // Checking for child products + if ($this->search[$i]->count_child_products > 0) { + $isChilds = true; + $attributes = array(); + } else { + $isChilds = false; + + // Get attributes + $attributes_set = array(); + + if ($this->search[$i]->attribute_set_id > 0) { + $attributes_set = \Redshop\Product\Attribute::getProductAttribute( + 0, + $this->search[$i]->attribute_set_id, + 0, + 1 + ); + } + + $attributes = \Redshop\Product\Attribute::getProductAttribute($this->search[$i]->product_id); + $attributes = array_merge($attributes, $attributes_set); + } + + // Product attribute Start + $totalatt = count($attributes); + + // Check product for not for sale + $data_add = RedshopHelperProduct::getProductNotForSaleComment($this->search[$i], $data_add, $attributes); + + $data_add = Redshop\Product\Stock::replaceInStock( + $this->search[$i]->product_id, + $data_add, + $attributes, + $attribute_template + ); + + $data_add = RedshopHelperAttribute::replaceAttributeData( + $this->search[$i]->product_id, + 0, + 0, + $attributes, + $data_add, + $attribute_template, + $isChilds + ); + + // Cart Template + $data_add = Redshop\Cart\Render::replace( + $this->search[$i]->product_id, + 0, + 0, + 0, + $data_add, + $isChilds, + $userfieldArr, + $totalatt, + 0, + $count_no_user_field + ); + + $data_add = RedshopHelperProductTag::getExtraSectionTag( + $extraFieldName, + $this->search[$i]->product_id, + "1", + $data_add + ); + + $productAvailabilityDate = strstr($data_add, "{product_availability_date}"); + $stockNotifyFlag = strstr($data_add, "{stock_notify_flag}"); + $stockStatus = strstr($data_add, "{stock_status"); + + $attributeproductStockStatus = array(); + + if ($productAvailabilityDate || $stockNotifyFlag || $stockStatus) { + $attributeproductStockStatus = RedshopHelperProduct::getproductStockStatus( + $this->search[$i]->product_id, + $totalatt + ); + } + + $data_add = \Redshop\Helper\Stockroom::replaceProductStockData( + $this->search[$i]->product_id, + 0, + 0, + $data_add, + $attributeproductStockStatus + ); + + $dispatcher->trigger('onAfterDisplayProduct', array(&$data_add, array(), $this->search[$i])); + + $data .= $data_add; + } + + $app = JFactory::getApplication(); + $router = $app->getRouter(); + + $getorderby = $app->input->get('order_by', Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD')); + + $vars = array( + 'option' => 'com_redshop', + 'view' => 'search', + 'layout' => $layout, + 'keyword' => $keyword, + 'manufacture_id' => $manufacture_id, + 'order_by' => $getorderby, + 'category_id' => $cid, + 'Itemid' => $Itemid, + 'search_type' => $search_type + ); + $router->setVars($vars); + unset($vars); + + if (strstr($template_org, "{show_all_products_in_category}")) { + $template_org = str_replace("{show_all_products_in_category}", "", $template_org); + $template_org = str_replace("{pagination}", "", $template_org); + } + + $pagination = new JPagination($total_product, $start, $endlimit); + + if (strstr($template_org, "{pagination}")) { + $template_org = str_replace("{pagination}", $pagination->getPagesLinks(), $template_org); + } + + $usePerPageLimit = false; + + if (strstr($template_org, "perpagelimit:")) { + $usePerPageLimit = true; + $perpage = explode('{perpagelimit:', $template_org); + $perpage = explode('}', $perpage[1]); + $template_org = str_replace("{perpagelimit:" . intval($perpage[0]) . "}", "", $template_org); + } + + if (strstr($template_org, "{product_display_limit}")) { + if ($usePerPageLimit) { + $limitBox = ''; + } else { + $limitBox = "
    " - . $pagination->getLimitBox() . "
    "; - } - - $template_org = str_replace("{product_display_limit}", $limitBox, $template_org); - } - - $template_org = str_replace("{order_by}", $orderby_form, $template_org); - $template_org = str_replace("{order_by_lbl}", JText::_('COM_REDSHOP_SELECT_ORDER_BY'), $template_org); - $template_org = str_replace("{filter_by_lbl}", JText::_('COM_REDSHOP_SELECT_FILTER_BY'), $template_org); - $template_org = str_replace("{attribute_price_with_vat}", "", $template_org); - $template_org = str_replace("{attribute_price_without_vat}", "", $template_org); - $template_org = str_replace("{product_loop_start}", "", $template_org); - $template_org = str_replace("{product_loop_end}", "", $template_org); - $template_org = str_replace($template_tmp_desc, $data, $template_org); - - $template_org = str_replace("{with_vat}", "", $template_org); - $template_org = str_replace("{without_vat}", "", $template_org); - - $template_org = RedshopHelperTemplate::parseRedshopPlugin($template_org); - $template_org = RedshopHelperText::replaceTexts($template_org); - - eval("?>" . $template_org . "

    " . JText::_('COM_REDSHOP_MSG_SORRY_NO_RESULT_FOUND') . "

    "; + . $pagination->getLimitBox() . ""; + } + + $template_org = str_replace("{product_display_limit}", $limitBox, $template_org); + } + + $template_org = str_replace("{order_by}", $orderby_form, $template_org); + $template_org = str_replace("{order_by_lbl}", JText::_('COM_REDSHOP_SELECT_ORDER_BY'), $template_org); + $template_org = str_replace("{filter_by_lbl}", JText::_('COM_REDSHOP_SELECT_FILTER_BY'), $template_org); + $template_org = str_replace("{attribute_price_with_vat}", "", $template_org); + $template_org = str_replace("{attribute_price_without_vat}", "", $template_org); + $template_org = str_replace("{product_loop_start}", "", $template_org); + $template_org = str_replace("{product_loop_end}", "", $template_org); + $template_org = str_replace($template_tmp_desc, $data, $template_org); + + $template_org = str_replace("{with_vat}", "", $template_org); + $template_org = str_replace("{without_vat}", "", $template_org); + + $template_org = RedshopHelperTemplate::parseRedshopPlugin($template_org); + $template_org = RedshopHelperText::replaceTexts($template_org); + + eval("?>" . $template_org . "

    " . JText::_('COM_REDSHOP_MSG_SORRY_NO_RESULT_FOUND') . "

    "; } diff --git a/component/site/views/search/tmpl/featuredproduct.xml b/component/site/views/search/tmpl/featuredproduct.xml index 46d89de54ab..40bcaa9a416 100644 --- a/component/site/views/search/tmpl/featuredproduct.xml +++ b/component/site/views/search/tmpl/featuredproduct.xml @@ -7,8 +7,8 @@
    - +
    diff --git a/component/site/views/search/tmpl/newproduct.xml b/component/site/views/search/tmpl/newproduct.xml index 949bcb4ed9a..be869f4da55 100644 --- a/component/site/views/search/tmpl/newproduct.xml +++ b/component/site/views/search/tmpl/newproduct.xml @@ -9,14 +9,14 @@
    + description="COM_REDSHOP_SEARCH_RESULT_DISPALY_IN_SELECTED_CATEGORY_TEMPLATE"/> + description="Displays the selected category product"/> + label="COM_REDSHOP_Enter_Number_of_Days_to_Find_Newest_Products" + description="COM_REDSHOP_Enter_No_of_Days_For_Find_Newest_Product"/> + description="COM_REDSHOP_Enter_No_of_Amount_How_Many_products_To_Show"/>
    diff --git a/component/site/views/search/tmpl/productonsale.php b/component/site/views/search/tmpl/productonsale.php index 547a87c778b..a9beda986e4 100644 --- a/component/site/views/search/tmpl/productonsale.php +++ b/component/site/views/search/tmpl/productonsale.php @@ -9,743 +9,800 @@ defined('_JEXEC') or die; -if (count($this->search) > 0) -{ - JPluginHelper::importPlugin('redshop_product'); - - $app = JFactory::getApplication(); - $input = JFactory::getApplication()->input; - $input->set('order_by', $app->getUserState('order_by')); - - $dispatcher = RedshopHelperUtility::getDispatcher(); - - $Itemid = $app->input->getInt('Itemid'); - $search_type = $app->input->getCmd('search_type'); - $cid = $app->input->getInt('category_id'); - $manufacture_id = $app->input->getInt('manufacture_id'); - - $templateid = $app->input->getInt('templateid'); - - // Cmd removes space between to words - $keyword = $app->input->getString('keyword'); - $layout = $app->input->getCmd('layout', 'default'); - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('name')) - ->from($db->qn('#__redshop_category')) - ->where($db->qn('id') . ' = ' . $db->q((int) $input->getInt('cid', 0))); - - $cat_name = $db->setQuery($query)->loadResult(); - - $model = $this->getModel('search'); - $total = $model->getTotal(); - - JHTML::_('behavior.modal'); - $url = JURI::base(); - - if ($this->params->get('page_title') != "") - { - $pagetitle = $this->params->get('page_title'); - } - else - { - $pagetitle = JText::_('COM_REDSHOP_SEARCH'); - } - - if ($this->params->get('show_page_heading', 1)) - { - echo '

    '; - echo $pagetitle; - echo '

    '; - } - - echo '
    '; - $category_tmpl = ""; - - if ($this->templatedata != "") - { - $templateDesc = $this->templatedata; - } - else - { - $templateDesc = "
    {print}
    \r\n
    \r\n
    {category_main_description}
    \r\n

    {if subcats} {category_loop_start}

    \r\n
    \r\n
    \r\n
    {category_thumb_image}
    \r\n
    \r\n

    {category_name}

    \r\n{category_description}
    \r\n
    \r\n
    \r\n

    {category_loop_end} {subcats end if}

    \r\n
    \r\n
    \r\n
    {order_by}
    \r\n
    \r\n
    {product_loop_start}\r\n
    \r\n
    \r\n
    {product_thumb_image}
    \r\n
    \r\n

    {product_name}

    \r\n
    \r\n
    {product_price}
    \r\n
    {read_more}
    \r\n
    {product_rating_summary}
    \r\n
    {form_addtocart:add_to_cart1}
    \r\n
    \r\n
    \r\n{product_loop_end}\r\n
    \r\n
    \r\n
    {pagination}
    "; - } - - $template_org = $templateDesc; - $template_d1 = explode("{category_loop_start}", $template_org); - - if (count($template_d1) > 1) - { - $template_d2 = explode("{category_loop_end}", $template_d1[1]); - - if (count($template_d2) > 0) - { - $category_tmpl = $template_d2[0]; - } - } - - $template_org = str_replace($category_tmpl, "", $template_org); - $template_org = str_replace("{category_loop_start}", "", $template_org); - $template_org = str_replace("{category_loop_end}", "", $template_org); - $print = $app->input->getInt('print'); - $p_url = @ explode('?', $app->input->server->get('REQUEST_URI', '', 'raw')); - $print_tag = ''; - - if ($print) - { - $print_tag = "" . JText::_("; - } - else - { - $print_url = $url . "index.php?option=com_redshop&view=search&print=1&tmpl=component"; - $print_tag = "" . JText::_("; - } - - if (strstr($template_org, '{compare_product_div}')) - { - $compareProductDiv = ''; - - if (Redshop::getConfig()->get('PRODUCT_COMPARISON_TYPE') != '') - { - $compareProductDiv = RedshopLayoutHelper::render('product.compare_product'); - } - - $template_org = str_replace('{compare_product_div}', $compareProductDiv, $template_org); - } - - // Skip html if nosubcategory - if (strstr($template_org, "{if subcats}")) - { - $template_d1 = explode("{if subcats}", $template_org); - $template_d2 = explode("{subcats end if}", $template_d1[1]); - $template_org = $template_d1[0] . $template_d2[1]; - } - - // End skip html if nosubcategory - $template_org = str_replace("{print}", $print_tag, $template_org); - $template_org = str_replace("{product_price_slider}", '', $template_org); - $template_org = str_replace("{filter_by}", '', $template_org); - $template_org = str_replace("{template_selector_category_lbl}", '', $template_org); - $template_org = str_replace("{template_selector_category}", '', $template_org); - $template_org = str_replace("{category_main_name}", $cat_name, $template_org); - $template_org = str_replace("{category_main_description}", '', $template_org); - $template_org = str_replace("{category_description}", '', $template_org); - $template_org = str_replace("{category_short_desc}", '', $template_org); - $template_org = str_replace("{if subcats}", '', $template_org); - $template_org = str_replace("{subcats end if}", '', $template_org); - $template_org = str_replace("{category_main_thumb_image_3}", '', $template_org); - $template_org = str_replace("{category_main_short_desc}", '', $template_org); - $template_org = str_replace("{category_main_thumb_image_2}", '', $template_org); - $template_org = str_replace("{category_main_thumb_image_1}", '', $template_org); - $template_org = str_replace("{category_main_thumb_image}", '', $template_org); - $template_org = str_replace("{attribute_price_without_vat}", '', $template_org); - $template_org = str_replace("{redproductfinderfilter_formstart}", '', $template_org); - $template_org = str_replace("{redproductfinderfilter:rp_myfilter}", '', $template_org); - $template_org = str_replace("{redproductfinderfilter_formend}", '', $template_org); - $template_org = str_replace("{total_product}", $total, $template_org); - $template_org = str_replace("{total_product_lbl}", JText::_('COM_REDSHOP_TOTAL_PRODUCT'), $template_org); - - // Replace redproductfilder filter tag - if (strstr($template_org, "{redproductfinderfilter:")) - { - $redProductFinerHelper = JPATH_SITE . "/components/com_redproductfinder/helpers/redproductfinder_helper.php"; - if (file_exists($redProductFinerHelper)) - { - include_once $redProductFinerHelper; - $redproductfinder_helper = new redproductfinder_helper; - $hdnFields = array('texpricemin' => '0', 'texpricemax' => '0', 'manufacturer_id' => $filter_by, 'category_template' => $templateid); - $hide_filter_flag = false; - - if ($this->_id) - { - $prodctofcat = RedshopHelperProduct::getProductCategory($this->_id); - - if (empty($prodctofcat)) - $hide_filter_flag = true; - } - - $template_org = $redproductfinder_helper->replaceProductfinder_tag($template_org, $hdnFields, $hide_filter_flag); - } - } - - // Replace redproductfilder filter tag end here - $template_d1 = explode("{product_loop_start}", $template_org); - $template_d2 = explode("{product_loop_end}", $template_d1[1]); - $template_tmp_desc = $template_d2[0]; - $templateDesc = $template_d2[0]; - - // Order By - $order_by = ""; - $orderby_form = "
    "; - $orderby_form .= $this->lists['order_select']; - $orderby_form .= " +if (count($this->search) > 0) { + JPluginHelper::importPlugin('redshop_product'); + + $app = JFactory::getApplication(); + $input = JFactory::getApplication()->input; + $input->set('order_by', $app->getUserState('order_by')); + + $dispatcher = RedshopHelperUtility::getDispatcher(); + + $Itemid = $app->input->getInt('Itemid'); + $search_type = $app->input->getCmd('search_type'); + $cid = $app->input->getInt('category_id'); + $manufacture_id = $app->input->getInt('manufacture_id'); + + $templateid = $app->input->getInt('templateid'); + + // Cmd removes space between to words + $keyword = $app->input->getString('keyword'); + $layout = $app->input->getCmd('layout', 'default'); + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('name')) + ->from($db->qn('#__redshop_category')) + ->where($db->qn('id') . ' = ' . $db->q((int)$input->getInt('cid', 0))); + + $cat_name = $db->setQuery($query)->loadResult(); + + $model = $this->getModel('search'); + $total = $model->getTotal(); + + JHTML::_('behavior.modal'); + $url = JURI::base(); + + if ($this->params->get('page_title') != "") { + $pagetitle = $this->params->get('page_title'); + } else { + $pagetitle = JText::_('COM_REDSHOP_SEARCH'); + } + + if ($this->params->get('show_page_heading', 1)) { + echo '

    '; + echo $pagetitle; + echo '

    '; + } + + echo '
    '; + $category_tmpl = ""; + + if ($this->templatedata != "") { + $templateDesc = $this->templatedata; + } else { + $templateDesc = "
    {print}
    \r\n
    \r\n
    {category_main_description}
    \r\n

    {if subcats} {category_loop_start}

    \r\n
    \r\n
    \r\n
    {category_thumb_image}
    \r\n
    \r\n

    {category_name}

    \r\n{category_description}
    \r\n
    \r\n
    \r\n

    {category_loop_end} {subcats end if}

    \r\n
    \r\n
    \r\n
    {order_by}
    \r\n
    \r\n
    {product_loop_start}\r\n
    \r\n
    \r\n
    {product_thumb_image}
    \r\n
    \r\n

    {product_name}

    \r\n
    \r\n
    {product_price}
    \r\n
    {read_more}
    \r\n
    {product_rating_summary}
    \r\n
    {form_addtocart:add_to_cart1}
    \r\n
    \r\n
    \r\n{product_loop_end}\r\n
    \r\n
    \r\n
    {pagination}
    "; + } + + $template_org = $templateDesc; + $template_d1 = explode("{category_loop_start}", $template_org); + + if (count($template_d1) > 1) { + $template_d2 = explode("{category_loop_end}", $template_d1[1]); + + if (count($template_d2) > 0) { + $category_tmpl = $template_d2[0]; + } + } + + $template_org = str_replace($category_tmpl, "", $template_org); + $template_org = str_replace("{category_loop_start}", "", $template_org); + $template_org = str_replace("{category_loop_end}", "", $template_org); + $print = $app->input->getInt('print'); + $p_url = @ explode('?', $app->input->server->get('REQUEST_URI', '', 'raw')); + $print_tag = ''; + + if ($print) { + $print_tag = "" . JText::_(
+                "; + } else { + $print_url = $url . "index.php?option=com_redshop&view=search&print=1&tmpl=component"; + $print_tag = "" . JText::_(
+                "; + } + + if (strstr($template_org, '{compare_product_div}')) { + $compareProductDiv = ''; + + if (Redshop::getConfig()->get('PRODUCT_COMPARISON_TYPE') != '') { + $compareProductDiv = RedshopLayoutHelper::render('product.compare_product'); + } + + $template_org = str_replace('{compare_product_div}', $compareProductDiv, $template_org); + } + + // Skip html if nosubcategory + if (strstr($template_org, "{if subcats}")) { + $template_d1 = explode("{if subcats}", $template_org); + $template_d2 = explode("{subcats end if}", $template_d1[1]); + $template_org = $template_d1[0] . $template_d2[1]; + } + + // End skip html if nosubcategory + $template_org = str_replace("{print}", $print_tag, $template_org); + $template_org = str_replace("{product_price_slider}", '', $template_org); + $template_org = str_replace("{filter_by}", '', $template_org); + $template_org = str_replace("{template_selector_category_lbl}", '', $template_org); + $template_org = str_replace("{template_selector_category}", '', $template_org); + $template_org = str_replace("{category_main_name}", $cat_name, $template_org); + $template_org = str_replace("{category_main_description}", '', $template_org); + $template_org = str_replace("{category_description}", '', $template_org); + $template_org = str_replace("{category_short_desc}", '', $template_org); + $template_org = str_replace("{if subcats}", '', $template_org); + $template_org = str_replace("{subcats end if}", '', $template_org); + $template_org = str_replace("{category_main_thumb_image_3}", '', $template_org); + $template_org = str_replace("{category_main_short_desc}", '', $template_org); + $template_org = str_replace("{category_main_thumb_image_2}", '', $template_org); + $template_org = str_replace("{category_main_thumb_image_1}", '', $template_org); + $template_org = str_replace("{category_main_thumb_image}", '', $template_org); + $template_org = str_replace("{attribute_price_without_vat}", '', $template_org); + $template_org = str_replace("{redproductfinderfilter_formstart}", '', $template_org); + $template_org = str_replace("{redproductfinderfilter:rp_myfilter}", '', $template_org); + $template_org = str_replace("{redproductfinderfilter_formend}", '', $template_org); + $template_org = str_replace("{total_product}", $total, $template_org); + $template_org = str_replace("{total_product_lbl}", JText::_('COM_REDSHOP_TOTAL_PRODUCT'), $template_org); + + // Replace redproductfilder filter tag + if (strstr($template_org, "{redproductfinderfilter:")) { + $redProductFinerHelper = JPATH_SITE . "/components/com_redproductfinder/helpers/redproductfinder_helper.php"; + if (file_exists($redProductFinerHelper)) { + include_once $redProductFinerHelper; + $redproductfinder_helper = new redproductfinder_helper; + $hdnFields = array( + 'texpricemin' => '0', + 'texpricemax' => '0', + 'manufacturer_id' => $filter_by, + 'category_template' => $templateid + ); + $hide_filter_flag = false; + + if ($this->_id) { + $prodctofcat = RedshopHelperProduct::getProductCategory($this->_id); + + if (empty($prodctofcat)) { + $hide_filter_flag = true; + } + } + + $template_org = $redproductfinder_helper->replaceProductfinder_tag( + $template_org, + $hdnFields, + $hide_filter_flag + ); + } + } + + // Replace redproductfilder filter tag end here + $template_d1 = explode("{product_loop_start}", $template_org); + $template_d2 = explode("{product_loop_end}", $template_d1[1]); + $template_tmp_desc = $template_d2[0]; + $templateDesc = $template_d2[0]; + + // Order By + $order_by = ""; + $orderby_form = ""; + $orderby_form .= $this->lists['order_select']; + $orderby_form .= "
    "; - if (strstr($templateDesc, '{order_by}')) - { - $order_by = $orderby_form; - } - - $extraFieldName = Redshop\Helper\ExtraFields::getSectionFieldNames(1, 1, 1); - $extraFieldsForCurrentTemplate = RedshopHelperTemplate::getExtraFieldsForCurrentTemplate($extraFieldName, $templateDesc, 1); - $attribute_template = \Redshop\Template\Helper::getAttribute($templateDesc); - - $total_product = $model->getTotal(); - $endlimit = $model->getState('list.limit'); - $start = $model->getState('list.start'); - - $tagarray = RedshopHelperText::getTextLibraryTagArray(); - $data = ""; - $count_no_user_field = 0; - $fieldArray = RedshopHelperExtrafields::getSectionFieldList(17, 0, 0); - - for ($i = 0, $countSearch = count($this->search); $i < $countSearch; $i++) - { - $this->search[$i]->stockroom = RedshopHelperStockroom::getStockroomTotalAmount($this->search[$i]->product_id); - $this->search[$i]->product_related = RedshopHelperProduct::getRelatedProduct($this->search[$i]->product_id); - $this->search[$i]->count_product_related = count($this->search[$i]->product_related); - - $data_add = $templateDesc; - - // RedSHOP Product Plugin - $params = array(); - $dispatcher->trigger('onPrepareProduct', array(&$data_add, &$params, $this->search[$i])); - - $thum_image = ""; - $pname = RedshopHelperUtility::maxChars($this->search[$i]->product_name, Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_MAX_CHARS'), Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_END_SUFFIX')); - - if ($search_type == 'product_number') - { - $product_number = preg_replace("/($keyword)/i", "$1", $this->search[$i]->product_number); - $pro_s_desc = $this->search[$i]->product_s_desc; - $pro_desc = $this->search[$i]->product_desc; - } - else - { - $product_number = $this->search[$i]->product_number; - $pro_s_desc = $this->search[$i]->product_s_desc; - $pro_desc = $this->search[$i]->product_desc; - - if (!empty($keyword) && !in_array($keyword, $tagarray)) - { - $regex = "/" . preg_quote($keyword, "/") . "(?![^<]*>)/"; - $pname = preg_replace($regex, "" . $keyword . "", $pname); - $product_number = preg_replace($regex, "" . $keyword . "", $product_number); - $pro_s_desc = preg_replace($regex, "" . $keyword . "", $pro_s_desc); - $pro_desc = preg_replace($regex, "" . $keyword . "", $pro_desc); - } - } - - $pro_s_desc = RedshopHelperUtility::maxChars($pro_s_desc, Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_MAX_CHARS'), Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_END_SUFFIX')); - - $ItemData = RedshopHelperProduct::getMenuInformation(0, 0, '', 'product&pid=' . $this->search[$i]->product_id); - - if (!empty($ItemData)) - { - $pItemid = $ItemData->id; - } - else - { - $pItemid = RedshopHelperRouter::getItemId($this->search[$i]->product_id, $this->search[$i]->category_id); - } - - $link = JRoute::_('index.php?option=com_redshop&view=product&pid=' . $this->search[$i]->product_id . '&cid=' . $this->search[$i]->category_id . '&Itemid=' . $pItemid); - - if (strstr($data_add, '{product_name}')) - { - $pname = "" . $pname . ""; - $data_add = str_replace("{product_name}", $pname, $data_add); - } - - if (strstr($data_add, '{product_name_nolink}')) - { - $data_add = str_replace("{product_name_nolink}", $pname, $data_add); - } - - if (strpos($data_add, "{category_name}") !== false) - { - $category = RedshopEntityCategory::getInstance($this->search[$i]->cat_in_sefurl)->getItem(); - $catItemId = RedshopHelperRouter::getCategoryItemid($category->id); - - $title = " title='" . $category->name . "' "; - $linkCat = JRoute::_( - 'index.php?option=com_redshop' . - '&view=category&cid=' . $category->id . - '&layout=detail&Itemid=' . $catItemId - ); - - $categoryName = '' . $category->name . ''; - $data_add = str_replace('{category_name}', $categoryName, $data_add); - } - - $readmore = "" . JText::_('COM_REDSHOP_READ_MORE') . ""; - $data_add = str_replace("{read_more}", $readmore, $data_add); - $data_add = str_replace("{read_more_link}", $link, $data_add); - - if (strstr($data_add, "{product_delivery_time}")) - { - $product_delivery_time = RedshopHelperProduct::getProductMinDeliveryTime($this->search[$i]->product_id); - - if ($product_delivery_time != "") - { - $data_add = str_replace("{delivery_time_lbl}", JText::_('DELIVERY_TIME'), $data_add); - $data_add = str_replace("{product_delivery_time}", $product_delivery_time, $data_add); - } - else - { - $data_add = str_replace("{delivery_time_lbl}", "", $data_add); - $data_add = str_replace("{product_delivery_time}", "", $data_add); - } - } - - // Product Review/Rating - // Fetching reviews - $final_avgreview_data = Redshop\Product\Rating::getRating($this->search[$i]->product_id); - - // Attribute ajax chage - $data_add = str_replace("{product_rating_summary}", $final_avgreview_data, $data_add); - $data_add = RedshopHelperProduct::getJcommentEditor($this->search[$i], $data_add); - - if ($extraFieldsForCurrentTemplate) - { - $data_add = Redshop\Helper\ExtraFields::displayExtraFields(1, $this->search[$i]->product_id, $extraFieldsForCurrentTemplate, $data_add, true); - } - - $data_add = str_replace("{product_s_desc}", $pro_s_desc, $data_add); - $data_add = str_replace("{product_desc}", $pro_desc, $data_add); - $data_add = str_replace("{product_id_lbl}", JText::_('COM_REDSHOP_PRODUCT_ID_LBL'), $data_add); - $data_add = str_replace("{product_id}", $this->search[$i]->product_id, $data_add); - $data_add = str_replace("{product_number_lbl}", JText::_('COM_REDSHOP_PRODUCT_NUMBER_LBL'), $data_add); - $data_add = str_replace("{product_number}", $product_number, $data_add); - - // Product category tags - $data_add = str_replace("{returntocategory_name}", $this->search[$i]->category_name, $data_add); - - if (strstr($data_add, "{returntoparent_category_name}")) - { - $parentCategoryId = RedshopHelperProduct::getParentCategory($this->search[$i]->category_id); - - if ($parentCategoryId != 0) - { - $parentCategory = RedshopEntityCategory::getInstance($parentCategoryId)->getItem(); - $data_add = str_replace("{returntoparent_category_name}", $parentCategory->category_name, $data_add); - } - else - { - $data_add = str_replace("{returntoparent_category_name}", '', $data_add); - } - } - - /** - * related Product List in Lightbox - * Tag Format = {related_product_lightbox:[:width][:height]} - */ - if (strstr($data_add, '{related_product_lightbox:')) - { - $related_product = RedshopHelperProduct::getRelatedProduct($this->search[$i]->product_id); - $rtlnone = explode("{related_product_lightbox:", $data_add); - $rtlntwo = explode("}", $rtlnone[1]); - $rtlnthree = explode(":", $rtlntwo[0]); - $rtln = $rtlnthree[0]; - $rtlnfwidth = (isset($rtlnthree[1])) ? $rtlnthree[1] : "900"; - $rtlnwidthtag = (isset($rtlnthree[1])) ? ":" . $rtlnthree[1] : ""; - - $rtlnfheight = (isset($rtlnthree[2])) ? $rtlnthree[2] : "600"; - $rtlnheighttag = (isset($rtlnthree[2])) ? ":" . $rtlnthree[2] : ""; - - $rtlntag = "{related_product_lightbox:$rtln$rtlnwidthtag$rtlnheighttag}"; - - if (count($related_product) > 0) - { - $linktortln = JURI::root() . "index.php?option=com_redshop&view=product&pid=" . $this->search[$i]->product_id . "&tmpl=component&template=" . $rtln . "&for=rtln"; - $rtlna = '' . JText::_('COM_REDSHOP_RELATED_PRODUCT_LIST_IN_LIGHTBOX') . ''; - } - else - { - $rtlna = ""; - } - - $data_add = str_replace($rtlntag, $rtlna, $data_add); - } - - $data_add = RedshopHelperTax::replaceVatInformation($data_add); - - /************************************ - * Conditional tag - * if product on discount : Yes - * {if product_on_sale} This product is on sale {product_on_sale end if} // OUTPUT : This product is on sale - * NO : // OUTPUT : Display blank - ************************************/ - - /* count product related start */ - if(isset($this->search[$i]->count_product_related) && $this->search[$i]->count_product_related) - { - $data_add = str_replace("{countrelated}","
  • " . $this->search[$i]->count_product_related . " " . JText::_('COM_REDSHOP_COUNT_RELATED') . "" . "
  • ", $data_add); - } - else - { - $data_add = str_replace("{countrelated}",'', $data_add); - } - /* count product related end */ - - /* stock room number start */ - $lang = JFactory::getLanguage(); - - if(isset($this->search[$i]->stockroom) && $this->search[$i]->stockroom == 0) - { - $data_add = str_replace("{stockroom}",'', $data_add); - } - else - { - $data_add = str_replace("{stockroom}","
  • " . - JText::sprintf('COM_REDSHOP_STOCK_AMOUNT_LEFT', $this->search[$i]->stockroom) . - "
  • " , $data_add); - } - /* stock room number end */ - - /*custom enddate discount start*/ - if(isset($this->search[$i]->discount_enddate) && $this->search[$i]->discount_enddate) - { - $data_add = str_replace("{discount_end_date}", date('d/m',$this->search[$i]->discount_enddate), $data_add); - } - else - { - $data_add = str_replace("{discount_end_date}", '', $data_add); - } - /*custom enddate discount end*/ - - $data_add = RedshopHelperProduct::getProductOnSaleComment($this->search[$i], $data_add); - - $data_add = RedshopHelperStockroom::replaceStockroomAmountDetail($data_add, $this->search[$i]->product_id); - - if (strstr($data_add, "{product_thumb_image_3}")) - { - $cimg_tag = '{product_thumb_image_3}'; - $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_3'); - $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_3'); - } - elseif (strstr($data_add, "{product_thumb_image_2}")) - { - $cimg_tag = '{product_thumb_image_2}'; - $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_2'); - $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_2'); - } - elseif (strstr($data_add, "{product_thumb_image_1}")) - { - $cimg_tag = '{product_thumb_image_1}'; - $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); - $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); - } - else - { - $cimg_tag = '{product_thumb_image}'; - $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); - $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); - } - - $hidden_thumb_image = ""; - $thum_image = Redshop\Product\Image\Image::getImage($this->search[$i]->product_id, $link, $cw_thumb, $ch_thumb); - $data_add = str_replace($cimg_tag, $thum_image . $hidden_thumb_image, $data_add); - - // More documents - if (strstr($data_add, "{more_documents}")) - { - $media_documents = RedshopHelperMedia::getAdditionMediaImage($this->search[$i]->product_id, "product", "document"); - $more_doc = ''; - - for ($m = 0, $countMedia = count($media_documents); $m < $countMedia; $m++) - { - $alttext = RedshopHelperMedia::getAlternativeText( - "product", $media_documents[$m]->section_id, "", $media_documents[$m]->media_id, "document" - ); - - if (!$alttext) - { - $alttext = $media_documents[$m]->media_name; - } - - if (JFile::exists(REDSHOP_FRONT_DOCUMENT_RELPATH . "product/" . $media_documents[$m]->media_name)) - { - $downlink = JURI::root() . 'index.php?tmpl=component&option=com_redshop&view=product&pid=' . $this->search[$i]->product_id . '&task=downloadDocument&fname=' . $media_documents[$m]->media_name . '&Itemid=' . $Itemid; - $more_doc .= ""; - } - } - - $data_add = str_replace("{more_documents}", "" . $more_doc . "", $data_add); - } - - // More documents end - - /************************************************ user fields*******************************************************/ - $hidden_userfield = ""; - $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($data_add); - $template_userfield = $returnArr[0]; - $userfieldArr = $returnArr[1]; - $count_no_user_field = 0; - - if ($template_userfield != "") - { - $ufield = ""; - - for ($ui = 0, $countUserField = count($userfieldArr); $ui < $countUserField; $ui++) - { - $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields($userfieldArr[$ui], 12, '', '', 0, $this->search[$i]->product_id); - $ufield .= $productUserFields[1]; - - if ($productUserFields[1] != "") - { - $count_no_user_field++; - } - - $data_add = str_replace('{' . $userfieldArr[$ui] . '_lbl}', $productUserFields[0], $data_add); - $data_add = str_replace('{' . $userfieldArr[$ui] . '}', $productUserFields[1], $data_add); - } - - $productUserFieldsForm = "
    "; - - if ($ufield != "") - { - $data_add = str_replace("{if product_userfield}", $productUserFieldsForm, $data_add); - $data_add = str_replace("{product_userfield end if}", "
    ", $data_add); - } - else - { - $data_add = str_replace("{if product_userfield}", "", $data_add); - $data_add = str_replace("{product_userfield end if}", "", $data_add); - } - } - elseif (Redshop::getConfig()->get('AJAX_CART_BOX')) - { - $ajax_detail_template_desc = ""; - $ajax_detail_template = \Redshop\Template\Helper::getAjaxDetailBox($this->search[$i]); - - if (null !== $ajax_detail_template) - { - $ajax_detail_template_desc = $ajax_detail_template->template_desc; - } - - $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($ajax_detail_template_desc); - $template_userfield = $returnArr[0]; - $userfieldArr = $returnArr[1]; - - if ($template_userfield != "") - { - $ufield = ""; - - for ($ui = 0, $countUserField = count($userfieldArr); $ui < $countUserField; $ui++) - { - $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields($userfieldArr[$ui], 12, '', '', 0, $this->search[$i]->product_id); - $ufield .= $productUserFields[1]; - - if ($productUserFields[1] != "") - { - $count_no_user_field++; - } - - $template_userfield = str_replace('{' . $userfieldArr[$ui] . '_lbl}', $productUserFields[0], $template_userfield); - $template_userfield = str_replace('{' . $userfieldArr[$ui] . '}', $productUserFields[1], $template_userfield); - } - - if ($ufield != "") - { - $hidden_userfield = "
    " . $template_userfield . "
    "; - } - } - } - - $data_add = $data_add . $hidden_userfield; - - /*************** end user fields ***************/ - - // ProductFinderDatepicker Extra Field Start - - $data_add = RedshopHelperProduct::getProductFinderDatepickerValue($data_add, $this->search[$i]->product_id, $fieldArray); - - // ProductFinderDatepicker Extra Field End - - /* - * manufacturer data - */ - $manufacturer_id = $this->search[$i]->id; - - if ($manufacturer_id != 0) - { - $manufacturer_link_href = JRoute::_('index.php?option=com_redshop&view=manufacturers&layout=detail&mid=' . $manufacturer_id . '&Itemid=' . $Itemid); - $manufacturer_name = $this->search[$i]->name; - $manufacturer_link = '' . $manufacturer_name . ''; - - if (strstr($data_add, "{manufacturer_link}")) - { - $data_add = str_replace("{manufacturer_name}", "", $data_add); - } - else - { - $data_add = str_replace("{manufacturer_name}", $manufacturer_name, $data_add); - } - - $data_add = str_replace("{manufacturer_link}", $manufacturer_link, $data_add); - } - else - { - $data_add = str_replace("{manufacturer_link}", "", $data_add); - $data_add = str_replace("{manufacturer_name}", "", $data_add); - } - - // End - - // Replace wishlistbutton - $data_add = RedshopHelperWishlist::replaceWishlistTag($this->search[$i]->product_id, $data_add); - - // Replace compare product button - $data_add = Redshop\Product\Compare::replaceCompareProductsButton($this->search[$i]->product_id, 0, $data_add); - - // Checking for child products - if ($this->search[$i]->count_child_products > 0) - { - $isChilds = true; - $attributes = array(); - } - else - { - $isChilds = false; - - // Get attributes - $attributes_set = array(); - - if ($this->search[$i]->attribute_set_id > 0) - { - $attributes_set = \Redshop\Product\Attribute::getProductAttribute(0, $this->search[$i]->attribute_set_id, 0, 1); - } - - $attributes = \Redshop\Product\Attribute::getProductAttribute($this->search[$i]->product_id); - $attributes = array_merge($attributes, $attributes_set); - } - - // Product attribute Start - $totalatt = count($attributes); - - // Check product for not for sale - $data_add = RedshopHelperProduct::getProductNotForSaleComment($this->search[$i], $data_add, $attributes); - - $data_add = Redshop\Product\Stock::replaceInStock($this->search[$i]->product_id, $data_add, $attributes, $attribute_template); - - $data_add = RedshopHelperAttribute::replaceAttributeData($this->search[$i]->product_id, 0, 0, $attributes, $data_add, $attribute_template, $isChilds); - - // Cart Template - $data_add = Redshop\Cart\Render::replace($this->search[$i]->product_id, 0, 0, 0, $data_add, $isChilds, $userfieldArr, $totalatt, 0, $count_no_user_field); - - $data_add = RedshopHelperProductTag::getExtraSectionTag($extraFieldName, $this->search[$i]->product_id, "1", $data_add); - - $productAvailabilityDate = strstr($data_add, "{product_availability_date}"); - $stockNotifyFlag = strstr($data_add, "{stock_notify_flag}"); - $stockStatus = strstr($data_add, "{stock_status"); - - $attributeproductStockStatus = array(); - - if ($productAvailabilityDate || $stockNotifyFlag || $stockStatus) - { - $attributeproductStockStatus = RedshopHelperProduct::getproductStockStatus($this->search[$i]->product_id, $totalatt); - } - - $data_add = \Redshop\Helper\Stockroom::replaceProductStockData( - $this->search[$i]->product_id, - 0, - 0, - $data_add, - $attributeproductStockStatus - ); - - $dispatcher->trigger('onAfterDisplayProduct', array(&$data_add, array(), $this->search[$i])); - - $data .= $data_add; - } - - $app = JFactory::getApplication(); - $router = $app->getRouter(); - - $getorderby = $app->input->get('order_by', Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD')); - - $vars = array( - 'option' => 'com_redshop', - 'view' => 'search', - 'layout' => $layout, - 'keyword' => $keyword, - 'manufacture_id' => $manufacture_id, - 'order_by' => $getorderby, - 'category_id' => $cid, - 'Itemid' => $Itemid, - 'search_type' => $search_type - ); - $router->setVars($vars); - unset($vars); - - if (strstr($template_org, "{show_all_products_in_category}")) - { - $template_org = str_replace("{show_all_products_in_category}", "", $template_org); - $template_org = str_replace("{pagination}", "", $template_org); - } - - $pagination = new JPagination($total_product, $start, $endlimit); - - if (strstr($template_org, "{pagination}")) - { - $template_org = str_replace("{pagination}", $pagination->getPagesLinks(), $template_org); - } - - $usePerPageLimit = false; - - if (strstr($template_org, "perpagelimit:")) - { - $usePerPageLimit = true; - $perpage = explode('{perpagelimit:', $template_org); - $perpage = explode('}', $perpage[1]); - $template_org = str_replace("{perpagelimit:" . intval($perpage[0]) . "}", "", $template_org); - } - - if (strstr($template_org, "{product_display_limit}")) - { - if ($usePerPageLimit) - { - $limitBox = ''; - } - else - { - $limitBox = "
    + if (strstr($templateDesc, '{order_by}')) { + $order_by = $orderby_form; + } + + $extraFieldName = Redshop\Helper\ExtraFields::getSectionFieldNames(1, 1, 1); + $extraFieldsForCurrentTemplate = RedshopHelperTemplate::getExtraFieldsForCurrentTemplate( + $extraFieldName, + $templateDesc, + 1 + ); + $attribute_template = \Redshop\Template\Helper::getAttribute($templateDesc); + + $total_product = $model->getTotal(); + $endlimit = $model->getState('list.limit'); + $start = $model->getState('list.start'); + + $tagarray = RedshopHelperText::getTextLibraryTagArray(); + $data = ""; + $count_no_user_field = 0; + $fieldArray = RedshopHelperExtrafields::getSectionFieldList(17, 0, 0); + + for ($i = 0, $countSearch = count($this->search); $i < $countSearch; $i++) { + $this->search[$i]->stockroom = RedshopHelperStockroom::getStockroomTotalAmount( + $this->search[$i]->product_id + ); + $this->search[$i]->product_related = RedshopHelperProduct::getRelatedProduct( + $this->search[$i]->product_id + ); + $this->search[$i]->count_product_related = count($this->search[$i]->product_related); + + $data_add = $templateDesc; + + // RedSHOP Product Plugin + $params = array(); + $dispatcher->trigger('onPrepareProduct', array(&$data_add, &$params, $this->search[$i])); + + $thum_image = ""; + $pname = RedshopHelperUtility::maxChars( + $this->search[$i]->product_name, + Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_MAX_CHARS'), + Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_END_SUFFIX') + ); + + if ($search_type == 'product_number') { + $product_number = preg_replace( + "/($keyword)/i", + "$1", + $this->search[$i]->product_number + ); + $pro_s_desc = $this->search[$i]->product_s_desc; + $pro_desc = $this->search[$i]->product_desc; + } else { + $product_number = $this->search[$i]->product_number; + $pro_s_desc = $this->search[$i]->product_s_desc; + $pro_desc = $this->search[$i]->product_desc; + + if (!empty($keyword) && !in_array($keyword, $tagarray)) { + $regex = "/" . preg_quote($keyword, "/") . "(?![^<]*>)/"; + $pname = preg_replace($regex, "" . $keyword . "", $pname); + $product_number = preg_replace( + $regex, + "" . $keyword . "", + $product_number + ); + $pro_s_desc = preg_replace( + $regex, + "" . $keyword . "", + $pro_s_desc + ); + $pro_desc = preg_replace($regex, "" . $keyword . "", $pro_desc); + } + } + + $pro_s_desc = RedshopHelperUtility::maxChars( + $pro_s_desc, + Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_MAX_CHARS'), + Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_END_SUFFIX') + ); + + $ItemData = RedshopHelperProduct::getMenuInformation(0, 0, '', 'product&pid=' . $this->search[$i]->product_id); + + if (!empty($ItemData)) { + $pItemid = $ItemData->id; + } else { + $pItemid = RedshopHelperRouter::getItemId($this->search[$i]->product_id, $this->search[$i]->category_id); + } + + $link = JRoute::_( + 'index.php?option=com_redshop&view=product&pid=' . $this->search[$i]->product_id . '&cid=' . $this->search[$i]->category_id . '&Itemid=' . $pItemid + ); + + if (strstr($data_add, '{product_name}')) { + $pname = "" . $pname . ""; + $data_add = str_replace("{product_name}", $pname, $data_add); + } + + if (strstr($data_add, '{product_name_nolink}')) { + $data_add = str_replace("{product_name_nolink}", $pname, $data_add); + } + + if (strpos($data_add, "{category_name}") !== false) { + $category = RedshopEntityCategory::getInstance($this->search[$i]->cat_in_sefurl)->getItem(); + $catItemId = RedshopHelperRouter::getCategoryItemid($category->id); + + $title = " title='" . $category->name . "' "; + $linkCat = JRoute::_( + 'index.php?option=com_redshop' . + '&view=category&cid=' . $category->id . + '&layout=detail&Itemid=' . $catItemId + ); + + $categoryName = '' . $category->name . ''; + $data_add = str_replace('{category_name}', $categoryName, $data_add); + } + + $readmore = "" . JText::_('COM_REDSHOP_READ_MORE') . ""; + $data_add = str_replace("{read_more}", $readmore, $data_add); + $data_add = str_replace("{read_more_link}", $link, $data_add); + + if (strstr($data_add, "{product_delivery_time}")) { + $product_delivery_time = RedshopHelperProduct::getProductMinDeliveryTime($this->search[$i]->product_id); + + if ($product_delivery_time != "") { + $data_add = str_replace("{delivery_time_lbl}", JText::_('DELIVERY_TIME'), $data_add); + $data_add = str_replace("{product_delivery_time}", $product_delivery_time, $data_add); + } else { + $data_add = str_replace("{delivery_time_lbl}", "", $data_add); + $data_add = str_replace("{product_delivery_time}", "", $data_add); + } + } + + // Product Review/Rating + // Fetching reviews + $final_avgreview_data = Redshop\Product\Rating::getRating($this->search[$i]->product_id); + + // Attribute ajax chage + $data_add = str_replace("{product_rating_summary}", $final_avgreview_data, $data_add); + $data_add = RedshopHelperProduct::getJcommentEditor($this->search[$i], $data_add); + + if ($extraFieldsForCurrentTemplate) { + $data_add = Redshop\Helper\ExtraFields::displayExtraFields( + 1, + $this->search[$i]->product_id, + $extraFieldsForCurrentTemplate, + $data_add, + true + ); + } + + $data_add = str_replace("{product_s_desc}", $pro_s_desc, $data_add); + $data_add = str_replace("{product_desc}", $pro_desc, $data_add); + $data_add = str_replace("{product_id_lbl}", JText::_('COM_REDSHOP_PRODUCT_ID_LBL'), $data_add); + $data_add = str_replace("{product_id}", $this->search[$i]->product_id, $data_add); + $data_add = str_replace("{product_number_lbl}", JText::_('COM_REDSHOP_PRODUCT_NUMBER_LBL'), $data_add); + $data_add = str_replace("{product_number}", $product_number, $data_add); + + // Product category tags + $data_add = str_replace("{returntocategory_name}", $this->search[$i]->category_name, $data_add); + + if (strstr($data_add, "{returntoparent_category_name}")) { + $parentCategoryId = RedshopHelperProduct::getParentCategory($this->search[$i]->category_id); + + if ($parentCategoryId != 0) { + $parentCategory = RedshopEntityCategory::getInstance($parentCategoryId)->getItem(); + $data_add = str_replace( + "{returntoparent_category_name}", + $parentCategory->category_name, + $data_add + ); + } else { + $data_add = str_replace("{returntoparent_category_name}", '', $data_add); + } + } + + /** + * related Product List in Lightbox + * Tag Format = {related_product_lightbox:[:width][:height]} + */ + if (strstr($data_add, '{related_product_lightbox:')) { + $related_product = RedshopHelperProduct::getRelatedProduct($this->search[$i]->product_id); + $rtlnone = explode("{related_product_lightbox:", $data_add); + $rtlntwo = explode("}", $rtlnone[1]); + $rtlnthree = explode(":", $rtlntwo[0]); + $rtln = $rtlnthree[0]; + $rtlnfwidth = (isset($rtlnthree[1])) ? $rtlnthree[1] : "900"; + $rtlnwidthtag = (isset($rtlnthree[1])) ? ":" . $rtlnthree[1] : ""; + + $rtlnfheight = (isset($rtlnthree[2])) ? $rtlnthree[2] : "600"; + $rtlnheighttag = (isset($rtlnthree[2])) ? ":" . $rtlnthree[2] : ""; + + $rtlntag = "{related_product_lightbox:$rtln$rtlnwidthtag$rtlnheighttag}"; + + if (count($related_product) > 0) { + $linktortln = JURI::root( + ) . "index.php?option=com_redshop&view=product&pid=" . $this->search[$i]->product_id . "&tmpl=component&template=" . $rtln . "&for=rtln"; + $rtlna = '' . JText::_( + 'COM_REDSHOP_RELATED_PRODUCT_LIST_IN_LIGHTBOX' + ) . ''; + } else { + $rtlna = ""; + } + + $data_add = str_replace($rtlntag, $rtlna, $data_add); + } + + $data_add = RedshopHelperTax::replaceVatInformation($data_add); + + /************************************ + * Conditional tag + * if product on discount : Yes + * {if product_on_sale} This product is on sale {product_on_sale end if} // OUTPUT : This product is on sale + * NO : // OUTPUT : Display blank + ************************************/ + + /* count product related start */ + if (isset($this->search[$i]->count_product_related) && $this->search[$i]->count_product_related) { + $data_add = str_replace( + "{countrelated}", + "
  • " . $this->search[$i]->count_product_related . " " . JText::_( + 'COM_REDSHOP_COUNT_RELATED' + ) . "" . "
  • ", + $data_add + ); + } else { + $data_add = str_replace("{countrelated}", '', $data_add); + } + /* count product related end */ + + /* stock room number start */ + $lang = JFactory::getLanguage(); + + if (isset($this->search[$i]->stockroom) && $this->search[$i]->stockroom == 0) { + $data_add = str_replace("{stockroom}", '', $data_add); + } else { + $data_add = str_replace( + "{stockroom}", + "
  • " . + JText::sprintf('COM_REDSHOP_STOCK_AMOUNT_LEFT', $this->search[$i]->stockroom) . + "
  • ", + $data_add + ); + } + /* stock room number end */ + + /*custom enddate discount start*/ + if (isset($this->search[$i]->discount_enddate) && $this->search[$i]->discount_enddate) { + $data_add = str_replace("{discount_end_date}", date('d/m', $this->search[$i]->discount_enddate), $data_add); + } else { + $data_add = str_replace("{discount_end_date}", '', $data_add); + } + /*custom enddate discount end*/ + + $data_add = RedshopHelperProduct::getProductOnSaleComment($this->search[$i], $data_add); + + $data_add = RedshopHelperStockroom::replaceStockroomAmountDetail($data_add, $this->search[$i]->product_id); + + if (strstr($data_add, "{product_thumb_image_3}")) { + $cimg_tag = '{product_thumb_image_3}'; + $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_3'); + $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_3'); + } elseif (strstr($data_add, "{product_thumb_image_2}")) { + $cimg_tag = '{product_thumb_image_2}'; + $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_2'); + $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_2'); + } elseif (strstr($data_add, "{product_thumb_image_1}")) { + $cimg_tag = '{product_thumb_image_1}'; + $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); + $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); + } else { + $cimg_tag = '{product_thumb_image}'; + $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); + $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); + } + + $hidden_thumb_image = ""; + $thum_image = Redshop\Product\Image\Image::getImage( + $this->search[$i]->product_id, + $link, + $cw_thumb, + $ch_thumb + ); + $data_add = str_replace($cimg_tag, $thum_image . $hidden_thumb_image, $data_add); + + // More documents + if (strstr($data_add, "{more_documents}")) { + $media_documents = RedshopHelperMedia::getAdditionMediaImage( + $this->search[$i]->product_id, + "product", + "document" + ); + $more_doc = ''; + + for ($m = 0, $countMedia = count($media_documents); $m < $countMedia; $m++) { + $alttext = RedshopHelperMedia::getAlternativeText( + "product", + $media_documents[$m]->section_id, + "", + $media_documents[$m]->media_id, + "document" + ); + + if (!$alttext) { + $alttext = $media_documents[$m]->media_name; + } + + if (JFile::exists(REDSHOP_FRONT_DOCUMENT_RELPATH . "product/" . $media_documents[$m]->media_name)) { + $downlink = JURI::root( + ) . 'index.php?tmpl=component&option=com_redshop&view=product&pid=' . $this->search[$i]->product_id . '&task=downloadDocument&fname=' . $media_documents[$m]->media_name . '&Itemid=' . $Itemid; + $more_doc .= ""; + } + } + + $data_add = str_replace( + "{more_documents}", + "" . $more_doc . "", + $data_add + ); + } + + // More documents end + + /************************************************ user fields*******************************************************/ + $hidden_userfield = ""; + $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($data_add); + $template_userfield = $returnArr[0]; + $userfieldArr = $returnArr[1]; + $count_no_user_field = 0; + + if ($template_userfield != "") { + $ufield = ""; + + for ($ui = 0, $countUserField = count($userfieldArr); $ui < $countUserField; $ui++) { + $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields( + $userfieldArr[$ui], + 12, + '', + '', + 0, + $this->search[$i]->product_id + ); + $ufield .= $productUserFields[1]; + + if ($productUserFields[1] != "") { + $count_no_user_field++; + } + + $data_add = str_replace('{' . $userfieldArr[$ui] . '_lbl}', $productUserFields[0], $data_add); + $data_add = str_replace('{' . $userfieldArr[$ui] . '}', $productUserFields[1], $data_add); + } + + $productUserFieldsForm = ""; + + if ($ufield != "") { + $data_add = str_replace("{if product_userfield}", $productUserFieldsForm, $data_add); + $data_add = str_replace("{product_userfield end if}", "", $data_add); + } else { + $data_add = str_replace("{if product_userfield}", "", $data_add); + $data_add = str_replace("{product_userfield end if}", "", $data_add); + } + } elseif (Redshop::getConfig()->get('AJAX_CART_BOX')) { + $ajax_detail_template_desc = ""; + $ajax_detail_template = \Redshop\Template\Helper::getAjaxDetailBox($this->search[$i]); + + if (null !== $ajax_detail_template) { + $ajax_detail_template_desc = $ajax_detail_template->template_desc; + } + + $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($ajax_detail_template_desc); + $template_userfield = $returnArr[0]; + $userfieldArr = $returnArr[1]; + + if ($template_userfield != "") { + $ufield = ""; + + for ($ui = 0, $countUserField = count($userfieldArr); $ui < $countUserField; $ui++) { + $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields( + $userfieldArr[$ui], + 12, + '', + '', + 0, + $this->search[$i]->product_id + ); + $ufield .= $productUserFields[1]; + + if ($productUserFields[1] != "") { + $count_no_user_field++; + } + + $template_userfield = str_replace( + '{' . $userfieldArr[$ui] . '_lbl}', + $productUserFields[0], + $template_userfield + ); + $template_userfield = str_replace( + '{' . $userfieldArr[$ui] . '}', + $productUserFields[1], + $template_userfield + ); + } + + if ($ufield != "") { + $hidden_userfield = "
    " . $template_userfield . "
    "; + } + } + } + + $data_add = $data_add . $hidden_userfield; + + /*************** end user fields ***************/ + + // ProductFinderDatepicker Extra Field Start + + $data_add = RedshopHelperProduct::getProductFinderDatepickerValue( + $data_add, + $this->search[$i]->product_id, + $fieldArray + ); + + // ProductFinderDatepicker Extra Field End + + /* + * manufacturer data + */ + $manufacturer_id = $this->search[$i]->id; + + if ($manufacturer_id != 0) { + $manufacturer_link_href = JRoute::_( + 'index.php?option=com_redshop&view=manufacturers&layout=detail&mid=' . $manufacturer_id . '&Itemid=' . $Itemid + ); + $manufacturer_name = $this->search[$i]->name; + $manufacturer_link = '' . $manufacturer_name . ''; + + if (strstr($data_add, "{manufacturer_link}")) { + $data_add = str_replace("{manufacturer_name}", "", $data_add); + } else { + $data_add = str_replace("{manufacturer_name}", $manufacturer_name, $data_add); + } + + $data_add = str_replace("{manufacturer_link}", $manufacturer_link, $data_add); + } else { + $data_add = str_replace("{manufacturer_link}", "", $data_add); + $data_add = str_replace("{manufacturer_name}", "", $data_add); + } + + // End + + // Replace wishlistbutton + $data_add = RedshopHelperWishlist::replaceWishlistTag($this->search[$i]->product_id, $data_add); + + // Replace compare product button + $data_add = Redshop\Product\Compare::replaceCompareProductsButton($this->search[$i]->product_id, 0, $data_add); + + // Checking for child products + if ($this->search[$i]->count_child_products > 0) { + $isChilds = true; + $attributes = array(); + } else { + $isChilds = false; + + // Get attributes + $attributes_set = array(); + + if ($this->search[$i]->attribute_set_id > 0) { + $attributes_set = \Redshop\Product\Attribute::getProductAttribute( + 0, + $this->search[$i]->attribute_set_id, + 0, + 1 + ); + } + + $attributes = \Redshop\Product\Attribute::getProductAttribute($this->search[$i]->product_id); + $attributes = array_merge($attributes, $attributes_set); + } + + // Product attribute Start + $totalatt = count($attributes); + + // Check product for not for sale + $data_add = RedshopHelperProduct::getProductNotForSaleComment($this->search[$i], $data_add, $attributes); + + $data_add = Redshop\Product\Stock::replaceInStock( + $this->search[$i]->product_id, + $data_add, + $attributes, + $attribute_template + ); + + $data_add = RedshopHelperAttribute::replaceAttributeData( + $this->search[$i]->product_id, + 0, + 0, + $attributes, + $data_add, + $attribute_template, + $isChilds + ); + + // Cart Template + $data_add = Redshop\Cart\Render::replace( + $this->search[$i]->product_id, + 0, + 0, + 0, + $data_add, + $isChilds, + $userfieldArr, + $totalatt, + 0, + $count_no_user_field + ); + + $data_add = RedshopHelperProductTag::getExtraSectionTag( + $extraFieldName, + $this->search[$i]->product_id, + "1", + $data_add + ); + + $productAvailabilityDate = strstr($data_add, "{product_availability_date}"); + $stockNotifyFlag = strstr($data_add, "{stock_notify_flag}"); + $stockStatus = strstr($data_add, "{stock_status"); + + $attributeproductStockStatus = array(); + + if ($productAvailabilityDate || $stockNotifyFlag || $stockStatus) { + $attributeproductStockStatus = RedshopHelperProduct::getproductStockStatus( + $this->search[$i]->product_id, + $totalatt + ); + } + + $data_add = \Redshop\Helper\Stockroom::replaceProductStockData( + $this->search[$i]->product_id, + 0, + 0, + $data_add, + $attributeproductStockStatus + ); + + $dispatcher->trigger('onAfterDisplayProduct', array(&$data_add, array(), $this->search[$i])); + + $data .= $data_add; + } + + $app = JFactory::getApplication(); + $router = $app->getRouter(); + + $getorderby = $app->input->get('order_by', Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD')); + + $vars = array( + 'option' => 'com_redshop', + 'view' => 'search', + 'layout' => $layout, + 'keyword' => $keyword, + 'manufacture_id' => $manufacture_id, + 'order_by' => $getorderby, + 'category_id' => $cid, + 'Itemid' => $Itemid, + 'search_type' => $search_type + ); + $router->setVars($vars); + unset($vars); + + if (strstr($template_org, "{show_all_products_in_category}")) { + $template_org = str_replace("{show_all_products_in_category}", "", $template_org); + $template_org = str_replace("{pagination}", "", $template_org); + } + + $pagination = new JPagination($total_product, $start, $endlimit); + + if (strstr($template_org, "{pagination}")) { + $template_org = str_replace("{pagination}", $pagination->getPagesLinks(), $template_org); + } + + $usePerPageLimit = false; + + if (strstr($template_org, "perpagelimit:")) { + $usePerPageLimit = true; + $perpage = explode('{perpagelimit:', $template_org); + $perpage = explode('}', $perpage[1]); + $template_org = str_replace("{perpagelimit:" . intval($perpage[0]) . "}", "", $template_org); + } + + if (strstr($template_org, "{product_display_limit}")) { + if ($usePerPageLimit) { + $limitBox = ''; + } else { + $limitBox = "
    " - . $pagination->getLimitBox() . "
    "; - } - - $template_org = str_replace("{product_display_limit}", $limitBox, $template_org); - } - - $template_org = str_replace("{order_by}", $orderby_form, $template_org); - $template_org = str_replace("{order_by_lbl}", JText::_('COM_REDSHOP_SELECT_ORDER_BY'), $template_org); - $template_org = str_replace("{filter_by_lbl}", JText::_('COM_REDSHOP_SELECT_FILTER_BY'), $template_org); - $template_org = str_replace("{attribute_price_with_vat}", "", $template_org); - $template_org = str_replace("{attribute_price_without_vat}", "", $template_org); - $template_org = str_replace("{product_loop_start}", "", $template_org); - $template_org = str_replace("{product_loop_end}", "", $template_org); - $template_org = str_replace($template_tmp_desc, $data, $template_org); - - $template_org = str_replace("{with_vat}", "", $template_org); - $template_org = str_replace("{without_vat}", "", $template_org); - - $template_org = RedshopHelperTemplate::parseRedshopPlugin($template_org); - $template_org = RedshopHelperText::replaceTexts($template_org); - - eval("?>" . $template_org . "

    " . JText::_('COM_REDSHOP_MSG_SORRY_NO_RESULT_FOUND') . "

    "; + . $pagination->getLimitBox() . ""; + } + + $template_org = str_replace("{product_display_limit}", $limitBox, $template_org); + } + + $template_org = str_replace("{order_by}", $orderby_form, $template_org); + $template_org = str_replace("{order_by_lbl}", JText::_('COM_REDSHOP_SELECT_ORDER_BY'), $template_org); + $template_org = str_replace("{filter_by_lbl}", JText::_('COM_REDSHOP_SELECT_FILTER_BY'), $template_org); + $template_org = str_replace("{attribute_price_with_vat}", "", $template_org); + $template_org = str_replace("{attribute_price_without_vat}", "", $template_org); + $template_org = str_replace("{product_loop_start}", "", $template_org); + $template_org = str_replace("{product_loop_end}", "", $template_org); + $template_org = str_replace($template_tmp_desc, $data, $template_org); + + $template_org = str_replace("{with_vat}", "", $template_org); + $template_org = str_replace("{without_vat}", "", $template_org); + + $template_org = RedshopHelperTemplate::parseRedshopPlugin($template_org); + $template_org = RedshopHelperText::replaceTexts($template_org); + + eval("?>" . $template_org . "

    " . JText::_('COM_REDSHOP_MSG_SORRY_NO_RESULT_FOUND') . "

    "; } ?> diff --git a/component/site/views/search/tmpl/productonsale.xml b/component/site/views/search/tmpl/productonsale.xml index bcfd3724bae..957240fa1e1 100644 --- a/component/site/views/search/tmpl/productonsale.xml +++ b/component/site/views/search/tmpl/productonsale.xml @@ -9,12 +9,12 @@
    + description="COM_REDSHOP_SEARCH_RESULT_DISPALY_IN_SELECTED_CATEGORY_TEMPLATE"/> + label="COM_REDSHOP_ENTER_CATEGORY_ID_FOR_TEMPLET" + description="COM_REDSHOP_CATEGORY_ID_FOR_NEWEST_PRODUCT_SEARCH_TEMPLATE"/> + description="COM_REDSHOP_ENTER_NO_OF_AMOUNT_HOW_MANY_PRODUCTS_TO_SHOW"/>
    diff --git a/component/site/views/search/tmpl/redfilter.xml b/component/site/views/search/tmpl/redfilter.xml index 8c9baf48daa..35a68364c06 100644 --- a/component/site/views/search/tmpl/redfilter.xml +++ b/component/site/views/search/tmpl/redfilter.xml @@ -8,7 +8,8 @@
    - diff --git a/component/site/views/search/view.html.php b/component/site/views/search/view.html.php index 2d23c65e306..096336f0574 100644 --- a/component/site/views/search/view.html.php +++ b/component/site/views/search/view.html.php @@ -12,780 +12,874 @@ class RedshopViewSearch extends RedshopView { - public function display($tpl = null) - { - $app = JFactory::getApplication(); - - $lists = array(); - - $params = $app->getParams('com_redshop'); - $document = JFactory::getDocument(); - - $layout = $app->input->getCmd('layout', ''); - $model = $this->getModel('search'); - - if ($layout == 'default') - { - $pagetitle = JText::_('COM_REDSHOP_SEARCH'); - $document->setTitle($pagetitle); - } - - if ($layout == 'redfilter') - { - $session = JSession::getInstance('none', array()); - $tagid = $app->input->getInt('tagid', 0); - $typeid = $app->input->getInt('typeid', 0); - $remove = $app->input->getInt('remove', 0); - $Itemid = $app->input->getInt('Itemid', 0); - $cntproduct = $app->input->getInt('cnt', 0); - $getredfilter = $session->get('redfilter'); - - if (empty($getredfilter)) - { - $redfilter = array(); - } - else - { - $redfilter = $getredfilter; - } - - if ($tagid != 0 && $typeid != 0 && !array_key_exists($typeid, $redfilter)) - { - $redfilter[$typeid] = $tagid; - } - - if ($remove == 1) - { - if ($typeid != 0) - { - unset($redfilter[$typeid]); - $session->set('redfilter', $redfilter); - - $this->setLayout('redfilter'); - $model->getRedFilterProduct($remove); - - echo $model->mod_redProductfilter($Itemid, $typeid) . '~'; - } - else - { - $session->destroy('redfilter'); - } - } - - $session->set('redfilter', $redfilter); - - if ($cntproduct == 1) - { - $mypid = $app->input->getInt('pid', 0); - - $app->redirect(JRoute::_('index.php?option=com_redshop&view=product&pid=' . $mypid . '&Itemid=' . $Itemid)); - } - } - - $order_data = RedshopHelperUtility::getOrderByList(); - $getorderby = $app->input->getString('order_by', - $app->getUserState('order_by', Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD')) - ); - $app->setUserState('order_by', $getorderby); - JFactory::getApplication()->input->set('order_by', $app->getUserState('order_by')); - $lists['order_select'] = JHTML::_('select.genericlist', $order_data, 'order_by', 'class="inputbox" size="1" onchange="document.orderby_form.submit();" ', 'value', 'text', $getorderby); - $search = $this->get('Data'); - $pagination = $this->get('Pagination'); - - $this->params = $params; - $this->lists = $lists; - $this->templatedata = $model->getState('templateDesc'); - $this->search = $search; - $this->pagination = $pagination; - parent::display($tpl); - } - - /** - * Generate product search output - */ - public function onRSProductSearch() - { - if (count($this->search) > 0) - { - JPluginHelper::importPlugin('redshop_product'); - - $app = JFactory::getApplication(); - $input = JFactory::getApplication()->input; - $input->set('order_by', $app->getUserState('order_by')); - - $dispatcher = RedshopHelperUtility::getDispatcher(); - - $Itemid = $app->input->getInt('Itemid'); - $search_type = $app->input->getCmd('search_type'); - $cid = $app->input->getInt('category_id'); - $manufacture_id = $app->input->getInt('manufacture_id'); - - $templateid = $app->input->getInt('templateid'); - - // Cmd removes space between to words - $keyword = $app->input->getString('keyword'); - $layout = $app->input->getCmd('layout', 'default'); - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('name')) - ->from($db->qn('#__redshop_category')) - ->where($db->qn('id') . ' = ' . $db->q((int) $input->getInt('cid', 0))); - - $cat_name = $db->setQuery($query)->loadResult(); - - $model = $this->getModel('search'); - $total = $model->getTotal(); - - JHTML::_('behavior.modal'); - $url = JURI::base(); - - if ($this->params->get('page_title') != "") - { - $pagetitle = $this->params->get('page_title'); - } - else - { - $pagetitle = JText::_('COM_REDSHOP_SEARCH'); - } - - if ($this->params->get('show_page_heading', 1)) - { - echo '

    '; - echo $pagetitle; - echo '

    '; - } - - echo '
    '; - $category_tmpl = ""; - - if ($this->templatedata != "") - { - $templateDesc = $this->templatedata; - } - else - { - $templateDesc = "
    {print}
    \r\n
    \r\n
    {category_main_description}
    \r\n

    {if subcats} {category_loop_start}

    \r\n
    \r\n
    \r\n
    {category_thumb_image}
    \r\n
    \r\n

    {category_name}

    \r\n{category_description}
    \r\n
    \r\n
    \r\n

    {category_loop_end} {subcats end if}

    \r\n
    \r\n
    \r\n
    {order_by}
    \r\n
    \r\n
    {product_loop_start}\r\n
    \r\n
    \r\n
    {product_thumb_image}
    \r\n
    \r\n

    {product_name}

    \r\n
    \r\n
    {product_price}
    \r\n
    {read_more}
    \r\n
    {product_rating_summary}
    \r\n
    {form_addtocart:add_to_cart1}
    \r\n
    \r\n
    \r\n{product_loop_end}\r\n
    \r\n
    \r\n
    {pagination}
    "; - } - - $template_org = $templateDesc; - $template_d1 = explode("{category_loop_start}", $template_org); - - if (count($template_d1) > 1) - { - $template_d2 = explode("{category_loop_end}", $template_d1[1]); - - if (count($template_d2) > 0) - { - $category_tmpl = $template_d2[0]; - } - } - - $template_org = str_replace($category_tmpl, "", $template_org); - $template_org = str_replace("{category_loop_start}", "", $template_org); - $template_org = str_replace("{category_loop_end}", "", $template_org); - $print = $app->input->getInt('print'); - $p_url = @ explode('?', $app->input->server->get('REQUEST_URI', '', 'raw')); - $print_tag = ''; - - if ($print) - { - $print_tag = "" . JText::_("; - } - else - { - $print_url = $url . "index.php?option=com_redshop&view=search&print=1&tmpl=component"; - $print_tag = "" . JText::_("; - } - - if (strstr($template_org, '{compare_product_div}')) - { - $compareProductDiv = ''; - - if (Redshop::getConfig()->get('PRODUCT_COMPARISON_TYPE') != '') - { - $compareProductDiv = RedshopLayoutHelper::render('product.compare_product'); - } - - $template_org = str_replace('{compare_product_div}', $compareProductDiv, $template_org); - } - - // Skip html if nosubcategory - if (strstr($template_org, "{if subcats}")) - { - $template_d1 = explode("{if subcats}", $template_org); - $template_d2 = explode("{subcats end if}", $template_d1[1]); - $template_org = $template_d1[0] . $template_d2[1]; - } - - // End skip html if nosubcategory - $template_org = str_replace("{print}", $print_tag, $template_org); - $template_org = str_replace("{product_price_slider}", '', $template_org); - $template_org = str_replace("{filter_by}", '', $template_org); - $template_org = str_replace("{template_selector_category_lbl}", '', $template_org); - $template_org = str_replace("{template_selector_category}", '', $template_org); - $template_org = str_replace("{category_main_name}", $cat_name, $template_org); - $template_org = str_replace("{category_main_description}", '', $template_org); - $template_org = str_replace("{category_description}", '', $template_org); - $template_org = str_replace("{category_short_desc}", '', $template_org); - $template_org = str_replace("{category_name}", '', $template_org); - $template_org = str_replace("{if subcats}", '', $template_org); - $template_org = str_replace("{subcats end if}", '', $template_org); - $template_org = str_replace("{category_main_thumb_image_3}", '', $template_org); - $template_org = str_replace("{category_main_short_desc}", '', $template_org); - $template_org = str_replace("{category_main_thumb_image_2}", '', $template_org); - $template_org = str_replace("{category_main_thumb_image_1}", '', $template_org); - $template_org = str_replace("{category_main_thumb_image}", '', $template_org); - $template_org = str_replace("{attribute_price_without_vat}", '', $template_org); - $template_org = str_replace("{redproductfinderfilter_formstart}", '', $template_org); - $template_org = str_replace("{redproductfinderfilter:rp_myfilter}", '', $template_org); - $template_org = str_replace("{redproductfinderfilter_formend}", '', $template_org); - $template_org = str_replace("{total_product}", $total, $template_org); - $template_org = str_replace("{total_product_lbl}", JText::_('COM_REDSHOP_TOTAL_PRODUCT'), $template_org); - - // Replace redproductfilder filter tag - if (strstr($template_org, "{redproductfinderfilter:")) - { - $redProductFinerHelper = JPATH_SITE . "/components/com_redproductfinder/helpers/redproductfinder_helper.php"; - if (file_exists($redProductFinerHelper)) - { - include_once $redProductFinerHelper; - $redproductfinder_helper = new redproductfinder_helper; - $hdnFields = array('texpricemin' => '0', 'texpricemax' => '0', 'manufacturer_id' => $filter_by, 'category_template' => $templateid); - $hide_filter_flag = false; - - if ($this->_id) - { - $prodctofcat = RedshopHelperProduct::getProductCategory($this->_id); - - if (empty($prodctofcat)) - $hide_filter_flag = true; - } - - $template_org = $redproductfinder_helper->replaceProductfinder_tag($template_org, $hdnFields, $hide_filter_flag); - } - } - - // Replace redproductfilder filter tag end here - $template_d1 = explode("{product_loop_start}", $template_org); - $template_d2 = explode("{product_loop_end}", $template_d1[1]); - $template_tmp_desc = $template_d2[0]; - $templateDesc = $template_d2[0]; - - // Order By - $order_by = ""; - $orderby_form = "
    "; - $orderby_form .= $this->lists['order_select']; - $orderby_form .= " + public function display($tpl = null) + { + $app = JFactory::getApplication(); + + $lists = array(); + + $params = $app->getParams('com_redshop'); + $document = JFactory::getDocument(); + + $layout = $app->input->getCmd('layout', ''); + $model = $this->getModel('search'); + + if ($layout == 'default') { + $pagetitle = JText::_('COM_REDSHOP_SEARCH'); + $document->setTitle($pagetitle); + } + + if ($layout == 'redfilter') { + $session = JSession::getInstance('none', array()); + $tagid = $app->input->getInt('tagid', 0); + $typeid = $app->input->getInt('typeid', 0); + $remove = $app->input->getInt('remove', 0); + $Itemid = $app->input->getInt('Itemid', 0); + $cntproduct = $app->input->getInt('cnt', 0); + $getredfilter = $session->get('redfilter'); + + if (empty($getredfilter)) { + $redfilter = array(); + } else { + $redfilter = $getredfilter; + } + + if ($tagid != 0 && $typeid != 0 && !array_key_exists($typeid, $redfilter)) { + $redfilter[$typeid] = $tagid; + } + + if ($remove == 1) { + if ($typeid != 0) { + unset($redfilter[$typeid]); + $session->set('redfilter', $redfilter); + + $this->setLayout('redfilter'); + $model->getRedFilterProduct($remove); + + echo $model->mod_redProductfilter($Itemid, $typeid) . '~'; + } else { + $session->destroy('redfilter'); + } + } + + $session->set('redfilter', $redfilter); + + if ($cntproduct == 1) { + $mypid = $app->input->getInt('pid', 0); + + $app->redirect( + JRoute::_('index.php?option=com_redshop&view=product&pid=' . $mypid . '&Itemid=' . $Itemid) + ); + } + } + + $order_data = RedshopHelperUtility::getOrderByList(); + $getorderby = $app->input->getString( + 'order_by', + $app->getUserState('order_by', Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD')) + ); + $app->setUserState('order_by', $getorderby); + JFactory::getApplication()->input->set('order_by', $app->getUserState('order_by')); + $lists['order_select'] = JHTML::_( + 'select.genericlist', + $order_data, + 'order_by', + 'class="inputbox" size="1" onchange="document.orderby_form.submit();" ', + 'value', + 'text', + $getorderby + ); + $search = $this->get('Data'); + $pagination = $this->get('Pagination'); + + $this->params = $params; + $this->lists = $lists; + $this->templatedata = $model->getState('templateDesc'); + $this->search = $search; + $this->pagination = $pagination; + parent::display($tpl); + } + + /** + * Generate product search output + */ + public function onRSProductSearch() + { + if (count($this->search) > 0) { + JPluginHelper::importPlugin('redshop_product'); + + $app = JFactory::getApplication(); + $input = JFactory::getApplication()->input; + $input->set('order_by', $app->getUserState('order_by')); + + $dispatcher = RedshopHelperUtility::getDispatcher(); + + $Itemid = $app->input->getInt('Itemid'); + $search_type = $app->input->getCmd('search_type'); + $cid = $app->input->getInt('category_id'); + $manufacture_id = $app->input->getInt('manufacture_id'); + + $templateid = $app->input->getInt('templateid'); + + // Cmd removes space between to words + $keyword = $app->input->getString('keyword'); + $layout = $app->input->getCmd('layout', 'default'); + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('name')) + ->from($db->qn('#__redshop_category')) + ->where($db->qn('id') . ' = ' . $db->q((int)$input->getInt('cid', 0))); + + $cat_name = $db->setQuery($query)->loadResult(); + + $model = $this->getModel('search'); + $total = $model->getTotal(); + + JHTML::_('behavior.modal'); + $url = JURI::base(); + + if ($this->params->get('page_title') != "") { + $pagetitle = $this->params->get('page_title'); + } else { + $pagetitle = JText::_('COM_REDSHOP_SEARCH'); + } + + if ($this->params->get('show_page_heading', 1)) { + echo '

    '; + echo $pagetitle; + echo '

    '; + } + + echo '
    '; + $category_tmpl = ""; + + if ($this->templatedata != "") { + $templateDesc = $this->templatedata; + } else { + $templateDesc = "
    {print}
    \r\n
    \r\n
    {category_main_description}
    \r\n

    {if subcats} {category_loop_start}

    \r\n
    \r\n
    \r\n
    {category_thumb_image}
    \r\n
    \r\n

    {category_name}

    \r\n{category_description}
    \r\n
    \r\n
    \r\n

    {category_loop_end} {subcats end if}

    \r\n
    \r\n
    \r\n
    {order_by}
    \r\n
    \r\n
    {product_loop_start}\r\n
    \r\n
    \r\n
    {product_thumb_image}
    \r\n
    \r\n

    {product_name}

    \r\n
    \r\n
    {product_price}
    \r\n
    {read_more}
    \r\n
    {product_rating_summary}
    \r\n
    {form_addtocart:add_to_cart1}
    \r\n
    \r\n
    \r\n{product_loop_end}\r\n
    \r\n
    \r\n
    {pagination}
    "; + } + + $template_org = $templateDesc; + $template_d1 = explode("{category_loop_start}", $template_org); + + if (count($template_d1) > 1) { + $template_d2 = explode("{category_loop_end}", $template_d1[1]); + + if (count($template_d2) > 0) { + $category_tmpl = $template_d2[0]; + } + } + + $template_org = str_replace($category_tmpl, "", $template_org); + $template_org = str_replace("{category_loop_start}", "", $template_org); + $template_org = str_replace("{category_loop_end}", "", $template_org); + $print = $app->input->getInt('print'); + $p_url = @ explode('?', $app->input->server->get('REQUEST_URI', '', 'raw')); + $print_tag = ''; + + if ($print) { + $print_tag = "" . JText::_(
+                        "; + } else { + $print_url = $url . "index.php?option=com_redshop&view=search&print=1&tmpl=component"; + $print_tag = "" . JText::_(
+                        "; + } + + if (strstr($template_org, '{compare_product_div}')) { + $compareProductDiv = ''; + + if (Redshop::getConfig()->get('PRODUCT_COMPARISON_TYPE') != '') { + $compareProductDiv = RedshopLayoutHelper::render('product.compare_product'); + } + + $template_org = str_replace('{compare_product_div}', $compareProductDiv, $template_org); + } + + // Skip html if nosubcategory + if (strstr($template_org, "{if subcats}")) { + $template_d1 = explode("{if subcats}", $template_org); + $template_d2 = explode("{subcats end if}", $template_d1[1]); + $template_org = $template_d1[0] . $template_d2[1]; + } + + // End skip html if nosubcategory + $template_org = str_replace("{print}", $print_tag, $template_org); + $template_org = str_replace("{product_price_slider}", '', $template_org); + $template_org = str_replace("{filter_by}", '', $template_org); + $template_org = str_replace("{template_selector_category_lbl}", '', $template_org); + $template_org = str_replace("{template_selector_category}", '', $template_org); + $template_org = str_replace("{category_main_name}", $cat_name, $template_org); + $template_org = str_replace("{category_main_description}", '', $template_org); + $template_org = str_replace("{category_description}", '', $template_org); + $template_org = str_replace("{category_short_desc}", '', $template_org); + $template_org = str_replace("{category_name}", '', $template_org); + $template_org = str_replace("{if subcats}", '', $template_org); + $template_org = str_replace("{subcats end if}", '', $template_org); + $template_org = str_replace("{category_main_thumb_image_3}", '', $template_org); + $template_org = str_replace("{category_main_short_desc}", '', $template_org); + $template_org = str_replace("{category_main_thumb_image_2}", '', $template_org); + $template_org = str_replace("{category_main_thumb_image_1}", '', $template_org); + $template_org = str_replace("{category_main_thumb_image}", '', $template_org); + $template_org = str_replace("{attribute_price_without_vat}", '', $template_org); + $template_org = str_replace("{redproductfinderfilter_formstart}", '', $template_org); + $template_org = str_replace("{redproductfinderfilter:rp_myfilter}", '', $template_org); + $template_org = str_replace("{redproductfinderfilter_formend}", '', $template_org); + $template_org = str_replace("{total_product}", $total, $template_org); + $template_org = str_replace("{total_product_lbl}", JText::_('COM_REDSHOP_TOTAL_PRODUCT'), $template_org); + + // Replace redproductfilder filter tag + if (strstr($template_org, "{redproductfinderfilter:")) { + $redProductFinerHelper = JPATH_SITE . "/components/com_redproductfinder/helpers/redproductfinder_helper.php"; + if (file_exists($redProductFinerHelper)) { + include_once $redProductFinerHelper; + $redproductfinder_helper = new redproductfinder_helper; + $hdnFields = array( + 'texpricemin' => '0', + 'texpricemax' => '0', + 'manufacturer_id' => $filter_by, + 'category_template' => $templateid + ); + $hide_filter_flag = false; + + if ($this->_id) { + $prodctofcat = RedshopHelperProduct::getProductCategory($this->_id); + + if (empty($prodctofcat)) { + $hide_filter_flag = true; + } + } + + $template_org = $redproductfinder_helper->replaceProductfinder_tag( + $template_org, + $hdnFields, + $hide_filter_flag + ); + } + } + + // Replace redproductfilder filter tag end here + $template_d1 = explode("{product_loop_start}", $template_org); + $template_d2 = explode("{product_loop_end}", $template_d1[1]); + $template_tmp_desc = $template_d2[0]; + $templateDesc = $template_d2[0]; + + // Order By + $order_by = ""; + $orderby_form = ""; + $orderby_form .= $this->lists['order_select']; + $orderby_form .= "
    "; - if (strstr($templateDesc, '{order_by}')) - { - $order_by = $orderby_form; - } - - $extraFieldName = Redshop\Helper\ExtraFields::getSectionFieldNames(1, 1, 1); - $extraFieldsForCurrentTemplate = RedshopHelperTemplate::getExtraFieldsForCurrentTemplate($extraFieldName, $templateDesc, 1); - $attribute_template = \Redshop\Template\Helper::getAttribute($templateDesc); - - $total_product = $model->getTotal(); - $endlimit = $model->getState('list.limit'); - $start = $model->getState('list.start'); - - $tagarray = RedshopHelperText::getTextLibraryTagArray(); - $data = ""; - $count_no_user_field = 0; - $fieldArray = RedshopHelperExtrafields::getSectionFieldList(17, 0, 0); - - for ($i = 0, $countSearch = count($this->search); $i < $countSearch; $i++) - { - $data_add = $templateDesc; - - // RedSHOP Product Plugin - $params = array(); - $dispatcher->trigger('onPrepareProduct', array(&$data_add, &$params, $this->search[$i])); - - $thum_image = ""; - $pname = RedshopHelperUtility::maxChars($this->search[$i]->product_name, Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_MAX_CHARS'), Redshop::getConfig()->get('CATEGORY_PRODUCT_TITLE_END_SUFFIX')); - - if ($search_type == 'product_number') - { - $product_number = preg_replace("/($keyword)/i", "$1", $this->search[$i]->product_number); - $pro_s_desc = $this->search[$i]->product_s_desc; - $pro_desc = $this->search[$i]->product_desc; - } - else - { - $product_number = $this->search[$i]->product_number; - $pro_s_desc = $this->search[$i]->product_s_desc; - $pro_desc = $this->search[$i]->product_desc; - - if (!empty($keyword) && !in_array($keyword, $tagarray)) - { - $regex = "/" . preg_quote($keyword, "/") . "(?![^<]*>)/"; - $pname = preg_replace($regex, "" . $keyword . "", $pname); - $product_number = preg_replace($regex, "" . $keyword . "", $product_number); - $pro_s_desc = preg_replace($regex, "" . $keyword . "", $pro_s_desc); - $pro_desc = preg_replace($regex, "" . $keyword . "", $pro_desc); - } - } - - $pro_s_desc = RedshopHelperUtility::maxChars($pro_s_desc, Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_MAX_CHARS'), Redshop::getConfig()->get('CATEGORY_PRODUCT_DESC_END_SUFFIX')); - - $ItemData = RedshopHelperProduct::getMenuInformation(0, 0, '', 'product&pid=' . $this->search[$i]->product_id); - - if (!empty($ItemData)) - { - $pItemid = $ItemData->id; - } - else - { - $pItemid = RedshopHelperRouter::getItemId($this->search[$i]->product_id, $this->search[$i]->category_id); - } - - $link = JRoute::_('index.php?option=com_redshop&view=product&pid=' . $this->search[$i]->product_id . '&cid=' . $this->search[$i]->category_id . '&Itemid=' . $pItemid); - - if (strstr($data_add, '{product_name}')) - { - $pname = "" . $pname . ""; - $data_add = str_replace("{product_name}", $pname, $data_add); - } - - if (strstr($data_add, '{product_name_nolink}')) - { - $data_add = str_replace("{product_name_nolink}", $pname, $data_add); - } - - $readmore = "" . JText::_('COM_REDSHOP_READ_MORE') . ""; - $data_add = str_replace("{read_more}", $readmore, $data_add); - $data_add = str_replace("{read_more_link}", $link, $data_add); - - if (strstr($data_add, "{product_delivery_time}")) - { - $product_delivery_time = RedshopHelperProduct::getProductMinDeliveryTime($this->search[$i]->product_id); - - if ($product_delivery_time != "") - { - $data_add = str_replace("{delivery_time_lbl}", JText::_('DELIVERY_TIME'), $data_add); - $data_add = str_replace("{product_delivery_time}", $product_delivery_time, $data_add); - } - else - { - $data_add = str_replace("{delivery_time_lbl}", "", $data_add); - $data_add = str_replace("{product_delivery_time}", "", $data_add); - } - } - - // Product Review/Rating - // Fetching reviews - $final_avgreview_data = Redshop\Product\Rating::getRating($this->search[$i]->product_id); - - // Attribute ajax chage - $data_add = str_replace("{product_rating_summary}", $final_avgreview_data, $data_add); - $data_add = RedshopHelperProduct::getJcommentEditor($this->search[$i], $data_add); - - if ($extraFieldsForCurrentTemplate) - { - $data_add = Redshop\Helper\ExtraFields::displayExtraFields(1, $this->search[$i]->product_id, $extraFieldsForCurrentTemplate, $data_add, true); - } - - $data_add = str_replace("{product_s_desc}", $pro_s_desc, $data_add); - $data_add = str_replace("{product_desc}", $pro_desc, $data_add); - $data_add = str_replace("{product_id_lbl}", JText::_('COM_REDSHOP_PRODUCT_ID_LBL'), $data_add); - $data_add = str_replace("{product_id}", $this->search[$i]->product_id, $data_add); - $data_add = str_replace("{product_number_lbl}", JText::_('COM_REDSHOP_PRODUCT_NUMBER_LBL'), $data_add); - $data_add = str_replace("{product_number}", $product_number, $data_add); - - // Product category tags - $data_add = str_replace("{returntocategory_name}", $this->search[$i]->category_name, $data_add); - - if (strstr($data_add, "{returntoparent_category_name}")) - { - $parentCategoryId = RedshopHelperProduct::getParentCategory($this->search[$i]->category_id); - - if ($parentCategoryId != 0) - { - $parentCategory = RedshopEntityCategory::getInstance($parentCategoryId)->getItem(); - $data_add = str_replace("{returntoparent_category_name}", $parentCategory->category_name, $data_add); - } - else - { - $data_add = str_replace("{returntoparent_category_name}", '', $data_add); - } - } - - /** - * related Product List in Lightbox - * Tag Format = {related_product_lightbox:[:width][:height]} - */ - if (strstr($data_add, '{related_product_lightbox:')) - { - $related_product = RedshopHelperProduct::getRelatedProduct($this->search[$i]->product_id); - $rtlnone = explode("{related_product_lightbox:", $data_add); - $rtlntwo = explode("}", $rtlnone[1]); - $rtlnthree = explode(":", $rtlntwo[0]); - $rtln = $rtlnthree[0]; - $rtlnfwidth = (isset($rtlnthree[1])) ? $rtlnthree[1] : "900"; - $rtlnwidthtag = (isset($rtlnthree[1])) ? ":" . $rtlnthree[1] : ""; - - $rtlnfheight = (isset($rtlnthree[2])) ? $rtlnthree[2] : "600"; - $rtlnheighttag = (isset($rtlnthree[2])) ? ":" . $rtlnthree[2] : ""; - - $rtlntag = "{related_product_lightbox:$rtln$rtlnwidthtag$rtlnheighttag}"; - - if (count($related_product) > 0) - { - $linktortln = JURI::root() . "index.php?option=com_redshop&view=product&pid=" . $this->search[$i]->product_id . "&tmpl=component&template=" . $rtln . "&for=rtln"; - $rtlna = '' . JText::_('COM_REDSHOP_RELATED_PRODUCT_LIST_IN_LIGHTBOX') . ''; - } - else - { - $rtlna = ""; - } - - $data_add = str_replace($rtlntag, $rtlna, $data_add); - } - - $data_add = RedshopHelperTax::replaceVatInformation($data_add); - - /************************************ - * Conditional tag - * if product on discount : Yes - * {if product_on_sale} This product is on sale {product_on_sale end if} // OUTPUT : This product is on sale - * NO : // OUTPUT : Display blank - ************************************/ - $data_add = RedshopHelperProduct::getProductOnSaleComment($this->search[$i], $data_add); - - $data_add = RedshopHelperStockroom::replaceStockroomAmountDetail($data_add, $this->search[$i]->product_id); - - if (strstr($data_add, "{product_thumb_image_3}")) - { - $cimg_tag = '{product_thumb_image_3}'; - $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_3'); - $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_3'); - } - elseif (strstr($data_add, "{product_thumb_image_2}")) - { - $cimg_tag = '{product_thumb_image_2}'; - $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_2'); - $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_2'); - } - elseif (strstr($data_add, "{product_thumb_image_1}")) - { - $cimg_tag = '{product_thumb_image_1}'; - $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); - $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); - } - else - { - $cimg_tag = '{product_thumb_image}'; - $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); - $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); - } - - $hidden_thumb_image = ""; - $thum_image = Redshop\Product\Image\Image::getImage($this->search[$i]->product_id, $link, $cw_thumb, $ch_thumb); - $data_add = str_replace($cimg_tag, $thum_image . $hidden_thumb_image, $data_add); - - // More documents - if (strstr($data_add, "{more_documents}")) - { - $media_documents = RedshopHelperMedia::getAdditionMediaImage($this->search[$i]->product_id, "product", "document"); - $more_doc = ''; - - for ($m = 0, $countMedia = count($media_documents); $m < $countMedia; $m++) - { - $alttext = RedshopHelperMedia::getAlternativeText( - "product", $media_documents[$m]->section_id, "", $media_documents[$m]->media_id, "document" - ); - - if (!$alttext) - { - $alttext = $media_documents[$m]->media_name; - } - - if (JFile::exists(REDSHOP_FRONT_DOCUMENT_RELPATH . "product/" . $media_documents[$m]->media_name)) - { - $downlink = JURI::root() . 'index.php?tmpl=component&option=com_redshop&view=product&pid=' . $this->search[$i]->product_id . '&task=downloadDocument&fname=' . $media_documents[$m]->media_name . '&Itemid=' . $Itemid; - $more_doc .= ""; - } - } - - $data_add = str_replace("{more_documents}", "" . $more_doc . "", $data_add); - } - - // More documents end - - /************************************************ user fields*******************************************************/ - $hidden_userfield = ""; - $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($data_add); - $template_userfield = $returnArr[0]; - $userfieldArr = $returnArr[1]; - $count_no_user_field = 0; - - if ($template_userfield != "") - { - $ufield = ""; - - for ($ui = 0, $countUserField = count($userfieldArr); $ui < $countUserField; $ui++) - { - $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields($userfieldArr[$ui], 12, '', '', 0, $this->search[$i]->product_id); - $ufield .= $productUserFields[1]; - - if ($productUserFields[1] != "") - { - $count_no_user_field++; - } - - $data_add = str_replace('{' . $userfieldArr[$ui] . '_lbl}', $productUserFields[0], $data_add); - $data_add = str_replace('{' . $userfieldArr[$ui] . '}', $productUserFields[1], $data_add); - } - - $productUserFieldsForm = "
    "; - - if ($ufield != "") - { - $data_add = str_replace("{if product_userfield}", $productUserFieldsForm, $data_add); - $data_add = str_replace("{product_userfield end if}", "
    ", $data_add); - } - else - { - $data_add = str_replace("{if product_userfield}", "", $data_add); - $data_add = str_replace("{product_userfield end if}", "", $data_add); - } - } - elseif (Redshop::getConfig()->get('AJAX_CART_BOX')) - { - $ajax_detail_template_desc = ""; - $ajax_detail_template = \Redshop\Template\Helper::getAjaxDetailBox($this->search[$i]); - - if (null !== $ajax_detail_template) - { - $ajax_detail_template_desc = $ajax_detail_template->template_desc; - } - - $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($ajax_detail_template_desc); - $template_userfield = $returnArr[0]; - $userfieldArr = $returnArr[1]; - - if ($template_userfield != "") - { - $ufield = ""; - - for ($ui = 0, $countUserField = count($userfieldArr); $ui < $countUserField; $ui++) - { - $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields($userfieldArr[$ui], 12, '', '', 0, $this->search[$i]->product_id); - $ufield .= $productUserFields[1]; - - if ($productUserFields[1] != "") - { - $count_no_user_field++; - } - - $template_userfield = str_replace('{' . $userfieldArr[$ui] . '_lbl}', $productUserFields[0], $template_userfield); - $template_userfield = str_replace('{' . $userfieldArr[$ui] . '}', $productUserFields[1], $template_userfield); - } - - if ($ufield != "") - { - $hidden_userfield = "
    " . $template_userfield . "
    "; - } - } - } - - $data_add = $data_add . $hidden_userfield; - - /*************** end user fields ***************/ - - // ProductFinderDatepicker Extra Field Start - - $data_add = RedshopHelperProduct::getProductFinderDatepickerValue($data_add, $this->search[$i]->product_id, $fieldArray); - - // ProductFinderDatepicker Extra Field End - - /* - * manufacturer data - */ - $manufacturer_id = $this->search[$i]->id; - - if ($manufacturer_id != 0) - { - $manufacturer_link_href = JRoute::_('index.php?option=com_redshop&view=manufacturers&layout=detail&mid=' . $manufacturer_id . '&Itemid=' . $Itemid); - $manufacturer_name = $this->search[$i]->name; - $manufacturer_link = '' . $manufacturer_name . ''; - - if (strstr($data_add, "{manufacturer_link}")) - { - $data_add = str_replace("{manufacturer_name}", "", $data_add); - } - else - { - $data_add = str_replace("{manufacturer_name}", $manufacturer_name, $data_add); - } - - $data_add = str_replace("{manufacturer_link}", $manufacturer_link, $data_add); - } - else - { - $data_add = str_replace("{manufacturer_link}", "", $data_add); - $data_add = str_replace("{manufacturer_name}", "", $data_add); - } - - // End - - // Replace wishlistbutton - $data_add = RedshopHelperWishlist::replaceWishlistTag($this->search[$i]->product_id, $data_add); - - // Replace compare product button - $data_add = Redshop\Product\Compare::replaceCompareProductsButton($this->search[$i]->product_id, 0, $data_add); - - // Checking for child products - if ($this->search[$i]->count_child_products > 0) - { - $isChilds = true; - $attributes = array(); - } - else - { - $isChilds = false; - - // Get attributes - $attributes_set = array(); - - if ($this->search[$i]->attribute_set_id > 0) - { - $attributes_set = \Redshop\Product\Attribute::getProductAttribute(0, $this->search[$i]->attribute_set_id, 0, 1); - } - - $attributes = \Redshop\Product\Attribute::getProductAttribute($this->search[$i]->product_id); - $attributes = array_merge($attributes, $attributes_set); - } - - // Product attribute Start - $totalatt = count($attributes); - - // Check product for not for sale - $data_add = RedshopHelperProduct::getProductNotForSaleComment($this->search[$i], $data_add, $attributes); - - $data_add = Redshop\Product\Stock::replaceInStock($this->search[$i]->product_id, $data_add, $attributes, $attribute_template); - - $data_add = RedshopHelperAttribute::replaceAttributeData($this->search[$i]->product_id, 0, 0, $attributes, $data_add, $attribute_template, $isChilds); - - // Cart Template - $data_add = Redshop\Cart\Render::replace($this->search[$i]->product_id, 0, 0, 0, $data_add, $isChilds, $userfieldArr, $totalatt, $this->search[$i]->total_accessories, $count_no_user_field); - - $data_add = RedshopHelperProductTag::getExtraSectionTag($extraFieldName, $this->search[$i]->product_id, "1", $data_add); - - $productAvailabilityDate = strstr($data_add, "{product_availability_date}"); - $stockNotifyFlag = strstr($data_add, "{stock_notify_flag}"); - $stockStatus = strstr($data_add, "{stock_status"); - - $attributeproductStockStatus = array(); - - if ($productAvailabilityDate || $stockNotifyFlag || $stockStatus) - { - $attributeproductStockStatus = RedshopHelperProduct::getproductStockStatus($this->search[$i]->product_id, $totalatt); - } - - $data_add = \Redshop\Helper\Stockroom::replaceProductStockData( - $this->search[$i]->product_id, - 0, - 0, - $data_add, - $attributeproductStockStatus - ); - - $dispatcher->trigger('onAfterDisplayProduct', array(&$data_add, array(), $this->search[$i])); - - $data .= $data_add; - } - - $app = JFactory::getApplication(); - $router = $app->getRouter(); - - $getorderby = $app->input->get('order_by', Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD')); - - $vars = array( - 'option' => 'com_redshop', - 'view' => 'search', - 'layout' => $layout, - 'keyword' => $keyword, - 'manufacture_id' => $manufacture_id, - 'order_by' => $getorderby, - 'category_id' => $cid, - 'Itemid' => $Itemid, - 'search_type' => $search_type - ); - $router->setVars($vars); - unset($vars); - - if (strstr($template_org, "{show_all_products_in_category}")) - { - $template_org = str_replace("{show_all_products_in_category}", "", $template_org); - $template_org = str_replace("{pagination}", "", $template_org); - } - - $pagination = new JPagination($total_product, $start, $endlimit); - - if (strstr($template_org, "{pagination}")) - { - $template_org = str_replace("{pagination}", $pagination->getPagesLinks(), $template_org); - } - - $usePerPageLimit = false; - - if (strstr($template_org, "perpagelimit:")) - { - $usePerPageLimit = true; - $perpage = explode('{perpagelimit:', $template_org); - $perpage = explode('}', $perpage[1]); - $template_org = str_replace("{perpagelimit:" . intval($perpage[0]) . "}", "", $template_org); - } - - if (strstr($template_org, "{product_display_limit}")) - { - if ($usePerPageLimit) - { - $limitBox = ''; - } - else - { - $limitBox = "
    + if (strstr($templateDesc, '{order_by}')) { + $order_by = $orderby_form; + } + + $extraFieldName = Redshop\Helper\ExtraFields::getSectionFieldNames(1, 1, 1); + $extraFieldsForCurrentTemplate = RedshopHelperTemplate::getExtraFieldsForCurrentTemplate( + $extraFieldName, + $templateDesc, + 1 + ); + $attribute_template = \Redshop\Template\Helper::getAttribute($templateDesc); + + $total_product = $model->getTotal(); + $endlimit = $model->getState('list.limit'); + $start = $model->getState('list.start'); + + $tagarray = RedshopHelperText::getTextLibraryTagArray(); + $data = ""; + $count_no_user_field = 0; + $fieldArray = RedshopHelperExtrafields::getSectionFieldList(17, 0, 0); + + for ($i = 0, $countSearch = count($this->search); $i < $countSearch; $i++) { + $data_add = $templateDesc; + + // RedSHOP Product Plugin + $params = array(); + $dispatcher->trigger('onPrepareProduct', array(&$data_add, &$params, $this->search[$i])); + + $thum_image = ""; + $pname = RedshopHelperUtility::maxChars( + $this->search[$i]->product_name, + Redshop::getConfig()->get( + 'CATEGORY_PRODUCT_TITLE_MAX_CHARS' + ), + Redshop::getConfig()->get( + 'CATEGORY_PRODUCT_TITLE_END_SUFFIX' + ) + ); + + if ($search_type == 'product_number') { + $product_number = preg_replace( + "/($keyword)/i", + "$1", + $this->search[$i]->product_number + ); + $pro_s_desc = $this->search[$i]->product_s_desc; + $pro_desc = $this->search[$i]->product_desc; + } else { + $product_number = $this->search[$i]->product_number; + $pro_s_desc = $this->search[$i]->product_s_desc; + $pro_desc = $this->search[$i]->product_desc; + + if (!empty($keyword) && !in_array($keyword, $tagarray)) { + $regex = "/" . preg_quote($keyword, "/") . "(?![^<]*>)/"; + $pname = preg_replace( + $regex, + "" . $keyword . "", + $pname + ); + $product_number = preg_replace( + $regex, + "" . $keyword . "", + $product_number + ); + $pro_s_desc = preg_replace( + $regex, + "" . $keyword . "", + $pro_s_desc + ); + $pro_desc = preg_replace( + $regex, + "" . $keyword . "", + $pro_desc + ); + } + } + + $pro_s_desc = RedshopHelperUtility::maxChars( + $pro_s_desc, + Redshop::getConfig()->get( + 'CATEGORY_PRODUCT_DESC_MAX_CHARS' + ), + Redshop::getConfig()->get( + 'CATEGORY_PRODUCT_DESC_END_SUFFIX' + ) + ); + + $ItemData = RedshopHelperProduct::getMenuInformation( + 0, + 0, + '', + 'product&pid=' . $this->search[$i]->product_id + ); + + if (!empty($ItemData)) { + $pItemid = $ItemData->id; + } else { + $pItemid = RedshopHelperRouter::getItemId( + $this->search[$i]->product_id, + $this->search[$i]->category_id + ); + } + + $link = JRoute::_( + 'index.php?option=com_redshop&view=product&pid=' . $this->search[$i]->product_id . '&cid=' . $this->search[$i]->category_id . '&Itemid=' . $pItemid + ); + + if (strstr($data_add, '{product_name}')) { + $pname = "" . $pname . ""; + $data_add = str_replace("{product_name}", $pname, $data_add); + } + + if (strstr($data_add, '{product_name_nolink}')) { + $data_add = str_replace("{product_name_nolink}", $pname, $data_add); + } + + $readmore = "" . JText::_('COM_REDSHOP_READ_MORE') . ""; + $data_add = str_replace("{read_more}", $readmore, $data_add); + $data_add = str_replace("{read_more_link}", $link, $data_add); + + if (strstr($data_add, "{product_delivery_time}")) { + $product_delivery_time = RedshopHelperProduct::getProductMinDeliveryTime( + $this->search[$i]->product_id + ); + + if ($product_delivery_time != "") { + $data_add = str_replace("{delivery_time_lbl}", JText::_('DELIVERY_TIME'), $data_add); + $data_add = str_replace("{product_delivery_time}", $product_delivery_time, $data_add); + } else { + $data_add = str_replace("{delivery_time_lbl}", "", $data_add); + $data_add = str_replace("{product_delivery_time}", "", $data_add); + } + } + + // Product Review/Rating + // Fetching reviews + $final_avgreview_data = Redshop\Product\Rating::getRating($this->search[$i]->product_id); + + // Attribute ajax chage + $data_add = str_replace("{product_rating_summary}", $final_avgreview_data, $data_add); + $data_add = RedshopHelperProduct::getJcommentEditor($this->search[$i], $data_add); + + if ($extraFieldsForCurrentTemplate) { + $data_add = Redshop\Helper\ExtraFields::displayExtraFields( + 1, + $this->search[$i]->product_id, + $extraFieldsForCurrentTemplate, + $data_add, + true + ); + } + + $data_add = str_replace("{product_s_desc}", $pro_s_desc, $data_add); + $data_add = str_replace("{product_desc}", $pro_desc, $data_add); + $data_add = str_replace("{product_id_lbl}", JText::_('COM_REDSHOP_PRODUCT_ID_LBL'), $data_add); + $data_add = str_replace("{product_id}", $this->search[$i]->product_id, $data_add); + $data_add = str_replace("{product_number_lbl}", JText::_('COM_REDSHOP_PRODUCT_NUMBER_LBL'), $data_add); + $data_add = str_replace("{product_number}", $product_number, $data_add); + + // Product category tags + $data_add = str_replace("{returntocategory_name}", $this->search[$i]->category_name, $data_add); + + if (strstr($data_add, "{returntoparent_category_name}")) { + $parentCategoryId = RedshopHelperProduct::getParentCategory($this->search[$i]->category_id); + + if ($parentCategoryId != 0) { + $parentCategory = RedshopEntityCategory::getInstance($parentCategoryId)->getItem(); + $data_add = str_replace( + "{returntoparent_category_name}", + $parentCategory->category_name, + $data_add + ); + } else { + $data_add = str_replace("{returntoparent_category_name}", '', $data_add); + } + } + + /** + * related Product List in Lightbox + * Tag Format = {related_product_lightbox:[:width][:height]} + */ + if (strstr($data_add, '{related_product_lightbox:')) { + $related_product = RedshopHelperProduct::getRelatedProduct($this->search[$i]->product_id); + $rtlnone = explode("{related_product_lightbox:", $data_add); + $rtlntwo = explode("}", $rtlnone[1]); + $rtlnthree = explode(":", $rtlntwo[0]); + $rtln = $rtlnthree[0]; + $rtlnfwidth = (isset($rtlnthree[1])) ? $rtlnthree[1] : "900"; + $rtlnwidthtag = (isset($rtlnthree[1])) ? ":" . $rtlnthree[1] : ""; + + $rtlnfheight = (isset($rtlnthree[2])) ? $rtlnthree[2] : "600"; + $rtlnheighttag = (isset($rtlnthree[2])) ? ":" . $rtlnthree[2] : ""; + + $rtlntag = "{related_product_lightbox:$rtln$rtlnwidthtag$rtlnheighttag}"; + + if (count($related_product) > 0) { + $linktortln = JURI::root( + ) . "index.php?option=com_redshop&view=product&pid=" . $this->search[$i]->product_id . "&tmpl=component&template=" . $rtln . "&for=rtln"; + $rtlna = '' . JText::_( + 'COM_REDSHOP_RELATED_PRODUCT_LIST_IN_LIGHTBOX' + ) . ''; + } else { + $rtlna = ""; + } + + $data_add = str_replace($rtlntag, $rtlna, $data_add); + } + + $data_add = RedshopHelperTax::replaceVatInformation($data_add); + + /************************************ + * Conditional tag + * if product on discount : Yes + * {if product_on_sale} This product is on sale {product_on_sale end if} // OUTPUT : This product is on sale + * NO : // OUTPUT : Display blank + ************************************/ + $data_add = RedshopHelperProduct::getProductOnSaleComment($this->search[$i], $data_add); + + $data_add = RedshopHelperStockroom::replaceStockroomAmountDetail( + $data_add, + $this->search[$i]->product_id + ); + + if (strstr($data_add, "{product_thumb_image_3}")) { + $cimg_tag = '{product_thumb_image_3}'; + $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_3'); + $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_3'); + } elseif (strstr($data_add, "{product_thumb_image_2}")) { + $cimg_tag = '{product_thumb_image_2}'; + $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_2'); + $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_2'); + } elseif (strstr($data_add, "{product_thumb_image_1}")) { + $cimg_tag = '{product_thumb_image_1}'; + $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); + $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); + } else { + $cimg_tag = '{product_thumb_image}'; + $ch_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); + $cw_thumb = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); + } + + $hidden_thumb_image = ""; + $thum_image = Redshop\Product\Image\Image::getImage( + $this->search[$i]->product_id, + $link, + $cw_thumb, + $ch_thumb + ); + $data_add = str_replace($cimg_tag, $thum_image . $hidden_thumb_image, $data_add); + + // More documents + if (strstr($data_add, "{more_documents}")) { + $media_documents = RedshopHelperMedia::getAdditionMediaImage( + $this->search[$i]->product_id, + "product", + "document" + ); + $more_doc = ''; + + for ($m = 0, $countMedia = count($media_documents); $m < $countMedia; $m++) { + $alttext = RedshopHelperMedia::getAlternativeText( + "product", + $media_documents[$m]->section_id, + "", + $media_documents[$m]->media_id, + "document" + ); + + if (!$alttext) { + $alttext = $media_documents[$m]->media_name; + } + + if (JFile::exists( + REDSHOP_FRONT_DOCUMENT_RELPATH . "product/" . $media_documents[$m]->media_name + )) { + $downlink = JURI::root( + ) . 'index.php?tmpl=component&option=com_redshop&view=product&pid=' . $this->search[$i]->product_id . '&task=downloadDocument&fname=' . $media_documents[$m]->media_name . '&Itemid=' . $Itemid; + $more_doc .= ""; + } + } + + $data_add = str_replace( + "{more_documents}", + "" . $more_doc . "", + $data_add + ); + } + + // More documents end + + /************************************************ user fields*******************************************************/ + $hidden_userfield = ""; + $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($data_add); + $template_userfield = $returnArr[0]; + $userfieldArr = $returnArr[1]; + $count_no_user_field = 0; + + if ($template_userfield != "") { + $ufield = ""; + + for ($ui = 0, $countUserField = count($userfieldArr); $ui < $countUserField; $ui++) { + $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields( + $userfieldArr[$ui], + 12, + '', + '', + 0, + $this->search[$i]->product_id + ); + $ufield .= $productUserFields[1]; + + if ($productUserFields[1] != "") { + $count_no_user_field++; + } + + $data_add = str_replace('{' . $userfieldArr[$ui] . '_lbl}', $productUserFields[0], $data_add); + $data_add = str_replace('{' . $userfieldArr[$ui] . '}', $productUserFields[1], $data_add); + } + + $productUserFieldsForm = ""; + + if ($ufield != "") { + $data_add = str_replace("{if product_userfield}", $productUserFieldsForm, $data_add); + $data_add = str_replace("{product_userfield end if}", "", $data_add); + } else { + $data_add = str_replace("{if product_userfield}", "", $data_add); + $data_add = str_replace("{product_userfield end if}", "", $data_add); + } + } elseif (Redshop::getConfig()->get('AJAX_CART_BOX')) { + $ajax_detail_template_desc = ""; + $ajax_detail_template = \Redshop\Template\Helper::getAjaxDetailBox($this->search[$i]); + + if (null !== $ajax_detail_template) { + $ajax_detail_template_desc = $ajax_detail_template->template_desc; + } + + $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate( + $ajax_detail_template_desc + ); + $template_userfield = $returnArr[0]; + $userfieldArr = $returnArr[1]; + + if ($template_userfield != "") { + $ufield = ""; + + for ($ui = 0, $countUserField = count($userfieldArr); $ui < $countUserField; $ui++) { + $productUserFields = Redshop\Fields\SiteHelper::listAllUserFields( + $userfieldArr[$ui], + 12, + '', + '', + 0, + $this->search[$i]->product_id + ); + $ufield .= $productUserFields[1]; + + if ($productUserFields[1] != "") { + $count_no_user_field++; + } + + $template_userfield = str_replace( + '{' . $userfieldArr[$ui] . '_lbl}', + $productUserFields[0], + $template_userfield + ); + $template_userfield = str_replace( + '{' . $userfieldArr[$ui] . '}', + $productUserFields[1], + $template_userfield + ); + } + + if ($ufield != "") { + $hidden_userfield = "
    " . $template_userfield . "
    "; + } + } + } + + $data_add = $data_add . $hidden_userfield; + + /*************** end user fields ***************/ + + // ProductFinderDatepicker Extra Field Start + + $data_add = RedshopHelperProduct::getProductFinderDatepickerValue( + $data_add, + $this->search[$i]->product_id, + $fieldArray + ); + + // ProductFinderDatepicker Extra Field End + + /* + * manufacturer data + */ + $manufacturer_id = $this->search[$i]->id; + + if ($manufacturer_id != 0) { + $manufacturer_link_href = JRoute::_( + 'index.php?option=com_redshop&view=manufacturers&layout=detail&mid=' . $manufacturer_id . '&Itemid=' . $Itemid + ); + $manufacturer_name = $this->search[$i]->name; + $manufacturer_link = '' . $manufacturer_name . ''; + + if (strstr($data_add, "{manufacturer_link}")) { + $data_add = str_replace("{manufacturer_name}", "", $data_add); + } else { + $data_add = str_replace("{manufacturer_name}", $manufacturer_name, $data_add); + } + + $data_add = str_replace("{manufacturer_link}", $manufacturer_link, $data_add); + } else { + $data_add = str_replace("{manufacturer_link}", "", $data_add); + $data_add = str_replace("{manufacturer_name}", "", $data_add); + } + + // End + + // Replace wishlistbutton + $data_add = RedshopHelperWishlist::replaceWishlistTag($this->search[$i]->product_id, $data_add); + + // Replace compare product button + $data_add = Redshop\Product\Compare::replaceCompareProductsButton( + $this->search[$i]->product_id, + 0, + $data_add + ); + + // Checking for child products + if ($this->search[$i]->count_child_products > 0) { + $isChilds = true; + $attributes = array(); + } else { + $isChilds = false; + + // Get attributes + $attributes_set = array(); + + if ($this->search[$i]->attribute_set_id > 0) { + $attributes_set = \Redshop\Product\Attribute::getProductAttribute( + 0, + $this->search[$i]->attribute_set_id, + 0, + 1 + ); + } + + $attributes = \Redshop\Product\Attribute::getProductAttribute($this->search[$i]->product_id); + $attributes = array_merge($attributes, $attributes_set); + } + + // Product attribute Start + $totalatt = count($attributes); + + // Check product for not for sale + $data_add = RedshopHelperProduct::getProductNotForSaleComment( + $this->search[$i], + $data_add, + $attributes + ); + + $data_add = Redshop\Product\Stock::replaceInStock( + $this->search[$i]->product_id, + $data_add, + $attributes, + $attribute_template + ); + + $data_add = RedshopHelperAttribute::replaceAttributeData( + $this->search[$i]->product_id, + 0, + 0, + $attributes, + $data_add, + $attribute_template, + $isChilds + ); + + // Cart Template + $data_add = Redshop\Cart\Render::replace( + $this->search[$i]->product_id, + 0, + 0, + 0, + $data_add, + $isChilds, + $userfieldArr, + $totalatt, + $this->search[$i]->total_accessories, + $count_no_user_field + ); + + $data_add = RedshopHelperProductTag::getExtraSectionTag( + $extraFieldName, + $this->search[$i]->product_id, + "1", + $data_add + ); + + $productAvailabilityDate = strstr($data_add, "{product_availability_date}"); + $stockNotifyFlag = strstr($data_add, "{stock_notify_flag}"); + $stockStatus = strstr($data_add, "{stock_status"); + + $attributeproductStockStatus = array(); + + if ($productAvailabilityDate || $stockNotifyFlag || $stockStatus) { + $attributeproductStockStatus = RedshopHelperProduct::getproductStockStatus( + $this->search[$i]->product_id, + $totalatt + ); + } + + $data_add = \Redshop\Helper\Stockroom::replaceProductStockData( + $this->search[$i]->product_id, + 0, + 0, + $data_add, + $attributeproductStockStatus + ); + + $dispatcher->trigger('onAfterDisplayProduct', array(&$data_add, array(), $this->search[$i])); + + $data .= $data_add; + } + + $app = JFactory::getApplication(); + $router = $app->getRouter(); + + $getorderby = $app->input->get('order_by', Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD')); + + $vars = array( + 'option' => 'com_redshop', + 'view' => 'search', + 'layout' => $layout, + 'keyword' => $keyword, + 'manufacture_id' => $manufacture_id, + 'order_by' => $getorderby, + 'category_id' => $cid, + 'Itemid' => $Itemid, + 'search_type' => $search_type + ); + $router->setVars($vars); + unset($vars); + + if (strstr($template_org, "{show_all_products_in_category}")) { + $template_org = str_replace("{show_all_products_in_category}", "", $template_org); + $template_org = str_replace("{pagination}", "", $template_org); + } + + $pagination = new JPagination($total_product, $start, $endlimit); + + if (strstr($template_org, "{pagination}")) { + $template_org = str_replace("{pagination}", $pagination->getPagesLinks(), $template_org); + } + + $usePerPageLimit = false; + + if (strstr($template_org, "perpagelimit:")) { + $usePerPageLimit = true; + $perpage = explode('{perpagelimit:', $template_org); + $perpage = explode('}', $perpage[1]); + $template_org = str_replace("{perpagelimit:" . intval($perpage[0]) . "}", "", $template_org); + } + + if (strstr($template_org, "{product_display_limit}")) { + if ($usePerPageLimit) { + $limitBox = ''; + } else { + $limitBox = "
    " - . $pagination->getLimitBox() . "
    "; - } - - $template_org = str_replace("{product_display_limit}", $limitBox, $template_org); - } - - $template_org = str_replace("{order_by}", $orderby_form, $template_org); - $template_org = str_replace("{order_by_lbl}", JText::_('COM_REDSHOP_SELECT_ORDER_BY'), $template_org); - $template_org = str_replace("{filter_by_lbl}", JText::_('COM_REDSHOP_SELECT_FILTER_BY'), $template_org); - $template_org = str_replace("{attribute_price_with_vat}", "", $template_org); - $template_org = str_replace("{attribute_price_without_vat}", "", $template_org); - $template_org = str_replace("{product_loop_start}", "", $template_org); - $template_org = str_replace("{product_loop_end}", "", $template_org); - $template_org = str_replace($template_tmp_desc, $data, $template_org); - - $template_org = str_replace("{with_vat}", "", $template_org); - $template_org = str_replace("{without_vat}", "", $template_org); - - $template_org = RedshopHelperTemplate::parseRedshopPlugin($template_org); - $template_org = RedshopHelperText::replaceTexts($template_org); - - eval("?>" . $template_org . "

    " . JText::_('COM_REDSHOP_MSG_SORRY_NO_RESULT_FOUND') . "

    "; - } - } + . $pagination->getLimitBox() . ""; + } + + $template_org = str_replace("{product_display_limit}", $limitBox, $template_org); + } + + $template_org = str_replace("{order_by}", $orderby_form, $template_org); + $template_org = str_replace("{order_by_lbl}", JText::_('COM_REDSHOP_SELECT_ORDER_BY'), $template_org); + $template_org = str_replace("{filter_by_lbl}", JText::_('COM_REDSHOP_SELECT_FILTER_BY'), $template_org); + $template_org = str_replace("{attribute_price_with_vat}", "", $template_org); + $template_org = str_replace("{attribute_price_without_vat}", "", $template_org); + $template_org = str_replace("{product_loop_start}", "", $template_org); + $template_org = str_replace("{product_loop_end}", "", $template_org); + $template_org = str_replace($template_tmp_desc, $data, $template_org); + + $template_org = str_replace("{with_vat}", "", $template_org); + $template_org = str_replace("{without_vat}", "", $template_org); + + $template_org = RedshopHelperTemplate::parseRedshopPlugin($template_org); + $template_org = RedshopHelperText::replaceTexts($template_org); + + eval("?>" . $template_org . "

    " . JText::_('COM_REDSHOP_MSG_SORRY_NO_RESULT_FOUND') . "

    "; + } + } } diff --git a/component/site/views/send_friend/tmpl/default.php b/component/site/views/send_friend/tmpl/default.php index e10b5ce9ab8..2f854abb7eb 100644 --- a/component/site/views/send_friend/tmpl/default.php +++ b/component/site/views/send_friend/tmpl/default.php @@ -18,9 +18,9 @@ - - + get('WISHLIST_LIST')) : ?> + document.getElementsByName('checkall-toggle')[0].click(); + submitform(); + + + +
    diff --git a/component/site/views/wishlist/tmpl/viewloginwishlist.php b/component/site/views/wishlist/tmpl/viewloginwishlist.php index a20877b7c1b..7eb610886f7 100644 --- a/component/site/views/wishlist/tmpl/viewloginwishlist.php +++ b/component/site/views/wishlist/tmpl/viewloginwishlist.php @@ -11,74 +11,75 @@ JHTML::_('behavior.modal'); -$app = JFactory::getApplication(); -$config = Redconfiguration::getInstance(); +$app = JFactory::getApplication(); +$config = Redconfiguration::getInstance(); -$uri = JURI::getInstance(); -$url = $uri->root(); -$Itemid = $app->input->getInt('Itemid'); -$wishlists = $this->wishlists; +$uri = JURI::getInstance(); +$url = $uri->root(); +$Itemid = $app->input->getInt('Itemid'); +$wishlists = $this->wishlists; $productId = $app->input->getInt('product_id'); -$user = JFactory::getUser(); -$session = JFactory::getSession(); -$auth = $session->get('auth'); +$user = JFactory::getUser(); +$session = JFactory::getSession(); +$auth = $session->get('auth'); ?> -
    - + -
    + $pagetitle = JText::_('COM_REDSHOP_LOGIN_NEWWISHLIST'); + ?> +
    -

    - -

    +

    + +

    -
     
    +
     
    -
    +
    -
    - id || (isset($auth['users_info_id']) && $auth['users_info_id'] > 0)) - { - $wishreturn = JRoute::_('index.php?loginwishlist=1&option=com_redshop&view=wishlist&Itemid=' . $Itemid, false); - $app->redirect($wishreturn); - } - else - { - $pagetitle = JText::_('COM_REDSHOP_LOGIN_PROMPTWISHLIST'); - ?> -
    +
    +id || (isset($auth['users_info_id']) && $auth['users_info_id'] > 0)) { + $wishreturn = JRoute::_('index.php?loginwishlist=1&option=com_redshop&view=wishlist&Itemid=' . $Itemid, false); + $app->redirect($wishreturn); +} else { + $pagetitle = JText::_('COM_REDSHOP_LOGIN_PROMPTWISHLIST'); + ?> +
    -

    - -

    +

    + +

    -
     
    +
     
    -
    - - - - - - -
    -   - -
    - - - + + + + + + + +
    +   + +
    + + + - - -
    -
    - + + +
    + input->getInt('Itemid'); +$url = JURI::base(); +$Itemid = $app->input->getInt('Itemid'); $wishlists = $this->wishlists; $productId = $app->input->getInt('product_id'); -$user = JFactory::getUser(); +$user = JFactory::getUser(); $pagetitle = JText::_('COM_REDSHOP_MY_WISHLIST'); -$redTemplate = Redtemplate::getInstance(); -$template = RedshopHelperTemplate::getTemplate("wishlist_template"); -$wishlistData = $template[0]->template_desc; -$returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($wishlistData); +$redTemplate = Redtemplate::getInstance(); +$template = RedshopHelperTemplate::getTemplate("wishlist_template"); +$wishlistData = $template[0]->template_desc; +$returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($wishlistData); $templateUserField = $returnArr[0]; -$userfieldArr = $returnArr[1]; +$userfieldArr = $returnArr[1]; if ($this->params->get('show_page_heading', 1)) { ?> -

    +

     
    $user, - 'wishlists' => $wishlists, + 'user' => $user, + 'wishlists' => $wishlists, 'wishlistSesion' => $this->wish_session, - 'userFieldArr' => $userfieldArr + 'userFieldArr' => $userfieldArr ) ); diff --git a/component/site/views/wishlist/view.html.php b/component/site/views/wishlist/view.html.php index 5a033a38cb0..d934e26eb65 100644 --- a/component/site/views/wishlist/view.html.php +++ b/component/site/views/wishlist/view.html.php @@ -19,39 +19,34 @@ */ class RedshopViewWishlist extends RedshopView { - /** - * @param string $tpl Template layout - * - * @since 1.0.0 - */ - public function display($tpl = null) - { - $app = JFactory::getApplication(); + /** + * @param string $tpl Template layout + * + * @since 1.0.0 + */ + public function display($tpl = null) + { + $app = JFactory::getApplication(); - // Request variables - $task = $app->input->getCmd('task', 'com_redshop'); - $layout = $app->input->getCmd('layout'); + // Request variables + $task = $app->input->getCmd('task', 'com_redshop'); + $layout = $app->input->getCmd('layout'); - $model = $this->getModel("wishlist"); + $model = $this->getModel("wishlist"); - $this->params = $app->getParams('com_redshop'); - $this->wishlists = $model->getUserWishlist(); + $this->params = $app->getParams('com_redshop'); + $this->wishlists = $model->getUserWishlist(); - if ($task == 'viewwishlist' || $layout == 'viewwishlist') - { - $this->setlayout('viewwishlist'); - $this->wish_products = $model->getWishlistProduct(); - $this->wish_session = $model->getWishlistProductFromSession(); - } - elseif ($task == 'viewloginwishlist') - { - $this->setlayout('viewloginwishlist'); - } - else - { - $this->wish_session = $model->getWishlistProductFromSession(); - } + if ($task == 'viewwishlist' || $layout == 'viewwishlist') { + $this->setlayout('viewwishlist'); + $this->wish_products = $model->getWishlistProduct(); + $this->wish_session = $model->getWishlistProductFromSession(); + } elseif ($task == 'viewloginwishlist') { + $this->setlayout('viewloginwishlist'); + } else { + $this->wish_session = $model->getWishlistProductFromSession(); + } - parent::display($tpl); - } + parent::display($tpl); + } } diff --git a/composer.json b/composer.json index 349afbd4668..6d9ad82abb4 100644 --- a/composer.json +++ b/composer.json @@ -1,40 +1,40 @@ { - "name" : "redcomponent-com/redshop", - "description": "a Joomla e-commerce solution", - "license" : "GPL-2.0+", - "minimum-stability": "stable", - "require" : { - "php": ">=7.0", - "phpmd/phpmd": "^2.6", - "joomla/joomla-cms": "3.7.5" - }, - "require-dev": { - "twig/twig": "2.12.3", - "squizlabs/php_codesniffer": "~2", - "codeception/codeception": "2.3.7", - "joomla-projects/joomla-browser": "v3.9.0", - "consolidation/robo": "~1", - "joomla-projects/joomla-testing-robo": "dev-container-test", - "joomla-projects/joomla-testing": "dev-container-test", - "fzaninotto/faker": "^1.5", - "cloudinary/cloudinary_php": "^1.7", - "knplabs/github-api": "~1", - "joomla-projects/selenium-server-standalone": "3.8.1", - "nette/reflection": "~2.4", - "phpunit/phpunit": "~4.0" - }, - "repositories": [ - { - "type": "package", - "package": { - "name": "joomla/joomla-cms", - "version": "3.7.5", - "source": { - "url": "https://github.com/joomla/joomla-cms.git", - "type": "git", - "reference": "3.7.5" - } - } + "name": "redcomponent-com/redshop", + "description": "a Joomla e-commerce solution", + "license": "GPL-2.0+", + "minimum-stability": "stable", + "require": { + "php": ">=7.0", + "phpmd/phpmd": "^2.6", + "joomla/joomla-cms": "3.7.5" + }, + "require-dev": { + "twig/twig": "2.12.3", + "squizlabs/php_codesniffer": "~2", + "codeception/codeception": "2.3.7", + "joomla-projects/joomla-browser": "v3.9.0", + "consolidation/robo": "~1", + "joomla-projects/joomla-testing-robo": "dev-container-test", + "joomla-projects/joomla-testing": "dev-container-test", + "fzaninotto/faker": "^1.5", + "cloudinary/cloudinary_php": "^1.7", + "knplabs/github-api": "~1", + "joomla-projects/selenium-server-standalone": "3.8.1", + "nette/reflection": "~2.4", + "phpunit/phpunit": "~4.0" + }, + "repositories": [ + { + "type": "package", + "package": { + "name": "joomla/joomla-cms", + "version": "3.7.5", + "source": { + "url": "https://github.com/joomla/joomla-cms.git", + "type": "git", + "reference": "3.7.5" } - ] + } + } + ] } \ No newline at end of file diff --git a/gulp-config.sample.json b/gulp-config.sample.json index 54aa5a91e8f..d1d8d67f345 100644 --- a/gulp-config.sample.json +++ b/gulp-config.sample.json @@ -1,11 +1,11 @@ { - "wwwDir" : "/home/travis/build/redCOMPONENT-COM/redSHOP/tests/joomla-cms", - "browserConfig" : { - "proxy" : "redshop.local" - }, - "releaseDir" : "./tests/releases/", - "basePaths": { - "plugins" : "./plugins", - "modules" : "./modules" - } + "wwwDir": "/home/travis/build/redCOMPONENT-COM/redSHOP/tests/joomla-cms", + "browserConfig": { + "proxy": "redshop.local" + }, + "releaseDir": "./tests/releases/", + "basePaths": { + "plugins": "./plugins", + "modules": "./modules" + } } \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js index 074cb9c41a2..9eef75a5183 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -18,8 +18,8 @@ global.config = require("./gulp-config.json"); global.getFolders = function getFolders(dir) { return fs.readdirSync(dir) .filter(function (file) { - return fs.statSync(path.join(dir, file)).isDirectory(); - } + return fs.statSync(path.join(dir, file)).isDirectory(); + } ); } @@ -101,7 +101,7 @@ global.getGlobExtensionPattern = function getGlobExtensionPattern(extensionType, */ global.executeComposer = function executeComposer(composerPath) { log("Composer found: ", colors.blue(composerPath)); - composer({ cwd: composerPath, bin: 'php ./composer.phar' }); + composer({cwd: composerPath, bin: 'php ./composer.phar'}); } gulp.task("composer", function (cb) { @@ -112,12 +112,12 @@ gulp.task("composer", function (cb) { // Make sure this is not composer.json inside vendor library if (composerPath.indexOf("vendor") == -1 && composerPath != '.') { log("Composer found: ", colors.blue(composerPath)); - composer({ cwd: composerPath, bin: 'php ./composer.phar' }).on('end', cb); + composer({cwd: composerPath, bin: 'php ./composer.phar'}).on('end', cb); } } }); }); -var jgulp = requireDir("./redGulp/extensions", { recurse: true }); -var gulpSrc = requireDir("./redGulp/tasks", { recurse: true }); -var gulpSrc = requireDir("./redGulp/src", { recurse: true }); \ No newline at end of file +var jgulp = requireDir("./redGulp/extensions", {recurse: true}); +var gulpSrc = requireDir("./redGulp/tasks", {recurse: true}); +var gulpSrc = requireDir("./redGulp/src", {recurse: true}); \ No newline at end of file diff --git a/install.php b/install.php index c2930ffbde7..acb3fe1e1ab 100644 --- a/install.php +++ b/install.php @@ -17,572 +17,586 @@ */ class Com_RedshopInstallerScript { - /** - * Status of the installation - * - * @var object - */ - public $status = null; - - /** - * The common JInstaller instance used to install all the extensions - * - * @var object - */ - public $installer = null; - - /** - * Install type - * - * @var string - */ - protected $type = null; - - /** - * Method to install the component - * - * @param object $parent Class calling this method - * - * @return void - */ - public function install($parent) - { - // Install extensions - $this->installLibraries($parent); - $this->installModules($parent); - $this->installPlugins($parent); - } - - /** - * method to run after an install/update/uninstall method - * - * @param string $type Type of method - * @param object $parent Parent class call this method - * - * @return void - * - * @since 2.0.0 - * - * @throws Exception - */ - public function postflight($type, $parent) - { - // Respond json for ajax request and redirect with standard request - if( - isset($_SERVER['HTTP_X_REQUESTED_WITH']) && - strcasecmp($_SERVER['HTTP_X_REQUESTED_WITH'], 'xmlhttprequest') == 0 - ){ - - $response = new JResponseJson(array('redirect' =>'index.php?option=com_redshop&view=install&install_type=' . $type)); - - header('Content-type: application/json'); - echo $response; - - JFactory::getApplication()->close(); - } - - JFactory::getApplication()->redirect('index.php?option=com_redshop&view=install&install_type=' . $type); - } - - /** - * method to uninstall the component - * - * @param object $parent Class calling this method - * - * @return void - */ - public function uninstall($parent) - { - // Uninstall extensions - $this->uninstallPlugins($parent); - $this->uninstallModules($parent); - $this->uninstallLibraries($parent); - } - - /** - * Method to update the component - * - * @param object $parent Class calling this method - * - * @return void - */ - public function update($parent) - { - $this->installLibraries($parent); - $this->installModules($parent); - $this->installPlugins($parent); - } - - /** - * method to run before an install/update/uninstall method - * - * @param object $type Type of change (install, update or discover_install) - * @param object $parent Class calling this method - * - * @return void - * - * @throws Exception - */ - public function preflight($type, $parent) - { - $this->type = $type; - - $this->implementProcedure(); - - if ($type == 'update' || $type == 'discover_install') - { - if (!class_exists('RedshopHelperJoomla')) - { - require_once __DIR__ . '/libraries/redshop/helper/joomla.php'; - } - - // Store redSHOP old version. - JFactory::getApplication()->setUserState('redshop.old_version', RedshopHelperJoomla::getManifestValue('version')); - } - } - - /** - * Get the common JInstaller instance used to install all the extensions - * - * @return JInstaller The JInstaller object - */ - public function getInstaller() - { - $this->installer = new JInstaller; - - return $this->installer; - } - - /** - * Install the package libraries - * - * @param object $parent Class calling this method - * - * @return void - */ - protected function installLibraries($parent) - { - // Required objects - $manifest = $parent->get('manifest'); - $src = $parent->getParent()->getPath('source'); - - if ($nodes = $manifest->libraries->library) - { - $installer = $this->getInstaller(); - - foreach ($nodes as $node) - { - $extName = $node->attributes()->name; - $extPath = $src . '/libraries/' . $extName; - - // Standard install - if (is_dir($extPath)) - { - $installer->install($extPath); - } - // Discover install - elseif ($extId = $this->searchExtension($extName, 'library', '-1')) - { - $installer->discover_install($extId); - } - } - } - } - - /** - * Install the package modules - * - * @param object $parent Class calling this method - * - * @return void - */ - protected function installModules($parent) - { - // Required objects - $manifest = $parent->get('manifest'); - $src = $parent->getParent()->getPath('source'); - - if ($nodes = $manifest->modules->module) - { - foreach ($nodes as $node) - { - $extName = (string) $node->attributes()->name; - $extClient = (string) $node->attributes()->client; - $extPath = $src . '/modules/' . $extClient . '/' . $extName; - - if (is_dir($extPath)) - { - $this->getInstaller()->install($extPath); - } - // Discover install - elseif ($extId = $this->searchExtension($extName, 'module', '-1')) - { - $this->getInstaller()->discover_install($extId); - } - } - } - } - - /** - * Install the package libraries - * - * @param object $parent Class calling this method - * - * @return void - */ - protected function installPlugins($parent) - { - // Required objects - $manifest = $parent->get('manifest'); - $src = $parent->getParent()->getPath('source'); - - if ($nodes = $manifest->plugins->plugin) - { - $installer = $this->getInstaller(); - - foreach ($nodes as $node) - { - $extName = (string) $node->attributes()->name; - $extGroup = (string) $node->attributes()->group; - $extPath = $src . '/plugins/' . $extGroup . '/' . $extName; - $result = 0; - - // Install or upgrade plugin - if (is_dir($extPath)) - { - $installer->setAdapter('plugin'); - $result = $installer->install($extPath); - } - // Discover install - elseif ($extId = $this->searchExtension($extName, 'plugin', '-1', $extGroup)) - { - $result = $installer->discover_install($extId); - } - - // We'll not enable plugin for update case - if ($this->type != 'update' && $result) - { - /* - * For another rest type cases - * Do not change plugin state if it's installed - * If plugin is installed successfully and it didn't exist before we enable it. - */ - $this->enablePlugin($extName, $extGroup); - } - - // Force to enable redSHOP - System plugin by anyways - $this->enablePlugin('redshop', 'system'); - - // Force to enable redSHOP PDF - TcPDF plugin by anyways - $this->enablePlugin('tcpdf', 'redshop_pdf'); - - // Force to enable redSHOP Export - Attribute plugin by anyways - $this->enablePlugin('attribute', 'redshop_export'); - - // Force to enable redSHOP Export - Category plugin by anyways - $this->enablePlugin('category', 'redshop_export'); - - // Force to enable redSHOP Export - Field plugin by anyways - $this->enablePlugin('field', 'redshop_export'); - - // Force to enable redSHOP Export - Manufacturer plugin by anyways - $this->enablePlugin('manufacturer', 'redshop_export'); - - // Force to enable redSHOP Export - Newsletter Subscriber plugin by anyways - $this->enablePlugin('newsletter_subscriber', 'redshop_export'); - - // Force to enable redSHOP Export - Product plugin by anyways - $this->enablePlugin('product', 'redshop_export'); - - // Force to enable redSHOP Export - Product Stockroom Data plugin by anyways - $this->enablePlugin('product_stockroom_data', 'redshop_export'); + /** + * Status of the installation + * + * @var object + */ + public $status = null; + + /** + * The common JInstaller instance used to install all the extensions + * + * @var object + */ + public $installer = null; + + /** + * Install type + * + * @var string + */ + protected $type = null; + + /** + * Method to install the component + * + * @param object $parent Class calling this method + * + * @return void + */ + public function install($parent) + { + // Install extensions + $this->installLibraries($parent); + $this->installModules($parent); + $this->installPlugins($parent); + } + + /** + * Install the package libraries + * + * @param object $parent Class calling this method + * + * @return void + */ + protected function installLibraries($parent) + { + // Required objects + $manifest = $parent->get('manifest'); + $src = $parent->getParent()->getPath('source'); + + if ($nodes = $manifest->libraries->library) { + $installer = $this->getInstaller(); + + foreach ($nodes as $node) { + $extName = $node->attributes()->name; + $extPath = $src . '/libraries/' . $extName; + + // Standard install + if (is_dir($extPath)) { + $installer->install($extPath); + } // Discover install + elseif ($extId = $this->searchExtension($extName, 'library', '-1')) { + $installer->discover_install($extId); + } + } + } + } + + /** + * Get the common JInstaller instance used to install all the extensions + * + * @return JInstaller The JInstaller object + */ + public function getInstaller() + { + $this->installer = new JInstaller; + + return $this->installer; + } + + /** + * Search a extension in the database + * + * @param string $element Extension technical name/alias + * @param string $type Type of extension (component, file, language, library, module, plugin) + * @param string $state State of the searched extension + * @param string $folder Folder name used mainly in plugins + * + * @return integer Extension identifier + */ + protected function searchExtension($element, $type, $state = null, $folder = null) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('extension_id') + ->from($db->quoteName("#__extensions")) + ->where("type = " . $db->quote($type)) + ->where("element = " . $db->quote($element)); + + if (!is_null($state)) { + $query->where("state = " . (int)$state); + } + + if (!is_null($folder)) { + $query->where("folder = " . $db->quote($folder)); + } + + $db->setQuery($query); + + return $db->loadResult(); + } + + /** + * Install the package modules + * + * @param object $parent Class calling this method + * + * @return void + */ + protected function installModules($parent) + { + // Required objects + $manifest = $parent->get('manifest'); + $src = $parent->getParent()->getPath('source'); + + if ($nodes = $manifest->modules->module) { + foreach ($nodes as $node) { + $extName = (string)$node->attributes()->name; + $extClient = (string)$node->attributes()->client; + $extPath = $src . '/modules/' . $extClient . '/' . $extName; + + if (is_dir($extPath)) { + $this->getInstaller()->install($extPath); + } // Discover install + elseif ($extId = $this->searchExtension($extName, 'module', '-1')) { + $this->getInstaller()->discover_install($extId); + } + } + } + } + + /** + * Install the package libraries + * + * @param object $parent Class calling this method + * + * @return void + */ + protected function installPlugins($parent) + { + // Required objects + $manifest = $parent->get('manifest'); + $src = $parent->getParent()->getPath('source'); + + if ($nodes = $manifest->plugins->plugin) { + $installer = $this->getInstaller(); + + foreach ($nodes as $node) { + $extName = (string)$node->attributes()->name; + $extGroup = (string)$node->attributes()->group; + $extPath = $src . '/plugins/' . $extGroup . '/' . $extName; + $result = 0; + + // Install or upgrade plugin + if (is_dir($extPath)) { + $installer->setAdapter('plugin'); + $result = $installer->install($extPath); + } // Discover install + elseif ($extId = $this->searchExtension($extName, 'plugin', '-1', $extGroup)) { + $result = $installer->discover_install($extId); + } + + // We'll not enable plugin for update case + if ($this->type != 'update' && $result) { + /* + * For another rest type cases + * Do not change plugin state if it's installed + * If plugin is installed successfully and it didn't exist before we enable it. + */ + $this->enablePlugin($extName, $extGroup); + } + + // Force to enable redSHOP - System plugin by anyways + $this->enablePlugin('redshop', 'system'); + + // Force to enable redSHOP PDF - TcPDF plugin by anyways + $this->enablePlugin('tcpdf', 'redshop_pdf'); + + // Force to enable redSHOP Export - Attribute plugin by anyways + $this->enablePlugin('attribute', 'redshop_export'); + + // Force to enable redSHOP Export - Category plugin by anyways + $this->enablePlugin('category', 'redshop_export'); - // Force to enable redSHOP Export - Related Product plugin by anyways - $this->enablePlugin('related_product', 'redshop_export'); + // Force to enable redSHOP Export - Field plugin by anyways + $this->enablePlugin('field', 'redshop_export'); - // Force to enable redSHOP Export - Shipping Address plugin by anyways - $this->enablePlugin('shipping_address', 'redshop_export'); + // Force to enable redSHOP Export - Manufacturer plugin by anyways + $this->enablePlugin('manufacturer', 'redshop_export'); - // Force to enable redSHOP Export - Shopper Group Attribute Price plugin by anyways - $this->enablePlugin('shopper_group_attribute_price', 'redshop_export'); + // Force to enable redSHOP Export - Newsletter Subscriber plugin by anyways + $this->enablePlugin('newsletter_subscriber', 'redshop_export'); - // Force to enable redSHOP Export - Shopper Group Product Price plugin by anyways - $this->enablePlugin('shopper_group_product_price', 'redshop_export'); + // Force to enable redSHOP Export - Product plugin by anyways + $this->enablePlugin('product', 'redshop_export'); - // Force to enable redSHOP Export - User plugin by anyways - $this->enablePlugin('user', 'redshop_export'); + // Force to enable redSHOP Export - Product Stockroom Data plugin by anyways + $this->enablePlugin('product_stockroom_data', 'redshop_export'); - // Force to enable redSHOP Import - Attribute plugin by anyways - $this->enablePlugin('attribute', 'redshop_import'); + // Force to enable redSHOP Export - Related Product plugin by anyways + $this->enablePlugin('related_product', 'redshop_export'); - // Force to enable redSHOP Import - Category plugin by anyways - $this->enablePlugin('category', 'redshop_import'); + // Force to enable redSHOP Export - Shipping Address plugin by anyways + $this->enablePlugin('shipping_address', 'redshop_export'); - // Force to enable redSHOP Import - Field plugin by anyways - $this->enablePlugin('field', 'redshop_import'); + // Force to enable redSHOP Export - Shopper Group Attribute Price plugin by anyways + $this->enablePlugin('shopper_group_attribute_price', 'redshop_export'); - // Force to enable redSHOP Import - Manufacturer plugin by anyways - $this->enablePlugin('manufacturer', 'redshop_import'); + // Force to enable redSHOP Export - Shopper Group Product Price plugin by anyways + $this->enablePlugin('shopper_group_product_price', 'redshop_export'); - // Force to enable redSHOP Import - Newsletter Subscriber plugin by anyways - $this->enablePlugin('newsletter_subscriber', 'redshop_import'); + // Force to enable redSHOP Export - User plugin by anyways + $this->enablePlugin('user', 'redshop_export'); - // Force to enable redSHOP Import - Product plugin by anyways - $this->enablePlugin('product', 'redshop_import'); + // Force to enable redSHOP Import - Attribute plugin by anyways + $this->enablePlugin('attribute', 'redshop_import'); - // Force to enable redSHOP Import - Product Stockroom Data plugin by anyways - $this->enablePlugin('product_stockroom_data', 'redshop_import'); + // Force to enable redSHOP Import - Category plugin by anyways + $this->enablePlugin('category', 'redshop_import'); - // Force to enable redSHOP Import - Related Product plugin by anyways - $this->enablePlugin('related_product', 'redshop_import'); + // Force to enable redSHOP Import - Field plugin by anyways + $this->enablePlugin('field', 'redshop_import'); - // Force to enable redSHOP Import - Shipping Address plugin by anyways - $this->enablePlugin('shipping_address', 'redshop_import'); + // Force to enable redSHOP Import - Manufacturer plugin by anyways + $this->enablePlugin('manufacturer', 'redshop_import'); - // Force to enable redSHOP Import - Shopper Group Attribute Price plugin by anyways - $this->enablePlugin('shopper_group_attribute_price', 'redshop_import'); + // Force to enable redSHOP Import - Newsletter Subscriber plugin by anyways + $this->enablePlugin('newsletter_subscriber', 'redshop_import'); - // Force to enable redSHOP Import - Shopper Group Product Price plugin by anyways - $this->enablePlugin('shopper_group_product_price', 'redshop_import'); + // Force to enable redSHOP Import - Product plugin by anyways + $this->enablePlugin('product', 'redshop_import'); - // Force to enable redSHOP Import - User plugin by anyways - $this->enablePlugin('user', 'redshop_import'); + // Force to enable redSHOP Import - Product Stockroom Data plugin by anyways + $this->enablePlugin('product_stockroom_data', 'redshop_import'); - // Force to enable cache - twig plugin by anyways - $this->enablePlugin('cache', 'twig'); + // Force to enable redSHOP Import - Related Product plugin by anyways + $this->enablePlugin('related_product', 'redshop_import'); - // Force to enable debug - twig plugin by anyways - $this->enablePlugin('debug', 'twig'); + // Force to enable redSHOP Import - Shipping Address plugin by anyways + $this->enablePlugin('shipping_address', 'redshop_import'); - // Force to enable japp - twig plugin by anyways - $this->enablePlugin('japp', 'twig'); + // Force to enable redSHOP Import - Shopper Group Attribute Price plugin by anyways + $this->enablePlugin('shopper_group_attribute_price', 'redshop_import'); - // Force to enable jarray - twig plugin by anyways - $this->enablePlugin('jarray', 'twig'); + // Force to enable redSHOP Import - Shopper Group Product Price plugin by anyways + $this->enablePlugin('shopper_group_product_price', 'redshop_import'); - // Force to enable jdoc - twig plugin by anyways - $this->enablePlugin('jdoc', 'twig'); + // Force to enable redSHOP Import - User plugin by anyways + $this->enablePlugin('user', 'redshop_import'); - // Force to enable jhtml - twig plugin by anyways - $this->enablePlugin('jhtml', 'twig'); + // Force to enable cache - twig plugin by anyways + $this->enablePlugin('cache', 'twig'); - // Force to enable jlang - twig plugin by anyways - $this->enablePlugin('jlang', 'twig'); + // Force to enable debug - twig plugin by anyways + $this->enablePlugin('debug', 'twig'); - // Force to enable jlayout - twig plugin by anyways - $this->enablePlugin('jlayout', 'twig'); + // Force to enable japp - twig plugin by anyways + $this->enablePlugin('japp', 'twig'); - // Force to enable jmodule - twig plugin by anyways - $this->enablePlugin('jmodule', 'twig'); + // Force to enable jarray - twig plugin by anyways + $this->enablePlugin('jarray', 'twig'); - // Force to enable jposition - twig plugin by anyways - $this->enablePlugin('jposition', 'twig'); + // Force to enable jdoc - twig plugin by anyways + $this->enablePlugin('jdoc', 'twig'); - // Force to enable jprofiler - twig plugin by anyways - $this->enablePlugin('jprofiler', 'twig'); - - // Force to enable jregistry - twig plugin by anyways - $this->enablePlugin('jregistry', 'twig'); - - // Force to enable jroute - twig plugin by anyways - $this->enablePlugin('jroute', 'twig'); - - // Force to enable jsession - twig plugin by anyways - $this->enablePlugin('jsession', 'twig'); - - // Force to enable jtext - twig plugin by anyways - $this->enablePlugin('jtext', 'twig'); - - // Force to enable juri - twig plugin by anyways - $this->enablePlugin('juri', 'twig'); - - // Force to enable juser - twig plugin by anyways - $this->enablePlugin('juser', 'twig'); - - // Force to enable redshop - twig plugin by anyways - $this->enablePlugin('redshop', 'twig'); - - // Force to enable unserialize - twig plugin by anyways - $this->enablePlugin('unserialize', 'twig'); - } - } - } - - /** - * Method for enable plugins - * - * @param string $extName Plugin name - * @param string $extGroup Plugin group - * @param int $state State of plugins - * - * @return mixed - */ - protected function enablePlugin($extName, $extGroup, $state = 1) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query->update($db->qn("#__extensions")) - ->set("enabled = " . (int) $state) - ->where('type = ' . $db->quote('plugin')) - ->where('element = ' . $db->quote($extName)) - ->where('folder = ' . $db->quote($extGroup)); - - return $db->setQuery($query)->execute(); - } - - /** - * Uninstall the package libraries - * - * @param object $parent Class calling this method - * - * @return void - */ - protected function uninstallLibraries($parent) - { - // Required objects - $manifest = $parent->get('manifest'); - - if ($nodes = $manifest->libraries->library) - { - foreach ($nodes as $node) - { - $extName = (string) $node->attributes()->name; - - if ($extId = $this->searchExtension($extName, 'library')) - { - $this->getInstaller()->uninstall('library', $extId); - } - } - } - } - - /** - * Uninstall the package modules - * - * @param object $parent Class calling this method - * - * @return void - */ - protected function uninstallModules($parent) - { - // Required objects - $manifest = $parent->get('manifest'); - - if ($nodes = $manifest->modules->module) - { - foreach ($nodes as $node) - { - $extName = (string) $node->attributes()->name; - $extClient = (string) $node->attributes()->client; - - if ($extId = $this->searchExtension($extName, 'module')) - { - $this->getInstaller()->uninstall('module', $extId); - } - } - } - } - - /** - * Uninstall the package plugins - * - * @param object $parent Class calling this method - * - * @return void - */ - protected function uninstallPlugins($parent) - { - // Required objects - $manifest = $parent->get('manifest'); - - if ($nodes = $manifest->plugins->plugin) - { - $installer = $this->getInstaller(); - - foreach ($nodes as $node) - { - $extName = (string) $node->attributes()->name; - $extGroup = (string) $node->attributes()->group; - - if ($extId = $this->searchExtension($extName, 'plugin', null, $extGroup)) - { - $installer->uninstall('plugin', $extId); - } - } - } - } - - /** - * Search a extension in the database - * - * @param string $element Extension technical name/alias - * @param string $type Type of extension (component, file, language, library, module, plugin) - * @param string $state State of the searched extension - * @param string $folder Folder name used mainly in plugins - * - * @return integer Extension identifier - */ - protected function searchExtension($element, $type, $state = null, $folder = null) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('extension_id') - ->from($db->quoteName("#__extensions")) - ->where("type = " . $db->quote($type)) - ->where("element = " . $db->quote($element)); - - if (!is_null($state)) - { - $query->where("state = " . (int) $state); - } - - if (!is_null($folder)) - { - $query->where("folder = " . $db->quote($folder)); - } - - $db->setQuery($query); - - return $db->loadResult(); - } - - /** - * Method for implement procedure function for MySQL server only - * - * @return void - * - * @since 2.1.0 - */ - protected function implementProcedure() - { - $this->procedureRemoveColumn(); - $this->procedureUpdateColumn(); - $this->procedureIndexRemove(); - $this->procedureIndexAdd(); - $this->procedureUniqueIndexAdd(); - $this->procedureFulltextIndexAdd(); - $this->procedureConstraintRemove(); - $this->procedureConstraintUpdate(); - $this->procedurePrimaryRemove(); - $this->procedurePrimaryAdd(); - } - - /** - * Method for implement procedure "redSHOP_Column_Update" - * - * @return void - * - * @since 2.1.0 - */ - protected function procedureUpdateColumn() - { - $db = JFactory::getDbo(); - - $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Column_Update'); - - $db->setQuery($query)->execute(); - - $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Column_Update") . "( + // Force to enable jhtml - twig plugin by anyways + $this->enablePlugin('jhtml', 'twig'); + + // Force to enable jlang - twig plugin by anyways + $this->enablePlugin('jlang', 'twig'); + + // Force to enable jlayout - twig plugin by anyways + $this->enablePlugin('jlayout', 'twig'); + + // Force to enable jmodule - twig plugin by anyways + $this->enablePlugin('jmodule', 'twig'); + + // Force to enable jposition - twig plugin by anyways + $this->enablePlugin('jposition', 'twig'); + + // Force to enable jprofiler - twig plugin by anyways + $this->enablePlugin('jprofiler', 'twig'); + + // Force to enable jregistry - twig plugin by anyways + $this->enablePlugin('jregistry', 'twig'); + + // Force to enable jroute - twig plugin by anyways + $this->enablePlugin('jroute', 'twig'); + + // Force to enable jsession - twig plugin by anyways + $this->enablePlugin('jsession', 'twig'); + + // Force to enable jtext - twig plugin by anyways + $this->enablePlugin('jtext', 'twig'); + + // Force to enable juri - twig plugin by anyways + $this->enablePlugin('juri', 'twig'); + + // Force to enable juser - twig plugin by anyways + $this->enablePlugin('juser', 'twig'); + + // Force to enable redshop - twig plugin by anyways + $this->enablePlugin('redshop', 'twig'); + + // Force to enable unserialize - twig plugin by anyways + $this->enablePlugin('unserialize', 'twig'); + } + } + } + + /** + * Method for enable plugins + * + * @param string $extName Plugin name + * @param string $extGroup Plugin group + * @param int $state State of plugins + * + * @return mixed + */ + protected function enablePlugin($extName, $extGroup, $state = 1) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->update($db->qn("#__extensions")) + ->set("enabled = " . (int)$state) + ->where('type = ' . $db->quote('plugin')) + ->where('element = ' . $db->quote($extName)) + ->where('folder = ' . $db->quote($extGroup)); + + return $db->setQuery($query)->execute(); + } + + /** + * method to run after an install/update/uninstall method + * + * @param string $type Type of method + * @param object $parent Parent class call this method + * + * @return void + * + * @throws Exception + * @since 2.0.0 + * + */ + public function postflight($type, $parent) + { + // Respond json for ajax request and redirect with standard request + if ( + isset($_SERVER['HTTP_X_REQUESTED_WITH']) && + strcasecmp($_SERVER['HTTP_X_REQUESTED_WITH'], 'xmlhttprequest') == 0 + ) { + $response = new JResponseJson( + array('redirect' => 'index.php?option=com_redshop&view=install&install_type=' . $type) + ); + + header('Content-type: application/json'); + echo $response; + + JFactory::getApplication()->close(); + } + + JFactory::getApplication()->redirect('index.php?option=com_redshop&view=install&install_type=' . $type); + } + + /** + * method to uninstall the component + * + * @param object $parent Class calling this method + * + * @return void + */ + public function uninstall($parent) + { + // Uninstall extensions + $this->uninstallPlugins($parent); + $this->uninstallModules($parent); + $this->uninstallLibraries($parent); + } + + /** + * Uninstall the package plugins + * + * @param object $parent Class calling this method + * + * @return void + */ + protected function uninstallPlugins($parent) + { + // Required objects + $manifest = $parent->get('manifest'); + + if ($nodes = $manifest->plugins->plugin) { + $installer = $this->getInstaller(); + + foreach ($nodes as $node) { + $extName = (string)$node->attributes()->name; + $extGroup = (string)$node->attributes()->group; + + if ($extId = $this->searchExtension($extName, 'plugin', null, $extGroup)) { + $installer->uninstall('plugin', $extId); + } + } + } + } + + /** + * Uninstall the package modules + * + * @param object $parent Class calling this method + * + * @return void + */ + protected function uninstallModules($parent) + { + // Required objects + $manifest = $parent->get('manifest'); + + if ($nodes = $manifest->modules->module) { + foreach ($nodes as $node) { + $extName = (string)$node->attributes()->name; + $extClient = (string)$node->attributes()->client; + + if ($extId = $this->searchExtension($extName, 'module')) { + $this->getInstaller()->uninstall('module', $extId); + } + } + } + } + + /** + * Uninstall the package libraries + * + * @param object $parent Class calling this method + * + * @return void + */ + protected function uninstallLibraries($parent) + { + // Required objects + $manifest = $parent->get('manifest'); + + if ($nodes = $manifest->libraries->library) { + foreach ($nodes as $node) { + $extName = (string)$node->attributes()->name; + + if ($extId = $this->searchExtension($extName, 'library')) { + $this->getInstaller()->uninstall('library', $extId); + } + } + } + } + + /** + * Method to update the component + * + * @param object $parent Class calling this method + * + * @return void + */ + public function update($parent) + { + $this->installLibraries($parent); + $this->installModules($parent); + $this->installPlugins($parent); + } + + /** + * method to run before an install/update/uninstall method + * + * @param object $type Type of change (install, update or discover_install) + * @param object $parent Class calling this method + * + * @return void + * + * @throws Exception + */ + public function preflight($type, $parent) + { + $this->type = $type; + + $this->implementProcedure(); + + if ($type == 'update' || $type == 'discover_install') { + if (!class_exists('RedshopHelperJoomla')) { + require_once __DIR__ . '/libraries/redshop/helper/joomla.php'; + } + + // Store redSHOP old version. + JFactory::getApplication()->setUserState( + 'redshop.old_version', + RedshopHelperJoomla::getManifestValue('version') + ); + } + } + + /** + * Method for implement procedure function for MySQL server only + * + * @return void + * + * @since 2.1.0 + */ + protected function implementProcedure() + { + $this->procedureRemoveColumn(); + $this->procedureUpdateColumn(); + $this->procedureIndexRemove(); + $this->procedureIndexAdd(); + $this->procedureUniqueIndexAdd(); + $this->procedureFulltextIndexAdd(); + $this->procedureConstraintRemove(); + $this->procedureConstraintUpdate(); + $this->procedurePrimaryRemove(); + $this->procedurePrimaryAdd(); + } + + /** + * Method for implement procedure "redSHOP_Column_Remove" + * + * @return void + * + * @since 2.1.0 + */ + protected function procedureRemoveColumn() + { + $db = JFactory::getDbo(); + + $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Column_Remove'); + + $db->setQuery($query)->execute(); + + $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Column_Remove") . "( + IN " . $db->qn('tableName') . " VARCHAR(50), + IN " . $db->qn('columnName') . " VARCHAR(50) + ) + LANGUAGE SQL + NOT DETERMINISTIC + CONTAINS SQL + COMMENT " . $db->quote('Procedure for use in redSHOP to remove column to table avoid unexpected errors.') . " + BEGIN + SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + IF ((SELECT COUNT(*) FROM information_schema.COLUMNS WHERE COLUMN_NAME=columnName AND TABLE_NAME=tableName AND table_schema = DATABASE()) >= 1) + THEN + set @StatementToExecute = concat('ALTER TABLE `',DATABASE(),'`.`',tableName,'` DROP COLUMN `',columnName,'`'); + prepare DynamicStatement from @StatementToExecute ; + execute DynamicStatement ; + deallocate prepare DynamicStatement ; + END IF ; + END"; + + $db->setQuery($query)->execute(); + } + + /** + * Method for implement procedure "redSHOP_Column_Update" + * + * @return void + * + * @since 2.1.0 + */ + protected function procedureUpdateColumn() + { + $db = JFactory::getDbo(); + + $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Column_Update'); + + $db->setQuery($query)->execute(); + + $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Column_Update") . "( IN " . $db->qn('tableName') . " VARCHAR(50), IN " . $db->qn('columnName') . " VARCHAR(50), IN " . $db->qn('newColumnName') . " VARCHAR(50), @@ -591,10 +605,16 @@ protected function procedureUpdateColumn() LANGUAGE SQL NOT DETERMINISTIC CONTAINS SQL - COMMENT " . $db->quote('Procedure for use in redSHOP to update / add column to table avoid unexpected errors.') . " + COMMENT " . $db->quote( + 'Procedure for use in redSHOP to update / add column to table avoid unexpected errors.' + ) . " BEGIN - SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET columnDetail = REPLACE(columnDetail, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; + SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET columnDetail = REPLACE(columnDetail, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; set @ColOldExist = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE COLUMN_NAME=columnName AND TABLE_NAME=tableName AND table_schema = DATABASE()); set @ColNewExist = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE COLUMN_NAME=newColumnName AND TABLE_NAME=tableName AND table_schema = DATABASE()); IF (@ColOldExist = 0 AND @ColNewExist = 0) THEN @@ -633,62 +653,25 @@ protected function procedureUpdateColumn() END IF; END"; - $db->setQuery($query)->execute(); - } - - /** - * Method for implement procedure "redSHOP_Column_Remove" - * - * @return void - * - * @since 2.1.0 - */ - protected function procedureRemoveColumn() - { - $db = JFactory::getDbo(); - - $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Column_Remove'); - - $db->setQuery($query)->execute(); - - $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Column_Remove") . "( - IN " . $db->qn('tableName') . " VARCHAR(50), - IN " . $db->qn('columnName') . " VARCHAR(50) - ) - LANGUAGE SQL - NOT DETERMINISTIC - CONTAINS SQL - COMMENT " . $db->quote('Procedure for use in redSHOP to remove column to table avoid unexpected errors.') . " - BEGIN - SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - IF ((SELECT COUNT(*) FROM information_schema.COLUMNS WHERE COLUMN_NAME=columnName AND TABLE_NAME=tableName AND table_schema = DATABASE()) >= 1) - THEN - set @StatementToExecute = concat('ALTER TABLE `',DATABASE(),'`.`',tableName,'` DROP COLUMN `',columnName,'`'); - prepare DynamicStatement from @StatementToExecute ; - execute DynamicStatement ; - deallocate prepare DynamicStatement ; - END IF ; - END"; - - $db->setQuery($query)->execute(); - } + $db->setQuery($query)->execute(); + } - /** - * Method for implement procedure "redSHOP_Index_Remove" - * - * @return void - * - * @since 2.1.0 - */ - protected function procedureIndexRemove() - { - $db = JFactory::getDbo(); + /** + * Method for implement procedure "redSHOP_Index_Remove" + * + * @return void + * + * @since 2.1.0 + */ + protected function procedureIndexRemove() + { + $db = JFactory::getDbo(); - $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Index_Remove'); + $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Index_Remove'); - $db->setQuery($query)->execute(); + $db->setQuery($query)->execute(); - $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Index_Remove") . "( + $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Index_Remove") . "( IN " . $db->qn('tableName') . " VARCHAR(50), IN " . $db->qn('indexName') . " VARCHAR(50) ) @@ -697,8 +680,12 @@ protected function procedureIndexRemove() CONTAINS SQL COMMENT " . $db->quote('Procedure for use in redSHOP to remove index from table avoid unexpected errors.') . " BEGIN - SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET indexName = REPLACE(indexName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; + SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET indexName = REPLACE(indexName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; IF ((SELECT COUNT(*) AS index_exists FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE() and table_name = tableName AND index_name = indexName) >= 1) THEN set @StatementToExecute = concat('ALTER TABLE `',DATABASE(),'`.`',tableName,'` DROP INDEX `',indexName,'`'); @@ -708,25 +695,25 @@ protected function procedureIndexRemove() END IF ; END"; - $db->setQuery($query)->execute(); - } + $db->setQuery($query)->execute(); + } - /** - * Method for implement procedure "redSHOP_Index_Add" - * - * @return void - * - * @since 2.1.0 - */ - protected function procedureIndexAdd() - { - $db = JFactory::getDbo(); + /** + * Method for implement procedure "redSHOP_Index_Add" + * + * @return void + * + * @since 2.1.0 + */ + protected function procedureIndexAdd() + { + $db = JFactory::getDbo(); - $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Index_Add'); + $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Index_Add'); - $db->setQuery($query)->execute(); + $db->setQuery($query)->execute(); - $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Index_Add") . "( + $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Index_Add") . "( IN " . $db->qn('tableName') . " VARCHAR(50), IN " . $db->qn('indexName') . " VARCHAR(50), IN " . $db->qn('indexData') . " VARCHAR(255) @@ -736,9 +723,15 @@ protected function procedureIndexAdd() CONTAINS SQL COMMENT " . $db->quote('Procedure for use in redSHOP to Add index to table avoid unexpected errors..') . " BEGIN - SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET indexName = REPLACE(indexName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET indexData = REPLACE(indexData, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; + SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET indexName = REPLACE(indexName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET indexData = REPLACE(indexData, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; CALL redSHOP_Index_Remove(tableName, indexName) ; set @StatementToExecute = concat('ALTER TABLE `',DATABASE(),'`.`',tableName,'` ADD INDEX `',indexName,'` ',indexData); prepare DynamicStatement from @StatementToExecute ; @@ -746,25 +739,25 @@ protected function procedureIndexAdd() deallocate prepare DynamicStatement ; END"; - $db->setQuery($query)->execute(); - } + $db->setQuery($query)->execute(); + } - /** - * Method for implement procedure "redSHOP_Index_Unique_Add" - * - * @return void - * - * @since 2.1.0 - */ - protected function procedureUniqueIndexAdd() - { - $db = JFactory::getDbo(); + /** + * Method for implement procedure "redSHOP_Index_Unique_Add" + * + * @return void + * + * @since 2.1.0 + */ + protected function procedureUniqueIndexAdd() + { + $db = JFactory::getDbo(); - $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Index_Unique_Add'); + $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Index_Unique_Add'); - $db->setQuery($query)->execute(); + $db->setQuery($query)->execute(); - $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Index_Unique_Add") . "( + $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Index_Unique_Add") . "( IN " . $db->qn('tableName') . " VARCHAR(50), IN " . $db->qn('indexName') . " VARCHAR(50), IN " . $db->qn('indexData') . " VARCHAR(255) @@ -772,11 +765,19 @@ protected function procedureUniqueIndexAdd() LANGUAGE SQL NOT DETERMINISTIC CONTAINS SQL - COMMENT " . $db->quote('Procedure for use in redSHOP to Add Unique Index to table avoid unexpected errors..') . " + COMMENT " . $db->quote( + 'Procedure for use in redSHOP to Add Unique Index to table avoid unexpected errors..' + ) . " BEGIN - SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET indexName = REPLACE(indexName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET indexData = REPLACE(indexData, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; + SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET indexName = REPLACE(indexName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET indexData = REPLACE(indexData, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; CALL redSHOP_Index_Remove(tableName, indexName); set @StatementToExecute = concat('ALTER TABLE `',DATABASE(),'`.`',tableName,'` ADD UNIQUE INDEX `',indexName,'` ',indexData); prepare DynamicStatement from @StatementToExecute ; @@ -784,25 +785,25 @@ protected function procedureUniqueIndexAdd() deallocate prepare DynamicStatement ; END"; - $db->setQuery($query)->execute(); - } + $db->setQuery($query)->execute(); + } - /** - * Method for implement procedure "redSHOP_Index_Fulltext_Add" - * - * @return void - * - * @since 2.1.0 - */ - protected function procedureFulltextIndexAdd() - { - $db = JFactory::getDbo(); + /** + * Method for implement procedure "redSHOP_Index_Fulltext_Add" + * + * @return void + * + * @since 2.1.0 + */ + protected function procedureFulltextIndexAdd() + { + $db = JFactory::getDbo(); - $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Index_Fulltext_Add'); + $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Index_Fulltext_Add'); - $db->setQuery($query)->execute(); + $db->setQuery($query)->execute(); - $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Index_Fulltext_Add") . "( + $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Index_Fulltext_Add") . "( IN " . $db->qn('tableName') . " VARCHAR(50), IN " . $db->qn('indexName') . " VARCHAR(50), IN " . $db->qn('indexData') . " VARCHAR(255) @@ -810,11 +811,19 @@ protected function procedureFulltextIndexAdd() LANGUAGE SQL NOT DETERMINISTIC CONTAINS SQL - COMMENT " . $db->quote('Procedure for use in redSHOP to Add Unique Index to table avoid unexpected errors..') . " + COMMENT " . $db->quote( + 'Procedure for use in redSHOP to Add Unique Index to table avoid unexpected errors..' + ) . " BEGIN - SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET indexName = REPLACE(indexName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET indexData = REPLACE(indexData, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; + SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET indexName = REPLACE(indexName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET indexData = REPLACE(indexData, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; CALL redSHOP_Index_Remove(tableName, indexName); set @StatementToExecute = concat('ALTER TABLE `',DATABASE(),'`.`',tableName,'` ADD FULLTEXT INDEX `',indexName,'` ',indexData); prepare DynamicStatement from @StatementToExecute ; @@ -822,35 +831,41 @@ protected function procedureFulltextIndexAdd() deallocate prepare DynamicStatement ; END"; - $db->setQuery($query)->execute(); - } + $db->setQuery($query)->execute(); + } - /** - * Method for implement procedure "redSHOP_Constraint_Remove" - * - * @return void - * - * @since 2.1.0 - */ - protected function procedureConstraintRemove() - { - $db = JFactory::getDbo(); + /** + * Method for implement procedure "redSHOP_Constraint_Remove" + * + * @return void + * + * @since 2.1.0 + */ + protected function procedureConstraintRemove() + { + $db = JFactory::getDbo(); - $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Constraint_Remove'); + $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Constraint_Remove'); - $db->setQuery($query)->execute(); + $db->setQuery($query)->execute(); - $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Constraint_Remove") . "( + $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Constraint_Remove") . "( IN " . $db->qn('tableName') . " VARCHAR(50), IN " . $db->qn('refName') . " VARCHAR(50) ) LANGUAGE SQL NOT DETERMINISTIC CONTAINS SQL - COMMENT " . $db->quote('Procedure for use in redSHOP to Add Constraint (Foreign Key) to table avoid unexpected errors..') . " + COMMENT " . $db->quote( + 'Procedure for use in redSHOP to Add Constraint (Foreign Key) to table avoid unexpected errors..' + ) . " BEGIN - SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET refName = REPLACE(refName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; + SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET refName = REPLACE(refName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; IF ((SELECT COUNT(*) AS constraint_exists FROM information_schema.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = DATABASE() and TABLE_NAME = tableName AND CONSTRAINT_NAME = refName AND CONSTRAINT_TYPE = 'FOREIGN KEY') >= 1) THEN SET FOREIGN_KEY_CHECKS = 0; @@ -862,25 +877,25 @@ protected function procedureConstraintRemove() END IF ; END"; - $db->setQuery($query)->execute(); - } + $db->setQuery($query)->execute(); + } - /** - * Method for implement procedure "redSHOP_Constraint_Update" - * - * @return void - * - * @since 2.1.0 - */ - protected function procedureConstraintUpdate() - { - $db = JFactory::getDbo(); + /** + * Method for implement procedure "redSHOP_Constraint_Update" + * + * @return void + * + * @since 2.1.0 + */ + protected function procedureConstraintUpdate() + { + $db = JFactory::getDbo(); - $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Constraint_Update'); + $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Constraint_Update'); - $db->setQuery($query)->execute(); + $db->setQuery($query)->execute(); - $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Constraint_Update") . "( + $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Constraint_Update") . "( IN " . $db->qn('tableName') . " VARCHAR(50), IN " . $db->qn('constraintName') . " VARCHAR(50), IN " . $db->qn('columnName') . " VARCHAR(50), @@ -892,13 +907,25 @@ protected function procedureConstraintUpdate() LANGUAGE SQL NOT DETERMINISTIC CONTAINS SQL - COMMENT " . $db->quote('Procedure for use in redSHOP to Update/Create Constraint (Foreign Key) to table avoid unexpected errors..') . " + COMMENT " . $db->quote( + 'Procedure for use in redSHOP to Update/Create Constraint (Foreign Key) to table avoid unexpected errors..' + ) . " BEGIN - SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET constraintName = REPLACE(constraintName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET columnName = REPLACE(columnName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET tableRef = REPLACE(tableRef, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET columnRef = REPLACE(columnRef, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; + SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET constraintName = REPLACE(constraintName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET columnName = REPLACE(columnName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET tableRef = REPLACE(tableRef, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET columnRef = REPLACE(columnRef, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; CALL redSHOP_Constraint_Remove(tableName, constraintName); SET FOREIGN_KEY_CHECKS = 0; SET @StatementToExecute = concat('ALTER TABLE `',DATABASE(),'`.`',tableName,'` ADD CONSTRAINT `',constraintName,'` FOREIGN KEY (`',columnName,'`) REFERENCES `',tableRef,'` (`',columnRef,'`) ON UPDATE ',onUpdateAction,' ON DELETE ',onDeleteAction); @@ -908,34 +935,40 @@ protected function procedureConstraintUpdate() SET FOREIGN_KEY_CHECKS = 1; END"; - $db->setQuery($query)->execute(); - } + $db->setQuery($query)->execute(); + } - /** - * Method for implement procedure "redSHOP_Primary_Remove" - * - * @return void - * - * @since 2.1.0 - */ - protected function procedurePrimaryRemove() - { - $db = JFactory::getDbo(); + /** + * Method for implement procedure "redSHOP_Primary_Remove" + * + * @return void + * + * @since 2.1.0 + */ + protected function procedurePrimaryRemove() + { + $db = JFactory::getDbo(); - $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Primary_Remove'); + $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Primary_Remove'); - $db->setQuery($query)->execute(); + $db->setQuery($query)->execute(); - $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Primary_Remove") . "( + $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Primary_Remove") . "( IN " . $db->qn('tableName') . " VARCHAR(50) ) LANGUAGE SQL NOT DETERMINISTIC CONTAINS SQL - COMMENT " . $db->quote('Procedure for use in redSHOP to remove primary key from table avoid unexpected errors.') . " + COMMENT " . $db->quote( + 'Procedure for use in redSHOP to remove primary key from table avoid unexpected errors.' + ) . " BEGIN - SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - IF ((SELECT COUNT(*) AS index_exists FROM information_schema.table_constraints WHERE TABLE_SCHEMA = DATABASE() and table_name = tableName AND constraint_name = " . $db->quote('PRIMARY') . ") >= 1) + SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + IF ((SELECT COUNT(*) AS index_exists FROM information_schema.table_constraints WHERE TABLE_SCHEMA = DATABASE() and table_name = tableName AND constraint_name = " . $db->quote( + 'PRIMARY' + ) . ") >= 1) THEN set @StatementToExecute = concat('ALTER TABLE `',DATABASE(),'`.`',tableName,'` DROP PRIMARY KEY'); prepare DynamicStatement from @StatementToExecute ; @@ -944,25 +977,25 @@ protected function procedurePrimaryRemove() END IF ; END"; - $db->setQuery($query)->execute(); - } + $db->setQuery($query)->execute(); + } - /** - * Method for implement procedure "redSHOP_Primary_Add" - * - * @return void - * - * @since 2.1.0 - */ - protected function procedurePrimaryAdd() - { - $db = JFactory::getDbo(); + /** + * Method for implement procedure "redSHOP_Primary_Add" + * + * @return void + * + * @since 2.1.0 + */ + protected function procedurePrimaryAdd() + { + $db = JFactory::getDbo(); - $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Primary_Add'); + $query = "DROP PROCEDURE IF EXISTS " . $db->qn('redSHOP_Primary_Add'); - $db->setQuery($query)->execute(); + $db->setQuery($query)->execute(); - $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Primary_Add") . "( + $query = "CREATE PROCEDURE " . $db->qn("redSHOP_Primary_Add") . "( IN " . $db->qn('tableName') . " VARCHAR(50), IN " . $db->qn('keyData') . " VARCHAR(255) ) @@ -971,8 +1004,12 @@ protected function procedurePrimaryAdd() CONTAINS SQL COMMENT " . $db->quote('Procedure for use in redSHOP to Add primary to table avoid unexpected errors..') . " BEGIN - SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; - SET keyData = REPLACE(keyData, " . $db->quote('#__') . ", " . $db->quote(JFactory::getConfig()->get('dbprefix')) . ") ; + SET tableName = REPLACE(tableName, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; + SET keyData = REPLACE(keyData, " . $db->quote('#__') . ", " . $db->quote( + JFactory::getConfig()->get('dbprefix') + ) . ") ; CALL redSHOP_Primary_Remove(tableName) ; set @StatementToExecute = concat('ALTER TABLE `',DATABASE(),'`.`',tableName,'` ADD PRIMARY KEY(',keyData,')'); prepare DynamicStatement from @StatementToExecute ; @@ -980,6 +1017,6 @@ protected function procedurePrimaryAdd() deallocate prepare DynamicStatement ; END"; - $db->setQuery($query)->execute(); - } + $db->setQuery($query)->execute(); + } } diff --git a/libraries/redshop/controller/admin.php b/libraries/redshop/controller/admin.php index f68afd22dcb..4731674ac0a 100644 --- a/libraries/redshop/controller/admin.php +++ b/libraries/redshop/controller/admin.php @@ -9,43 +9,39 @@ defined('_JEXEC') or die; -if (version_compare(JVERSION, '3.0', 'lt')) -{ - JLoader::import('joomla.application.component.model'); +if (version_compare(JVERSION, '3.0', 'lt')) { + JLoader::import('joomla.application.component.model'); - /** - * redSHOP Controller Admin - * - * @package Redshop - * @subpackage Controller - * @since 2.0.0.3 - */ - class RedshopControllerAdmin extends RedshopControllerAdminBase - { - /** - * We need to redeclare the method as JModelLegacy was not existing before 3.0. - * - * @param JModel $model The data model object. - * @param integer $id The validated data. - * - * @return void - */ - protected function postDeleteHook(JModel $model, $id = null) - { - } - } -} - -else -{ - /** - * redCORE Controller Admin - * - * @package Redcore - * @subpackage Controller - * @since 1.0 - */ - class RedshopControllerAdmin extends RedshopControllerAdminBase - { - } + /** + * redSHOP Controller Admin + * + * @package Redshop + * @subpackage Controller + * @since 2.0.0.3 + */ + class RedshopControllerAdmin extends RedshopControllerAdminBase + { + /** + * We need to redeclare the method as JModelLegacy was not existing before 3.0. + * + * @param JModel $model The data model object. + * @param integer $id The validated data. + * + * @return void + */ + protected function postDeleteHook(JModel $model, $id = null) + { + } + } +} else { + /** + * redCORE Controller Admin + * + * @package Redcore + * @subpackage Controller + * @since 1.0 + */ + class RedshopControllerAdmin extends RedshopControllerAdminBase + { + } } diff --git a/libraries/redshop/controller/admin/base.php b/libraries/redshop/controller/admin/base.php index 4486b8956f4..3465ec1b780 100644 --- a/libraries/redshop/controller/admin/base.php +++ b/libraries/redshop/controller/admin/base.php @@ -23,425 +23,395 @@ */ abstract class RedshopControllerAdminBase extends JControllerAdmin { - /** - * The method => state map. - * - * @var array - */ - protected $states = array( - 'publish' => 1, - 'unpublish' => 0, - 'archive' => 2, - 'trash' => -2, - 'report' => -3 - ); - - /** - * Constructor. - * - * @param array $config An optional associative array of configuration settings. - * - * @throws Exception - */ - public function __construct($config = array()) - { - parent::__construct($config); - - // J2.5 compatibility - if (null === $this->input) - { - $this->input = JFactory::getApplication()->input; - } - } - - /** - * Method to get a model object, loading it if required. - * - * @param string $name The model name. Optional. - * @param string $prefix The class prefix. Optional. - * @param array $config Configuration array for model. Optional. - * - * @return object The model. - */ - public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true)) - { - $class = get_class($this); - - if (empty($name)) - { - $name = strstr($class, 'Controller'); - $name = str_replace('Controller', '', $name); - $name = Inflector::singularize($name); - } - - if (empty($prefix)) - { - $prefix = strstr($class, 'Controller', true) . 'Model'; - } - - return parent::getModel($name, $prefix, $config); - } - - /** - * Method to save the submitted ordering values for records via AJAX. - * - * @return void - * - * @throws Exception - */ - public function saveOrderAjax() - { - // Get the input - $pks = $this->input->post->get('cid', array(), 'array'); - $order = $this->input->post->get('order', array(), 'array'); - - // Sanitize the input - $pks = ArrayHelper::toInteger($pks); - $order = ArrayHelper::toInteger($order); - - // Get the model - $model = $this->getModel(); - - // Save the ordering - $return = $model->saveorder($pks, $order); - - if ($return) - { - echo "1"; - } - - // Close the application - JFactory::getApplication()->close(); - } - - /** - * Removes an item. - * - * @return void - * - * @throws Exception - */ - public function delete() - { - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); - - // Get items to remove from the request. - $cid = JFactory::getApplication()->input->get('cid', array(), 'array'); - - if (!is_array($cid) || count($cid) < 1) - { - JLog::add(JText::_($this->text_prefix . '_NO_ITEM_SELECTED'), JLog::WARNING, 'jerror'); - } - else - { - // Get the model. - $model = $this->getModel(); - - // Make sure the item ids are integers - $cid = ArrayHelper::toInteger($cid); - - // Remove the items. - if ($model->delete($cid)) - { - $this->setMessage(JText::plural($this->text_prefix . '_N_ITEMS_DELETED', count($cid))); - } - else - { - $this->setMessage($model->getError(), 'error'); - } - - // Invoke the postDelete method to allow for the child class to access the model. - $this->postDeleteHook($model, $cid); - } - - // Set redirect - $this->setRedirect($this->getRedirectToListRoute()); - } - - /** - * Method to publish a list of items - * - * @return void - * - * @throws Exception - */ - public function publish() - { - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); - - // Get items to publish from the request. - $cid = JFactory::getApplication()->input->get('cid', array(), 'array'); - $value = ArrayHelper::getValue($this->states, $this->getTask(), 0, 'int'); - - if (empty($cid)) - { - JLog::add(JText::_($this->text_prefix . '_NO_ITEM_SELECTED'), JLog::WARNING, 'jerror'); - } - else - { - // Get the model. - $model = $this->getModel(); - - // Make sure the item ids are integers - $cid = ArrayHelper::toInteger($cid); - - // Publish the items. - try - { - $text = $this->text_prefix; - - if ($model->publish($cid, $value)) - { - switch ($this->getTask()) - { - case 'publish': - $text .= '_N_ITEMS_PUBLISHED'; - break; - - case 'unpublish': - $text .= '_N_ITEMS_UNPUBLISHED'; - break; - - case 'archive': - $text .= '_N_ITEMS_ARCHIVED'; - break; - - case 'trash': - $text .= '_N_ITEMS_TRASHED'; - break; - - case 'report': - $text .= '_N_ITEMS_REPORTED'; - break; - } - - $this->setMessage(JText::plural($text, count($cid))); - } - else - { - $this->setMessage($model->getError(), 'error'); - } - } - catch (Exception $e) - { - $this->setMessage(JText::_('JLIB_DATABASE_ERROR_ANCESTOR_NODES_LOWER_STATE'), 'error'); - } - } - - $extension = $this->input->get('extension'); - $extensionURL = ($extension) ? '&extension=' . $extension : ''; - - // Set redirect - $this->setRedirect($this->getRedirectToListRoute($extensionURL)); - } - - /** - * Check in of one or more records. - * - * @return boolean True on success - * - * @throws Exception - */ - public function checkin() - { - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); - - $ids = JFactory::getApplication()->input->post->get('cid', array(), 'array'); - $model = $this->getModel(); - $return = $model->checkin($ids); - - if ($return === false) - { - // Check in failed. - $message = JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError()); - - // Set redirect - $this->setRedirect($this->getRedirectToListRoute(), $message, 'error'); - - return false; - } - - // Check in succeeded. - $message = JText::plural($this->text_prefix . '_N_ITEMS_CHECKED_IN', count($ids)); - - // Set redirect - $this->setRedirect($this->getRedirectToListRoute(), $message); - - return true; - } - - /** - * Changes the order of one or more records. - * - * @return boolean True on success - * - * @throws Exception - */ - public function reorder() - { - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); - - $ids = JFactory::getApplication()->input->post->get('cid', array(), 'array'); - $inc = $this->getTask() === 'orderup' ? -1 : 1; - - $model = $this->getModel(); - $return = $model->reorder($ids, $inc); - - if ($return === false) - { - // Reorder failed. - $message = JText::sprintf('JLIB_APPLICATION_ERROR_REORDER_FAILED', $model->getError()); - - // Set redirect - $this->setRedirect($this->getRedirectToListRoute(), $message, 'error'); - - return false; - } - - // Reorder succeeded. - $message = JText::_('JLIB_APPLICATION_SUCCESS_ITEM_REORDERED'); - - // Set redirect - $this->setRedirect($this->getRedirectToListRoute(), $message); - - return true; - } - - /** - * Method to save the submitted ordering values for records. - * - * @return boolean True on success - */ - public function saveorder() - { - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); - - // Get the input - $pks = $this->input->post->get('cid', array(), 'array'); - $order = $this->input->post->get('order', array(), 'array'); - - // Sanitize the input - $pks = ArrayHelper::toInteger($pks); - $order = ArrayHelper::toInteger($order); - - // Get the model - $model = $this->getModel(); - - // Save the ordering - $return = $model->saveorder($pks, $order); - - if ($return === false) - { - // Reorder failed - $message = JText::sprintf('JLIB_APPLICATION_ERROR_REORDER_FAILED', $model->getError()); - - // Set redirect - $this->setRedirect($this->getRedirectToListRoute(), $message, 'error'); - - return false; - } - - // Reorder succeeded. - $this->setMessage(JText::_('JLIB_APPLICATION_SUCCESS_ORDERING_SAVED')); - - // Set redirect - $this->setRedirect($this->getRedirectToListRoute()); - - return true; - } - - /** - * Get the JRoute object for a redirect to list. - * - * @param string $append An optional string to append to the route - * - * @return string The JRoute string - */ - protected function getRedirectToListRoute($append = null) - { - $returnUrl = (string) $this->input->get('return', '', 'Base64'); - - if ($returnUrl) - { - return JRoute::_(base64_decode($returnUrl) . $append, false); - } - - return JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list . $append, false); - } - - /** - * Method to publish a list of items - * - * @return void - * - * @throws Exception - */ - public function ajaxInlineEdit() - { - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); - $app = JFactory::getApplication(); - - $editData = $this->input->get('jform_inline', array(), 'ARRAY'); - $editKey = $this->input->get('id', 0); - - if (empty($editData) || empty($editData[$editKey])) - { - echo 0; - - $app->close(); - } - - $editData = $editData[$editKey]; - - /** @var RedshopTable $table */ - $table = $this->getModel()->getTable(); - - if (!$table->load($editKey) || !$table->bind($editData) || !$table->check()) - { - echo 0; - - $app->close(); - } - - $table->setOption('inlineMode', true); - - if (!$table->store()) - { - echo 0; - - $app->close(); - } - - echo 1; - - $app->close(); - } - - /** - * Method to clone an existing item. - * - * @return void - * - * @since 2.0.7 - */ - public function copy() - { - JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); - - $pks = $this->input->post->get('cid', array(), 'array'); - $pks = ArrayHelper::toInteger($pks); - - try - { - $model = $this->getModel(); - $model->copy($pks); - $this->setMessage(JText::plural('COM_REDSHOP_N_ITEMS_COPIED', count($pks))); - } - catch (Exception $e) - { - JError::raiseWarning(500, $e->getMessage()); - } - - $this->setRedirect($this->getRedirectToListRoute()); - } + /** + * The method => state map. + * + * @var array + */ + protected $states = array( + 'publish' => 1, + 'unpublish' => 0, + 'archive' => 2, + 'trash' => -2, + 'report' => -3 + ); + + /** + * Constructor. + * + * @param array $config An optional associative array of configuration settings. + * + * @throws Exception + */ + public function __construct($config = array()) + { + parent::__construct($config); + + // J2.5 compatibility + if (null === $this->input) { + $this->input = JFactory::getApplication()->input; + } + } + + /** + * Method to save the submitted ordering values for records via AJAX. + * + * @return void + * + * @throws Exception + */ + public function saveOrderAjax() + { + // Get the input + $pks = $this->input->post->get('cid', array(), 'array'); + $order = $this->input->post->get('order', array(), 'array'); + + // Sanitize the input + $pks = ArrayHelper::toInteger($pks); + $order = ArrayHelper::toInteger($order); + + // Get the model + $model = $this->getModel(); + + // Save the ordering + $return = $model->saveorder($pks, $order); + + if ($return) { + echo "1"; + } + + // Close the application + JFactory::getApplication()->close(); + } + + /** + * Method to get a model object, loading it if required. + * + * @param string $name The model name. Optional. + * @param string $prefix The class prefix. Optional. + * @param array $config Configuration array for model. Optional. + * + * @return object The model. + */ + public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true)) + { + $class = get_class($this); + + if (empty($name)) { + $name = strstr($class, 'Controller'); + $name = str_replace('Controller', '', $name); + $name = Inflector::singularize($name); + } + + if (empty($prefix)) { + $prefix = strstr($class, 'Controller', true) . 'Model'; + } + + return parent::getModel($name, $prefix, $config); + } + + /** + * Removes an item. + * + * @return void + * + * @throws Exception + */ + public function delete() + { + JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + + // Get items to remove from the request. + $cid = JFactory::getApplication()->input->get('cid', array(), 'array'); + + if (!is_array($cid) || count($cid) < 1) { + JLog::add(JText::_($this->text_prefix . '_NO_ITEM_SELECTED'), JLog::WARNING, 'jerror'); + } else { + // Get the model. + $model = $this->getModel(); + + // Make sure the item ids are integers + $cid = ArrayHelper::toInteger($cid); + + // Remove the items. + if ($model->delete($cid)) { + $this->setMessage(JText::plural($this->text_prefix . '_N_ITEMS_DELETED', count($cid))); + } else { + $this->setMessage($model->getError(), 'error'); + } + + // Invoke the postDelete method to allow for the child class to access the model. + $this->postDeleteHook($model, $cid); + } + + // Set redirect + $this->setRedirect($this->getRedirectToListRoute()); + } + + /** + * Get the JRoute object for a redirect to list. + * + * @param string $append An optional string to append to the route + * + * @return string The JRoute string + */ + protected function getRedirectToListRoute($append = null) + { + $returnUrl = (string)$this->input->get('return', '', 'Base64'); + + if ($returnUrl) { + return JRoute::_(base64_decode($returnUrl) . $append, false); + } + + return JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list . $append, false); + } + + /** + * Method to publish a list of items + * + * @return void + * + * @throws Exception + */ + public function publish() + { + JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + + // Get items to publish from the request. + $cid = JFactory::getApplication()->input->get('cid', array(), 'array'); + $value = ArrayHelper::getValue($this->states, $this->getTask(), 0, 'int'); + + if (empty($cid)) { + JLog::add(JText::_($this->text_prefix . '_NO_ITEM_SELECTED'), JLog::WARNING, 'jerror'); + } else { + // Get the model. + $model = $this->getModel(); + + // Make sure the item ids are integers + $cid = ArrayHelper::toInteger($cid); + + // Publish the items. + try { + $text = $this->text_prefix; + + if ($model->publish($cid, $value)) { + switch ($this->getTask()) { + case 'publish': + $text .= '_N_ITEMS_PUBLISHED'; + break; + + case 'unpublish': + $text .= '_N_ITEMS_UNPUBLISHED'; + break; + + case 'archive': + $text .= '_N_ITEMS_ARCHIVED'; + break; + + case 'trash': + $text .= '_N_ITEMS_TRASHED'; + break; + + case 'report': + $text .= '_N_ITEMS_REPORTED'; + break; + } + + $this->setMessage(JText::plural($text, count($cid))); + } else { + $this->setMessage($model->getError(), 'error'); + } + } catch (Exception $e) { + $this->setMessage(JText::_('JLIB_DATABASE_ERROR_ANCESTOR_NODES_LOWER_STATE'), 'error'); + } + } + + $extension = $this->input->get('extension'); + $extensionURL = ($extension) ? '&extension=' . $extension : ''; + + // Set redirect + $this->setRedirect($this->getRedirectToListRoute($extensionURL)); + } + + /** + * Check in of one or more records. + * + * @return boolean True on success + * + * @throws Exception + */ + public function checkin() + { + JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + + $ids = JFactory::getApplication()->input->post->get('cid', array(), 'array'); + $model = $this->getModel(); + $return = $model->checkin($ids); + + if ($return === false) { + // Check in failed. + $message = JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError()); + + // Set redirect + $this->setRedirect($this->getRedirectToListRoute(), $message, 'error'); + + return false; + } + + // Check in succeeded. + $message = JText::plural($this->text_prefix . '_N_ITEMS_CHECKED_IN', count($ids)); + + // Set redirect + $this->setRedirect($this->getRedirectToListRoute(), $message); + + return true; + } + + /** + * Changes the order of one or more records. + * + * @return boolean True on success + * + * @throws Exception + */ + public function reorder() + { + JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + + $ids = JFactory::getApplication()->input->post->get('cid', array(), 'array'); + $inc = $this->getTask() === 'orderup' ? -1 : 1; + + $model = $this->getModel(); + $return = $model->reorder($ids, $inc); + + if ($return === false) { + // Reorder failed. + $message = JText::sprintf('JLIB_APPLICATION_ERROR_REORDER_FAILED', $model->getError()); + + // Set redirect + $this->setRedirect($this->getRedirectToListRoute(), $message, 'error'); + + return false; + } + + // Reorder succeeded. + $message = JText::_('JLIB_APPLICATION_SUCCESS_ITEM_REORDERED'); + + // Set redirect + $this->setRedirect($this->getRedirectToListRoute(), $message); + + return true; + } + + /** + * Method to save the submitted ordering values for records. + * + * @return boolean True on success + */ + public function saveorder() + { + JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + + // Get the input + $pks = $this->input->post->get('cid', array(), 'array'); + $order = $this->input->post->get('order', array(), 'array'); + + // Sanitize the input + $pks = ArrayHelper::toInteger($pks); + $order = ArrayHelper::toInteger($order); + + // Get the model + $model = $this->getModel(); + + // Save the ordering + $return = $model->saveorder($pks, $order); + + if ($return === false) { + // Reorder failed + $message = JText::sprintf('JLIB_APPLICATION_ERROR_REORDER_FAILED', $model->getError()); + + // Set redirect + $this->setRedirect($this->getRedirectToListRoute(), $message, 'error'); + + return false; + } + + // Reorder succeeded. + $this->setMessage(JText::_('JLIB_APPLICATION_SUCCESS_ORDERING_SAVED')); + + // Set redirect + $this->setRedirect($this->getRedirectToListRoute()); + + return true; + } + + /** + * Method to publish a list of items + * + * @return void + * + * @throws Exception + */ + public function ajaxInlineEdit() + { + JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + $app = JFactory::getApplication(); + + $editData = $this->input->get('jform_inline', array(), 'ARRAY'); + $editKey = $this->input->get('id', 0); + + if (empty($editData) || empty($editData[$editKey])) { + echo 0; + + $app->close(); + } + + $editData = $editData[$editKey]; + + /** @var RedshopTable $table */ + $table = $this->getModel()->getTable(); + + if (!$table->load($editKey) || !$table->bind($editData) || !$table->check()) { + echo 0; + + $app->close(); + } + + $table->setOption('inlineMode', true); + + if (!$table->store()) { + echo 0; + + $app->close(); + } + + echo 1; + + $app->close(); + } + + /** + * Method to clone an existing item. + * + * @return void + * + * @since 2.0.7 + */ + public function copy() + { + JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); + + $pks = $this->input->post->get('cid', array(), 'array'); + $pks = ArrayHelper::toInteger($pks); + + try { + $model = $this->getModel(); + $model->copy($pks); + $this->setMessage(JText::plural('COM_REDSHOP_N_ITEMS_COPIED', count($pks))); + } catch (Exception $e) { + JError::raiseWarning(500, $e->getMessage()); + } + + $this->setRedirect($this->getRedirectToListRoute()); + } } diff --git a/libraries/redshop/controller/controller.php b/libraries/redshop/controller/controller.php index fe4bf307a5e..3a18024b83a 100644 --- a/libraries/redshop/controller/controller.php +++ b/libraries/redshop/controller/controller.php @@ -20,40 +20,37 @@ */ class RedshopController extends JControllerLegacy { - /** - * Gets the URL arguments to append to an item redirect. - * - * @param integer $recordId The primary key id for the item. - * @param string $urlVar The name of the URL variable for the id. - * - * @return string The arguments to append to the redirect URL. - * - * @since 1.5.1 - * @throws Exception - */ - protected function getRedirectToItemAppend($recordId = null, $urlVar = 'id') - { - $app = JFactory::getApplication(); - $tmpl = $app->input->get('tmpl'); - $layout = $app->input->get('layout', 'edit', 'string'); - $append = ''; + /** + * Gets the URL arguments to append to an item redirect. + * + * @param integer $recordId The primary key id for the item. + * @param string $urlVar The name of the URL variable for the id. + * + * @return string The arguments to append to the redirect URL. + * + * @throws Exception + * @since 1.5.1 + */ + protected function getRedirectToItemAppend($recordId = null, $urlVar = 'id') + { + $app = JFactory::getApplication(); + $tmpl = $app->input->get('tmpl'); + $layout = $app->input->get('layout', 'edit', 'string'); + $append = ''; - // Setup redirect info. - if ($tmpl) - { - $append .= '&tmpl=' . $tmpl; - } + // Setup redirect info. + if ($tmpl) { + $append .= '&tmpl=' . $tmpl; + } - if ($layout) - { - $append .= '&layout=' . $layout; - } + if ($layout) { + $append .= '&layout=' . $layout; + } - if ($recordId) - { - $append .= '&' . $urlVar . '=' . $recordId; - } + if ($recordId) { + $append .= '&' . $urlVar . '=' . $recordId; + } - return $append; - } + return $append; + } } diff --git a/libraries/redshop/controller/form.php b/libraries/redshop/controller/form.php index b200b01c51b..4c57871cfee 100644 --- a/libraries/redshop/controller/form.php +++ b/libraries/redshop/controller/form.php @@ -22,711 +22,659 @@ */ class RedshopControllerForm extends JControllerForm { - use \Redshop\Model\Traits\HasDateTimeRange; - - /** - * The name of the controller - * - * @var string - * @since 2.1.3 - */ - protected $name; - - /** - * Constructor. - * - * @param array $config An optional associative array of configuration settings. - * Recognized key values include 'name', 'default_task', 'model_path', and - * 'view_path' (this list is not meant to be comprehensive). - * - * @throws Exception - */ - public function __construct($config = array()) - { - /** JControllerLegacy */ - $this->methods = array(); - $this->message = null; - $this->messageType = 'message'; - $this->paths = array(); - $this->redirect = null; - $this->taskMap = array(); - - if (defined('JDEBUG') && JDEBUG) - { - JLog::addLogger(array('text_file' => 'jcontroller.log.php'), JLog::ALL, array('controller')); - } - - $this->input = JFactory::getApplication()->input; - - // Determine the methods to exclude from the base class. - $xMethods = get_class_methods('JControllerLegacy'); - - // Get the public methods in this class using reflection. - $r = new ReflectionClass($this); - $rMethods = $r->getMethods(ReflectionMethod::IS_PUBLIC); - - foreach ($rMethods as $rMethod) - { - $mName = $rMethod->getName(); - - // Add default display method if not explicitly declared. - if (!in_array($mName, $xMethods) || $mName == 'display') - { - $this->methods[] = strtolower($mName); - - // Auto register the methods as tasks. - $this->taskMap[strtolower($mName)] = $mName; - } - } - - // Set the view name - if (empty($this->name)) - { - if (array_key_exists('name', $config)) - { - $this->name = $config['name']; - } - else - { - $this->name = $this->getName(); - } - } - - // Set a base path for use by the controller - if (array_key_exists('base_path', $config)) - { - $this->basePath = $config['base_path']; - } - else - { - $this->basePath = JPATH_COMPONENT; - } - - // If the default task is set, register it as such - if (array_key_exists('default_task', $config)) - { - $this->registerDefaultTask($config['default_task']); - } - else - { - $this->registerDefaultTask('display'); - } - - // Set the models prefix - if (empty($this->model_prefix)) - { - if (array_key_exists('model_prefix', $config)) - { - // User-defined prefix - $this->model_prefix = $config['model_prefix']; - } - else - { - $this->model_prefix = $this->name . 'Model'; - } - } - - // Set the default model search path - if (array_key_exists('model_path', $config)) - { - // User-defined dirs - $this->addModelPath($config['model_path'], $this->model_prefix); - } - else - { - $this->addModelPath($this->basePath . '/models', $this->model_prefix); - } - - // Set the default view search path - if (array_key_exists('view_path', $config)) - { - // User-defined dirs - $this->setPath('view', $config['view_path']); - } - else - { - $this->setPath('view', $this->basePath . '/views'); - } - - // Set the default view. - if (array_key_exists('default_view', $config)) - { - $this->default_view = $config['default_view']; - } - elseif (empty($this->default_view)) - { - $this->default_view = $this->getName(); - } - - /** JControllerForm */ - // Guess the option as com_NameOfController - if (empty($this->option)) - { - $this->option = 'com_' . strtolower($this->getName()); - } - - // Guess the JText message prefix. Defaults to the option. - if (empty($this->text_prefix)) - { - $this->text_prefix = strtoupper($this->option); - } - - // Guess the context as the suffix, eg: OptionControllerContent. - if (empty($this->context)) - { - $r = null; - - if (!preg_match('/(.*)Controller(.*)/i', get_class($this), $r)) - { - throw new Exception(JText::_('JLIB_APPLICATION_ERROR_CONTROLLER_GET_NAME'), 500); - } - - $this->context = strtolower($r[2]); - } - - // Apply, Save & New, and Save As copy should be standard on forms. - $this->registerTask('apply', 'save'); - $this->registerTask('save2new', 'save'); - $this->registerTask('save2copy', 'save'); - - /** Custom */ - // Guess the item view as the context. - if (empty($this->view_item)) - { - $this->view_item = $this->context; - } - - if (empty($this->view_list)) - { - $this->view_list = Inflector::pluralize($this->view_item); - } - - if (!property_exists($this, 'input') || empty($this->input)) - { - $this->input = JFactory::getApplication()->input; - } - } - - /** - * Method to get a model object, loading it if required. - * - * @param string $name The model name. Optional. - * @param string $prefix The class prefix. Optional. - * @param array $config Configuration array for model. Optional. - * - * @return object The model. - */ - public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true)) - { - $class = get_class($this); - - if (empty($name)) - { - $name = strstr($class, 'Controller'); - $name = str_replace('Controller', '', $name); - } - - if (empty($prefix)) - { - $prefix = strstr($class, 'Controller', true) . 'Model'; - } - - return parent::getModel($name, $prefix, $config); - } - - /** - * Method to cancel an edit. - * - * @param string $key The name of the primary key of the URL variable. - * - * @return boolean True if access level checks pass, false otherwise. - */ - public function cancel($key = null) - { - JSession::checkToken() or jexit(JText::_('INVALID_TOKEN')); - - $app = JFactory::getApplication(); - $model = $this->getModel(); - $table = $model->getTable(); - $checkin = property_exists($table, 'checked_out'); - $context = "$this->option.edit.$this->context"; - - if (empty($key)) - { - $key = $table->getKeyName(); - } - - $recordId = $app->input->getInt($key); - - // Attempt to check-in the current record. - if ($recordId) - { - // Check we are holding the id in the edit list. - if (!$this->checkEditId($context, $recordId)) - { - // Somehow the person just went to the form - we don't allow that. - /** @scrutinizer ignore-deprecated */ $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $recordId)); - $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); - - // Redirect to the list screen - $this->setRedirect( - $this->getRedirectToListRoute($this->getRedirectToListAppend()) - ); - - return false; - } - - if ($checkin) - { - if ($model->checkin($recordId) === false) - { - // Check-in failed, go back to the record and display a notice. - /** @scrutinizer ignore-deprecated */ $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError())); - $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); - - // Redirect back to the edit screen. - $this->setRedirect( - $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $key)) - ); - - return false; - } - } - } - - // Clean the session data and redirect. - $this->releaseEditId($context, $recordId); - $app->setUserState($context . '.data', null); - - // Redirect to the list screen - $this->setRedirect( - $this->getRedirectToListRoute($this->getRedirectToListAppend()) - ); - - return true; - } - - /** - * Method to edit an existing record. - * - * @param string $key The name of the primary key of the URL variable. - * @param string $urlVar The name of the URL variable if different from the primary key - * (sometimes required to avoid router collisions). - * - * @return boolean True if access level check and checkout passes, false otherwise. - */ - public function edit($key = null, $urlVar = null) - { - $app = JFactory::getApplication(); - $model = $this->getModel(); - $table = $model->getTable(); - $cid = $this->input->post->get('cid', array(), 'array'); - $context = "$this->option.edit.$this->context"; - - // Determine the name of the primary key for the data. - if (empty($key)) - { - $key = $table->getKeyName(); - } - - // To avoid data collisions the urlVar may be different from the primary key. - if (empty($urlVar)) - { - $urlVar = $key; - } - - // Get the previous record id (if any) and the current record id. - $recordId = (int) (count($cid) ? $cid[0] : $this->input->getInt($urlVar)); - $checkin = property_exists($table, 'checked_out'); - - // Access check. - if (!$this->allowEdit(array($key => $recordId), $key)) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('JLIB_APPLICATION_ERROR_EDIT_NOT_PERMITTED')); - $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); - - // Redirect to the list screen - $this->setRedirect( - $this->getRedirectToListRoute($this->getRedirectToListAppend()) - ); - - return false; - } - - // Attempt to check-out the new record for editing and redirect. - if ($checkin && !$model->checkout($recordId)) - { - // Check-out failed, display a notice but allow the user to see the record. - /** @scrutinizer ignore-deprecated */ $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKOUT_FAILED', $model->getError())); - $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); - - // Redirect back to the edit screen. - $this->setRedirect( - $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) - ); - - return false; - } - else - { - // Check-out succeeded, push the new record id into the session. - $this->holdEditId($context, $recordId); - $app->setUserState($context . '.data', null); - - // Redirect back to the edit screen. - $this->setRedirect( - $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) - ); - - return true; - } - } - - /** - * Method to add a new record. - * - * @return mixed True if the record can be added, a error object if not. - */ - public function add() - { - $app = JFactory::getApplication(); - $context = "$this->option.edit.$this->context"; - - // Access check. - if (!$this->allowAdd()) - { - // Set the internal error and also the redirect error. - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('JLIB_APPLICATION_ERROR_CREATE_RECORD_NOT_PERMITTED')); - $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); - - // Redirect to the list screen - $this->setRedirect( - $this->getRedirectToListRoute($this->getRedirectToListAppend()) - ); - - return false; - } - - // Clear the record edit information from the session. - $app->setUserState($context . '.data', null); - - // Redirect back to the edit screen. - $this->setRedirect( - $this->getRedirectToItemRoute($this->getRedirectToItemAppend()) - ); - - return true; - } - - /** - * Method to save a record. - * - * @param string $key The name of the primary key of the URL variable. - * @param string $urlVar The name of the URL variable if different from the primary key (sometimes required to avoid router collisions). - * - * @return boolean True if successful, false otherwise. - * @throws Exception - */ - public function save($key = null, $urlVar = null) - { - // Check for request forgeries. - JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); - - $app = JFactory::getApplication(); - $lang = JFactory::getLanguage(); - $model = $this->getModel(); - $table = $model->getTable(); - $data = $this->input->post->get('jform', array(), 'array'); - $checkin = property_exists($table, 'checked_out'); - $context = "$this->option.edit.$this->context"; - $task = $this->getTask(); - - // Determine the name of the primary key for the data. - if (null === $key) - { - $key = $table->getKeyName(); - } - - // To avoid data collisions the urlVar may be different from the primary key. - if (null === $urlVar) - { - $urlVar = $key; - } - - if (isset($data['start_date']) && isset($data['end_date'])) - { - $this->handleDateTimeRange($data['start_date'], $data['end_date']); - } - - $recordId = $this->input->getInt($urlVar); - - if (!$this->checkEditId($context, $recordId)) - { - // Somehow the person just went to the form and tried to save it. We don't allow that. - /** @scrutinizer ignore-deprecated */ $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $recordId)); - $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); - - // Redirect to the list screen - $this->setRedirect( - $this->getRedirectToListRoute($this->getRedirectToListAppend()) - ); - - return false; - } - - // Populate the row id from the session. - $data[$key] = $recordId; - - // The save2copy task needs to be handled slightly differently. - if ($task === 'save2copy') - { - // Check-in the original row. - if ($checkin && $model->checkin($data[$key]) === false) - { - // Check-in failed. Go back to the item and display a notice. - /** @scrutinizer ignore-deprecated */ $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError())); - $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); - - // Redirect back to the edit screen. - $this->setRedirect( - $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) - ); - - return false; - } - - // Reset the ID, the multilingual associations and then treat the request as for Apply. - $data[$key] = 0; - $data['associations'] = array(); - $task = 'apply'; - } - - // Access check. - if (!$this->allowSave($data, $key)) - { - /** @scrutinizer ignore-deprecated */ $this->setError(JText::_('JLIB_APPLICATION_ERROR_SAVE_NOT_PERMITTED')); - $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); - - // Redirect to the list screen - $this->setRedirect( - $this->getRedirectToListRoute($this->getRedirectToListAppend()) - ); - - return false; - } - - // Validate the posted data. - // Sometimes the form needs some posted data, such as for plugins and modules. - $form = $model->getForm($data, false); - - if (!$form) - { - $app->enqueueMessage($model->getError(), 'error'); - - return false; - } - - // Test whether the data is valid. - $validData = $model->validate($form, $data); - - // Check for validation errors. - if ($validData === false) - { - // Get the validation messages. - $errors = $model->getErrors(); - - // Push up to three validation messages out to the user. - for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) - { - if ($errors[$i] instanceof Exception) - { - $app->enqueueMessage($errors[$i]->getMessage(), 'error'); - } - else - { - $app->enqueueMessage($errors[$i], 'error'); - } - } - - // Save the data in the session. - $app->setUserState($context . '.data', $data); - - // Redirect back to the edit screen. - $this->setRedirect( - $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) - ); - - return false; - } - - if (!isset($validData['tags'])) - { - $validData['tags'] = null; - } - - // Attempt to save the data. - if (!$model->save($validData)) - { - // Save the data in the session. - $app->setUserState($context . '.data', $validData); - - // Redirect back to the edit screen. - /** @scrutinizer ignore-deprecated */ $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError())); - $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); - - // Redirect back to the edit screen. - $this->setRedirect( - $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) - ); - - return false; - } - - // Save succeeded, so check-in the record. - if ($checkin && $model->checkin($validData[$key]) === false) - { - // Save the data in the session. - $app->setUserState($context . '.data', $validData); - - // Check-in failed, so go back to the record and display a notice. - /** @scrutinizer ignore-deprecated */ $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError())); - $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); - - // Redirect back to the edit screen. - $this->setRedirect( - $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) - ); - - return false; - } - - $this->setMessage( - JText::_( - ($lang->hasKey($this->text_prefix . ($recordId == 0 && $app->isClient('site') ? '_SUBMIT' : '') . '_SAVE_SUCCESS') - ? $this->text_prefix - : 'JLIB_APPLICATION') . ($recordId == 0 && $app->isClient('site') ? '_SUBMIT' : '') . '_SAVE_SUCCESS' - ) - ); - - // Redirect the user and adjust session state based on the chosen task. - switch ($task) - { - case 'apply': - // Set the record data in the session. - $recordId = $model->getState($this->context . '.id'); - $this->holdEditId($context, $recordId); - $app->setUserState($context . '.data', null); - $model->checkout($recordId); - - // Redirect back to the edit screen. - $this->setRedirect( - $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) - ); - break; - - case 'save2new': - // Clear the record id and data from the session. - $this->releaseEditId($context, $recordId); - $app->setUserState($context . '.data', null); - - // Redirect back to the edit screen. - $this->setRedirect( - $this->getRedirectToItemRoute($this->getRedirectToItemAppend(null, $urlVar)) - ); - break; - - default: - // Clear the record id and data from the session. - $this->releaseEditId($context, $recordId); - $app->setUserState($context . '.data', null); - - // Set redirect - $this->setRedirect( - $this->getRedirectToListRoute($this->getRedirectToListAppend()) - ); - break; - } - - // Invoke the postSave method to allow for the child class to access the model. - $this->postSaveHook($model, $validData); - - return true; - } - - /** - * Gets the URL arguments to append to an item redirect. - * - * @param integer $recordId The primary key id for the item. - * @param string $urlVar The name of the URL variable for the id. - * - * @return string The arguments to append to the redirect URL. - */ - protected function getRedirectToItemAppend($recordId = null, $urlVar = 'id') - { - $append = parent::getRedirectToItemAppend($recordId, $urlVar); - - $return = $this->input->get('return', '', 'Base64'); - - if ($return) - { - $append .= '&return=' . $return; - } - - return $append; - } - - /** - * Gets the URL arguments to append to a list redirect. - * - * @return string The arguments to append to the redirect URL. - */ - protected function getRedirectToListAppend() - { - $append = parent::getRedirectToListAppend(); - - $return = $this->input->get('return', '', 'Base64'); - - if ($return) - { - $append .= '&return=' . $return; - } - - return $append; - } - - /** - * Get the JRoute object for a redirect to list. - * - * @param string $append An optional string to append to the route - * - * @return string - */ - protected function getRedirectToListRoute($append = null) - { - $returnUrl = $this->input->get('return', '', 'Base64'); - - if ($returnUrl) - { - $returnUrl = base64_decode($returnUrl); - - return JRoute::_($returnUrl . $append, false); - } - - return JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list . $append, false); - } - - /** - * Get the JRoute object for a redirect to item. - * - * @param string $append An optionnal string to append to the route - * - * @return string The url string - */ - protected function getRedirectToItemRoute($append = null) - { - return JRoute::_( - 'index.php?option=' . $this->option . '&view=' . $this->view_item - . $append, false - ); - } + use \Redshop\Model\Traits\HasDateTimeRange; + + /** + * The name of the controller + * + * @var string + * @since 2.1.3 + */ + protected $name; + + /** + * Constructor. + * + * @param array $config An optional associative array of configuration settings. + * Recognized key values include 'name', 'default_task', 'model_path', and + * 'view_path' (this list is not meant to be comprehensive). + * + * @throws Exception + */ + public function __construct($config = array()) + { + /** JControllerLegacy */ + $this->methods = array(); + $this->message = null; + $this->messageType = 'message'; + $this->paths = array(); + $this->redirect = null; + $this->taskMap = array(); + + if (defined('JDEBUG') && JDEBUG) { + JLog::addLogger(array('text_file' => 'jcontroller.log.php'), JLog::ALL, array('controller')); + } + + $this->input = JFactory::getApplication()->input; + + // Determine the methods to exclude from the base class. + $xMethods = get_class_methods('JControllerLegacy'); + + // Get the public methods in this class using reflection. + $r = new ReflectionClass($this); + $rMethods = $r->getMethods(ReflectionMethod::IS_PUBLIC); + + foreach ($rMethods as $rMethod) { + $mName = $rMethod->getName(); + + // Add default display method if not explicitly declared. + if (!in_array($mName, $xMethods) || $mName == 'display') { + $this->methods[] = strtolower($mName); + + // Auto register the methods as tasks. + $this->taskMap[strtolower($mName)] = $mName; + } + } + + // Set the view name + if (empty($this->name)) { + if (array_key_exists('name', $config)) { + $this->name = $config['name']; + } else { + $this->name = $this->getName(); + } + } + + // Set a base path for use by the controller + if (array_key_exists('base_path', $config)) { + $this->basePath = $config['base_path']; + } else { + $this->basePath = JPATH_COMPONENT; + } + + // If the default task is set, register it as such + if (array_key_exists('default_task', $config)) { + $this->registerDefaultTask($config['default_task']); + } else { + $this->registerDefaultTask('display'); + } + + // Set the models prefix + if (empty($this->model_prefix)) { + if (array_key_exists('model_prefix', $config)) { + // User-defined prefix + $this->model_prefix = $config['model_prefix']; + } else { + $this->model_prefix = $this->name . 'Model'; + } + } + + // Set the default model search path + if (array_key_exists('model_path', $config)) { + // User-defined dirs + $this->addModelPath($config['model_path'], $this->model_prefix); + } else { + $this->addModelPath($this->basePath . '/models', $this->model_prefix); + } + + // Set the default view search path + if (array_key_exists('view_path', $config)) { + // User-defined dirs + $this->setPath('view', $config['view_path']); + } else { + $this->setPath('view', $this->basePath . '/views'); + } + + // Set the default view. + if (array_key_exists('default_view', $config)) { + $this->default_view = $config['default_view']; + } elseif (empty($this->default_view)) { + $this->default_view = $this->getName(); + } + + /** JControllerForm */ + // Guess the option as com_NameOfController + if (empty($this->option)) { + $this->option = 'com_' . strtolower($this->getName()); + } + + // Guess the JText message prefix. Defaults to the option. + if (empty($this->text_prefix)) { + $this->text_prefix = strtoupper($this->option); + } + + // Guess the context as the suffix, eg: OptionControllerContent. + if (empty($this->context)) { + $r = null; + + if (!preg_match('/(.*)Controller(.*)/i', get_class($this), $r)) { + throw new Exception(JText::_('JLIB_APPLICATION_ERROR_CONTROLLER_GET_NAME'), 500); + } + + $this->context = strtolower($r[2]); + } + + // Apply, Save & New, and Save As copy should be standard on forms. + $this->registerTask('apply', 'save'); + $this->registerTask('save2new', 'save'); + $this->registerTask('save2copy', 'save'); + + /** Custom */ + // Guess the item view as the context. + if (empty($this->view_item)) { + $this->view_item = $this->context; + } + + if (empty($this->view_list)) { + $this->view_list = Inflector::pluralize($this->view_item); + } + + if (!property_exists($this, 'input') || empty($this->input)) { + $this->input = JFactory::getApplication()->input; + } + } + + /** + * Method to cancel an edit. + * + * @param string $key The name of the primary key of the URL variable. + * + * @return boolean True if access level checks pass, false otherwise. + */ + public function cancel($key = null) + { + JSession::checkToken() or jexit(JText::_('INVALID_TOKEN')); + + $app = JFactory::getApplication(); + $model = $this->getModel(); + $table = $model->getTable(); + $checkin = property_exists($table, 'checked_out'); + $context = "$this->option.edit.$this->context"; + + if (empty($key)) { + $key = $table->getKeyName(); + } + + $recordId = $app->input->getInt($key); + + // Attempt to check-in the current record. + if ($recordId) { + // Check we are holding the id in the edit list. + if (!$this->checkEditId($context, $recordId)) { + // Somehow the person just went to the form - we don't allow that. + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $recordId)); + $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); + + // Redirect to the list screen + $this->setRedirect( + $this->getRedirectToListRoute($this->getRedirectToListAppend()) + ); + + return false; + } + + if ($checkin) { + if ($model->checkin($recordId) === false) { + // Check-in failed, go back to the record and display a notice. + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError())); + $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); + + // Redirect back to the edit screen. + $this->setRedirect( + $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $key)) + ); + + return false; + } + } + } + + // Clean the session data and redirect. + $this->releaseEditId($context, $recordId); + $app->setUserState($context . '.data', null); + + // Redirect to the list screen + $this->setRedirect( + $this->getRedirectToListRoute($this->getRedirectToListAppend()) + ); + + return true; + } + + /** + * Method to get a model object, loading it if required. + * + * @param string $name The model name. Optional. + * @param string $prefix The class prefix. Optional. + * @param array $config Configuration array for model. Optional. + * + * @return object The model. + */ + public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true)) + { + $class = get_class($this); + + if (empty($name)) { + $name = strstr($class, 'Controller'); + $name = str_replace('Controller', '', $name); + } + + if (empty($prefix)) { + $prefix = strstr($class, 'Controller', true) . 'Model'; + } + + return parent::getModel($name, $prefix, $config); + } + + /** + * Get the JRoute object for a redirect to list. + * + * @param string $append An optional string to append to the route + * + * @return string + */ + protected function getRedirectToListRoute($append = null) + { + $returnUrl = $this->input->get('return', '', 'Base64'); + + if ($returnUrl) { + $returnUrl = base64_decode($returnUrl); + + return JRoute::_($returnUrl . $append, false); + } + + return JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list . $append, false); + } + + /** + * Gets the URL arguments to append to a list redirect. + * + * @return string The arguments to append to the redirect URL. + */ + protected function getRedirectToListAppend() + { + $append = parent::getRedirectToListAppend(); + + $return = $this->input->get('return', '', 'Base64'); + + if ($return) { + $append .= '&return=' . $return; + } + + return $append; + } + + /** + * Get the JRoute object for a redirect to item. + * + * @param string $append An optionnal string to append to the route + * + * @return string The url string + */ + protected function getRedirectToItemRoute($append = null) + { + return JRoute::_( + 'index.php?option=' . $this->option . '&view=' . $this->view_item + . $append, + false + ); + } + + /** + * Gets the URL arguments to append to an item redirect. + * + * @param integer $recordId The primary key id for the item. + * @param string $urlVar The name of the URL variable for the id. + * + * @return string The arguments to append to the redirect URL. + */ + protected function getRedirectToItemAppend($recordId = null, $urlVar = 'id') + { + $append = parent::getRedirectToItemAppend($recordId, $urlVar); + + $return = $this->input->get('return', '', 'Base64'); + + if ($return) { + $append .= '&return=' . $return; + } + + return $append; + } + + /** + * Method to edit an existing record. + * + * @param string $key The name of the primary key of the URL variable. + * @param string $urlVar The name of the URL variable if different from the primary key + * (sometimes required to avoid router collisions). + * + * @return boolean True if access level check and checkout passes, false otherwise. + */ + public function edit($key = null, $urlVar = null) + { + $app = JFactory::getApplication(); + $model = $this->getModel(); + $table = $model->getTable(); + $cid = $this->input->post->get('cid', array(), 'array'); + $context = "$this->option.edit.$this->context"; + + // Determine the name of the primary key for the data. + if (empty($key)) { + $key = $table->getKeyName(); + } + + // To avoid data collisions the urlVar may be different from the primary key. + if (empty($urlVar)) { + $urlVar = $key; + } + + // Get the previous record id (if any) and the current record id. + $recordId = (int)(count($cid) ? $cid[0] : $this->input->getInt($urlVar)); + $checkin = property_exists($table, 'checked_out'); + + // Access check. + if (!$this->allowEdit(array($key => $recordId), $key)) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('JLIB_APPLICATION_ERROR_EDIT_NOT_PERMITTED')); + $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); + + // Redirect to the list screen + $this->setRedirect( + $this->getRedirectToListRoute($this->getRedirectToListAppend()) + ); + + return false; + } + + // Attempt to check-out the new record for editing and redirect. + if ($checkin && !$model->checkout($recordId)) { + // Check-out failed, display a notice but allow the user to see the record. + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKOUT_FAILED', $model->getError())); + $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); + + // Redirect back to the edit screen. + $this->setRedirect( + $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) + ); + + return false; + } else { + // Check-out succeeded, push the new record id into the session. + $this->holdEditId($context, $recordId); + $app->setUserState($context . '.data', null); + + // Redirect back to the edit screen. + $this->setRedirect( + $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) + ); + + return true; + } + } + + /** + * Method to add a new record. + * + * @return mixed True if the record can be added, a error object if not. + */ + public function add() + { + $app = JFactory::getApplication(); + $context = "$this->option.edit.$this->context"; + + // Access check. + if (!$this->allowAdd()) { + // Set the internal error and also the redirect error. + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('JLIB_APPLICATION_ERROR_CREATE_RECORD_NOT_PERMITTED')); + $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); + + // Redirect to the list screen + $this->setRedirect( + $this->getRedirectToListRoute($this->getRedirectToListAppend()) + ); + + return false; + } + + // Clear the record edit information from the session. + $app->setUserState($context . '.data', null); + + // Redirect back to the edit screen. + $this->setRedirect( + $this->getRedirectToItemRoute($this->getRedirectToItemAppend()) + ); + + return true; + } + + /** + * Method to save a record. + * + * @param string $key The name of the primary key of the URL variable. + * @param string $urlVar The name of the URL variable if different from the primary key (sometimes required to avoid router collisions). + * + * @return boolean True if successful, false otherwise. + * @throws Exception + */ + public function save($key = null, $urlVar = null) + { + // Check for request forgeries. + JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); + + $app = JFactory::getApplication(); + $lang = JFactory::getLanguage(); + $model = $this->getModel(); + $table = $model->getTable(); + $data = $this->input->post->get('jform', array(), 'array'); + $checkin = property_exists($table, 'checked_out'); + $context = "$this->option.edit.$this->context"; + $task = $this->getTask(); + + // Determine the name of the primary key for the data. + if (null === $key) { + $key = $table->getKeyName(); + } + + // To avoid data collisions the urlVar may be different from the primary key. + if (null === $urlVar) { + $urlVar = $key; + } + + if (isset($data['start_date']) && isset($data['end_date'])) { + $this->handleDateTimeRange($data['start_date'], $data['end_date']); + } + + $recordId = $this->input->getInt($urlVar); + + if (!$this->checkEditId($context, $recordId)) { + // Somehow the person just went to the form and tried to save it. We don't allow that. + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $recordId)); + $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); + + // Redirect to the list screen + $this->setRedirect( + $this->getRedirectToListRoute($this->getRedirectToListAppend()) + ); + + return false; + } + + // Populate the row id from the session. + $data[$key] = $recordId; + + // The save2copy task needs to be handled slightly differently. + if ($task === 'save2copy') { + // Check-in the original row. + if ($checkin && $model->checkin($data[$key]) === false) { + // Check-in failed. Go back to the item and display a notice. + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError())); + $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); + + // Redirect back to the edit screen. + $this->setRedirect( + $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) + ); + + return false; + } + + // Reset the ID, the multilingual associations and then treat the request as for Apply. + $data[$key] = 0; + $data['associations'] = array(); + $task = 'apply'; + } + + // Access check. + if (!$this->allowSave($data, $key)) { + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::_('JLIB_APPLICATION_ERROR_SAVE_NOT_PERMITTED')); + $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); + + // Redirect to the list screen + $this->setRedirect( + $this->getRedirectToListRoute($this->getRedirectToListAppend()) + ); + + return false; + } + + // Validate the posted data. + // Sometimes the form needs some posted data, such as for plugins and modules. + $form = $model->getForm($data, false); + + if (!$form) { + $app->enqueueMessage($model->getError(), 'error'); + + return false; + } + + // Test whether the data is valid. + $validData = $model->validate($form, $data); + + // Check for validation errors. + if ($validData === false) { + // Get the validation messages. + $errors = $model->getErrors(); + + // Push up to three validation messages out to the user. + for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) { + if ($errors[$i] instanceof Exception) { + $app->enqueueMessage($errors[$i]->getMessage(), 'error'); + } else { + $app->enqueueMessage($errors[$i], 'error'); + } + } + + // Save the data in the session. + $app->setUserState($context . '.data', $data); + + // Redirect back to the edit screen. + $this->setRedirect( + $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) + ); + + return false; + } + + if (!isset($validData['tags'])) { + $validData['tags'] = null; + } + + // Attempt to save the data. + if (!$model->save($validData)) { + // Save the data in the session. + $app->setUserState($context . '.data', $validData); + + // Redirect back to the edit screen. + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError())); + $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); + + // Redirect back to the edit screen. + $this->setRedirect( + $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) + ); + + return false; + } + + // Save succeeded, so check-in the record. + if ($checkin && $model->checkin($validData[$key]) === false) { + // Save the data in the session. + $app->setUserState($context . '.data', $validData); + + // Check-in failed, so go back to the record and display a notice. + /** @scrutinizer ignore-deprecated */ + $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError())); + $this->setMessage(/** @scrutinizer ignore-deprecated */ $this->getError(), 'error'); + + // Redirect back to the edit screen. + $this->setRedirect( + $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) + ); + + return false; + } + + $this->setMessage( + JText::_( + ($lang->hasKey( + $this->text_prefix . ($recordId == 0 && $app->isClient('site') ? '_SUBMIT' : '') . '_SAVE_SUCCESS' + ) + ? $this->text_prefix + : 'JLIB_APPLICATION') . ($recordId == 0 && $app->isClient( + 'site' + ) ? '_SUBMIT' : '') . '_SAVE_SUCCESS' + ) + ); + + // Redirect the user and adjust session state based on the chosen task. + switch ($task) { + case 'apply': + // Set the record data in the session. + $recordId = $model->getState($this->context . '.id'); + $this->holdEditId($context, $recordId); + $app->setUserState($context . '.data', null); + $model->checkout($recordId); + + // Redirect back to the edit screen. + $this->setRedirect( + $this->getRedirectToItemRoute($this->getRedirectToItemAppend($recordId, $urlVar)) + ); + break; + + case 'save2new': + // Clear the record id and data from the session. + $this->releaseEditId($context, $recordId); + $app->setUserState($context . '.data', null); + + // Redirect back to the edit screen. + $this->setRedirect( + $this->getRedirectToItemRoute($this->getRedirectToItemAppend(null, $urlVar)) + ); + break; + + default: + // Clear the record id and data from the session. + $this->releaseEditId($context, $recordId); + $app->setUserState($context . '.data', null); + + // Set redirect + $this->setRedirect( + $this->getRedirectToListRoute($this->getRedirectToListAppend()) + ); + break; + } + + // Invoke the postSave method to allow for the child class to access the model. + $this->postSaveHook($model, $validData); + + return true; + } } diff --git a/libraries/redshop/entities/collection.php b/libraries/redshop/entities/collection.php index 1a01f64374e..39478619c7d 100644 --- a/libraries/redshop/entities/collection.php +++ b/libraries/redshop/entities/collection.php @@ -16,241 +16,236 @@ */ class RedshopEntitiesCollection implements Countable, Iterator { - /** - * @var array - */ - protected $entities = array(); - - /** - * Constructor. - * - * @param array $entities Entities to initialise the collection - */ - public function __construct(array $entities = array()) - { - $this->entities = $entities; - } - - /** - * Adds an entity to the collection. It won't add any entity that already exists - * - * @param RedshopEntity $entity Entity going to be added - * - * @return self - */ - public function add(RedshopEntity $entity) - { - if ($entity->hasId() && !$this->has($entity->getId())) - { - $this->entities[$entity->getId()] = $entity; - } - - return $this; - } - - /** - * Clears the entities of the collection - * - * @return self - */ - public function clear() - { - $this->entities = array(); - - return $this; - } - - /** - * Gets the count of entities in this collection - * - * @return integer - */ - public function count() - { - return count($this->entities); - } - - /** - * Get the active entity. - * Iterator implementation. - * - * @return mixed RedshopEntity | FALSE if no entities - */ - public function current() - { - return current($this->entities); - } - - /** - * Get an item by it's id - * - * @param integer $id Item's identifier - * - * @return mixed RedshopEntity if item exists. Null otherwise - */ - public function get($id) - { - if ($this->has($id)) - { - return $this->entities[$id]; - } - - return null; - } - - /** - * Gets all the entities - * - * @return array - */ - public function getAll() - { - return $this->entities; - } - - /** - * Check if an entity is already in this collection - * - * @param integer $id Entity identifier - * - * @return boolean - */ - public function has($id) - { - return isset($this->entities[$id]); - } - - /** - * Returns ids of the entities in the collection - * - * @return array - */ - public function ids() - { - return array_keys($this->entities); - } - - /** - * Check if the collection is empty - * - * @return boolean - */ - public function isEmpty() - { - return !$this->entities; - } - - /** - * Return the id of the active entity. - * Iterator implementation. - * - * @return mixed integer | FALSE if no entities - */ - public function key() - { - return key($this->entities); - } - - /** - * Gets the next entity. - * Iterator implementation. - * - * @return mixed RedshopEntity | FALSE if no entities - */ - public function next() - { - return next($this->entities); - } - - /** - * Removes an item from the collection - * - * @param integer $id Entity identifier - * - * @return boolean - */ - public function remove($id) - { - if (!$this->has($id)) - { - return false; - } - - unset($this->entities[$id]); - - return true; - } - - /** - * Method to get the first entity. - * Iterator implementation. - * - * @return mixed RedshopEntity | FALSE if no entities - */ - public function rewind() - { - return reset($this->entities); - } - - /** - * Sets an item. This removes previous item if it already exists - * - * @param integer $id Entity identifier - * @param RedshopEntity $entity Entity - * - * @return self - */ - public function set($id, RedshopEntity $entity) - { - $this->entities[$id] = $entity; - - return $this; - } - - /** - * Return entities as stdClass objects - * - * @return array An array of stdClass objects - */ - public function toObjects() - { - $objects = array(); - - foreach ($this->entities as $id => $entity) - { - $objects[$id] = $entity->getItem(); - } - - return $objects; - } - - /** - * Return entities as an array of a single field - * - * @param string $fieldName Name of the field to return in the array - * - * @return array An array of fields - */ - public function toFieldArray($fieldName) - { - $fields = array(); - - foreach ($this->entities as $id => $entity) - { - $fields[] = $entity->getItem()->$fieldName; - } - - return $fields; - } - - /** - * Check if there are still entities in the entities array. - * Iterator implementation. - * - * @return boolean - */ - public function valid() - { - return key($this->entities) !== null; - } + /** + * @var array + */ + protected $entities = array(); + + /** + * Constructor. + * + * @param array $entities Entities to initialise the collection + */ + public function __construct(array $entities = array()) + { + $this->entities = $entities; + } + + /** + * Adds an entity to the collection. It won't add any entity that already exists + * + * @param RedshopEntity $entity Entity going to be added + * + * @return self + */ + public function add(RedshopEntity $entity) + { + if ($entity->hasId() && !$this->has($entity->getId())) { + $this->entities[$entity->getId()] = $entity; + } + + return $this; + } + + /** + * Check if an entity is already in this collection + * + * @param integer $id Entity identifier + * + * @return boolean + */ + public function has($id) + { + return isset($this->entities[$id]); + } + + /** + * Clears the entities of the collection + * + * @return self + */ + public function clear() + { + $this->entities = array(); + + return $this; + } + + /** + * Gets the count of entities in this collection + * + * @return integer + */ + public function count() + { + return count($this->entities); + } + + /** + * Get the active entity. + * Iterator implementation. + * + * @return mixed RedshopEntity | FALSE if no entities + */ + public function current() + { + return current($this->entities); + } + + /** + * Get an item by it's id + * + * @param integer $id Item's identifier + * + * @return mixed RedshopEntity if item exists. Null otherwise + */ + public function get($id) + { + if ($this->has($id)) { + return $this->entities[$id]; + } + + return null; + } + + /** + * Gets all the entities + * + * @return array + */ + public function getAll() + { + return $this->entities; + } + + /** + * Returns ids of the entities in the collection + * + * @return array + */ + public function ids() + { + return array_keys($this->entities); + } + + /** + * Check if the collection is empty + * + * @return boolean + */ + public function isEmpty() + { + return !$this->entities; + } + + /** + * Return the id of the active entity. + * Iterator implementation. + * + * @return mixed integer | FALSE if no entities + */ + public function key() + { + return key($this->entities); + } + + /** + * Gets the next entity. + * Iterator implementation. + * + * @return mixed RedshopEntity | FALSE if no entities + */ + public function next() + { + return next($this->entities); + } + + /** + * Removes an item from the collection + * + * @param integer $id Entity identifier + * + * @return boolean + */ + public function remove($id) + { + if (!$this->has($id)) { + return false; + } + + unset($this->entities[$id]); + + return true; + } + + /** + * Method to get the first entity. + * Iterator implementation. + * + * @return mixed RedshopEntity | FALSE if no entities + */ + public function rewind() + { + return reset($this->entities); + } + + /** + * Sets an item. This removes previous item if it already exists + * + * @param integer $id Entity identifier + * @param RedshopEntity $entity Entity + * + * @return self + */ + public function set($id, RedshopEntity $entity) + { + $this->entities[$id] = $entity; + + return $this; + } + + /** + * Return entities as stdClass objects + * + * @return array An array of stdClass objects + */ + public function toObjects() + { + $objects = array(); + + foreach ($this->entities as $id => $entity) { + $objects[$id] = $entity->getItem(); + } + + return $objects; + } + + /** + * Return entities as an array of a single field + * + * @param string $fieldName Name of the field to return in the array + * + * @return array An array of fields + */ + public function toFieldArray($fieldName) + { + $fields = array(); + + foreach ($this->entities as $id => $entity) { + $fields[] = $entity->getItem()->$fieldName; + } + + return $fields; + } + + /** + * Check if there are still entities in the entities array. + * Iterator implementation. + * + * @return boolean + */ + public function valid() + { + return key($this->entities) !== null; + } } diff --git a/libraries/redshop/entity/accessory.php b/libraries/redshop/entity/accessory.php index 0f9345ca585..bfb6e25eea4 100644 --- a/libraries/redshop/entity/accessory.php +++ b/libraries/redshop/entity/accessory.php @@ -18,15 +18,15 @@ */ class RedshopEntityAccessory extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Accessory_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Accessory_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/account_group.php b/libraries/redshop/entity/account_group.php index 17527d975b7..b2295edd970 100644 --- a/libraries/redshop/entity/account_group.php +++ b/libraries/redshop/entity/account_group.php @@ -18,15 +18,15 @@ */ class RedshopEntityAccount_Group extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Accountgroup_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Accountgroup_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/attribute_price.php b/libraries/redshop/entity/attribute_price.php index 804b8d52e8e..a6dce5c0947 100644 --- a/libraries/redshop/entity/attribute_price.php +++ b/libraries/redshop/entity/attribute_price.php @@ -18,15 +18,15 @@ */ class RedshopEntityAttribute_Price extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('AttributePrices_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('AttributePrices_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/attribute_set.php b/libraries/redshop/entity/attribute_set.php index b821021f0aa..f8bd86ea3a5 100644 --- a/libraries/redshop/entity/attribute_set.php +++ b/libraries/redshop/entity/attribute_set.php @@ -18,15 +18,15 @@ */ class RedshopEntityAttribute_Set extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Attribute_Set_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Attribute_Set_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/base.php b/libraries/redshop/entity/base.php index c53843f8ba1..c52ab70936d 100644 --- a/libraries/redshop/entity/base.php +++ b/libraries/redshop/entity/base.php @@ -19,969 +19,913 @@ */ abstract class RedshopEntityBase extends BaseObject { - /** - * @const integer - * @since 1.0 - */ - const STATE_ENABLED = 1; - - /** - * @const integer - * @since 1.0 - */ - const STATE_DISABLED = 0; - - /** - * ACL prefix used to check permissions - * - * @var string - * @since 1.0 - */ - protected $aclPrefix = "core"; - - /** - * Identifier of the loaded instance - * - * @var mixed - */ - protected $id = null; - - /** - * Cached instances - * - * @var array - */ - protected static $instances = array(); - - /** - * Cached table. - * - * @var JTable - */ - protected $table; - - /** - * Option of the component containing the tables. Example: com_content - * - * @var string - */ - protected $component; - - /** - * Translations for items that support them - * - * @var array - */ - protected $translations = array(); - - /** - * Table primary key for load item. - * - * @var string - */ - protected $tableKey = null; - - /** - * Constructor - * - * @param mixed $id Identifier of the active item - */ - public function __construct($id = null) - { - if ($id) - { - $this->id = $id; - } - - if (null === $this->tableKey) - { - $this->tableKey = false !== $this->getTable() ? $this->getTable()->getKeyName() : 'id'; - } - } - - /** - * Bind an object/array to the entity - * - * @param mixed $item Array/Object containing the item fields - * - * @return $this - */ - public function bind($item) - { - // Accept basic array binding - if (is_array($item)) - { - $item = (object) $item; - } - - $this->item = $item; - - if (property_exists($item, 'id')) - { - $this->id = $item->id; - - $class = get_called_class(); - - // Ensure that we cache the item - if (!isset(static::$instances[$class][$this->id])) - { - static::$instances[$class][$this->id] = $this; - } - } - - return $this; - } - - /** - * Check if current user can create an item - * - * @return boolean - * - * @since 1.0 - */ - public function canCreate() - { - if ($this->canDo($this->getAclPrefix() . '.create')) - { - return true; - } - - if ($this->canDo($this->getAclPrefix() . '.create.own')) - { - return $this->isOwner(); - } - - return false; - } - - /** - * Check if current user can delete an item - * - * @return boolean - */ - public function canDelete() - { - if (!$this->hasId()) - { - return false; - } - - if ($this->canDo($this->getAclPrefix() . '.delete')) - { - return true; - } - - if ($this->canDo($this->getAclPrefix() . '.delete.own')) - { - return $this->isOwner(); - } - - return false; - } - - /** - * Check if current user can edit this item - * - * @return boolean - */ - public function canEdit() - { - if (!$this->hasId()) - { - return false; - } - - // User has global edit permissions - if ($this->canDo($this->getAclPrefix() . '.edit')) - { - return true; - } - - // User has global edit permissions - if ($this->canDo($this->getAclPrefix() . '.edit.own')) - { - return $this->isOwner(); - } - - return false; - } - - /** - * Check if current user has permission to perform an action - * - * @param string $action The action. Example: core.create - * - * @return boolean - */ - public function canDo($action) - { - $user = JFactory::getUser(); - - return $user->authorise($action, $this->getAssetName()); - } - - /** - * Check if user can view this item. - * - * @return boolean - * - * @since 1.0 - */ - public function canView() - { - $item = $this->getItem(); - - if (!$item) - { - return false; - } - - return ((int) $item->state === static::STATE_ENABLED || $this->isOwner()); - } - - /** - * Remove an instance from cache - * - * @param integer $id Identifier of the active item - * - * @return void - */ - public static function clearInstance($id = null) - { - $class = get_called_class(); - - unset(static::$instances[$class][$id]); - } - - /** - * Format a link - * - * @param string $url Url to format - * @param boolean $routed Process Url through JRoute? - * @param boolean $xhtml Replace & by & for XML compliance. - * - * @return string - */ - protected function formatUrl($url, $routed = true, $xhtml = true) - { - if (!$url) - { - return null; - } - - if (!$routed) - { - return $url; - } - - return JRoute::_($url, $xhtml); - } - - /** - * Get an item property - * - * @param string $property Property to get - * @param mixed $default Default value to assign if property === null | property === '' - * - * @return string - */ - public function get($property, $default = null) - { - $item = $this->getItem(); - - if (!empty($item) && property_exists($item, $property)) - { - return ($item->$property !== null && $item->$property !== '') ? $item->$property : $default; - } - - return $default; - } - - /** - * Set an item property - * - * @param string $property Property to get - * @param mixed $data Data for set to property - * - * @return self - */ - public function set($property, $data = null) - { - if (null === $this->item) - { - $this->loadItem(); - } - - $this->item->{$property} = $data; - - return $this; - } - - /** - * Get the ACL prefix applied to this class - * - * @return string - * - * @since 1.0 - */ - public function getAclPrefix() - { - return $this->aclPrefix; - } - - /** - * Get the item add link - * - * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid - * @param boolean $routed Process URL with JRoute? - * @param boolean $xhtml Replace & by & for XML compliance. - * - * @return string - */ - public function getAddLink($itemId = 'inherit', $routed = true, $xhtml = true) - { - $url = $this->getBaseUrl() . '&task=' . $this->getInstanceName() . '.add' . $this->getLinkItemIdString($itemId); - - return $this->formatUrl($url, $routed, $xhtml); - } - - /** - * Get the item add link with a return link to the current page. - * - * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid - * @param boolean $routed Process URL with JRoute? - * @param boolean $xhtml Replace & by & for XML compliance. - * - * @return string - */ - public function getAddLinkWithReturn($itemId = 'inherit', $routed = true, $xhtml = true) - { - $url = $this->getAddLink($itemId, false, false) . '&return=' . base64_encode(JUri::getInstance()->toString()); - - return $this->formatUrl($url, $routed, $xhtml); - } - - /** - * Get the identifier of the project asset - * - * @return string - */ - protected function getAssetName() - { - if ($this->hasId()) - { - return $this->getComponent() . '.' . $this->getInstanceName() . '.' . $this->id; - } - - // Use the global permissions - return $this->getComponent(); - } - - /** - * Gets the base URL for tasks/views. - * - * Example: index.php?option=com_redshopb&view=shop - * - * @return string - */ - protected function getBaseUrl() - { - return 'index.php?option=' . $this->getComponent() . '&view=' . $this->getInstanceName(); - } - - /** - * Get the component that contains the tables - * - * @return string - */ - protected function getComponent() - { - if (null === $this->component) - { - $this->component = $this->getComponentFromPrefix(); - } - - return $this->component; - } - - /** - * Get the component from the prefix. Ex.: ContentEntityArticle will return com_content - * - * @return string - */ - protected function getComponentFromPrefix() - { - return 'com_' . $this->getPrefix(); - } - - /** - * Get an entity date field formatted - * - * @param string $itemProperty Item property containing the date - * @param string $format Desired date format - * @param boolean $translateFormat Translate the format for multilanguage purposes - * - * @return string - */ - public function getDate($itemProperty, $format = 'DATE_FORMAT_LC1', $translateFormat = true) - { - $item = $this->getItem(); - - if (!$item || !property_exists($item, $itemProperty)) - { - return null; - } - - if ($format && $translateFormat) - { - $format = JText::_($format); - } - - return JHtml::_('date', $item->{$itemProperty}, $format); - } - - /** - * Local proxy for JFactory::getDbo() - * - * @return JDatabaseDriver - */ - protected function getDbo() - { - return JFactory::getDbo(); - } - - /** - * Get the item delete link - * - * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid - * @param boolean $routed Process URL with JRoute? - * @param boolean $xhtml Replace & by & for XML compliance. - * - * @return string - */ - public function getDeleteLink($itemId = 'inherit', $routed = true, $xhtml = true) - { - if (!$this->hasId()) - { - return null; - } - - $urlToken = '&' . JSession::getFormToken() . '=1'; - - $url = $this->getBaseUrl() . '&task=' . $this->getInstanceName() - . '.delete&id=' . $this->getSlug() . $urlToken . $this->getLinkItemIdString($itemId); - - return $this->formatUrl($url, $routed, $xhtml); - } - - /** - * Get the item delete link with a return link to the current page. - * - * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid - * @param boolean $routed Process URL with JRoute? - * @param boolean $xhtml Replace & by & for XML compliance. - * - * @return string - */ - public function getDeleteLinkWithReturn($itemId = 'inherit', $routed = true, $xhtml = true) - { - if (!$this->hasId()) - { - return null; - } - - $url = $this->getDeleteLink($itemId, false, false) . '&return=' . base64_encode(JUri::getInstance()->toString()); - - return $this->formatUrl($url, $routed, $xhtml); - } - - /** - * Get the item edit link - * - * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid - * @param boolean $routed Process URL with JRoute? - * @param boolean $xhtml Replace & by & for XML compliance. - * - * @return string - */ - public function getEditLink($itemId = 'inherit', $routed = true, $xhtml = true) - { - if (!$this->hasId()) - { - return null; - } - - $url = $this->getBaseUrl() . '&task=' . $this->getInstanceName() - . '.edit&id=' . $this->getSlug() . $this->getLinkItemIdString($itemId); - - return $this->formatUrl($url, $routed, $xhtml); - } - - /** - * Get the item edit link with a return link to the current page. - * - * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid - * @param boolean $routed Process URL with JRoute? - * @param boolean $xhtml Replace & by & for XML compliance. - * - * @return string - * - * @since 1.0 - */ - public function getEditLinkWithReturn($itemId = 'inherit', $routed = true, $xhtml = true) - { - if (!$this->hasId()) - { - return null; - } - - $url = $this->getEditLink($itemId, false, false) . '&return=' . base64_encode(JUri::getInstance()->toString()); - - return $this->formatUrl($url, $routed, $xhtml); - } - - /** - * Create and return a cached instance - * - * @param integer $id Identifier of the active item - * - * @return $this - */ - public static function getInstance($id = null) - { - if (null === $id) - { - return new static; - } - - $class = get_called_class(); - - if (empty(static::$instances[$class][$id])) - { - static::$instances[$class][$id] = new static($id); - } - - return static::$instances[$class][$id]; - } - - /** - * Create and return a cached instance by a different field of the table (UID) - * - * @param string $fieldName Field to use - * @param string $fieldValue Key value - * - * @return $this - */ - public static function getInstanceByField($fieldName, $fieldValue) - { - $instance = static::getInstance(); - - return $instance->loadItem($fieldName, $fieldValue); - } - - /** - * Get the name of the current entity type - * - * @return string - */ - public function getInstanceName() - { - $class = get_class($this); - - $name = strstr($class, 'Entity'); - $name = str_replace('Entity', '', $name); - - return strtolower($name); - } - - /** - * Get the id - * - * @return integer | null - */ - public function getId() - { - return $this->id; - } - - /** - * Get item from the database - * - * @return mixed Object / null - */ - public function getItem() - { - if (empty($this->item)) - { - $this->loadItem(); - } - - return $this->item; - } - - /** - * Get the item link - * - * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid - * @param boolean $routed Process URL with JRoute? - * @param boolean $xhtml Replace & by & for XML compliance. - * - * @return string - */ - public function getLink($itemId = 'inherit', $routed = true, $xhtml = true) - { - if (!$this->hasId()) - { - return null; - } - - $url = $this->getBaseUrl() . '&id=' . $this->getSlug() . $this->getLinkItemIdString($itemId); - - return $this->formatUrl($url, $routed, $xhtml); - } - - /** - * Generate the Itemid string part for URLs - * - * @param mixed $itemId inherit or desired itemId. Use 0 to not inherit active itemId - * - * @return string - */ - protected function getLinkItemIdString($itemId = 'inherit') - { - return ($itemId !== 'inherit') ? '&Itemid=' . (int) $itemId : null; - } - - /** - * Get the prefix of this entity. - * - * @return string - * - * @since 2.0 - */ - protected function getPrefix() - { - $class = get_class($this); - - return strtolower(strstr($class, 'Entity', true)); - } - - /** - * Generate the item slug for URLs - * - * @return string - */ - protected function getSlug() - { - $item = $this->getItem(); - - if (!$item) - { - return $this->hasId() ? $this->id : null; - } - - return !empty($item->alias) ? $this->id . '-' . $item->alias : $this->id; - } - - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - if (null === $name) - { - $class = get_class($this); - $name = strstr($class, 'Entity'); - } - - $name = str_replace('Entity', '', $name); - - return RedshopTable::getAdminInstance($name, array(), $this->getComponent()); - } - - /** - * Check if we have an identifier loaded - * - * @return boolean - */ - public function hasId() - { - $id = (int) $this->id; - - return !empty($id); - } - - /** - * Check if item has been loaded - * - * @return boolean - */ - public function isLoaded() - { - return ($this->hasId() && $this->item !== null); - } - - /** - * Check if current member is owner - * - * @return boolean - * - * @since 1.0 - */ - public function isOwner() - { - if (!$this->hasId()) - { - return false; - } - - $user = JFactory::getUser(); - - if ($user->get('guest')) - { - return false; - } - - $item = $this->getItem(); - - if (!$item) - { - return false; - } - - return ($item->created_by == $user->get('id')); - } - - /** - * Basic instance check: has id + loadable item - * - * @return boolean - */ - public function isValid() - { - if (!$this->hasId()) - { - return false; - } - - $item = $this->getItem(); - - return !empty($item); - } - - /** - * Load a cached instance and ensure that the item is loaded - * - * @param integer $id Identifier of the active item - * - * @return self - */ - public static function load($id = null) - { - $instance = static::getInstance($id); - - if (!$instance->isLoaded()) - { - $instance->loadItem(); - } - - return $instance; - } - - /** - * Load the item already loaded in a table - * - * @param RedshopTable|JTable $table Table with the item loaded - * - * @return self - */ - public function loadFromTable($table) - { - $key = $table->getKeyName(); - - if (!empty($table->{$key})) - { - // Get the data from the table - if (method_exists($table, 'getTableProperties')) - { - // Redshopb method to get only public properties - $data = $table->getTableProperties(); - } - else - { - // Fallback for every other JTable (not redshopb tables) - $data = $table->getProperties(true); - } - - // Item is always an object - $this->item = ArrayHelper::toObject($data); - - $this->id = $table->{$key}; - $this->table = clone $table; - - $class = get_called_class(); - - // Ensure that we cache the item - if (!isset(static::$instances[$class][$this->id]) || !static::$instances[$class][$this->id]->isLoaded()) - { - static::$instances[$class][$this->id] = $this; - } - } - - return $this; - } - - /** - * Default loading is trying to use the associated table - * - * @param string $key Field name used as key - * @param string $keyValue Value used if it's not the $this->id property of the instance - * - * @return self - */ - public function loadItem($key = null, $keyValue = null) - { - $key = null === $key ? $this->tableKey : $key; - - if ($key === $this->tableKey && !$this->hasId()) - { - return $this; - } - - $table = $this->getTable(); - - if (false !== $table && $table->load(array($key => ($key === $this->tableKey ? $this->id : $keyValue)))) - { - $this->loadFromTable($table); - } - - return $this; - } - - /** - * @param array $data Data - * - * @return self - */ - public function loadItemByArray($data) - { - $table = $this->getTable(); - - if (false === $table) - { - return $this; - } - - if ($table->load($data)) - { - $this->loadFromTable($table); - } - - return $this; - } - - /** - * Try to directly save the entity using the associated table - * - * @param mixed $item Object / Array to save. Null = try to store current item - * - * @return boolean|integer The item id - * - * @since 1.0 - */ - public function save($item = null) - { - if (!$this->processBeforeSaving($item)) - { - return false; - } - - if (null === $item) - { - $item = $this->getItem(); - } - - if (!$item) - { - JLog::add("Nothing to save", JLog::ERROR, 'entity'); - - return false; - } - - try - { - $table = $this->getTable(); - } - catch (Exception $exception) - { - JLog::add("Table for instance " . $this->getInstanceName() . " could not be loaded", JLog::ERROR, 'entity'); - - return false; - } - - if (!$table->save((array) $item)) - { - JLog::add($table->getError(), JLog::ERROR, 'entity'); - - return false; - } - - // Force entity reload / save to cache - static::clearInstance($this->id); - static::loadFromTable($table); - - $this->processAfterSaving($table); - - return $table->{$table->getKeyName()}; - } - - /** - * Method for reset this static for load new data. - * - * @return self - * - * @since 2.0.6 - */ - public function reset() - { - if (!$this->isLoaded()) - { - return $this; - } - - $class = get_called_class(); - $id = $this->getId(); - - unset(static::$instances[$class][$id]); - - return static::getInstance($id); - } - - /** - * Process $item data before saving. - * - * @param mixed $item Array / Object of data. - * - * @return boolean Return false will break save process - */ - public function processBeforeSaving(&$item) - { - return true; - } - - /** - * Process data after saving. - * - * @param JTable $table JTable instance data. - * - * @return boolean - */ - public function processAfterSaving(&$table) - { - return true; - } + /** + * @const integer + * @since 1.0 + */ + const STATE_ENABLED = 1; + + /** + * @const integer + * @since 1.0 + */ + const STATE_DISABLED = 0; + /** + * Cached instances + * + * @var array + */ + protected static $instances = array(); + /** + * ACL prefix used to check permissions + * + * @var string + * @since 1.0 + */ + protected $aclPrefix = "core"; + /** + * Identifier of the loaded instance + * + * @var mixed + */ + protected $id = null; + /** + * Cached table. + * + * @var JTable + */ + protected $table; + + /** + * Option of the component containing the tables. Example: com_content + * + * @var string + */ + protected $component; + + /** + * Translations for items that support them + * + * @var array + */ + protected $translations = array(); + + /** + * Table primary key for load item. + * + * @var string + */ + protected $tableKey = null; + + /** + * Constructor + * + * @param mixed $id Identifier of the active item + */ + public function __construct($id = null) + { + if ($id) { + $this->id = $id; + } + + if (null === $this->tableKey) { + $this->tableKey = false !== $this->getTable() ? $this->getTable()->getKeyName() : 'id'; + } + } + + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + if (null === $name) { + $class = get_class($this); + $name = strstr($class, 'Entity'); + } + + $name = str_replace('Entity', '', $name); + + return RedshopTable::getAdminInstance($name, array(), $this->getComponent()); + } + + /** + * Get the component that contains the tables + * + * @return string + */ + protected function getComponent() + { + if (null === $this->component) { + $this->component = $this->getComponentFromPrefix(); + } + + return $this->component; + } + + /** + * Get the component from the prefix. Ex.: ContentEntityArticle will return com_content + * + * @return string + */ + protected function getComponentFromPrefix() + { + return 'com_' . $this->getPrefix(); + } + + /** + * Get the prefix of this entity. + * + * @return string + * + * @since 2.0 + */ + protected function getPrefix() + { + $class = get_class($this); + + return strtolower(strstr($class, 'Entity', true)); + } + + /** + * Create and return a cached instance by a different field of the table (UID) + * + * @param string $fieldName Field to use + * @param string $fieldValue Key value + * + * @return $this + */ + public static function getInstanceByField($fieldName, $fieldValue) + { + $instance = static::getInstance(); + + return $instance->loadItem($fieldName, $fieldValue); + } + + /** + * Create and return a cached instance + * + * @param integer $id Identifier of the active item + * + * @return $this + */ + public static function getInstance($id = null) + { + if (null === $id) { + return new static; + } + + $class = get_called_class(); + + if (empty(static::$instances[$class][$id])) { + static::$instances[$class][$id] = new static($id); + } + + return static::$instances[$class][$id]; + } + + /** + * Load a cached instance and ensure that the item is loaded + * + * @param integer $id Identifier of the active item + * + * @return self + */ + public static function load($id = null) + { + $instance = static::getInstance($id); + + if (!$instance->isLoaded()) { + $instance->loadItem(); + } + + return $instance; + } + + /** + * Check if item has been loaded + * + * @return boolean + */ + public function isLoaded() + { + return ($this->hasId() && $this->item !== null); + } + + /** + * Bind an object/array to the entity + * + * @param mixed $item Array/Object containing the item fields + * + * @return $this + */ + public function bind($item) + { + // Accept basic array binding + if (is_array($item)) { + $item = (object)$item; + } + + $this->item = $item; + + if (property_exists($item, 'id')) { + $this->id = $item->id; + + $class = get_called_class(); + + // Ensure that we cache the item + if (!isset(static::$instances[$class][$this->id])) { + static::$instances[$class][$this->id] = $this; + } + } + + return $this; + } + + /** + * Check if current user can create an item + * + * @return boolean + * + * @since 1.0 + */ + public function canCreate() + { + if ($this->canDo($this->getAclPrefix() . '.create')) { + return true; + } + + if ($this->canDo($this->getAclPrefix() . '.create.own')) { + return $this->isOwner(); + } + + return false; + } + + /** + * Check if current user has permission to perform an action + * + * @param string $action The action. Example: core.create + * + * @return boolean + */ + public function canDo($action) + { + $user = JFactory::getUser(); + + return $user->authorise($action, $this->getAssetName()); + } + + /** + * Get the identifier of the project asset + * + * @return string + */ + protected function getAssetName() + { + if ($this->hasId()) { + return $this->getComponent() . '.' . $this->getInstanceName() . '.' . $this->id; + } + + // Use the global permissions + return $this->getComponent(); + } + + /** + * Check if we have an identifier loaded + * + * @return boolean + */ + public function hasId() + { + $id = (int)$this->id; + + return !empty($id); + } + + /** + * Get the name of the current entity type + * + * @return string + */ + public function getInstanceName() + { + $class = get_class($this); + + $name = strstr($class, 'Entity'); + $name = str_replace('Entity', '', $name); + + return strtolower($name); + } + + /** + * Get the ACL prefix applied to this class + * + * @return string + * + * @since 1.0 + */ + public function getAclPrefix() + { + return $this->aclPrefix; + } + + /** + * Check if current member is owner + * + * @return boolean + * + * @since 1.0 + */ + public function isOwner() + { + if (!$this->hasId()) { + return false; + } + + $user = JFactory::getUser(); + + if ($user->get('guest')) { + return false; + } + + $item = $this->getItem(); + + if (!$item) { + return false; + } + + return ($item->created_by == $user->get('id')); + } + + /** + * Get item from the database + * + * @return mixed Object / null + */ + public function getItem() + { + if (empty($this->item)) { + $this->loadItem(); + } + + return $this->item; + } + + /** + * Default loading is trying to use the associated table + * + * @param string $key Field name used as key + * @param string $keyValue Value used if it's not the $this->id property of the instance + * + * @return self + */ + public function loadItem($key = null, $keyValue = null) + { + $key = null === $key ? $this->tableKey : $key; + + if ($key === $this->tableKey && !$this->hasId()) { + return $this; + } + + $table = $this->getTable(); + + if (false !== $table && $table->load(array($key => ($key === $this->tableKey ? $this->id : $keyValue)))) { + $this->loadFromTable($table); + } + + return $this; + } + + /** + * Load the item already loaded in a table + * + * @param RedshopTable|JTable $table Table with the item loaded + * + * @return self + */ + public function loadFromTable($table) + { + $key = $table->getKeyName(); + + if (!empty($table->{$key})) { + // Get the data from the table + if (method_exists($table, 'getTableProperties')) { + // Redshopb method to get only public properties + $data = $table->getTableProperties(); + } else { + // Fallback for every other JTable (not redshopb tables) + $data = $table->getProperties(true); + } + + // Item is always an object + $this->item = ArrayHelper::toObject($data); + + $this->id = $table->{$key}; + $this->table = clone $table; + + $class = get_called_class(); + + // Ensure that we cache the item + if (!isset(static::$instances[$class][$this->id]) || !static::$instances[$class][$this->id]->isLoaded()) { + static::$instances[$class][$this->id] = $this; + } + } + + return $this; + } + + /** + * Check if current user can delete an item + * + * @return boolean + */ + public function canDelete() + { + if (!$this->hasId()) { + return false; + } + + if ($this->canDo($this->getAclPrefix() . '.delete')) { + return true; + } + + if ($this->canDo($this->getAclPrefix() . '.delete.own')) { + return $this->isOwner(); + } + + return false; + } + + /** + * Check if current user can edit this item + * + * @return boolean + */ + public function canEdit() + { + if (!$this->hasId()) { + return false; + } + + // User has global edit permissions + if ($this->canDo($this->getAclPrefix() . '.edit')) { + return true; + } + + // User has global edit permissions + if ($this->canDo($this->getAclPrefix() . '.edit.own')) { + return $this->isOwner(); + } + + return false; + } + + /** + * Check if user can view this item. + * + * @return boolean + * + * @since 1.0 + */ + public function canView() + { + $item = $this->getItem(); + + if (!$item) { + return false; + } + + return ((int)$item->state === static::STATE_ENABLED || $this->isOwner()); + } + + /** + * Get an item property + * + * @param string $property Property to get + * @param mixed $default Default value to assign if property === null | property === '' + * + * @return string + */ + public function get($property, $default = null) + { + $item = $this->getItem(); + + if (!empty($item) && property_exists($item, $property)) { + return ($item->$property !== null && $item->$property !== '') ? $item->$property : $default; + } + + return $default; + } + + /** + * Set an item property + * + * @param string $property Property to get + * @param mixed $data Data for set to property + * + * @return self + */ + public function set($property, $data = null) + { + if (null === $this->item) { + $this->loadItem(); + } + + $this->item->{$property} = $data; + + return $this; + } + + /** + * Get the item add link with a return link to the current page. + * + * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid + * @param boolean $routed Process URL with JRoute? + * @param boolean $xhtml Replace & by & for XML compliance. + * + * @return string + */ + public function getAddLinkWithReturn($itemId = 'inherit', $routed = true, $xhtml = true) + { + $url = $this->getAddLink($itemId, false, false) . '&return=' . base64_encode(JUri::getInstance()->toString()); + + return $this->formatUrl($url, $routed, $xhtml); + } + + /** + * Get the item add link + * + * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid + * @param boolean $routed Process URL with JRoute? + * @param boolean $xhtml Replace & by & for XML compliance. + * + * @return string + */ + public function getAddLink($itemId = 'inherit', $routed = true, $xhtml = true) + { + $url = $this->getBaseUrl() . '&task=' . $this->getInstanceName() . '.add' . $this->getLinkItemIdString($itemId); + + return $this->formatUrl($url, $routed, $xhtml); + } + + /** + * Gets the base URL for tasks/views. + * + * Example: index.php?option=com_redshopb&view=shop + * + * @return string + */ + protected function getBaseUrl() + { + return 'index.php?option=' . $this->getComponent() . '&view=' . $this->getInstanceName(); + } + + /** + * Generate the Itemid string part for URLs + * + * @param mixed $itemId inherit or desired itemId. Use 0 to not inherit active itemId + * + * @return string + */ + protected function getLinkItemIdString($itemId = 'inherit') + { + return ($itemId !== 'inherit') ? '&Itemid=' . (int)$itemId : null; + } + + /** + * Format a link + * + * @param string $url Url to format + * @param boolean $routed Process Url through JRoute? + * @param boolean $xhtml Replace & by & for XML compliance. + * + * @return string + */ + protected function formatUrl($url, $routed = true, $xhtml = true) + { + if (!$url) { + return null; + } + + if (!$routed) { + return $url; + } + + return JRoute::_($url, $xhtml); + } + + /** + * Get an entity date field formatted + * + * @param string $itemProperty Item property containing the date + * @param string $format Desired date format + * @param boolean $translateFormat Translate the format for multilanguage purposes + * + * @return string + */ + public function getDate($itemProperty, $format = 'DATE_FORMAT_LC1', $translateFormat = true) + { + $item = $this->getItem(); + + if (!$item || !property_exists($item, $itemProperty)) { + return null; + } + + if ($format && $translateFormat) { + $format = JText::_($format); + } + + return JHtml::_('date', $item->{$itemProperty}, $format); + } + + /** + * Get the item delete link with a return link to the current page. + * + * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid + * @param boolean $routed Process URL with JRoute? + * @param boolean $xhtml Replace & by & for XML compliance. + * + * @return string + */ + public function getDeleteLinkWithReturn($itemId = 'inherit', $routed = true, $xhtml = true) + { + if (!$this->hasId()) { + return null; + } + + $url = $this->getDeleteLink($itemId, false, false) . '&return=' . base64_encode( + JUri::getInstance()->toString() + ); + + return $this->formatUrl($url, $routed, $xhtml); + } + + /** + * Get the item delete link + * + * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid + * @param boolean $routed Process URL with JRoute? + * @param boolean $xhtml Replace & by & for XML compliance. + * + * @return string + */ + public function getDeleteLink($itemId = 'inherit', $routed = true, $xhtml = true) + { + if (!$this->hasId()) { + return null; + } + + $urlToken = '&' . JSession::getFormToken() . '=1'; + + $url = $this->getBaseUrl() . '&task=' . $this->getInstanceName() + . '.delete&id=' . $this->getSlug() . $urlToken . $this->getLinkItemIdString($itemId); + + return $this->formatUrl($url, $routed, $xhtml); + } + + /** + * Generate the item slug for URLs + * + * @return string + */ + protected function getSlug() + { + $item = $this->getItem(); + + if (!$item) { + return $this->hasId() ? $this->id : null; + } + + return !empty($item->alias) ? $this->id . '-' . $item->alias : $this->id; + } + + /** + * Get the item edit link with a return link to the current page. + * + * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid + * @param boolean $routed Process URL with JRoute? + * @param boolean $xhtml Replace & by & for XML compliance. + * + * @return string + * + * @since 1.0 + */ + public function getEditLinkWithReturn($itemId = 'inherit', $routed = true, $xhtml = true) + { + if (!$this->hasId()) { + return null; + } + + $url = $this->getEditLink($itemId, false, false) . '&return=' . base64_encode(JUri::getInstance()->toString()); + + return $this->formatUrl($url, $routed, $xhtml); + } + + /** + * Get the item edit link + * + * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid + * @param boolean $routed Process URL with JRoute? + * @param boolean $xhtml Replace & by & for XML compliance. + * + * @return string + */ + public function getEditLink($itemId = 'inherit', $routed = true, $xhtml = true) + { + if (!$this->hasId()) { + return null; + } + + $url = $this->getBaseUrl() . '&task=' . $this->getInstanceName() + . '.edit&id=' . $this->getSlug() . $this->getLinkItemIdString($itemId); + + return $this->formatUrl($url, $routed, $xhtml); + } + + /** + * Get the item link + * + * @param mixed $itemId Specify a custom itemId if needed. Default: joomla way to use active itemid + * @param boolean $routed Process URL with JRoute? + * @param boolean $xhtml Replace & by & for XML compliance. + * + * @return string + */ + public function getLink($itemId = 'inherit', $routed = true, $xhtml = true) + { + if (!$this->hasId()) { + return null; + } + + $url = $this->getBaseUrl() . '&id=' . $this->getSlug() . $this->getLinkItemIdString($itemId); + + return $this->formatUrl($url, $routed, $xhtml); + } + + /** + * Basic instance check: has id + loadable item + * + * @return boolean + */ + public function isValid() + { + if (!$this->hasId()) { + return false; + } + + $item = $this->getItem(); + + return !empty($item); + } + + /** + * @param array $data Data + * + * @return self + */ + public function loadItemByArray($data) + { + $table = $this->getTable(); + + if (false === $table) { + return $this; + } + + if ($table->load($data)) { + $this->loadFromTable($table); + } + + return $this; + } + + /** + * Try to directly save the entity using the associated table + * + * @param mixed $item Object / Array to save. Null = try to store current item + * + * @return boolean|integer The item id + * + * @since 1.0 + */ + public function save($item = null) + { + if (!$this->processBeforeSaving($item)) { + return false; + } + + if (null === $item) { + $item = $this->getItem(); + } + + if (!$item) { + JLog::add("Nothing to save", JLog::ERROR, 'entity'); + + return false; + } + + try { + $table = $this->getTable(); + } catch (Exception $exception) { + JLog::add("Table for instance " . $this->getInstanceName() . " could not be loaded", JLog::ERROR, 'entity'); + + return false; + } + + if (!$table->save((array)$item)) { + JLog::add($table->getError(), JLog::ERROR, 'entity'); + + return false; + } + + // Force entity reload / save to cache + static::clearInstance($this->id); + static::loadFromTable($table); + + $this->processAfterSaving($table); + + return $table->{$table->getKeyName()}; + } + + /** + * Process $item data before saving. + * + * @param mixed $item Array / Object of data. + * + * @return boolean Return false will break save process + */ + public function processBeforeSaving(&$item) + { + return true; + } + + /** + * Remove an instance from cache + * + * @param integer $id Identifier of the active item + * + * @return void + */ + public static function clearInstance($id = null) + { + $class = get_called_class(); + + unset(static::$instances[$class][$id]); + } + + /** + * Process data after saving. + * + * @param JTable $table JTable instance data. + * + * @return boolean + */ + public function processAfterSaving(&$table) + { + return true; + } + + /** + * Method for reset this static for load new data. + * + * @return self + * + * @since 2.0.6 + */ + public function reset() + { + if (!$this->isLoaded()) { + return $this; + } + + $class = get_called_class(); + $id = $this->getId(); + + unset(static::$instances[$class][$id]); + + return static::getInstance($id); + } + + /** + * Get the id + * + * @return integer | null + */ + public function getId() + { + return $this->id; + } + + /** + * Local proxy for JFactory::getDbo() + * + * @return JDatabaseDriver + */ + protected function getDbo() + { + return JFactory::getDbo(); + } } diff --git a/libraries/redshop/entity/category.php b/libraries/redshop/entity/category.php index 895e51310e0..7354767ec23 100644 --- a/libraries/redshop/entity/category.php +++ b/libraries/redshop/entity/category.php @@ -18,285 +18,274 @@ */ class RedshopEntityCategory extends RedshopEntity { - /** - * Product count - * - * @var integer - */ - protected $productCount; - - /** - * Products - * - * @var array - */ - protected $products; - - /** - * @var RedshopEntitiesCollection - * - * @since 2.0.6 - */ - protected $childCategories; - - /** - * @var RedshopEntitiesCollection - * - * @since 2.1.0 - */ - protected $media; - - /** - * Method for get product count of category - * - * @return integer - */ - public function productCount() - { - if (is_null($this->productCount)) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('COUNT(category_id)') - ->from($db->qn('#__redshop_product_category_xref')) - ->where($db->qn('category_id') . ' = ' . $db->quote((int) $this->getId())); - - $this->productCount = $db->setQuery($query)->loadResult(); - } - - return $this->productCount; - } - - /** - * Method for get products of current category - * - * @return array - * - * @since 2.0.6 - */ - public function getProducts($includeProductsFromSubCat = false) - { - if (null === $this->products) - { - $this->loadProducts($includeProductsFromSubCat); - } - - return $this->products; - } - - /** - * Method for load products - * - * @return $this - * - * @since 2.0.6 - */ - protected function loadProducts($includeProductsFromSubCat = false) - { - if (!$this->hasId()) - { - return $this; - } - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('DISTINCT p.product_id AS id') - ->select('p.*') - ->from($db->qn('#__redshop_product_category_xref', 'pcx')) - ->leftJoin($db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('pcx.product_id')) - ->leftJoin($db->qn('#__redshop_category', 'c') . ' ON ' . $db->qn('pcx.category_id') . ' = ' . $db->qn('c.id')) - ->where($db->qn('p.published') . ' = 1') - ->order($db->qn('p.product_id') . ' DESC'); - - $categories = array(); - - if ($includeProductsFromSubCat) - { - $childs = $this->getChildCategories(); - - if ($childs && !$childs->isEmpty()) - { - $categories = $childs->toFieldArray('id'); - } - } - - $categories[] = (int) $this->getId(); - - $query->where($db->qn('c.id') . ' IN (' . implode(',', $categories) . ')'); - - $this->products = $db->setQuery($query)->loadObjectList(); - - return $this; - } - - /** - * Method for get child categories of current category - * - * @return RedshopEntitiesCollection - * - * @since 2.0.6 - */ - public function getChildCategories() - { - if (null === $this->childCategories) - { - $this->loadChildCategories(); - } - - return $this->childCategories; - } - - /** - * Method for load child categories - * - * @return self - * - * @since 2.0.6 - */ - protected function loadChildCategories() - { - if (!$this->hasId()) - { - return $this; - } - - $this->childCategories = new RedshopEntitiesCollection; - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('id') - ->from($db->qn('#__redshop_category')) - ->where($db->qn('lft') . ' > ' . $this->get('lft')) - ->where($db->qn('rgt') . ' < ' . $this->get('rgt')); - - $results = $db->setQuery($query)->loadColumn(); - - if (empty($results)) - { - return $this; - } - - foreach ($results as $categoryId) - { - $this->childCategories->add(self::getInstance($categoryId)); - } - - return $this; - } - - /** - * Method for get medias of current category - * - * @return RedshopEntitiesCollection - * - * @since 2.1.0 - */ - public function getMedia() - { - if (null === $this->media) - { - $this->loadMedia(); - } - - return $this->media; - } - - /** - * Method for load medias - * - * @return self - * - * @since 2.1.0 - */ - protected function loadMedia() - { - $this->media = new RedshopEntitiesCollection; - - if (!$this->hasId()) - { - return $this; - } - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('media_id') - ->from($db->qn('#__redshop_media')) - ->where($db->qn('media_section') . ' = ' . $db->quote('category')) - ->where($db->qn('section_id') . ' = ' . $db->quote($this->getId())); - - $results = $db->setQuery($query)->loadColumn(); - - if (empty($results)) - { - return $this; - } - - foreach ($results as $mediaId) - { - $this->media->add(RedshopEntityMedia::getInstance($mediaId)); - } - - return $this; - } - - /** - * Try to directly save the entity using the associated table - * - * @param mixed $item Object / Array to save. Null = try to store current item - * - * @return integer|boolean The item id - * - * @since 1.0 - */ - public function save($item = null) - { - if (!$this->processBeforeSaving($item)) - { - return false; - } - - if (null === $item) - { - $item = $this->getItem(); - } - - if (!$item) - { - JLog::add("Nothing to save", JLog::ERROR, 'entity'); - - return false; - } - - try - { - /** @var RedshopTableCategory $table */ - $table = $this->getTable(); - } - catch (\Exception $e) - { - JLog::add("Table for instance " . $this->getInstanceName() . " could not be loaded", JLog::ERROR, 'entity'); - - return false; - } - - $item = Joomla\Utilities\ArrayHelper::fromObject($item); - - $table->setLocation(isset($item['parent_id']) ? $item['parent_id'] : RedshopHelperCategory::getRootId(), 'last-child'); - - if (!$table->save($item)) - { - JLog::add($table->getError(), JLog::ERROR, 'entity'); - - return false; - } - - // Force entity reload / save to cache - static::clearInstance($this->id); - static::getInstance($this->id)->loadFromTable($table); - - $this->processAfterSaving($table); - - return (int) $table->{$table->getKeyName()}; - } + /** + * Product count + * + * @var integer + */ + protected $productCount; + + /** + * Products + * + * @var array + */ + protected $products; + + /** + * @var RedshopEntitiesCollection + * + * @since 2.0.6 + */ + protected $childCategories; + + /** + * @var RedshopEntitiesCollection + * + * @since 2.1.0 + */ + protected $media; + + /** + * Method for get product count of category + * + * @return integer + */ + public function productCount() + { + if (is_null($this->productCount)) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('COUNT(category_id)') + ->from($db->qn('#__redshop_product_category_xref')) + ->where($db->qn('category_id') . ' = ' . $db->quote((int)$this->getId())); + + $this->productCount = $db->setQuery($query)->loadResult(); + } + + return $this->productCount; + } + + /** + * Method for get products of current category + * + * @return array + * + * @since 2.0.6 + */ + public function getProducts($includeProductsFromSubCat = false) + { + if (null === $this->products) { + $this->loadProducts($includeProductsFromSubCat); + } + + return $this->products; + } + + /** + * Method for load products + * + * @return $this + * + * @since 2.0.6 + */ + protected function loadProducts($includeProductsFromSubCat = false) + { + if (!$this->hasId()) { + return $this; + } + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('DISTINCT p.product_id AS id') + ->select('p.*') + ->from($db->qn('#__redshop_product_category_xref', 'pcx')) + ->leftJoin( + $db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn( + 'pcx.product_id' + ) + ) + ->leftJoin( + $db->qn('#__redshop_category', 'c') . ' ON ' . $db->qn('pcx.category_id') . ' = ' . $db->qn('c.id') + ) + ->where($db->qn('p.published') . ' = 1') + ->order($db->qn('p.product_id') . ' DESC'); + + $categories = array(); + + if ($includeProductsFromSubCat) { + $childs = $this->getChildCategories(); + + if ($childs && !$childs->isEmpty()) { + $categories = $childs->toFieldArray('id'); + } + } + + $categories[] = (int)$this->getId(); + + $query->where($db->qn('c.id') . ' IN (' . implode(',', $categories) . ')'); + + $this->products = $db->setQuery($query)->loadObjectList(); + + return $this; + } + + /** + * Method for get child categories of current category + * + * @return RedshopEntitiesCollection + * + * @since 2.0.6 + */ + public function getChildCategories() + { + if (null === $this->childCategories) { + $this->loadChildCategories(); + } + + return $this->childCategories; + } + + /** + * Method for load child categories + * + * @return self + * + * @since 2.0.6 + */ + protected function loadChildCategories() + { + if (!$this->hasId()) { + return $this; + } + + $this->childCategories = new RedshopEntitiesCollection; + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('id') + ->from($db->qn('#__redshop_category')) + ->where($db->qn('lft') . ' > ' . $this->get('lft')) + ->where($db->qn('rgt') . ' < ' . $this->get('rgt')); + + $results = $db->setQuery($query)->loadColumn(); + + if (empty($results)) { + return $this; + } + + foreach ($results as $categoryId) { + $this->childCategories->add(self::getInstance($categoryId)); + } + + return $this; + } + + /** + * Method for get medias of current category + * + * @return RedshopEntitiesCollection + * + * @since 2.1.0 + */ + public function getMedia() + { + if (null === $this->media) { + $this->loadMedia(); + } + + return $this->media; + } + + /** + * Method for load medias + * + * @return self + * + * @since 2.1.0 + */ + protected function loadMedia() + { + $this->media = new RedshopEntitiesCollection; + + if (!$this->hasId()) { + return $this; + } + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('media_id') + ->from($db->qn('#__redshop_media')) + ->where($db->qn('media_section') . ' = ' . $db->quote('category')) + ->where($db->qn('section_id') . ' = ' . $db->quote($this->getId())); + + $results = $db->setQuery($query)->loadColumn(); + + if (empty($results)) { + return $this; + } + + foreach ($results as $mediaId) { + $this->media->add(RedshopEntityMedia::getInstance($mediaId)); + } + + return $this; + } + + /** + * Try to directly save the entity using the associated table + * + * @param mixed $item Object / Array to save. Null = try to store current item + * + * @return integer|boolean The item id + * + * @since 1.0 + */ + public function save($item = null) + { + if (!$this->processBeforeSaving($item)) { + return false; + } + + if (null === $item) { + $item = $this->getItem(); + } + + if (!$item) { + JLog::add("Nothing to save", JLog::ERROR, 'entity'); + + return false; + } + + try { + /** @var RedshopTableCategory $table */ + $table = $this->getTable(); + } catch (\Exception $e) { + JLog::add("Table for instance " . $this->getInstanceName() . " could not be loaded", JLog::ERROR, 'entity'); + + return false; + } + + $item = Joomla\Utilities\ArrayHelper::fromObject($item); + + $table->setLocation( + isset($item['parent_id']) ? $item['parent_id'] : RedshopHelperCategory::getRootId(), + 'last-child' + ); + + if (!$table->save($item)) { + JLog::add($table->getError(), JLog::ERROR, 'entity'); + + return false; + } + + // Force entity reload / save to cache + static::clearInstance($this->id); + static::getInstance($this->id)->loadFromTable($table); + + $this->processAfterSaving($table); + + return (int)$table->{$table->getKeyName()}; + } } diff --git a/libraries/redshop/entity/coupon_transaction.php b/libraries/redshop/entity/coupon_transaction.php index 245fca950e7..842c6b8d410 100644 --- a/libraries/redshop/entity/coupon_transaction.php +++ b/libraries/redshop/entity/coupon_transaction.php @@ -18,15 +18,15 @@ */ class RedshopEntityCoupon_Transaction extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Transaction_Coupon_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Transaction_Coupon_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/currency.php b/libraries/redshop/entity/currency.php index 2b53508c795..f615019f417 100644 --- a/libraries/redshop/entity/currency.php +++ b/libraries/redshop/entity/currency.php @@ -18,41 +18,38 @@ */ class RedshopEntityCurrency extends RedshopEntity { - /** - * @var array - * @since 2.0.6 - */ - protected static $codeInstance; + /** + * @var array + * @since 2.0.6 + */ + protected static $codeInstance; - /** - * Method for load currency instance base on currency code - * - * @param string $code Currency Code - * - * @return self - * - * @since 2.0.6 - */ - public function loadFromCode($code = '') - { - if (empty($code)) - { - return self::getInstance(); - } + /** + * Method for load currency instance base on currency code + * + * @param string $code Currency Code + * + * @return self + * + * @since 2.0.6 + */ + public function loadFromCode($code = '') + { + if (empty($code)) { + return self::getInstance(); + } - if (!isset(static::$codeInstance[$code])) - { - /** @var RedshopTableCurrency $table */ - $table = $this->getTable(); + if (!isset(static::$codeInstance[$code])) { + /** @var RedshopTableCurrency $table */ + $table = $this->getTable(); - if (!$table->load(array('code' => $code))) - { - return self::getInstance(); - } + if (!$table->load(array('code' => $code))) { + return self::getInstance(); + } - static::$codeInstance[$code] = $table->id; - } + static::$codeInstance[$code] = $table->id; + } - return self::getInstance(static::$codeInstance[$code]); - } + return self::getInstance(static::$codeInstance[$code]); + } } diff --git a/libraries/redshop/entity/discount.php b/libraries/redshop/entity/discount.php index 418688efc04..83a34f3acdf 100644 --- a/libraries/redshop/entity/discount.php +++ b/libraries/redshop/entity/discount.php @@ -18,63 +18,59 @@ */ class RedshopEntityDiscount extends RedshopEntity { - /** - * @var RedshopEntitiesCollection - */ - protected $shopperGroups; + /** + * @var RedshopEntitiesCollection + */ + protected $shopperGroups; - /** - * Method for get shopper groups associate with this discount - * - * @return RedshopEntitiesCollection - * - * @since 2.1.0 - */ - public function getShopperGroups() - { - if (null === $this->shopperGroups) - { - $this->loadShopperGroups(); - } + /** + * Method for get shopper groups associate with this discount + * + * @return RedshopEntitiesCollection + * + * @since 2.1.0 + */ + public function getShopperGroups() + { + if (null === $this->shopperGroups) { + $this->loadShopperGroups(); + } - return $this->shopperGroups; - } + return $this->shopperGroups; + } - /** - * Method for load shopper groups associate with this discount - * - * @return self - * - * @since 2.1.0 - */ - protected function loadShopperGroups() - { - $this->shopperGroups = new RedshopEntitiesCollection; + /** + * Method for load shopper groups associate with this discount + * + * @return self + * + * @since 2.1.0 + */ + protected function loadShopperGroups() + { + $this->shopperGroups = new RedshopEntitiesCollection; - if (!$this->hasId()) - { - return $this; - } + if (!$this->hasId()) { + return $this; + } - $db = JFactory::getDbo(); + $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('shopper_group_id')) - ->from($db->qn('#__redshop_discount_shoppers')) - ->where($db->qn('discount_id') . ' = ' . $this->getId()); + $query = $db->getQuery(true) + ->select($db->qn('shopper_group_id')) + ->from($db->qn('#__redshop_discount_shoppers')) + ->where($db->qn('discount_id') . ' = ' . $this->getId()); - $result = $db->setQuery($query)->loadColumn(); + $result = $db->setQuery($query)->loadColumn(); - if (empty($result)) - { - return $this; - } + if (empty($result)) { + return $this; + } - foreach ($result as $shopperGroupId) - { - $this->shopperGroups->add(RedshopEntityShopper_Group::getInstance($shopperGroupId)); - } + foreach ($result as $shopperGroupId) { + $this->shopperGroups->add(RedshopEntityShopper_Group::getInstance($shopperGroupId)); + } - return $this; - } + return $this; + } } diff --git a/libraries/redshop/entity/discount_product.php b/libraries/redshop/entity/discount_product.php index 74c246563d1..9394cef4315 100644 --- a/libraries/redshop/entity/discount_product.php +++ b/libraries/redshop/entity/discount_product.php @@ -18,111 +18,104 @@ */ class RedshopEntityDiscount_Product extends RedshopEntity { - /** - * @var RedshopEntitiesCollection - */ - protected $shopperGroups; - - /** - * @var RedshopEntitiesCollection - */ - protected $categories; - - /** - * Method for get shopper groups associate with this discount - * - * @return RedshopEntitiesCollection - * - * @since 2.1.0 - */ - public function getShopperGroups() - { - if (null === $this->shopperGroups) - { - $this->loadShopperGroups(); - } - - return $this->shopperGroups; - } - - /** - * Method for get categories associate with this discount - * - * @return RedshopEntitiesCollection - * - * @since 2.1.0 - */ - public function getCategories() - { - if (null === $this->categories) - { - $this->loadCategories(); - } - - return $this->categories; - } - - /** - * Method for load categories associate with this discount - * - * @return self - * - * @since 2.1.0 - */ - protected function loadCategories() - { - $this->categories = new RedshopEntitiesCollection; - - if (!$this->hasId() || empty($this->get('category_ids'))) - { - return $this; - } - - $categoryIds = explode(',', $this->get('category_ids')); - - foreach ($categoryIds as $categoryId) - { - $this->categories->add(RedshopEntityCategory::getInstance($categoryId)); - } - - return $this; - } - - /** - * Method for load shopper groups associate with this discount - * - * @return self - * - * @since 2.1.0 - */ - protected function loadShopperGroups() - { - $this->shopperGroups = new RedshopEntitiesCollection; - - if (!$this->hasId()) - { - return $this; - } - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->qn('shopper_group_id')) - ->from($db->qn('#__redshop_discount_product_shoppers')) - ->where($db->qn('discount_product_id') . ' = ' . $this->getId()); - - $result = $db->setQuery($query)->loadColumn(); - - if (empty($result)) - { - return $this; - } - - foreach ($result as $shopperGroupId) - { - $this->shopperGroups->add(RedshopEntityShopper_Group::getInstance($shopperGroupId)); - } - - return $this; - } + /** + * @var RedshopEntitiesCollection + */ + protected $shopperGroups; + + /** + * @var RedshopEntitiesCollection + */ + protected $categories; + + /** + * Method for get shopper groups associate with this discount + * + * @return RedshopEntitiesCollection + * + * @since 2.1.0 + */ + public function getShopperGroups() + { + if (null === $this->shopperGroups) { + $this->loadShopperGroups(); + } + + return $this->shopperGroups; + } + + /** + * Method for load shopper groups associate with this discount + * + * @return self + * + * @since 2.1.0 + */ + protected function loadShopperGroups() + { + $this->shopperGroups = new RedshopEntitiesCollection; + + if (!$this->hasId()) { + return $this; + } + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->qn('shopper_group_id')) + ->from($db->qn('#__redshop_discount_product_shoppers')) + ->where($db->qn('discount_product_id') . ' = ' . $this->getId()); + + $result = $db->setQuery($query)->loadColumn(); + + if (empty($result)) { + return $this; + } + + foreach ($result as $shopperGroupId) { + $this->shopperGroups->add(RedshopEntityShopper_Group::getInstance($shopperGroupId)); + } + + return $this; + } + + /** + * Method for get categories associate with this discount + * + * @return RedshopEntitiesCollection + * + * @since 2.1.0 + */ + public function getCategories() + { + if (null === $this->categories) { + $this->loadCategories(); + } + + return $this->categories; + } + + /** + * Method for load categories associate with this discount + * + * @return self + * + * @since 2.1.0 + */ + protected function loadCategories() + { + $this->categories = new RedshopEntitiesCollection; + + if (!$this->hasId() || empty($this->get('category_ids'))) { + return $this; + } + + $categoryIds = explode(',', $this->get('category_ids')); + + foreach ($categoryIds as $categoryId) { + $this->categories->add(RedshopEntityCategory::getInstance($categoryId)); + } + + return $this; + } } diff --git a/libraries/redshop/entity/entity.php b/libraries/redshop/entity/entity.php index efa6ceea2d0..1f952dcb4c2 100644 --- a/libraries/redshop/entity/entity.php +++ b/libraries/redshop/entity/entity.php @@ -16,52 +16,49 @@ */ abstract class RedshopEntity extends RedshopEntityBase { - /** - * Option of the component containing the tables. Example: com_content - * - * @var string - * @since 2.0.3 - */ - protected $component = 'com_redshop'; + /** + * Option of the component containing the tables. Example: com_content + * + * @var string + * @since 2.0.3 + */ + protected $component = 'com_redshop'; - /** - * Asset of this for this entity - * - * @var JTable - * @since 2.0.3 - */ - protected $asset; + /** + * Asset of this for this entity + * + * @var JTable + * @since 2.0.3 + */ + protected $asset; - /** - * Converts an array of entities into an array of objects - * - * @param array $entities Array of RedshopbEntity - * - * @return array - * - * @throws InvalidArgumentException If an array of RedshopbEntity is not received - * - * @since 2.0.3 - */ - public function entitiesToObjects(array $entities) - { - $results = array(); + /** + * Converts an array of entities into an array of objects + * + * @param array $entities Array of RedshopbEntity + * + * @return array + * + * @throws InvalidArgumentException If an array of RedshopbEntity is not received + * + * @since 2.0.3 + */ + public function entitiesToObjects(array $entities) + { + $results = array(); - if (!$entities) - { - return $results; - } + if (!$entities) { + return $results; + } - foreach ($entities as $key => $entity) - { - if (!$entity instanceof RedshopEntity) - { - throw new InvalidArgumentException("RedshopEntityExpected in " . __FUNCTION__); - } + foreach ($entities as $key => $entity) { + if (!$entity instanceof RedshopEntity) { + throw new InvalidArgumentException("RedshopEntityExpected in " . __FUNCTION__); + } - $results[$key] = $entity->getItem(); - } + $results[$key] = $entity->getItem(); + } - return $results; - } + return $results; + } } diff --git a/libraries/redshop/entity/field.php b/libraries/redshop/entity/field.php index 911c79ad9c5..dbfb351b5b1 100644 --- a/libraries/redshop/entity/field.php +++ b/libraries/redshop/entity/field.php @@ -18,71 +18,68 @@ */ class RedshopEntityField extends RedshopEntity { - /** - * @var array - * - * @since 2.0.6 - */ - protected $fieldValues; + /** + * @var array + * + * @since 2.0.6 + */ + protected $fieldValues; - /** - * Method for get field values - * - * @return array - * - * @since 2.0.6 - */ - public function getFieldValues() - { - if (null == $this->fieldValues) - { - $this->loadFieldValues(); - } + /** + * Method for get field values + * + * @return array + * + * @since 2.0.6 + */ + public function getFieldValues() + { + if (null == $this->fieldValues) { + $this->loadFieldValues(); + } - return $this->fieldValues; - } + return $this->fieldValues; + } - /** - * Method for get group of this field - * - * @return null|RedshopEntityField_Group - * - * @since 2.1.0 - */ - public function getGroup() - { - if (!$this->hasId() || $this->get('groupId') === null) - { - return null; - } + /** + * Method for load field values + * + * @return self + * + * @since 2.0.6 + */ + protected function loadFieldValues() + { + if (!$this->hasId()) { + return $this; + } - return RedshopEntityField_Group::getInstance((int) $this->get('groupId')); - } + $db = JFactory::getDbo(); - /** - * Method for load field values - * - * @return self - * - * @since 2.0.6 - */ - protected function loadFieldValues() - { - if (!$this->hasId()) - { - return $this; - } + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_fields_value')) + ->where($db->qn('field_id') . ' = ' . (int)$this->getId()) + ->order($db->qn('value_id') . ' ASC'); - $db = JFactory::getDbo(); + $this->fieldValues = $db->setQuery($query)->loadObjectList(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_fields_value')) - ->where($db->qn('field_id') . ' = ' . (int) $this->getId()) - ->order($db->qn('value_id') . ' ASC'); + return $this; + } - $this->fieldValues = $db->setQuery($query)->loadObjectList(); + /** + * Method for get group of this field + * + * @return null|RedshopEntityField_Group + * + * @since 2.1.0 + */ + public function getGroup() + { + if (!$this->hasId() || $this->get('groupId') === null) { + return null; + } - return $this; - } + return RedshopEntityField_Group::getInstance((int)$this->get('groupId')); + } } diff --git a/libraries/redshop/entity/field_group.php b/libraries/redshop/entity/field_group.php index c56c76d16cf..8993d4527fd 100644 --- a/libraries/redshop/entity/field_group.php +++ b/libraries/redshop/entity/field_group.php @@ -18,65 +18,61 @@ */ class RedshopEntityField_Group extends RedshopEntity { - /** - * List of fields - * - * @var RedshopEntitiesCollection - */ - protected $fields; + /** + * List of fields + * + * @var RedshopEntitiesCollection + */ + protected $fields; - /** - * Method for get fields associate with this group - * - * @return RedshopEntitiesCollection - * - * @since 2.1.0 - */ - public function getFields() - { - if (null === $this->fields) - { - $this->loadFields(); - } + /** + * Method for get fields associate with this group + * + * @return RedshopEntitiesCollection + * + * @since 2.1.0 + */ + public function getFields() + { + if (null === $this->fields) { + $this->loadFields(); + } - return $this->fields; - } + return $this->fields; + } - /** - * Method for load fields associate with this field group - * - * @return self - * - * @since 2.1.0 - */ - protected function loadFields() - { - $this->fields = new RedshopEntitiesCollection; + /** + * Method for load fields associate with this field group + * + * @return self + * + * @since 2.1.0 + */ + protected function loadFields() + { + $this->fields = new RedshopEntitiesCollection; - if (!$this->hasId()) - { - return $this; - } + if (!$this->hasId()) { + return $this; + } - $db = JFactory::getDbo(); + $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('id')) - ->from($db->qn('#__redshop_fields')) - ->where($db->qn('groupId') . ' = ' . $this->getId()); + $query = $db->getQuery(true) + ->select($db->qn('id')) + ->from($db->qn('#__redshop_fields')) + ->where($db->qn('groupId') . ' = ' . $this->getId()); - $result = $db->setQuery($query)->loadColumn(); + $result = $db->setQuery($query)->loadColumn(); - if (empty($result)) - { - return $this; - } + if (empty($result)) { + return $this; + } - foreach ($result as $fieldId) - { - $this->fields->add(RedshopEntityField::getInstance($fieldId)); - } + foreach ($result as $fieldId) { + $this->fields->add(RedshopEntityField::getInstance($fieldId)); + } - return $this; - } + return $this; + } } diff --git a/libraries/redshop/entity/field_value.php b/libraries/redshop/entity/field_value.php index 04bcdaa20b9..c0ebbeb1582 100644 --- a/libraries/redshop/entity/field_value.php +++ b/libraries/redshop/entity/field_value.php @@ -18,15 +18,15 @@ */ class RedshopEntityField_Value extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Fields_Value', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Fields_Value', 'Table'); + } } diff --git a/libraries/redshop/entity/manufacturer.php b/libraries/redshop/entity/manufacturer.php index 0d0da6024a1..6b31fad4b18 100644 --- a/libraries/redshop/entity/manufacturer.php +++ b/libraries/redshop/entity/manufacturer.php @@ -18,76 +18,73 @@ */ class RedshopEntityManufacturer extends RedshopEntity { - /** - * @var RedshopEntityMediaImage - * - * @since 2.1.0 - */ - protected $media; + /** + * @var RedshopEntityMediaImage + * + * @since 2.1.0 + */ + protected $media; - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTableManufacturer - * @throws Exception - */ - public function getTable($name = "Manufacturer") - { - return RedshopTable::getAdminInstance($name, array('ignore_request' => true), 'com_redshop'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTableManufacturer + * @throws Exception + */ + public function getTable($name = "Manufacturer") + { + return RedshopTable::getAdminInstance($name, array('ignore_request' => true), 'com_redshop'); + } - /** - * Method for get medias of current category - * - * @return RedshopEntityMediaImage - * - * @since 2.1.0 - */ - public function getMedia() - { - if (null === $this->media) - { - $this->loadMedia(); - } + /** + * Method for get medias of current category + * + * @return RedshopEntityMediaImage + * + * @since 2.1.0 + */ + public function getMedia() + { + if (null === $this->media) { + $this->loadMedia(); + } - return $this->media; - } + return $this->media; + } - /** - * Method for load medias - * - * @return self - * - * @since 2.1.0 - */ - protected function loadMedia() - { - $this->media = RedshopEntityMediaImage::getInstance(); + /** + * Method for load medias + * + * @return self + * + * @since 2.1.0 + */ + protected function loadMedia() + { + $this->media = RedshopEntityMediaImage::getInstance(); - if (!$this->hasId()) - { - return $this; - } + if (!$this->hasId()) { + return $this; + } - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_media')) - ->where($db->qn('media_section') . ' = ' . $db->quote('manufacturer')) - ->where($db->qn('section_id') . ' = ' . $db->quote($this->getId())); + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_media')) + ->where($db->qn('media_section') . ' = ' . $db->quote('manufacturer')) + ->where($db->qn('section_id') . ' = ' . $db->quote($this->getId())); - $result = $db->setQuery($query)->loadObject(); + $result = $db->setQuery($query)->loadObject(); - if (empty($result)) - { - return $this; - } + if (empty($result)) { + return $this; + } - $this->media = RedshopEntityMediaImage::getInstance($result->media_id); - $this->media->bind($result); + $this->media = RedshopEntityMediaImage::getInstance($result->media_id); + $this->media->bind($result); - return $this; - } + return $this; + } } diff --git a/libraries/redshop/entity/media.php b/libraries/redshop/entity/media.php index 10ce05c6e3a..b8503b51252 100644 --- a/libraries/redshop/entity/media.php +++ b/libraries/redshop/entity/media.php @@ -18,45 +18,43 @@ */ class RedshopEntityMedia extends RedshopEntity { - /** - * @var RedshopEntity - */ - protected $sectionEntity; + /** + * @var RedshopEntity + */ + protected $sectionEntity; - /** - * Method for get section entity - * - * @return RedshopEntity - * - * @since 2.1.0 - */ - public function getSection() - { - if ($this->sectionEntity === null) - { - $this->loadSectionEntity(); - } + /** + * Method for get section entity + * + * @return RedshopEntity + * + * @since 2.1.0 + */ + public function getSection() + { + if ($this->sectionEntity === null) { + $this->loadSectionEntity(); + } - return $this->sectionEntity; - } + return $this->sectionEntity; + } - /** - * Method for load section entity - * - * @return self - * - * @since 2.1.0 - */ - public function loadSectionEntity() - { - if (!$this->hasId()) - { - return $this; - } + /** + * Method for load section entity + * + * @return self + * + * @since 2.1.0 + */ + public function loadSectionEntity() + { + if (!$this->hasId()) { + return $this; + } - $entityClass = 'RedshopEntity' . ucfirst($this->get('media_section')); - $this->sectionEntity = $entityClass::getInstance($this->get('section_id')); + $entityClass = 'RedshopEntity' . ucfirst($this->get('media_section')); + $this->sectionEntity = $entityClass::getInstance($this->get('section_id')); - return $this; - } + return $this; + } } diff --git a/libraries/redshop/entity/media/image.php b/libraries/redshop/entity/media/image.php index f085c6e4935..74c95e7f6be 100644 --- a/libraries/redshop/entity/media/image.php +++ b/libraries/redshop/entity/media/image.php @@ -9,12 +9,12 @@ defined('_JEXEC') or die; -use Imagine\Image\Palette\RGB; +use ImageOptimizer\OptimizerFactory; use Imagine\Gd\Image; use Imagine\Gd\Imagine; use Imagine\Image\Box; use Imagine\Image\ImageInterface; -use ImageOptimizer\OptimizerFactory; +use Imagine\Image\Palette\RGB; /** * Media image entity @@ -25,128 +25,123 @@ */ class RedshopEntityMediaImage extends RedshopEntityMedia { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - * @throws Exception - */ - public function getTable($name = null) - { - return RedshopTable::getAdminInstance('Media', array(), 'com_redshop'); - } - - /** - * Method get image path - * - * @return string - */ - public function getImagePath() - { - if (!$this->hasId()) - { - return ''; - } - - return JPath::clean( - REDSHOP_MEDIA_IMAGE_RELPATH . $this->get('media_section') - . '/' . $this->get('section_id') . '/' . $this->get('media_name') - ); - } - - /** - * Method get image path - * - * @return string - */ - public function getAbsImagePath() - { - if (!$this->hasId()) - { - return ''; - } - - return REDSHOP_MEDIA_IMAGE_ABSPATH . $this->get('media_section') - . '/' . $this->get('section_id') . '/' . $this->get('media_name'); - } - - /** - * Method for generate thumbnail - * - * @param integer $width Width of thumbnail - * @param integer $height Height of thumbnail - * @param boolean $crop Is crop image or not - * @param boolean $force Force create image. - * - * @return array List of relative and absolute path - * @throws Exception - * - * @since 2.1.0 - */ - public function generateThumb($width, $height, $crop = false, $force = false) - { - $result = array('rel' => '', 'abs' => ''); - - // Check if this is correct media image - if (!$this->hasId()) - { - return $result; - } - - // Get original file path - $sourceFile = $this->getImagePath(); - - if (empty($sourceFile) || !JFile::exists($sourceFile)) - { - return $result; - } - - $destinationFile = JFile::stripExt(basename($this->get('media_name'))); - $destinationFile .= '_w' . $width . '_h' . $height; - $destinationFile .= '.' . JFile::getExt($this->get('media_name')); - - // Create thumb folder if not exist - $thumbPath = REDSHOP_MEDIA_IMAGE_RELPATH . $this->get('media_section') - . '/' . $this->get('section_id') . '/thumb/'; - \Redshop\Helper\Media::createFolder($thumbPath); - - $result = array( - 'rel' => JPath::clean( - $thumbPath . $destinationFile - ), - 'abs' => REDSHOP_MEDIA_IMAGE_ABSPATH . $this->get('media_section') - . '/' . $this->get('section_id') . '/thumb/' . $destinationFile - ); - - if ($force === false && JFile::exists($result['rel'])) - { - return $result; - } - - $originalMemoryLimit = ini_get('memory_limit'); - ini_set('memory_limit', '1024M'); - - $data = file_get_contents($sourceFile); - $resource = imagecreatefromstring($data); - $imagine = new Imagine; - $image = new Image($resource, new RGB, $imagine->getMetadataReader()->readFile($sourceFile)); - $box = new Box($width, $height); - $mode = $crop ? ImageInterface::THUMBNAIL_OUTBOUND : ImageInterface::THUMBNAIL_INSET; - $thumbnail = $image->thumbnail($box, $mode); - - $thumbnail->save($result['rel']); - - unset($thumbnail, $image, $imagine); - - $factory = new OptimizerFactory; - $optimizer = $factory->get(); - $optimizer->optimize($result['rel']); - - // Memory limit back to normal - ini_set('memory_limit', $originalMemoryLimit); - - return $result; - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + * @throws Exception + */ + public function getTable($name = null) + { + return RedshopTable::getAdminInstance('Media', array(), 'com_redshop'); + } + + /** + * Method get image path + * + * @return string + */ + public function getAbsImagePath() + { + if (!$this->hasId()) { + return ''; + } + + return REDSHOP_MEDIA_IMAGE_ABSPATH . $this->get('media_section') + . '/' . $this->get('section_id') . '/' . $this->get('media_name'); + } + + /** + * Method for generate thumbnail + * + * @param integer $width Width of thumbnail + * @param integer $height Height of thumbnail + * @param boolean $crop Is crop image or not + * @param boolean $force Force create image. + * + * @return array List of relative and absolute path + * @throws Exception + * + * @since 2.1.0 + */ + public function generateThumb($width, $height, $crop = false, $force = false) + { + $result = array('rel' => '', 'abs' => ''); + + // Check if this is correct media image + if (!$this->hasId()) { + return $result; + } + + // Get original file path + $sourceFile = $this->getImagePath(); + + if (empty($sourceFile) || !JFile::exists($sourceFile)) { + return $result; + } + + $destinationFile = JFile::stripExt(basename($this->get('media_name'))); + $destinationFile .= '_w' . $width . '_h' . $height; + $destinationFile .= '.' . JFile::getExt($this->get('media_name')); + + // Create thumb folder if not exist + $thumbPath = REDSHOP_MEDIA_IMAGE_RELPATH . $this->get('media_section') + . '/' . $this->get('section_id') . '/thumb/'; + \Redshop\Helper\Media::createFolder($thumbPath); + + $result = array( + 'rel' => JPath::clean( + $thumbPath . $destinationFile + ), + 'abs' => REDSHOP_MEDIA_IMAGE_ABSPATH . $this->get('media_section') + . '/' . $this->get('section_id') . '/thumb/' . $destinationFile + ); + + if ($force === false && JFile::exists($result['rel'])) { + return $result; + } + + $originalMemoryLimit = ini_get('memory_limit'); + ini_set('memory_limit', '1024M'); + + $data = file_get_contents($sourceFile); + $resource = imagecreatefromstring($data); + $imagine = new Imagine; + $image = new Image($resource, new RGB, $imagine->getMetadataReader()->readFile($sourceFile)); + $box = new Box($width, $height); + $mode = $crop ? ImageInterface::THUMBNAIL_OUTBOUND : ImageInterface::THUMBNAIL_INSET; + $thumbnail = $image->thumbnail($box, $mode); + + $thumbnail->save($result['rel']); + + unset($thumbnail, $image, $imagine); + + $factory = new OptimizerFactory; + $optimizer = $factory->get(); + $optimizer->optimize($result['rel']); + + // Memory limit back to normal + ini_set('memory_limit', $originalMemoryLimit); + + return $result; + } + + /** + * Method get image path + * + * @return string + */ + public function getImagePath() + { + if (!$this->hasId()) { + return ''; + } + + return JPath::clean( + REDSHOP_MEDIA_IMAGE_RELPATH . $this->get('media_section') + . '/' . $this->get('section_id') . '/' . $this->get('media_name') + ); + } } diff --git a/libraries/redshop/entity/newsletter.php b/libraries/redshop/entity/newsletter.php index a5ea5bf0f26..0ba55cd733d 100644 --- a/libraries/redshop/entity/newsletter.php +++ b/libraries/redshop/entity/newsletter.php @@ -18,15 +18,15 @@ */ class RedshopEntityNewsletter extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Newsletter_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Newsletter_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/order.php b/libraries/redshop/entity/order.php index 883b1757d68..ac92052ae81 100644 --- a/libraries/redshop/entity/order.php +++ b/libraries/redshop/entity/order.php @@ -18,401 +18,372 @@ */ class RedshopEntityOrder extends RedshopEntity { - /** - * @var RedshopEntitiesCollection - * - * @since 2.0.6 - */ - protected $orderItems; - - /** - * @var RedshopEntityOrder_Payment - * - * @since 2.0.6 - */ - protected $payment; - - /** - * @var RedshopEntitiesCollection - * - * @since 2.0.6 - */ - protected $users; - - /** - * @var RedshopEntityOrder_User - * - * @since 2.0.6 - */ - protected $billing; - - /** - * @var RedshopEntityOrder_User - * - * @since 2.0.6 - */ - protected $shipping; - - /** - * @var array - * - * @since 2.0.6 - */ - protected $statusLog; - - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return boolean|Tableorder_detail - */ - public function getTable($name = null) - { - return JTable::getInstance('Order_Detail', 'Table'); - } - - /** - * Method for get order items for this order - * - * @return RedshopEntitiesCollection RedshopEntitiesCollection if success. Null otherwise. - * - * @since 2.0.6 - */ - public function getOrderItems() - { - if (!$this->hasId()) - { - return null; - } - - if (null === $this->orderItems) - { - $this->loadOrderItems(); - } - - return $this->orderItems; - } - - /** - * Method for get order status log for this order - * - * @return array RedshopEntitiesCollection if success. Null otherwise. - * - * @since 2.0.6 - */ - public function getStatusLog() - { - if (!$this->hasId()) - { - return null; - } - - if (null === $this->statusLog) - { - $this->loadStatusLog(); - } - - return $this->statusLog; - } - - /** - * Method for get payment for this order - * - * @return RedshopEntityOrder_Payment Payment data if success. Null otherwise. - * - * @since 2.0.6 - */ - public function getPayment() - { - if (!$this->hasId()) - { - return null; - } - - if (null === $this->payment) - { - $this->loadPayment(); - } - - return $this->payment; - } - - /** - * Method for get users of this order - * - * @return RedshopEntitiesCollection Collection of users if success. Null otherwise. - * - * @since 2.0.6 - */ - public function getUsers() - { - if (!$this->hasId()) - { - return null; - } - - if (null === $this->users) - { - $this->loadUsers(); - } - - return $this->users; - } - - /** - * Method for get billing information of this order - * - * @return RedshopEntityOrder_User User infor if success. Null otherwise. - * - * @since 2.0.6 - */ - public function getBilling() - { - if (!$this->hasId()) - { - return null; - } - - if (null === $this->billing) - { - $this->loadBilling(); - } - - return $this->billing; - } - - /** - * Method for get shipping information of this order - * - * @return RedshopEntityOrder_User User infor if success. Null otherwise. - * - * @since 2.0.6 - */ - public function getShipping() - { - if (!$this->hasId()) - { - return null; - } - - if (null === $this->shipping) - { - $this->loadShipping(); - } - - return $this->shipping; - } - - /** - * Method for load order items for this order - * - * @return self - * - * @since 2.0.6 - */ - protected function loadOrderItems() - { - if (!$this->hasId()) - { - return $this; - } - - $this->orderItems = new RedshopEntitiesCollection; - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_order_item')) - ->where($db->qn('order_id') . ' = ' . $this->getId()); - $orderItems = $db->setQuery($query)->loadObjectList(); - - if (empty($orderItems)) - { - return $this; - } - - foreach ($orderItems as $orderItem) - { - $entity = RedshopEntityOrder_Item::getInstance($orderItem->order_item_id); - $entity->bind($orderItem); - - $this->orderItems->add($entity); - } - - return $this; - } - - /** - * Method for load order status log for this order - * - * @return self - * - * @since 2.0.6 - */ - protected function loadStatusLog() - { - if (!$this->hasId()) - { - return $this; - } - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('l.*') - ->select($db->qn('s.order_status_name')) - ->from($db->qn('#__redshop_order_status_log', 'l')) - ->leftJoin( - $db->qn('#__redshop_order_status', 's') . ' ON ' - . $db->qn('l.order_status') . ' = ' . $db->qn('s.order_status_code') - ) - ->where($db->qn('l.order_id') . ' = ' . $this->getId()); - - $this->statusLog = $db->setQuery($query)->loadObjectList(); - - return $this; - } - - /** - * Method for load payment of this order - * - * @return self - * - * @since 2.0.6 - */ - protected function loadPayment() - { - if (!$this->hasId()) - { - return $this; - } - - $this->payment = RedshopEntityOrder_Payment::getInstance(); - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_order_payment')) - ->where($db->qn('order_id') . ' = ' . (int) $this->getId()); - $result = $db->setQuery($query)->loadObject(); - - if (empty($result)) - { - return $this; - } - - $this->payment = RedshopEntityOrder_Payment::getInstance($result->payment_order_id)->bind($result); - $this->payment->loadPlugin(); - - return $this; - } - - /** - * Method for load users of this order - * - * @return self - * - * @since 2.0.6 - */ - protected function loadUsers() - { - if (!$this->hasId()) - { - return $this; - } - - $this->users = new RedshopEntitiesCollection; - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_order_users_info')) - ->where($db->qn('order_id') . ' = ' . (int) $this->getId()); - $results = $db->setQuery($query)->loadObjectList(); - - if (empty($results)) - { - return $this; - } - - foreach ($results as $result) - { - $entity = RedshopEntityOrder_User::getInstance($result->order_info_id)->bind($result)->loadExtraFields(); - - $this->users->add($entity); - } - - return $this; - } - - /** - * Method for load billing user information of this order - * - * @return self - * - * @since 2.0.6 - */ - protected function loadBilling() - { - if (!$this->hasId()) - { - return $this; - } - - $this->billing = RedshopEntityOrder_User::getInstance(); - $users = $this->getUsers(); - - if ($users->isEmpty()) - { - return $this; - } - - foreach ($users as $user) - { - if ($user->get('address_type') == 'BT') - { - $this->billing = $user; - - return $this; - } - } - - return $this; - } - - /** - * Method for load shipping user information of this order - * - * @return self - * - * @since 2.0.6 - */ - protected function loadShipping() - { - if (!$this->hasId()) - { - return $this; - } - - $this->shipping = RedshopEntityOrder_User::getInstance(); - $users = $this->getUsers(); - - if ($users->isEmpty()) - { - return $this; - } - - foreach ($users as $user) - { - if ($user->get('address_type') == 'ST') - { - $this->shipping = $user; - - return $this; - } - } - - return $this; - } + /** + * @var RedshopEntitiesCollection + * + * @since 2.0.6 + */ + protected $orderItems; + + /** + * @var RedshopEntityOrder_Payment + * + * @since 2.0.6 + */ + protected $payment; + + /** + * @var RedshopEntitiesCollection + * + * @since 2.0.6 + */ + protected $users; + + /** + * @var RedshopEntityOrder_User + * + * @since 2.0.6 + */ + protected $billing; + + /** + * @var RedshopEntityOrder_User + * + * @since 2.0.6 + */ + protected $shipping; + + /** + * @var array + * + * @since 2.0.6 + */ + protected $statusLog; + + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return boolean|Tableorder_detail + */ + public function getTable($name = null) + { + return JTable::getInstance('Order_Detail', 'Table'); + } + + /** + * Method for get order items for this order + * + * @return RedshopEntitiesCollection RedshopEntitiesCollection if success. Null otherwise. + * + * @since 2.0.6 + */ + public function getOrderItems() + { + if (!$this->hasId()) { + return null; + } + + if (null === $this->orderItems) { + $this->loadOrderItems(); + } + + return $this->orderItems; + } + + /** + * Method for load order items for this order + * + * @return self + * + * @since 2.0.6 + */ + protected function loadOrderItems() + { + if (!$this->hasId()) { + return $this; + } + + $this->orderItems = new RedshopEntitiesCollection; + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_order_item')) + ->where($db->qn('order_id') . ' = ' . $this->getId()); + $orderItems = $db->setQuery($query)->loadObjectList(); + + if (empty($orderItems)) { + return $this; + } + + foreach ($orderItems as $orderItem) { + $entity = RedshopEntityOrder_Item::getInstance($orderItem->order_item_id); + $entity->bind($orderItem); + + $this->orderItems->add($entity); + } + + return $this; + } + + /** + * Method for get order status log for this order + * + * @return array RedshopEntitiesCollection if success. Null otherwise. + * + * @since 2.0.6 + */ + public function getStatusLog() + { + if (!$this->hasId()) { + return null; + } + + if (null === $this->statusLog) { + $this->loadStatusLog(); + } + + return $this->statusLog; + } + + /** + * Method for load order status log for this order + * + * @return self + * + * @since 2.0.6 + */ + protected function loadStatusLog() + { + if (!$this->hasId()) { + return $this; + } + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('l.*') + ->select($db->qn('s.order_status_name')) + ->from($db->qn('#__redshop_order_status_log', 'l')) + ->leftJoin( + $db->qn('#__redshop_order_status', 's') . ' ON ' + . $db->qn('l.order_status') . ' = ' . $db->qn('s.order_status_code') + ) + ->where($db->qn('l.order_id') . ' = ' . $this->getId()); + + $this->statusLog = $db->setQuery($query)->loadObjectList(); + + return $this; + } + + /** + * Method for get payment for this order + * + * @return RedshopEntityOrder_Payment Payment data if success. Null otherwise. + * + * @since 2.0.6 + */ + public function getPayment() + { + if (!$this->hasId()) { + return null; + } + + if (null === $this->payment) { + $this->loadPayment(); + } + + return $this->payment; + } + + /** + * Method for load payment of this order + * + * @return self + * + * @since 2.0.6 + */ + protected function loadPayment() + { + if (!$this->hasId()) { + return $this; + } + + $this->payment = RedshopEntityOrder_Payment::getInstance(); + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_order_payment')) + ->where($db->qn('order_id') . ' = ' . (int)$this->getId()); + $result = $db->setQuery($query)->loadObject(); + + if (empty($result)) { + return $this; + } + + $this->payment = RedshopEntityOrder_Payment::getInstance($result->payment_order_id)->bind($result); + $this->payment->loadPlugin(); + + return $this; + } + + /** + * Method for get billing information of this order + * + * @return RedshopEntityOrder_User User infor if success. Null otherwise. + * + * @since 2.0.6 + */ + public function getBilling() + { + if (!$this->hasId()) { + return null; + } + + if (null === $this->billing) { + $this->loadBilling(); + } + + return $this->billing; + } + + /** + * Method for load billing user information of this order + * + * @return self + * + * @since 2.0.6 + */ + protected function loadBilling() + { + if (!$this->hasId()) { + return $this; + } + + $this->billing = RedshopEntityOrder_User::getInstance(); + $users = $this->getUsers(); + + if ($users->isEmpty()) { + return $this; + } + + foreach ($users as $user) { + if ($user->get('address_type') == 'BT') { + $this->billing = $user; + + return $this; + } + } + + return $this; + } + + /** + * Method for get users of this order + * + * @return RedshopEntitiesCollection Collection of users if success. Null otherwise. + * + * @since 2.0.6 + */ + public function getUsers() + { + if (!$this->hasId()) { + return null; + } + + if (null === $this->users) { + $this->loadUsers(); + } + + return $this->users; + } + + /** + * Method for load users of this order + * + * @return self + * + * @since 2.0.6 + */ + protected function loadUsers() + { + if (!$this->hasId()) { + return $this; + } + + $this->users = new RedshopEntitiesCollection; + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_order_users_info')) + ->where($db->qn('order_id') . ' = ' . (int)$this->getId()); + $results = $db->setQuery($query)->loadObjectList(); + + if (empty($results)) { + return $this; + } + + foreach ($results as $result) { + $entity = RedshopEntityOrder_User::getInstance($result->order_info_id)->bind($result)->loadExtraFields(); + + $this->users->add($entity); + } + + return $this; + } + + /** + * Method for get shipping information of this order + * + * @return RedshopEntityOrder_User User infor if success. Null otherwise. + * + * @since 2.0.6 + */ + public function getShipping() + { + if (!$this->hasId()) { + return null; + } + + if (null === $this->shipping) { + $this->loadShipping(); + } + + return $this->shipping; + } + + /** + * Method for load shipping user information of this order + * + * @return self + * + * @since 2.0.6 + */ + protected function loadShipping() + { + if (!$this->hasId()) { + return $this; + } + + $this->shipping = RedshopEntityOrder_User::getInstance(); + $users = $this->getUsers(); + + if ($users->isEmpty()) { + return $this; + } + + foreach ($users as $user) { + if ($user->get('address_type') == 'ST') { + $this->shipping = $user; + + return $this; + } + } + + return $this; + } } diff --git a/libraries/redshop/entity/order_item.php b/libraries/redshop/entity/order_item.php index 30df7a62345..d70102b875c 100644 --- a/libraries/redshop/entity/order_item.php +++ b/libraries/redshop/entity/order_item.php @@ -18,84 +18,79 @@ */ class RedshopEntityOrder_Item extends RedshopEntity { - /** - * @var RedshopEntitiesCollection - * - * @since 2.0.6 - */ - protected $accessoryItems; + /** + * @var RedshopEntitiesCollection + * + * @since 2.0.6 + */ + protected $accessoryItems; - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Order_Item_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Order_Item_Detail', 'Table'); + } - /** - * Method for get accessory items for this order item - * - * @return RedshopEntitiesCollection RedshopEntitiesCollection if success. Null otherwise. - * - * @since 2.0.6 - */ - public function getAccessoryItems() - { - if (!$this->hasId()) - { - return null; - } + /** + * Method for get accessory items for this order item + * + * @return RedshopEntitiesCollection RedshopEntitiesCollection if success. Null otherwise. + * + * @since 2.0.6 + */ + public function getAccessoryItems() + { + if (!$this->hasId()) { + return null; + } - if (null === $this->accessoryItems) - { - $this->loadAccessoryItems(); - } + if (null === $this->accessoryItems) { + $this->loadAccessoryItems(); + } - return $this->accessoryItems; - } + return $this->accessoryItems; + } - /** - * Method for load accessory items for this order item - * - * @return self - * - * @since 2.0.6 - */ - protected function loadAccessoryItems() - { - if (!$this->hasId()) - { - return $this; - } + /** + * Method for load accessory items for this order item + * + * @return self + * + * @since 2.0.6 + */ + protected function loadAccessoryItems() + { + if (!$this->hasId()) { + return $this; + } - $this->accessoryItems = new RedshopEntitiesCollection; + $this->accessoryItems = new RedshopEntitiesCollection; - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_order_acc_item')) - ->where($db->qn('order_item_id') . ' = ' . $this->getId()); - $items = $db->setQuery($query)->loadObjectList(); + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_order_acc_item')) + ->where($db->qn('order_item_id') . ' = ' . $this->getId()); + $items = $db->setQuery($query)->loadObjectList(); - if (empty($items)) - { - return $this; - } + if (empty($items)) { + return $this; + } - foreach ($items as $item) - { - $entity = RedshopEntityOrder_Item_Accessory::getInstance($item->order_item_acc_id); + foreach ($items as $item) { + $entity = RedshopEntityOrder_Item_Accessory::getInstance($item->order_item_acc_id); - $entity->bind($item); + $entity->bind($item); - $this->accessoryItems->add($entity); - } + $this->accessoryItems->add($entity); + } - return $this; - } + return $this; + } } diff --git a/libraries/redshop/entity/order_item_accessory.php b/libraries/redshop/entity/order_item_accessory.php index 1721e99b940..59cb64936d4 100644 --- a/libraries/redshop/entity/order_item_accessory.php +++ b/libraries/redshop/entity/order_item_accessory.php @@ -18,15 +18,15 @@ */ class RedshopEntityOrder_Item_Accessory extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Order_Acc_Item', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Order_Acc_Item', 'Table'); + } } diff --git a/libraries/redshop/entity/order_item_attribute.php b/libraries/redshop/entity/order_item_attribute.php index 22364e42b01..bb5e8d250a2 100644 --- a/libraries/redshop/entity/order_item_attribute.php +++ b/libraries/redshop/entity/order_item_attribute.php @@ -18,15 +18,15 @@ */ class RedshopEntityOrder_Item_Attribute extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Order_Attribute_Item', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Order_Attribute_Item', 'Table'); + } } diff --git a/libraries/redshop/entity/order_payment.php b/libraries/redshop/entity/order_payment.php index 681367a107e..7947575eaf2 100644 --- a/libraries/redshop/entity/order_payment.php +++ b/libraries/redshop/entity/order_payment.php @@ -20,45 +20,42 @@ */ class RedshopEntityOrder_Payment extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Order_Payment', 'Table'); - } - - /** - * Method for load plugin data of this payment - * - * @return self - * - * @since 2.0.6 - */ - public function loadPlugin() - { - if (!$this->hasId() || !is_null($this->get('plugin', null))) - { - return $this; - } - - if (!empty($this->get('payment_method_class'))) - { - // Get plugin information - $plugin = JPluginHelper::getPlugin('redshop_payment', $this->get('payment_method_class')); - - if ($plugin) - { - $plugin->params = new Registry($plugin->params); - } - - $this->set('plugin', $plugin); - } - - return $this; - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Order_Payment', 'Table'); + } + + /** + * Method for load plugin data of this payment + * + * @return self + * + * @since 2.0.6 + */ + public function loadPlugin() + { + if (!$this->hasId() || !is_null($this->get('plugin', null))) { + return $this; + } + + if (!empty($this->get('payment_method_class'))) { + // Get plugin information + $plugin = JPluginHelper::getPlugin('redshop_payment', $this->get('payment_method_class')); + + if ($plugin) { + $plugin->params = new Registry($plugin->params); + } + + $this->set('plugin', $plugin); + } + + return $this; + } } diff --git a/libraries/redshop/entity/order_status_log.php b/libraries/redshop/entity/order_status_log.php index 6406ba66399..edc38e17559 100644 --- a/libraries/redshop/entity/order_status_log.php +++ b/libraries/redshop/entity/order_status_log.php @@ -18,15 +18,15 @@ */ class RedshopEntityOrder_Status_Log extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Order_Status_Log', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Order_Status_Log', 'Table'); + } } diff --git a/libraries/redshop/entity/order_user.php b/libraries/redshop/entity/order_user.php index 8c15a575a9b..eca2b7f5d55 100644 --- a/libraries/redshop/entity/order_user.php +++ b/libraries/redshop/entity/order_user.php @@ -18,77 +18,73 @@ */ class RedshopEntityOrder_User extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return JTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Order_User_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return JTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Order_User_Detail', 'Table'); + } - /** - * Method for load plugin data of this payment - * - * @return self - * - * @since 2.0.6 - */ - public function loadExtraFields() - { - if (!$this->hasId() || !is_null($this->get('fields', null))) - { - return $this; - } + /** + * Method for load plugin data of this payment + * + * @return self + * + * @since 2.0.6 + */ + public function loadExtraFields() + { + if (!$this->hasId() || !is_null($this->get('fields', null))) { + return $this; + } - $this->set('email', $this->get('user_email')); + $this->set('email', $this->get('user_email')); - $privateSection = RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS; - $companySection = RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS; + $privateSection = RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS; + $companySection = RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS; - if ($this->get('address_type', '') == 'ST') - { - $privateSection = RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS; - $companySection = RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS; - } + if ($this->get('address_type', '') == 'ST') { + $privateSection = RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS; + $companySection = RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS; + } - $db = JFactory::getDbo(); + $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('f.name') . ',' . $db->qn('fd.data_txt')) - ->from($db->qn('#__redshop_fields_data', 'fd')) - ->leftJoin($db->qn('#__redshop_fields', 'f') . ' ON ' . $db->qn('f.id') . '=' . $db->qn('fd.fieldid')) - ->where( - '(' - . $db->qn('fd.section') . ' = ' . $privateSection - . ' OR ' - . $db->qn('fd.section') . ' = ' . $companySection - . ')' - ) - ->where($db->qn('fd.itemid') . ' = ' . $this->get('users_info_id')); + $query = $db->getQuery(true) + ->select($db->qn('f.name') . ',' . $db->qn('fd.data_txt')) + ->from($db->qn('#__redshop_fields_data', 'fd')) + ->leftJoin($db->qn('#__redshop_fields', 'f') . ' ON ' . $db->qn('f.id') . '=' . $db->qn('fd.fieldid')) + ->where( + '(' + . $db->qn('fd.section') . ' = ' . $privateSection + . ' OR ' + . $db->qn('fd.section') . ' = ' . $companySection + . ')' + ) + ->where($db->qn('fd.itemid') . ' = ' . $this->get('users_info_id')); - // Set the query and load the result. - $results = $db->setQuery($query)->loadObjectList(); + // Set the query and load the result. + $results = $db->setQuery($query)->loadObjectList(); - if (empty($results)) - { - $this->set('fields', array()); + if (empty($results)) { + $this->set('fields', array()); - return $this; - } + return $this; + } - $fieldsData = array(); + $fieldsData = array(); - foreach ($results as $result) - { - $fieldsData[$result->name] = $result->data_txt; - } + foreach ($results as $result) { + $fieldsData[$result->name] = $result->data_txt; + } - $this->set('fields', $fieldsData); + $this->set('fields', $fieldsData); - return $this; - } + return $this; + } } diff --git a/libraries/redshop/entity/price.php b/libraries/redshop/entity/price.php index 2c9bfdbc093..9796b7d563f 100644 --- a/libraries/redshop/entity/price.php +++ b/libraries/redshop/entity/price.php @@ -18,15 +18,15 @@ */ class RedshopEntityPrice extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Prices_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Prices_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/product.php b/libraries/redshop/entity/product.php index 41805b0ff19..c3b7da27530 100644 --- a/libraries/redshop/entity/product.php +++ b/libraries/redshop/entity/product.php @@ -18,185 +18,171 @@ */ class RedshopEntityProduct extends RedshopEntity { - use \Redshop\Entity\Traits\Product\Related, - \Redshop\Entity\Traits\Product\Categories, - \Redshop\Entity\Traits\Product\Media, - \Redshop\Entity\Traits\Product\Stock; - - /** - * @var RedshopEntitiesCollection Collections of child products - */ - protected $childProducts = null; - - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return JTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Product_Detail', 'Table'); - } - - /** - * Method for get child products - * - * @param boolean $reload Force reload even it's cached - * - * @return RedshopEntitiesCollection - * - * @since 2.1.0 - */ - public function getChildProducts($reload = false) - { - if (null === $this->childProducts || $reload === true) - { - $this->loadChild(); - } - - return $this->childProducts; - } - - /** - * Method to load child product - * - * @return self - * - * @since 2.1.0 - */ - protected function loadChild() - { - if (!$this->hasId()) - { - return $this; - } - - $this->childProducts = new RedshopEntitiesCollection; - - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select($db->quoteName('product_id')) - ->from($db->quoteName('#__redshop_product')) - ->where($db->quoteName('product_parent_id') . ' = ' . (int) $this->getId()); - - $productIds = $db->setQuery($query)->loadColumn(); - - foreach ($productIds as $productId) - { - $this->childProducts->add(self::getInstance($productId)); - } - - return $this; - } - - /** - * Assign a product with a custom field - * - * @param integer $fieldId Field id - * @param string $value Field value - * - * @return boolean - */ - public function assignCustomField($fieldId, $value) - { - // Try to load this custom field data - /** @var RedshopEntityField_Data $entity */ - $entity = RedshopEntityField_Data::getInstance()->loadItemByArray( - array - ( - 'fieldid' => $fieldId, - 'itemid' => $this->id, - // Product section - 'section' => 1 - ) - ); - - // This custom field data is not linked with this product than create it - if ($entity->hasId()) - { - return true; - } - - return (boolean) $entity->save( - array - ( - 'fieldid' => $fieldId, - 'data_txt' => $value, - 'itemid' => $this->id, - 'section' => 1 - ) - ); - } - - /** - * @param float $productPrice Product price - * @param integer $userId User id - * @param integer $taxExempt Tax - * - * @return boolean|float|integer - * - * @since 2.1.0 - */ - public function getTax($productPrice = 0.0, $userId = 0, $taxExempt = 0) - { - if (!$this->hasId()) - { - return false; - } - - $redshopUser = \JFactory::getSession()->get('rs_user'); - - if ($userId == 0) - { - $user = \JFactory::getUser(); - $userId = $user->id; - } - - $productTax = 0; - $redshopUser = empty($redshopUser) ? array('rs_is_user_login' => 0) : $redshopUser; - - if ($redshopUser['rs_is_user_login'] == 0 && $userId != 0) - { - \RedshopHelperUser::createUserSession($userId); - } - - $vatRateData = \RedshopHelperTax::getVatRates($this->getId(), $userId); - $taxRate = !empty($vatRateData) ? $vatRateData->tax_rate : 0; - - if ($productPrice <= 0) - { - $productPrice = $this->get('product_price', $productPrice); - } - - $productPrice = \RedshopHelperProductPrice::priceRound((float) $productPrice); - - if ($taxExempt) - { - return $productPrice * $taxRate; - } - - if (!$taxRate) - { - return \RedshopHelperProductPrice::priceRound($productTax); - } - - if (!$userId) - { - $productTax = $productPrice * $taxRate; - } - else - { - $userInformation = \RedshopHelperUser::getUserInformation($userId); - - if (null === $userInformation || $userInformation->requesting_tax_exempt !== 1 || !$userInformation->tax_exempt_approved) - { - $productTax = $productPrice * $taxRate; - } - } - - return \RedshopHelperProductPrice::priceRound($productTax); - } + use \Redshop\Entity\Traits\Product\Related, + \Redshop\Entity\Traits\Product\Categories, + \Redshop\Entity\Traits\Product\Media, + \Redshop\Entity\Traits\Product\Stock; + + /** + * @var RedshopEntitiesCollection Collections of child products + */ + protected $childProducts = null; + + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return JTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Product_Detail', 'Table'); + } + + /** + * Method for get child products + * + * @param boolean $reload Force reload even it's cached + * + * @return RedshopEntitiesCollection + * + * @since 2.1.0 + */ + public function getChildProducts($reload = false) + { + if (null === $this->childProducts || $reload === true) { + $this->loadChild(); + } + + return $this->childProducts; + } + + /** + * Method to load child product + * + * @return self + * + * @since 2.1.0 + */ + protected function loadChild() + { + if (!$this->hasId()) { + return $this; + } + + $this->childProducts = new RedshopEntitiesCollection; + + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select($db->quoteName('product_id')) + ->from($db->quoteName('#__redshop_product')) + ->where($db->quoteName('product_parent_id') . ' = ' . (int)$this->getId()); + + $productIds = $db->setQuery($query)->loadColumn(); + + foreach ($productIds as $productId) { + $this->childProducts->add(self::getInstance($productId)); + } + + return $this; + } + + /** + * Assign a product with a custom field + * + * @param integer $fieldId Field id + * @param string $value Field value + * + * @return boolean + */ + public function assignCustomField($fieldId, $value) + { + // Try to load this custom field data + /** @var RedshopEntityField_Data $entity */ + $entity = RedshopEntityField_Data::getInstance()->loadItemByArray( + array + ( + 'fieldid' => $fieldId, + 'itemid' => $this->id, + // Product section + 'section' => 1 + ) + ); + + // This custom field data is not linked with this product than create it + if ($entity->hasId()) { + return true; + } + + return (boolean)$entity->save( + array + ( + 'fieldid' => $fieldId, + 'data_txt' => $value, + 'itemid' => $this->id, + 'section' => 1 + ) + ); + } + + /** + * @param float $productPrice Product price + * @param integer $userId User id + * @param integer $taxExempt Tax + * + * @return boolean|float|integer + * + * @since 2.1.0 + */ + public function getTax($productPrice = 0.0, $userId = 0, $taxExempt = 0) + { + if (!$this->hasId()) { + return false; + } + + $redshopUser = \JFactory::getSession()->get('rs_user'); + + if ($userId == 0) { + $user = \JFactory::getUser(); + $userId = $user->id; + } + + $productTax = 0; + $redshopUser = empty($redshopUser) ? array('rs_is_user_login' => 0) : $redshopUser; + + if ($redshopUser['rs_is_user_login'] == 0 && $userId != 0) { + \RedshopHelperUser::createUserSession($userId); + } + + $vatRateData = \RedshopHelperTax::getVatRates($this->getId(), $userId); + $taxRate = !empty($vatRateData) ? $vatRateData->tax_rate : 0; + + if ($productPrice <= 0) { + $productPrice = $this->get('product_price', $productPrice); + } + + $productPrice = \RedshopHelperProductPrice::priceRound((float)$productPrice); + + if ($taxExempt) { + return $productPrice * $taxRate; + } + + if (!$taxRate) { + return \RedshopHelperProductPrice::priceRound($productTax); + } + + if (!$userId) { + $productTax = $productPrice * $taxRate; + } else { + $userInformation = \RedshopHelperUser::getUserInformation($userId); + + if (null === $userInformation || $userInformation->requesting_tax_exempt !== 1 || !$userInformation->tax_exempt_approved) { + $productTax = $productPrice * $taxRate; + } + } + + return \RedshopHelperProductPrice::priceRound($productTax); + } } diff --git a/libraries/redshop/entity/product_compare.php b/libraries/redshop/entity/product_compare.php index d7aa3989729..a9dedf29d9a 100644 --- a/libraries/redshop/entity/product_compare.php +++ b/libraries/redshop/entity/product_compare.php @@ -18,15 +18,15 @@ */ class RedshopEntityProduct_Compare extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Product_Compare', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Product_Compare', 'Table'); + } } diff --git a/libraries/redshop/entity/product_discount.php b/libraries/redshop/entity/product_discount.php index 5faaff8a3d0..559e477b751 100644 --- a/libraries/redshop/entity/product_discount.php +++ b/libraries/redshop/entity/product_discount.php @@ -18,15 +18,15 @@ */ class RedshopEntityProduct_Discount extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Discount_Product', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Discount_Product', 'Table'); + } } diff --git a/libraries/redshop/entity/product_discount_calculate.php b/libraries/redshop/entity/product_discount_calculate.php index a58329c0f98..104ba44c59d 100644 --- a/libraries/redshop/entity/product_discount_calculate.php +++ b/libraries/redshop/entity/product_discount_calculate.php @@ -18,15 +18,15 @@ */ class RedshopEntityProduct_Discount_Calculate extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Product_Discount_Calc', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Product_Discount_Calc', 'Table'); + } } diff --git a/libraries/redshop/entity/product_discount_calculate_extra.php b/libraries/redshop/entity/product_discount_calculate_extra.php index 0f9e096201f..b8157bccda1 100644 --- a/libraries/redshop/entity/product_discount_calculate_extra.php +++ b/libraries/redshop/entity/product_discount_calculate_extra.php @@ -18,15 +18,15 @@ */ class RedshopEntityProduct_Discount_Calculate_Extra extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Product_Discount_Calc_Extra', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Product_Discount_Calc_Extra', 'Table'); + } } diff --git a/libraries/redshop/entity/product_serial.php b/libraries/redshop/entity/product_serial.php index 6fd2e169f2b..3954dd4a319 100644 --- a/libraries/redshop/entity/product_serial.php +++ b/libraries/redshop/entity/product_serial.php @@ -18,15 +18,15 @@ */ class RedshopEntityProduct_Serial extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Product_Serial_Number', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Product_Serial_Number', 'Table'); + } } diff --git a/libraries/redshop/entity/product_subscribe.php b/libraries/redshop/entity/product_subscribe.php index 20d1ebaf85c..5f7cce66728 100644 --- a/libraries/redshop/entity/product_subscribe.php +++ b/libraries/redshop/entity/product_subscribe.php @@ -18,15 +18,15 @@ */ class RedshopEntityProduct_Subscribe extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Product_Subscribe_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Product_Subscribe_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/product_subscription.php b/libraries/redshop/entity/product_subscription.php index 6adcb06c392..905aa9753a8 100644 --- a/libraries/redshop/entity/product_subscription.php +++ b/libraries/redshop/entity/product_subscription.php @@ -18,15 +18,15 @@ */ class RedshopEntityProduct_Subscription extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Product_Subscription', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Product_Subscription', 'Table'); + } } diff --git a/libraries/redshop/entity/product_subscription_renewal.php b/libraries/redshop/entity/product_subscription_renewal.php index 629ccb6c66d..216b2489540 100644 --- a/libraries/redshop/entity/product_subscription_renewal.php +++ b/libraries/redshop/entity/product_subscription_renewal.php @@ -18,15 +18,15 @@ */ class RedshopEntityProduct_Subscription_Renewal extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Product_Subscription_Renewal', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Product_Subscription_Renewal', 'Table'); + } } diff --git a/libraries/redshop/entity/product_tag.php b/libraries/redshop/entity/product_tag.php index 28974d452cb..df683893959 100644 --- a/libraries/redshop/entity/product_tag.php +++ b/libraries/redshop/entity/product_tag.php @@ -18,15 +18,15 @@ */ class RedshopEntityProduct_Tag extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Product_Tags', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Product_Tags', 'Table'); + } } diff --git a/libraries/redshop/entity/property.php b/libraries/redshop/entity/property.php index 69b7dd8560d..05e90dd7469 100644 --- a/libraries/redshop/entity/property.php +++ b/libraries/redshop/entity/property.php @@ -18,15 +18,15 @@ */ class RedshopEntityProperty extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Attribute_Property', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Attribute_Property', 'Table'); + } } diff --git a/libraries/redshop/entity/quotation.php b/libraries/redshop/entity/quotation.php index aac63ae19f0..f8f61863f6d 100644 --- a/libraries/redshop/entity/quotation.php +++ b/libraries/redshop/entity/quotation.php @@ -18,15 +18,15 @@ */ class RedshopEntityQuotation extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Quotation_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Quotation_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/quotation_item.php b/libraries/redshop/entity/quotation_item.php index c8a13f78b45..f3fff6ad098 100644 --- a/libraries/redshop/entity/quotation_item.php +++ b/libraries/redshop/entity/quotation_item.php @@ -18,15 +18,15 @@ */ class RedshopEntityQuotation_Item extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Quotation_Item_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Quotation_Item_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/quotation_item_accessory.php b/libraries/redshop/entity/quotation_item_accessory.php index 9badb46baca..6e108e73ecb 100644 --- a/libraries/redshop/entity/quotation_item_accessory.php +++ b/libraries/redshop/entity/quotation_item_accessory.php @@ -18,15 +18,15 @@ */ class RedshopEntityQuotation_Item_Accessory extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Quotation_Accessory_Item', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Quotation_Accessory_Item', 'Table'); + } } diff --git a/libraries/redshop/entity/quotation_item_attribute.php b/libraries/redshop/entity/quotation_item_attribute.php index ef9aac5b609..28e57e57df8 100644 --- a/libraries/redshop/entity/quotation_item_attribute.php +++ b/libraries/redshop/entity/quotation_item_attribute.php @@ -18,15 +18,15 @@ */ class RedshopEntityQuotation_Item_Attribute extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Quotation_Attribute_Item', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Quotation_Attribute_Item', 'Table'); + } } diff --git a/libraries/redshop/entity/rating.php b/libraries/redshop/entity/rating.php index adae3da15f9..1f2a0f0b5f4 100644 --- a/libraries/redshop/entity/rating.php +++ b/libraries/redshop/entity/rating.php @@ -18,15 +18,15 @@ */ class RedshopEntityRating extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Rating_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Rating_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/shipping.php b/libraries/redshop/entity/shipping.php index 4171f48360c..7c1cb5c0146 100644 --- a/libraries/redshop/entity/shipping.php +++ b/libraries/redshop/entity/shipping.php @@ -18,15 +18,15 @@ */ class RedshopEntityShipping extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Shipping_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Shipping_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/shipping_rate.php b/libraries/redshop/entity/shipping_rate.php index f163d555915..17bad435e48 100644 --- a/libraries/redshop/entity/shipping_rate.php +++ b/libraries/redshop/entity/shipping_rate.php @@ -18,15 +18,15 @@ */ class RedshopEntityShipping_Rate extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Shipping_Rate_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Shipping_Rate_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/shopper_group.php b/libraries/redshop/entity/shopper_group.php index d89ecd2c9b8..f44471c24c1 100644 --- a/libraries/redshop/entity/shopper_group.php +++ b/libraries/redshop/entity/shopper_group.php @@ -18,80 +18,75 @@ */ class RedshopEntityShopper_Group extends RedshopEntity { - /** - * @var RedshopEntitiesCollection - * - * @since 2.0.6 - */ - protected $discounts; + /** + * @var RedshopEntitiesCollection + * + * @since 2.0.6 + */ + protected $discounts; - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Shopper_Group_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Shopper_Group_Detail', 'Table'); + } - /** - * Method for get discounts of this shopper group - * - * @return RedshopEntitiesCollection RedshopEntitiesCollection if success. Null otherwise. - * - * @since 2.0.6 - */ - public function getDiscounts() - { - if (!$this->hasId()) - { - return null; - } + /** + * Method for get discounts of this shopper group + * + * @return RedshopEntitiesCollection RedshopEntitiesCollection if success. Null otherwise. + * + * @since 2.0.6 + */ + public function getDiscounts() + { + if (!$this->hasId()) { + return null; + } - if (null === $this->discounts) - { - $this->loadDiscounts(); - } + if (null === $this->discounts) { + $this->loadDiscounts(); + } - return $this->discounts; - } + return $this->discounts; + } - /** - * Method for load discounts for this shopper group - * - * @return self - * - * @since 2.0.6 - */ - protected function loadDiscounts() - { - if (!$this->hasId()) - { - return $this; - } + /** + * Method for load discounts for this shopper group + * + * @return self + * + * @since 2.0.6 + */ + protected function loadDiscounts() + { + if (!$this->hasId()) { + return $this; + } - $this->discounts = new RedshopEntitiesCollection; + $this->discounts = new RedshopEntitiesCollection; - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('discount_id')) - ->from($db->qn('#__redshop_discount_shoppers')) - ->where($db->qn('shopper_group_id') . ' = ' . $this->getId()); - $discounts = $db->setQuery($query)->loadColumn(); + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('discount_id')) + ->from($db->qn('#__redshop_discount_shoppers')) + ->where($db->qn('shopper_group_id') . ' = ' . $this->getId()); + $discounts = $db->setQuery($query)->loadColumn(); - if (empty($discounts)) - { - return $this; - } + if (empty($discounts)) { + return $this; + } - foreach ($discounts as $discountId) - { - $this->discounts->add(RedshopEntityDiscount::getInstance($discountId)); - } + foreach ($discounts as $discountId) { + $this->discounts->add(RedshopEntityDiscount::getInstance($discountId)); + } - return $this; - } + return $this; + } } diff --git a/libraries/redshop/entity/stockroom.php b/libraries/redshop/entity/stockroom.php index 96b21ab9b3b..49bbf2f3184 100644 --- a/libraries/redshop/entity/stockroom.php +++ b/libraries/redshop/entity/stockroom.php @@ -18,15 +18,15 @@ */ class RedshopEntityStockroom extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Stockroom_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Stockroom_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/stockroom_image.php b/libraries/redshop/entity/stockroom_image.php index 0112f59de63..edaac1a6d1d 100644 --- a/libraries/redshop/entity/stockroom_image.php +++ b/libraries/redshop/entity/stockroom_image.php @@ -18,15 +18,15 @@ */ class RedshopEntityStockroom_Image extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('StockImage_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('StockImage_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/sub_attribute.php b/libraries/redshop/entity/sub_attribute.php index 9b1675d7a95..cb6ffc7ad63 100644 --- a/libraries/redshop/entity/sub_attribute.php +++ b/libraries/redshop/entity/sub_attribute.php @@ -18,15 +18,15 @@ */ class RedshopEntitySub_Attribute extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('SubAttribute_Property', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('SubAttribute_Property', 'Table'); + } } diff --git a/libraries/redshop/entity/subscription.php b/libraries/redshop/entity/subscription.php index 86f7823a015..49c4a00ab3a 100644 --- a/libraries/redshop/entity/subscription.php +++ b/libraries/redshop/entity/subscription.php @@ -18,15 +18,15 @@ */ class RedshopEntitySubscription extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('NewsletterSubscr_detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('NewsletterSubscr_detail', 'Table'); + } } diff --git a/libraries/redshop/entity/tax_group.php b/libraries/redshop/entity/tax_group.php index b5f20fe985b..840a51751ab 100644 --- a/libraries/redshop/entity/tax_group.php +++ b/libraries/redshop/entity/tax_group.php @@ -18,64 +18,60 @@ */ class RedshopEntityTax_Group extends RedshopEntity { - /** - * List of tax rates belong to this tax group - * - * @var RedshopEntitiesCollection - * - * @since 2.0.4 - */ - protected $taxRates; + /** + * List of tax rates belong to this tax group + * + * @var RedshopEntitiesCollection + * + * @since 2.0.4 + */ + protected $taxRates; - /** - * Method for get all associated tax rates - * - * @return RedshopEntitiesCollection - * - * @since 2.0.4 - */ - public function getTaxRates() - { - if (is_null($this->taxRates)) - { - $this->loadTaxRates(); - } + /** + * Method for get all associated tax rates + * + * @return RedshopEntitiesCollection + * + * @since 2.0.4 + */ + public function getTaxRates() + { + if (is_null($this->taxRates)) { + $this->loadTaxRates(); + } - return $this->taxRates; - } + return $this->taxRates; + } - /** - * Method for load all tax rates - * - * @return self - * - * @since 2.0.4 - */ - protected function loadTaxRates() - { - /** @var RedshopEntitiesCollection taxRates */ - $this->taxRates = new RedshopEntitiesCollection; + /** + * Method for load all tax rates + * + * @return self + * + * @since 2.0.4 + */ + protected function loadTaxRates() + { + /** @var RedshopEntitiesCollection taxRates */ + $this->taxRates = new RedshopEntitiesCollection; - if (!$this->hasId()) - { - return $this; - } + if (!$this->hasId()) { + return $this; + } - $model = RedshopModel::getInstance('Tax_Rates', 'RedshopModel', array('ignore_request' => true)); - $model->setState('filter.tax_group', $this->getId()); + $model = RedshopModel::getInstance('Tax_Rates', 'RedshopModel', array('ignore_request' => true)); + $model->setState('filter.tax_group', $this->getId()); - $taxRates = $model->getItems(); + $taxRates = $model->getItems(); - if (empty($taxRates)) - { - return $this; - } + if (empty($taxRates)) { + return $this; + } - foreach ($taxRates as $taxRate) - { - $this->taxRates->add(RedshopEntityTax_Rate::getInstance($taxRate->id)->bind($taxRate)); - } + foreach ($taxRates as $taxRate) { + $this->taxRates->add(RedshopEntityTax_Rate::getInstance($taxRate->id)->bind($taxRate)); + } - return $this; - } + return $this; + } } diff --git a/libraries/redshop/entity/user.php b/libraries/redshop/entity/user.php index 6224b2b0b67..f70be43d67d 100644 --- a/libraries/redshop/entity/user.php +++ b/libraries/redshop/entity/user.php @@ -18,15 +18,15 @@ */ class RedshopEntityUser extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('User_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('User_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/user_cart_item_accessory.php b/libraries/redshop/entity/user_cart_item_accessory.php index dc9307867e9..8e126b7fbdf 100644 --- a/libraries/redshop/entity/user_cart_item_accessory.php +++ b/libraries/redshop/entity/user_cart_item_accessory.php @@ -18,16 +18,16 @@ */ class RedshopEntityUser_Cart_Item_Accessory extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return JTable|boolean - * @throws Exception - */ - public function getTable($name = null) - { - return RedshopTable::getInstance('Usercart_Accessory_Item', 'RedshopTable'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return JTable|boolean + * @throws Exception + */ + public function getTable($name = null) + { + return RedshopTable::getInstance('Usercart_Accessory_Item', 'RedshopTable'); + } } diff --git a/libraries/redshop/entity/user_cart_item_attribute.php b/libraries/redshop/entity/user_cart_item_attribute.php index 74567020c0c..fb3aa3930a0 100644 --- a/libraries/redshop/entity/user_cart_item_attribute.php +++ b/libraries/redshop/entity/user_cart_item_attribute.php @@ -18,16 +18,16 @@ */ class RedshopEntityUser_Cart_Item_Attribute extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return \JTable|boolean - * @throws Exception - */ - public function getTable($name = null) - { - return RedshopTable::getInstance('usercart_attribute_item', 'RedshopTable'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return \JTable|boolean + * @throws Exception + */ + public function getTable($name = null) + { + return RedshopTable::getInstance('usercart_attribute_item', 'RedshopTable'); + } } diff --git a/libraries/redshop/entity/user_notify_stock.php b/libraries/redshop/entity/user_notify_stock.php index 92191617d44..642c068747e 100644 --- a/libraries/redshop/entity/user_notify_stock.php +++ b/libraries/redshop/entity/user_notify_stock.php @@ -18,15 +18,15 @@ */ class RedshopEntityUser_Notify_Stock extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('NotifyStock_User', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('NotifyStock_User', 'Table'); + } } diff --git a/libraries/redshop/entity/voucher.php b/libraries/redshop/entity/voucher.php index 3b20f87b2f0..dc2a31d526a 100644 --- a/libraries/redshop/entity/voucher.php +++ b/libraries/redshop/entity/voucher.php @@ -18,62 +18,58 @@ */ class RedshopEntityVoucher extends RedshopEntity { - /** - * @var RedshopEntitiesCollection - * @since 2.0.7 - */ - protected $products; + /** + * @var RedshopEntitiesCollection + * @since 2.0.7 + */ + protected $products; - /** - * Method for get products available with this voucher - * - * @return RedshopEntitiesCollection - * - * @since 2.0.7 - */ - public function getProducts() - { - if (null === $this->products) - { - $this->loadProducts(); - } + /** + * Method for get products available with this voucher + * + * @return RedshopEntitiesCollection + * + * @since 2.0.7 + */ + public function getProducts() + { + if (null === $this->products) { + $this->loadProducts(); + } - return $this->products; - } + return $this->products; + } - /** - * Method for load products available with this voucher - * - * @return self - * - * @since 2.0.7 - */ - protected function loadProducts() - { - $this->products = new RedshopEntitiesCollection; + /** + * Method for load products available with this voucher + * + * @return self + * + * @since 2.0.7 + */ + protected function loadProducts() + { + $this->products = new RedshopEntitiesCollection; - if (!$this->hasId()) - { - return $this; - } + if (!$this->hasId()) { + return $this; + } - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('product_id')) - ->from($db->qn('#__redshop_product_voucher_xref')) - ->where($db->qn('voucher_id') . ' = ' . $this->getId()); - $result = $db->setQuery($query)->loadColumn(); + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('product_id')) + ->from($db->qn('#__redshop_product_voucher_xref')) + ->where($db->qn('voucher_id') . ' = ' . $this->getId()); + $result = $db->setQuery($query)->loadColumn(); - if (empty($result)) - { - return $this; - } + if (empty($result)) { + return $this; + } - foreach ($result as $productId) - { - $this->products->add(RedshopEntityProduct::getInstance($productId)); - } + foreach ($result as $productId) { + $this->products->add(RedshopEntityProduct::getInstance($productId)); + } - return $this; - } + return $this; + } } diff --git a/libraries/redshop/entity/voucher_transaction.php b/libraries/redshop/entity/voucher_transaction.php index fbd0e63f32c..94a9eabc86b 100644 --- a/libraries/redshop/entity/voucher_transaction.php +++ b/libraries/redshop/entity/voucher_transaction.php @@ -18,15 +18,15 @@ */ class RedshopEntityVoucher_Transaction extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Transaction_Voucher_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Transaction_Voucher_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/wishlist.php b/libraries/redshop/entity/wishlist.php index c68ae3637e3..cfe3677c78f 100644 --- a/libraries/redshop/entity/wishlist.php +++ b/libraries/redshop/entity/wishlist.php @@ -18,15 +18,15 @@ */ class RedshopEntityWishlist extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Wishlist', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Wishlist', 'Table'); + } } diff --git a/libraries/redshop/entity/wrapper.php b/libraries/redshop/entity/wrapper.php index 44386bbcaa0..15cea9b00c1 100644 --- a/libraries/redshop/entity/wrapper.php +++ b/libraries/redshop/entity/wrapper.php @@ -18,15 +18,15 @@ */ class RedshopEntityWrapper extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Wrapper_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Wrapper_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/xml_export.php b/libraries/redshop/entity/xml_export.php index 61352fbe676..43933b79752 100644 --- a/libraries/redshop/entity/xml_export.php +++ b/libraries/redshop/entity/xml_export.php @@ -18,15 +18,15 @@ */ class RedshopEntityXml_Export extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('XmlExport_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('XmlExport_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/xml_import.php b/libraries/redshop/entity/xml_import.php index b905f7372ae..39471637849 100644 --- a/libraries/redshop/entity/xml_import.php +++ b/libraries/redshop/entity/xml_import.php @@ -18,15 +18,15 @@ */ class RedshopEntityXml_Import extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('XmlImport_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('XmlImport_Detail', 'Table'); + } } diff --git a/libraries/redshop/entity/zipcode.php b/libraries/redshop/entity/zipcode.php index 16622273721..fc3d08404ef 100644 --- a/libraries/redshop/entity/zipcode.php +++ b/libraries/redshop/entity/zipcode.php @@ -18,15 +18,15 @@ */ class RedshopEntityZipcode extends RedshopEntity { - /** - * Get the associated table - * - * @param string $name Main name of the Table. Example: Article for ContentTableArticle - * - * @return RedshopTable - */ - public function getTable($name = null) - { - return JTable::getInstance('Zipcode_Detail', 'Table'); - } + /** + * Get the associated table + * + * @param string $name Main name of the Table. Example: Article for ContentTableArticle + * + * @return RedshopTable + */ + public function getTable($name = null) + { + return JTable::getInstance('Zipcode_Detail', 'Table'); + } } diff --git a/libraries/redshop/form/field/calendar.php b/libraries/redshop/form/field/calendar.php index 47b8c4f866e..3b1adc863c8 100644 --- a/libraries/redshop/form/field/calendar.php +++ b/libraries/redshop/form/field/calendar.php @@ -18,196 +18,195 @@ */ class RedshopFormFieldCalendar extends JFormField { - /** - * The form field type. - * - * @var string - * @since 11.1 - */ - protected $type = 'Calendar'; - - /** - * The allowable maxlength of calendar field. - * - * @var integer - * @since 3.2 - */ - protected $maxlength; - - /** - * The format of date and time. - * - * @var string - * @since 3.2 - */ - protected $format; - - /** - * The filter. - * - * @var string - * @since 3.2 - */ - protected $filter; - - /** - * Method to get certain otherwise inaccessible properties from the form field object. - * - * @param string $name The property name for which to the the value. - * - * @return mixed The property value or null. - * - * @since 3.2 - */ - public function __get($name) - { - switch ($name) - { - case 'maxlength': - case 'format': - case 'filter': - return $this->{$name}; - } - - return parent::__get($name); - } - - /** - * Method to set certain otherwise inaccessible properties of the form field object. - * - * @param string $name The property name for which to the the value. - * @param mixed $value The value of the property. - * - * @return void - * - * @since 3.2 - */ - public function __set($name, $value) - { - switch ($name) - { - case 'maxlength': - $this->{$name} = (int) $value; - break; - - case 'format': - case 'filter': - $this->{$name} = (string) $value; - break; - - default: - parent::__set($name, $value); - } - } - - /** - * Method to attach a JForm object to the field. - * - * @param SimpleXMLElement $element The SimpleXMLElement object representing the `` tag for the form field object. - * @param mixed $value The form field value to validate. - * @param string $group The field name group control value. This acts as as an array container for the field. - * For example if the field has name="foo" and the group value is set to "bar" then the - * full field name would end up being "bar[foo]". - * - * @return boolean True on success. - * - * @see JFormField::setup() - * @since 3.2 - */ - public function setup(SimpleXMLElement $element, $value, $group = null) - { - $return = parent::setup($element, $value, $group); - - if ($return) - { - $this->maxlength = (int) $this->element['maxlength'] ? (int) $this->element['maxlength'] : 45; - $this->format = (string) $this->element['format'] ? (string) $this->element['format'] - : Redshop::getConfig()->getString('DEFAULT_DATEFORMAT', 'Y-m-d'); - $this->filter = (string) $this->element['filter'] ? (string) $this->element['filter'] : null; - } - - return $return; - } - - /** - * Method to get the field input markup. - * - * @return string The field input markup. - * - * @since 11.1 - */ - protected function getInput() - { - // Translate placeholder text - $hint = $this->translateHint ? JText::_($this->hint) : $this->hint; - - // Initialize some field attributes. - $format = $this->format; - - // Build the attributes array. - $attributes = array(); - - empty($this->size) ? null : $attributes['size'] = $this->size; - empty($this->maxlength) ? null : $attributes['maxlength'] = $this->maxlength; - empty($this->class) ? null : $attributes['class'] = $this->class; - !$this->readonly ? null : $attributes['readonly'] = 'readonly'; - !$this->disabled ? null : $attributes['disabled'] = 'disabled'; - empty($this->onchange) ? null : $attributes['onchange'] = $this->onchange; - !strlen($hint) ? null : $attributes['placeholder'] = $hint; - $this->autocomplete ? null : $attributes['autocomplete'] = 'off'; - !$this->autofocus ? null : $attributes['autofocus'] = ''; - - if ($this->required) - { - $attributes['required'] = ''; - $attributes['aria-required'] = 'true'; - } - - // Handle the special case for "now". - if (strtoupper($this->value) == 'NOW') - { - $this->value = JFactory::getDate()->toUnix(); - } - - // Get some system objects. - $config = JFactory::getConfig(); - $user = JFactory::getUser(); - $tz = $config->get('offset'); - - // If a known filter is given use it. - if (strtoupper($this->filter) == 'SERVER_UTC') - { - // Convert a date to UTC based on the server timezone. - if ($this->value && $this->value != JFactory::getDbo()->getNullDate()) - { - // Get a date object based on the correct timezone. - $date = JFactory::getDate($this->value, 'UTC'); - $date->setTimezone(new DateTimeZone($tz)); - - // Transform the date string. - $this->value = $date->format($format, true, false); - } - } - else - { - // Convert a date to UTC based on the user timezone. - if ($this->value && $this->value != JFactory::getDbo()->getNullDate()) - { - // Get a date object based on the correct timezone. - $date = JFactory::getDate($this->value, 'UTC'); - $tz = $user->getParam('timezone', $tz); - - $date->setTimezone(new DateTimeZone($tz)); - - // Transform the date string. - $this->value = $date->format($format, true, false); - } - } - - // Including fallback code for HTML5 non supported browsers. - JHtml::_('jquery.framework'); - JHtml::_('script', 'system/html5fallback.js', false, true); - - return JHtml::_('redshopcalendar.calendar', $this->value, $this->name, $this->id, $format, $attributes, null, $tz); - } + /** + * The form field type. + * + * @var string + * @since 11.1 + */ + protected $type = 'Calendar'; + + /** + * The allowable maxlength of calendar field. + * + * @var integer + * @since 3.2 + */ + protected $maxlength; + + /** + * The format of date and time. + * + * @var string + * @since 3.2 + */ + protected $format; + + /** + * The filter. + * + * @var string + * @since 3.2 + */ + protected $filter; + + /** + * Method to get certain otherwise inaccessible properties from the form field object. + * + * @param string $name The property name for which to the the value. + * + * @return mixed The property value or null. + * + * @since 3.2 + */ + public function __get($name) + { + switch ($name) { + case 'maxlength': + case 'format': + case 'filter': + return $this->{$name}; + } + + return parent::__get($name); + } + + /** + * Method to set certain otherwise inaccessible properties of the form field object. + * + * @param string $name The property name for which to the the value. + * @param mixed $value The value of the property. + * + * @return void + * + * @since 3.2 + */ + public function __set($name, $value) + { + switch ($name) { + case 'maxlength': + $this->{$name} = (int)$value; + break; + + case 'format': + case 'filter': + $this->{$name} = (string)$value; + break; + + default: + parent::__set($name, $value); + } + } + + /** + * Method to attach a JForm object to the field. + * + * @param SimpleXMLElement $element The SimpleXMLElement object representing the `` tag for the form field object. + * @param mixed $value The form field value to validate. + * @param string $group The field name group control value. This acts as as an array container for the field. + * For example if the field has name="foo" and the group value is set to "bar" then the + * full field name would end up being "bar[foo]". + * + * @return boolean True on success. + * + * @see JFormField::setup() + * @since 3.2 + */ + public function setup(SimpleXMLElement $element, $value, $group = null) + { + $return = parent::setup($element, $value, $group); + + if ($return) { + $this->maxlength = (int)$this->element['maxlength'] ? (int)$this->element['maxlength'] : 45; + $this->format = (string)$this->element['format'] ? (string)$this->element['format'] + : Redshop::getConfig()->getString('DEFAULT_DATEFORMAT', 'Y-m-d'); + $this->filter = (string)$this->element['filter'] ? (string)$this->element['filter'] : null; + } + + return $return; + } + + /** + * Method to get the field input markup. + * + * @return string The field input markup. + * + * @since 11.1 + */ + protected function getInput() + { + // Translate placeholder text + $hint = $this->translateHint ? JText::_($this->hint) : $this->hint; + + // Initialize some field attributes. + $format = $this->format; + + // Build the attributes array. + $attributes = array(); + + empty($this->size) ? null : $attributes['size'] = $this->size; + empty($this->maxlength) ? null : $attributes['maxlength'] = $this->maxlength; + empty($this->class) ? null : $attributes['class'] = $this->class; + !$this->readonly ? null : $attributes['readonly'] = 'readonly'; + !$this->disabled ? null : $attributes['disabled'] = 'disabled'; + empty($this->onchange) ? null : $attributes['onchange'] = $this->onchange; + !strlen($hint) ? null : $attributes['placeholder'] = $hint; + $this->autocomplete ? null : $attributes['autocomplete'] = 'off'; + !$this->autofocus ? null : $attributes['autofocus'] = ''; + + if ($this->required) { + $attributes['required'] = ''; + $attributes['aria-required'] = 'true'; + } + + // Handle the special case for "now". + if (strtoupper($this->value) == 'NOW') { + $this->value = JFactory::getDate()->toUnix(); + } + + // Get some system objects. + $config = JFactory::getConfig(); + $user = JFactory::getUser(); + $tz = $config->get('offset'); + + // If a known filter is given use it. + if (strtoupper($this->filter) == 'SERVER_UTC') { + // Convert a date to UTC based on the server timezone. + if ($this->value && $this->value != JFactory::getDbo()->getNullDate()) { + // Get a date object based on the correct timezone. + $date = JFactory::getDate($this->value, 'UTC'); + $date->setTimezone(new DateTimeZone($tz)); + + // Transform the date string. + $this->value = $date->format($format, true, false); + } + } else { + // Convert a date to UTC based on the user timezone. + if ($this->value && $this->value != JFactory::getDbo()->getNullDate()) { + // Get a date object based on the correct timezone. + $date = JFactory::getDate($this->value, 'UTC'); + $tz = $user->getParam('timezone', $tz); + + $date->setTimezone(new DateTimeZone($tz)); + + // Transform the date string. + $this->value = $date->format($format, true, false); + } + } + + // Including fallback code for HTML5 non supported browsers. + JHtml::_('jquery.framework'); + JHtml::_('script', 'system/html5fallback.js', false, true); + + return JHtml::_( + 'redshopcalendar.calendar', + $this->value, + $this->name, + $this->id, + $format, + $attributes, + null, + $tz + ); + } } diff --git a/libraries/redshop/form/field/country.php b/libraries/redshop/form/field/country.php index f2f3d60c393..0d15b4f0d7d 100644 --- a/libraries/redshop/form/field/country.php +++ b/libraries/redshop/form/field/country.php @@ -18,33 +18,33 @@ */ class RedshopFormFieldCountry extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Country'; + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Country'; - /** - * Method to get the field input markup. - * - * @return string The field input markup. - */ - protected function getOptions() - { - $key = isset($this->element['idfield']) ? (string) $this->element['idfield'] : 'id'; + /** + * Method to get the field input markup. + * + * @return string The field input markup. + */ + protected function getOptions() + { + $key = isset($this->element['idfield']) ? (string)$this->element['idfield'] : 'id'; - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn($key, 'value')) - ->select($db->qn('country_name', 'text')) - ->from($db->qn('#__redshop_country')); - $options = $db->setQuery($query)->loadObjectList(); + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn($key, 'value')) + ->select($db->qn('country_name', 'text')) + ->from($db->qn('#__redshop_country')); + $options = $db->setQuery($query)->loadObjectList(); - $parentOptions = parent::getOptions(); - $options = array_merge($parentOptions, $options); + $parentOptions = parent::getOptions(); + $options = array_merge($parentOptions, $options); - return $options; - } + return $options; + } } diff --git a/libraries/redshop/form/field/coupon_remaining.php b/libraries/redshop/form/field/coupon_remaining.php index bb67091de40..2f9c9afe80b 100644 --- a/libraries/redshop/form/field/coupon_remaining.php +++ b/libraries/redshop/form/field/coupon_remaining.php @@ -18,37 +18,36 @@ */ class RedshopFormFieldCoupon_Remaining extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Coupon_Remaining'; + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Coupon_Remaining'; - /** - * Method to get the field input markup for a generic list. - * Use the multiple attribute to enable multiselect. - * - * @return string The field input markup. - * - * @since 3.7.0 - */ - protected function getInput() - { - $couponId = isset($this->element['coupon_id']) ? (int) $this->element['coupon_id'] : false; + /** + * Method to get the field input markup for a generic list. + * Use the multiple attribute to enable multiselect. + * + * @return string The field input markup. + * + * @since 3.7.0 + */ + protected function getInput() + { + $couponId = isset($this->element['coupon_id']) ? (int)$this->element['coupon_id'] : false; - if ($couponId !== false) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('coupon_value')) - ->from($db->qn('#__redshop_coupons_transaction')) - ->where($db->qn('coupon_id') . ' = ' . $couponId); + if ($couponId !== false) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('coupon_value')) + ->from($db->qn('#__redshop_coupons_transaction')) + ->where($db->qn('coupon_id') . ' = ' . $couponId); - return ''; - } + return ''; + } - return ''; - } + return ''; + } } diff --git a/libraries/redshop/form/field/fieldsection.php b/libraries/redshop/form/field/fieldsection.php index f6cace20f32..9bd4271f481 100755 --- a/libraries/redshop/form/field/fieldsection.php +++ b/libraries/redshop/form/field/fieldsection.php @@ -20,46 +20,46 @@ */ class RedshopFormFieldFieldSection extends JFormFieldList { - /** - * Element name - * - * @access protected - * @var string - */ - protected $type = 'fieldsection'; + /** + * Element name + * + * @access protected + * @var string + */ + protected $type = 'fieldsection'; - /** - * Method to get the field options. - * - * @return array The field option objects. - * - * @since 11.1 - */ - protected function getOptions() - { - JFactory::getLanguage()->load('com_redshop'); + /** + * Method to get the field options. + * + * @return array The field option objects. + * + * @since 11.1 + */ + protected function getOptions() + { + JFactory::getLanguage()->load('com_redshop'); - $fieldSections = array(); - $fieldSections[] = (object) array('value' => '1', 'text' => JText::_('COM_REDSHOP_PRODUCT')); - $fieldSections[] = (object) array('value' => '2', 'text' => JText::_('COM_REDSHOP_CATEGORY')); - $fieldSections[] = (object) array('value' => '7', 'text' => JText::_('COM_REDSHOP_CUSTOMER_ADDRESS')); - $fieldSections[] = (object) array('value' => '8', 'text' => JText::_('COM_REDSHOP_COMPANY_ADDRESS')); - $fieldSections[] = (object) array('value' => '9', 'text' => JText::_('COM_REDSHOP_COLOR_SAMPLE')); - $fieldSections[] = (object) array('value' => '10', 'text' => JText::_('COM_REDSHOP_MANUFACTURER')); - $fieldSections[] = (object) array('value' => '11', 'text' => JText::_('COM_REDSHOP_SHIPPING')); - $fieldSections[] = (object) array('value' => '12', 'text' => JText::_('COM_REDSHOP_PRODUCT_USERFIELD')); - $fieldSections[] = (object) array('value' => '13', 'text' => JText::_('COM_REDSHOP_GIFTCARD_USERFIELD')); - $fieldSections[] = (object) array('value' => '14', 'text' => JText::_('COM_REDSHOP_CUSTOMER_SHIPPING_ADDRESS')); - $fieldSections[] = (object) array('value' => '15', 'text' => JText::_('COM_REDSHOP_COMPANY_SHIPPING_ADDRESS')); - $fieldSections[] = (object) array('value' => '17', 'text' => JText::_('COM_REDSHOP_PRODUCTFINDER_DATEPICKER')); - $fieldSections[] = (object) array('value' => '16', 'text' => JText::_('COM_REDSHOP_QUOTATION')); - $fieldSections[] = (object) array('value' => '18', 'text' => JText::_('COM_REDSHOP_PAYMENT_GATEWAY')); - $fieldSections[] = (object) array('value' => '19', 'text' => JText::_('COM_REDSHOP_SHIPPING_GATEWAY')); - $fieldSections[] = (object) array('value' => '20', 'text' => JText::_('COM_REDSHOP_ORDER')); + $fieldSections = array(); + $fieldSections[] = (object)array('value' => '1', 'text' => JText::_('COM_REDSHOP_PRODUCT')); + $fieldSections[] = (object)array('value' => '2', 'text' => JText::_('COM_REDSHOP_CATEGORY')); + $fieldSections[] = (object)array('value' => '7', 'text' => JText::_('COM_REDSHOP_CUSTOMER_ADDRESS')); + $fieldSections[] = (object)array('value' => '8', 'text' => JText::_('COM_REDSHOP_COMPANY_ADDRESS')); + $fieldSections[] = (object)array('value' => '9', 'text' => JText::_('COM_REDSHOP_COLOR_SAMPLE')); + $fieldSections[] = (object)array('value' => '10', 'text' => JText::_('COM_REDSHOP_MANUFACTURER')); + $fieldSections[] = (object)array('value' => '11', 'text' => JText::_('COM_REDSHOP_SHIPPING')); + $fieldSections[] = (object)array('value' => '12', 'text' => JText::_('COM_REDSHOP_PRODUCT_USERFIELD')); + $fieldSections[] = (object)array('value' => '13', 'text' => JText::_('COM_REDSHOP_GIFTCARD_USERFIELD')); + $fieldSections[] = (object)array('value' => '14', 'text' => JText::_('COM_REDSHOP_CUSTOMER_SHIPPING_ADDRESS')); + $fieldSections[] = (object)array('value' => '15', 'text' => JText::_('COM_REDSHOP_COMPANY_SHIPPING_ADDRESS')); + $fieldSections[] = (object)array('value' => '17', 'text' => JText::_('COM_REDSHOP_PRODUCTFINDER_DATEPICKER')); + $fieldSections[] = (object)array('value' => '16', 'text' => JText::_('COM_REDSHOP_QUOTATION')); + $fieldSections[] = (object)array('value' => '18', 'text' => JText::_('COM_REDSHOP_PAYMENT_GATEWAY')); + $fieldSections[] = (object)array('value' => '19', 'text' => JText::_('COM_REDSHOP_SHIPPING_GATEWAY')); + $fieldSections[] = (object)array('value' => '20', 'text' => JText::_('COM_REDSHOP_ORDER')); - $parentOptions = parent::getOptions(); - $options = array_merge($parentOptions, $fieldSections); + $parentOptions = parent::getOptions(); + $options = array_merge($parentOptions, $fieldSections); - return $options; - } + return $options; + } } diff --git a/libraries/redshop/form/field/fieldsgroups.php b/libraries/redshop/form/field/fieldsgroups.php index 1d3d4365454..76a0da42ba3 100644 --- a/libraries/redshop/form/field/fieldsgroups.php +++ b/libraries/redshop/form/field/fieldsgroups.php @@ -18,46 +18,44 @@ */ class RedshopFormFieldFieldsgroups extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 2.1.0 - */ - protected $type = 'Fieldsgroups'; - - /** - * Method to get the field options. - * - * @return array The field option objects. - * - * @since 2.1.0 - */ - public function getOptions() - { - JModelList::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/models', 'RedshopModel'); - - /** - * @var $model RedshopModelField_Groups - */ - $model = JModelList::getInstance('Field_Groups', 'RedshopModel'); - $model->setState('list.limit', 99); - $groups = $model->getItems(); - - $options = array( - JHtml::_('select.option', 0, JText::_('COM_REDSHOP_FIELD_GROUP_NOGROUP')) - ); - - if ($groups) - { - foreach ($groups as $group) - { - $options[] = array('value' => $group->id, 'text' => $group->name); - } - } - - $parentOptions = parent::getOptions(); - - return array_merge($parentOptions, $options); - } + /** + * The form field type. + * + * @var string + * @since 2.1.0 + */ + protected $type = 'Fieldsgroups'; + + /** + * Method to get the field options. + * + * @return array The field option objects. + * + * @since 2.1.0 + */ + public function getOptions() + { + JModelList::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/models', 'RedshopModel'); + + /** + * @var $model RedshopModelField_Groups + */ + $model = JModelList::getInstance('Field_Groups', 'RedshopModel'); + $model->setState('list.limit', 99); + $groups = $model->getItems(); + + $options = array( + JHtml::_('select.option', 0, JText::_('COM_REDSHOP_FIELD_GROUP_NOGROUP')) + ); + + if ($groups) { + foreach ($groups as $group) { + $options[] = array('value' => $group->id, 'text' => $group->name); + } + } + + $parentOptions = parent::getOptions(); + + return array_merge($parentOptions, $options); + } } diff --git a/libraries/redshop/form/field/fieldtype.php b/libraries/redshop/form/field/fieldtype.php index 83102bd486d..4f9cd07ff71 100755 --- a/libraries/redshop/form/field/fieldtype.php +++ b/libraries/redshop/form/field/fieldtype.php @@ -20,30 +20,30 @@ */ class RedshopFormFieldFieldType extends JFormFieldList { - /** - * Element name - * - * @access protected - * @var string - */ - protected $type = 'fieldtype'; + /** + * Element name + * + * @access protected + * @var string + */ + protected $type = 'fieldtype'; - /** - * Method to get the field options. - * - * @return array The field option objects. - * - * @since 11.1 - */ - protected function getOptions() - { - JFactory::getLanguage()->load('com_redshop'); + /** + * Method to get the field options. + * + * @return array The field option objects. + * + * @since 11.1 + */ + protected function getOptions() + { + JFactory::getLanguage()->load('com_redshop'); - $fieldTypes = RedshopHelperTemplate::getFieldTypeSections(); + $fieldTypes = RedshopHelperTemplate::getFieldTypeSections(); - $parentOptions = parent::getOptions(); - $options = array_merge($parentOptions, $fieldTypes); + $parentOptions = parent::getOptions(); + $options = array_merge($parentOptions, $fieldTypes); - return $options; - } + return $options; + } } diff --git a/libraries/redshop/form/field/fontlist.php b/libraries/redshop/form/field/fontlist.php index 295796de8c2..e462dcf5785 100644 --- a/libraries/redshop/form/field/fontlist.php +++ b/libraries/redshop/form/field/fontlist.php @@ -18,51 +18,48 @@ */ class RedshopFormFieldFontList extends JFormFieldFileList { - /** - * The form field type. - * - * @var string - * @since 2.1.2 - */ - protected $type = 'FontList'; - - /** - * Method to get the list of images field options. - * Use the filter attribute to specify allowable file extensions. - * - * @return array The field option objects. - * - * @since 2.1.2 - */ - protected function getOptions() - { - $filter = "ttf"; + /** + * The form field type. + * + * @var string + * @since 2.1.2 + */ + protected $type = 'FontList'; - $path = JPATH_ROOT . '/media/com_redshop/fonts'; + /** + * Method to get the list of images field options. + * Use the filter attribute to specify allowable file extensions. + * + * @return array The field option objects. + * + * @since 2.1.2 + */ + protected function getOptions() + { + $filter = "ttf"; - $path = JPath::clean($path); + $path = JPATH_ROOT . '/media/com_redshop/fonts'; - $fontFile = JFolder::files($path, $filter); + $path = JPath::clean($path); - $options = array(); + $fontFile = JFolder::files($path, $filter); - foreach ($fontFile as $file) - { - // Check to see if the file is in the exclude mask. - if ($this->exclude && preg_match(chr(1) . $this->exclude . chr(1), $file)) - { - continue; - } + $options = array(); - // If the extension is to be stripped, do it. - if ($this->stripExt) - { - $file = JFile::stripExt($file); - } + foreach ($fontFile as $file) { + // Check to see if the file is in the exclude mask. + if ($this->exclude && preg_match(chr(1) . $this->exclude . chr(1), $file)) { + continue; + } - $options[] = JHtml::_('select.option', 'ttf.' . $file, $file); - } + // If the extension is to be stripped, do it. + if ($this->stripExt) { + $file = JFile::stripExt($file); + } - return array_merge(parent::getOptions(), $options); - } + $options[] = JHtml::_('select.option', 'ttf.' . $file, $file); + } + + return array_merge(parent::getOptions(), $options); + } } diff --git a/libraries/redshop/form/field/mail_section.php b/libraries/redshop/form/field/mail_section.php index 0622a400c56..a02cf2d6dd4 100644 --- a/libraries/redshop/form/field/mail_section.php +++ b/libraries/redshop/form/field/mail_section.php @@ -19,34 +19,34 @@ */ class RedshopFormFieldMail_Section extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Mail_Section'; - - /** - * Method to get the field input markup. - * - * @return string The field input markup. - */ - protected function getOptions() - { - $options = RedshopHelperTemplate::getMailSections(); - - foreach ($options as $value => $text) { - $option = new stdClass; - - $option->text = $text; - $option->value = $value; - $option->disable = false; - $option->class = ''; - $option->selected = false; - $option->checked = false; - } - - return array_merge(parent::getOptions(), $options); - } + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Mail_Section'; + + /** + * Method to get the field input markup. + * + * @return string The field input markup. + */ + protected function getOptions() + { + $options = RedshopHelperTemplate::getMailSections(); + + foreach ($options as $value => $text) { + $option = new stdClass; + + $option->text = $text; + $option->value = $value; + $option->disable = false; + $option->class = ''; + $option->selected = false; + $option->checked = false; + } + + return array_merge(parent::getOptions(), $options); + } } diff --git a/libraries/redshop/form/field/manufacturer.php b/libraries/redshop/form/field/manufacturer.php index ac987157790..dff363c9f28 100644 --- a/libraries/redshop/form/field/manufacturer.php +++ b/libraries/redshop/form/field/manufacturer.php @@ -18,36 +18,35 @@ */ class RedshopFormFieldManufacturer extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Manufacturer'; + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Manufacturer'; - /** - * Method to get the field input markup. - * - * @return array The field input markup. - */ - protected function getOptions() - { - // Process value - if (!empty($this->value) && $this->multiple && !is_array($this->value)) - { - $this->value = explode(',', $this->value); - } + /** + * Method to get the field input markup. + * + * @return array The field input markup. + */ + protected function getOptions() + { + // Process value + if (!empty($this->value) && $this->multiple && !is_array($this->value)) { + $this->value = explode(',', $this->value); + } - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('id', 'value')) - ->select($db->qn('name', 'text')) - ->from($db->qn('#__redshop_manufacturer')); - $options = $db->setQuery($query)->loadObjectList(); + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('id', 'value')) + ->select($db->qn('name', 'text')) + ->from($db->qn('#__redshop_manufacturer')); + $options = $db->setQuery($query)->loadObjectList(); - $options = array_merge(parent::getOptions(), $options); + $options = array_merge(parent::getOptions(), $options); - return $options; - } + return $options; + } } diff --git a/libraries/redshop/form/field/media.php b/libraries/redshop/form/field/media.php index d30e88bc738..a7e3f892e21 100644 --- a/libraries/redshop/form/field/media.php +++ b/libraries/redshop/form/field/media.php @@ -18,69 +18,73 @@ */ class RedshopFormFieldMedia extends JFormField { - /** - * The form field type. - * - * @var string - * @since 2.1.0 - */ - public $type = 'Media'; + /** + * The form field type. + * + * @var string + * @since 2.1.0 + */ + public $type = 'Media'; - /** - * Input field attributes - * - * @var array - */ - protected $attribs = array(); + /** + * Input field attributes + * + * @var array + */ + protected $attribs = array(); - /** - * Method to get the field input markup. - * - * @return string The field input markup. - */ - protected function getInput() - { - $mediaDOMId = isset($this->element['media-dom']) ? (string) $this->element['media-dom'] : null; - $mediaType = isset($this->element['media-type']) ? (string) $this->element['media-type'] : null; - $mediaSection = isset($this->element['media-section']) ? (string) $this->element['media-section'] : null; - $showGallery = isset($this->element['media-gallery']) ? boolval((string) $this->element['media-gallery']) : false; - $useMediaPath = isset($this->element['media-newMediaPath']) ? boolval((string) $this->element['media-newMediaPath']) : false; - $showAlternateText = isset($this->element['media-alternate']) ? boolval((string) $this->element['media-alternate']) : false; - $referenceId = isset($this->element['media-reference']) ? (int) $this->element['media-reference'] : 0; - $mediaId = isset($this->element['media-id']) ? (int) $this->element['media-id'] : 0; + /** + * Method to get the field input markup. + * + * @return string The field input markup. + */ + protected function getInput() + { + $mediaDOMId = isset($this->element['media-dom']) ? (string)$this->element['media-dom'] : null; + $mediaType = isset($this->element['media-type']) ? (string)$this->element['media-type'] : null; + $mediaSection = isset($this->element['media-section']) ? (string)$this->element['media-section'] : null; + $showGallery = isset($this->element['media-gallery']) ? boolval( + (string)$this->element['media-gallery'] + ) : false; + $useMediaPath = isset($this->element['media-newMediaPath']) ? boolval( + (string)$this->element['media-newMediaPath'] + ) : false; + $showAlternateText = isset($this->element['media-alternate']) ? boolval( + (string)$this->element['media-alternate'] + ) : false; + $referenceId = isset($this->element['media-reference']) ? (int)$this->element['media-reference'] : 0; + $mediaId = isset($this->element['media-id']) ? (int)$this->element['media-id'] : 0; - $media = RedshopEntityMediaImage::getInstance(); + $media = RedshopEntityMediaImage::getInstance(); - if ($mediaId) - { - $media = RedshopEntityMediaImage::getInstance($mediaId); - } + if ($mediaId) { + $media = RedshopEntityMediaImage::getInstance($mediaId); + } - $html = ''; + $html = ''; - if ($showAlternateText) - { - $inputId = 'dropzone_alternate_text[' . $mediaDOMId . ']'; - $inputId .= !empty($mediaId) ? '[media-' . $mediaId . ']' : '[]'; - $html = '
    ' - . '' - . '' - . '

    '; - } + if ($showAlternateText) { + $inputId = 'dropzone_alternate_text[' . $mediaDOMId . ']'; + $inputId .= !empty($mediaId) ? '[media-' . $mediaId . ']' : '[]'; + $html = '
    ' + . '' + . '' + . '

    '; + } - $html .= RedshopHelperMediaImage::render( - $mediaDOMId, - $mediaType, - $referenceId, - $mediaSection, - $media->get('media_name'), - $showGallery, - $useMediaPath, - $mediaId - ); + $html .= RedshopHelperMediaImage::render( + $mediaDOMId, + $mediaType, + $referenceId, + $mediaSection, + $media->get('media_name'), + $showGallery, + $useMediaPath, + $mediaId + ); - return $html; - } + return $html; + } } diff --git a/libraries/redshop/form/field/modulelayout.php b/libraries/redshop/form/field/modulelayout.php index f2e6e98c1ea..228fe538ed1 100644 --- a/libraries/redshop/form/field/modulelayout.php +++ b/libraries/redshop/form/field/modulelayout.php @@ -3,8 +3,8 @@ * @package Phproberto.Joomla-Twig * @subpackage Form.Field * - * @copyright Copyright (C) 2017-2018 Roberto Segura López, Inc. All rights reserved. - * @license See COPYING.txt + * @copyright Copyright (C) 2017-2018 Roberto Segura López, Inc. All rights reserved. + * @license See COPYING.txt */ defined('_JEXEC') || die; diff --git a/libraries/redshop/form/field/order_status.php b/libraries/redshop/form/field/order_status.php index 699c8d719d2..5d592c3cc44 100644 --- a/libraries/redshop/form/field/order_status.php +++ b/libraries/redshop/form/field/order_status.php @@ -18,28 +18,28 @@ */ class RedshopFormFieldOrder_Status extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Order_Status'; + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Order_Status'; - /** - * Method to get the field input markup. - * - * @return array The field input markup. - */ - protected function getOptions() - { - // Load redSHOP Library - JLoader::import('redshop.library'); + /** + * Method to get the field input markup. + * + * @return array The field input markup. + */ + protected function getOptions() + { + // Load redSHOP Library + JLoader::import('redshop.library'); - $this->value = $this->multiple ? (array) $this->value : (string) $this->value; - $orderStatus = RedshopHelperOrder::getOrderStatusList(); + $this->value = $this->multiple ? (array)$this->value : (string)$this->value; + $orderStatus = RedshopHelperOrder::getOrderStatusList(); - // Merge any additional options in the XML definition. - return array_merge(parent::getOptions(), $orderStatus); - } + // Merge any additional options in the XML definition. + return array_merge(parent::getOptions(), $orderStatus); + } } diff --git a/libraries/redshop/form/field/payment_method.php b/libraries/redshop/form/field/payment_method.php index a0331afd712..d08db510acd 100644 --- a/libraries/redshop/form/field/payment_method.php +++ b/libraries/redshop/form/field/payment_method.php @@ -18,43 +18,41 @@ */ class RedshopFormFieldPayment_Method extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Payment_Method'; - - /** - * Method to get the field input markup. - * - * @return array The field input markup. - */ - protected function getOptions() - { - $payments = RedshopHelperOrder::getPaymentMethodInfo(); - - if (empty($payments)) - { - return parent::getOptions(); - } - - RedshopHelperPayment::loadLanguages(); - - $options = array(); - $this->value = $this->multiple ? (array) $this->value : (string) $this->value; - - foreach ($payments as $payment) - { - $option = new stdClass; - - $option->text = JText::_($payment->name); - $option->value = $payment->element; - - $options[] = $option; - } - - return array_merge(parent::getOptions(), $options); - } + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Payment_Method'; + + /** + * Method to get the field input markup. + * + * @return array The field input markup. + */ + protected function getOptions() + { + $payments = RedshopHelperOrder::getPaymentMethodInfo(); + + if (empty($payments)) { + return parent::getOptions(); + } + + RedshopHelperPayment::loadLanguages(); + + $options = array(); + $this->value = $this->multiple ? (array)$this->value : (string)$this->value; + + foreach ($payments as $payment) { + $option = new stdClass; + + $option->text = JText::_($payment->name); + $option->value = $payment->element; + + $options[] = $option; + } + + return array_merge(parent::getOptions(), $options); + } } diff --git a/libraries/redshop/form/field/pluginlayout.php b/libraries/redshop/form/field/pluginlayout.php index 80f2c91b13d..7c435ba0d98 100644 --- a/libraries/redshop/form/field/pluginlayout.php +++ b/libraries/redshop/form/field/pluginlayout.php @@ -3,8 +3,8 @@ * @package Phproberto.Joomla-Twig * @subpackage Form.Field * - * @copyright Copyright (C) 2017-2018 Roberto Segura López, Inc. All rights reserved. - * @license See COPYING.txt + * @copyright Copyright (C) 2017-2018 Roberto Segura López, Inc. All rights reserved. + * @license See COPYING.txt */ defined('_JEXEC') || die; diff --git a/libraries/redshop/form/field/radio.php b/libraries/redshop/form/field/radio.php index d4e4401527b..2bd2aa7a721 100644 --- a/libraries/redshop/form/field/radio.php +++ b/libraries/redshop/form/field/radio.php @@ -20,114 +20,114 @@ */ class RedshopFormFieldRadio extends JFormFieldRadio { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Radio'; + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Radio'; - /** - * @var string - */ - protected $labelLayout = 'field.label'; + /** + * @var string + */ + protected $labelLayout = 'field.label'; - /** - * @var string - */ - protected $inputLayout = 'field.radio'; + /** + * @var string + */ + protected $inputLayout = 'field.radio'; - /** - * Enable debug mode for field - * - * @return boolean - */ - protected function debugEnabled() - { - return !empty($this->element['debug']) ? ((string) $this->element['debug'] === 'true') : false; - } + /** + * Enable debug mode for field + * + * @return boolean + */ + protected function debugEnabled() + { + return !empty($this->element['debug']) ? ((string)$this->element['debug'] === 'true') : false; + } - /** - * Method to get the radio button field input markup. - * - * @return string The field input markup. - * - * @since 1.0 - */ - protected function getInput() - { - return RedshopLayoutHelper::render($this->getInputLayout(), $this->getLayoutData()); - } + /** + * Method to get the radio button field input markup. + * + * @return string The field input markup. + * + * @since 1.0 + */ + protected function getInput() + { + return RedshopLayoutHelper::render($this->getInputLayout(), $this->getLayoutData()); + } - /** - * Method to get the radio button field input markup. - * - * @return string The field input markup. - * - * @since 1.0 - */ - protected function getInputLayout() - { - return !empty($this->element['input-layout']) ? (string) $this->element['input-layout'] : $this->inputLayout; - } + /** + * Method to get the radio button field input markup. + * + * @return string The field input markup. + * + * @since 1.0 + */ + protected function getInputLayout() + { + return !empty($this->element['input-layout']) ? (string)$this->element['input-layout'] : $this->inputLayout; + } - /** - * Get the active label layout - * - * @return string - * - * @since 1.0 - */ - protected function getLabelLayout() - { - return !empty($this->element['label-layout']) ? (string) $this->element['label-layout'] : $this->labelLayout; - } + /** + * Get the layout information + * + * @return array + */ + protected function getLayoutData() + { + // Label preprocess + $label = $this->element['label'] ? (string)$this->element['label'] : (string)$this->element['name']; + $label = $this->translateLabel ? JText::_($label) : $label; - /** - * Get the layout information - * - * @return array - */ - protected function getLayoutData() - { - // Label preprocess - $label = $this->element['label'] ? (string) $this->element['label'] : (string) $this->element['name']; - $label = $this->translateLabel ? JText::_($label) : $label; + // Description preprocess + $description = !empty($this->description) ? $this->description : null; + $description = !empty($description) && $this->translateDescription ? JText::_($description) : $description; - // Description preprocess - $description = !empty($this->description) ? $this->description : null; - $description = !empty($description) && $this->translateDescription ? JText::_($description) : $description; + $alt = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname); - $alt = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname); + return array( + 'autocomplete' => $this->autocomplete, + 'autofocus' => $this->autofocus, + 'class' => $this->class, + 'description' => $description, + 'disabled' => $this->disabled, + 'element' => $this->element, + 'field' => $this, + 'group' => $this->group, + 'hidden' => $this->hidden, + 'hint' => $this->translateHint ? JText::alt($this->hint, $alt) : $this->hint, + 'id' => $this->id, + 'label' => $label, + 'labelclass' => $this->labelclass, + 'multiple' => $this->multiple, + 'name' => $this->name, + 'onchange' => $this->onchange, + 'onclick' => $this->onclick, + 'options' => $this->getOptions(), + 'pattern' => $this->pattern, + 'readonly' => $this->readonly, + 'repeat' => $this->repeat, + 'required' => (bool)$this->required, + 'size' => $this->size, + 'spellcheck' => $this->spellcheck, + 'validate' => $this->validate, + 'value' => $this->value + ); + } - return array( - 'autocomplete' => $this->autocomplete, - 'autofocus' => $this->autofocus, - 'class' => $this->class, - 'description' => $description, - 'disabled' => $this->disabled, - 'element' => $this->element, - 'field' => $this, - 'group' => $this->group, - 'hidden' => $this->hidden, - 'hint' => $this->translateHint ? JText::alt($this->hint, $alt) : $this->hint, - 'id' => $this->id, - 'label' => $label, - 'labelclass' => $this->labelclass, - 'multiple' => $this->multiple, - 'name' => $this->name, - 'onchange' => $this->onchange, - 'onclick' => $this->onclick, - 'options' => $this->getOptions(), - 'pattern' => $this->pattern, - 'readonly' => $this->readonly, - 'repeat' => $this->repeat, - 'required' => (bool) $this->required, - 'size' => $this->size, - 'spellcheck' => $this->spellcheck, - 'validate' => $this->validate, - 'value' => $this->value - ); - } + /** + * Get the active label layout + * + * @return string + * + * @since 1.0 + */ + protected function getLabelLayout() + { + return !empty($this->element['label-layout']) ? (string)$this->element['label-layout'] : $this->labelLayout; + } } diff --git a/libraries/redshop/form/field/rules.php b/libraries/redshop/form/field/rules.php index d9708bb38c2..eda58e50562 100644 --- a/libraries/redshop/form/field/rules.php +++ b/libraries/redshop/form/field/rules.php @@ -18,164 +18,156 @@ */ class RedshopFormFieldRules extends JFormField { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Rules'; - - /** - * Method to get the field input markup for Access Control Lists. - * Optionally can be associated with a specific component and section. - * - * @return string The field input markup. - * - * @since 11.1 - */ - protected function getInput() - { - JHtml::_('bootstrap.tooltip'); - - // Initialise some field attributes. - $section = $this->element['section'] ? (string) $this->element['section'] : ''; - $component = $this->element['component'] ? (string) $this->element['component'] : ''; - $assetField = $this->element['asset_field'] ? (string) $this->element['asset_field'] : 'asset_id'; - $showGroup = $this->element['show_group'] ? (string) $this->element['show_group'] : ''; - $showGroup = ($showGroup == 'true') ? true : false; - - // Current view is global config? - $isGlobalConfig = $component === 'root.1'; - - // Get the actions for the asset. - $actions = JAccess::getActions($component, $section); - - // Iterate over the children and add to the actions. - foreach ($this->element->children() as $el) - { - if ($el->getName() != 'action') - { - continue; - } - - $actions[] = (object) array( - 'name' => (string) $el['name'], - 'title' => (string) $el['title'], - 'description' => (string) $el['description'] - ); - } - - if ($showGroup === true) - { - $newActions = array(); - - foreach ($actions as $action) - { - $group = explode('.', (string) $action->name); - $group = $group[0]; - - if (!isset($newActions[$group])) - { - $newActions[$group] = array(); - } - - $newActions[$group][] = $action; - } - - $actions = $newActions; - } - - ksort($actions); - - // Get the asset id. - // Note that for global configuration, com_config injects asset_id = 1 into the form. - $assetId = $this->form->getValue($assetField); - $newItem = empty($assetId) && $isGlobalConfig === false && $section !== 'component'; - $parentAssetId = null; - - // If the asset id is empty (component or new item). - if (empty($assetId)) - { - // Get the component asset id as fallback. - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->quoteName('id')) - ->from($db->quoteName('#__assets')) - ->where($db->quoteName('name') . ' = ' . $db->quote($component)); - - $db->setQuery($query); - - $assetId = (int) $db->loadResult(); - - /** - * @to do: incorrect info - * When creating a new item (not saving) it uses the calculated permissions from the component (item <-> component <-> global config). - * But if we have a section too (item <-> section(s) <-> component <-> global config) this is not correct. - * Also, currently it uses the component permission, but should use the calculated permissions for achild of the component/section. - */ - } - - // If not in global config we need the parent_id asset to calculate permissions. - if (!$isGlobalConfig) - { - // In this case we need to get the component rules too. - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->quoteName('parent_id')) - ->from($db->quoteName('#__assets')) - ->where($db->quoteName('id') . ' = ' . $assetId); - - $db->setQuery($query); - - $parentAssetId = (int) $db->loadResult(); - } - - // Full width format. - - // Get the rules for just this asset (non-recursive). - $assetRules = JAccess::getAssetRules($assetId, false, false); - - // Get the available user groups. - $groups = $this->getUserGroups(); - - return RedshopLayoutHelper::render( - 'field.rules.wrapper', - array( - 'groups' => $groups, - 'actions' => $actions, - 'field' => $this, - 'newItem' => $newItem, - 'assetRules' => $assetRules, - 'assetId' => $assetId, - 'isGlobalConfig' => $isGlobalConfig, - 'component' => $component, - 'showGroup' => $showGroup, - 'section' => $section - ) - ); - } - - /** - * Get a list of the user groups. - * - * @return array - * - * @since 11.1 - */ - protected function getUserGroups() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('a.id AS value, a.title AS text, COUNT(DISTINCT b.id) AS level, a.parent_id') - ->from('#__usergroups AS a') - ->join('LEFT', $db->quoteName('#__usergroups') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt') - ->group('a.id, a.title, a.lft, a.rgt, a.parent_id') - ->order('a.lft ASC'); - $db->setQuery($query); - $options = $db->loadObjectList(); - - return $options; - } + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Rules'; + + /** + * Method to get the field input markup for Access Control Lists. + * Optionally can be associated with a specific component and section. + * + * @return string The field input markup. + * + * @since 11.1 + */ + protected function getInput() + { + JHtml::_('bootstrap.tooltip'); + + // Initialise some field attributes. + $section = $this->element['section'] ? (string)$this->element['section'] : ''; + $component = $this->element['component'] ? (string)$this->element['component'] : ''; + $assetField = $this->element['asset_field'] ? (string)$this->element['asset_field'] : 'asset_id'; + $showGroup = $this->element['show_group'] ? (string)$this->element['show_group'] : ''; + $showGroup = ($showGroup == 'true') ? true : false; + + // Current view is global config? + $isGlobalConfig = $component === 'root.1'; + + // Get the actions for the asset. + $actions = JAccess::getActions($component, $section); + + // Iterate over the children and add to the actions. + foreach ($this->element->children() as $el) { + if ($el->getName() != 'action') { + continue; + } + + $actions[] = (object)array( + 'name' => (string)$el['name'], + 'title' => (string)$el['title'], + 'description' => (string)$el['description'] + ); + } + + if ($showGroup === true) { + $newActions = array(); + + foreach ($actions as $action) { + $group = explode('.', (string)$action->name); + $group = $group[0]; + + if (!isset($newActions[$group])) { + $newActions[$group] = array(); + } + + $newActions[$group][] = $action; + } + + $actions = $newActions; + } + + ksort($actions); + + // Get the asset id. + // Note that for global configuration, com_config injects asset_id = 1 into the form. + $assetId = $this->form->getValue($assetField); + $newItem = empty($assetId) && $isGlobalConfig === false && $section !== 'component'; + $parentAssetId = null; + + // If the asset id is empty (component or new item). + if (empty($assetId)) { + // Get the component asset id as fallback. + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->quoteName('id')) + ->from($db->quoteName('#__assets')) + ->where($db->quoteName('name') . ' = ' . $db->quote($component)); + + $db->setQuery($query); + + $assetId = (int)$db->loadResult(); + /** + * @to do: incorrect info + * When creating a new item (not saving) it uses the calculated permissions from the component (item <-> component <-> global config). + * But if we have a section too (item <-> section(s) <-> component <-> global config) this is not correct. + * Also, currently it uses the component permission, but should use the calculated permissions for achild of the component/section. + */ + } + + // If not in global config we need the parent_id asset to calculate permissions. + if (!$isGlobalConfig) { + // In this case we need to get the component rules too. + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->quoteName('parent_id')) + ->from($db->quoteName('#__assets')) + ->where($db->quoteName('id') . ' = ' . $assetId); + + $db->setQuery($query); + + $parentAssetId = (int)$db->loadResult(); + } + + // Full width format. + + // Get the rules for just this asset (non-recursive). + $assetRules = JAccess::getAssetRules($assetId, false, false); + + // Get the available user groups. + $groups = $this->getUserGroups(); + + return RedshopLayoutHelper::render( + 'field.rules.wrapper', + array( + 'groups' => $groups, + 'actions' => $actions, + 'field' => $this, + 'newItem' => $newItem, + 'assetRules' => $assetRules, + 'assetId' => $assetId, + 'isGlobalConfig' => $isGlobalConfig, + 'component' => $component, + 'showGroup' => $showGroup, + 'section' => $section + ) + ); + } + + /** + * Get a list of the user groups. + * + * @return array + * + * @since 11.1 + */ + protected function getUserGroups() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('a.id AS value, a.title AS text, COUNT(DISTINCT b.id) AS level, a.parent_id') + ->from('#__usergroups AS a') + ->join('LEFT', $db->quoteName('#__usergroups') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt') + ->group('a.id, a.title, a.lft, a.rgt, a.parent_id') + ->order('a.lft ASC'); + $db->setQuery($query); + $options = $db->loadObjectList(); + + return $options; + } } diff --git a/libraries/redshop/form/field/shipping_method.php b/libraries/redshop/form/field/shipping_method.php index 0fccb670df0..d1ada57e583 100644 --- a/libraries/redshop/form/field/shipping_method.php +++ b/libraries/redshop/form/field/shipping_method.php @@ -18,47 +18,45 @@ */ class RedshopFormFieldShipping_Method extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Shipping_Method'; - - /** - * Method to get the field input markup. - * - * @return array The field input markup. - */ - protected function getOptions() - { - $shippingMethods = RedshopHelperOrder::getShippingMethodInfo(); - - if (empty($shippingMethods)) - { - return parent::getOptions(); - } - - RedshopHelperShipping::loadLanguages(); - - $options = array(); - $this->value = $this->multiple ? (array) $this->value : (string) $this->value; - - foreach ($shippingMethods as $shipping) - { - $option = new stdClass; - - $option->text = JText::_($shipping->name); - $option->value = $shipping->element; - $option->disable = false; - $option->class = ''; - $option->selected = false; - $option->checked = false; - - $options[] = $option; - } - - return array_merge(parent::getOptions(), $options); - } + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Shipping_Method'; + + /** + * Method to get the field input markup. + * + * @return array The field input markup. + */ + protected function getOptions() + { + $shippingMethods = RedshopHelperOrder::getShippingMethodInfo(); + + if (empty($shippingMethods)) { + return parent::getOptions(); + } + + RedshopHelperShipping::loadLanguages(); + + $options = array(); + $this->value = $this->multiple ? (array)$this->value : (string)$this->value; + + foreach ($shippingMethods as $shipping) { + $option = new stdClass; + + $option->text = JText::_($shipping->name); + $option->value = $shipping->element; + $option->disable = false; + $option->class = ''; + $option->selected = false; + $option->checked = false; + + $options[] = $option; + } + + return array_merge(parent::getOptions(), $options); + } } diff --git a/libraries/redshop/form/field/state.php b/libraries/redshop/form/field/state.php index 296fdcec37e..e01298cdeed 100644 --- a/libraries/redshop/form/field/state.php +++ b/libraries/redshop/form/field/state.php @@ -18,56 +18,56 @@ */ class RedshopFormFieldState extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'State'; + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'State'; - /** - * Method to get the field input markup. - * - * @return string The field input markup. - */ - protected function getOptions() - { - $key = isset($this->element['idfield']) ? (string) $this->element['idfield'] : 'id'; + /** + * Method to get the field input markup. + * + * @return string The field input markup. + */ + protected function getOptions() + { + $key = isset($this->element['idfield']) ? (string)$this->element['idfield'] : 'id'; - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn($key, 'value')) - ->select($db->qn('state_name', 'text')) - ->select($db->qn('country_id')) - ->from($db->qn('#__redshop_state', 's')); + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn($key, 'value')) + ->select($db->qn('state_name', 'text')) + ->select($db->qn('country_id')) + ->from($db->qn('#__redshop_state', 's')); - if (!empty($this->form->getData()->get('tax_country'))) - { - $query->leftJoin($db->qn('#__redshop_country', 'c') . ' ON ' . $db->qn('s.country_id') . ' = ' . $db->qn('c.id')) - ->where($db->qn('c.country_3_code') . ' = ' . $db->q($this->form->getData()->get('tax_country'))); - } + if (!empty($this->form->getData()->get('tax_country'))) { + $query->leftJoin( + $db->qn('#__redshop_country', 'c') . ' ON ' . $db->qn('s.country_id') . ' = ' . $db->qn('c.id') + ) + ->where($db->qn('c.country_3_code') . ' = ' . $db->q($this->form->getData()->get('tax_country'))); + } - $options = $db->setQuery($query)->loadObjectList(); + $options = $db->setQuery($query)->loadObjectList(); - $fieldName = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname); + $fieldName = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname); - foreach ($options as $option) - { - $option->text = JText::alt((string) $option->text, $fieldName); - $option->value = (string) $option->value; - $option->disable = false; - $option->class = ''; - $option->selected = false; - $option->checked = false; - $option->country = $option->country_id; - } + foreach ($options as $option) { + $option->text = JText::alt((string)$option->text, $fieldName); + $option->value = (string)$option->value; + $option->disable = false; + $option->class = ''; + $option->selected = false; + $option->checked = false; + $option->country = $option->country_id; + } - reset($options); + reset($options); - $parentOptions = parent::getOptions(); - $options = array_merge($parentOptions, $options); + $parentOptions = parent::getOptions(); + $options = array_merge($parentOptions, $options); - return $options; - } + return $options; + } } diff --git a/libraries/redshop/form/field/taxgroup.php b/libraries/redshop/form/field/taxgroup.php index 2ad343abc5a..dc12c7aeb79 100644 --- a/libraries/redshop/form/field/taxgroup.php +++ b/libraries/redshop/form/field/taxgroup.php @@ -18,31 +18,31 @@ */ class RedshopFormFieldTaxgroup extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Taxgroup'; + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Taxgroup'; - /** - * Method to get the field input markup. - * - * @return string The field input markup. - */ - protected function getOptions() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('id', 'value')) - ->select($db->qn('name', 'text')) - ->from($db->qn('#__redshop_tax_group')); - $options = $db->setQuery($query)->loadObjectList(); + /** + * Method to get the field input markup. + * + * @return string The field input markup. + */ + protected function getOptions() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('id', 'value')) + ->select($db->qn('name', 'text')) + ->from($db->qn('#__redshop_tax_group')); + $options = $db->setQuery($query)->loadObjectList(); - $parentOptions = parent::getOptions(); - $options = array_merge($parentOptions, $options); + $parentOptions = parent::getOptions(); + $options = array_merge($parentOptions, $options); - return $options; - } + return $options; + } } diff --git a/libraries/redshop/form/field/template.php b/libraries/redshop/form/field/template.php index 1372d8b867b..fceb7ceba5f 100644 --- a/libraries/redshop/form/field/template.php +++ b/libraries/redshop/form/field/template.php @@ -18,54 +18,50 @@ */ class RedshopFormFieldTemplate extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Template'; + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Template'; - /** - * Method to get the field input markup. - * - * @return array The field input markup. - */ - protected function getOptions() - { - $section = isset($this->element['section']) ? (string) $this->element['section'] : null; + /** + * Method to get the field input markup. + * + * @return array The field input markup. + */ + protected function getOptions() + { + $section = isset($this->element['section']) ? (string)$this->element['section'] : null; - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('id')) - ->select($db->qn('name')) - ->from($db->qn('#__redshop_template')) - ->where($db->qn('published') . ' = 1'); + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('id')) + ->select($db->qn('name')) + ->from($db->qn('#__redshop_template')) + ->where($db->qn('published') . ' = 1'); - if (null !== $section) - { - $arrSection = explode(',', $section); + if (null !== $section) { + $arrSection = explode(',', $section); - foreach ($arrSection as $value) - { - $sections[] = "'". $value ."'"; - } + foreach ($arrSection as $value) { + $sections[] = "'" . $value . "'"; + } - $query->where($db->qn('section') . ' IN (' . implode(',', $sections) . ')'); - } + $query->where($db->qn('section') . ' IN (' . implode(',', $sections) . ')'); + } - $items = $db->setQuery($query)->loadObjectList(); - $options = array(); + $items = $db->setQuery($query)->loadObjectList(); + $options = array(); - if (count($items) > 0) - { - foreach ($items as $item) - { - $option = JHTML::_('select.option', $item->id, $item->name); - $options[] = $option; - } - } + if (count($items) > 0) { + foreach ($items as $item) { + $option = JHTML::_('select.option', $item->id, $item->name); + $options[] = $option; + } + } - return array_merge(parent::getOptions(), $options); - } + return array_merge(parent::getOptions(), $options); + } } diff --git a/libraries/redshop/form/field/template_section.php b/libraries/redshop/form/field/template_section.php index 9ffb687f66f..0143e6a486f 100644 --- a/libraries/redshop/form/field/template_section.php +++ b/libraries/redshop/form/field/template_section.php @@ -18,36 +18,35 @@ */ class RedshopFormFieldTemplate_Section extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Template_Section'; + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Template_Section'; - /** - * Method to get the field input markup. - * - * @return array The field input markup. - */ - protected function getOptions() - { - $options = RedshopHelperTemplate::getTemplateSections(); - $this->value = $this->multiple ? (array) $this->value : (string) $this->value; + /** + * Method to get the field input markup. + * + * @return array The field input markup. + */ + protected function getOptions() + { + $options = RedshopHelperTemplate::getTemplateSections(); + $this->value = $this->multiple ? (array)$this->value : (string)$this->value; - foreach ($options as $value => $text) - { - $option = new stdClass; + foreach ($options as $value => $text) { + $option = new stdClass; - $option->text = $text; - $option->value = $value; - $option->disable = false; - $option->class = ''; - $option->selected = false; - $option->checked = false; - } + $option->text = $text; + $option->value = $value; + $option->disable = false; + $option->class = ''; + $option->selected = false; + $option->checked = false; + } - return array_merge(parent::getOptions(), $options); - } + return array_merge(parent::getOptions(), $options); + } } diff --git a/libraries/redshop/form/field/text.php b/libraries/redshop/form/field/text.php index 501f13f7cd4..f53e5686424 100644 --- a/libraries/redshop/form/field/text.php +++ b/libraries/redshop/form/field/text.php @@ -18,99 +18,100 @@ */ class RedshopFormFieldText extends JFormField { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Text'; - - /** - * Input field attributes - * - * @var array - */ - protected $attribs = array(); - - /** - * Attributes not allowed to use in field definition - * - * @var array - */ - protected $forbiddenAttributes = array( - 'id', 'default', 'description', 'disabled', 'name', 'multiple', 'placeholder', 'type', 'value' - ); - - /** - * Add an attribute to the input field - * - * @param string $name Name of the attribute - * @param string $value Value for the attribute - * - * @return void - */ - protected function addAttribute($name, $value) - { - if (!is_null($value)) - { - $name = strtolower($name); - - $this->attribs[$name] = (string) $value; - } - } - - /** - * Method to get the field input markup. - * - * @return string The field input markup. - */ - protected function getInput() - { - // Manually handled attributes - $this->attribs['id'] = $this->id; - $this->attribs['name'] = $this->name; - $this->attribs['type'] = 'text'; - $this->attribs['readonly'] = ($this->element['readonly'] == 'true') ? 'readonly' : null; - $this->attribs['disabled'] = ($this->element['disabled'] == 'true') ? 'disabled' : null; - $this->attribs['placeholder'] = $this->element['placeholder'] ? JText::_($this->element['placeholder']) : null; - - if (isset($this->element['filter']) && ($this->element['filter'] == 'float' || $this->element['filter'] == 'integer')) - { - $this->attribs['type'] = 'number'; - } - - $elementAttribs = $this->element->attributes(); - - // Automatically insert any other attribute inserted - if (!empty($elementAttribs)) - { - foreach ($elementAttribs as $name => $value) - { - if (!in_array($name, $this->forbiddenAttributes)) - { - $this->addAttribute($name, $value); - } - } - } - - $html = ''; - - if ($this->multiple == 1 && is_array($this->value)) - { - foreach ($this->value AS $value) - { - $this->attribs['value'] = htmlspecialchars($value, ENT_COMPAT, 'UTF-8'); - - $html .= '
    attribs) . ' />
    '; - } - - return $html; - } - - $this->attribs['value'] = htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8'); - - return 'attribs) . ' />'; - } + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Text'; + + /** + * Input field attributes + * + * @var array + */ + protected $attribs = array(); + + /** + * Attributes not allowed to use in field definition + * + * @var array + */ + protected $forbiddenAttributes = array( + 'id', + 'default', + 'description', + 'disabled', + 'name', + 'multiple', + 'placeholder', + 'type', + 'value' + ); + + /** + * Method to get the field input markup. + * + * @return string The field input markup. + */ + protected function getInput() + { + // Manually handled attributes + $this->attribs['id'] = $this->id; + $this->attribs['name'] = $this->name; + $this->attribs['type'] = 'text'; + $this->attribs['readonly'] = ($this->element['readonly'] == 'true') ? 'readonly' : null; + $this->attribs['disabled'] = ($this->element['disabled'] == 'true') ? 'disabled' : null; + $this->attribs['placeholder'] = $this->element['placeholder'] ? JText::_($this->element['placeholder']) : null; + + if (isset($this->element['filter']) && ($this->element['filter'] == 'float' || $this->element['filter'] == 'integer')) { + $this->attribs['type'] = 'number'; + } + + $elementAttribs = $this->element->attributes(); + + // Automatically insert any other attribute inserted + if (!empty($elementAttribs)) { + foreach ($elementAttribs as $name => $value) { + if (!in_array($name, $this->forbiddenAttributes)) { + $this->addAttribute($name, $value); + } + } + } + + $html = ''; + + if ($this->multiple == 1 && is_array($this->value)) { + foreach ($this->value AS $value) { + $this->attribs['value'] = htmlspecialchars($value, ENT_COMPAT, 'UTF-8'); + + $html .= '
    attribs) . ' />
    '; + } + + return $html; + } + + $this->attribs['value'] = htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8'); + + return 'attribs) . ' />'; + } + + /** + * Add an attribute to the input field + * + * @param string $name Name of the attribute + * @param string $value Value for the attribute + * + * @return void + */ + protected function addAttribute($name, $value) + { + if (!is_null($value)) { + $name = strtolower($name); + + $this->attribs[$name] = (string)$value; + } + } } diff --git a/libraries/redshop/form/field/users.php b/libraries/redshop/form/field/users.php index a2c096acca1..78273206881 100644 --- a/libraries/redshop/form/field/users.php +++ b/libraries/redshop/form/field/users.php @@ -18,45 +18,46 @@ */ class RedshopFormFieldUsers extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Users'; - - /** - * Method to get the field input markup. - * - * @return array The field input markup. - */ - protected function getOptions() - { - $addressType = isset($this->element['address_type']) ? (string) $this->element['address_type'] : false; - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->qn('u.id', 'value')) - ->select( - 'CONCAT(' . $db->qn('ru.firstname') . ',' - . $db->quote(' ') . ',' - . $db->qn('ru.lastname') . ',' - . $db->quote(' (') . ',' - . $db->qn('u.username') . ',' - . $db->quote(')') . ') AS ' . $db->qn('text') - ) - ->from($db->qn('#__users', 'u')) - ->leftJoin($db->qn('#__redshop_users_info', 'ru') . ' ON ' . $db->qn('u.id') . ' = ' . $db->qn('ru.user_id')); - - if ($addressType !== false) - { - $query->where($db->qn('ru.address_type') . ' = ' . $db->quote($addressType)); - } - - $options = $db->setQuery($query)->loadObjectList(); - - return array_merge(parent::getOptions(), $options); - } + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Users'; + + /** + * Method to get the field input markup. + * + * @return array The field input markup. + */ + protected function getOptions() + { + $addressType = isset($this->element['address_type']) ? (string)$this->element['address_type'] : false; + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->qn('u.id', 'value')) + ->select( + 'CONCAT(' . $db->qn('ru.firstname') . ',' + . $db->quote(' ') . ',' + . $db->qn('ru.lastname') . ',' + . $db->quote(' (') . ',' + . $db->qn('u.username') . ',' + . $db->quote(')') . ') AS ' . $db->qn('text') + ) + ->from($db->qn('#__users', 'u')) + ->leftJoin( + $db->qn('#__redshop_users_info', 'ru') . ' ON ' . $db->qn('u.id') . ' = ' . $db->qn('ru.user_id') + ); + + if ($addressType !== false) { + $query->where($db->qn('ru.address_type') . ' = ' . $db->quote($addressType)); + } + + $options = $db->setQuery($query)->loadObjectList(); + + return array_merge(parent::getOptions(), $options); + } } diff --git a/libraries/redshop/form/field/viewlayout.php b/libraries/redshop/form/field/viewlayout.php index b41ac1a5533..5fc15eabeaf 100644 --- a/libraries/redshop/form/field/viewlayout.php +++ b/libraries/redshop/form/field/viewlayout.php @@ -3,8 +3,8 @@ * @package Phproberto.Joomla-Twig * @subpackage Form.Field * - * @copyright Copyright (C) 2017-2018 Roberto Segura López, Inc. All rights reserved. - * @license See COPYING.txt + * @copyright Copyright (C) 2017-2018 Roberto Segura López, Inc. All rights reserved. + * @license See COPYING.txt */ defined('_JEXEC') || die; diff --git a/libraries/redshop/form/field/voucher_product.php b/libraries/redshop/form/field/voucher_product.php index 3557dbed55c..5fc4b0b1297 100644 --- a/libraries/redshop/form/field/voucher_product.php +++ b/libraries/redshop/form/field/voucher_product.php @@ -18,84 +18,78 @@ */ class RedshopFormFieldVoucher_Product extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - public $type = 'Voucher_Product'; + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + public $type = 'Voucher_Product'; - /** - * Method to get the field input markup for a generic list. - * Use the multiple attribute to enable multiselect. - * - * @return string The field input markup. - * - * @since 3.7.0 - */ - protected function getInput() - { - $voucherId = isset($this->element['voucher_id']) ? (int) $this->element['voucher_id'] : false; - $selected = array(); - $typeField = ', alert:"voucher"'; + /** + * Method to get the field input markup for a generic list. + * Use the multiple attribute to enable multiselect. + * + * @return string The field input markup. + * + * @since 3.7.0 + */ + protected function getInput() + { + $voucherId = isset($this->element['voucher_id']) ? (int)$this->element['voucher_id'] : false; + $selected = array(); + $typeField = ', alert:"voucher"'; - if ($voucherId) - { - $products = RedshopEntityVoucher::getInstance($voucherId)->getProducts(); - $typeField .= ', voucher_id:' . $voucherId; + if ($voucherId) { + $products = RedshopEntityVoucher::getInstance($voucherId)->getProducts(); + $typeField .= ', voucher_id:' . $voucherId; - if (!$products->isEmpty()) - { - foreach ($products->getAll() as $product) - { - $data = new stdClass; - $data->value = $product->get('product_id'); - $data->text = $product->get('product_name'); + if (!$products->isEmpty()) { + foreach ($products->getAll() as $product) { + $data = new stdClass; + $data->value = $product->get('product_id'); + $data->text = $product->get('product_name'); - $selected[$product->get('product_id')] = $data; - } - } - } + $selected[$product->get('product_id')] = $data; + } + } + } - if (!empty($this->value)) - { - $values = !$this->multiple || !is_array($this->value) ? array($this->value) : $this->value; - $db = JFactory::getDbo(); + if (!empty($this->value)) { + $values = !$this->multiple || !is_array($this->value) ? array($this->value) : $this->value; + $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn(array('product_id', 'product_name'))) - ->from($db->qn('#__redshop_product')) - ->where($db->qn('product_id') . ' IN (' . implode(',', $values) . ')'); + $query = $db->getQuery(true) + ->select($db->qn(array('product_id', 'product_name'))) + ->from($db->qn('#__redshop_product')) + ->where($db->qn('product_id') . ' IN (' . implode(',', $values) . ')'); - $products = $db->setQuery($query)->loadObjectList(); + $products = $db->setQuery($query)->loadObjectList(); - foreach ($products as $product) - { - if (isset($selected[$product->product_id])) - { - continue; - } + foreach ($products as $product) { + if (isset($selected[$product->product_id])) { + continue; + } - $data = new stdClass; - $data->value = $product->product_id; - $data->text = $product->product_name; + $data = new stdClass; + $data->value = $product->product_id; + $data->text = $product->product_name; - $selected[$product->product_id] = $data; - } - } + $selected[$product->product_id] = $data; + } + } - return JHtml::_( - 'redshopselect.search', - $selected, - 'jform[' . $this->fieldname . ']', - array( - 'select2.ajaxOptions' => array( - 'typeField' => $typeField - ), - 'select2.options' => array('multiple' => true), - 'list.attr' => array('required' => 'required') - ) - ); - } + return JHtml::_( + 'redshopselect.search', + $selected, + 'jform[' . $this->fieldname . ']', + array( + 'select2.ajaxOptions' => array( + 'typeField' => $typeField + ), + 'select2.options' => array('multiple' => true), + 'list.attr' => array('required' => 'required') + ) + ); + } } diff --git a/libraries/redshop/form/fields/cardtypes.php b/libraries/redshop/form/fields/cardtypes.php index b656d02efe8..3b9cac6f8cc 100644 --- a/libraries/redshop/form/fields/cardtypes.php +++ b/libraries/redshop/form/fields/cardtypes.php @@ -20,79 +20,79 @@ */ class JFormFieldCardTypes extends JFormFieldCheckboxes { - /** - * Element name - * - * @var string - */ - public $type = 'cardtypes'; + /** + * Element name + * + * @var string + */ + public $type = 'cardtypes'; - /** - * Method to get the field options. - * - * @return array The field option objects. - * - * @since 11.1 - */ - protected function getOptions() - { - JFactory::getLanguage()->load('com_redshop'); + /** + * Method to get the field options. + * + * @return array The field option objects. + * + * @since 11.1 + */ + protected function getOptions() + { + JFactory::getLanguage()->load('com_redshop'); - $cardTypes = array(); - $cardTypes['ALL'] = 'COM_REDSHOP_CARD_TYPE_ALL'; - $cardTypes['DANKORT'] = 'COM_REDSHOP_CARD_TYPE_DANKORT'; - $cardTypes['VD'] = 'COM_REDSHOP_CARD_TYPE_VD'; - $cardTypes['VE'] = 'COM_REDSHOP_CARD_TYPE_VE'; - $cardTypes['MCDK'] = 'COM_REDSHOP_CARD_TYPE_MCDK'; - $cardTypes['MC'] = 'COM_REDSHOP_CARD_TYPE_MC'; - $cardTypes['VEDK'] = 'COM_REDSHOP_CARD_TYPE_VEDK'; - $cardTypes['JCB'] = 'COM_REDSHOP_CARD_TYPE_JCB'; - $cardTypes['DDK'] = 'COM_REDSHOP_CARD_TYPE_DDK'; - $cardTypes['MDK'] = 'COM_REDSHOP_CARD_TYPE_MDK'; - $cardTypes['AEDK'] = 'COM_REDSHOP_CARD_TYPE_AEDK'; - $cardTypes['DINERS'] = 'COM_REDSHOP_CARD_TYPE_DINERS'; - $cardTypes['JCBS'] = 'COM_REDSHOP_CARD_TYPE_JCBS'; - $cardTypes['AE'] = 'COM_REDSHOP_CARD_TYPE_AE'; - $cardTypes['MAESTRO'] = 'COM_REDSHOP_CARD_TYPE_MAESTRO'; - $cardTypes['FORBRUGSFORENINGEN'] = 'COM_REDSHOP_CARD_TYPE_FORBRUGSFORENINGEN'; - $cardTypes['EWIRE'] = 'COM_REDSHOP_CARD_TYPE_EWIRE'; - $cardTypes['VISA'] = 'COM_REDSHOP_CARD_TYPE_VISA'; - $cardTypes['IKANO'] = 'COM_REDSHOP_CARD_TYPE_IKANO'; - $cardTypes['NORDEA'] = 'COM_REDSHOP_CARD_TYPE_NORDEA'; - $cardTypes['DB'] = 'COM_REDSHOP_CARD_TYPE_DB'; - $cardTypes['IKANO'] = 'COM_REDSHOP_CARD_TYPE_IKANO'; - $cardTypes['MASTERCARDDEBETCARD'] = 'COM_REDSHOP_CARD_TYPE_MASTERCARDDEBETCARD'; - $cardTypes['PAII'] = 'COM_REDSHOP_CARD_TYPE_PAII'; - $cardTypes['VIABILL'] = 'COM_REDSHOP_CARD_TYPE_VIABILL'; + $cardTypes = array(); + $cardTypes['ALL'] = 'COM_REDSHOP_CARD_TYPE_ALL'; + $cardTypes['DANKORT'] = 'COM_REDSHOP_CARD_TYPE_DANKORT'; + $cardTypes['VD'] = 'COM_REDSHOP_CARD_TYPE_VD'; + $cardTypes['VE'] = 'COM_REDSHOP_CARD_TYPE_VE'; + $cardTypes['MCDK'] = 'COM_REDSHOP_CARD_TYPE_MCDK'; + $cardTypes['MC'] = 'COM_REDSHOP_CARD_TYPE_MC'; + $cardTypes['VEDK'] = 'COM_REDSHOP_CARD_TYPE_VEDK'; + $cardTypes['JCB'] = 'COM_REDSHOP_CARD_TYPE_JCB'; + $cardTypes['DDK'] = 'COM_REDSHOP_CARD_TYPE_DDK'; + $cardTypes['MDK'] = 'COM_REDSHOP_CARD_TYPE_MDK'; + $cardTypes['AEDK'] = 'COM_REDSHOP_CARD_TYPE_AEDK'; + $cardTypes['DINERS'] = 'COM_REDSHOP_CARD_TYPE_DINERS'; + $cardTypes['JCBS'] = 'COM_REDSHOP_CARD_TYPE_JCBS'; + $cardTypes['AE'] = 'COM_REDSHOP_CARD_TYPE_AE'; + $cardTypes['MAESTRO'] = 'COM_REDSHOP_CARD_TYPE_MAESTRO'; + $cardTypes['FORBRUGSFORENINGEN'] = 'COM_REDSHOP_CARD_TYPE_FORBRUGSFORENINGEN'; + $cardTypes['EWIRE'] = 'COM_REDSHOP_CARD_TYPE_EWIRE'; + $cardTypes['VISA'] = 'COM_REDSHOP_CARD_TYPE_VISA'; + $cardTypes['IKANO'] = 'COM_REDSHOP_CARD_TYPE_IKANO'; + $cardTypes['NORDEA'] = 'COM_REDSHOP_CARD_TYPE_NORDEA'; + $cardTypes['DB'] = 'COM_REDSHOP_CARD_TYPE_DB'; + $cardTypes['IKANO'] = 'COM_REDSHOP_CARD_TYPE_IKANO'; + $cardTypes['MASTERCARDDEBETCARD'] = 'COM_REDSHOP_CARD_TYPE_MASTERCARDDEBETCARD'; + $cardTypes['PAII'] = 'COM_REDSHOP_CARD_TYPE_PAII'; + $cardTypes['VIABILL'] = 'COM_REDSHOP_CARD_TYPE_VIABILL'; - // Allow parent options - This will extends the options added directly from XML - $options = parent::getOptions(); + // Allow parent options - This will extends the options added directly from XML + $options = parent::getOptions(); - foreach ($cardTypes as $value => $text) - { - $tmp = JHtml::_( - 'select.option', - $value, - $text, - 'value', - 'text' - ); + foreach ($cardTypes as $value => $text) { + $tmp = JHtml::_( + 'select.option', + $value, + $text, + 'value', + 'text' + ); - // Set some option attributes. - $tmp->checked = false; + // Set some option attributes. + $tmp->checked = false; - // Add the option object to the result set. - $options[] = $tmp; - } + // Add the option object to the result set. + $options[] = $tmp; + } - JFactory::getDocument()->addScriptDeclaration(' + JFactory::getDocument()->addScriptDeclaration( + ' jQuery(document).ready(function (){ jQuery("#jform_params_cardtypes0").click(function(event) { jQuery("[id^=jform_params_cardtypes]").attr("checked", jQuery(this).get(0).checked); }); });' - ); + ); - return $options; - } + return $options; + } } diff --git a/libraries/redshop/form/fields/categories.php b/libraries/redshop/form/fields/categories.php index 5aa6a1c3528..46c311ca260 100644 --- a/libraries/redshop/form/fields/categories.php +++ b/libraries/redshop/form/fields/categories.php @@ -18,43 +18,50 @@ */ class JFormFieldCategories extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.6 - */ - protected $type = 'Categories'; - - /** - * Method to get the field input markup for a generic list. - * - * @return string The field input markup. - */ - public function getInput() - { - $categories = RedshopHelperCategory::getParentCategories(); - - if (count($categories) > 0) - { - foreach ($categories as $category) - { - $option = JHtml::_('select.option', $category->id, $category->name); - $options[] = $option; - } - } - - $options = array_merge(parent::getOptions(), $options); - $attr = ''; - - // Initialize some field attributes. - $attr .= $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; - $attr .= $this->element['size'] ? ' size="' . (int) $this->element['size'] . '"' : ''; - $attr .= $this->element['multiple'] ? ' multiple' : ''; - - // Initialize JavaScript field attributes. - $attr .= $this->element['onchange'] ? ' onchange="' . (string) $this->element['onchange'] . '"' : ''; - - return JHtml::_('select.genericlist', $options, $this->name, trim($attr), 'value', 'text', $this->value, $this->id); - } + /** + * The form field type. + * + * @var string + * @since 1.6 + */ + protected $type = 'Categories'; + + /** + * Method to get the field input markup for a generic list. + * + * @return string The field input markup. + */ + public function getInput() + { + $categories = RedshopHelperCategory::getParentCategories(); + + if (count($categories) > 0) { + foreach ($categories as $category) { + $option = JHtml::_('select.option', $category->id, $category->name); + $options[] = $option; + } + } + + $options = array_merge(parent::getOptions(), $options); + $attr = ''; + + // Initialize some field attributes. + $attr .= $this->element['class'] ? ' class="' . (string)$this->element['class'] . '"' : ''; + $attr .= $this->element['size'] ? ' size="' . (int)$this->element['size'] . '"' : ''; + $attr .= $this->element['multiple'] ? ' multiple' : ''; + + // Initialize JavaScript field attributes. + $attr .= $this->element['onchange'] ? ' onchange="' . (string)$this->element['onchange'] . '"' : ''; + + return JHtml::_( + 'select.genericlist', + $options, + $this->name, + trim($attr), + 'value', + 'text', + $this->value, + $this->id + ); + } } diff --git a/libraries/redshop/form/fields/categoriesparent.php b/libraries/redshop/form/fields/categoriesparent.php index c22e0a4a574..3f0b25c8e9f 100644 --- a/libraries/redshop/form/fields/categoriesparent.php +++ b/libraries/redshop/form/fields/categoriesparent.php @@ -18,161 +18,136 @@ */ class JFormFieldCategoriesParent extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.6 - */ - protected $type = 'CategoriesParent'; - - /** - * Method to get the field options. - * - * @return array The field option objects. - * - * @since 1.6 - */ - protected function getOptions() - { - // Initialise variables. - $options = array(); - $name = (string) $this->element['name']; - - // Let's get the id for the current item, either category or content item. - $input = JFactory::getApplication()->input; - $extension = 'com_redshop'; - - // For categories the old category is the category id 0 for new category. - if ($this->element['parent']) - { - $oldCat = $input->get('id', 0); - } - else - // For items the old category is the category they are in when opened or 0 if new. - { - $oldCat = $this->form->getValue($name); - } - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('a.id AS value, a.name AS text, a.level, a.published') - ->from('#__redshop_category AS a') - ->join('LEFT', $db->quoteName('#__redshop_category') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt'); - - if ($this->element['parent']) - { - // Prevent parenting to children of this item. - if ($id = $this->form->getValue('id')) - { - $query->join('LEFT', $db->quoteName('#__redshop_category') . ' AS p ON p.id = ' . (int) $id) - ->where('NOT(a.lft >= p.lft AND a.rgt <= p.rgt)'); - - $rowQuery = $db->getQuery(true); - $rowQuery->select('a.id AS value, a.name AS text, a.level, a.parent_id') - ->from('#__redshop_category AS a') - ->where('a.id = ' . (int) $id); - $db->setQuery($rowQuery); - $row = $db->loadObject(); - } - } - - $query->where('a.published IN (0,1)') - ->group('a.id, a.name, a.level, a.lft, a.rgt, a.parent_id') - ->order('a.lft ASC'); - - // Get the options. - $db->setQuery($query); - - try - { - $options = $db->loadObjectList(); - } - catch (RuntimeException $e) - { - JError::raiseWarning(500, $e->getMessage()); - } - - // Pad the option text with spaces using depth level as a multiplier. - for ($i = 0, $n = count($options); $i < $n; $i++) - { - // Translate ROOT - if ($this->element['parent'] == true) - { - if ($options[$i]->level == 0) - { - $options[$i]->text = JText::_('JGLOBAL_ROOT_PARENT'); - } - } - - if ($options[$i]->published == 1) - { - $options[$i]->text = str_repeat('- ', $options[$i]->level) . $options[$i]->text; - } - else - { - $options[$i]->text = str_repeat('- ', $options[$i]->level) . '[' . $options[$i]->text . ']'; - } - } - - // Get the current user object. - $user = JFactory::getUser(); - - // For new items we want a list of categories you are allowed to create in. - if ($oldCat == 0) - { - foreach ($options as $i => $option) - { - /* - * To take save or create in a category you need to have create rights for that category unless the item is already in that category. - * Unset the option if the user isn't authorised for it. In this field assets are always categories. - */ - if ($user->authorise('core.create', $extension . '.category.' . $option->value) != true) - { - unset($options[$i]); - } - } - } - // If you have an existing category id things are more complex. - else - { - foreach ($options as $i => $option) - { - /* - * If you are only allowed to edit in this category but not edit.state, you should not get any - * option to change the category parent for a category or the category for a content item, - * but you should be able to save in that category. - */ - if ($user->authorise('core.edit.state', $extension . '.category.' . $oldCat) != true) - { - if ($option->value != $oldCat) - { - echo 'y'; - unset($options[$i]); - } - } - /* + /** + * The form field type. + * + * @var string + * @since 1.6 + */ + protected $type = 'CategoriesParent'; + + /** + * Method to get the field options. + * + * @return array The field option objects. + * + * @since 1.6 + */ + protected function getOptions() + { + // Initialise variables. + $options = array(); + $name = (string)$this->element['name']; + + // Let's get the id for the current item, either category or content item. + $input = JFactory::getApplication()->input; + $extension = 'com_redshop'; + + // For categories the old category is the category id 0 for new category. + if ($this->element['parent']) { + $oldCat = $input->get('id', 0); + } else // For items the old category is the category they are in when opened or 0 if new. + { + $oldCat = $this->form->getValue($name); + } + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('a.id AS value, a.name AS text, a.level, a.published') + ->from('#__redshop_category AS a') + ->join('LEFT', $db->quoteName('#__redshop_category') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt'); + + if ($this->element['parent']) { + // Prevent parenting to children of this item. + if ($id = $this->form->getValue('id')) { + $query->join('LEFT', $db->quoteName('#__redshop_category') . ' AS p ON p.id = ' . (int)$id) + ->where('NOT(a.lft >= p.lft AND a.rgt <= p.rgt)'); + + $rowQuery = $db->getQuery(true); + $rowQuery->select('a.id AS value, a.name AS text, a.level, a.parent_id') + ->from('#__redshop_category AS a') + ->where('a.id = ' . (int)$id); + $db->setQuery($rowQuery); + $row = $db->loadObject(); + } + } + + $query->where('a.published IN (0,1)') + ->group('a.id, a.name, a.level, a.lft, a.rgt, a.parent_id') + ->order('a.lft ASC'); + + // Get the options. + $db->setQuery($query); + + try { + $options = $db->loadObjectList(); + } catch (RuntimeException $e) { + JError::raiseWarning(500, $e->getMessage()); + } + + // Pad the option text with spaces using depth level as a multiplier. + for ($i = 0, $n = count($options); $i < $n; $i++) { + // Translate ROOT + if ($this->element['parent'] == true) { + if ($options[$i]->level == 0) { + $options[$i]->text = JText::_('JGLOBAL_ROOT_PARENT'); + } + } + + if ($options[$i]->published == 1) { + $options[$i]->text = str_repeat('- ', $options[$i]->level) . $options[$i]->text; + } else { + $options[$i]->text = str_repeat('- ', $options[$i]->level) . '[' . $options[$i]->text . ']'; + } + } + + // Get the current user object. + $user = JFactory::getUser(); + + // For new items we want a list of categories you are allowed to create in. + if ($oldCat == 0) { + foreach ($options as $i => $option) { + /* + * To take save or create in a category you need to have create rights for that category unless the item is already in that category. + * Unset the option if the user isn't authorised for it. In this field assets are always categories. + */ + if ($user->authorise('core.create', $extension . '.category.' . $option->value) != true) { + unset($options[$i]); + } + } + } // If you have an existing category id things are more complex. + else { + foreach ($options as $i => $option) { + /* + * If you are only allowed to edit in this category but not edit.state, you should not get any + * option to change the category parent for a category or the category for a content item, + * but you should be able to save in that category. + */ + if ($user->authorise('core.edit.state', $extension . '.category.' . $oldCat) != true) { + if ($option->value != $oldCat) { + echo 'y'; + unset($options[$i]); + } + } /* * However, if you can edit.state you can also move this to another category for which you have * create permission and you should also still be able to save in the current category. */ - elseif (($user->authorise('core.create', $extension . '.category.' . $option->value) != true) - && $option->value != $oldCat - ) - { - echo 'x'; - unset($options[$i]); - } - } - } - - if (isset($row) && !isset($options[0]) && $row->parent_id == '1') - { - $parent = new stdClass; - $parent->text = JText::_('JGLOBAL_ROOT_PARENT'); - array_unshift($options, $parent); - } - - // Merge any additional options in the XML definition. - return array_merge(parent::getOptions(), $options); - } + elseif (($user->authorise('core.create', $extension . '.category.' . $option->value) != true) + && $option->value != $oldCat + ) { + echo 'x'; + unset($options[$i]); + } + } + } + + if (isset($row) && !isset($options[0]) && $row->parent_id == '1') { + $parent = new stdClass; + $parent->text = JText::_('JGLOBAL_ROOT_PARENT'); + array_unshift($options, $parent); + } + + // Merge any additional options in the XML definition. + return array_merge(parent::getOptions(), $options); + } } diff --git a/libraries/redshop/form/fields/categorylist.php b/libraries/redshop/form/fields/categorylist.php index ef618bdbb4b..b6ad7e77047 100644 --- a/libraries/redshop/form/fields/categorylist.php +++ b/libraries/redshop/form/fields/categorylist.php @@ -20,381 +20,366 @@ */ class JFormFieldCategoryList extends JFormFieldList { - /** - * To allow creation of new categories. - * - * @var integer - * @since 3.6 - */ - protected $allowAdd; - - /** - * A flexible category list that respects access controls - * - * @var string - * @since 1.6 - */ - public $type = 'CategoryList'; - - /** - * Method to attach a JForm object to the field. - * - * @param SimpleXMLElement $element The SimpleXMLElement object representing the tag for the form field object. - * @param mixed $value The form field value to validate. - * @param string $group The field name group control value. This acts as as an array container for the field. - * For example if the field has name="foo" and the group value is set to "bar" then the - * full field name would end up being "bar[foo]". - * - * @return boolean True on success. - * - * @see JFormField::setup() - * @since 3.2 - */ - public function setup(SimpleXMLElement $element, $value, $group = null) - { - $return = parent::setup($element, $value, $group); - - if ($return) - { - $this->allowAdd = isset($this->element['allowAdd']) ? $this->element['allowAdd'] : ''; - } - - return $return; - } - - /** - * Method to get certain otherwise inaccessible properties from the form field object. - * - * @param string $name The property name for which to the the value. - * - * @return mixed The property value or null. - * - * @since 3.6 - */ - public function __get($name) - { - switch ($name) - { - case 'allowAdd': - return $this->$name; - } - - return parent::__get($name); - } - - /** - * Method to set certain otherwise inaccessible properties of the form field object. - * - * @param string $name The property name for which to the the value. - * @param mixed $value The value of the property. - * - * @return void - * - * @since 3.6 - */ - public function __set($name, $value) - { - $value = (string) $value; - - switch ($name) - { - case 'allowAdd': - $value = (string) $value; - $this->$name = ($value === 'true' || $value === $name || $value === '1'); - break; - default: - parent::__set($name, $value); - } - } - - /** - * Method to get a list of categories that respects access controls and can be used for - * either category assignment or parent category assignment in edit screens. - * Use the parent element to indicate that the field will be used for assigning parent categories. - * - * @return array The field option objects. - * - * @since 1.6 - */ - protected function getOptions() - { - $options = array(); - $published = $this->element['published'] ? $this->element['published'] : array(0, 1); - $name = (string) $this->element['name']; - - // Let's get the id for the current item, either category or content item. - $jinput = JFactory::getApplication()->input; - $extension = 'com_redshop'; - - // For categories the old category is the category id or 0 for new category. - if ($this->element['parent']) - { - $oldCat = $jinput->get('id', 0); - $oldParent = $this->form->getValue($name, 0); - - } - // For items the old category is the category they are in when opened or 0 if new. - else - { - $oldCat = $this->form->getValue($name, 0); - } - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('DISTINCT a.id AS value, a.name AS text, a.level, a.published, a.lft'); - - $subQuery = $db->getQuery(true) - ->select('id, name, level, published, parent_id, lft, rgt') - ->from('#__redshop_category'); - - // Filter on the published state - if (is_numeric($published)) - { - $subQuery->where('published = ' . (int) $published); - } - elseif (is_array($published)) - { - $subQuery->where('published IN (' . implode(',', ArrayHelper::toInteger($published)) . ')'); - } - - $query->from('(' . (string) $subQuery . ') AS a') - ->join('LEFT', $db->qn('#__redshop_category') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt'); - $query->order('a.lft ASC'); - - // If parent isn't explicitly stated but we are in com_redshop assume we want parents - if ($oldCat != 0 && ($this->element['parent'] == true)) - { - // Prevent parenting to children of this item. - // To rearrange parents and children move the children up, not the parents down. - $query->join('LEFT', $db->qn('#__redshop_category') . ' AS p ON p.id = ' . (int) $oldCat) - ->where('NOT(a.lft >= p.lft AND a.rgt <= p.rgt)'); - - $rowQuery = $db->getQuery(true); - $rowQuery->select('a.id AS value, a.name AS text, a.level, a.parent_id') - ->from('#__redshop_category AS a') - ->where('a.id = ' . (int) $oldCat); - $db->setQuery($rowQuery); - $row = $db->loadObject(); - } - - // Get the options. - $db->setQuery($query); - - try - { - $options = $db->loadObjectList(); - } - catch (RuntimeException $e) - { - JError::raiseWarning(500, $e->getMessage()); - } - - // Pad the option text with spaces using depth level as a multiplier. - for ($i = 0, $n = count($options); $i < $n; $i++) - { - // Translate ROOT - if ($this->element['parent'] == true) - { - if ($options[$i]->level == 0) - { - $options[$i]->text = JText::_('JGLOBAL_ROOT_PARENT'); - } - } - - if ($options[$i]->published == 1) - { - $options[$i]->text = str_repeat('- ', $options[$i]->level) . $options[$i]->text; - } - else - { - $options[$i]->text = str_repeat('- ', $options[$i]->level) . '[' . $options[$i]->text . ']'; - } - } - - // Get the current user object. - $user = JFactory::getUser(); - - // For new items we want a list of categories you are allowed to create in. - if ($oldCat == 0) - { - foreach ($options as $i => $option) - { - /* - * To take save or create in a category you need to have create rights for that category unless the item is already in that category. - * Unset the option if the user isn't authorised for it. In this field assets are always categories. - */ - if ($user->authorise('core.create', $extension . '.category.' . $option->value) != true && $option->level != 0) - { - unset($options[$i]); - } - } - } - // If you have an existing category id things are more complex. - else - { - /* - * If you are only allowed to edit in this category but not edit.state, you should not get any - * option to change the category parent for a category or the category for a content item, - * but you should be able to save in that category. - */ - foreach ($options as $i => $option) - { - if ($user->authorise('core.edit.state', $extension . '.category.' . $oldCat) != true && !isset($oldParent)) - { - if ($option->value != $oldCat) - { - unset($options[$i]); - } - } - - if ($user->authorise('core.edit.state', $extension . '.category.' . $oldCat) != true - && (isset($oldParent)) - && $option->value != $oldParent - ) - { - unset($options[$i]); - } - - /* - * However, if you can edit.state you can also move this to another category for which you have - * create permission and you should also still be able to save in the current category. - */ - if (($user->authorise('core.create', $extension . '.category.' . $option->value) != true) - && ($option->value != $oldCat && !isset($oldParent)) - ) - { - { - unset($options[$i]); - } - } - - if (($user->authorise('core.create', $extension . '.category.' . $option->value) != true) - && (isset($oldParent)) - && $option->value != $oldParent - ) - { - { - unset($options[$i]); - } - } - } - } - - if (($this->element['parent'] == true) - && (isset($row) && !isset($options[0])) - && isset($this->element['show_root']) - ) - { - if ($row->parent_id == '1') - { - $parent = new stdClass; - $parent->text = JText::_('JGLOBAL_ROOT_PARENT'); - - array_unshift($options, $parent); - } - - array_unshift($options, JHtml::_('select.option', '0', JText::_('JGLOBAL_ROOT_PARENT'))); - } - - if (!isset($this->element['show_root'])) - { - $options[0]->value = ''; - $options[0]->text = JText::_('COM_REDSHOP_SELECT_CATEGORY'); - } - - if (isset($this->element['remove_select'])) - { - unset($options[0]); - array_merge($options, array()); - } - - // Merge any additional options in the XML definition. - return array_merge(parent::getOptions(), $options); - } - - /** - * Method to get the field input markup for a generic list. - * Use the multiple attribute to enable multiselect. - * - * @return string The field input markup. - * - * @since 3.6 - */ - protected function getInput() - { - $html = array(); - $class = array(); - $attr = ''; - - // Initialize some field attributes. - $class[] = !empty($this->class) ? $this->class : ''; - - if ($this->allowAdd) - { - $customGroupText = JText::_('JGLOBAL_CUSTOM_CATEGORY'); - - $class[] = 'chzn-custom-value'; - $attr .= ' data-custom_group_text="' . $customGroupText . '" ' - . 'data-no_results_text="' . JText::_('JGLOBAL_ADD_CUSTOM_CATEGORY') . '" ' - . 'data-placeholder="' . JText::_('JGLOBAL_TYPE_OR_SELECT_CATEGORY') . '" '; - } - - if ($class) - { - $attr .= 'class="' . implode(' ', $class) . '"'; - } - - $attr .= !empty($this->size) ? ' size="' . $this->size . '"' : ''; - $attr .= $this->multiple ? ' multiple' : ''; - $attr .= $this->required ? ' required aria-required="true"' : ''; - $attr .= $this->autofocus ? ' autofocus' : ''; - - // To avoid user's confusion, readonly="true" should imply disabled="true". - if ((string) $this->readonly == '1' - || (string) $this->readonly == 'true' - || (string) $this->disabled == '1' - || (string) $this->disabled == 'true' - ) - { - $attr .= ' disabled="disabled"'; - } - - // Initialize JavaScript field attributes. - $attr .= $this->onchange ? ' onchange="' . $this->onchange . '"' : ''; - - // Get the field options. - $options = (array) $this->getOptions(); - - // Create a read-only list (no name) with hidden input(s) to store the value(s). - if ((string) $this->readonly == '1' || (string) $this->readonly == 'true') - { - $html[] = JHtml::_('select.genericlist', $options, '', trim($attr), 'value', 'text', $this->value, $this->id); - - // E.g. form field type tag sends $this->value as array - if ($this->multiple && is_array($this->value)) - { - if (!count($this->value)) - { - $this->value[] = ''; - } - - foreach ($this->value as $value) - { - $html[] = ''; - } - } - else - { - $html[] = ''; - } - } - else - // Create a regular list. - { - $html[] = JHtml::_('select.genericlist', $options, $this->name, trim($attr), 'value', 'text', $this->value, $this->id); - } - - return implode($html); - } + /** + * A flexible category list that respects access controls + * + * @var string + * @since 1.6 + */ + public $type = 'CategoryList'; + /** + * To allow creation of new categories. + * + * @var integer + * @since 3.6 + */ + protected $allowAdd; + + /** + * Method to attach a JForm object to the field. + * + * @param SimpleXMLElement $element The SimpleXMLElement object representing the tag for the form field object. + * @param mixed $value The form field value to validate. + * @param string $group The field name group control value. This acts as as an array container for the field. + * For example if the field has name="foo" and the group value is set to "bar" then the + * full field name would end up being "bar[foo]". + * + * @return boolean True on success. + * + * @see JFormField::setup() + * @since 3.2 + */ + public function setup(SimpleXMLElement $element, $value, $group = null) + { + $return = parent::setup($element, $value, $group); + + if ($return) { + $this->allowAdd = isset($this->element['allowAdd']) ? $this->element['allowAdd'] : ''; + } + + return $return; + } + + /** + * Method to get certain otherwise inaccessible properties from the form field object. + * + * @param string $name The property name for which to the the value. + * + * @return mixed The property value or null. + * + * @since 3.6 + */ + public function __get($name) + { + switch ($name) { + case 'allowAdd': + return $this->$name; + } + + return parent::__get($name); + } + + /** + * Method to set certain otherwise inaccessible properties of the form field object. + * + * @param string $name The property name for which to the the value. + * @param mixed $value The value of the property. + * + * @return void + * + * @since 3.6 + */ + public function __set($name, $value) + { + $value = (string)$value; + + switch ($name) { + case 'allowAdd': + $value = (string)$value; + $this->$name = ($value === 'true' || $value === $name || $value === '1'); + break; + default: + parent::__set($name, $value); + } + } + + /** + * Method to get the field input markup for a generic list. + * Use the multiple attribute to enable multiselect. + * + * @return string The field input markup. + * + * @since 3.6 + */ + protected function getInput() + { + $html = array(); + $class = array(); + $attr = ''; + + // Initialize some field attributes. + $class[] = !empty($this->class) ? $this->class : ''; + + if ($this->allowAdd) { + $customGroupText = JText::_('JGLOBAL_CUSTOM_CATEGORY'); + + $class[] = 'chzn-custom-value'; + $attr .= ' data-custom_group_text="' . $customGroupText . '" ' + . 'data-no_results_text="' . JText::_('JGLOBAL_ADD_CUSTOM_CATEGORY') . '" ' + . 'data-placeholder="' . JText::_('JGLOBAL_TYPE_OR_SELECT_CATEGORY') . '" '; + } + + if ($class) { + $attr .= 'class="' . implode(' ', $class) . '"'; + } + + $attr .= !empty($this->size) ? ' size="' . $this->size . '"' : ''; + $attr .= $this->multiple ? ' multiple' : ''; + $attr .= $this->required ? ' required aria-required="true"' : ''; + $attr .= $this->autofocus ? ' autofocus' : ''; + + // To avoid user's confusion, readonly="true" should imply disabled="true". + if ((string)$this->readonly == '1' + || (string)$this->readonly == 'true' + || (string)$this->disabled == '1' + || (string)$this->disabled == 'true' + ) { + $attr .= ' disabled="disabled"'; + } + + // Initialize JavaScript field attributes. + $attr .= $this->onchange ? ' onchange="' . $this->onchange . '"' : ''; + + // Get the field options. + $options = (array)$this->getOptions(); + + // Create a read-only list (no name) with hidden input(s) to store the value(s). + if ((string)$this->readonly == '1' || (string)$this->readonly == 'true') { + $html[] = JHtml::_( + 'select.genericlist', + $options, + '', + trim($attr), + 'value', + 'text', + $this->value, + $this->id + ); + + // E.g. form field type tag sends $this->value as array + if ($this->multiple && is_array($this->value)) { + if (!count($this->value)) { + $this->value[] = ''; + } + + foreach ($this->value as $value) { + $html[] = ''; + } + } else { + $html[] = ''; + } + } else // Create a regular list. + { + $html[] = JHtml::_( + 'select.genericlist', + $options, + $this->name, + trim($attr), + 'value', + 'text', + $this->value, + $this->id + ); + } + + return implode($html); + } + + /** + * Method to get a list of categories that respects access controls and can be used for + * either category assignment or parent category assignment in edit screens. + * Use the parent element to indicate that the field will be used for assigning parent categories. + * + * @return array The field option objects. + * + * @since 1.6 + */ + protected function getOptions() + { + $options = array(); + $published = $this->element['published'] ? $this->element['published'] : array(0, 1); + $name = (string)$this->element['name']; + + // Let's get the id for the current item, either category or content item. + $jinput = JFactory::getApplication()->input; + $extension = 'com_redshop'; + + // For categories the old category is the category id or 0 for new category. + if ($this->element['parent']) { + $oldCat = $jinput->get('id', 0); + $oldParent = $this->form->getValue($name, 0); + } // For items the old category is the category they are in when opened or 0 if new. + else { + $oldCat = $this->form->getValue($name, 0); + } + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('DISTINCT a.id AS value, a.name AS text, a.level, a.published, a.lft'); + + $subQuery = $db->getQuery(true) + ->select('id, name, level, published, parent_id, lft, rgt') + ->from('#__redshop_category'); + + // Filter on the published state + if (is_numeric($published)) { + $subQuery->where('published = ' . (int)$published); + } elseif (is_array($published)) { + $subQuery->where('published IN (' . implode(',', ArrayHelper::toInteger($published)) . ')'); + } + + $query->from('(' . (string)$subQuery . ') AS a') + ->join('LEFT', $db->qn('#__redshop_category') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt'); + $query->order('a.lft ASC'); + + // If parent isn't explicitly stated but we are in com_redshop assume we want parents + if ($oldCat != 0 && ($this->element['parent'] == true)) { + // Prevent parenting to children of this item. + // To rearrange parents and children move the children up, not the parents down. + $query->join('LEFT', $db->qn('#__redshop_category') . ' AS p ON p.id = ' . (int)$oldCat) + ->where('NOT(a.lft >= p.lft AND a.rgt <= p.rgt)'); + + $rowQuery = $db->getQuery(true); + $rowQuery->select('a.id AS value, a.name AS text, a.level, a.parent_id') + ->from('#__redshop_category AS a') + ->where('a.id = ' . (int)$oldCat); + $db->setQuery($rowQuery); + $row = $db->loadObject(); + } + + // Get the options. + $db->setQuery($query); + + try { + $options = $db->loadObjectList(); + } catch (RuntimeException $e) { + JError::raiseWarning(500, $e->getMessage()); + } + + // Pad the option text with spaces using depth level as a multiplier. + for ($i = 0, $n = count($options); $i < $n; $i++) { + // Translate ROOT + if ($this->element['parent'] == true) { + if ($options[$i]->level == 0) { + $options[$i]->text = JText::_('JGLOBAL_ROOT_PARENT'); + } + } + + if ($options[$i]->published == 1) { + $options[$i]->text = str_repeat('- ', $options[$i]->level) . $options[$i]->text; + } else { + $options[$i]->text = str_repeat('- ', $options[$i]->level) . '[' . $options[$i]->text . ']'; + } + } + + // Get the current user object. + $user = JFactory::getUser(); + + // For new items we want a list of categories you are allowed to create in. + if ($oldCat == 0) { + foreach ($options as $i => $option) { + /* + * To take save or create in a category you need to have create rights for that category unless the item is already in that category. + * Unset the option if the user isn't authorised for it. In this field assets are always categories. + */ + if ($user->authorise( + 'core.create', + $extension . '.category.' . $option->value + ) != true && $option->level != 0) { + unset($options[$i]); + } + } + } // If you have an existing category id things are more complex. + else { + /* + * If you are only allowed to edit in this category but not edit.state, you should not get any + * option to change the category parent for a category or the category for a content item, + * but you should be able to save in that category. + */ + foreach ($options as $i => $option) { + if ($user->authorise( + 'core.edit.state', + $extension . '.category.' . $oldCat + ) != true && !isset($oldParent)) { + if ($option->value != $oldCat) { + unset($options[$i]); + } + } + + if ($user->authorise('core.edit.state', $extension . '.category.' . $oldCat) != true + && (isset($oldParent)) + && $option->value != $oldParent + ) { + unset($options[$i]); + } + + /* + * However, if you can edit.state you can also move this to another category for which you have + * create permission and you should also still be able to save in the current category. + */ + if (($user->authorise('core.create', $extension . '.category.' . $option->value) != true) + && ($option->value != $oldCat && !isset($oldParent)) + ) { + { + unset($options[$i]); + } + } + + if (($user->authorise('core.create', $extension . '.category.' . $option->value) != true) + && (isset($oldParent)) + && $option->value != $oldParent + ) { + { + unset($options[$i]); + } + } + } + } + + if (($this->element['parent'] == true) + && (isset($row) && !isset($options[0])) + && isset($this->element['show_root']) + ) { + if ($row->parent_id == '1') { + $parent = new stdClass; + $parent->text = JText::_('JGLOBAL_ROOT_PARENT'); + + array_unshift($options, $parent); + } + + array_unshift($options, JHtml::_('select.option', '0', JText::_('JGLOBAL_ROOT_PARENT'))); + } + + if (!isset($this->element['show_root'])) { + $options[0]->value = ''; + $options[0]->text = JText::_('COM_REDSHOP_SELECT_CATEGORY'); + } + + if (isset($this->element['remove_select'])) { + unset($options[0]); + array_merge($options, array()); + } + + // Merge any additional options in the XML definition. + return array_merge(parent::getOptions(), $options); + } } diff --git a/libraries/redshop/form/fields/creditcards.php b/libraries/redshop/form/fields/creditcards.php index 7a3f83f1331..a76a9492565 100644 --- a/libraries/redshop/form/fields/creditcards.php +++ b/libraries/redshop/form/fields/creditcards.php @@ -20,53 +20,52 @@ */ class JFormFieldCreditCards extends JFormFieldCheckboxes { - /** - * Element name - * - * @var string - */ - protected $type = 'creditcards'; + /** + * Element name + * + * @var string + */ + protected $type = 'creditcards'; - /** - * Method to get the field options. - * - * @return array The field option objects. - * - * @since 11.1 - */ - protected function getOptions() - { - JFactory::getLanguage()->load('com_redshop'); + /** + * Method to get the field options. + * + * @return array The field option objects. + * + * @since 11.1 + */ + protected function getOptions() + { + JFactory::getLanguage()->load('com_redshop'); - $cardTypes = array(); - $cardTypes['VISA'] = JText::_('COM_REDSHOP_CARD_TYPE_VISA'); - $cardTypes['MC'] = JText::_('COM_REDSHOP_CARD_TYPE_MASTERCARD'); - $cardTypes['amex'] = JText::_('COM_REDSHOP_CARD_TYPE_AMERICAN_EXPRESS'); - $cardTypes['maestro'] = JText::_('COM_REDSHOP_CARD_TYPE_MAESTRO'); - $cardTypes['jcb'] = JText::_('COM_REDSHOP_CARD_TYPE_JCB'); - $cardTypes['diners'] = JText::_('COM_REDSHOP_CARD_TYPE_DINERS_CLUB'); - $cardTypes['discover'] = JText::_('COM_REDSHOP_CARD_TYPE_DISCOVER'); + $cardTypes = array(); + $cardTypes['VISA'] = JText::_('COM_REDSHOP_CARD_TYPE_VISA'); + $cardTypes['MC'] = JText::_('COM_REDSHOP_CARD_TYPE_MASTERCARD'); + $cardTypes['amex'] = JText::_('COM_REDSHOP_CARD_TYPE_AMERICAN_EXPRESS'); + $cardTypes['maestro'] = JText::_('COM_REDSHOP_CARD_TYPE_MAESTRO'); + $cardTypes['jcb'] = JText::_('COM_REDSHOP_CARD_TYPE_JCB'); + $cardTypes['diners'] = JText::_('COM_REDSHOP_CARD_TYPE_DINERS_CLUB'); + $cardTypes['discover'] = JText::_('COM_REDSHOP_CARD_TYPE_DISCOVER'); - // Allow parent options - This will extends the options added directly from XML - $options = parent::getOptions(); + // Allow parent options - This will extends the options added directly from XML + $options = parent::getOptions(); - foreach ($cardTypes as $value => $text) - { - $tmp = JHtml::_( - 'select.option', - $value, - $text, - 'value', - 'text' - ); + foreach ($cardTypes as $value => $text) { + $tmp = JHtml::_( + 'select.option', + $value, + $text, + 'value', + 'text' + ); - // Set some option attributes. - $tmp->checked = false; + // Set some option attributes. + $tmp->checked = false; - // Add the option object to the result set. - $options[] = $tmp; - } + // Add the option object to the result set. + $options[] = $tmp; + } - return $options; - } + return $options; + } } diff --git a/libraries/redshop/form/fields/currency.php b/libraries/redshop/form/fields/currency.php index 3bd2170f307..471f078b4c5 100644 --- a/libraries/redshop/form/fields/currency.php +++ b/libraries/redshop/form/fields/currency.php @@ -23,93 +23,91 @@ */ class JFormFieldCurrency extends JFormField { - /** - * Element name - * - * @var string - */ - public $type = 'currency'; - - /** - * Method to get the field input markup. - * - * @return string The field input markup. - * - * @since 11.1 - */ - protected function getInput() - { - $currency = array(); - - if (Redshop::getConfig()->get('CURRENCY_LIBRARIES') == 1) - { - $convertedCurrencies = CurrencyLayer::getInstance()->getConvertedCurrencies(); - } - else - { - $convertedCurrencies = Currency::getInstance()->getConvertedCurrencies(); - } - - if (!empty($convertedCurrencies)) - { - foreach ($convertedCurrencies as $key => $val) - { - $currency[] = $key; - } - - $currency = '\'' . implode("','", $currency) . '\''; - } - - $shopCurrency = $this->getCurrency($currency); - $ctrl = $this->name; - - // Construct the various argument calls that are supported. - $attributes = ' '; - - if ($v = $this->element['size']) - { - $attributes .= 'size="' . $v . '"'; - } - - if ($v = $this->element['class']) - { - $attributes .= 'class="' . $v . '"'; - } - else - { - $attributes .= 'class="form-control inputbox"'; - } - - if ($this->element['multiple']) - { - $attributes .= ' multiple="multiple"'; - } - - return JHtml::_('select.genericlist', $shopCurrency, $ctrl, $attributes, 'value', 'text', $this->value, $this->id); - } - - /** - * Get Shop Currency Support - * - * @param string $currency Comma separated countries - * - * @return array Array for Shop country - * - */ - protected function getCurrency($currency = "") - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('code', 'value')) - ->select($db->qn('name', 'text')) - ->from($db->qn('#__redshop_currency')) - ->order($db->qn('name') . ' ASC'); - - if (!empty($currency)) - { - $query->where($db->qn('code') . ' IN (' . $currency . ')'); - } - - return $db->setQuery($query)->loadObjectList(); - } + /** + * Element name + * + * @var string + */ + public $type = 'currency'; + + /** + * Method to get the field input markup. + * + * @return string The field input markup. + * + * @since 11.1 + */ + protected function getInput() + { + $currency = array(); + + if (Redshop::getConfig()->get('CURRENCY_LIBRARIES') == 1) { + $convertedCurrencies = CurrencyLayer::getInstance()->getConvertedCurrencies(); + } else { + $convertedCurrencies = Currency::getInstance()->getConvertedCurrencies(); + } + + if (!empty($convertedCurrencies)) { + foreach ($convertedCurrencies as $key => $val) { + $currency[] = $key; + } + + $currency = '\'' . implode("','", $currency) . '\''; + } + + $shopCurrency = $this->getCurrency($currency); + $ctrl = $this->name; + + // Construct the various argument calls that are supported. + $attributes = ' '; + + if ($v = $this->element['size']) { + $attributes .= 'size="' . $v . '"'; + } + + if ($v = $this->element['class']) { + $attributes .= 'class="' . $v . '"'; + } else { + $attributes .= 'class="form-control inputbox"'; + } + + if ($this->element['multiple']) { + $attributes .= ' multiple="multiple"'; + } + + return JHtml::_( + 'select.genericlist', + $shopCurrency, + $ctrl, + $attributes, + 'value', + 'text', + $this->value, + $this->id + ); + } + + /** + * Get Shop Currency Support + * + * @param string $currency Comma separated countries + * + * @return array Array for Shop country + * + */ + protected function getCurrency($currency = "") + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('code', 'value')) + ->select($db->qn('name', 'text')) + ->from($db->qn('#__redshop_currency')) + ->order($db->qn('name') . ' ASC'); + + if (!empty($currency)) { + $query->where($db->qn('code') . ' IN (' . $currency . ')'); + } + + return $db->setQuery($query)->loadObjectList(); + } } diff --git a/libraries/redshop/form/fields/economicaccountgroup.php b/libraries/redshop/form/fields/economicaccountgroup.php index 0da03804ae6..3ef39d31af4 100644 --- a/libraries/redshop/form/fields/economicaccountgroup.php +++ b/libraries/redshop/form/fields/economicaccountgroup.php @@ -1,4 +1,5 @@ getQuery(true); - - $query->select($db->quoteName('accountgroup_id', 'value')) - ->select($db->quoteName('accountgroup_name', 'text')) - ->from($db->quoteName('#__redshop_economic_accountgroup')) - ->where($db->quoteName('published') . ' = 1'); - $db->setQuery($query); - - $options = $db->loadObjectList(); - - // Get other options inserted in the XML file - $parentOptions = parent::getOptions(); - - return array_merge($parentOptions, $options); - } + /** + * The form field type. + * + * @var string + */ + protected $type = 'EconomicAccountGroup'; + + /** + * Get the select options + * + * @return array Options to populate the select field + */ + public function getOptions() + { + // Initialize variables. + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select($db->quoteName('accountgroup_id', 'value')) + ->select($db->quoteName('accountgroup_name', 'text')) + ->from($db->quoteName('#__redshop_economic_accountgroup')) + ->where($db->quoteName('published') . ' = 1'); + $db->setQuery($query); + + $options = $db->loadObjectList(); + + // Get other options inserted in the XML file + $parentOptions = parent::getOptions(); + + return array_merge($parentOptions, $options); + } } diff --git a/libraries/redshop/form/fields/epaycardtypes.php b/libraries/redshop/form/fields/epaycardtypes.php index eabdefde3c4..ee0bbf08b4b 100644 --- a/libraries/redshop/form/fields/epaycardtypes.php +++ b/libraries/redshop/form/fields/epaycardtypes.php @@ -19,23 +19,24 @@ */ class JFormFieldEpayCardTypes extends JFormField { - /** - * Element name - * - * @var string - */ - public $type = 'epaycardtypes'; + /** + * Element name + * + * @var string + */ + public $type = 'epaycardtypes'; - /** - * Get input HTML - * - * @return string - * - * @since 1.7 - */ - protected function getInput() - { - JFactory::getDocument()->addScriptDeclaration(' + /** + * Get input HTML + * + * @return string + * + * @since 1.7 + */ + protected function getInput() + { + JFactory::getDocument()->addScriptDeclaration( + ' function enableDisableAll() { if (document.getElementById("ALL").checked == true) { document.getElementById("VD").checked = true; @@ -67,66 +68,56 @@ function enableDisableAll() { document.getElementById("MOBILPENGE").checked = false; } } - '); + ' + ); - // This might get a conflict with the dynamic translation - TODO: search for better solution + // This might get a conflict with the dynamic translation - TODO: search for better solution - //$selected_cc = explode(",",$this->detail->accepted_credict_card); - $creditCards = array(); + //$selected_cc = explode(",",$this->detail->accepted_credict_card); + $creditCards = array(); - $creditCards['ALL'] = 'All cards'; - $creditCards['VD'] = 'Dankort/VISA Dankort'; - $creditCards['ED'] = 'eDankort'; - $creditCards['VE'] = 'VISA / VISA Electron'; - $creditCards['MC'] = 'MASTERCARD'; - $creditCards['JCB'] = 'JCB'; - $creditCards['DINERS'] = 'DINERS'; - $creditCards['MAESTRO'] = 'MAESTRO'; - $creditCards['AE'] = 'AMERICAN EXPRESS'; - $creditCards['FORBRUGSFORENINGEN'] = 'FORBRUGSFORENINGEN'; - $creditCards['NORDEA'] = 'NORDEA'; - $creditCards['DANSKE'] = 'Danske Netbetalinger'; - $creditCards['PAYPAL'] = 'PAYPAL'; - $creditCards['MOBILPENGE'] = 'MOBILPENGE'; + $creditCards['ALL'] = 'All cards'; + $creditCards['VD'] = 'Dankort/VISA Dankort'; + $creditCards['ED'] = 'eDankort'; + $creditCards['VE'] = 'VISA / VISA Electron'; + $creditCards['MC'] = 'MASTERCARD'; + $creditCards['JCB'] = 'JCB'; + $creditCards['DINERS'] = 'DINERS'; + $creditCards['MAESTRO'] = 'MAESTRO'; + $creditCards['AE'] = 'AMERICAN EXPRESS'; + $creditCards['FORBRUGSFORENINGEN'] = 'FORBRUGSFORENINGEN'; + $creditCards['NORDEA'] = 'NORDEA'; + $creditCards['DANSKE'] = 'Danske Netbetalinger'; + $creditCards['PAYPAL'] = 'PAYPAL'; + $creditCards['MOBILPENGE'] = 'MOBILPENGE'; - $html = ''; + $html = ''; - foreach ($creditCards as $key => $value) - { - if (count($this->value) != 0 || $this->value != 0) - { - if (is_array($this->value)) - { - $checked = in_array($key, $this->value) ? "checked" : ""; - } - else - { - $checked = ($key == $this->value) ? "checked" : ""; - } - } - else - { - $checked = ''; - } + foreach ($creditCards as $key => $value) { + if (count($this->value) != 0 || $this->value != 0) { + if (is_array($this->value)) { + $checked = in_array($key, $this->value) ? "checked" : ""; + } else { + $checked = ($key == $this->value) ? "checked" : ""; + } + } else { + $checked = ''; + } - if ($key == 'ALL') - { - if ($key == $this->value) - { - $checked = 'checked'; - } + if ($key == 'ALL') { + if ($key == $this->value) { + $checked = 'checked'; + } - $html .= ""; - } - else - { - $html .= ""; - } - } + $html .= ""; + } else { + $html .= ""; + } + } - return $html; - } + return $html; + } } diff --git a/libraries/redshop/form/fields/extrafieldpayment.php b/libraries/redshop/form/fields/extrafieldpayment.php index 8d368ff068d..b149bb87772 100644 --- a/libraries/redshop/form/fields/extrafieldpayment.php +++ b/libraries/redshop/form/fields/extrafieldpayment.php @@ -21,43 +21,42 @@ */ class JFormFieldExtraFieldPayment extends JFormFieldList { - /** - * Element name - * - * @var string - */ - public $type = 'extrafieldpayment'; - - /** - * Get Extra field info as an option - * - * @return array Extra Field list - */ - protected function getOptions() - { - if (!is_array($this->value)) - { - $this->value = explode(',', $this->value); - } - - // Init variables. - $db = JFactory::getDbo(); - - // Create the base select statement. - $query = $db->getQuery(true) - ->select('name as value, title as text') - ->from($db->qn('#__redshop_fields')) - ->where($db->qn('published') . ' = 1') - ->where($db->qn('show_in_front') . ' = 1') - ->where($db->qn('section') . ' = 18') - ->order($db->qn('ordering') . ' ASC'); - - // Set the query and load the result. - $db->setQuery($query); - - return array_merge( - parent::getOptions(), - $db->loadObjectList() - ); - } + /** + * Element name + * + * @var string + */ + public $type = 'extrafieldpayment'; + + /** + * Get Extra field info as an option + * + * @return array Extra Field list + */ + protected function getOptions() + { + if (!is_array($this->value)) { + $this->value = explode(',', $this->value); + } + + // Init variables. + $db = JFactory::getDbo(); + + // Create the base select statement. + $query = $db->getQuery(true) + ->select('name as value, title as text') + ->from($db->qn('#__redshop_fields')) + ->where($db->qn('published') . ' = 1') + ->where($db->qn('show_in_front') . ' = 1') + ->where($db->qn('section') . ' = 18') + ->order($db->qn('ordering') . ' ASC'); + + // Set the query and load the result. + $db->setQuery($query); + + return array_merge( + parent::getOptions(), + $db->loadObjectList() + ); + } } diff --git a/libraries/redshop/form/fields/extrafields.php b/libraries/redshop/form/fields/extrafields.php index 7f200f12004..553a7ef19a0 100644 --- a/libraries/redshop/form/fields/extrafields.php +++ b/libraries/redshop/form/fields/extrafields.php @@ -18,15 +18,15 @@ * Example: * * + * name="privatePNO" + * type="extrafields" + * field_section="7" + * value_field="field_id" + * text_field="CONCAT(field_title, ' (', field_name, ')')" + * required="true" + * label="PLG_REDSHOP_PAYMENT_KLARNA_PRIVATE_BILLING" + * description="PLG_REDSHOP_PAYMENT_KLARNA_PRIVATE_BILLING_DESC" + * /> * * @package RedSHOP.Library * @subpackage Form.Field @@ -34,133 +34,127 @@ */ class JFormFieldExtraFields extends JFormFieldList { - /** - * Element name - * - * @access protected - * @var string - */ - protected $type = 'extrafields'; - - /** - * Extra Field Section Id for field_section database column - * - * @access protected - * @var integer - */ - protected $fieldSection; - - /** - * Extra Field Show In Front flag value for field_show_in_front database column - * - * @access protected - * @var integer - */ - protected $fieldShowInFront; - - /** - * Extra Field Publishing flag value for published database column - * - * @access protected - * @var integer - */ - protected $published; - - /** - * Database Query Select value to set as element value - * - * @access protected - * @var integer - */ - protected $valueField; - - /** - * Database Query Select value to set as element text - * - * @access protected - * @var integer - */ - protected $textField; - - protected $extraFields = array(); - - /** - * Get Extra field info as an option - * - * @return array Extra Field list - */ - protected function getOptions() - { - $this->fieldSection = 1; - - if (isset($this->element['section'])) - { - $this->fieldSection = (int) $this->element['section']; - } - elseif (isset($this->element['field_section'])) - { - $this->fieldSection = (int) $this->element['field_section']; - } - - $this->fieldType = isset($this->element['field_type']) ? $this->element['field_type'] : ""; - $this->fieldShowInFront = isset($this->element['show_in_front']) ? (int) $this->element['show_in_front'] : null; - $this->published = isset($this->element['published']) ? (int) $this->element['published'] : 1; - - // Dynamic query select options - $this->valueField = isset($this->element['value_field']) ? (string) $this->element['value_field'] : 'name'; - $this->textField = isset($this->element['text_field']) ? (string) $this->element['text_field'] : 'title'; - - return array_merge( - parent::getOptions(), - $this->getExtraFields() - ); - } - - /** - * Get Extra Fields using sections. - * - * @return array Extra Fields list - */ - protected function getExtraFields() - { - $db = JFactory::getDbo(); - - $key = $this->fieldSection . $this->fieldShowInFront . $this->published; - - if (array_key_exists($key, $this->extraFields)) - { - return $this->extraFields[$key]; - } - - // Create the base select statement. - $query = $db->getQuery(true) - ->select( - array( - $this->valueField . ' as value', - $this->textField . ' as text' - ) - ) - ->from($db->qn('#__redshop_fields')) - ->where($db->qn('published') . ' = ' . (int) $this->published); - - if ($this->fieldShowInFront !== null) - { - $query->where($db->qn('show_in_front') . ' = ' . (int) $this->fieldShowInFront); - } - - $query->where($db->qn('section') . ' = ' . (int) $this->fieldSection) - ->order($db->qn('ordering') . ' ASC'); - - if ($this->fieldType != "") - { - $query->where($db->qn('type') . 'IN (' . $this->fieldType . ')'); - } - - // Set the query and load the result. - $db->setQuery($query); - - $this->extraFields[$key] = $db->loadObjectList(); - - return $this->extraFields[$key]; - } + /** + * Element name + * + * @access protected + * @var string + */ + protected $type = 'extrafields'; + + /** + * Extra Field Section Id for field_section database column + * + * @access protected + * @var integer + */ + protected $fieldSection; + + /** + * Extra Field Show In Front flag value for field_show_in_front database column + * + * @access protected + * @var integer + */ + protected $fieldShowInFront; + + /** + * Extra Field Publishing flag value for published database column + * + * @access protected + * @var integer + */ + protected $published; + + /** + * Database Query Select value to set as element value + * + * @access protected + * @var integer + */ + protected $valueField; + + /** + * Database Query Select value to set as element text + * + * @access protected + * @var integer + */ + protected $textField; + + protected $extraFields = array(); + + /** + * Get Extra field info as an option + * + * @return array Extra Field list + */ + protected function getOptions() + { + $this->fieldSection = 1; + + if (isset($this->element['section'])) { + $this->fieldSection = (int)$this->element['section']; + } elseif (isset($this->element['field_section'])) { + $this->fieldSection = (int)$this->element['field_section']; + } + + $this->fieldType = isset($this->element['field_type']) ? $this->element['field_type'] : ""; + $this->fieldShowInFront = isset($this->element['show_in_front']) ? (int)$this->element['show_in_front'] : null; + $this->published = isset($this->element['published']) ? (int)$this->element['published'] : 1; + + // Dynamic query select options + $this->valueField = isset($this->element['value_field']) ? (string)$this->element['value_field'] : 'name'; + $this->textField = isset($this->element['text_field']) ? (string)$this->element['text_field'] : 'title'; + + return array_merge( + parent::getOptions(), + $this->getExtraFields() + ); + } + + /** + * Get Extra Fields using sections. + * + * @return array Extra Fields list + */ + protected function getExtraFields() + { + $db = JFactory::getDbo(); + + $key = $this->fieldSection . $this->fieldShowInFront . $this->published; + + if (array_key_exists($key, $this->extraFields)) { + return $this->extraFields[$key]; + } + + // Create the base select statement. + $query = $db->getQuery(true) + ->select( + array( + $this->valueField . ' as value', + $this->textField . ' as text' + ) + ) + ->from($db->qn('#__redshop_fields')) + ->where($db->qn('published') . ' = ' . (int)$this->published); + + if ($this->fieldShowInFront !== null) { + $query->where($db->qn('show_in_front') . ' = ' . (int)$this->fieldShowInFront); + } + + $query->where($db->qn('section') . ' = ' . (int)$this->fieldSection) + ->order($db->qn('ordering') . ' ASC'); + + if ($this->fieldType != "") { + $query->where($db->qn('type') . 'IN (' . $this->fieldType . ')'); + } + + // Set the query and load the result. + $db->setQuery($query); + + $this->extraFields[$key] = $db->loadObjectList(); + + return $this->extraFields[$key]; + } } diff --git a/libraries/redshop/form/fields/extrafieldshipping.php b/libraries/redshop/form/fields/extrafieldshipping.php index c899c01418c..af3f31a4116 100644 --- a/libraries/redshop/form/fields/extrafieldshipping.php +++ b/libraries/redshop/form/fields/extrafieldshipping.php @@ -21,39 +21,39 @@ */ class JFormFieldExtraFieldShipping extends JFormFieldList { - /** - * Element name - * - * @access protected - * @var string - */ - public $type = 'extrafieldshipping'; + /** + * Element name + * + * @access protected + * @var string + */ + public $type = 'extrafieldshipping'; - /** - * Get Extra field info as an option - * - * @return array Extra Field list - */ - protected function getOptions() - { - // Initialiase variables. - $db = JFactory::getDbo(); + /** + * Get Extra field info as an option + * + * @return array Extra Field list + */ + protected function getOptions() + { + // Initialiase variables. + $db = JFactory::getDbo(); - // Create the base select statement. - $query = $db->getQuery(true) - ->select('name as value, title as text') - ->from($db->qn('#__redshop_fields')) - ->where($db->qn('published') . ' = 1') - ->where($db->qn('show_in_front') . ' = 1') - ->where($db->qn('section') . ' = 19') - ->order($db->qn('ordering') . ' ASC'); + // Create the base select statement. + $query = $db->getQuery(true) + ->select('name as value, title as text') + ->from($db->qn('#__redshop_fields')) + ->where($db->qn('published') . ' = 1') + ->where($db->qn('show_in_front') . ' = 1') + ->where($db->qn('section') . ' = 19') + ->order($db->qn('ordering') . ' ASC'); - // Set the query and load the result. - $db->setQuery($query); + // Set the query and load the result. + $db->setQuery($query); - return array_merge( - parent::getOptions(), - $db->loadObjectList() - ); - } + return array_merge( + parent::getOptions(), + $db->loadObjectList() + ); + } } diff --git a/libraries/redshop/form/fields/extrainfo.php b/libraries/redshop/form/fields/extrainfo.php index 21d6dff0bc0..e569c1ba8c5 100644 --- a/libraries/redshop/form/fields/extrainfo.php +++ b/libraries/redshop/form/fields/extrainfo.php @@ -16,23 +16,22 @@ * @subpackage Banners * @since 1.5 */ - class JFormFieldextrainfo extends JFormField { - /** - * Element name - * - * @access protected - * @var string - */ + /** + * Element name + * + * @access protected + * @var string + */ - public $type = 'extrainfo'; + public $type = 'extrainfo'; - protected function getInput() - { - $html = ''; - $html .= ""; + protected function getInput() + { + $html = ''; + $html .= ""; - return $html; - } + return $html; + } } diff --git a/libraries/redshop/form/fields/index.html b/libraries/redshop/form/fields/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/libraries/redshop/form/fields/index.html +++ b/libraries/redshop/form/fields/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/libraries/redshop/form/fields/manufacturer.php b/libraries/redshop/form/fields/manufacturer.php index 63d44cc36a1..ec41d8588e5 100644 --- a/libraries/redshop/form/fields/manufacturer.php +++ b/libraries/redshop/form/fields/manufacturer.php @@ -9,8 +9,6 @@ defined('_JEXEC') or die; -use Joomla\Utilities\ArrayHelper; - JFormHelper::loadFieldClass('list'); /** @@ -22,29 +20,38 @@ */ class JFormFieldmanufacturer extends JFormFieldList { - /** - * Element name - * - * @access protected - * @var string - */ - public $type = 'manufacturer'; - - - protected function getInput() - { - $db = JFactory::getDbo(); - $name = $this->name; - - // This might get a conflict with the dynamic translation - TODO: search for better solution - $query = 'SELECT id,name ' . - ' FROM #__redshop_manufacturer WHERE published=1'; - $db->setQuery($query); - $options = $db->loadObjectList(); - array_unshift($options, JHTML::_('select.option', '', '- ' . JText::_('COM_REDSHOP_SELECT_MANUFACTURER') . ' -', 'id', 'name')); - - $attr = $this->required ? ' required aria-required="true"' : ''; - - return JHTML::_('select.genericlist', $options, $name, trim($attr), 'id', 'name', $this->value, $this->id); - } + /** + * Element name + * + * @access protected + * @var string + */ + public $type = 'manufacturer'; + + + protected function getInput() + { + $db = JFactory::getDbo(); + $name = $this->name; + + // This might get a conflict with the dynamic translation - TODO: search for better solution + $query = 'SELECT id,name ' . + ' FROM #__redshop_manufacturer WHERE published=1'; + $db->setQuery($query); + $options = $db->loadObjectList(); + array_unshift( + $options, + JHTML::_( + 'select.option', + '', + '- ' . JText::_('COM_REDSHOP_SELECT_MANUFACTURER') . ' -', + 'id', + 'name' + ) + ); + + $attr = $this->required ? ' required aria-required="true"' : ''; + + return JHTML::_('select.genericlist', $options, $name, trim($attr), 'id', 'name', $this->value, $this->id); + } } diff --git a/libraries/redshop/form/fields/mediadragdrop.php b/libraries/redshop/form/fields/mediadragdrop.php index 2c3e6796187..0b77382fd3f 100644 --- a/libraries/redshop/form/fields/mediadragdrop.php +++ b/libraries/redshop/form/fields/mediadragdrop.php @@ -20,35 +20,35 @@ */ class JFormFieldMediadragdrop extends JFormField { - /** - * The form field type - * - * @var string - * - * @since 2.0.3 - */ - protected $type = 'mediadragdrop'; + /** + * The form field type + * + * @var string + * + * @since 2.0.3 + */ + protected $type = 'mediadragdrop'; - /** - * [getInput description] - * - * @return [type] [description] - */ - protected function getInput() - { - // Define data to display in html - $displayData = [ - 'id' => $this->id, - 'name' => $this->name, - 'value' => $this->value - ]; + /** + * [getInput description] + * + * @return [type] [description] + */ + protected function getInput() + { + // Define data to display in html + $displayData = [ + 'id' => $this->id, + 'name' => $this->name, + 'value' => $this->value + ]; - // Render html in layouts/html - return RedshopLayoutHelper::render( - 'media.dropzone', - $displayData, - null, - array('option' => 'com_redshop') - ); - } + // Render html in layouts/html + return RedshopLayoutHelper::render( + 'media.dropzone', + $displayData, + null, + array('option' => 'com_redshop') + ); + } } diff --git a/libraries/redshop/form/fields/orderbymanufacturer.php b/libraries/redshop/form/fields/orderbymanufacturer.php index e8a40353a16..22f124cda7b 100644 --- a/libraries/redshop/form/fields/orderbymanufacturer.php +++ b/libraries/redshop/form/fields/orderbymanufacturer.php @@ -19,33 +19,41 @@ */ class JFormFieldOrderbymanufacturer extends JFormField { - /** - * Element name - * - * @access protected - * @var string - */ - public $type = 'orderbymanufacturer'; - - /** - * Method to get the field input markup. - * - * @return string The field input markup. - */ - protected function getInput() - { - $name = $this->name; - $value = $this->value; - - if (!$value) - { - $value = Redshop::getConfig()->get('DEFAULT_MANUFACTURER_ORDERING_METHOD'); - } - - $order_data = RedshopHelperUtility::getManufacturerOrderByList(); - - $order_select = JHTML::_('select.genericlist', $order_data, $name, 'class="inputbox"', 'value', 'text', $value, $name); - - return $order_select; - } + /** + * Element name + * + * @access protected + * @var string + */ + public $type = 'orderbymanufacturer'; + + /** + * Method to get the field input markup. + * + * @return string The field input markup. + */ + protected function getInput() + { + $name = $this->name; + $value = $this->value; + + if (!$value) { + $value = Redshop::getConfig()->get('DEFAULT_MANUFACTURER_ORDERING_METHOD'); + } + + $order_data = RedshopHelperUtility::getManufacturerOrderByList(); + + $order_select = JHTML::_( + 'select.genericlist', + $order_data, + $name, + 'class="inputbox"', + 'value', + 'text', + $value, + $name + ); + + return $order_select; + } } diff --git a/libraries/redshop/form/fields/orderbyproduct.php b/libraries/redshop/form/fields/orderbyproduct.php index 63d9277fbd8..17591979abf 100644 --- a/libraries/redshop/form/fields/orderbyproduct.php +++ b/libraries/redshop/form/fields/orderbyproduct.php @@ -19,40 +19,39 @@ */ class JFormFieldOrderByProduct extends JFormFieldList { - /** - * Element name - * - * @access protected - * @var string - */ - public $type = 'orderbyproduct'; + /** + * Element name + * + * @access protected + * @var string + */ + public $type = 'orderbyproduct'; - /** - * Method to get the field input markup. - * - * @return string The field input markup. - * - * @since 1.6 - */ - protected function getInput() - { - if (!$this->value) - { - $this->value = Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD'); - } + /** + * Method to get the field input markup. + * + * @return string The field input markup. + * + * @since 1.6 + */ + protected function getInput() + { + if (!$this->value) { + $this->value = Redshop::getConfig()->get('DEFAULT_PRODUCT_ORDERING_METHOD'); + } - return parent::getInput(); - } + return parent::getInput(); + } - /** - * Method to get the field options. - * - * @return array The field option objects. - * - * @since 1.6 - */ - protected function getOptions() - { - return array_merge(parent::getOptions(), RedshopHelperUtility::getOrderByList()); - } + /** + * Method to get the field options. + * + * @return array The field option objects. + * + * @since 1.6 + */ + protected function getOptions() + { + return array_merge(parent::getOptions(), RedshopHelperUtility::getOrderByList()); + } } diff --git a/libraries/redshop/form/fields/orderstatus.php b/libraries/redshop/form/fields/orderstatus.php index 1b9eaec600e..8b598abf2e9 100644 --- a/libraries/redshop/form/fields/orderstatus.php +++ b/libraries/redshop/form/fields/orderstatus.php @@ -18,27 +18,27 @@ */ class JFormFieldOrderStatus extends JFormFieldList { - /** - * Element name - * - * @access protected - * @var string - */ - public $type = 'orderstatus'; + /** + * Element name + * + * @access protected + * @var string + */ + public $type = 'orderstatus'; - /** - * Set select list options - * - * @return string select list options - */ - protected function getOptions() - { - // Load redSHOP Library - JLoader::import('redshop.library'); + /** + * Set select list options + * + * @return string select list options + */ + protected function getOptions() + { + // Load redSHOP Library + JLoader::import('redshop.library'); - $orderStatus = RedshopHelperOrder::getOrderStatusList(); + $orderStatus = RedshopHelperOrder::getOrderStatusList(); - // Merge any additional options in the XML definition. - return array_merge(parent::getOptions(), $orderStatus); - } + // Merge any additional options in the XML definition. + return array_merge(parent::getOptions(), $orderStatus); + } } diff --git a/libraries/redshop/form/fields/ordertemplatelist.php b/libraries/redshop/form/fields/ordertemplatelist.php index 7618cf278fa..bb37fb8cccc 100644 --- a/libraries/redshop/form/fields/ordertemplatelist.php +++ b/libraries/redshop/form/fields/ordertemplatelist.php @@ -18,30 +18,46 @@ */ class JFormFieldordertemplatelist extends JFormField { - /** - * Element name - * - * @access protected - * @var string - */ - public $type = 'ordertemplatelist'; - - protected function getInput() - { - $db = JFactory::getDbo(); - - // This might get a conflict with the dynamic translation - TODO: search for better solution - $query = 'SELECT id,name FROM #__redshop_template ' - . 'WHERE published=1 ' - . 'AND section="order_list" '; - $db->setQuery($query); - $options = $db->loadObjectList(); - array_unshift($options, JHTML::_('select.option', '0', '- ' . JText::_('COM_REDSHOP_SELECT_TEMPLATE') . ' -', 'id', 'name')); - - return JHTML::_('select.genericlist', $options, $this->name, 'class="inputbox"', 'id', 'name', $this->value, $this->id); - - - } + /** + * Element name + * + * @access protected + * @var string + */ + public $type = 'ordertemplatelist'; + + protected function getInput() + { + $db = JFactory::getDbo(); + + // This might get a conflict with the dynamic translation - TODO: search for better solution + $query = 'SELECT id,name FROM #__redshop_template ' + . 'WHERE published=1 ' + . 'AND section="order_list" '; + $db->setQuery($query); + $options = $db->loadObjectList(); + array_unshift( + $options, + JHTML::_( + 'select.option', + '0', + '- ' . JText::_('COM_REDSHOP_SELECT_TEMPLATE') . ' -', + 'id', + 'name' + ) + ); + + return JHTML::_( + 'select.genericlist', + $options, + $this->name, + 'class="inputbox"', + 'id', + 'name', + $this->value, + $this->id + ); + } } ?> diff --git a/libraries/redshop/form/fields/productattributes.php b/libraries/redshop/form/fields/productattributes.php index a12103bde99..94cefde1990 100644 --- a/libraries/redshop/form/fields/productattributes.php +++ b/libraries/redshop/form/fields/productattributes.php @@ -18,56 +18,54 @@ */ class JFormFieldProductattributes extends JFormFieldList { - /** - * A flexible category list that respects access controls - * - * @var string - * @since 2.1.2 - */ - public $type = 'productattributes'; + /** + * A flexible category list that respects access controls + * + * @var string + * @since 2.1.2 + */ + public $type = 'productattributes'; - public $productIds = array(); + public $productIds = array(); - /** - * Set select list options - * - * @return array select list options - */ - public function getOptions() - { - $db = JFactory::getDbo(); - $subQuery = "SELECT a.product_id, ap.attribute_id, a.attribute_name, ap.property_name + /** + * Set select list options + * + * @return array select list options + */ + public function getOptions() + { + $db = JFactory::getDbo(); + $subQuery = "SELECT a.product_id, ap.attribute_id, a.attribute_name, ap.property_name FROM #__redshop_product_attribute_property ap LEFT JOIN #__redshop_product_attribute a ON a.attribute_id = ap.attribute_id WHERE a.attribute_published = 1 AND a.product_id > 0 "; - if (!empty($this->product_ids)) - { - $subQuery .= " AND a.product_id IN (" . implode(',', $this->product_ids) . ") "; - } + if (!empty($this->product_ids)) { + $subQuery .= " AND a.product_id IN (" . implode(',', $this->product_ids) . ") "; + } - $query = "SELECT DISTINCT uniq_att.attribute_name AS text, uniq_att.attribute_name AS value FROM (" . $subQuery . ") AS uniq_att"; + $query = "SELECT DISTINCT uniq_att.attribute_name AS text, uniq_att.attribute_name AS value FROM (" . $subQuery . ") AS uniq_att"; - $attributes = $db->setQuery($query)->loadObjectList(); + $attributes = $db->setQuery($query)->loadObjectList(); - return array_merge(parent::getOptions(), $attributes); - } + return array_merge(parent::getOptions(), $attributes); + } - /** - * Method to get a control group with label and input. - * - * @param array $options Options to be passed into the rendering of the field - * - * @return string A string containing the html for the control group - * - * @since 3.7.3 - */ - public function renderField($options = array()) - { - if (!empty($options) && isset($options['product_ids'])) - { - $this->product_ids = $options['product_ids']; - } + /** + * Method to get a control group with label and input. + * + * @param array $options Options to be passed into the rendering of the field + * + * @return string A string containing the html for the control group + * + * @since 3.7.3 + */ + public function renderField($options = array()) + { + if (!empty($options) && isset($options['product_ids'])) { + $this->product_ids = $options['product_ids']; + } - return parent::renderField($options); - } + return parent::renderField($options); + } } diff --git a/libraries/redshop/form/fields/products.php b/libraries/redshop/form/fields/products.php index 14e875458fb..b726d24ae82 100644 --- a/libraries/redshop/form/fields/products.php +++ b/libraries/redshop/form/fields/products.php @@ -16,64 +16,66 @@ * @subpackage redSHOP * @since 1.5 */ - class JFormFieldProducts extends JFormField { - /** - * Element name - * - * @access Public - * @var string - */ - public $type = 'Products'; + /** + * Element name + * + * @access Public + * @var string + */ + public $type = 'Products'; - protected function getInput() - { - $name = $this->name; - $fieldName = $this->name; + protected function getInput() + { + $name = $this->name; + $fieldName = $this->name; - JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/tables'); + JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/tables'); - $product = JTable::getInstance('product_detail', 'Table'); + $product = JTable::getInstance('product_detail', 'Table'); - if ($this->value) - { - $product->load($this->value); - } - else - { - $product->product_name = JText::_('COM_REDSHOP_SELECT_A_PRODUCT'); - } + if ($this->value) { + $product->load($this->value); + } else { + $product->product_name = JText::_('COM_REDSHOP_SELECT_A_PRODUCT'); + } - JFactory::getDocument()->addScriptDeclaration(" + JFactory::getDocument()->addScriptDeclaration( + " function jSelectProduct(id, title, object) { document.getElementById(object + '_id').value = id; document.getElementById(object + '_name').value = title; window.parent.SqueezeBox.close(); } - "); + " + ); - $link = 'index.php?option=com_redshop&view=product&layout=element&tmpl=component&object=' . $name; + $link = 'index.php?option=com_redshop&view=product&layout=element&tmpl=component&object=' . $name; - JHTML::_('behavior.modal', 'a.modal'); + JHTML::_('behavior.modal', 'a.modal'); - $value = htmlspecialchars($product->product_name, ENT_QUOTES, 'UTF-8'); - $attributes [] = 'style="background: #ffffff;"'; - $attributes [] = ($this->required) ? 'required="required"' : ''; - $class [] = ($this->required) ? 'required=' : ''; - $attributes = array_merge($attributes, $class); - $attributes = trim(implode(' ', array_unique($attributes))); + $value = htmlspecialchars($product->product_name, ENT_QUOTES, 'UTF-8'); + $attributes [] = 'style="background: #ffffff;"'; + $attributes [] = ($this->required) ? 'required="required"' : ''; + $class [] = ($this->required) ? 'required=' : ''; + $attributes = array_merge($attributes, $class); + $attributes = trim(implode(' ', array_unique($attributes))); - $html = '
    '; - $html .= ''; - $html .= '
    '; - $html .= '
    '; - $html .= '
    '; - $html .= '' . JText::_('COM_REDSHOP_Select') . ''; - $html .= '
    '; - $html .= '
    '; - $html .= ''; + $html = '
    '; + $html .= ''; + $html .= '
    '; + $html .= '
    '; + $html .= '
    '; + $html .= '' . JText::_( + 'COM_REDSHOP_Select' + ) . ''; + $html .= '
    '; + $html .= '
    '; + $html .= ''; - return $html; - } + return $html; + } } diff --git a/libraries/redshop/form/fields/productsearchtype.php b/libraries/redshop/form/fields/productsearchtype.php index bf299faaa6b..ffdcd87df86 100644 --- a/libraries/redshop/form/fields/productsearchtype.php +++ b/libraries/redshop/form/fields/productsearchtype.php @@ -18,28 +18,37 @@ */ class JFormFieldproductsearchtype extends JFormField { - /** - * Element name - * - * @access protected - * @var string - */ - public $type = 'productsearchtype'; + /** + * Element name + * + * @access protected + * @var string + */ + public $type = 'productsearchtype'; - protected function getInput() - { - $searchType = array(); + protected function getInput() + { + $searchType = array(); - $searchType[] = JHTML::_('select.option', 'p.product_name ASC', JText::_('COM_REDSHOP_PRODUCT_NAME')); - $searchType[] = JHTML::_('select.option', 'p.product_price ASC', JText::_('COM_REDSHOP_PRODUCT_PRICE_ASC')); - $searchType[] = JHTML::_('select.option', 'p.product_price DESC', JText::_('COM_REDSHOP_PRODUCT_PRICE_DESC')); - $searchType[] = JHTML::_('select.option', 'p.product_number ASC', JText::_('COM_REDSHOP_PRODUCT_NUMBER_ASC')); - $searchType[] = JHTML::_('select.option', 'p.product_id DESC', JText::_('COM_REDSHOP_NEWEST')); - $searchType[] = JHTML::_('select.option', 'pc.ordering ASC', JText::_('COM_REDSHOP_ORDER')); - $searchType[] = JHTML::_('select.option', 'm.manufacturer_name ASC', JText::_('COM_REDSHOP_MANUFACTURER_NAME')); + $searchType[] = JHTML::_('select.option', 'p.product_name ASC', JText::_('COM_REDSHOP_PRODUCT_NAME')); + $searchType[] = JHTML::_('select.option', 'p.product_price ASC', JText::_('COM_REDSHOP_PRODUCT_PRICE_ASC')); + $searchType[] = JHTML::_('select.option', 'p.product_price DESC', JText::_('COM_REDSHOP_PRODUCT_PRICE_DESC')); + $searchType[] = JHTML::_('select.option', 'p.product_number ASC', JText::_('COM_REDSHOP_PRODUCT_NUMBER_ASC')); + $searchType[] = JHTML::_('select.option', 'p.product_id DESC', JText::_('COM_REDSHOP_NEWEST')); + $searchType[] = JHTML::_('select.option', 'pc.ordering ASC', JText::_('COM_REDSHOP_ORDER')); + $searchType[] = JHTML::_('select.option', 'm.manufacturer_name ASC', JText::_('COM_REDSHOP_MANUFACTURER_NAME')); // array_unshift($searchType, JHTML::_('select.option', '0', '- '.JText::_('COM_REDSHOP_SELECT_SEARCH_TYPE').' -', 'value', 'text')); - return JHTML::_('select.genericlist', $searchType, $this->name, 'class="inputbox"', 'value', 'text', $this->value, $this->id); - } + return JHTML::_( + 'select.genericlist', + $searchType, + $this->name, + 'class="inputbox"', + 'value', + 'text', + $this->value, + $this->id + ); + } } diff --git a/libraries/redshop/form/fields/rajaxproducts.php b/libraries/redshop/form/fields/rajaxproducts.php index cbfde171544..c3db345ef26 100644 --- a/libraries/redshop/form/fields/rajaxproducts.php +++ b/libraries/redshop/form/fields/rajaxproducts.php @@ -16,31 +16,33 @@ * @subpackage FormField * @since 2.0.0.4 */ - class JFormFieldRAjaxProducts extends JFormField { - /** - * Element name - * - * @access Public - * @var string - */ - public $type = 'RAjaxProducts'; + /** + * Element name + * + * @access Public + * @var string + */ + public $type = 'RAjaxProducts'; - /** - * getInput. - * - * @return object The model. - * - * @since 2.0.0.4 - */ - protected function getInput() - { - return JHTML::_('redshopselect.jFormSearch', $this->value, 'productid', - array( - 'select2.ajaxOptions' => array('typeField' => ', product:1'), - 'select2.options' => array('placeholder' => JText::_('COM_REDSHOP_PRODUCT')) - ) - ); - } + /** + * getInput. + * + * @return object The model. + * + * @since 2.0.0.4 + */ + protected function getInput() + { + return JHTML::_( + 'redshopselect.jFormSearch', + $this->value, + 'productid', + array( + 'select2.ajaxOptions' => array('typeField' => ', product:1'), + 'select2.options' => array('placeholder' => JText::_('COM_REDSHOP_PRODUCT')) + ) + ); + } } diff --git a/libraries/redshop/form/fields/rajaxusers.php b/libraries/redshop/form/fields/rajaxusers.php index 68064c2c58d..1fef5e9331f 100644 --- a/libraries/redshop/form/fields/rajaxusers.php +++ b/libraries/redshop/form/fields/rajaxusers.php @@ -13,32 +13,35 @@ * Ajax Users Form Field * * @package RedSHOP.Libraries - * @subpackage FormField + * @subpackage FormField * @since 2.0.0.4 */ class JFormFieldRAjaxUsers extends JFormField { - /** - * Element name - * - * @var string - */ - public $type = 'RAjaxUsers'; + /** + * Element name + * + * @var string + */ + public $type = 'RAjaxUsers'; - /** - * getInput. - * - * @return object The model. - * - * @since 2.0.0.4 - */ - protected function getInput() - { - return JHtml::_('redshopselect.jFormSearch', $this->value, 'userid', - array( - 'select2.ajaxOptions' => array('typeField' => ', user:1'), - 'select2.options' => array('placeholder' => JText::_('COM_REDSHOP_USER')) - ) - ); - } + /** + * getInput. + * + * @return object The model. + * + * @since 2.0.0.4 + */ + protected function getInput() + { + return JHtml::_( + 'redshopselect.jFormSearch', + $this->value, + 'userid', + array( + 'select2.ajaxOptions' => array('typeField' => ', user:1'), + 'select2.options' => array('placeholder' => JText::_('COM_REDSHOP_USER')) + ) + ); + } } diff --git a/libraries/redshop/form/fields/rcountries.php b/libraries/redshop/form/fields/rcountries.php index ccfdaaa3d87..634bcec95b4 100644 --- a/libraries/redshop/form/fields/rcountries.php +++ b/libraries/redshop/form/fields/rcountries.php @@ -18,32 +18,32 @@ */ class JFormFieldRcountries extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 2.0.0.4 - */ - protected $type = 'Rcountries'; + /** + * The form field type. + * + * @var string + * @since 2.0.0.4 + */ + protected $type = 'Rcountries'; - /** - * Method to get the field input markup for a generic list. - * - * @return array The field input markup. - */ - public function getOptions() - { - $db = JFactory::getDBO(); - $query = $db->getQuery(true) - ->select($db->qn('id', 'value')) - ->select($db->qn('country_name', 'text')) - ->from($db->qn('#__redshop_country')) - ->order($db->qn('country_name')); + /** + * Method to get the field input markup for a generic list. + * + * @return array The field input markup. + */ + public function getOptions() + { + $db = JFactory::getDBO(); + $query = $db->getQuery(true) + ->select($db->qn('id', 'value')) + ->select($db->qn('country_name', 'text')) + ->from($db->qn('#__redshop_country')) + ->order($db->qn('country_name')); - $options = $db->setQuery($query)->loadObjectList(); + $options = $db->setQuery($query)->loadObjectList(); - $parentOptions = parent::getOptions(); + $parentOptions = parent::getOptions(); - return array_merge($parentOptions, $options); - } + return array_merge($parentOptions, $options); + } } diff --git a/libraries/redshop/form/fields/rcountry3code.php b/libraries/redshop/form/fields/rcountry3code.php index 6db669c680d..8a2d48b4a52 100644 --- a/libraries/redshop/form/fields/rcountry3code.php +++ b/libraries/redshop/form/fields/rcountry3code.php @@ -1,4 +1,5 @@ getQuery(true); - $query->select($db->quoteName('country_3_code', 'value')) - ->select($db->quoteName('country_name', 'text')) - ->from($db->quoteName('#__redshop_country')); - $db->setQuery($query); + /** + * The form field type. + * + * @var string + */ + protected $type = 'RCountry3Code'; + + /** + * Get the select options + * + * @return array Options to populate the select field + */ + public function getOptions() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->select($db->quoteName('country_3_code', 'value')) + ->select($db->quoteName('country_name', 'text')) + ->from($db->quoteName('#__redshop_country')); + $db->setQuery($query); - try - { - $options = $db->loadObjectList(); - } - catch (RuntimeException $e) - { - throw new Exception($e->getMessage()); - } + try { + $options = $db->loadObjectList(); + } catch (RuntimeException $e) { + throw new Exception($e->getMessage()); + } - // Get other options inserted in the XML file - $parentOptions = parent::getOptions(); + // Get other options inserted in the XML file + $parentOptions = parent::getOptions(); - return array_merge($parentOptions, $options); - } + return array_merge($parentOptions, $options); + } } \ No newline at end of file diff --git a/libraries/redshop/form/fields/rdaterange.php b/libraries/redshop/form/fields/rdaterange.php index 5f9b47fcc23..959208a2cdd 100644 --- a/libraries/redshop/form/fields/rdaterange.php +++ b/libraries/redshop/form/fields/rdaterange.php @@ -20,56 +20,58 @@ */ class JFormFieldRdaterange extends JFormField { - /** - * Element name - * - * @var string - */ - protected $type = 'Rdaterange'; + /** + * Element name + * + * @var string + */ + protected $type = 'Rdaterange'; - /** - * The autocomplete state for the form field. If 'off' element will not be automatically - * completed by browser. - * - * @var mixed - * @since 3.2 - */ - protected $autocomplete = 'false'; + /** + * The autocomplete state for the form field. If 'off' element will not be automatically + * completed by browser. + * + * @var mixed + * @since 3.2 + */ + protected $autocomplete = 'false'; - /** - * Method to get the field input markup. - * - * @return string The field input markup. - * - * @since 11.1 - */ - public function getInput() - { - $format = (isset($this->element['format'])) ? (string) $this->element['format'] : 'DD/MM/YYYY'; - $firstDay = (isset($this->element['first_day'])) ? (int) $this->element['first_day'] : 1; - $autoApply = (isset($this->element['auto_apply'])) ? (boolean) $this->element['auto_apply'] : true; - $showButton = (isset($this->element['show_button'])) ? (boolean) $this->element['show_button'] : true; - $class = (isset($this->element['class'])) ? (string) $this->element['class'] : ''; - $onChange = (isset($this->element['onChange'])) ? (string) $this->element['onChange'] : ''; - $phpFormat = (isset($this->element['phpFormat'])) ? (string) $this->element['phpFormat'] : 'd/m/Y'; + /** + * Method to get the field input markup. + * + * @return string The field input markup. + * + * @since 11.1 + */ + public function getInput() + { + $format = (isset($this->element['format'])) ? (string)$this->element['format'] : 'DD/MM/YYYY'; + $firstDay = (isset($this->element['first_day'])) ? (int)$this->element['first_day'] : 1; + $autoApply = (isset($this->element['auto_apply'])) ? (boolean)$this->element['auto_apply'] : true; + $showButton = (isset($this->element['show_button'])) ? (boolean)$this->element['show_button'] : true; + $class = (isset($this->element['class'])) ? (string)$this->element['class'] : ''; + $onChange = (isset($this->element['onChange'])) ? (string)$this->element['onChange'] : ''; + $phpFormat = (isset($this->element['phpFormat'])) ? (string)$this->element['phpFormat'] : 'd/m/Y'; - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/moment.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/daterangepicker.min.js', false, true); - JHtml::stylesheet('com_redshop/daterangepicker.min.css', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/moment.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/daterangepicker.min.js', false, true); + JHtml::stylesheet('com_redshop/daterangepicker.min.css', false, true); - return RedshopLayoutHelper::render( - 'field.date_range', - array( - 'format' => $format, - 'firstDay' => $firstDay, - 'autoApply' => $autoApply, - 'field' => $this, - 'value' => $this->value, - 'class' => $class, - 'showButton' => $showButton, - 'onChange' => $onChange, - 'phpFormat' => $phpFormat - ) - ); - } + return RedshopLayoutHelper::render( + 'field.date_range', + array( + 'format' => $format, + 'firstDay' => $firstDay, + 'autoApply' => $autoApply, + 'field' => $this, + 'value' => $this->value, + 'class' => $class, + 'showButton' => $showButton, + 'onChange' => $onChange, + 'phpFormat' => $phpFormat + ) + ); + } } diff --git a/libraries/redshop/form/fields/redshopcategory.php b/libraries/redshop/form/fields/redshopcategory.php index 7fc420eb109..348c8f9b004 100644 --- a/libraries/redshop/form/fields/redshopcategory.php +++ b/libraries/redshop/form/fields/redshopcategory.php @@ -23,68 +23,60 @@ */ class JFormFieldRedshopCategory extends JFormFieldList { - /** - * Element name - * - * @var string - */ - public $type = 'redshopcategory'; + /** + * A static cache. + * + * @var array|null + */ + protected static $cache = null; + /** + * Element name + * + * @var string + */ + public $type = 'redshopcategory'; - /** - * A static cache. - * - * @var array|null - */ - protected static $cache = null; + /** + * Method to get the field options. + * + * @return array The field option objects. + */ + protected function getOptions() + { + // Process value + if (!empty($this->value) && $this->multiple && !is_array($this->value)) { + $this->value = explode(',', $this->value); + } - /** - * Method to get the field options. - * - * @return array The field option objects. - */ - protected function getOptions() - { - // Process value - if (!empty($this->value) && $this->multiple && !is_array($this->value)) - { - $this->value = explode(',', $this->value); - } + $options = array(); - $options = array(); + if (!$this->multiple) { + $options[] = JHtml::_('select.option', '', JText::_('COM_REDSHOP_SELECT_CATEGORY'), 'value', 'text'); + } - if (!$this->multiple) - { - $options[] = JHtml::_('select.option', '', JText::_('COM_REDSHOP_SELECT_CATEGORY'), 'value', 'text'); - } + if (!self::$cache) { + // Get the categories. + self::$cache = RedshopHelperCategory::getCategoryListArray(); + } - if (!self::$cache) - { - // Get the categories. - self::$cache = RedshopHelperCategory::getCategoryListArray(); - } + // Build the field options. + if (!empty(self::$cache)) { + if ($this->multiple) { + $options[] = JHtml::_('select.optgroup', JText::_('COM_REDSHOP_SELECT_CATEGORY')); + } - // Build the field options. - if (!empty(self::$cache)) - { - if ($this->multiple) - { - $options[] = JHtml::_('select.optgroup', JText::_('COM_REDSHOP_SELECT_CATEGORY')); - } + foreach (self::$cache as $item) { + $options[] = JHtml::_('select.option', $item->id, $item->name, 'value', 'text'); + } - foreach (self::$cache as $item) - { - $options[] = JHtml::_('select.option', $item->id, $item->name, 'value', 'text'); - } + if ($this->multiple) { + $options[] = JHtml::_('select.optgroup', JText::_('COM_REDSHOP_SELECT_CATEGORY')); + } + } - if ($this->multiple) - { - $options[] = JHtml::_('select.optgroup', JText::_('COM_REDSHOP_SELECT_CATEGORY')); - } - } + // Merge any additional options in the XML definition. + $options = array_merge(parent::getOptions(), $options); - // Merge any additional options in the XML definition. - $options = array_merge(parent::getOptions(), $options); - - return $options; - } + return $options; + } } diff --git a/libraries/redshop/form/fields/redshopeditor.php b/libraries/redshop/form/fields/redshopeditor.php index 67e378cd9c1..39d3bd67c97 100644 --- a/libraries/redshop/form/fields/redshopeditor.php +++ b/libraries/redshop/form/fields/redshopeditor.php @@ -19,28 +19,31 @@ */ class JFormFieldRedshopEditor extends JFormFieldEditor { - /** - * The form field type. - * - * @var string - */ - public $type = 'redshopeditor'; + /** + * The form field type. + * + * @var string + */ + public $type = 'redshopeditor'; - /** - * Method to get the field input markup for the editor area - * - * @return string The field input markup. - */ - protected function getInput() - { - if (!$this->value) - { - $layoutFile = $this->element['layoutFile'] ? (string) $this->element['layoutFile'] : 'sample'; - $this->value = RedshopLayoutHelper::render($layoutFile, null, JPATH_SITE . (string) $this->element['basePath']); - } + /** + * Method to get the field input markup for the editor area + * + * @return string The field input markup. + */ + protected function getInput() + { + if (!$this->value) { + $layoutFile = $this->element['layoutFile'] ? (string)$this->element['layoutFile'] : 'sample'; + $this->value = RedshopLayoutHelper::render( + $layoutFile, + null, + JPATH_SITE . (string)$this->element['basePath'] + ); + } - // Style needed for J2.5 - // @todo: remove style in redSHOP 1.6 - return '
    ' . parent::getInput() . '
    '; - } + // Style needed for J2.5 + // @todo: remove style in redSHOP 1.6 + return '
    ' . parent::getInput() . '
    '; + } } diff --git a/libraries/redshop/form/fields/rpredefinedlist.php b/libraries/redshop/form/fields/rpredefinedlist.php index a8ddd2ca1a2..87a3a55be2f 100644 --- a/libraries/redshop/form/fields/rpredefinedlist.php +++ b/libraries/redshop/form/fields/rpredefinedlist.php @@ -20,76 +20,71 @@ */ abstract class JFormFieldPredefinedList extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.0 - */ - protected $type = 'PredefinedList'; + /** + * Cached array of the category items. + * + * @var array + * @since 1.0 + */ + protected static $options = array(); + /** + * The form field type. + * + * @var string + * @since 1.0 + */ + protected $type = 'PredefinedList'; + /** + * Available predefined options + * + * @var array + * @since 1.0 + */ + protected $predefinedOptions = array(); - /** - * Cached array of the category items. - * - * @var array - * @since 1.0 - */ - protected static $options = array(); + /** + * Translate options labels ? + * + * @var boolean + * @since 1.0 + */ + protected $translate = true; - /** - * Available predefined options - * - * @var array - * @since 1.0 - */ - protected $predefinedOptions = array(); + /** + * Method to get the options to populate list + * + * @return array The field option objects. + * + * @since 1.0 + */ + protected function getOptions() + { + // Hash for caching + $hash = md5($this->element); + $type = strtolower($this->type); - /** - * Translate options labels ? - * - * @var boolean - * @since 1.0 - */ - protected $translate = true; + if (!isset(static::$options[$type][$hash]) && !empty($this->predefinedOptions)) { + static::$options[$type][$hash] = parent::getOptions(); - /** - * Method to get the options to populate list - * - * @return array The field option objects. - * - * @since 1.0 - */ - protected function getOptions() - { - // Hash for caching - $hash = md5($this->element); - $type = strtolower($this->type); + $options = array(); - if (!isset(static::$options[$type][$hash]) && !empty($this->predefinedOptions)) - { - static::$options[$type][$hash] = parent::getOptions(); + // Allow to only use specific values of the predefined list + $filter = isset($this->element['filter']) ? explode(',', $this->element['filter']) : array(); - $options = array(); + foreach ($this->predefinedOptions as $value => $text) { + if (empty($filter) || in_array($value, $filter)) { + $text = $this->translate ? JText::_($text) : $text; - // Allow to only use specific values of the predefined list - $filter = isset($this->element['filter']) ? explode(',', $this->element['filter']) : array(); + $options[] = (object)array( + 'value' => $value, + 'text' => $text + ); + } + } - foreach ($this->predefinedOptions as $value => $text) - { - if (empty($filter) || in_array($value, $filter)) - { - $text = $this->translate ? JText::_($text) : $text; + static::$options[$type][$hash] = array_merge(static::$options[$type][$hash], $options); + } - $options[] = (object) array( - 'value' => $value, - 'text' => $text - ); - } - } - - static::$options[$type][$hash] = array_merge(static::$options[$type][$hash], $options); - } - - return static::$options[$type][$hash]; - } + return static::$options[$type][$hash]; + } } diff --git a/libraries/redshop/form/fields/rproducts.php b/libraries/redshop/form/fields/rproducts.php index be07bf7bcd8..ca5e7f444fd 100644 --- a/libraries/redshop/form/fields/rproducts.php +++ b/libraries/redshop/form/fields/rproducts.php @@ -18,63 +18,72 @@ */ class JFormFieldRproducts extends JFormFieldList { - /** - * The form field type. - * - * @var string - * @since 1.6 - */ - protected $type = 'Rproducts'; + /** + * The form field type. + * + * @var string + * @since 1.6 + */ + protected $type = 'Rproducts'; - /** - * Method to get the field input markup for a generic list. - * - * @return array The field input markup. - */ - public function getInput() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('product_id')) - ->select($db->qn('product_name')) - ->select($db->qn('product_number')) - ->from($db->qn('#__redshop_product')) - ->order($db->qn('product_name')); + /** + * Method to get the field input markup for a generic list. + * + * @return array The field input markup. + */ + public function getInput() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('product_id')) + ->select($db->qn('product_name')) + ->select($db->qn('product_number')) + ->from($db->qn('#__redshop_product')) + ->order($db->qn('product_name')); - if (isset($this->element['parent']) && $this->element['parent'] === '0') - { - $query->where($db->qn('product_parent_id') . ' != 0'); - } + if (isset($this->element['parent']) && $this->element['parent'] === '0') { + $query->where($db->qn('product_parent_id') . ' != 0'); + } - $items = $db->setQuery($query)->loadObjectList(); - $options = array(); + $items = $db->setQuery($query)->loadObjectList(); + $options = array(); - if (count($items) > 0) - { - foreach ($items as $item) - { - $option = JHTML::_('select.option', $item->product_id, $item->product_name . '(' . $item->product_number . ')'); - $options[] = $option; - } - } + if (count($items) > 0) { + foreach ($items as $item) { + $option = JHTML::_( + 'select.option', + $item->product_id, + $item->product_name . '(' . $item->product_number . ')' + ); + $options[] = $option; + } + } - $options = array_merge(parent::getOptions(), $options); - $attr = ''; + $options = array_merge(parent::getOptions(), $options); + $attr = ''; - // Initialize some field attributes. - $attr .= $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; - $attr .= $this->element['size'] ? ' size="' . (int) $this->element['size'] . '"' : ''; - $attr .= $this->element['multiple'] ? ' multiple' : ''; + // Initialize some field attributes. + $attr .= $this->element['class'] ? ' class="' . (string)$this->element['class'] . '"' : ''; + $attr .= $this->element['size'] ? ' size="' . (int)$this->element['size'] . '"' : ''; + $attr .= $this->element['multiple'] ? ' multiple' : ''; - // Initialize JavaScript field attributes. - $attr .= $this->element['onchange'] ? ' onchange="' . (string) $this->element['onchange'] . '"' : ''; + // Initialize JavaScript field attributes. + $attr .= $this->element['onchange'] ? ' onchange="' . (string)$this->element['onchange'] . '"' : ''; - // Process value - if (!empty($this->value) && $this->multiple && !is_array($this->value)) - { - $this->value = explode(',', $this->value); - } + // Process value + if (!empty($this->value) && $this->multiple && !is_array($this->value)) { + $this->value = explode(',', $this->value); + } - return JHTML::_('select.genericlist', $options, $this->name, trim($attr), 'value', 'text', $this->value, $this->id); - } + return JHTML::_( + 'select.genericlist', + $options, + $this->name, + trim($attr), + 'value', + 'text', + $this->value, + $this->id + ); + } } diff --git a/libraries/redshop/form/fields/rpublished.php b/libraries/redshop/form/fields/rpublished.php index 42b15a96191..0ede8b0dda1 100644 --- a/libraries/redshop/form/fields/rpublished.php +++ b/libraries/redshop/form/fields/rpublished.php @@ -20,58 +20,54 @@ */ class JFormFieldRpublished extends JFormFieldPredefinedList { - /** - * The form field type. - * - * @var string - */ - protected $type = 'Rpublished'; + /** + * Cached array of the category items. + * + * @var array + * @since 1.0 + */ + protected static $options = array(); + /** + * The form field type. + * + * @var string + */ + protected $type = 'Rpublished'; + /** + * The array of values + * + * @var string + */ + protected $predefinedOptions = array( + 1 => 'JPUBLISHED', + 0 => 'JUNPUBLISHED', + 2 => 'JARCHIVED', + -2 => 'JTRASHED', + '*' => 'JALL' + ); - /** - * Cached array of the category items. - * - * @var array - * @since 1.0 - */ - protected static $options = array(); + /** + * Method to get the options to populate list + * + * @return array The field option objects. + * + * @since 1.0 + */ + protected function getOptions() + { + // Hash for caching + $hash = md5($this->element); + $type = strtolower($this->type); - /** - * The array of values - * - * @var string - */ - protected $predefinedOptions = array( - 1 => 'JPUBLISHED', - 0 => 'JUNPUBLISHED', - 2 => 'JARCHIVED', - -2 => 'JTRASHED', - '*' => 'JALL' - ); + if (!isset(static::$options[$type][$hash]) && !empty($this->predefinedOptions)) { + // B/C with statuses options + if (!isset($this->element['filter']) && isset($this->element['statuses'])) { + $this->element['filter'] = (string)$this->element['statuses']; + } - /** - * Method to get the options to populate list - * - * @return array The field option objects. - * - * @since 1.0 - */ - protected function getOptions() - { - // Hash for caching - $hash = md5($this->element); - $type = strtolower($this->type); + static::$options[$type][$hash] = parent::getOptions(); + } - if (!isset(static::$options[$type][$hash]) && !empty($this->predefinedOptions)) - { - // B/C with statuses options - if (!isset($this->element['filter']) && isset($this->element['statuses'])) - { - $this->element['filter'] = (string) $this->element['statuses']; - } - - static::$options[$type][$hash] = parent::getOptions(); - } - - return static::$options[$type][$hash]; - } + return static::$options[$type][$hash]; + } } diff --git a/libraries/redshop/form/fields/rstate2code.php b/libraries/redshop/form/fields/rstate2code.php index 98776d996c1..8b7fdb9e234 100644 --- a/libraries/redshop/form/fields/rstate2code.php +++ b/libraries/redshop/form/fields/rstate2code.php @@ -1,4 +1,5 @@ input->get('country_code'); - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query->select($db->qn('s.state_2_code', 'value')) - ->select($db->qn('s.state_name', 'text')) - ->from($db->qn('#__redshop_state', 's')) - ->leftJoin($db->qn('#__redshop_country', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('s.country_id')) - ->where($db->qn('c.country_3_code') . ' = ' . $db->q($country3Code)); + /** + * The form field type. + * + * @var string + */ + protected $type = 'RState2Code'; + + /** + * Get the select options + * + * @return array Options to populate the select field + */ + public function getOptions() + { + $app = JFactory::getApplication(); + $country3Code = $app->input->get('country_code'); + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->select($db->qn('s.state_2_code', 'value')) + ->select($db->qn('s.state_name', 'text')) + ->from($db->qn('#__redshop_state', 's')) + ->leftJoin($db->qn('#__redshop_country', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('s.country_id')) + ->where($db->qn('c.country_3_code') . ' = ' . $db->q($country3Code)); - $db->setQuery($query); + $db->setQuery($query); - try - { - $options = $db->loadObjectList(); - } - catch (RuntimeException $e) - { - throw new Exception($e->getMessage()); - } + try { + $options = $db->loadObjectList(); + } catch (RuntimeException $e) { + throw new Exception($e->getMessage()); + } - // Get other options inserted in the XML file - $parentOptions = parent::getOptions(); + // Get other options inserted in the XML file + $parentOptions = parent::getOptions(); - return array_merge($parentOptions, $options); - } + return array_merge($parentOptions, $options); + } } \ No newline at end of file diff --git a/libraries/redshop/form/fields/sample.php b/libraries/redshop/form/fields/sample.php index 988150db24d..1ce73ef823a 100644 --- a/libraries/redshop/form/fields/sample.php +++ b/libraries/redshop/form/fields/sample.php @@ -19,39 +19,39 @@ */ class JFormFieldSample extends JFormField { - /** - * The form field type. - * - * @var string - */ - protected $type = 'Sample'; + /** + * The form field type. + * + * @var string + */ + protected $type = 'Sample'; - /** - * Method to get the field label markup. - * - * @return string The field label markup. - * - * @since 11.1 - */ - protected function getLabel() - { - $layoutFile = $this->element['layoutFile'] ? (string) $this->element['layoutFile'] : 'sample'; - $html = RedshopLayoutHelper::render($layoutFile, null, JPATH_SITE . (string) $this->element['basePath']); + /** + * Method to get the field label markup. + * + * @return string The field label markup. + * + * @since 11.1 + */ + protected function getLabel() + { + $layoutFile = $this->element['layoutFile'] ? (string)$this->element['layoutFile'] : 'sample'; + $html = RedshopLayoutHelper::render($layoutFile, null, JPATH_SITE . (string)$this->element['basePath']); - // Style needed for J2.5 - // @todo: remove style in redSHOP 1.6 - return '
    ' . htmlentities($html) . '
    '; - } + // Style needed for J2.5 + // @todo: remove style in redSHOP 1.6 + return '
    ' . htmlentities($html) . '
    '; + } - /** - * Method to get the field input markup. - * - * @return string The field input markup. - * - * @since 11.1 - */ - protected function getInput() - { - return ''; - } + /** + * Method to get the field input markup. + * + * @return string The field input markup. + * + * @since 11.1 + */ + protected function getInput() + { + return ''; + } } diff --git a/libraries/redshop/form/fields/searchtype.php b/libraries/redshop/form/fields/searchtype.php index 2534792207a..169d050a335 100644 --- a/libraries/redshop/form/fields/searchtype.php +++ b/libraries/redshop/form/fields/searchtype.php @@ -18,27 +18,50 @@ */ class JFormFieldsearchtype extends JFormField { - /** - * Element name - * - * @access protected - * @var string - */ - public $type = 'searchtype'; + /** + * Element name + * + * @access protected + * @var string + */ + public $type = 'searchtype'; - protected function getInput() - { - $searchType = array(); - $searchType[] = JHTML::_('select.option', 'product_name', JText::_('COM_REDSHOP_PRODUCT_NAME')); - $searchType[] = JHTML::_('select.option', 'product_desc', JText::_('COM_REDSHOP_PRODUCT_DESCRIPTION')); - $searchType[] = JHTML::_('select.option', 'product_number', JText::_('COM_REDSHOP_PRODUCT_NUMBER')); - $searchType[] = JHTML::_('select.option', 'name_number', JText::_("COM_REDSHOP_PRODUCT_NAME") . ' & ' . JText::_("COM_REDSHOP_PRODUCT_NUMBER")); - $searchType[] = JHTML::_('select.option', 'virtual_product_num', JTEXT::_("COM_REDSHOP_VIRTUAL_PRODUCT_NUM")); - $searchType[] = JHTML::_('select.option', 'name_desc', JText::_("COM_REDSHOP_PRODUCT_NAME_AND_PRODUCT_DESCRIPTION")); - $searchType[] = JHTML::_('select.option', 'name_number_desc', JText::_("COM_REDSHOP_PRODUCT_NAME_AND_PRODUCT_NUMBER_AND_VIRTUAL_PRODUCT_NUM_AND_PRODUCT_DESCRIPTION")); + protected function getInput() + { + $searchType = array(); + $searchType[] = JHTML::_('select.option', 'product_name', JText::_('COM_REDSHOP_PRODUCT_NAME')); + $searchType[] = JHTML::_('select.option', 'product_desc', JText::_('COM_REDSHOP_PRODUCT_DESCRIPTION')); + $searchType[] = JHTML::_('select.option', 'product_number', JText::_('COM_REDSHOP_PRODUCT_NUMBER')); + $searchType[] = JHTML::_( + 'select.option', + 'name_number', + JText::_("COM_REDSHOP_PRODUCT_NAME") . ' & ' . JText::_("COM_REDSHOP_PRODUCT_NUMBER") + ); + $searchType[] = JHTML::_('select.option', 'virtual_product_num', JTEXT::_("COM_REDSHOP_VIRTUAL_PRODUCT_NUM")); + $searchType[] = JHTML::_( + 'select.option', + 'name_desc', + JText::_("COM_REDSHOP_PRODUCT_NAME_AND_PRODUCT_DESCRIPTION") + ); + $searchType[] = JHTML::_( + 'select.option', + 'name_number_desc', + JText::_( + "COM_REDSHOP_PRODUCT_NAME_AND_PRODUCT_NUMBER_AND_VIRTUAL_PRODUCT_NUM_AND_PRODUCT_DESCRIPTION" + ) + ); // array_unshift($searchType, JHTML::_('select.option', '0', '- '.JText::_('COM_REDSHOP_SELECT_SEARCH_TYPE').' -', 'value', 'text')); - return JHTML::_('select.genericlist', $searchType, $this->name, 'class="inputbox"', 'value', 'text', $this->value, $this->id); - } + return JHTML::_( + 'select.genericlist', + $searchType, + $this->name, + 'class="inputbox"', + 'value', + 'text', + $this->value, + $this->id + ); + } } diff --git a/libraries/redshop/form/fields/shoppergrouplist.php b/libraries/redshop/form/fields/shoppergrouplist.php index 7c1ba0b6675..ded3e37c583 100644 --- a/libraries/redshop/form/fields/shoppergrouplist.php +++ b/libraries/redshop/form/fields/shoppergrouplist.php @@ -18,28 +18,28 @@ */ class JFormFieldShoppergrouplist extends JFormFieldList { - /** - * Element name - * - * @access protected - * @var string - */ - public $type = 'shoppergrouplist'; + /** + * Element name + * + * @access protected + * @var string + */ + public $type = 'shoppergrouplist'; - /** - * Set select list options - * - * @return string select list options - */ - protected function getOptions() - { - // Load redSHOP Library - JLoader::import('redshop.library'); - $shopperGroups = Redshop\Helper\ShopperGroup::generateList(); + /** + * Set select list options + * + * @return string select list options + */ + protected function getOptions() + { + // Load redSHOP Library + JLoader::import('redshop.library'); + $shopperGroups = Redshop\Helper\ShopperGroup::generateList(); - // Merge any additional options in the XML definition. - $shopperGroups = array_merge(parent::getOptions(), $shopperGroups); + // Merge any additional options in the XML definition. + $shopperGroups = array_merge(parent::getOptions(), $shopperGroups); - return $shopperGroups; - } + return $shopperGroups; + } } diff --git a/libraries/redshop/form/fields/stockroomlist.php b/libraries/redshop/form/fields/stockroomlist.php index 23e743a18ec..8cbd24b5096 100644 --- a/libraries/redshop/form/fields/stockroomlist.php +++ b/libraries/redshop/form/fields/stockroomlist.php @@ -23,63 +23,56 @@ */ class JFormFieldStockroomlist extends JFormFieldList { - /** - * Element name - * - * @access protected - * @var string - */ - protected $type = 'stockroomlist'; + /** + * A static cache. + * + * @var array|null + */ + protected static $cache = null; + /** + * Element name + * + * @access protected + * @var string + */ + protected $type = 'stockroomlist'; - /** - * A static cache. - * - * @var array|null - */ - protected static $cache = null; + /** + * Method to get the field options. + * + * @return array The field option objects. + */ + protected function getOptions() + { + $options = array(); - /** - * Method to get the field options. - * - * @return array The field option objects. - */ - protected function getOptions() - { - $options = array(); + if (!$this->multiple) { + $options[] = JHTML::_('select.option', '', JText::_('COM_REDSHOP_SELECT_STOCKROOM'), 'value', 'text'); + } - if (!$this->multiple) - { - $options[] = JHTML::_('select.option', '', JText::_('COM_REDSHOP_SELECT_STOCKROOM'), 'value', 'text'); - } + if (!self::$cache) { + // Get the Stockroom. + self::$cache = RedshopHelperStockroom::getStockroom(); + } - if (!self::$cache) - { - // Get the Stockroom. - self::$cache = RedshopHelperStockroom::getStockroom(); - } + // Build the field options. + if (!empty(self::$cache)) { + if ($this->multiple) { + $options[] = JHtml::_('select.optgroup', JText::_('COM_REDSHOP_SELECT_STOCKROOM')); + } - // Build the field options. - if (!empty(self::$cache)) - { - if ($this->multiple) - { - $options[] = JHtml::_('select.optgroup', JText::_('COM_REDSHOP_SELECT_STOCKROOM')); - } + foreach (self::$cache as $item) { + $options[] = JHtml::_('select.option', $item->stockroom_id, $item->stockroom_name, 'value', 'text'); + } - foreach (self::$cache as $item) - { - $options[] = JHtml::_('select.option', $item->stockroom_id, $item->stockroom_name, 'value', 'text'); - } + if ($this->multiple) { + $options[] = JHtml::_('select.optgroup', JText::_('COM_REDSHOP_SELECT_STOCKROOM')); + } + } - if ($this->multiple) - { - $options[] = JHtml::_('select.optgroup', JText::_('COM_REDSHOP_SELECT_STOCKROOM')); - } - } + // Merge any additional options in the XML definition. + $options = array_merge(parent::getOptions(), $options); - // Merge any additional options in the XML definition. - $options = array_merge(parent::getOptions(), $options); - - return $options; - } + return $options; + } } diff --git a/libraries/redshop/form/fields/template.php b/libraries/redshop/form/fields/template.php index 02cdf36d2e8..e02f0abc6da 100644 --- a/libraries/redshop/form/fields/template.php +++ b/libraries/redshop/form/fields/template.php @@ -20,36 +20,34 @@ */ class JFormFieldTemplate extends JFormFieldList { - /** - * Element name - * - * @access protected - * @var string - */ - public $type = 'Template'; + /** + * Element name + * + * @access protected + * @var string + */ + public $type = 'Template'; - protected function getOptions() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('id')) - ->select($db->qn('name')) - ->from($db->qn('#__redshop_template')) - ->where($db->qn('published') . ' = 1') - ->where($db->qn('section') . ' = ' . $db->q('category')); + protected function getOptions() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('id')) + ->select($db->qn('name')) + ->from($db->qn('#__redshop_template')) + ->where($db->qn('published') . ' = 1') + ->where($db->qn('section') . ' = ' . $db->q('category')); - $items = $db->setQuery($query)->loadObjectList(); - $options = array(); + $items = $db->setQuery($query)->loadObjectList(); + $options = array(); - if (count($items) > 0) - { - foreach ($items as $item) - { - $option = JHTML::_('select.option', $item->id, $item->name); - $options[] = $option; - } - } + if (count($items) > 0) { + foreach ($items as $item) { + $option = JHTML::_('select.option', $item->id, $item->name); + $options[] = $option; + } + } - return array_merge(parent::getOptions(), $options); - } + return array_merge(parent::getOptions(), $options); + } } diff --git a/libraries/redshop/form/fields/templatecompare.php b/libraries/redshop/form/fields/templatecompare.php index 8946b06152b..700d6dd5230 100644 --- a/libraries/redshop/form/fields/templatecompare.php +++ b/libraries/redshop/form/fields/templatecompare.php @@ -20,49 +20,55 @@ */ class JFormFieldTemplatecompare extends JFormFieldList { - /** - * Element name - * - * @access protected - * @var string - */ - public $type = 'Templatecompare'; + /** + * Element name + * + * @access protected + * @var string + */ + public $type = 'Templatecompare'; - protected function getInput() - { - $db = JFactory::getDBO(); - $query = $db->getQuery(true) - ->select($db->qn('id')) - ->select($db->qn('name')) - ->from($db->qn('#__redshop_template')) - ->where($db->qn('published') . ' = 1') - ->where($db->qn('section') . ' = ' . $db->q('compare_product')); + protected function getInput() + { + $db = JFactory::getDBO(); + $query = $db->getQuery(true) + ->select($db->qn('id')) + ->select($db->qn('name')) + ->from($db->qn('#__redshop_template')) + ->where($db->qn('published') . ' = 1') + ->where($db->qn('section') . ' = ' . $db->q('compare_product')); - $items = $db->setQuery($query)->loadObjectList(); - $options = array(); + $items = $db->setQuery($query)->loadObjectList(); + $options = array(); - if (count($items) > 0) - { - foreach ($items as $item) - { - $option = JHTML::_('select.option', $item->id, $item->name); - $options[] = $option; - } - } + if (count($items) > 0) { + foreach ($items as $item) { + $option = JHTML::_('select.option', $item->id, $item->name); + $options[] = $option; + } + } - $options = array_merge(parent::getOptions(), $options); + $options = array_merge(parent::getOptions(), $options); - $attr = ''; + $attr = ''; - // Initialize some field attributes. - $attr .= $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; - $attr .= $this->element['size'] ? ' size="' . (int) $this->element['size'] . '"' : ''; - $attr .= $this->element['multiple'] ? ' multiple' : ''; + // Initialize some field attributes. + $attr .= $this->element['class'] ? ' class="' . (string)$this->element['class'] . '"' : ''; + $attr .= $this->element['size'] ? ' size="' . (int)$this->element['size'] . '"' : ''; + $attr .= $this->element['multiple'] ? ' multiple' : ''; - // Initialize JavaScript field attributes. - $attr .= $this->element['onchange'] ? ' onchange="' . (string) $this->element['onchange'] . '"' : ''; + // Initialize JavaScript field attributes. + $attr .= $this->element['onchange'] ? ' onchange="' . (string)$this->element['onchange'] . '"' : ''; - return JHTML::_('select.genericlist', $options, $this->name, trim($attr), 'value', 'text', $this->value, $this->id); - - } + return JHTML::_( + 'select.genericlist', + $options, + $this->name, + trim($attr), + 'value', + 'text', + $this->value, + $this->id + ); + } } diff --git a/libraries/redshop/form/fields/timestamp.php b/libraries/redshop/form/fields/timestamp.php index b4cffb5d6b5..b2e43934e01 100644 --- a/libraries/redshop/form/fields/timestamp.php +++ b/libraries/redshop/form/fields/timestamp.php @@ -18,42 +18,41 @@ */ class JFormFieldTimestamp extends JFormField { - /** - * Element name - * - * @var string - */ - protected $type = 'timestamp'; + /** + * Element name + * + * @var string + */ + protected $type = 'timestamp'; - /** - * Method to get the field input markup. - * - * @return string The field input markup. - */ - protected function getInput() - { - return ''; - } + /** + * Method to attach a JForm object to the field. + * + * @param SimpleXMLElement $element The SimpleXMLElement object representing the tag for the form field object. + * @param mixed $value The form field value to validate. + * @param string $group The field name group control value. This acts as as an array container for the field. + * For example if the field has name="foo" and the group value is set to "bar" then the + * full field name would end up being "bar[foo]". + * + * @return boolean True on success. + */ + public function setup(SimpleXMLElement $element, $value, $group = null) + { + if ($return = parent::setup($element, $value, $group)) { + $this->hidden = true; + } - /** - * Method to attach a JForm object to the field. - * - * @param SimpleXMLElement $element The SimpleXMLElement object representing the tag for the form field object. - * @param mixed $value The form field value to validate. - * @param string $group The field name group control value. This acts as as an array container for the field. - * For example if the field has name="foo" and the group value is set to "bar" then the - * full field name would end up being "bar[foo]". - * - * @return boolean True on success. - */ - public function setup(SimpleXMLElement $element, $value, $group = null) - { - if ($return = parent::setup($element, $value, $group)) - { - $this->hidden = true; - } + return $return; + } - return $return; - } + /** + * Method to get the field input markup. + * + * @return string The field input markup. + */ + protected function getInput() + { + return ''; + } } diff --git a/libraries/redshop/helper/access.php b/libraries/redshop/helper/access.php index b41f3d8c73b..7375f27186b 100644 --- a/libraries/redshop/helper/access.php +++ b/libraries/redshop/helper/access.php @@ -18,181 +18,169 @@ */ class RedshopHelperAccess { - /** - * @var array - * - * @since 2.0.3 - */ - protected static $portalCategories = array(); - - /** - * Check permission for Products shopper group can access or can't access - * - * @param int $pid Product id that need to be checked - * - * @return boolean - * - * @since 2.0.3 - * @throws Exception - */ - public static function checkPortalProductPermission($pid = 0) - { - if (!$pid) - { - return false; - } - - $product = RedshopProduct::getInstance($pid); - - if (empty($product) || empty($product->categories)) - { - return false; - } - - foreach ($product->categories as $cid) - { - $checkPermission = self::checkPortalCategoryPermission($cid); - - if (!$checkPermission) - { - return false; - } - } - - return true; - } - - /** - * Check permission for Categories shopper group can access or can't access - * - * @param int $cid Category id that need to be checked. - * - * @return boolean - * - * @since 2.0.3 - */ - public static function checkPortalCategoryPermission($cid = 0) - { - if (array_key_exists($cid, static::$portalCategories)) - { - return true; - } - - $shopperGroupId = RedshopHelperUser::getShopperGroup(JFactory::getUser()->id); - $shopperGroupData = Redshop\Helper\ShopperGroup::generateList($shopperGroupId); - - if (!empty($shopperGroupData)) - { - if (isset($shopperGroupData[0]) && $shopperGroupData[0]->shopper_group_categories) - { - $shopperCategories = explode(',', $shopperGroupData[0]->shopper_group_categories); - - if (array_search((int) $cid, $shopperCategories) !== false) - { - static::$portalCategories = $shopperCategories; - - return true; - } - } - } - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('shopper_group_id')) - ->from($db->qn('#__redshop_shopper_group')) - ->where('FIND_IN_SET(' . $db->quote($cid) . ', shopper_group_categories)') - ->where($db->qn('shopper_group_id') . ' = ' . (int) $shopperGroupId); - - if (!$db->setQuery($query)->loadResult()) - { - return false; - } - - return true; - } - - /** - * Method for check if user can view this object or not - * - * @param string $target Target name - * @param int $userId ID of user. If null, use current user. - * - * @return boolean True on success. False otherwise. - * - * @since 2.0.6 - */ - public static function canView($target = '', $userId = 0) - { - return self::canDo($target, 'view', $userId); - } - - /** - * Method for check if user can create this object or not - * - * @param string $target Target name - * @param int $userId ID of user. If null, use current user. - * - * @return boolean True on success. False otherwise. - * - * @since 2.0.6 - */ - public static function canCreate($target = '', $userId = 0) - { - return self::canDo($target, 'create', $userId); - } - - /** - * Method for check if user can edit this object or not - * - * @param string $target Target name - * @param int $userId ID of user. If null, use current user. - * - * @return boolean True on success. False otherwise. - * - * @since 2.0.6 - */ - public static function canEdit($target = '', $userId = 0) - { - return self::canDo($target, 'edit', $userId); - } - - /** - * Method for check if user can delete this object or not - * - * @param string $target Target name - * @param int $userId ID of user. If null, use current user. - * - * @return boolean True on success. False otherwise. - * - * @since 2.0.6 - */ - public static function canDelete($target = '', $userId = 0) - { - return self::canDo($target, 'delete', $userId); - } - - /** - * Method for check if user can have permission this object or not - * - * @param string $target Target name - * @param string $task Permission name - * @param int $userId ID of user. If null, use current user. - * - * @return boolean True on success. False otherwise. - * - * @since 2.0.6 - */ - public static function canDo($target = '', $task = '', $userId = 0) - { - if (!$userId) - { - $user = JFactory::getUser(); - } - else - { - $user = JFactory::getUser($userId); - } - - return $user->authorise($target . '.' . $task, 'com_redshop.backend'); - } + /** + * @var array + * + * @since 2.0.3 + */ + protected static $portalCategories = array(); + + /** + * Check permission for Products shopper group can access or can't access + * + * @param int $pid Product id that need to be checked + * + * @return boolean + * + * @throws Exception + * @since 2.0.3 + */ + public static function checkPortalProductPermission($pid = 0) + { + if (!$pid) { + return false; + } + + $product = RedshopProduct::getInstance($pid); + + if (empty($product) || empty($product->categories)) { + return false; + } + + foreach ($product->categories as $cid) { + $checkPermission = self::checkPortalCategoryPermission($cid); + + if (!$checkPermission) { + return false; + } + } + + return true; + } + + /** + * Check permission for Categories shopper group can access or can't access + * + * @param int $cid Category id that need to be checked. + * + * @return boolean + * + * @since 2.0.3 + */ + public static function checkPortalCategoryPermission($cid = 0) + { + if (array_key_exists($cid, static::$portalCategories)) { + return true; + } + + $shopperGroupId = RedshopHelperUser::getShopperGroup(JFactory::getUser()->id); + $shopperGroupData = Redshop\Helper\ShopperGroup::generateList($shopperGroupId); + + if (!empty($shopperGroupData)) { + if (isset($shopperGroupData[0]) && $shopperGroupData[0]->shopper_group_categories) { + $shopperCategories = explode(',', $shopperGroupData[0]->shopper_group_categories); + + if (array_search((int)$cid, $shopperCategories) !== false) { + static::$portalCategories = $shopperCategories; + + return true; + } + } + } + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('shopper_group_id')) + ->from($db->qn('#__redshop_shopper_group')) + ->where('FIND_IN_SET(' . $db->quote($cid) . ', shopper_group_categories)') + ->where($db->qn('shopper_group_id') . ' = ' . (int)$shopperGroupId); + + if (!$db->setQuery($query)->loadResult()) { + return false; + } + + return true; + } + + /** + * Method for check if user can view this object or not + * + * @param string $target Target name + * @param int $userId ID of user. If null, use current user. + * + * @return boolean True on success. False otherwise. + * + * @since 2.0.6 + */ + public static function canView($target = '', $userId = 0) + { + return self::canDo($target, 'view', $userId); + } + + /** + * Method for check if user can have permission this object or not + * + * @param string $target Target name + * @param string $task Permission name + * @param int $userId ID of user. If null, use current user. + * + * @return boolean True on success. False otherwise. + * + * @since 2.0.6 + */ + public static function canDo($target = '', $task = '', $userId = 0) + { + if (!$userId) { + $user = JFactory::getUser(); + } else { + $user = JFactory::getUser($userId); + } + + return $user->authorise($target . '.' . $task, 'com_redshop.backend'); + } + + /** + * Method for check if user can create this object or not + * + * @param string $target Target name + * @param int $userId ID of user. If null, use current user. + * + * @return boolean True on success. False otherwise. + * + * @since 2.0.6 + */ + public static function canCreate($target = '', $userId = 0) + { + return self::canDo($target, 'create', $userId); + } + + /** + * Method for check if user can edit this object or not + * + * @param string $target Target name + * @param int $userId ID of user. If null, use current user. + * + * @return boolean True on success. False otherwise. + * + * @since 2.0.6 + */ + public static function canEdit($target = '', $userId = 0) + { + return self::canDo($target, 'edit', $userId); + } + + /** + * Method for check if user can delete this object or not + * + * @param string $target Target name + * @param int $userId ID of user. If null, use current user. + * + * @return boolean True on success. False otherwise. + * + * @since 2.0.6 + */ + public static function canDelete($target = '', $userId = 0) + { + return self::canDo($target, 'delete', $userId); + } } diff --git a/libraries/redshop/helper/accessory.php b/libraries/redshop/helper/accessory.php index 3f7a522b5a1..977df4c357c 100644 --- a/libraries/redshop/helper/accessory.php +++ b/libraries/redshop/helper/accessory.php @@ -18,173 +18,168 @@ */ class RedshopHelperAccessory { - /** - * @var array - */ - protected static $accessories = array(); - - /** - * Prepare and collect accessory as a product information from cart. - * - * @param array $data Information array from cart - * - * @return object Accessory as product information - */ - public static function getAccessoryAsProduct($data) - { - $collection = new stdClass; - - if (!Redshop::getConfig()->get('ACCESSORY_AS_PRODUCT_IN_CART_ENABLE')) - { - return $collection; - } - - // Check the accessory as product ids are not null - if (!empty($data[0])) - { - $collection->accessory_data = explode("@@", $data[0]); - $collection->acc_quantity_data = explode("@@", $data[1]); - $collection->acc_attribute_data = explode("@@", $data[2]); - $collection->acc_property_data = explode("@@", $data[3]); - $collection->acc_subproperty_data = explode("@@", $data[4]); - - $info = array(); - - foreach ($collection->accessory_data as $key => $accessoryId) - { - $accessoryDetail = self::getProductAccessories($accessoryId); - $object = $accessoryDetail[0]; - $object->quantity = $collection->acc_quantity_data[$key]; - $object->attributes = $collection->acc_attribute_data[$key]; - $object->properties = $collection->acc_property_data[$key]; - $object->subproperties = $collection->acc_subproperty_data[$key]; - - $info[$object->child_product_id] = $object; - } - - $collection->accessory = $info; - } - - return $collection; - } - - /** - * Method for get Product Accessories. - * - * @param string $accessoryId ID of accessory. - * @param string $productId ID of product. - * @param int $childProductId ID of child product. - * @param int $categoryId ID of category. - * - * @return array List of accessories. - * - * @since 2.0.3 - */ - public static function getProductAccessories($accessoryId = '', $productId = '', $childProductId = 0, $categoryId = 0) - { - $key = $accessoryId . '_' . $productId . '_' . $childProductId . '_' . $categoryId; - - if (!array_key_exists($key, static::$accessories)) - { - $db = JFactory::getDbo(); - - $orderBy = " ORDER BY a.child_product_id ASC"; - - if (Redshop::getConfig()->get('DEFAULT_ACCESSORY_ORDERING_METHOD')) - { - $orderBy = " ORDER BY " . Redshop::getConfig()->get('DEFAULT_ACCESSORY_ORDERING_METHOD'); - } - - $and = ""; - $groupBy = ""; - - if ($accessoryId != 0) - { - // Sanitize ids - $accessoryId = explode(',', $accessoryId); - $accessoryId = ArrayHelper::toInteger($accessoryId); - - $and .= " AND a.accessory_id IN (" . implode(',', $accessoryId) . ")"; - } - - if ($productId != 0) - { - // Sanitize ids - $productId = explode(',', $productId); - $productId = ArrayHelper::toInteger($productId); - - $and .= " AND a.product_id IN (" . implode(',', $productId) . ")"; - } - - if ($childProductId != 0) - { - $and .= " AND a.child_product_id = " . (int) $childProductId; - } - - if ($categoryId != 0) - { - $and .= " AND a.category_id = " . (int) $categoryId; - $groupBy = " GROUP BY a.child_product_id"; - } - - $switchQuery = ", CASE a.oprand " - . "WHEN '+' THEN IF ( (p.product_on_sale>0 && ((p.discount_enddate='' AND p.discount_stratdate='') OR ( p.discount_enddate>='" - . time() . "' AND p.discount_stratdate<='" . time() . "'))), p.discount_price, p.product_price ) + accessory_price " - . "WHEN '-' THEN IF ( (p.product_on_sale>0 && ((p.discount_enddate='' AND p.discount_stratdate='') OR ( p.discount_enddate>='" - . time() . "' AND p.discount_stratdate<='" . time() . "'))), p.discount_price, p.product_price ) - accessory_price " - . "WHEN '=' THEN accessory_price " - . "END AS newaccessory_price "; - - $priceQuery = "IF ( (p.product_on_sale>0 && ((p.discount_enddate='' AND p.discount_stratdate='') OR ( p.discount_enddate>='" - . time() . "' AND p.discount_stratdate<='" . time() . "'))), p.discount_price, p.product_price ) AS accessory_main_price "; - - $query = "SELECT a.*,p.product_number, p.product_name, " . $priceQuery - . ", p.product_s_desc, p.product_full_image, p.product_on_sale " - . $switchQuery - . "FROM " . $db->qn('#__redshop_product_accessory') . " AS a " - . "LEFT JOIN " . $db->qn('#__redshop_product') . " AS p ON p.product_id = a.child_product_id " - . "WHERE p.published = 1 " - . $and . $groupBy - . $orderBy; - - static::$accessories[$key] = $db->setQuery($query)->loadObjectList(); - } - - return static::$accessories[$key]; - } - - /** - * Check if Accessory is existed - * - * @param integer $productId Product ID - * @param integer $accessoryId Accessory ID - * - * @return integer - * - * @since 2.0.0.3 - */ - public static function checkAccessoryExists($productId, $accessoryId) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->qn(array('pa.accessory_id', 'pa.product_id'))) - ->from($db->qn('#__redshop_product_accessory', 'pa')) - ->where($db->qn('pa.product_id') . ' = ' . (int) $productId) - ->where($db->qn('pa.child_product_id') . ' = ' . (int) $accessoryId); - - $db->setQuery($query); - $result = $db->loadObjectList(); - - if (count($result) > 0) - { - $return = $result[0]->accessory_id; - } - else - { - $return = 0; - } - - return $return; - } + /** + * @var array + */ + protected static $accessories = array(); + + /** + * Prepare and collect accessory as a product information from cart. + * + * @param array $data Information array from cart + * + * @return object Accessory as product information + */ + public static function getAccessoryAsProduct($data) + { + $collection = new stdClass; + + if (!Redshop::getConfig()->get('ACCESSORY_AS_PRODUCT_IN_CART_ENABLE')) { + return $collection; + } + + // Check the accessory as product ids are not null + if (!empty($data[0])) { + $collection->accessory_data = explode("@@", $data[0]); + $collection->acc_quantity_data = explode("@@", $data[1]); + $collection->acc_attribute_data = explode("@@", $data[2]); + $collection->acc_property_data = explode("@@", $data[3]); + $collection->acc_subproperty_data = explode("@@", $data[4]); + + $info = array(); + + foreach ($collection->accessory_data as $key => $accessoryId) { + $accessoryDetail = self::getProductAccessories($accessoryId); + $object = $accessoryDetail[0]; + $object->quantity = $collection->acc_quantity_data[$key]; + $object->attributes = $collection->acc_attribute_data[$key]; + $object->properties = $collection->acc_property_data[$key]; + $object->subproperties = $collection->acc_subproperty_data[$key]; + + $info[$object->child_product_id] = $object; + } + + $collection->accessory = $info; + } + + return $collection; + } + + /** + * Method for get Product Accessories. + * + * @param string $accessoryId ID of accessory. + * @param string $productId ID of product. + * @param int $childProductId ID of child product. + * @param int $categoryId ID of category. + * + * @return array List of accessories. + * + * @since 2.0.3 + */ + public static function getProductAccessories( + $accessoryId = '', + $productId = '', + $childProductId = 0, + $categoryId = 0 + ) { + $key = $accessoryId . '_' . $productId . '_' . $childProductId . '_' . $categoryId; + + if (!array_key_exists($key, static::$accessories)) { + $db = JFactory::getDbo(); + + $orderBy = " ORDER BY a.child_product_id ASC"; + + if (Redshop::getConfig()->get('DEFAULT_ACCESSORY_ORDERING_METHOD')) { + $orderBy = " ORDER BY " . Redshop::getConfig()->get('DEFAULT_ACCESSORY_ORDERING_METHOD'); + } + + $and = ""; + $groupBy = ""; + + if ($accessoryId != 0) { + // Sanitize ids + $accessoryId = explode(',', $accessoryId); + $accessoryId = ArrayHelper::toInteger($accessoryId); + + $and .= " AND a.accessory_id IN (" . implode(',', $accessoryId) . ")"; + } + + if ($productId != 0) { + // Sanitize ids + $productId = explode(',', $productId); + $productId = ArrayHelper::toInteger($productId); + + $and .= " AND a.product_id IN (" . implode(',', $productId) . ")"; + } + + if ($childProductId != 0) { + $and .= " AND a.child_product_id = " . (int)$childProductId; + } + + if ($categoryId != 0) { + $and .= " AND a.category_id = " . (int)$categoryId; + $groupBy = " GROUP BY a.child_product_id"; + } + + $switchQuery = ", CASE a.oprand " + . "WHEN '+' THEN IF ( (p.product_on_sale>0 && ((p.discount_enddate='' AND p.discount_stratdate='') OR ( p.discount_enddate>='" + . time() . "' AND p.discount_stratdate<='" . time( + ) . "'))), p.discount_price, p.product_price ) + accessory_price " + . "WHEN '-' THEN IF ( (p.product_on_sale>0 && ((p.discount_enddate='' AND p.discount_stratdate='') OR ( p.discount_enddate>='" + . time() . "' AND p.discount_stratdate<='" . time( + ) . "'))), p.discount_price, p.product_price ) - accessory_price " + . "WHEN '=' THEN accessory_price " + . "END AS newaccessory_price "; + + $priceQuery = "IF ( (p.product_on_sale>0 && ((p.discount_enddate='' AND p.discount_stratdate='') OR ( p.discount_enddate>='" + . time() . "' AND p.discount_stratdate<='" . time( + ) . "'))), p.discount_price, p.product_price ) AS accessory_main_price "; + + $query = "SELECT a.*,p.product_number, p.product_name, " . $priceQuery + . ", p.product_s_desc, p.product_full_image, p.product_on_sale " + . $switchQuery + . "FROM " . $db->qn('#__redshop_product_accessory') . " AS a " + . "LEFT JOIN " . $db->qn('#__redshop_product') . " AS p ON p.product_id = a.child_product_id " + . "WHERE p.published = 1 " + . $and . $groupBy + . $orderBy; + + static::$accessories[$key] = $db->setQuery($query)->loadObjectList(); + } + + return static::$accessories[$key]; + } + + /** + * Check if Accessory is existed + * + * @param integer $productId Product ID + * @param integer $accessoryId Accessory ID + * + * @return integer + * + * @since 2.0.0.3 + */ + public static function checkAccessoryExists($productId, $accessoryId) + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->qn(array('pa.accessory_id', 'pa.product_id'))) + ->from($db->qn('#__redshop_product_accessory', 'pa')) + ->where($db->qn('pa.product_id') . ' = ' . (int)$productId) + ->where($db->qn('pa.child_product_id') . ' = ' . (int)$accessoryId); + + $db->setQuery($query); + $result = $db->loadObjectList(); + + if (count($result) > 0) { + $return = $result[0]->accessory_id; + } else { + $return = 0; + } + + return $return; + } } diff --git a/libraries/redshop/helper/ajax.php b/libraries/redshop/helper/ajax.php index e14d0f66921..8c97edc4343 100644 --- a/libraries/redshop/helper/ajax.php +++ b/libraries/redshop/helper/ajax.php @@ -18,31 +18,31 @@ */ abstract class RedshopHelperAjax { - /** - * Check if we have received an AJAX request for security reasons - * - * @deprecated Use \Redshop\Helper\Ajax::isAjaxRequest() - * - * @return boolean - */ - public static function isAjaxRequest() - { - return \Redshop\Helper\Ajax::isAjaxRequest(); - } + /** + * Check if we have received an AJAX request for security reasons + * + * @return boolean + * @deprecated Use \Redshop\Helper\Ajax::isAjaxRequest() + * + */ + public static function isAjaxRequest() + { + return \Redshop\Helper\Ajax::isAjaxRequest(); + } - /** - * Verify that an AJAX request has been received - * - * @param string $method Method to validate the ajax request - * - * @deprecated Use \Redshop\Helper\Ajax::validateAjaxRequest() - * - * @return void - * - * @throws Exception - */ - public static function validateAjaxRequest($method = 'post') - { - \Redshop\Helper\Ajax::validateAjaxRequest($method); - } + /** + * Verify that an AJAX request has been received + * + * @param string $method Method to validate the ajax request + * + * @return void + * + * @throws Exception + * @deprecated Use \Redshop\Helper\Ajax::validateAjaxRequest() + * + */ + public static function validateAjaxRequest($method = 'post') + { + \Redshop\Helper\Ajax::validateAjaxRequest($method); + } } diff --git a/libraries/redshop/helper/attribute.php b/libraries/redshop/helper/attribute.php index 0f0b9a921ed..3c3b482aa31 100644 --- a/libraries/redshop/helper/attribute.php +++ b/libraries/redshop/helper/attribute.php @@ -18,311 +18,345 @@ */ class RedshopHelperAttribute { - /** - * Method for replace attribute data in template. - * - * @param int $productId Product ID - * @param int $accessoryId Accessory ID - * @param int $relatedProductId Related product ID - * @param array $attributes List of attribute data. - * @param string $templateContent HTML content of template. - * @param object $attributeTemplate List of attribute templates. - * @param bool $isChild Is child? - * @param array $selectedAttributes Preselected attribute list. - * @param int $displayIndCart Display in cart? - * @param bool $onlySelected True for just render selected / pre-selected attribute. False as normal. - * - * @return string HTML content with replaced data. - * - * @since 2.0.3 - * - * @deprecated use RedshopTagsReplacer with section is attributes - * - * @throws Exception - */ - public static function replaceAttributeData($productId = 0, $accessoryId = 0, $relatedProductId = 0, $attributes = array(), $templateContent = '', - $attributeTemplate = null, $isChild = false, $selectedAttributes = array(), $displayIndCart = 1, $onlySelected = false) - { - return RedshopTagsReplacer::_( - 'attributes', - $templateContent, - array( - 'productId' => $productId, - 'accessoryId' => $accessoryId, - 'relatedProductId' => $relatedProductId, - 'attributes' => $attributes, - 'attributeTemplate' => $attributeTemplate, - 'isChild' => $isChild, - 'selectedAttributes' => $selectedAttributes, - 'displayIndCart' => $displayIndCart, - 'onlySelected' => $onlySelected, - ) - ); - } - - /** - * Method for replace attribute data with allow add to cart in template. - * - * @param int $productId Product ID - * @param int $accessoryId Accessory ID - * @param int $relatedProductId Related product ID - * @param array $attributes List of attribute data. - * @param string $templateContent HTML content of template. - * @param object $attributeTemplate List of attribute templates. - * @param bool $isChild Is child? - * @param bool $onlySelected True for just render selected / pre-selected attribute. False as normal. - * - * @return string HTML content with replaced data. - * - * @since 2.0.3 - */ - public static function replaceAttributeWithCartData($productId = 0, $accessoryId = 0, $relatedProductId = 0, $attributes = array(), - $templateContent = '', $attributeTemplate = null, $isChild = false, $onlySelected = false) - { - $user_id = 0; - - if (empty($attributeTemplate)) - { - return $templateContent; - } - - if ($isChild || !count($attributes)) - { - return str_replace("{attributewithcart_template:$attributeTemplate->name}", "", $templateContent); - } - - $layout = JFactory::getApplication()->input->getCmd('layout', ''); - $prePrefix = ""; - $isAjax = false; - - if ($layout == 'viewajaxdetail') - { - $prePrefix = "ajax_"; - $isAjax = true; - } - - if ($accessoryId != 0) - { - $prefix = $prePrefix . "acc_"; - } - elseif ($relatedProductId != 0) - { - $prefix = $prePrefix . "rel_"; - } - else - { - $prefix = $prePrefix . "prd_"; - } - - if ($relatedProductId != 0) - { - $productId = $relatedProductId; - } - - $product = \Redshop\Product\Product::getProductById($productId); - $productTemplate = RedshopHelperTemplate::getTemplate("product", $product->product_template); - $productTemplate = $productTemplate[0]; - - if (strpos($productTemplate->template_desc, "{more_images_3}") !== false) - { - $mph_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_HEIGHT_3'); - $mpw_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_3'); - } - elseif (strpos($productTemplate->template_desc, "{more_images_2}") !== false) - { - $mph_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_HEIGHT_2'); - $mpw_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_2'); - } - elseif (strpos($productTemplate->template_desc, "{more_images_1}") !== false) - { - $mph_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_HEIGHT'); - $mpw_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE'); - } - else - { - $mph_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_HEIGHT'); - $mpw_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE'); - } - - $cartTemplate = array(); - $attributeTable = ""; - - foreach ($attributes as $attribute) - { - $attributeTable .= $attributeTemplate->template_desc; - - $attributeTable = str_replace("{property_image_lbl}", JText::_('COM_REDSHOP_PROPERTY_IMAGE_LBL'), $attributeTable); - $attributeTable = str_replace("{virtual_number_lbl}", JText::_('COM_REDSHOP_VIRTUAL_NUMBER_LBL'), $attributeTable); - $attributeTable = str_replace("{property_name_lbl}", JText::_('COM_REDSHOP_PROPERTY_NAME_LBL'), $attributeTable); - $attributeTable = str_replace("{property_price_lbl}", JText::_('COM_REDSHOP_PROPERTY_PRICE_LBL'), $attributeTable); - $attributeTable = str_replace("{property_stock_lbl}", JText::_('COM_REDSHOP_PROPERTY_STOCK_LBL'), $attributeTable); - $attributeTable = str_replace("{add_to_cart_lbl}", JText::_('COM_REDSHOP_ADD_TO_CART_LBL'), $attributeTable); - - if (empty($attribute->properties)) - { - $properties = RedshopHelperProduct_Attribute::getAttributeProperties(0, $attribute->attribute_id); - } - else - { - $properties = $attribute->properties; - } - - if (empty($attribute->text) || empty($properties) - || strpos($attributeTable, "{property_start}") === false || strpos($attributeTable, "{property_start}") === false) - { - continue; - } - - $start = explode("{property_start}", $attributeTable); - $end = explode("{property_end}", $start[1]); - $propertyTemplate = $end[0]; - - $commonId = $prefix . $productId . '_' . $accessoryId . '_' . $attribute->value; - $propertyId = 'property_id_' . $commonId; - - $propertyData = ""; - - foreach ($properties as $property) - { - // Skip if "onlySelected" is true and this property not set as selected. - if ($onlySelected && !$property->setdefault_selected) - { - continue; - } - - $propertyData .= $propertyTemplate; - - $priceWithVat = 0; - $priceWithoutVat = 0; - $propertyStock = RedshopHelperStockroom::getStockAmountWithReserve($property->value, "property"); - $preOrderPropertyStock = RedshopHelperStockroom::getPreorderStockAmountwithReserve($property->value, "property"); - - $propertyData = str_replace("{property_name}", urldecode($property->property_name), $propertyData); - $propertyData = str_replace("{virtual_number}", $property->property_number, $propertyData); - - // Replace {property_stock} - if (strpos($propertyData, '{property_stock}') !== false) - { - $displayStock = ($propertyStock) ? JText::_('COM_REDSHOP_IN_STOCK') : JText::_('COM_REDSHOP_NOT_IN_STOCK'); - $propertyData = str_replace("{property_stock}", $displayStock, $propertyData); - } - - // Replace {property_image} - if (strpos($propertyData, '{property_image}') !== false) - { - $propertyImage = ""; - - if ($property->property_image - && JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . "product_attributes/" . $property->property_image)) - { - $thumbUrl = RedshopHelperMedia::getImagePath( - $property->property_image, - '', - 'thumb', - 'product_attributes', - $mpw_thumb, - $mph_thumb, - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') - ); - $propertyImage = ""; - } - - $propertyData = str_replace("{property_image}", $propertyImage, $propertyData); - } - - if (strpos($propertyData, '{property_oprand}') !== false || strpos($propertyData, '{property_price}') !== false) - { - $price = ''; - $opRand = ''; - - if ($property->property_price > 0) - { - $prices = RedshopHelperProduct_Attribute::getPropertyPrice($property->value, 1, 'property'); - - if (count($prices) > 0) - { - $property->property_price = $prices->product_price; - } - - $priceWithoutVat = $property->property_price; - - if (\Redshop\Template\Helper::isApplyAttributeVat($propertyData)) - { - $priceWithVat = RedshopHelperProduct::getProducttax($productId, $property->property_price, $user_id); - } - - $priceWithVat += $property->property_price; - - if (Redshop::getConfig()->get('SHOW_PRICE') - && (!Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') - || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') && Redshop::getConfig()->get('SHOW_QUOTATION_PRICE'))) - && !$attribute->hide_attribute_price) - { - $opRand = $property->oprand; - $price = RedshopHelperProductPrice::formattedPrice($priceWithVat); - } - } - - $propertyData = str_replace("{property_oprand}", $opRand, $propertyData); - $propertyData = str_replace("{property_price}", $price, $propertyData); - } - - if (empty($cartTemplate)) - { - $cartTemplate = \Redshop\Template\Helper::getAddToCart($propertyData); - } - - if (null !== $cartTemplate) - { - $propertyData = Redshop\Product\Property::replaceAddToCart( - $productId, $property->value, 0, $propertyId, $propertyStock, - $propertyData, $cartTemplate, $templateContent - ); - } - - $propertyData .= ''; - $propertyData .= ''; - $propertyData .= ''; - - $propertyData .= ''; - $propertyData .= ''; - - $formId = 'addtocart_' . $propertyId . '_' . $property->value; - - $propertyData = RedshopHelperWishlist::replaceWishlistTag($productId, $propertyData, $formId); - } - - $attributeTitle = urldecode($attribute->text); - - if ($attribute->attribute_required > 0) - { - $pos = Redshop::getConfig()->get('ASTERISK_POSITION') > 0 ? urldecode($attribute->text) - . " * " : "* " - . urldecode($attribute->text); - $attributeTitle = $pos; - } - - $attributeTable = str_replace("{attribute_title}", $attributeTitle, $attributeTable); - $attributeTable = str_replace("{property_start}", "", $attributeTable); - $attributeTable = str_replace("{property_end}", "", $attributeTable); - $attributeTable = str_replace($propertyTemplate, $propertyData, $attributeTable); - } - - if ($attributeTable != "") - { - $cart_template = \Redshop\Template\Helper::getAddToCart($templateContent); - - if (null !== $cart_template) - { - $templateContent = str_replace("{form_addtocart:$cart_template->name}", "", $templateContent); - } - } - - return str_replace("{attributewithcart_template:$attributeTemplate->name}", $attributeTable, $templateContent); - } + /** + * Method for replace attribute data in template. + * + * @param int $productId Product ID + * @param int $accessoryId Accessory ID + * @param int $relatedProductId Related product ID + * @param array $attributes List of attribute data. + * @param string $templateContent HTML content of template. + * @param object $attributeTemplate List of attribute templates. + * @param bool $isChild Is child? + * @param array $selectedAttributes Preselected attribute list. + * @param int $displayIndCart Display in cart? + * @param bool $onlySelected True for just render selected / pre-selected attribute. False as normal. + * + * @return string HTML content with replaced data. + * + * @throws Exception + * @since 2.0.3 + * + * @deprecated use RedshopTagsReplacer with section is attributes + * + */ + public static function replaceAttributeData( + $productId = 0, + $accessoryId = 0, + $relatedProductId = 0, + $attributes = array(), + $templateContent = '', + $attributeTemplate = null, + $isChild = false, + $selectedAttributes = array(), + $displayIndCart = 1, + $onlySelected = false + ) { + return RedshopTagsReplacer::_( + 'attributes', + $templateContent, + array( + 'productId' => $productId, + 'accessoryId' => $accessoryId, + 'relatedProductId' => $relatedProductId, + 'attributes' => $attributes, + 'attributeTemplate' => $attributeTemplate, + 'isChild' => $isChild, + 'selectedAttributes' => $selectedAttributes, + 'displayIndCart' => $displayIndCart, + 'onlySelected' => $onlySelected, + ) + ); + } + + /** + * Method for replace attribute data with allow add to cart in template. + * + * @param int $productId Product ID + * @param int $accessoryId Accessory ID + * @param int $relatedProductId Related product ID + * @param array $attributes List of attribute data. + * @param string $templateContent HTML content of template. + * @param object $attributeTemplate List of attribute templates. + * @param bool $isChild Is child? + * @param bool $onlySelected True for just render selected / pre-selected attribute. False as normal. + * + * @return string HTML content with replaced data. + * + * @since 2.0.3 + */ + public static function replaceAttributeWithCartData( + $productId = 0, + $accessoryId = 0, + $relatedProductId = 0, + $attributes = array(), + $templateContent = '', + $attributeTemplate = null, + $isChild = false, + $onlySelected = false + ) { + $user_id = 0; + + if (empty($attributeTemplate)) { + return $templateContent; + } + + if ($isChild || !count($attributes)) { + return str_replace("{attributewithcart_template:$attributeTemplate->name}", "", $templateContent); + } + + $layout = JFactory::getApplication()->input->getCmd('layout', ''); + $prePrefix = ""; + $isAjax = false; + + if ($layout == 'viewajaxdetail') { + $prePrefix = "ajax_"; + $isAjax = true; + } + + if ($accessoryId != 0) { + $prefix = $prePrefix . "acc_"; + } elseif ($relatedProductId != 0) { + $prefix = $prePrefix . "rel_"; + } else { + $prefix = $prePrefix . "prd_"; + } + + if ($relatedProductId != 0) { + $productId = $relatedProductId; + } + + $product = \Redshop\Product\Product::getProductById($productId); + $productTemplate = RedshopHelperTemplate::getTemplate("product", $product->product_template); + $productTemplate = $productTemplate[0]; + + if (strpos($productTemplate->template_desc, "{more_images_3}") !== false) { + $mph_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_HEIGHT_3'); + $mpw_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_3'); + } elseif (strpos($productTemplate->template_desc, "{more_images_2}") !== false) { + $mph_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_HEIGHT_2'); + $mpw_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_2'); + } elseif (strpos($productTemplate->template_desc, "{more_images_1}") !== false) { + $mph_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_HEIGHT'); + $mpw_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE'); + } else { + $mph_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_HEIGHT'); + $mpw_thumb = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE'); + } + + $cartTemplate = array(); + $attributeTable = ""; + + foreach ($attributes as $attribute) { + $attributeTable .= $attributeTemplate->template_desc; + + $attributeTable = str_replace( + "{property_image_lbl}", + JText::_('COM_REDSHOP_PROPERTY_IMAGE_LBL'), + $attributeTable + ); + $attributeTable = str_replace( + "{virtual_number_lbl}", + JText::_('COM_REDSHOP_VIRTUAL_NUMBER_LBL'), + $attributeTable + ); + $attributeTable = str_replace( + "{property_name_lbl}", + JText::_('COM_REDSHOP_PROPERTY_NAME_LBL'), + $attributeTable + ); + $attributeTable = str_replace( + "{property_price_lbl}", + JText::_('COM_REDSHOP_PROPERTY_PRICE_LBL'), + $attributeTable + ); + $attributeTable = str_replace( + "{property_stock_lbl}", + JText::_('COM_REDSHOP_PROPERTY_STOCK_LBL'), + $attributeTable + ); + $attributeTable = str_replace( + "{add_to_cart_lbl}", + JText::_('COM_REDSHOP_ADD_TO_CART_LBL'), + $attributeTable + ); + + if (empty($attribute->properties)) { + $properties = RedshopHelperProduct_Attribute::getAttributeProperties(0, $attribute->attribute_id); + } else { + $properties = $attribute->properties; + } + + if (empty($attribute->text) || empty($properties) + || strpos($attributeTable, "{property_start}") === false || strpos( + $attributeTable, + "{property_start}" + ) === false) { + continue; + } + + $start = explode("{property_start}", $attributeTable); + $end = explode("{property_end}", $start[1]); + $propertyTemplate = $end[0]; + + $commonId = $prefix . $productId . '_' . $accessoryId . '_' . $attribute->value; + $propertyId = 'property_id_' . $commonId; + + $propertyData = ""; + + foreach ($properties as $property) { + // Skip if "onlySelected" is true and this property not set as selected. + if ($onlySelected && !$property->setdefault_selected) { + continue; + } + + $propertyData .= $propertyTemplate; + + $priceWithVat = 0; + $priceWithoutVat = 0; + $propertyStock = RedshopHelperStockroom::getStockAmountWithReserve( + $property->value, + "property" + ); + $preOrderPropertyStock = RedshopHelperStockroom::getPreorderStockAmountwithReserve( + $property->value, + "property" + ); + + $propertyData = str_replace("{property_name}", urldecode($property->property_name), $propertyData); + $propertyData = str_replace("{virtual_number}", $property->property_number, $propertyData); + + // Replace {property_stock} + if (strpos($propertyData, '{property_stock}') !== false) { + $displayStock = ($propertyStock) ? JText::_('COM_REDSHOP_IN_STOCK') : JText::_( + 'COM_REDSHOP_NOT_IN_STOCK' + ); + $propertyData = str_replace("{property_stock}", $displayStock, $propertyData); + } + + // Replace {property_image} + if (strpos($propertyData, '{property_image}') !== false) { + $propertyImage = ""; + + if ($property->property_image + && JFile::exists( + REDSHOP_FRONT_IMAGES_RELPATH . "product_attributes/" . $property->property_image + )) { + $thumbUrl = RedshopHelperMedia::getImagePath( + $property->property_image, + '', + 'thumb', + 'product_attributes', + $mpw_thumb, + $mph_thumb, + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') + ); + $propertyImage = ""; + } + + $propertyData = str_replace("{property_image}", $propertyImage, $propertyData); + } + + if (strpos($propertyData, '{property_oprand}') !== false || strpos( + $propertyData, + '{property_price}' + ) !== false) { + $price = ''; + $opRand = ''; + + if ($property->property_price > 0) { + $prices = RedshopHelperProduct_Attribute::getPropertyPrice($property->value, 1, 'property'); + + if (count($prices) > 0) { + $property->property_price = $prices->product_price; + } + + $priceWithoutVat = $property->property_price; + + if (\Redshop\Template\Helper::isApplyAttributeVat($propertyData)) { + $priceWithVat = RedshopHelperProduct::getProducttax( + $productId, + $property->property_price, + $user_id + ); + } + + $priceWithVat += $property->property_price; + + if (Redshop::getConfig()->get('SHOW_PRICE') + && (!Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') + || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') && Redshop::getConfig()->get( + 'SHOW_QUOTATION_PRICE' + ))) + && !$attribute->hide_attribute_price) { + $opRand = $property->oprand; + $price = RedshopHelperProductPrice::formattedPrice($priceWithVat); + } + } + + $propertyData = str_replace("{property_oprand}", $opRand, $propertyData); + $propertyData = str_replace("{property_price}", $price, $propertyData); + } + + if (empty($cartTemplate)) { + $cartTemplate = \Redshop\Template\Helper::getAddToCart($propertyData); + } + + if (null !== $cartTemplate) { + $propertyData = Redshop\Product\Property::replaceAddToCart( + $productId, + $property->value, + 0, + $propertyId, + $propertyStock, + $propertyData, + $cartTemplate, + $templateContent + ); + } + + $propertyData .= ''; + $propertyData .= ''; + $propertyData .= ''; + + $propertyData .= ''; + $propertyData .= ''; + + $formId = 'addtocart_' . $propertyId . '_' . $property->value; + + $propertyData = RedshopHelperWishlist::replaceWishlistTag($productId, $propertyData, $formId); + } + + $attributeTitle = urldecode($attribute->text); + + if ($attribute->attribute_required > 0) { + $pos = Redshop::getConfig()->get('ASTERISK_POSITION') > 0 ? urldecode($attribute->text) + . " * " : "* " + . urldecode($attribute->text); + $attributeTitle = $pos; + } + + $attributeTable = str_replace("{attribute_title}", $attributeTitle, $attributeTable); + $attributeTable = str_replace("{property_start}", "", $attributeTable); + $attributeTable = str_replace("{property_end}", "", $attributeTable); + $attributeTable = str_replace($propertyTemplate, $propertyData, $attributeTable); + } + + if ($attributeTable != "") { + $cart_template = \Redshop\Template\Helper::getAddToCart($templateContent); + + if (null !== $cart_template) { + $templateContent = str_replace("{form_addtocart:$cart_template->name}", "", $templateContent); + } + } + + return str_replace("{attributewithcart_template:$attributeTemplate->name}", $attributeTable, $templateContent); + } } diff --git a/libraries/redshop/helper/billing.php b/libraries/redshop/helper/billing.php index a94e108dc99..45449de939c 100644 --- a/libraries/redshop/helper/billing.php +++ b/libraries/redshop/helper/billing.php @@ -18,54 +18,56 @@ */ class RedshopHelperBilling { - /** - * Method for render billing layout - * - * @param array $post Available data. - * @param integer $isCompany Is company? - * @param array $lists Lists - * @param integer $showShipping Show shipping? - * @param integer $showNewsletter Show newsletter? - * @param integer $createAccount Is create account? - * - * @return string HTML content layout. - * - * @since 2.1.0 - * - * @throws Exception - */ - public static function render($post = array(), $isCompany = 0, $lists, $showShipping = 0, $showNewsletter = 0, - $createAccount = 1) - { - $billingTemplate = RedshopHelperTemplate::getTemplate("billing_template"); + /** + * Method for render billing layout + * + * @param array $post Available data. + * @param integer $isCompany Is company? + * @param array $lists Lists + * @param integer $showShipping Show shipping? + * @param integer $showNewsletter Show newsletter? + * @param integer $createAccount Is create account? + * + * @return string HTML content layout. + * + * @throws Exception + * @since 2.1.0 + * + */ + public static function render( + $post = array(), + $isCompany = 0, + $lists, + $showShipping = 0, + $showNewsletter = 0, + $createAccount = 1 + ) { + $billingTemplate = RedshopHelperTemplate::getTemplate("billing_template"); - if (!empty($billingTemplate) && !empty($billingTemplate[0]->template_desc) - && strpos($billingTemplate[0]->template_desc, "private_billing_template:") !== false - && strpos($billingTemplate[0]->template_desc, "company_billing_template:") !== false) - { - $templateHtml = $billingTemplate[0]->template_desc; - } - else - { - $templateHtml = RedshopHelperTemplate::getDefaultTemplateContent('billing_template'); - } + if (!empty($billingTemplate) && !empty($billingTemplate[0]->template_desc) + && strpos($billingTemplate[0]->template_desc, "private_billing_template:") !== false + && strpos($billingTemplate[0]->template_desc, "company_billing_template:") !== false) { + $templateHtml = $billingTemplate[0]->template_desc; + } else { + $templateHtml = RedshopHelperTemplate::getDefaultTemplateContent('billing_template'); + } - $templateHtml = RedshopTagsReplacer::_( - 'billingtemplate', - $templateHtml, - array( - 'isCompany' => $isCompany, - 'data' => $post, - 'lists' => $lists, - 'showShipping' => $showShipping, - 'createAccount' => $createAccount, - 'showNewsletter' => $showNewsletter - ) - ); + $templateHtml = RedshopTagsReplacer::_( + 'billingtemplate', + $templateHtml, + array( + 'isCompany' => $isCompany, + 'data' => $post, + 'lists' => $lists, + 'showShipping' => $showShipping, + 'createAccount' => $createAccount, + 'showNewsletter' => $showNewsletter + ) + ); - JPluginHelper::importPlugin('redshop_checkout'); - RedshopHelperUtility::getDispatcher()->trigger('onRenderBillingCheckout', array(&$templateHtml)); + JPluginHelper::importPlugin('redshop_checkout'); + RedshopHelperUtility::getDispatcher()->trigger('onRenderBillingCheckout', array(&$templateHtml)); - return $templateHtml; - } + return $templateHtml; + } } diff --git a/libraries/redshop/helper/billing/tag.php b/libraries/redshop/helper/billing/tag.php index 109522e54dc..206a3128c5e 100644 --- a/libraries/redshop/helper/billing/tag.php +++ b/libraries/redshop/helper/billing/tag.php @@ -16,260 +16,308 @@ */ class RedshopHelperBillingTag { - /** - * Method for replace Billing Address - * - * @param string $content Template content - * @param object $billingAddress Billing data - * @param boolean $sendMail Is in send mail? - * - * @return mixed - * @since 2.0.7 - */ - public static function replaceBillingAddress($content, $billingAddress, $sendMail = false) - { - self::replaceBlock($content, $billingAddress); - self::replaceSingle($content, $billingAddress, $sendMail); - - return str_replace('{billing_address_information_lbl}', JText::_('COM_REDSHOP_BILLING_ADDRESS_INFORMATION_LBL'), $content); - } - - /** - * Method for replace Billing Address tag {billing_address} - * - * @param string $content Template content - * @param object $billingAddress Billing data - * @param boolean $sendMail Is in send mail? - * - * @return void - * @since 2.0.7 - */ - public static function replaceSingle(&$content, $billingAddress, $sendMail = false) - { - if (strpos($content, '{billing_address}') === false) - { - return; - } - - if (null === $billingAddress) - { - $content = str_replace('{billing_address}', '', $content); - - return; - } - - $billingLayout = $sendMail ? 'mail.billing' : 'cart.billing'; - - JPluginHelper::importPlugin('redshop_shipping'); - $dispatcher = RedshopHelperUtility::getDispatcher(); - $dispatcher->trigger('onBeforeRenderBillingAddress', array(&$billingAddress)); - - $billingContent = RedshopLayoutHelper::render( - $billingLayout, - array('billingAddresses' => $billingAddress), - null, - array('client' => 0) - ); - - if (strpos($content, '{quotation_custom_field_list}') !== false) - { - $content = str_replace('{quotation_custom_field_list}', '', $content); - - if (Redshop::getConfig()->getBool('DEFAULT_QUOTATION_MODE')) - { - $billingContent .= RedshopHelperExtrafields::listAllField( - RedshopHelperExtrafields::SECTION_QUOTATION, $billingAddress->users_info_id - ); - } - } - elseif (Redshop::getConfig()->getBool('DEFAULT_QUOTATION_MODE')) - { - $content = RedshopHelperExtrafields::listAllField( - RedshopHelperExtrafields::SECTION_QUOTATION, $billingAddress->users_info_id, '', $content - ); - } - - $content = str_replace('{billing_address}', $billingContent, $content); - } - - /** - * Method for replace Billing Address tags between {billing_address_start} and {billing_address_end} - * - * @param string $content Template content - * @param object $billingAddress Billing data - * - * @return void - * @since 2.0.7 - */ - public static function replaceBlock(&$content, $billingAddress) - { - if (strpos($content, '{billing_address_start}') === false || strpos($content, '{billing_address_end}') === false) - { - return; - } - - $templateStart = explode('{billing_address_start}', $content); - $templateEnd = explode('{billing_address_end}', $templateStart[1]); - $billingTemplate = $templateEnd[0]; - - $extraFields = ''; - $companyName = ''; - $companyNameLabel = ''; - $firstName = ''; - $firstNameLabel = ''; - $lastName = ''; - $lastNameLabel = ''; - $fullName = ''; - $fullNameLabel = ''; - $address = ''; - $addressLabel = ''; - $zip = ''; - $zipLabel = ''; - $city = ''; - $cityLabel = ''; - $country = ''; - $countryLabel = ''; - $state = ''; - $stateLabel = ''; - $phone = ''; - $phoneLabel = ''; - $email = ''; - $emailLabel = ''; - $vatNumber = ''; - $vatNumberLabel = ''; - $eanNumber = ''; - $eanNumberLabel = ''; - $taxExempt = ''; - $taxExemptLabel = ''; - $taxExemptRequest = ''; - $taxExemptRequestLabel = ''; - - if (null !== $billingAddress) - { - if (!empty($billingAddress->firstname)) - { - $firstName = $billingAddress->firstname; - $firstNameLabel = JText::_('COM_REDSHOP_FIRSTNAME'); - } - - if (!empty($billingAddress->lastname)) - { - $lastName = $billingAddress->lastname; - $lastNameLabel = JText::_('COM_REDSHOP_LASTNAME'); - } - - if (!empty($billingAddress->lastname) || !empty($billingAddress->firstname)) - { - $fullName = $billingAddress->lastname . ' ' . $billingAddress->firstname; - $fullNameLabel = JText::_('COM_REDSHOP_FULLNAME'); - } - - if (!empty($billingAddress->address)) - { - $address = $billingAddress->address; - $addressLabel = JText::_('COM_REDSHOP_ADDRESS'); - } - - if (!empty($billingAddress->zipcode)) - { - $zip = $billingAddress->zipcode; - $zipLabel = JText::_('COM_REDSHOP_ZIP'); - } - - if (!empty($billingAddress->city)) - { - $city = $billingAddress->city; - $cityLabel = JText::_('COM_REDSHOP_CITY'); - } - - $countryName = RedshopHelperOrder::getCountryName($billingAddress->country_code); - - if (!empty($countryName)) - { - $country = JText::_($countryName); - $countryLabel = JText::_('COM_REDSCOM_REDSHOP_COUNTRYHOP_CITY'); - } - - $stateName = RedshopHelperOrder::getStateName($billingAddress->state_code, $billingAddress->country_code); - - if (!empty($stateName)) - { - $state = JText::_($stateName); - $stateLabel = JText::_('COM_REDSHOP_STATE'); - } - - if (!empty($billingAddress->phone)) - { - $phone = $billingAddress->phone; - $phoneLabel = JText::_('COM_REDSHOP_PHONE'); - } - - if (!empty($billingAddress->user_email)) - { - $email = $billingAddress->user_email; - $emailLabel = JText::_('COM_REDSHOP_EMAIL'); - } - elseif (!empty(JFactory::getUser()->email)) - { - $email = JFactory::getUser()->email; - $emailLabel = JText::_('COM_REDSHOP_EMAIL'); - } - - if ((int) $billingAddress->is_company === 1) - { - if (!empty($billingAddress->company_name)) - { - $companyName = $billingAddress->company_name; - $companyNameLabel = JText::_('COM_REDSHOP_COMPANY_NAME'); - } - - if (!empty($billingAddress->vat_number)) - { - $vatNumber = $billingAddress->vat_number; - $vatNumberLabel = JText::_('COM_REDSHOP_VAT_NUMBER'); - } - - if (!empty($billingAddress->ean_number)) - { - $eanNumber = $billingAddress->ean_number; - $eanNumberLabel = JText::_('COM_REDSHOP_EAN_NUMBER'); - } - - if (Redshop::getConfig()->getBool('SHOW_TAX_EXEMPT_INFRONT')) - { - $taxExempt = $billingAddress->tax_exempt === 1 ? JText::_('COM_REDSHOP_TAX_YES') : JText::_('COM_REDSHOP_TAX_NO'); - - $taxExemptLabel = JText::_('COM_REDSHOP_TAX_EXEMPT'); - - $taxExemptRequest = $billingAddress->requesting_tax_exempt === 1 ? - JText::_('COM_REDSHOP_TAX_YES') : JText::_('COM_REDSHOP_TAX_NO'); - - $taxExemptRequestLabel = JText::_('COM_REDSHOP_USER_TAX_EXEMPT_REQUEST_LBL'); - } - } - - $fieldSection = $billingAddress->is_company === 1 ? - RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS : RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS; - - $extraFields = RedshopHelperExtrafields::listAllFieldDisplay($fieldSection, $billingAddress->users_info_id, 1); - } - - $tags = array('{companyname}', '{companyname_lbl}', '{firstname}', '{firstname_lbl}', '{lastname}', - '{lastname_lbl}', '{fullname}', '{fullname_lbl}','{address}', '{address_lbl}', '{zip}', '{zip_lbl}', - '{city}', '{city_lbl}', '{country}', '{country_lbl}', '{state}', '{state_lbl}', '{email}', '{email_lbl}', '{phone}', - '{phone_lbl}', '{vatnumber}', '{vatnumber_lbl}', '{ean_number}', '{ean_number_lbl}', '{taxexempt}', - '{taxexempt_lbl}', '{user_taxexempt_request}', '{user_taxexempt_request_lbl}', '{billing_extrafield}'); - - $replace = array($companyName, $companyNameLabel, $firstName, $firstNameLabel, $lastName, $lastNameLabel, - $fullName, $fullNameLabel, $address, $addressLabel, $zip, $zipLabel, $city, $cityLabel, $country, - $countryLabel, $state, $stateLabel, $email, $emailLabel, $phone, $phoneLabel, $vatNumber, $vatNumberLabel, - $eanNumber, $eanNumberLabel, $taxExempt, $taxExemptLabel, $taxExemptRequest, $taxExemptRequestLabel, - $extraFields); - - // Merge content - $content = $templateStart[0] . str_replace($tags, $replace, $billingTemplate) . $templateEnd[1]; - - // Remove {billing_address} tag from content if already run through this function - $content = str_replace('{billing_address}', '', $content); - } + /** + * Method for replace Billing Address + * + * @param string $content Template content + * @param object $billingAddress Billing data + * @param boolean $sendMail Is in send mail? + * + * @return mixed + * @since 2.0.7 + */ + public static function replaceBillingAddress($content, $billingAddress, $sendMail = false) + { + self::replaceBlock($content, $billingAddress); + self::replaceSingle($content, $billingAddress, $sendMail); + + return str_replace( + '{billing_address_information_lbl}', + JText::_('COM_REDSHOP_BILLING_ADDRESS_INFORMATION_LBL'), + $content + ); + } + + /** + * Method for replace Billing Address tags between {billing_address_start} and {billing_address_end} + * + * @param string $content Template content + * @param object $billingAddress Billing data + * + * @return void + * @since 2.0.7 + */ + public static function replaceBlock(&$content, $billingAddress) + { + if (strpos($content, '{billing_address_start}') === false || strpos( + $content, + '{billing_address_end}' + ) === false) { + return; + } + + $templateStart = explode('{billing_address_start}', $content); + $templateEnd = explode('{billing_address_end}', $templateStart[1]); + $billingTemplate = $templateEnd[0]; + + $extraFields = ''; + $companyName = ''; + $companyNameLabel = ''; + $firstName = ''; + $firstNameLabel = ''; + $lastName = ''; + $lastNameLabel = ''; + $fullName = ''; + $fullNameLabel = ''; + $address = ''; + $addressLabel = ''; + $zip = ''; + $zipLabel = ''; + $city = ''; + $cityLabel = ''; + $country = ''; + $countryLabel = ''; + $state = ''; + $stateLabel = ''; + $phone = ''; + $phoneLabel = ''; + $email = ''; + $emailLabel = ''; + $vatNumber = ''; + $vatNumberLabel = ''; + $eanNumber = ''; + $eanNumberLabel = ''; + $taxExempt = ''; + $taxExemptLabel = ''; + $taxExemptRequest = ''; + $taxExemptRequestLabel = ''; + + if (null !== $billingAddress) { + if (!empty($billingAddress->firstname)) { + $firstName = $billingAddress->firstname; + $firstNameLabel = JText::_('COM_REDSHOP_FIRSTNAME'); + } + + if (!empty($billingAddress->lastname)) { + $lastName = $billingAddress->lastname; + $lastNameLabel = JText::_('COM_REDSHOP_LASTNAME'); + } + + if (!empty($billingAddress->lastname) || !empty($billingAddress->firstname)) { + $fullName = $billingAddress->lastname . ' ' . $billingAddress->firstname; + $fullNameLabel = JText::_('COM_REDSHOP_FULLNAME'); + } + + if (!empty($billingAddress->address)) { + $address = $billingAddress->address; + $addressLabel = JText::_('COM_REDSHOP_ADDRESS'); + } + + if (!empty($billingAddress->zipcode)) { + $zip = $billingAddress->zipcode; + $zipLabel = JText::_('COM_REDSHOP_ZIP'); + } + + if (!empty($billingAddress->city)) { + $city = $billingAddress->city; + $cityLabel = JText::_('COM_REDSHOP_CITY'); + } + + $countryName = RedshopHelperOrder::getCountryName($billingAddress->country_code); + + if (!empty($countryName)) { + $country = JText::_($countryName); + $countryLabel = JText::_('COM_REDSCOM_REDSHOP_COUNTRYHOP_CITY'); + } + + $stateName = RedshopHelperOrder::getStateName($billingAddress->state_code, $billingAddress->country_code); + + if (!empty($stateName)) { + $state = JText::_($stateName); + $stateLabel = JText::_('COM_REDSHOP_STATE'); + } + + if (!empty($billingAddress->phone)) { + $phone = $billingAddress->phone; + $phoneLabel = JText::_('COM_REDSHOP_PHONE'); + } + + if (!empty($billingAddress->user_email)) { + $email = $billingAddress->user_email; + $emailLabel = JText::_('COM_REDSHOP_EMAIL'); + } elseif (!empty(JFactory::getUser()->email)) { + $email = JFactory::getUser()->email; + $emailLabel = JText::_('COM_REDSHOP_EMAIL'); + } + + if ((int)$billingAddress->is_company === 1) { + if (!empty($billingAddress->company_name)) { + $companyName = $billingAddress->company_name; + $companyNameLabel = JText::_('COM_REDSHOP_COMPANY_NAME'); + } + + if (!empty($billingAddress->vat_number)) { + $vatNumber = $billingAddress->vat_number; + $vatNumberLabel = JText::_('COM_REDSHOP_VAT_NUMBER'); + } + + if (!empty($billingAddress->ean_number)) { + $eanNumber = $billingAddress->ean_number; + $eanNumberLabel = JText::_('COM_REDSHOP_EAN_NUMBER'); + } + + if (Redshop::getConfig()->getBool('SHOW_TAX_EXEMPT_INFRONT')) { + $taxExempt = $billingAddress->tax_exempt === 1 ? JText::_('COM_REDSHOP_TAX_YES') : JText::_( + 'COM_REDSHOP_TAX_NO' + ); + + $taxExemptLabel = JText::_('COM_REDSHOP_TAX_EXEMPT'); + + $taxExemptRequest = $billingAddress->requesting_tax_exempt === 1 ? + JText::_('COM_REDSHOP_TAX_YES') : JText::_('COM_REDSHOP_TAX_NO'); + + $taxExemptRequestLabel = JText::_('COM_REDSHOP_USER_TAX_EXEMPT_REQUEST_LBL'); + } + } + + $fieldSection = $billingAddress->is_company === 1 ? + RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS : RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS; + + $extraFields = RedshopHelperExtrafields::listAllFieldDisplay( + $fieldSection, + $billingAddress->users_info_id, + 1 + ); + } + + $tags = array( + '{companyname}', + '{companyname_lbl}', + '{firstname}', + '{firstname_lbl}', + '{lastname}', + '{lastname_lbl}', + '{fullname}', + '{fullname_lbl}', + '{address}', + '{address_lbl}', + '{zip}', + '{zip_lbl}', + '{city}', + '{city_lbl}', + '{country}', + '{country_lbl}', + '{state}', + '{state_lbl}', + '{email}', + '{email_lbl}', + '{phone}', + '{phone_lbl}', + '{vatnumber}', + '{vatnumber_lbl}', + '{ean_number}', + '{ean_number_lbl}', + '{taxexempt}', + '{taxexempt_lbl}', + '{user_taxexempt_request}', + '{user_taxexempt_request_lbl}', + '{billing_extrafield}' + ); + + $replace = array( + $companyName, + $companyNameLabel, + $firstName, + $firstNameLabel, + $lastName, + $lastNameLabel, + $fullName, + $fullNameLabel, + $address, + $addressLabel, + $zip, + $zipLabel, + $city, + $cityLabel, + $country, + $countryLabel, + $state, + $stateLabel, + $email, + $emailLabel, + $phone, + $phoneLabel, + $vatNumber, + $vatNumberLabel, + $eanNumber, + $eanNumberLabel, + $taxExempt, + $taxExemptLabel, + $taxExemptRequest, + $taxExemptRequestLabel, + $extraFields + ); + + // Merge content + $content = $templateStart[0] . str_replace($tags, $replace, $billingTemplate) . $templateEnd[1]; + + // Remove {billing_address} tag from content if already run through this function + $content = str_replace('{billing_address}', '', $content); + } + + /** + * Method for replace Billing Address tag {billing_address} + * + * @param string $content Template content + * @param object $billingAddress Billing data + * @param boolean $sendMail Is in send mail? + * + * @return void + * @since 2.0.7 + */ + public static function replaceSingle(&$content, $billingAddress, $sendMail = false) + { + if (strpos($content, '{billing_address}') === false) { + return; + } + + if (null === $billingAddress) { + $content = str_replace('{billing_address}', '', $content); + + return; + } + + $billingLayout = $sendMail ? 'mail.billing' : 'cart.billing'; + + JPluginHelper::importPlugin('redshop_shipping'); + $dispatcher = RedshopHelperUtility::getDispatcher(); + $dispatcher->trigger('onBeforeRenderBillingAddress', array(&$billingAddress)); + + $billingContent = RedshopLayoutHelper::render( + $billingLayout, + array('billingAddresses' => $billingAddress), + null, + array('client' => 0) + ); + + if (strpos($content, '{quotation_custom_field_list}') !== false) { + $content = str_replace('{quotation_custom_field_list}', '', $content); + + if (Redshop::getConfig()->getBool('DEFAULT_QUOTATION_MODE')) { + $billingContent .= RedshopHelperExtrafields::listAllField( + RedshopHelperExtrafields::SECTION_QUOTATION, + $billingAddress->users_info_id + ); + } + } elseif (Redshop::getConfig()->getBool('DEFAULT_QUOTATION_MODE')) { + $content = RedshopHelperExtrafields::listAllField( + RedshopHelperExtrafields::SECTION_QUOTATION, + $billingAddress->users_info_id, + '', + $content + ); + } + + $content = str_replace('{billing_address}', $billingContent, $content); + } } diff --git a/libraries/redshop/helper/breadcrumb.php b/libraries/redshop/helper/breadcrumb.php index 104f782d40c..2897f846744 100644 --- a/libraries/redshop/helper/breadcrumb.php +++ b/libraries/redshop/helper/breadcrumb.php @@ -18,374 +18,341 @@ */ class RedshopHelperBreadcrumb { - /** - * Method for generate breadcrumb base on specific section - * - * @param integer $sectionId Section ID - * - * @return void - * - * @since 2.0.7 - * - * @throws Exception - */ - public static function generate($sectionId = 0) - { - $app = JFactory::getApplication(); - - /** @var JPathway $pathway */ - $pathway = $app->getPathway(); - - $view = $app->input->getCmd('view'); - $layout = $app->input->getCmd('layout'); - $itemId = $app->input->getInt('Itemid'); - $categoryId = $app->input->getInt('cid'); - $customPathways = array(); - - // Clean up current pathway. - $paths = $pathway->getPathway(); - $menuPaths = $paths; - - foreach ($paths as $j => $path) - { - unset($paths[$j]); - } - - $pathway->setPathway($paths); - - switch ($view) - { - case "category": - // Use menu path if menu of category detail is same. - if ($sectionId) - { - $manufacturerId = $app->input->getInt('manufacturer_id', 0); - - $link = "index.php?option=com_redshop&view=category&layout=detail&cid=" . $sectionId . "&manufacturer_id=" . $manufacturerId; - $menu = RedshopHelperProduct::getMenuDetail($link); - - if ($menu) - { - $pathway->setPathway($menuPaths); - - return; - } - } - - $customPathways = array(); - $newLink = 'index.php?option=com_redshop&view=category'; - - if ($layout === 'categoryproduct') - { - $newLink = 'index.php?option=com_redshop&view=category&layout=' . $layout; - } - - $menu = RedshopHelperProduct::getMenuDetail($newLink); - - if (!empty($menu) && $menu->home !== 1) - { - $main = new stdClass; - $main->name = $menu->title; - $main->link = JRoute::_($newLink . '&Itemid=' . $menu->id); - $customPathways[] = $main; - } - - if ($sectionId != 0) - { - $category_list = array_reverse(RedshopHelperProduct::getCategoryNavigationlist($sectionId)); - $customPathways = array_merge($customPathways, self::getPathway($category_list)); - } - - break; - - case "product": - $menu = RedshopHelperProduct::getMenuInformation($itemId); - - if (!is_null($menu) - && (strpos($menu->params, "manufacturer") !== false && strpos($menu->params, '"manufacturer_id":"0"') === false)) - { - $customPathways = array(); - $menu = RedshopHelperProduct::getMenuDetail("index.php?option=com_redshop&view=manufacturers"); - - if (count($menu) > 0 && $menu->home != 1) - { - if (isset($menu->parent)) - { - $parentMenu = RedshopHelperProduct::getMenuInformation($menu->parent); - - if (count($parentMenu) > 0) - { - $main = new stdClass; - $main->name = $parentMenu->name; - $main->link = JRoute::_($parentMenu->link . '&Itemid=' . $parentMenu->id); - $customPathways[] = $main; - } - } - - $main = new stdClass; - $main->name = $menu->title; - $main->link = JRoute::_('index.php?option=com_redshop&view=manufacturers&Itemid=' . $menu->id); - $customPathways[] = $main; - } - - if ($sectionId != 0) - { - $prd = \Redshop\Product\Product::getProductById($sectionId); - $menu = RedshopEntityManufacturer::getInstance($prd->manufacturer_id)->getItem(); - - if (!empty($menu)) - { - $main = new stdClass; - $main->name = $menu->name; - $main->link = JRoute::_( - 'index.php?option=com_redshop&view=manufacturers&layout=products&mid=' . $prd->manufacturer_id - . '&Itemid=' . $itemId - ); - $customPathways[] = $main; - } - - $main = new stdClass; - $main->name = $prd->product_name; - $main->link = ""; - $customPathways[] = $main; - } - } - else - { - $customPathways = array(); - $menu = RedshopHelperProduct::getMenuDetail("index.php?option=com_redshop&view=category"); - - if (!empty($menu) && $menu->home != 1) - { - $main = new stdClass; - $main->name = $menu->title; - $main->link = JRoute::_('index.php?option=com_redshop&view=category&Itemid=' . $menu->id); - $customPathways[] = $main; - } - else - { - $menu = RedshopHelperProduct::getMenuDetail("index.php?option=com_redshop&view=product&pid=" . $sectionId); - - if (!empty($menu) && $menu->home != 1 && property_exists($menu, 'parent')) - { - $parentMenu = RedshopHelperProduct::getMenuInformation($menu->parent); - - if (!empty($parentMenu)) - { - $main = new stdClass; - $main->name = $parentMenu->name; - $main->link = JRoute::_($parentMenu->link . '&Itemid=' . $parentMenu->id); - $customPathways[] = $main; - } - } - } - - if ($sectionId != 0) - { - $prd = \Redshop\Product\Product::getProductById($sectionId); - - if (!$categoryId) - { - $categoryId = RedshopHelperProduct::getCategoryProduct($sectionId); - } - - if ($categoryId) - { - $category_list = array_reverse(RedshopHelperProduct::getCategoryNavigationlist($categoryId)); - $customPathways = array_merge($customPathways, self::getPathway($category_list)); - } - - $main = new stdClass; - $main->name = $prd->product_name; - $main->link = ""; - $customPathways[] = $main; - } - } - - break; - - case "manufacturers": - - $customPathways = array(); - $menu = RedshopHelperProduct::getMenuDetail("index.php?option=com_redshop&view=manufacturers"); - - if (isset($menu->id) && $menu->home != 1) - { - if (property_exists($menu, 'parent')) - { - $parentMenu = RedshopHelperProduct::getMenuInformation($menu->parent); - - if (count($parentMenu) > 0) - { - $main = new stdClass; - $main->name = $parentMenu->name; - $main->link = JRoute::_($parentMenu->link . '&Itemid=' . $parentMenu->id); - $customPathways[] = $main; - } - } - - $main = new stdClass; - $main->name = $menu->title; - $main->link = JRoute::_('index.php?option=com_redshop&view=manufacturers&Itemid=' . $menu->id); - $customPathways[] = $main; - } - - if ($sectionId != 0) - { - $menu = RedshopHelperProduct::getMenuInformation(0, $sectionId, "manufacturerid", "manufacturers"); - - if (!empty((array) $menu)) - { - $main = new stdClass; - $main->name = $menu->title; - $main->link = ""; - $customPathways[] = $main; - } - else - { - $menu = RedshopEntityManufacturer::getInstance($sectionId)->getItem(); - - if (!empty((array) $menu)) - { - $main = new stdClass; - $main->name = $menu->name; - $main->link = ""; - $customPathways[] = $main; - } - } - } - - break; - - case "account": - $customPathways = array(); - $menu = RedshopHelperProduct::getMenuInformation($itemId); - - if (isset($menu) && count((array)$menu) > 0) - { - $main = new stdClass; - $main->name = $menu->title; - $main->link = ""; - } - else - { - $main = new stdClass; - $main->name = JText::_('COM_REDSHOP_ACCOUNT_MAINTAINANCE'); - $main->link = ""; - } - - $customPathways[] = $main; - - break; - - case "order_detail": - $customPathways = array(); - $menu = RedshopHelperProduct::getMenuInformation(0, 0, "", "account"); - - if (!empty($menu)) - { - $main = new stdClass; - $main->name = $menu->title; - $main->link = JRoute::_('index.php?option=com_redshop&view=account&Itemid=' . $menu->id); - $customPathways[] = $main; - } - else - { - $main = new stdClass; - $main->name = JText::_('COM_REDSHOP_ACCOUNT_MAINTAINANCE'); - $main->link = JRoute::_('index.php?option=com_redshop&view=account&Itemid=' . $itemId); - $customPathways[] = $main; - } - - $main = new stdClass; - $main->name = JText::_('COM_REDSHOP_ORDER_DETAILS'); - $main->link = ""; - $customPathways[] = $main; - - break; - - case "orders": - case "account_billto": - case "account_shipto": - $customPathways = array(); - $menu = RedshopHelperProduct::getMenuInformation(0, 0, "", "account"); - - if (is_object($menu) && count(get_object_vars($menu)) > 0) - { - $main = new stdClass; - $main->name = $menu->title; - $main->link = JRoute::_('index.php?option=com_redshop&view=account&Itemid=' . $menu->id); - $customPathways[] = $main; - } - else - { - $main = new stdClass; - $main->name = JText::_('COM_REDSHOP_ACCOUNT_MAINTAINANCE'); - $main->link = JRoute::_('index.php?option=com_redshop&view=account&Itemid=' . $itemId); - $customPathways[] = $main; - } - - if ($view == 'orders') - { - $lastlink = JText::_('COM_REDSHOP_ORDER_LIST'); - } - elseif ($view == 'account_billto') - { - $lastlink = JText::_('COM_REDSHOP_BILLING_ADDRESS_INFORMATION_LBL'); - } - elseif ($view == 'account_shipto') - { - $lastlink = JText::_('COM_REDSHOP_SHIPPING_ADDRESS_INFO_LBL'); - } - - $main = new stdClass; - $main->name = $lastlink; - $main->link = ""; - $customPathways[] = $main; - - break; - - default: - break; - } - - if (empty($customPathways)) - { - return; - } - - $customPathways[count($customPathways) - 1]->link = ''; - - foreach ($customPathways as $customPathway) - { - $pathway->addItem($customPathway->name, $customPathway->link); - } - } - - /** - * Method for get list of pathway - * - * @param array $categories List of category - * - * @return array List of pathway - * - * @since 2.0.7 - */ - public static function getPathway($categories = array()) - { - $items = array(); - - foreach ($categories as $category) - { - $item = new stdClass; - $item->name = $category['category_name']; - $item->link = JRoute::_( - 'index.php?option=com_redshop&view=category&layout=detail&cid=' . $category['category_id'] . '&Itemid=' . $category['catItemid'] - ); - - $items[] = $item; - } - - return $items; - } + /** + * Method for generate breadcrumb base on specific section + * + * @param integer $sectionId Section ID + * + * @return void + * + * @throws Exception + * @since 2.0.7 + * + */ + public static function generate($sectionId = 0) + { + $app = JFactory::getApplication(); + + /** @var JPathway $pathway */ + $pathway = $app->getPathway(); + + $view = $app->input->getCmd('view'); + $layout = $app->input->getCmd('layout'); + $itemId = $app->input->getInt('Itemid'); + $categoryId = $app->input->getInt('cid'); + $customPathways = array(); + + // Clean up current pathway. + $paths = $pathway->getPathway(); + $menuPaths = $paths; + + foreach ($paths as $j => $path) { + unset($paths[$j]); + } + + $pathway->setPathway($paths); + + switch ($view) { + case "category": + // Use menu path if menu of category detail is same. + if ($sectionId) { + $manufacturerId = $app->input->getInt('manufacturer_id', 0); + + $link = "index.php?option=com_redshop&view=category&layout=detail&cid=" . $sectionId . "&manufacturer_id=" . $manufacturerId; + $menu = RedshopHelperProduct::getMenuDetail($link); + + if ($menu) { + $pathway->setPathway($menuPaths); + + return; + } + } + + $customPathways = array(); + $newLink = 'index.php?option=com_redshop&view=category'; + + if ($layout === 'categoryproduct') { + $newLink = 'index.php?option=com_redshop&view=category&layout=' . $layout; + } + + $menu = RedshopHelperProduct::getMenuDetail($newLink); + + if (!empty($menu) && $menu->home !== 1) { + $main = new stdClass; + $main->name = $menu->title; + $main->link = JRoute::_($newLink . '&Itemid=' . $menu->id); + $customPathways[] = $main; + } + + if ($sectionId != 0) { + $category_list = array_reverse(RedshopHelperProduct::getCategoryNavigationlist($sectionId)); + $customPathways = array_merge($customPathways, self::getPathway($category_list)); + } + + break; + + case "product": + $menu = RedshopHelperProduct::getMenuInformation($itemId); + + if (!is_null($menu) + && (strpos($menu->params, "manufacturer") !== false && strpos( + $menu->params, + '"manufacturer_id":"0"' + ) === false)) { + $customPathways = array(); + $menu = RedshopHelperProduct::getMenuDetail( + "index.php?option=com_redshop&view=manufacturers" + ); + + if (count($menu) > 0 && $menu->home != 1) { + if (isset($menu->parent)) { + $parentMenu = RedshopHelperProduct::getMenuInformation($menu->parent); + + if (count($parentMenu) > 0) { + $main = new stdClass; + $main->name = $parentMenu->name; + $main->link = JRoute::_($parentMenu->link . '&Itemid=' . $parentMenu->id); + $customPathways[] = $main; + } + } + + $main = new stdClass; + $main->name = $menu->title; + $main->link = JRoute::_( + 'index.php?option=com_redshop&view=manufacturers&Itemid=' . $menu->id + ); + $customPathways[] = $main; + } + + if ($sectionId != 0) { + $prd = \Redshop\Product\Product::getProductById($sectionId); + $menu = RedshopEntityManufacturer::getInstance($prd->manufacturer_id)->getItem(); + + if (!empty($menu)) { + $main = new stdClass; + $main->name = $menu->name; + $main->link = JRoute::_( + 'index.php?option=com_redshop&view=manufacturers&layout=products&mid=' . $prd->manufacturer_id + . '&Itemid=' . $itemId + ); + $customPathways[] = $main; + } + + $main = new stdClass; + $main->name = $prd->product_name; + $main->link = ""; + $customPathways[] = $main; + } + } else { + $customPathways = array(); + $menu = RedshopHelperProduct::getMenuDetail("index.php?option=com_redshop&view=category"); + + if (!empty($menu) && $menu->home != 1) { + $main = new stdClass; + $main->name = $menu->title; + $main->link = JRoute::_('index.php?option=com_redshop&view=category&Itemid=' . $menu->id); + $customPathways[] = $main; + } else { + $menu = RedshopHelperProduct::getMenuDetail( + "index.php?option=com_redshop&view=product&pid=" . $sectionId + ); + + if (!empty($menu) && $menu->home != 1 && property_exists($menu, 'parent')) { + $parentMenu = RedshopHelperProduct::getMenuInformation($menu->parent); + + if (!empty($parentMenu)) { + $main = new stdClass; + $main->name = $parentMenu->name; + $main->link = JRoute::_($parentMenu->link . '&Itemid=' . $parentMenu->id); + $customPathways[] = $main; + } + } + } + + if ($sectionId != 0) { + $prd = \Redshop\Product\Product::getProductById($sectionId); + + if (!$categoryId) { + $categoryId = RedshopHelperProduct::getCategoryProduct($sectionId); + } + + if ($categoryId) { + $category_list = array_reverse( + RedshopHelperProduct::getCategoryNavigationlist($categoryId) + ); + $customPathways = array_merge($customPathways, self::getPathway($category_list)); + } + + $main = new stdClass; + $main->name = $prd->product_name; + $main->link = ""; + $customPathways[] = $main; + } + } + + break; + + case "manufacturers": + + $customPathways = array(); + $menu = RedshopHelperProduct::getMenuDetail( + "index.php?option=com_redshop&view=manufacturers" + ); + + if (isset($menu->id) && $menu->home != 1) { + if (property_exists($menu, 'parent')) { + $parentMenu = RedshopHelperProduct::getMenuInformation($menu->parent); + + if (count($parentMenu) > 0) { + $main = new stdClass; + $main->name = $parentMenu->name; + $main->link = JRoute::_($parentMenu->link . '&Itemid=' . $parentMenu->id); + $customPathways[] = $main; + } + } + + $main = new stdClass; + $main->name = $menu->title; + $main->link = JRoute::_( + 'index.php?option=com_redshop&view=manufacturers&Itemid=' . $menu->id + ); + $customPathways[] = $main; + } + + if ($sectionId != 0) { + $menu = RedshopHelperProduct::getMenuInformation(0, $sectionId, "manufacturerid", "manufacturers"); + + if (!empty((array)$menu)) { + $main = new stdClass; + $main->name = $menu->title; + $main->link = ""; + $customPathways[] = $main; + } else { + $menu = RedshopEntityManufacturer::getInstance($sectionId)->getItem(); + + if (!empty((array)$menu)) { + $main = new stdClass; + $main->name = $menu->name; + $main->link = ""; + $customPathways[] = $main; + } + } + } + + break; + + case "account": + $customPathways = array(); + $menu = RedshopHelperProduct::getMenuInformation($itemId); + + if (isset($menu) && count((array)$menu) > 0) { + $main = new stdClass; + $main->name = $menu->title; + $main->link = ""; + } else { + $main = new stdClass; + $main->name = JText::_('COM_REDSHOP_ACCOUNT_MAINTAINANCE'); + $main->link = ""; + } + + $customPathways[] = $main; + + break; + + case "order_detail": + $customPathways = array(); + $menu = RedshopHelperProduct::getMenuInformation(0, 0, "", "account"); + + if (!empty($menu)) { + $main = new stdClass; + $main->name = $menu->title; + $main->link = JRoute::_('index.php?option=com_redshop&view=account&Itemid=' . $menu->id); + $customPathways[] = $main; + } else { + $main = new stdClass; + $main->name = JText::_('COM_REDSHOP_ACCOUNT_MAINTAINANCE'); + $main->link = JRoute::_('index.php?option=com_redshop&view=account&Itemid=' . $itemId); + $customPathways[] = $main; + } + + $main = new stdClass; + $main->name = JText::_('COM_REDSHOP_ORDER_DETAILS'); + $main->link = ""; + $customPathways[] = $main; + + break; + + case "orders": + case "account_billto": + case "account_shipto": + $customPathways = array(); + $menu = RedshopHelperProduct::getMenuInformation(0, 0, "", "account"); + + if (is_object($menu) && count(get_object_vars($menu)) > 0) { + $main = new stdClass; + $main->name = $menu->title; + $main->link = JRoute::_('index.php?option=com_redshop&view=account&Itemid=' . $menu->id); + $customPathways[] = $main; + } else { + $main = new stdClass; + $main->name = JText::_('COM_REDSHOP_ACCOUNT_MAINTAINANCE'); + $main->link = JRoute::_('index.php?option=com_redshop&view=account&Itemid=' . $itemId); + $customPathways[] = $main; + } + + if ($view == 'orders') { + $lastlink = JText::_('COM_REDSHOP_ORDER_LIST'); + } elseif ($view == 'account_billto') { + $lastlink = JText::_('COM_REDSHOP_BILLING_ADDRESS_INFORMATION_LBL'); + } elseif ($view == 'account_shipto') { + $lastlink = JText::_('COM_REDSHOP_SHIPPING_ADDRESS_INFO_LBL'); + } + + $main = new stdClass; + $main->name = $lastlink; + $main->link = ""; + $customPathways[] = $main; + + break; + + default: + break; + } + + if (empty($customPathways)) { + return; + } + + $customPathways[count($customPathways) - 1]->link = ''; + + foreach ($customPathways as $customPathway) { + $pathway->addItem($customPathway->name, $customPathway->link); + } + } + + /** + * Method for get list of pathway + * + * @param array $categories List of category + * + * @return array List of pathway + * + * @since 2.0.7 + */ + public static function getPathway($categories = array()) + { + $items = array(); + + foreach ($categories as $category) { + $item = new stdClass; + $item->name = $category['category_name']; + $item->link = JRoute::_( + 'index.php?option=com_redshop&view=category&layout=detail&cid=' . $category['category_id'] . '&Itemid=' . $category['catItemid'] + ); + + $items[] = $item; + } + + return $items; + } } diff --git a/libraries/redshop/helper/cart.php b/libraries/redshop/helper/cart.php index 7922b33a2ac..43840bfad16 100644 --- a/libraries/redshop/helper/cart.php +++ b/libraries/redshop/helper/cart.php @@ -18,927 +18,903 @@ */ abstract class RedshopHelperCart { - /** - * @var array - */ - public static $cart = array(); - - /** - * Method for remove cart from Database - * - * @param int $cartId ID of cart. - * @param int $userId Id of user. - * @param bool $delCart Delete cart. - * - * @return boolean - * - * @since 2.0.3 - * @throws Exception - */ - public static function removeCartFromDatabase($cartId = 0, $userId = 0, $delCart = false) - { - if (!$userId) - { - $user = JFactory::getUser(); - $userId = (int) $user->id; - } - - $db = JFactory::getDbo(); - - if ($cartId === 0) - { - $query = $db->getQuery(true) - ->select($db->qn('cart_id')) - ->from($db->qn('#__redshop_usercart')) - ->where($db->qn('user_id') . ' = ' . (int) $userId); - - $cartId = $db->setQuery($query)->loadResult(); - } - - if (!$cartId) - { - return true; - } - - $query = $db->getQuery(true) - ->select($db->qn('cart_item_id')) - ->from($db->qn('#__redshop_usercart_item')) - ->where($db->qn('cart_id') . ' = ' . (int) $cartId); - - $cartItemIds = $db->setQuery($query)->loadColumn(); - - try - { - $db->transactionStart(); - - if ($cartItemIds) - { - $cartItemIds = ArrayHelper::toInteger($cartItemIds); - - // Delete accessory - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_usercart_accessory_item')) - ->where($db->qn('cart_item_id') . ' IN (' . implode(',', $cartItemIds) . ')'); - - $db->setQuery($query)->execute(); - - // Delete attribute - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_usercart_attribute_item')) - ->where($db->qn('cart_item_id') . ' IN (' . implode(',', $cartItemIds) . ')'); - - $db->setQuery($query)->execute(); - } - - // Delete cart item - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_usercart_item')) - ->where($db->qn('cart_id') . ' = ' . (int) $cartId); - - $db->setQuery($query)->execute(); - - if ($delCart) - { - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_usercart')) - ->where($db->qn('cart_id') . ' = ' . (int) $cartId); - - $db->setQuery($query)->execute(); - } - - $db->transactionCommit(); - } - catch (Exception $e) - { - $db->transactionRollback(); - - return false; - } - - return true; - } - - /** - * Store Cart to Database - * - * @param array $cart Cart data. - * - * @return boolean True on success. False otherwise. - * @throws Exception - * - * @since 2.0.3 - */ - public static function addCartToDatabase($cart = array()) - { - $user = JFactory::getUser(); - - // If user is not logged in don't save in db - if ($user->guest) - { - return false; - } - - $cart = empty($cart) ? \Redshop\Cart\Helper::getCart() : $cart; - - JPluginHelper::importPlugin('redshop_product'); - RedshopHelperUtility::getDispatcher()->trigger('onAddCartToDatabase', array(&$cart)); - - $idx = isset($cart['idx']) ? (int) $cart['idx'] : 0; - $db = JFactory::getDbo(); - - // Get cart ID. - - /** @var RedshopTableUsercart $userCartTable */ - $userCartTable = RedshopTable::getInstance('Usercart', 'RedshopTable'); - - if (!$userCartTable->load(array('user_id' => $user->id))) - { - $userCartTable->user_id = $user->id; - $userCartTable->cdate = time(); - $userCartTable->mdate = time(); - - if (!$userCartTable->store()) - { - return false; - } - - $cartId = $userCartTable->cart_id; - } - else - { - $cartId = $userCartTable->cart_id; - } - - try - { - $db->transactionStart(); - - $delCart = (!$idx) ? true : false; - - // Clean current cart. - if (!self::removeCartFromDatabase($cartId, $user->id, $delCart)) - { - return false; - } - - for ($i = 0; $i < $idx; $i++) - { - /** @var RedshopTableUsercart_Item $userCartItem */ - $userCartItem = RedshopTable::getInstance('Usercart_Item', 'RedshopTable'); - - $userCartItem->cart_idx = $i; - $userCartItem->cart_id = $cartId; - $userCartItem->product_id = $cart[$i]['product_id']; - $userCartItem->attribs = serialize($cart[$i]); - - if (isset($cart[$i]['giftcard_id']) === false) - { - $cart[$i]['giftcard_id'] = 0; - } - - if (isset($cart[$i]['wrapper_id']) === false) - { - $cart[$i]['wrapper_id'] = 0; - } - - $userCartItem->giftcard_id = $cart[$i]['giftcard_id']; - $userCartItem->product_quantity = $cart[$i]['quantity']; - $userCartItem->product_wrapper_id = $cart[$i]['wrapper_id']; - - if (isset($cart[$i]['subscription_id']) === false) - { - $cart[$i]['subscription_id'] = 0; - } - - $userCartItem->product_subscription_id = $cart[$i]['subscription_id']; - - if (!$userCartItem->store()) - { - throw new Exception(/** @scrutinizer ignore-deprecated */ $userCartItem->getError()); - } - - $cartItemId = $userCartItem->cart_item_id; - $cartAttributes = array(); - - if (isset($cart[$i]['cart_attribute'])) - { - $cartAttributes = $cart[$i]['cart_attribute']; - } - - // Store attribute in db - self::addCartAttributeToDatabase($cartAttributes, $cartItemId, $userCartItem->product_id); - - $cartAccessories = !empty($cart[$i]['cart_accessory']) ? (array) $cart[$i]['cart_accessory'] : array(); - - foreach ($cartAccessories as $cartAccessory) - { - /** @var RedshopTableUsercart_Accessory_Item $userCartItemAccessory */ - $userCartItemAccessory = RedshopTable::getInstance('Usercart_Accessory_Item', 'RedshopTable'); - $userCartItemAccessory->accessory_id = $cartAccessory['accessory_id']; - - // Store product quantity as accessory quantity. - $userCartItemAccessory->accessory_quantity = $cart[$i]['quantity']; - - if (!$userCartItemAccessory->store()) - { - throw new Exception(/** @scrutinizer ignore-deprecated */ $userCartItemAccessory->getError()); - } - - self::addCartAttributeToDatabase( - $cartAccessory['accessory_childs'], $cartItemId, $userCartItemAccessory->accessory_id, true - ); - } - } - - $db->transactionCommit(); - } - catch (Exception $e) - { - $db->transactionRollback(); - - return false; - } - - return true; - } - - /** - * Store Cart Attribute to Database - * - * @param array $attributes Cart attribute data. - * @param integer $cartItemId Cart item ID - * @param integer $productId Cart product ID. - * @param boolean $isAccessory Is this accessory? - * - * @return boolean True on success. False otherwise. - * - * @since 2.0.3 - * @throws Exception - */ - public static function addCartAttributeToDatabase($attributes = array(), $cartItemId = 0, $productId = 0, $isAccessory = false) - { - if (!$cartItemId) - { - return false; - } - - $db = JFactory::getDbo(); - - try - { - $db->transactionStart(); - - foreach ($attributes as $attribute) - { - /** @var RedshopTableUsercart_Attribute_Item $table */ - $table = RedshopTable::getInstance('Usercart_Attribute_Item', 'RedshopTable'); - - $table->cart_item_id = $cartItemId; - $table->section_id = $attribute['attribute_id']; - $table->section = 'attribute'; - $table->parent_section_id = $productId; - $table->is_accessory_att = (int) $isAccessory; - - if (!$table->store()) - { - throw new Exception(/** @scrutinizer ignore-deprecated */ $table->getError()); - } - - $attributeChildren = (array) $attribute['attribute_childs']; - - foreach ($attributeChildren as $attributeChild) - { - /** @var RedshopTableUsercart_Attribute_Item $itemTable */ - $itemTable = RedshopTable::getInstance('Usercart_Attribute_Item', 'RedshopTable'); - - $itemTable->cart_item_id = $cartItemId; - $itemTable->section_id = $attributeChild['property_id']; - $itemTable->section = 'property'; - $itemTable->parent_section_id = $attribute['attribute_id']; - $itemTable->is_accessory_att = (int) $isAccessory; - - if (!$itemTable->store()) - { - throw new Exception(/** @scrutinizer ignore-deprecated */ $table->getError()); - } - - if (empty($attributeChild['property_childs'])) - { - continue; - } - - foreach ($attributeChild['property_childs'] as $property) - { - /** @var RedshopTableUsercart_Attribute_Item $propertyTable */ - $propertyTable = RedshopTable::getInstance('usercart_attribute_item', 'RedshopTable'); - - $propertyTable->section_id = $property['subproperty_id']; - $propertyTable->section = 'subproperty'; - $propertyTable->parent_section_id = $attributeChild['property_id']; - $propertyTable->is_accessory_att = (int) $isAccessory; - - if (!$propertyTable->store()) - { - throw new Exception(/** @scrutinizer ignore-deprecated */ $table->getError()); - } - } - } - } - - $db->transactionCommit(); - } - catch (Exception $e) - { - $db->transactionRollback(); - - return false; - } - - return true; - } - - /** - * Method for convert data from database to cart. - * - * @param int $userId ID of user. - * - * @return void - * - * @since 2.0.3 - * @throws Exception - */ - public static function databaseToCart($userId = 0) - { - if (!$userId) - { - $user = JFactory::getUser(); - $userId = $user->id; - } - - JPluginHelper::importPlugin('redshop_product'); - - if (!array_key_exists($userId, self::$cart)) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select( - $db->qn( - array( - 'ci.cart_item_id', 'ci.cart_idx', 'ci.product_id', 'ci.product_quantity', - 'ci.product_wrapper_id', 'ci.product_subscription_id', 'ci.giftcard_id', 'ci.attribs') - ) - ) - ->from($db->qn('#__redshop_usercart_item', 'ci')) - ->leftJoin($db->qn('#__redshop_usercart', 'c') . ' ON ' . $db->qn('c.cart_id') . ' = ' . $db->qn('ci.cart_id')) - ->where($db->qn('c.user_id') . ' = ' . $userId) - ->order($db->qn('ci.cart_idx')); - - self::$cart[$userId] = $db->setQuery($query)->loadObjectList(); - } - - $cartItems = self::$cart[$userId]; - - if (empty($cartItems)) - { - return; - } - - $cart = array(); - $idx = 0; - - foreach ($cartItems as $cartItem) - { - RedshopHelperUtility::getDispatcher()->trigger('onDatabaseToCart', array(&$cartItem)); - - $setCartItem = true; - $quantity = $cartItem->product_quantity; - $calcOutput = ""; - $calcOutputs = array(); - $productId = $cartItem->product_id; - $subscriptionId = 0; - $wrapperPrice = 0; - $productVatPrice = 0; - $productOldPrice = 0; - $productOldPriceNoVat = 0; - $generateAttributeCart = ''; - $generateAccessoryCart = ''; - $giftCardId = ''; - $attributes = unserialize($cartItem->attribs); - - if ($cartItem->giftcard_id) - { - $section = 13; - $giftCardId = $cartItem->giftcard_id; - $giftCardPrice = 0; - $giftCardData = RedshopEntityGiftcard::getInstance($giftCardId)->getItem(); - - if (!empty($giftCardData)) - { - if ($giftCardData->customer_amount) - { - $customerAmount = ''; - - if (isset($attributes['customer_amount'])) - { - $customerAmount = $attributes['customer_amount']; - } - - $giftCardPrice = $customerAmount; - } - else - { - $giftCardPrice = $giftCardData->giftcard_price; - } - } - - $productPrice = $giftCardPrice; - $productPriceNoVat = $giftCardPrice; - } - else - { - $section = 12; - $cartItemId = $cartItem->cart_item_id; - $productPrice = 0; - $productData = \Redshop\Product\Product::getProductById($productId); - - if ($productData->published === 0) - { - continue; - } - - // Attribute price added - $generateAttributeCart = self::generateAttributeFromCart($cartItemId, 0, $productId, $quantity); - $cartAttributes = \RedshopHelperProduct::makeAttributeCart($generateAttributeCart, $productId, 0, $productPrice, $quantity); - - $productPriceNoVat = $cartAttributes[1]; - $productVatPrice = $cartAttributes[2]; - $selectedAttributeId = $cartAttributes[3]; - $isStock = $cartAttributes[4]; - $productOldPrice = $cartAttributes[5] + $cartAttributes[6]; - $productOldPriceNoVat = $cartAttributes[5]; - $productPrice = $productPriceNoVat + $productVatPrice; - - if (!$isStock) - { - $setCartItem = false; - $msg = JText::_('COM_REDSHOP_PRODUCT_OUTOFSTOCK_MESSAGE'); - } - - if ($productData->product_type === 'subscription') - { - $productSubscription = \RedshopHelperProduct::getProductSubscriptionDetail($productId, $cartItem->product_subscription_id); - - if (!empty($productSubscription->subscription_id)) - { - $subscriptionId = $productSubscription->subscription_id; - $subscriptionPrice = $productSubscription->subscription_price; - $subscriptionVAT = 0; - - if ($subscriptionPrice) - { - $subscriptionVAT = RedshopHelperProduct::getProductTax($productId, $subscriptionPrice); - } - - $productVatPrice += $subscriptionVAT; - $productPrice += $subscriptionPrice + $subscriptionVAT; - $productOldPrice = $productOldPrice + $subscriptionPrice + $subscriptionVAT; - $productOldPriceNoVat += $subscriptionPrice; - $productPriceNoVat += $subscriptionPrice; - } - else - { - $setCartItem = false; - $msg = JText::_('COM_REDSHOP_SELECT_PRODUCT_SUBSCRIPTION'); - } - } - - // Accessory price - $generateAccessoryCart = \Redshop\Accessory\Helper::generateAccessoryFromCart($cartItemId, $productId, $quantity); - $accessoriesData = RedshopHelperProduct::makeAccessoryCart($generateAccessoryCart, $productId); - $accessoryTotalPrice = $accessoriesData[1]; - $accessoryVATPrice = $accessoriesData[2]; - - $productPriceNoVat += $accessoryTotalPrice; - $productPrice += $accessoryTotalPrice + $accessoryVATPrice; - $productOldPrice += $accessoryTotalPrice + $accessoryVATPrice; - $productOldPriceNoVat += $accessoryTotalPrice; - $productVatPrice = $productVatPrice + $accessoryVATPrice; - - // Check if required attribute is filled or not - if (count($selectedAttributeId) > 0) - { - $selectedAttributeId = implode(",", $selectedAttributeId); - } - - $requiredAttributeData = \Redshop\Product\Attribute::getProductAttribute( - $productId, 0, 0, 0, 1, $selectedAttributeId - ); - - if (count($requiredAttributeData) > 0) - { - $requiredAttributes = array(); - - foreach ($requiredAttributeData as $requiredAttribute) - { - $requiredAttributes = $requiredAttribute->attribute_name; - } - - $requiredAttributeName = implode(', ', $requiredAttributes); - - // Throw an error as first attribute is required - $msg = $requiredAttributeName . " " . JText::_('COM_REDSHOP_IS_REQUIRED'); - $setCartItem = false; - } - - // ADD WRAPPER PRICE - $wrapperVAT = 0; - - if ($cartItem->product_wrapper_id) - { - $wrapperArr = \Redshop\Wrapper\Helper::getWrapperPrice(array('product_id' => $productId, 'wrapper_id' => $cartItem->product_wrapper_id)); - $wrapperVAT = $wrapperArr['wrapper_vat']; - $wrapperPrice = $wrapperArr['wrapper_price']; - } - - $productVatPrice += $wrapperVAT; - $productPrice += $wrapperPrice + $wrapperVAT; - $productOldPrice += $wrapperPrice + $wrapperVAT; - $productOldPriceNoVat += $wrapperPrice; - $productPriceNoVat += $wrapperPrice; - } - - // END WRAPPER PRICE - if ($setCartItem) - { - if ($productPrice < 0) - { - $productPrice = 0; - } - - if ($fields = RedshopHelperExtrafields::getSectionFieldList($section)) - { - foreach ($fields as $field) - { - $dataTxt = isset($attributes[$field->name]) ? $attributes[$field->name] : ''; - $text = strpbrk($dataTxt, '`'); - - if ($text) - { - $list = explode('`', $dataTxt); - - if (is_array($list)) - { - $dataTxt = implode(",", $list); - } - } - - $cart[$idx][$field->name] = $dataTxt; - } - } - - $cart[$idx]['product_price'] = $productPrice; - $cart[$idx]['product_price_excl_vat'] = $productPriceNoVat; - $cart[$idx]['giftcard_id'] = $giftCardId; - - if ($giftCardId) - { - $cart[$idx]['reciver_email'] = $attributes['reciver_email']; - $cart[$idx]['reciver_name'] = $attributes['reciver_name']; - $cart[$idx]['customer_amount'] = ''; - - if (isset($attributes['customer_amount'])) - { - $cart[$idx]['customer_amount'] = $attributes['customer_amount']; - } - - $cart[$idx]['product_vat'] = 0; - $cart[$idx]['product_id'] = ''; - $cart[$idx]['quantity'] = $quantity; - } - else - { - $cart[$idx]['product_id'] = $productId; - $cart[$idx]['discount_calc_output'] = $calcOutput; - $cart[$idx]['discount_calc'] = $calcOutputs; - $cart[$idx]['product_vat'] = $productVatPrice; - $cart[$idx]['product_old_price'] = $productOldPrice; - $cart[$idx]['product_old_price_excl_vat'] = $productOldPriceNoVat; - $cart[$idx]['cart_attribute'] = $generateAttributeCart; - $cart[$idx]['cart_accessory'] = $generateAccessoryCart; - $cart[$idx]['subscription_id'] = $subscriptionId; - $cart[$idx]['category_id'] = 0; - $cart[$idx]['wrapper_id'] = $cartItem->product_wrapper_id; - $cart[$idx]['wrapper_price'] = $wrapperPrice; - $cart[$idx]['quantity'] = \Redshop\Stock\Helper::checkQuantityInStock($cart[$idx], $quantity); - } - - if ($cart[$idx]['quantity'] <= 0) - { - $msg = JText::_('COM_REDSHOP_PRODUCT_OUTOFSTOCK_MESSAGE'); - - if (!empty(Redshop::getConfig()->getString('CART_RESERVATION_MESSAGE'))) - { - $msg = Redshop::getConfig()->get('CART_RESERVATION_MESSAGE'); - } - } - else - { - $idx++; - } - } - } - - $shopperGroup = RedshopHelperUser::getShopperGroup($userId); - - $cart['idx'] = $idx; - $cart['discount_type'] = 0; - $cart['discount'] = 0; - $cart['user_shopper_group_id'] = $shopperGroup; - - // Set 0 as default.. - $cart['free_shipping'] = 0; - $cart['voucher_discount'] = 0; - $cart['coupon_discount'] = 0; - $cart['cart_discount'] = 0; - - JFactory::getSession()->set('cart', $cart); - - self::cartFinalCalculation(); - } - - /** - * Method for generate attribute from cart. - * - * @param integer $cartItemId ID of cart item. - * @param integer $isAccessory Is accessory? - * @param integer $parentSectionId ID of parent section - * @param integer $quantity Quantity of product. - * - * @return array - * @throws Exception - * - * @since 2.0.3 - */ - public static function generateAttributeFromCart($cartItemId = 0, $isAccessory = 0, $parentSectionId = 0, $quantity = 1) - { - $cartAttributes = (array) \Redshop\Attribute\Helper::getCartItemAttributeDetail( - $cartItemId, $isAccessory, 'attribute', $parentSectionId - ); - - if (empty($cartAttributes)) - { - return array(); - } - - $generateAttributes = array(); - - foreach ($cartAttributes as $i => $cartAttribute) - { - $attribute = \Redshop\Product\Attribute::getProductAttribute(0, 0, $cartAttribute->section_id); - $generateProperties = array(); - - $generateAttributes[$i]['attribute_id'] = $cartAttribute->section_id; - $generateAttributes[$i]['attribute_name'] = $attribute[0]->text; - - $cartProperties = (array) \Redshop\Attribute\Helper::getCartItemAttributeDetail( - $cartItemId, $isAccessory, 'property', $cartAttribute->section_id - ); - - foreach ($cartProperties as $p => $cartProperty) - { - $generateSubProperties = array(); - $property = RedshopHelperProduct_Attribute::getAttributeProperties($cartProperty->section_id); - $priceList = RedshopHelperProduct_Attribute::getPropertyPrice($cartProperty->section_id, $quantity, 'property'); - - if (!empty($priceList->product_price)) - { - $propertyPrice = $priceList->product_price; - } - else - { - $propertyPrice = $property[0]->property_price; - } - - $generateProperties[$p]['property_id'] = $cartProperty->section_id; - $generateProperties[$p]['property_name'] = $property[0]->text; - $generateProperties[$p]['property_oprand'] = $property[0]->oprand; - $generateProperties[$p]['property_price'] = $propertyPrice; - - $cartSubProperties = (array) \Redshop\Attribute\Helper::getCartItemAttributeDetail( - $cartItemId, $isAccessory, 'subproperty', $cartProperty->section_id - ); - - foreach ($cartSubProperties as $index => $cartSubProperty) - { - $subProperty = RedshopHelperProduct_Attribute::getAttributeSubProperties($cartSubProperty->section_id); - $price = RedshopHelperProduct_Attribute::getPropertyPrice($cartSubProperty->section_id, $quantity, 'subproperty'); - $subPropertyPrice = $subProperty[0]->subattribute_color_price; - - if (!empty($price)) - { - $subPropertyPrice = $price->product_price; - } - - $generateSubProperties[$index]['subproperty_id'] = $cartSubProperty->section_id; - $generateSubProperties[$index]['subproperty_name'] = $subProperty[0]->text; - $generateSubProperties[$index]['subproperty_oprand'] = $subProperty[0]->oprand; - $generateSubProperties[$index]['subproperty_price'] = $subPropertyPrice; - } - - $generateProperties[$p]['property_childs'] = $generateSubProperties; - } - - $generateAttributes[$i]['attribute_childs'] = $generateProperties; - } - - return $generateAttributes; - } - - /** - * Method for calculate final price of cart. - * - * @param bool $isModify Is modify cart? - * - * @return array - * - * @since 2.0.3 - * - * @throws Exception - */ - public static function cartFinalCalculation($isModify = true) - { - $ajax = JFactory::getApplication()->input->getInt('ajax_cart_box'); - $cart = \Redshop\Cart\Helper::getCart(); - - if ($isModify === true) - { - $cart = RedshopHelperDiscount::modifyDiscount($cart); - } - - $cartOutput = array(); - $carts = self::generateCartOutput($cart); - - $cartOutput['cart_output'] = $carts[0]; - $cartOutput['total_quantity'] = $carts[1]; - $text = Redshop\Shipping\Rate::getFreeShippingRate(); - - if ($ajax === 1 &&Redshop::getConfig()->getBool('AJAX_CART_BOX')) - { - echo '`' . $carts[0] . '`' . $text; - JFactory::getApplication()->close(); - } - - return $cartOutput; - } - - /** - * Method for render cart. - * - * @param array $cart Cart data - * - * @return array - * - * @since 2.0.3 - */ - public static function generateCartOutput($cart = array()) - { - $return = array(); - $totalQuantity = 0; - $idx = $cart['idx']; - $cartParams = \Redshop\Cart\Module::getParams(); - $html = (string) $cartParams->get('cart_output', 'simple'); - $showShippingLine = (int) $cartParams->get('show_shipping_line', 0); - $showWithVAT = (int) $cartParams->get('show_with_vat', 0); - - for ($i = 0; $i < $idx; $i++) - { - $totalQuantity += $cart[$i]['quantity']; - } - - // Load cart module language - $lang = JFactory::getLanguage(); - $lang->load('mod_redshop_cart', JPATH_SITE); - - $return[] = RedshopLayoutHelper::render( - 'cart.cart', - array( - 'cartOutput' => $html, - 'totalQuantity' => $totalQuantity, - 'cart' => $cart, - 'showWithVat' => $showWithVAT, - 'showShippingLine' => $showShippingLine - ), - '', - array('option' => 'com_redshop') - ); - - $return[] = $totalQuantity; - - return $return; - } - - /** - * Calculate tax after Discount is apply - * - * @param float $tax Tax amount - * @param float $discount Discount amount. - * - * @return float Tax after apply discount. - * - * @since 2.0.3 - */ - public static function calculateTaxAfterDiscount($tax = 0.0, $discount = 0.0) - { - $taxAfterDiscount = 0; - $cart = JFactory::getSession()->get('cart'); - - if (Redshop::getConfig()->get('APPLY_VAT_ON_DISCOUNT') && (float) Redshop::getConfig()->get('VAT_RATE_AFTER_DISCOUNT')) - { - if ($discount > 0.0) - { - $applyTax = (float) Redshop::getConfig()->get('VAT_RATE_AFTER_DISCOUNT') * $discount; - $taxAfterDiscount = $tax - $applyTax; - } - } - - $cart['tax_after_discount'] = $taxAfterDiscount; - JFactory::getSession()->set('cart', $cart); - - return $taxAfterDiscount; - } - - /** - * Check user for Tax Exemption approved - * - * @param integer $userId User Information Id - Login user id - * @param boolean $isShowButtonAddToCart Display Add to cart button for tax exemption user - * - * @return boolean True if VAT applied else false - * - * @since 2.0.6 - */ - public static function taxExemptAddToCart($userId = 0, $isShowButtonAddToCart = false) - { - $userId = !$userId ? JFactory::getUser()->id : $userId; - - if (!$userId) - { - return true; - } - - $userInformation = RedshopHelperUser::getUserInformation($userId); - - if (empty($userInformation->user_id)) - { - return true; - } - - if ($userInformation->requesting_tax_exempt === 0) - { - return true; - } - - if ($userInformation->requesting_tax_exempt === 1 && $userInformation->tax_exempt_approved === 0) - { - if ($isShowButtonAddToCart) - { - return false; - } - - return true; - } - - if ($userInformation->requesting_tax_exempt === 1 && $userInformation->tax_exempt_approved === 1) - { - if ($isShowButtonAddToCart) - { - return true; - } - - return false; - } - - return true; - } - - /** - * Empty and delete current cart - * - * @return boolean - * - * @since 2.0.6 - */ - public static function emptyCart() - { - $cart = \Redshop\Cart\Helper::getCart(); - unset($cart); - - setcookie('redSHOPcart', '', time() - 3600, '/'); - - $cart['idx'] = 0; - \Redshop\Cart\Helper::setCart($cart); - - return RedshopHelperStockroom::deleteCartAfterEmpty(); - } + /** + * @var array + */ + public static $cart = array(); + + /** + * Store Cart to Database + * + * @param array $cart Cart data. + * + * @return boolean True on success. False otherwise. + * @throws Exception + * + * @since 2.0.3 + */ + public static function addCartToDatabase($cart = array()) + { + $user = JFactory::getUser(); + + // If user is not logged in don't save in db + if ($user->guest) { + return false; + } + + $cart = empty($cart) ? \Redshop\Cart\Helper::getCart() : $cart; + + JPluginHelper::importPlugin('redshop_product'); + RedshopHelperUtility::getDispatcher()->trigger('onAddCartToDatabase', array(&$cart)); + + $idx = isset($cart['idx']) ? (int)$cart['idx'] : 0; + $db = JFactory::getDbo(); + + // Get cart ID. + + /** @var RedshopTableUsercart $userCartTable */ + $userCartTable = RedshopTable::getInstance('Usercart', 'RedshopTable'); + + if (!$userCartTable->load(array('user_id' => $user->id))) { + $userCartTable->user_id = $user->id; + $userCartTable->cdate = time(); + $userCartTable->mdate = time(); + + if (!$userCartTable->store()) { + return false; + } + + $cartId = $userCartTable->cart_id; + } else { + $cartId = $userCartTable->cart_id; + } + + try { + $db->transactionStart(); + + $delCart = (!$idx) ? true : false; + + // Clean current cart. + if (!self::removeCartFromDatabase($cartId, $user->id, $delCart)) { + return false; + } + + for ($i = 0; $i < $idx; $i++) { + /** @var RedshopTableUsercart_Item $userCartItem */ + $userCartItem = RedshopTable::getInstance('Usercart_Item', 'RedshopTable'); + + $userCartItem->cart_idx = $i; + $userCartItem->cart_id = $cartId; + $userCartItem->product_id = $cart[$i]['product_id']; + $userCartItem->attribs = serialize($cart[$i]); + + if (isset($cart[$i]['giftcard_id']) === false) { + $cart[$i]['giftcard_id'] = 0; + } + + if (isset($cart[$i]['wrapper_id']) === false) { + $cart[$i]['wrapper_id'] = 0; + } + + $userCartItem->giftcard_id = $cart[$i]['giftcard_id']; + $userCartItem->product_quantity = $cart[$i]['quantity']; + $userCartItem->product_wrapper_id = $cart[$i]['wrapper_id']; + + if (isset($cart[$i]['subscription_id']) === false) { + $cart[$i]['subscription_id'] = 0; + } + + $userCartItem->product_subscription_id = $cart[$i]['subscription_id']; + + if (!$userCartItem->store()) { + throw new Exception(/** @scrutinizer ignore-deprecated */ $userCartItem->getError()); + } + + $cartItemId = $userCartItem->cart_item_id; + $cartAttributes = array(); + + if (isset($cart[$i]['cart_attribute'])) { + $cartAttributes = $cart[$i]['cart_attribute']; + } + + // Store attribute in db + self::addCartAttributeToDatabase($cartAttributes, $cartItemId, $userCartItem->product_id); + + $cartAccessories = !empty($cart[$i]['cart_accessory']) ? (array)$cart[$i]['cart_accessory'] : array(); + + foreach ($cartAccessories as $cartAccessory) { + /** @var RedshopTableUsercart_Accessory_Item $userCartItemAccessory */ + $userCartItemAccessory = RedshopTable::getInstance( + 'Usercart_Accessory_Item', + 'RedshopTable' + ); + $userCartItemAccessory->accessory_id = $cartAccessory['accessory_id']; + + // Store product quantity as accessory quantity. + $userCartItemAccessory->accessory_quantity = $cart[$i]['quantity']; + + if (!$userCartItemAccessory->store()) { + throw new Exception(/** @scrutinizer ignore-deprecated */ $userCartItemAccessory->getError()); + } + + self::addCartAttributeToDatabase( + $cartAccessory['accessory_childs'], + $cartItemId, + $userCartItemAccessory->accessory_id, + true + ); + } + } + + $db->transactionCommit(); + } catch (Exception $e) { + $db->transactionRollback(); + + return false; + } + + return true; + } + + /** + * Method for remove cart from Database + * + * @param int $cartId ID of cart. + * @param int $userId Id of user. + * @param bool $delCart Delete cart. + * + * @return boolean + * + * @throws Exception + * @since 2.0.3 + */ + public static function removeCartFromDatabase($cartId = 0, $userId = 0, $delCart = false) + { + if (!$userId) { + $user = JFactory::getUser(); + $userId = (int)$user->id; + } + + $db = JFactory::getDbo(); + + if ($cartId === 0) { + $query = $db->getQuery(true) + ->select($db->qn('cart_id')) + ->from($db->qn('#__redshop_usercart')) + ->where($db->qn('user_id') . ' = ' . (int)$userId); + + $cartId = $db->setQuery($query)->loadResult(); + } + + if (!$cartId) { + return true; + } + + $query = $db->getQuery(true) + ->select($db->qn('cart_item_id')) + ->from($db->qn('#__redshop_usercart_item')) + ->where($db->qn('cart_id') . ' = ' . (int)$cartId); + + $cartItemIds = $db->setQuery($query)->loadColumn(); + + try { + $db->transactionStart(); + + if ($cartItemIds) { + $cartItemIds = ArrayHelper::toInteger($cartItemIds); + + // Delete accessory + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_usercart_accessory_item')) + ->where($db->qn('cart_item_id') . ' IN (' . implode(',', $cartItemIds) . ')'); + + $db->setQuery($query)->execute(); + + // Delete attribute + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_usercart_attribute_item')) + ->where($db->qn('cart_item_id') . ' IN (' . implode(',', $cartItemIds) . ')'); + + $db->setQuery($query)->execute(); + } + + // Delete cart item + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_usercart_item')) + ->where($db->qn('cart_id') . ' = ' . (int)$cartId); + + $db->setQuery($query)->execute(); + + if ($delCart) { + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_usercart')) + ->where($db->qn('cart_id') . ' = ' . (int)$cartId); + + $db->setQuery($query)->execute(); + } + + $db->transactionCommit(); + } catch (Exception $e) { + $db->transactionRollback(); + + return false; + } + + return true; + } + + /** + * Store Cart Attribute to Database + * + * @param array $attributes Cart attribute data. + * @param integer $cartItemId Cart item ID + * @param integer $productId Cart product ID. + * @param boolean $isAccessory Is this accessory? + * + * @return boolean True on success. False otherwise. + * + * @throws Exception + * @since 2.0.3 + */ + public static function addCartAttributeToDatabase( + $attributes = array(), + $cartItemId = 0, + $productId = 0, + $isAccessory = false + ) { + if (!$cartItemId) { + return false; + } + + $db = JFactory::getDbo(); + + try { + $db->transactionStart(); + + foreach ($attributes as $attribute) { + /** @var RedshopTableUsercart_Attribute_Item $table */ + $table = RedshopTable::getInstance('Usercart_Attribute_Item', 'RedshopTable'); + + $table->cart_item_id = $cartItemId; + $table->section_id = $attribute['attribute_id']; + $table->section = 'attribute'; + $table->parent_section_id = $productId; + $table->is_accessory_att = (int)$isAccessory; + + if (!$table->store()) { + throw new Exception(/** @scrutinizer ignore-deprecated */ $table->getError()); + } + + $attributeChildren = (array)$attribute['attribute_childs']; + + foreach ($attributeChildren as $attributeChild) { + /** @var RedshopTableUsercart_Attribute_Item $itemTable */ + $itemTable = RedshopTable::getInstance('Usercart_Attribute_Item', 'RedshopTable'); + + $itemTable->cart_item_id = $cartItemId; + $itemTable->section_id = $attributeChild['property_id']; + $itemTable->section = 'property'; + $itemTable->parent_section_id = $attribute['attribute_id']; + $itemTable->is_accessory_att = (int)$isAccessory; + + if (!$itemTable->store()) { + throw new Exception(/** @scrutinizer ignore-deprecated */ $table->getError()); + } + + if (empty($attributeChild['property_childs'])) { + continue; + } + + foreach ($attributeChild['property_childs'] as $property) { + /** @var RedshopTableUsercart_Attribute_Item $propertyTable */ + $propertyTable = RedshopTable::getInstance('usercart_attribute_item', 'RedshopTable'); + + $propertyTable->section_id = $property['subproperty_id']; + $propertyTable->section = 'subproperty'; + $propertyTable->parent_section_id = $attributeChild['property_id']; + $propertyTable->is_accessory_att = (int)$isAccessory; + + if (!$propertyTable->store()) { + throw new Exception(/** @scrutinizer ignore-deprecated */ $table->getError()); + } + } + } + } + + $db->transactionCommit(); + } catch (Exception $e) { + $db->transactionRollback(); + + return false; + } + + return true; + } + + /** + * Method for convert data from database to cart. + * + * @param int $userId ID of user. + * + * @return void + * + * @throws Exception + * @since 2.0.3 + */ + public static function databaseToCart($userId = 0) + { + if (!$userId) { + $user = JFactory::getUser(); + $userId = $user->id; + } + + JPluginHelper::importPlugin('redshop_product'); + + if (!array_key_exists($userId, self::$cart)) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select( + $db->qn( + array( + 'ci.cart_item_id', + 'ci.cart_idx', + 'ci.product_id', + 'ci.product_quantity', + 'ci.product_wrapper_id', + 'ci.product_subscription_id', + 'ci.giftcard_id', + 'ci.attribs' + ) + ) + ) + ->from($db->qn('#__redshop_usercart_item', 'ci')) + ->leftJoin( + $db->qn('#__redshop_usercart', 'c') . ' ON ' . $db->qn('c.cart_id') . ' = ' . $db->qn('ci.cart_id') + ) + ->where($db->qn('c.user_id') . ' = ' . $userId) + ->order($db->qn('ci.cart_idx')); + + self::$cart[$userId] = $db->setQuery($query)->loadObjectList(); + } + + $cartItems = self::$cart[$userId]; + + if (empty($cartItems)) { + return; + } + + $cart = array(); + $idx = 0; + + foreach ($cartItems as $cartItem) { + RedshopHelperUtility::getDispatcher()->trigger('onDatabaseToCart', array(&$cartItem)); + + $setCartItem = true; + $quantity = $cartItem->product_quantity; + $calcOutput = ""; + $calcOutputs = array(); + $productId = $cartItem->product_id; + $subscriptionId = 0; + $wrapperPrice = 0; + $productVatPrice = 0; + $productOldPrice = 0; + $productOldPriceNoVat = 0; + $generateAttributeCart = ''; + $generateAccessoryCart = ''; + $giftCardId = ''; + $attributes = unserialize($cartItem->attribs); + + if ($cartItem->giftcard_id) { + $section = 13; + $giftCardId = $cartItem->giftcard_id; + $giftCardPrice = 0; + $giftCardData = RedshopEntityGiftcard::getInstance($giftCardId)->getItem(); + + if (!empty($giftCardData)) { + if ($giftCardData->customer_amount) { + $customerAmount = ''; + + if (isset($attributes['customer_amount'])) { + $customerAmount = $attributes['customer_amount']; + } + + $giftCardPrice = $customerAmount; + } else { + $giftCardPrice = $giftCardData->giftcard_price; + } + } + + $productPrice = $giftCardPrice; + $productPriceNoVat = $giftCardPrice; + } else { + $section = 12; + $cartItemId = $cartItem->cart_item_id; + $productPrice = 0; + $productData = \Redshop\Product\Product::getProductById($productId); + + if ($productData->published === 0) { + continue; + } + + // Attribute price added + $generateAttributeCart = self::generateAttributeFromCart($cartItemId, 0, $productId, $quantity); + $cartAttributes = \RedshopHelperProduct::makeAttributeCart( + $generateAttributeCart, + $productId, + 0, + $productPrice, + $quantity + ); + + $productPriceNoVat = $cartAttributes[1]; + $productVatPrice = $cartAttributes[2]; + $selectedAttributeId = $cartAttributes[3]; + $isStock = $cartAttributes[4]; + $productOldPrice = $cartAttributes[5] + $cartAttributes[6]; + $productOldPriceNoVat = $cartAttributes[5]; + $productPrice = $productPriceNoVat + $productVatPrice; + + if (!$isStock) { + $setCartItem = false; + $msg = JText::_('COM_REDSHOP_PRODUCT_OUTOFSTOCK_MESSAGE'); + } + + if ($productData->product_type === 'subscription') { + $productSubscription = \RedshopHelperProduct::getProductSubscriptionDetail( + $productId, + $cartItem->product_subscription_id + ); + + if (!empty($productSubscription->subscription_id)) { + $subscriptionId = $productSubscription->subscription_id; + $subscriptionPrice = $productSubscription->subscription_price; + $subscriptionVAT = 0; + + if ($subscriptionPrice) { + $subscriptionVAT = RedshopHelperProduct::getProductTax($productId, $subscriptionPrice); + } + + $productVatPrice += $subscriptionVAT; + $productPrice += $subscriptionPrice + $subscriptionVAT; + $productOldPrice = $productOldPrice + $subscriptionPrice + $subscriptionVAT; + $productOldPriceNoVat += $subscriptionPrice; + $productPriceNoVat += $subscriptionPrice; + } else { + $setCartItem = false; + $msg = JText::_('COM_REDSHOP_SELECT_PRODUCT_SUBSCRIPTION'); + } + } + + // Accessory price + $generateAccessoryCart = \Redshop\Accessory\Helper::generateAccessoryFromCart( + $cartItemId, + $productId, + $quantity + ); + $accessoriesData = RedshopHelperProduct::makeAccessoryCart($generateAccessoryCart, $productId); + $accessoryTotalPrice = $accessoriesData[1]; + $accessoryVATPrice = $accessoriesData[2]; + + $productPriceNoVat += $accessoryTotalPrice; + $productPrice += $accessoryTotalPrice + $accessoryVATPrice; + $productOldPrice += $accessoryTotalPrice + $accessoryVATPrice; + $productOldPriceNoVat += $accessoryTotalPrice; + $productVatPrice = $productVatPrice + $accessoryVATPrice; + + // Check if required attribute is filled or not + if (count($selectedAttributeId) > 0) { + $selectedAttributeId = implode(",", $selectedAttributeId); + } + + $requiredAttributeData = \Redshop\Product\Attribute::getProductAttribute( + $productId, + 0, + 0, + 0, + 1, + $selectedAttributeId + ); + + if (count($requiredAttributeData) > 0) { + $requiredAttributes = array(); + + foreach ($requiredAttributeData as $requiredAttribute) { + $requiredAttributes = $requiredAttribute->attribute_name; + } + + $requiredAttributeName = implode(', ', $requiredAttributes); + + // Throw an error as first attribute is required + $msg = $requiredAttributeName . " " . JText::_('COM_REDSHOP_IS_REQUIRED'); + $setCartItem = false; + } + + // ADD WRAPPER PRICE + $wrapperVAT = 0; + + if ($cartItem->product_wrapper_id) { + $wrapperArr = \Redshop\Wrapper\Helper::getWrapperPrice( + array('product_id' => $productId, 'wrapper_id' => $cartItem->product_wrapper_id) + ); + $wrapperVAT = $wrapperArr['wrapper_vat']; + $wrapperPrice = $wrapperArr['wrapper_price']; + } + + $productVatPrice += $wrapperVAT; + $productPrice += $wrapperPrice + $wrapperVAT; + $productOldPrice += $wrapperPrice + $wrapperVAT; + $productOldPriceNoVat += $wrapperPrice; + $productPriceNoVat += $wrapperPrice; + } + + // END WRAPPER PRICE + if ($setCartItem) { + if ($productPrice < 0) { + $productPrice = 0; + } + + if ($fields = RedshopHelperExtrafields::getSectionFieldList($section)) { + foreach ($fields as $field) { + $dataTxt = isset($attributes[$field->name]) ? $attributes[$field->name] : ''; + $text = strpbrk($dataTxt, '`'); + + if ($text) { + $list = explode('`', $dataTxt); + + if (is_array($list)) { + $dataTxt = implode(",", $list); + } + } + + $cart[$idx][$field->name] = $dataTxt; + } + } + + $cart[$idx]['product_price'] = $productPrice; + $cart[$idx]['product_price_excl_vat'] = $productPriceNoVat; + $cart[$idx]['giftcard_id'] = $giftCardId; + + if ($giftCardId) { + $cart[$idx]['reciver_email'] = $attributes['reciver_email']; + $cart[$idx]['reciver_name'] = $attributes['reciver_name']; + $cart[$idx]['customer_amount'] = ''; + + if (isset($attributes['customer_amount'])) { + $cart[$idx]['customer_amount'] = $attributes['customer_amount']; + } + + $cart[$idx]['product_vat'] = 0; + $cart[$idx]['product_id'] = ''; + $cart[$idx]['quantity'] = $quantity; + } else { + $cart[$idx]['product_id'] = $productId; + $cart[$idx]['discount_calc_output'] = $calcOutput; + $cart[$idx]['discount_calc'] = $calcOutputs; + $cart[$idx]['product_vat'] = $productVatPrice; + $cart[$idx]['product_old_price'] = $productOldPrice; + $cart[$idx]['product_old_price_excl_vat'] = $productOldPriceNoVat; + $cart[$idx]['cart_attribute'] = $generateAttributeCart; + $cart[$idx]['cart_accessory'] = $generateAccessoryCart; + $cart[$idx]['subscription_id'] = $subscriptionId; + $cart[$idx]['category_id'] = 0; + $cart[$idx]['wrapper_id'] = $cartItem->product_wrapper_id; + $cart[$idx]['wrapper_price'] = $wrapperPrice; + $cart[$idx]['quantity'] = \Redshop\Stock\Helper::checkQuantityInStock( + $cart[$idx], + $quantity + ); + } + + if ($cart[$idx]['quantity'] <= 0) { + $msg = JText::_('COM_REDSHOP_PRODUCT_OUTOFSTOCK_MESSAGE'); + + if (!empty(Redshop::getConfig()->getString('CART_RESERVATION_MESSAGE'))) { + $msg = Redshop::getConfig()->get('CART_RESERVATION_MESSAGE'); + } + } else { + $idx++; + } + } + } + + $shopperGroup = RedshopHelperUser::getShopperGroup($userId); + + $cart['idx'] = $idx; + $cart['discount_type'] = 0; + $cart['discount'] = 0; + $cart['user_shopper_group_id'] = $shopperGroup; + + // Set 0 as default.. + $cart['free_shipping'] = 0; + $cart['voucher_discount'] = 0; + $cart['coupon_discount'] = 0; + $cart['cart_discount'] = 0; + + JFactory::getSession()->set('cart', $cart); + + self::cartFinalCalculation(); + } + + /** + * Method for generate attribute from cart. + * + * @param integer $cartItemId ID of cart item. + * @param integer $isAccessory Is accessory? + * @param integer $parentSectionId ID of parent section + * @param integer $quantity Quantity of product. + * + * @return array + * @throws Exception + * + * @since 2.0.3 + */ + public static function generateAttributeFromCart( + $cartItemId = 0, + $isAccessory = 0, + $parentSectionId = 0, + $quantity = 1 + ) { + $cartAttributes = (array)\Redshop\Attribute\Helper::getCartItemAttributeDetail( + $cartItemId, + $isAccessory, + 'attribute', + $parentSectionId + ); + + if (empty($cartAttributes)) { + return array(); + } + + $generateAttributes = array(); + + foreach ($cartAttributes as $i => $cartAttribute) { + $attribute = \Redshop\Product\Attribute::getProductAttribute(0, 0, $cartAttribute->section_id); + $generateProperties = array(); + + $generateAttributes[$i]['attribute_id'] = $cartAttribute->section_id; + $generateAttributes[$i]['attribute_name'] = $attribute[0]->text; + + $cartProperties = (array)\Redshop\Attribute\Helper::getCartItemAttributeDetail( + $cartItemId, + $isAccessory, + 'property', + $cartAttribute->section_id + ); + + foreach ($cartProperties as $p => $cartProperty) { + $generateSubProperties = array(); + $property = RedshopHelperProduct_Attribute::getAttributeProperties( + $cartProperty->section_id + ); + $priceList = RedshopHelperProduct_Attribute::getPropertyPrice( + $cartProperty->section_id, + $quantity, + 'property' + ); + + if (!empty($priceList->product_price)) { + $propertyPrice = $priceList->product_price; + } else { + $propertyPrice = $property[0]->property_price; + } + + $generateProperties[$p]['property_id'] = $cartProperty->section_id; + $generateProperties[$p]['property_name'] = $property[0]->text; + $generateProperties[$p]['property_oprand'] = $property[0]->oprand; + $generateProperties[$p]['property_price'] = $propertyPrice; + + $cartSubProperties = (array)\Redshop\Attribute\Helper::getCartItemAttributeDetail( + $cartItemId, + $isAccessory, + 'subproperty', + $cartProperty->section_id + ); + + foreach ($cartSubProperties as $index => $cartSubProperty) { + $subProperty = RedshopHelperProduct_Attribute::getAttributeSubProperties( + $cartSubProperty->section_id + ); + $price = RedshopHelperProduct_Attribute::getPropertyPrice( + $cartSubProperty->section_id, + $quantity, + 'subproperty' + ); + $subPropertyPrice = $subProperty[0]->subattribute_color_price; + + if (!empty($price)) { + $subPropertyPrice = $price->product_price; + } + + $generateSubProperties[$index]['subproperty_id'] = $cartSubProperty->section_id; + $generateSubProperties[$index]['subproperty_name'] = $subProperty[0]->text; + $generateSubProperties[$index]['subproperty_oprand'] = $subProperty[0]->oprand; + $generateSubProperties[$index]['subproperty_price'] = $subPropertyPrice; + } + + $generateProperties[$p]['property_childs'] = $generateSubProperties; + } + + $generateAttributes[$i]['attribute_childs'] = $generateProperties; + } + + return $generateAttributes; + } + + /** + * Method for calculate final price of cart. + * + * @param bool $isModify Is modify cart? + * + * @return array + * + * @throws Exception + * @since 2.0.3 + * + */ + public static function cartFinalCalculation($isModify = true) + { + $ajax = JFactory::getApplication()->input->getInt('ajax_cart_box'); + $cart = \Redshop\Cart\Helper::getCart(); + + if ($isModify === true) { + $cart = RedshopHelperDiscount::modifyDiscount($cart); + } + + $cartOutput = array(); + $carts = self::generateCartOutput($cart); + + $cartOutput['cart_output'] = $carts[0]; + $cartOutput['total_quantity'] = $carts[1]; + $text = Redshop\Shipping\Rate::getFreeShippingRate(); + + if ($ajax === 1 && Redshop::getConfig()->getBool('AJAX_CART_BOX')) { + echo '`' . $carts[0] . '`' . $text; + JFactory::getApplication()->close(); + } + + return $cartOutput; + } + + /** + * Method for render cart. + * + * @param array $cart Cart data + * + * @return array + * + * @since 2.0.3 + */ + public static function generateCartOutput($cart = array()) + { + $return = array(); + $totalQuantity = 0; + $idx = $cart['idx']; + $cartParams = \Redshop\Cart\Module::getParams(); + $html = (string)$cartParams->get('cart_output', 'simple'); + $showShippingLine = (int)$cartParams->get('show_shipping_line', 0); + $showWithVAT = (int)$cartParams->get('show_with_vat', 0); + + for ($i = 0; $i < $idx; $i++) { + $totalQuantity += $cart[$i]['quantity']; + } + + // Load cart module language + $lang = JFactory::getLanguage(); + $lang->load('mod_redshop_cart', JPATH_SITE); + + $return[] = RedshopLayoutHelper::render( + 'cart.cart', + array( + 'cartOutput' => $html, + 'totalQuantity' => $totalQuantity, + 'cart' => $cart, + 'showWithVat' => $showWithVAT, + 'showShippingLine' => $showShippingLine + ), + '', + array('option' => 'com_redshop') + ); + + $return[] = $totalQuantity; + + return $return; + } + + /** + * Calculate tax after Discount is apply + * + * @param float $tax Tax amount + * @param float $discount Discount amount. + * + * @return float Tax after apply discount. + * + * @since 2.0.3 + */ + public static function calculateTaxAfterDiscount($tax = 0.0, $discount = 0.0) + { + $taxAfterDiscount = 0; + $cart = JFactory::getSession()->get('cart'); + + if (Redshop::getConfig()->get('APPLY_VAT_ON_DISCOUNT') && (float)Redshop::getConfig()->get( + 'VAT_RATE_AFTER_DISCOUNT' + )) { + if ($discount > 0.0) { + $applyTax = (float)Redshop::getConfig()->get('VAT_RATE_AFTER_DISCOUNT') * $discount; + $taxAfterDiscount = $tax - $applyTax; + } + } + + $cart['tax_after_discount'] = $taxAfterDiscount; + JFactory::getSession()->set('cart', $cart); + + return $taxAfterDiscount; + } + + /** + * Check user for Tax Exemption approved + * + * @param integer $userId User Information Id - Login user id + * @param boolean $isShowButtonAddToCart Display Add to cart button for tax exemption user + * + * @return boolean True if VAT applied else false + * + * @since 2.0.6 + */ + public static function taxExemptAddToCart($userId = 0, $isShowButtonAddToCart = false) + { + $userId = !$userId ? JFactory::getUser()->id : $userId; + + if (!$userId) { + return true; + } + + $userInformation = RedshopHelperUser::getUserInformation($userId); + + if (empty($userInformation->user_id)) { + return true; + } + + if ($userInformation->requesting_tax_exempt === 0) { + return true; + } + + if ($userInformation->requesting_tax_exempt === 1 && $userInformation->tax_exempt_approved === 0) { + if ($isShowButtonAddToCart) { + return false; + } + + return true; + } + + if ($userInformation->requesting_tax_exempt === 1 && $userInformation->tax_exempt_approved === 1) { + if ($isShowButtonAddToCart) { + return true; + } + + return false; + } + + return true; + } + + /** + * Empty and delete current cart + * + * @return boolean + * + * @since 2.0.6 + */ + public static function emptyCart() + { + $cart = \Redshop\Cart\Helper::getCart(); + unset($cart); + + setcookie('redSHOPcart', '', time() - 3600, '/'); + + $cart['idx'] = 0; + \Redshop\Cart\Helper::setCart($cart); + + return RedshopHelperStockroom::deleteCartAfterEmpty(); + } } diff --git a/libraries/redshop/helper/cart/discount.php b/libraries/redshop/helper/cart/discount.php index 6de8e531586..4244457614f 100644 --- a/libraries/redshop/helper/cart/discount.php +++ b/libraries/redshop/helper/cart/discount.php @@ -1,4 +1,5 @@ - * - * @since 2.0.7 - */ - public static function getDiscountCalcDataExtra($extraIds = "", $productId = 0) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select('*')->from($db->qn('#__redshop_product_discount_calc_extra')); - - if (!empty($extraIds)) - { - // Secure - $extraIds = explode(',', $extraIds); - $extraIds = ArrayHelper::toInteger($extraIds); - - $query->where($db->qn('pdcextra_id') . ' IN (' . implode(',', $extraIds) . ')'); - } - - if ($productId) - { - $query->where($db->qn('product_id') . ' = ' . (int) $productId); - } - - $query->order($db->qn('option_name')); - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * Method for apply coupon to cart. - * - * @param array $cartData Cart data - * @param string $couponCode Coupon code for apply - * - * @return array|bool Array of cart or boolean value. - * - * @since 2.0.7 - * - * @throws Exception - */ - public static function applyCoupon($cartData = array(), $couponCode = '') - { - $couponCode = empty($couponCode) ? JFactory::getApplication()->input->getString('discount_code', '') : $couponCode; - $cart = empty($cartData) ? \Redshop\Cart\Helper::getCart() : $cartData; - - if (empty($couponCode)) - { - return !empty($cartData) ? $cart : false; - } - - $view = JFactory::getApplication()->input->getCmd('view', ''); - $user = JFactory::getUser(); - $db = JFactory::getDbo(); - $return = false; - - $coupon = \Redshop\Promotion\Voucher::getCouponData($couponCode, $cart['product_subtotal_excl_vat']); - - foreach ($cart['coupon'] as $cartCoupon) - { - if ($coupon->id == $cartCoupon['coupon_id']) - { - return false; - } - } - - if (!empty($coupon)) - { - $discountType = $coupon->type; - $couponId = $coupon->id; - $couponType = $coupon->effect; - $couponUser = $coupon->userid; - $userType = false; - $return = true; - $counter = 0; - - foreach ($cart['coupon'] as $key => $val) - { - if ($val['coupon_code'] == $couponCode) - { - $counter++; - } - } - - if ($coupon->amount_left <= $counter) - { - return false; - } - - if ($couponType == 1) - { - if (!$user->id) - { - return false; - } - - $query = $db->getQuery(true) - ->select('SUM(' . $db->qn('coupon_value') . ') AS usertotal') - ->from($db->qn('#__redshop_coupons_transaction')) - ->where($db->qn('userid') . ' = ' . (int) $user->id) - ->group($db->qn('userid')); - - // Set the query and load the result. - $userData = $db->setQuery($query)->loadResult(); - - if (!empty($userData)) - { - $userType = $couponUser != $userData->userid; - } - else - { - if ($couponUser != $user->id) - { - return false; - } - - $return = false; - } - } - - if (!$userType) - { - $return = true; - } - - $productSubtotal = $cart['product_subtotal_excl_vat']; - - if (Redshop::getConfig()->get('DISCOUNT_TYPE') == 2 || Redshop::getConfig()->get('DISCOUNT_TYPE') == 1) - { - unset($cart['voucher']); - $cart['voucher_discount'] = 0; - } - - if (Redshop::getConfig()->get('DISCOUNT_TYPE') == 4) - { - $subTotal = $productSubtotal - $cart['voucher_discount'] - $cart['cart_discount'] - $cart['coupon_discount']; - } - else - { - $subTotal = $productSubtotal - $cart['voucher_discount'] - $cart['cart_discount']; - } - - if ($subTotal <= 0) - { - $subTotal = 0; - } - - if ($discountType == 0) - { - $avgVAT = 1; - - if ((float) Redshop::getConfig()->get('VAT_RATE_AFTER_DISCOUNT') && !Redshop::getConfig()->get('APPLY_VAT_ON_DISCOUNT')) - { - $avgVAT = $subTotal / $cart['product_subtotal_excl_vat']; - } - - $couponValue = $avgVAT * $coupon->value; - } - else - { - $couponValue = ($subTotal * $coupon->value) / (100); - } - - $key = \Redshop\Helper\Utility::rsMultiArrayKeyExists('coupon', $cart); - - $coupons = array(); - - if (!$key) - { - $oldCoupons = array(); - $couponIndex = 0; - } - else - { - $oldCoupons = $cart['coupon']; - $couponIndex = count($oldCoupons) + 1; - } - - if ($couponValue < 0) - { - return; - } - - if (!Redshop::getConfig()->get('APPLY_VOUCHER_COUPON_ALREADY_DISCOUNT')) - { - if (Redshop::getConfig()->get('DISCOUNT_TYPE') == 1) - { - $couponValue = RedshopHelperDiscount::calculateAlreadyDiscount($couponValue, $cart); - } - } - - $couponRemaining = 0; - - if ($couponValue > $subTotal && $couponIndex === 1) - { - $couponRemaining = $couponValue - $subTotal; - $couponValue = $subTotal; - } - - if (!is_null($cart['total']) && $cart['total'] == 0 && $view != 'cart') - { - $couponValue = 0; - } - - $valueExist = is_array($cart['coupon']) ? + /** + * @param string $extraIds Extra Ids + * @param integer $productId Product id + * + * @return array + * + * @since 2.0.7 + */ + public static function getDiscountCalcDataExtra($extraIds = "", $productId = 0) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select('*')->from($db->qn('#__redshop_product_discount_calc_extra')); + + if (!empty($extraIds)) { + // Secure + $extraIds = explode(',', $extraIds); + $extraIds = ArrayHelper::toInteger($extraIds); + + $query->where($db->qn('pdcextra_id') . ' IN (' . implode(',', $extraIds) . ')'); + } + + if ($productId) { + $query->where($db->qn('product_id') . ' = ' . (int)$productId); + } + + $query->order($db->qn('option_name')); + + return $db->setQuery($query)->loadObjectList(); + } + + /** + * Method for apply coupon to cart. + * + * @param array $cartData Cart data + * @param string $couponCode Coupon code for apply + * + * @return array|bool Array of cart or boolean value. + * + * @throws Exception + * @since 2.0.7 + * + */ + public static function applyCoupon($cartData = array(), $couponCode = '') + { + $couponCode = empty($couponCode) ? JFactory::getApplication()->input->getString( + 'discount_code', + '' + ) : $couponCode; + $cart = empty($cartData) ? \Redshop\Cart\Helper::getCart() : $cartData; + + if (empty($couponCode)) { + return !empty($cartData) ? $cart : false; + } + + $view = JFactory::getApplication()->input->getCmd('view', ''); + $user = JFactory::getUser(); + $db = JFactory::getDbo(); + $return = false; + + $coupon = \Redshop\Promotion\Voucher::getCouponData($couponCode, $cart['product_subtotal_excl_vat']); + + foreach ($cart['coupon'] as $cartCoupon) { + if ($coupon->id == $cartCoupon['coupon_id']) { + return false; + } + } + + if (!empty($coupon)) { + $discountType = $coupon->type; + $couponId = $coupon->id; + $couponType = $coupon->effect; + $couponUser = $coupon->userid; + $userType = false; + $return = true; + $counter = 0; + + foreach ($cart['coupon'] as $key => $val) { + if ($val['coupon_code'] == $couponCode) { + $counter++; + } + } + + if ($coupon->amount_left <= $counter) { + return false; + } + + if ($couponType == 1) { + if (!$user->id) { + return false; + } + + $query = $db->getQuery(true) + ->select('SUM(' . $db->qn('coupon_value') . ') AS usertotal') + ->from($db->qn('#__redshop_coupons_transaction')) + ->where($db->qn('userid') . ' = ' . (int)$user->id) + ->group($db->qn('userid')); + + // Set the query and load the result. + $userData = $db->setQuery($query)->loadResult(); + + if (!empty($userData)) { + $userType = $couponUser != $userData->userid; + } else { + if ($couponUser != $user->id) { + return false; + } + + $return = false; + } + } + + if (!$userType) { + $return = true; + } + + $productSubtotal = $cart['product_subtotal_excl_vat']; + + if (Redshop::getConfig()->get('DISCOUNT_TYPE') == 2 || Redshop::getConfig()->get('DISCOUNT_TYPE') == 1) { + unset($cart['voucher']); + $cart['voucher_discount'] = 0; + } + + if (Redshop::getConfig()->get('DISCOUNT_TYPE') == 4) { + $subTotal = $productSubtotal - $cart['voucher_discount'] - $cart['cart_discount'] - $cart['coupon_discount']; + } else { + $subTotal = $productSubtotal - $cart['voucher_discount'] - $cart['cart_discount']; + } + + if ($subTotal <= 0) { + $subTotal = 0; + } + + if ($discountType == 0) { + $avgVAT = 1; + + if ((float)Redshop::getConfig()->get('VAT_RATE_AFTER_DISCOUNT') && !Redshop::getConfig()->get( + 'APPLY_VAT_ON_DISCOUNT' + )) { + $avgVAT = $subTotal / $cart['product_subtotal_excl_vat']; + } + + $couponValue = $avgVAT * $coupon->value; + } else { + $couponValue = ($subTotal * $coupon->value) / (100); + } + + $key = \Redshop\Helper\Utility::rsMultiArrayKeyExists('coupon', $cart); + + $coupons = array(); + + if (!$key) { + $oldCoupons = array(); + $couponIndex = 0; + } else { + $oldCoupons = $cart['coupon']; + $couponIndex = count($oldCoupons) + 1; + } + + if ($couponValue < 0) { + return; + } + + if (!Redshop::getConfig()->get('APPLY_VOUCHER_COUPON_ALREADY_DISCOUNT')) { + if (Redshop::getConfig()->get('DISCOUNT_TYPE') == 1) { + $couponValue = RedshopHelperDiscount::calculateAlreadyDiscount($couponValue, $cart); + } + } + + $couponRemaining = 0; + + if ($couponValue > $subTotal && $couponIndex === 1) { + $couponRemaining = $couponValue - $subTotal; + $couponValue = $subTotal; + } + + if (!is_null($cart['total']) && $cart['total'] == 0 && $view != 'cart') { + $couponValue = 0; + } + + $valueExist = is_array($cart['coupon']) ? \Redshop\Helper\Utility::rsRecursiveArraySearch($cart['coupon'], $couponCode) : 0; - switch (Redshop::getConfig()->getInt('DISCOUNT_TYPE')) - { - case 4: - if ($valueExist) - { - $return = true; - } - - break; - - case 3: - $coupons = array(); - $oldCoupons = array(); - unset($cart['coupon']); - $return = true; - - break; - - case 2: - $coupons = array(); - $oldCoupons = array(); - unset($cart['voucher']); - unset($cart['coupon']); - $cart['voucher_discount'] = 0; - $return = true; - - break; - - case 1: - default: - $coupons = array(); - $oldCoupons = array(); - unset($cart['voucher']); - unset($cart['coupon']); - $cart['voucher_discount'] = 0; - - $return = true; - - break; - } - - if ($return) - { - $transactionCouponId = 0; - - if (\Redshop\Helper\Utility::rsMultiArrayKeyExists('transaction_coupon_id', $coupon)) - { - $transactionCouponId = $coupon->transaction_coupon_id; - } - - $coupons['coupon'][$couponIndex]['coupon_code'] = $couponCode; - $coupons['coupon'][$couponIndex]['coupon_id'] = $couponId; - $coupons['coupon'][$couponIndex]['used_coupon'] = 1; - $coupons['coupon'][$couponIndex]['coupon_value'] = $couponValue; - $coupons['coupon'][$couponIndex]['remaining_coupon_discount'] = $couponRemaining; - $coupons['coupon'][$couponIndex]['transaction_coupon_id'] = $transactionCouponId; - - $coupons['coupon'] = array_merge($coupons['coupon'], $oldCoupons); - - if (Redshop::getConfig()->get('DISCOUNT_TYPE') == 1) - { - foreach ($cart as $index => $value) - { - if (!is_numeric($index)) - { - continue; - } - - $checkDiscountPrice = RedshopHelperDiscount::getDiscountPriceBaseDiscountDate($value['product_id']); - - if ($checkDiscountPrice != 0) - { - return false; - } - } - } - - $cart = array_merge($cart, $coupons); - $cart['free_shipping'] = $coupon->free_shipping; - \Redshop\Cart\Helper::setCart($cart); - } - } - elseif (Redshop::getConfig()->getBool('VOUCHERS_ENABLE') === true) - { - $return = self::applyVoucher(); - } - - if (!empty($cartData)) - { - return $cart; - } - - return $return; - } - - /** - * Method for apply voucher to cart. - * - * @param array $cartData Cart data - * @param string $voucherCode Voucher code - * - * @return array|bool Array of cart or boolean value. - * - * @since 2.0.7 - * - * @throws Exception - */ - public static function applyVoucher($cartData = array(), $voucherCode = '') - { - $voucherCode = empty($voucherCode) ? JFactory::getApplication()->input->getString('discount_code', '') : $voucherCode; - $cart = empty($cartData) ? \Redshop\Cart\Helper::getCart() : $cartData; - - if (empty($voucherCode)) - { - return !empty($cartData) ? $cart : false; - } - - $voucher = \Redshop\Promotion\Voucher::getVoucherData($voucherCode); - - foreach ($cart['voucher'] as $cartVoucher) - { - if ($voucher->id == $cartVoucher['voucher_id']) - { - return false; - } - } - - if (null === $voucher) - { - return !empty($cartData) ? $cart : false; - } - - $counter = 0; - - foreach ($cart['voucher'] as $val) - { - if ($val['voucher_code'] == $voucherCode) - { - $counter++; - } - } - - if ($voucher->voucher_left <= $counter) - { - return false; - } - - $return = true; - $type = $voucher->type; - $voucherId = $voucher->id; - $productId = isset($voucher->nproduct) ? $voucher->nproduct : 0; - $productArr = \Redshop\Cart\Helper::getCartProductPrice($productId, $cart); - - if (empty($productArr['product_ids'])) - { - return false; - } - - $productPrice = $productArr['product_price']; - $productIds = $productArr['product_ids']; - $productQuantity = $productArr['product_quantity']; - $productQuantity = $productQuantity > $voucher->voucher_left ? $voucher->voucher_left : $productQuantity; - - if ($type != 'Percentage') - { - $voucher->total *= $productQuantity; - $voucherValue = $voucher->total; - } - else - { - $voucherValue = ($productPrice * $voucher->total) / (100); - } - - $vouchers = array(); - $oldVouchers = array(); - - $multiArrayKeyExists = \Redshop\Helper\Utility::rsMultiArrayKeyExists('voucher', $cart); - - if (!$multiArrayKeyExists) - { - $voucherIndex = 0; - } - else - { - $oldVouchers = $cart['voucher']; - $voucherIndex = count($oldVouchers) + 1; - } - - if (!Redshop::getConfig()->get('APPLY_VOUCHER_COUPON_ALREADY_DISCOUNT')) - { - if (Redshop::getConfig()->get('DISCOUNT_TYPE') == 1) - { - $voucherValue = RedshopHelperDiscount::calculateAlreadyDiscount($voucherValue, $cart); - } - } - - $remainingVoucherDiscount = 0; - - if ($productPrice < $voucherValue) - { - $remainingVoucherDiscount = $voucherValue - $productPrice; - $voucherValue = $productPrice; - } - elseif ($cart['voucher_discount'] > 0 && ($productPrice - $cart['voucher_discount']) <= 0 && Redshop::getConfig()->get('DISCOUNT_TYPE') != 4) - { - $remainingVoucherDiscount = $voucherValue; - $voucherValue = 0; - } - - $valueExist = is_array($cart['voucher']) ? + switch (Redshop::getConfig()->getInt('DISCOUNT_TYPE')) { + case 4: + if ($valueExist) { + $return = true; + } + + break; + + case 3: + $coupons = array(); + $oldCoupons = array(); + unset($cart['coupon']); + $return = true; + + break; + + case 2: + $coupons = array(); + $oldCoupons = array(); + unset($cart['voucher']); + unset($cart['coupon']); + $cart['voucher_discount'] = 0; + $return = true; + + break; + + case 1: + default: + $coupons = array(); + $oldCoupons = array(); + unset($cart['voucher']); + unset($cart['coupon']); + $cart['voucher_discount'] = 0; + + $return = true; + + break; + } + + if ($return) { + $transactionCouponId = 0; + + if (\Redshop\Helper\Utility::rsMultiArrayKeyExists('transaction_coupon_id', $coupon)) { + $transactionCouponId = $coupon->transaction_coupon_id; + } + + $coupons['coupon'][$couponIndex]['coupon_code'] = $couponCode; + $coupons['coupon'][$couponIndex]['coupon_id'] = $couponId; + $coupons['coupon'][$couponIndex]['used_coupon'] = 1; + $coupons['coupon'][$couponIndex]['coupon_value'] = $couponValue; + $coupons['coupon'][$couponIndex]['remaining_coupon_discount'] = $couponRemaining; + $coupons['coupon'][$couponIndex]['transaction_coupon_id'] = $transactionCouponId; + + $coupons['coupon'] = array_merge($coupons['coupon'], $oldCoupons); + + if (Redshop::getConfig()->get('DISCOUNT_TYPE') == 1) { + foreach ($cart as $index => $value) { + if (!is_numeric($index)) { + continue; + } + + $checkDiscountPrice = RedshopHelperDiscount::getDiscountPriceBaseDiscountDate( + $value['product_id'] + ); + + if ($checkDiscountPrice != 0) { + return false; + } + } + } + + $cart = array_merge($cart, $coupons); + $cart['free_shipping'] = $coupon->free_shipping; + \Redshop\Cart\Helper::setCart($cart); + } + } elseif (Redshop::getConfig()->getBool('VOUCHERS_ENABLE') === true) { + $return = self::applyVoucher(); + } + + if (!empty($cartData)) { + return $cart; + } + + return $return; + } + + /** + * Method for apply voucher to cart. + * + * @param array $cartData Cart data + * @param string $voucherCode Voucher code + * + * @return array|bool Array of cart or boolean value. + * + * @throws Exception + * @since 2.0.7 + * + */ + public static function applyVoucher($cartData = array(), $voucherCode = '') + { + $voucherCode = empty($voucherCode) ? JFactory::getApplication()->input->getString( + 'discount_code', + '' + ) : $voucherCode; + $cart = empty($cartData) ? \Redshop\Cart\Helper::getCart() : $cartData; + + if (empty($voucherCode)) { + return !empty($cartData) ? $cart : false; + } + + $voucher = \Redshop\Promotion\Voucher::getVoucherData($voucherCode); + + foreach ($cart['voucher'] as $cartVoucher) { + if ($voucher->id == $cartVoucher['voucher_id']) { + return false; + } + } + + if (null === $voucher) { + return !empty($cartData) ? $cart : false; + } + + $counter = 0; + + foreach ($cart['voucher'] as $val) { + if ($val['voucher_code'] == $voucherCode) { + $counter++; + } + } + + if ($voucher->voucher_left <= $counter) { + return false; + } + + $return = true; + $type = $voucher->type; + $voucherId = $voucher->id; + $productId = isset($voucher->nproduct) ? $voucher->nproduct : 0; + $productArr = \Redshop\Cart\Helper::getCartProductPrice($productId, $cart); + + if (empty($productArr['product_ids'])) { + return false; + } + + $productPrice = $productArr['product_price']; + $productIds = $productArr['product_ids']; + $productQuantity = $productArr['product_quantity']; + $productQuantity = $productQuantity > $voucher->voucher_left ? $voucher->voucher_left : $productQuantity; + + if ($type != 'Percentage') { + $voucher->total *= $productQuantity; + $voucherValue = $voucher->total; + } else { + $voucherValue = ($productPrice * $voucher->total) / (100); + } + + $vouchers = array(); + $oldVouchers = array(); + + $multiArrayKeyExists = \Redshop\Helper\Utility::rsMultiArrayKeyExists('voucher', $cart); + + if (!$multiArrayKeyExists) { + $voucherIndex = 0; + } else { + $oldVouchers = $cart['voucher']; + $voucherIndex = count($oldVouchers) + 1; + } + + if (!Redshop::getConfig()->get('APPLY_VOUCHER_COUPON_ALREADY_DISCOUNT')) { + if (Redshop::getConfig()->get('DISCOUNT_TYPE') == 1) { + $voucherValue = RedshopHelperDiscount::calculateAlreadyDiscount($voucherValue, $cart); + } + } + + $remainingVoucherDiscount = 0; + + if ($productPrice < $voucherValue) { + $remainingVoucherDiscount = $voucherValue - $productPrice; + $voucherValue = $productPrice; + } elseif ($cart['voucher_discount'] > 0 && ($productPrice - $cart['voucher_discount']) <= 0 && Redshop::getConfig( + )->get('DISCOUNT_TYPE') != 4) { + $remainingVoucherDiscount = $voucherValue; + $voucherValue = 0; + } + + $valueExist = is_array($cart['voucher']) ? \Redshop\Helper\Utility::rsRecursiveArraySearch($cart['voucher'], $voucherCode) : 0; - switch (Redshop::getConfig()->get('DISCOUNT_TYPE')) - { - case 4: - if ($valueExist) - { - $return = true; - } - - break; - - case 3: - - $vouchers = array(); - $oldVouchers = array(); - unset($cart['voucher']); - $return = true; - - break; - - case 2: - if ($cart['voucher']['voucher_code'] == $voucherCode) - { - $return = false; - } - else - { - $vouchers = array(); - $oldVouchers = array(); - unset($cart['voucher']); - unset($cart['coupon']); - $cart['voucher_discount'] = 0; - $return = true; - } - - break; - - case 1: - default: - $vouchers = array(); - $oldVouchers = array(); - - unset($cart['coupon']); - - $cart['cart_discount'] = 0; - $cart['coupon_discount'] = 0; - $cart['voucher_discount'] = 0; - - $return = true; - - break; - } - - if ($return) - { - $transactionVoucherId = 0; - - if (\Redshop\Helper\Utility::rsMultiArrayKeyExists('transaction_voucher_id', $voucher)) - { - $transactionVoucherId = $voucher->transaction_voucher_id; - } - - $vouchers['voucher'][$voucherIndex]['voucher_code'] = $voucherCode; - $vouchers['voucher'][$voucherIndex]['voucher_id'] = $voucherId; - $vouchers['voucher'][$voucherIndex]['product_id'] = $productIds; - $vouchers['voucher'][$voucherIndex]['used_voucher'] = $productQuantity; - $vouchers['voucher'][$voucherIndex]['voucher_value'] = $voucherValue; - $vouchers['voucher'][$voucherIndex]['remaining_voucher_discount'] = $remainingVoucherDiscount; - $vouchers['voucher'][$voucherIndex]['transaction_voucher_id'] = $transactionVoucherId; - - $vouchers['voucher'] = array_merge($vouchers['voucher'], $oldVouchers); - - if (Redshop::getConfig()->get('DISCOUNT_TYPE') == 1) - { - foreach ($cart as $index => $value) - { - if (!is_numeric($index)) - { - continue; - } - - $checkDiscountPrice = RedshopHelperDiscount::getDiscountPriceBaseDiscountDate($value['product_id']); - - if ($checkDiscountPrice != 0) - { - return false; - } - } - } - - $cart = array_merge($cart, $vouchers); - $cart['free_shipping'] = $voucher->free_ship; - - \Redshop\Cart\Helper::setCart($cart); - } - - if (!empty($cartData)) - { - return $cart; - } - - return $return; - } + switch (Redshop::getConfig()->get('DISCOUNT_TYPE')) { + case 4: + if ($valueExist) { + $return = true; + } + + break; + + case 3: + + $vouchers = array(); + $oldVouchers = array(); + unset($cart['voucher']); + $return = true; + + break; + + case 2: + if ($cart['voucher']['voucher_code'] == $voucherCode) { + $return = false; + } else { + $vouchers = array(); + $oldVouchers = array(); + unset($cart['voucher']); + unset($cart['coupon']); + $cart['voucher_discount'] = 0; + $return = true; + } + + break; + + case 1: + default: + $vouchers = array(); + $oldVouchers = array(); + + unset($cart['coupon']); + + $cart['cart_discount'] = 0; + $cart['coupon_discount'] = 0; + $cart['voucher_discount'] = 0; + + $return = true; + + break; + } + + if ($return) { + $transactionVoucherId = 0; + + if (\Redshop\Helper\Utility::rsMultiArrayKeyExists('transaction_voucher_id', $voucher)) { + $transactionVoucherId = $voucher->transaction_voucher_id; + } + + $vouchers['voucher'][$voucherIndex]['voucher_code'] = $voucherCode; + $vouchers['voucher'][$voucherIndex]['voucher_id'] = $voucherId; + $vouchers['voucher'][$voucherIndex]['product_id'] = $productIds; + $vouchers['voucher'][$voucherIndex]['used_voucher'] = $productQuantity; + $vouchers['voucher'][$voucherIndex]['voucher_value'] = $voucherValue; + $vouchers['voucher'][$voucherIndex]['remaining_voucher_discount'] = $remainingVoucherDiscount; + $vouchers['voucher'][$voucherIndex]['transaction_voucher_id'] = $transactionVoucherId; + + $vouchers['voucher'] = array_merge($vouchers['voucher'], $oldVouchers); + + if (Redshop::getConfig()->get('DISCOUNT_TYPE') == 1) { + foreach ($cart as $index => $value) { + if (!is_numeric($index)) { + continue; + } + + $checkDiscountPrice = RedshopHelperDiscount::getDiscountPriceBaseDiscountDate($value['product_id']); + + if ($checkDiscountPrice != 0) { + return false; + } + } + } + + $cart = array_merge($cart, $vouchers); + $cart['free_shipping'] = $voucher->free_ship; + + \Redshop\Cart\Helper::setCart($cart); + } + + if (!empty($cartData)) { + return $cart; + } + + return $return; + } } diff --git a/libraries/redshop/helper/cart/session.php b/libraries/redshop/helper/cart/session.php index f1eaf4bbb81..f87f9759312 100644 --- a/libraries/redshop/helper/cart/session.php +++ b/libraries/redshop/helper/cart/session.php @@ -1,4 +1,5 @@ get('cart', array()); - } + /** + * Get cart from session + * + * @return array + * + * @since 2.0.7 + */ + public static function getCart() + { + return (array)JFactory::getSession()->get('cart', array()); + } - /** - * @param array $cart Cart array - * - * @return boolean|array - * - * @since 2.0.7 - */ - public static function setCart($cart) - { - return JFactory::getSession()->set('cart', $cart); - } + /** + * Reset cart session + * + * @return void + * + * @since 2.0.7 + */ + public static function reset() + { + self::setCart(null); + } - /** - * Reset cart session - * - * @return void - * - * @since 2.0.7 - */ - public static function reset() - { - self::setCart(null); - } + /** + * @param array $cart Cart array + * + * @return boolean|array + * + * @since 2.0.7 + */ + public static function setCart($cart) + { + return JFactory::getSession()->set('cart', $cart); + } } diff --git a/libraries/redshop/helper/cart/shipping.php b/libraries/redshop/helper/cart/shipping.php index 371a78e6ce0..35dfbbe70a0 100644 --- a/libraries/redshop/helper/cart/shipping.php +++ b/libraries/redshop/helper/cart/shipping.php @@ -1,4 +1,5 @@ get('DEFAULT_SHIPPING_COUNTRY'); - $state = ''; - $isCompany = 0; - $whereState = ''; - $whereShopper = ''; - $userId = JFactory::getUser()->id; - - if ($userInfo) - { - $country = $userInfo->country_code; - $isCompany = (int) $userInfo->is_company; - $userId = $userInfo->user_id; - $state = $userInfo->state_code; - } - - $shopperGroup = RedshopHelperUser::getShopperGroupData($userId); - - if (null !== $shopperGroup) - { - $whereShopper = ' AND (FIND_IN_SET(' . $db->quote((int) $shopperGroup->shopper_group_id) . ', ' - . $db->qn('shipping_rate_on_shopper_group') . ' ) OR ' - . $db->qn('shipping_rate_on_shopper_group') . ' = "") '; - } - - $whereCountry = '(FIND_IN_SET(' . (string) $db->quote($country) . ', ' . $db->qn('shipping_rate_country') . ') OR ' - . $db->qn('shipping_rate_country') . ' = ' . $db->quote(0) . ' OR ' . $db->qn('shipping_rate_country') . ' = "")'; - - if ($state) - { - $whereState = ' AND (FIND_IN_SET(' . (string) $db->quote($state) . ', ' . $db->qn('shipping_rate_state') . ') OR ' - . $db->qn('shipping_rate_state') . ' = ' . $db->quote(0) . ' OR ' . $db->qn('shipping_rate_state') . ' = "")'; - } - - $companyOnly = !$isCompany ? 2 : 1; - $isWhere = ' AND (' . $db->qn('company_only') . ' = ' . $companyOnly . ' OR ' . $db->qn('company_only') . ' = 0) '; - - $shippingRate = self::getShippingRateFirst( - $volume, $weightTotal, $orderSubtotal, $whereCountry, $isWhere, $whereState, $whereShopper - ); - - if (null === $shippingRate) - { - $shippingRate = self::getShippingRateSecond($volume, $weightTotal, $orderSubtotal, $whereCountry, $isWhere, $whereState, $whereShopper); - } - - if (null === $shippingRate) - { - $shippingRate = self::getShippingRateThird($volume, $weightTotal, $orderSubtotal, $whereCountry, $isWhere, $whereState, $whereShopper); - } - - self::$defaultShipping[$key] = array('shipping_rate' => 0, 'shipping_vat' => 0); - - if (null === $shippingRate) - { - return self::$defaultShipping[$key]; - } - - if ($shippingRate->apply_vat != 1) - { - self::$defaultShipping[$key]['shipping_rate'] = $shippingRate->shipping_rate_value; - - return self::$defaultShipping[$key]; - } - - $result = RedshopHelperShipping::getShippingVatRates($shippingRate->shipping_tax_group_id, $data); - $addVat = RedshopHelperCart::taxExemptAddToCart($userId); - - if (!empty($result) && $addVat && $result->tax_rate > 0) - { - $shippingVat = $shippingRate->shipping_rate_value * $result->tax_rate; - $total = $shippingVat + $shippingRate->shipping_rate_value; - - self::$defaultShipping[$key]['shipping_rate'] = $total; - self::$defaultShipping[$key]['shipping_vat'] = $shippingVat; - } - - return self::$defaultShipping[$key]; - } - - /** - * Method for get shipping rate base on weight and volume - * - * @param integer $volume Volume - * @param float $weightTotal Weight total - * @param integer $orderSubtotal Order subtotal - * @param string $whereCountry Where country - * @param string $isWhere Is where - * @param string $whereState Where state - * @param string $whereShopper Where shopper - * - * @return mixed - * - * @since 2.1.0 - */ - public static function getShippingRateFirst($volume = 0, $weightTotal = 0.0, $orderSubtotal = 0, $whereCountry = '', $isWhere = '', - $whereState = '', $whereShopper = '') - { - $cart = \Redshop\Cart\Helper::getCart(); - $idx = (int) $cart['idx']; - - if (!$idx) - { - return null; - } - - $db = JFactory::getDbo(); - - $productWhere = self::prepareProductWhere(); - $sql = ' SELECT * ' - . ' FROM ' . $db->qn('#__redshop_shipping_rate', 'sr') - . ' LEFT JOIN ' . $db->qn('#__extensions', 's') - . ' ON ' . $db->qn('sr.shipping_class') . ' = ' . $db->qn('s.element') - . ' WHERE ' . $db->qn('s.folder') . ' = ' . $db->quote('redshop_shipping') - . ' AND ' . $db->qn('s.enabled') . ' = 1 ' - . ' AND ' . $whereCountry . $isWhere - . ' AND ( ' - . ' ( ' . $db->qn('shipping_rate_volume_start') . ' <= ' . $db->quote($volume) - . ' AND ' . $db->qn('shipping_rate_volume_end') . ' >= ' . $db->quote($volume) . ' ) ' - . ' OR ( ' . $db->qn('shipping_rate_volume_end') . ' = 0) ' - . ' ) ' - . ' AND ( ' - . ' ( ' . $db->qn('shipping_rate_ordertotal_start') . ' <= ' . $db->quote($orderSubtotal) - . ' AND ' . $db->qn('shipping_rate_ordertotal_end') . ' >= ' . $db->quote($orderSubtotal) . ' ) ' - . ' OR ( ' . $db->qn('shipping_rate_ordertotal_end') . ' = 0 ' - . ' ) ' - . ' ) ' - . ' AND ( ' - . ' ( ' . $db->qn('shipping_rate_weight_start') . ' <= ' . $db->quote($weightTotal) - . ' AND ' . $db->qn('shipping_rate_weight_end') . ' >= ' . $db->quote($weightTotal) - . ' ) ' - . ' OR ( ' . $db->qn('shipping_rate_weight_end') . ' = 0 ) ' - . ' ) ' - . $productWhere . $whereState . $whereShopper - . ' ORDER BY ' . $db->qn('s.ordering') . ' , ' . $db->qn('sr.shipping_rate_priority') . ' LIMIT 0,1 '; - - return $db->setQuery($sql)->loadObject(); - } - - /** - * Method for prepare where product - * - * @return string - * - * @since 2.1.0 - */ - public static function prepareProductWhere() - { - $cart = \Redshop\Cart\Helper::getCart(); - $idx = (int) $cart['idx']; - - if (!$idx) - { - return ''; - } - - $db = JFactory::getDbo(); - - $pWhere = 'AND ( '; - - for ($i = 0; $i < $idx; $i++) - { - $productId = (int) $cart[$i]['product_id']; - - $pWhere .= 'FIND_IN_SET(' . $productId . ', ' . $db->qn('shipping_rate_on_product') . ')'; - - if ($i != $idx - 1) - { - $pWhere .= " OR "; - } - } - - $pWhere .= ")"; - - return $pWhere; - } - - /** - * Method for get shipping rate second round - * - * @param integer $volume Volume - * @param float $weightTotal Weight total - * @param integer $orderSubtotal Order subtotal - * @param string $whereCountry Where country - * @param string $isWhere Is where - * @param string $whereState Where state - * @param string $whereShopper Where shopper - * - * @return mixed - * - * @since 2.1.0 - */ - public static function getShippingRateSecond($volume = 0, $weightTotal = 0.0, $orderSubtotal = 0, $whereCountry = '', $isWhere = '', - $whereState = '', $whereShopper = '') - { - $cart = \Redshop\Cart\Helper::getCart(); - $idx = (int) $cart['idx']; - - if (!$idx) - { - return null; - } - - $db = JFactory::getDbo(); - - $where = self::prepareCategoryWhere(); - - $sql = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') . " AS sr + /** + * List of default shipping + * + * @var array + * + * @since 2.1.0 + */ + protected static $defaultShipping = array(); + + /** + * Get Shipping rate for cart + * + * @param array $data Shipping data + * + * @return array + * + * @since 2.1.0 + */ + public static function getDefault($data) + { + $shipping = RedshopHelperShipping::getShopperGroupDefaultShipping(); + + if (!empty($shipping)) { + return $shipping; + } + + $userInfo = RedshopHelperOrder::getBillingAddress(); + $key = md5(serialize($data)) . md5(serialize($userInfo)); + + if (array_key_exists($key, self::$defaultShipping)) { + return self::$defaultShipping[$key]; + } + + $db = JFactory::getDbo(); + $orderSubtotal = $data['order_subtotal']; + $totalDimension = RedshopHelperShipping::getCartItemDimension(); + $weightTotal = $totalDimension['totalweight']; + $volume = $totalDimension['totalvolume']; + $country = Redshop::getConfig()->get('DEFAULT_SHIPPING_COUNTRY'); + $state = ''; + $isCompany = 0; + $whereState = ''; + $whereShopper = ''; + $userId = JFactory::getUser()->id; + + if ($userInfo) { + $country = $userInfo->country_code; + $isCompany = (int)$userInfo->is_company; + $userId = $userInfo->user_id; + $state = $userInfo->state_code; + } + + $shopperGroup = RedshopHelperUser::getShopperGroupData($userId); + + if (null !== $shopperGroup) { + $whereShopper = ' AND (FIND_IN_SET(' . $db->quote((int)$shopperGroup->shopper_group_id) . ', ' + . $db->qn('shipping_rate_on_shopper_group') . ' ) OR ' + . $db->qn('shipping_rate_on_shopper_group') . ' = "") '; + } + + $whereCountry = '(FIND_IN_SET(' . (string)$db->quote($country) . ', ' . $db->qn( + 'shipping_rate_country' + ) . ') OR ' + . $db->qn('shipping_rate_country') . ' = ' . $db->quote(0) . ' OR ' . $db->qn( + 'shipping_rate_country' + ) . ' = "")'; + + if ($state) { + $whereState = ' AND (FIND_IN_SET(' . (string)$db->quote($state) . ', ' . $db->qn( + 'shipping_rate_state' + ) . ') OR ' + . $db->qn('shipping_rate_state') . ' = ' . $db->quote(0) . ' OR ' . $db->qn( + 'shipping_rate_state' + ) . ' = "")'; + } + + $companyOnly = !$isCompany ? 2 : 1; + $isWhere = ' AND (' . $db->qn('company_only') . ' = ' . $companyOnly . ' OR ' . $db->qn( + 'company_only' + ) . ' = 0) '; + + $shippingRate = self::getShippingRateFirst( + $volume, + $weightTotal, + $orderSubtotal, + $whereCountry, + $isWhere, + $whereState, + $whereShopper + ); + + if (null === $shippingRate) { + $shippingRate = self::getShippingRateSecond( + $volume, + $weightTotal, + $orderSubtotal, + $whereCountry, + $isWhere, + $whereState, + $whereShopper + ); + } + + if (null === $shippingRate) { + $shippingRate = self::getShippingRateThird( + $volume, + $weightTotal, + $orderSubtotal, + $whereCountry, + $isWhere, + $whereState, + $whereShopper + ); + } + + self::$defaultShipping[$key] = array('shipping_rate' => 0, 'shipping_vat' => 0); + + if (null === $shippingRate) { + return self::$defaultShipping[$key]; + } + + if ($shippingRate->apply_vat != 1) { + self::$defaultShipping[$key]['shipping_rate'] = $shippingRate->shipping_rate_value; + + return self::$defaultShipping[$key]; + } + + $result = RedshopHelperShipping::getShippingVatRates($shippingRate->shipping_tax_group_id, $data); + $addVat = RedshopHelperCart::taxExemptAddToCart($userId); + + if (!empty($result) && $addVat && $result->tax_rate > 0) { + $shippingVat = $shippingRate->shipping_rate_value * $result->tax_rate; + $total = $shippingVat + $shippingRate->shipping_rate_value; + + self::$defaultShipping[$key]['shipping_rate'] = $total; + self::$defaultShipping[$key]['shipping_vat'] = $shippingVat; + } + + return self::$defaultShipping[$key]; + } + + /** + * Method for get shipping rate base on weight and volume + * + * @param integer $volume Volume + * @param float $weightTotal Weight total + * @param integer $orderSubtotal Order subtotal + * @param string $whereCountry Where country + * @param string $isWhere Is where + * @param string $whereState Where state + * @param string $whereShopper Where shopper + * + * @return mixed + * + * @since 2.1.0 + */ + public static function getShippingRateFirst( + $volume = 0, + $weightTotal = 0.0, + $orderSubtotal = 0, + $whereCountry = '', + $isWhere = '', + $whereState = '', + $whereShopper = '' + ) { + $cart = \Redshop\Cart\Helper::getCart(); + $idx = (int)$cart['idx']; + + if (!$idx) { + return null; + } + + $db = JFactory::getDbo(); + + $productWhere = self::prepareProductWhere(); + $sql = ' SELECT * ' + . ' FROM ' . $db->qn('#__redshop_shipping_rate', 'sr') + . ' LEFT JOIN ' . $db->qn('#__extensions', 's') + . ' ON ' . $db->qn('sr.shipping_class') . ' = ' . $db->qn('s.element') + . ' WHERE ' . $db->qn('s.folder') . ' = ' . $db->quote('redshop_shipping') + . ' AND ' . $db->qn('s.enabled') . ' = 1 ' + . ' AND ' . $whereCountry . $isWhere + . ' AND ( ' + . ' ( ' . $db->qn('shipping_rate_volume_start') . ' <= ' . $db->quote($volume) + . ' AND ' . $db->qn('shipping_rate_volume_end') . ' >= ' . $db->quote($volume) . ' ) ' + . ' OR ( ' . $db->qn('shipping_rate_volume_end') . ' = 0) ' + . ' ) ' + . ' AND ( ' + . ' ( ' . $db->qn('shipping_rate_ordertotal_start') . ' <= ' . $db->quote($orderSubtotal) + . ' AND ' . $db->qn('shipping_rate_ordertotal_end') . ' >= ' . $db->quote($orderSubtotal) . ' ) ' + . ' OR ( ' . $db->qn('shipping_rate_ordertotal_end') . ' = 0 ' + . ' ) ' + . ' ) ' + . ' AND ( ' + . ' ( ' . $db->qn('shipping_rate_weight_start') . ' <= ' . $db->quote($weightTotal) + . ' AND ' . $db->qn('shipping_rate_weight_end') . ' >= ' . $db->quote($weightTotal) + . ' ) ' + . ' OR ( ' . $db->qn('shipping_rate_weight_end') . ' = 0 ) ' + . ' ) ' + . $productWhere . $whereState . $whereShopper + . ' ORDER BY ' . $db->qn('s.ordering') . ' , ' . $db->qn('sr.shipping_rate_priority') . ' LIMIT 0,1 '; + + return $db->setQuery($sql)->loadObject(); + } + + /** + * Method for prepare where product + * + * @return string + * + * @since 2.1.0 + */ + public static function prepareProductWhere() + { + $cart = \Redshop\Cart\Helper::getCart(); + $idx = (int)$cart['idx']; + + if (!$idx) { + return ''; + } + + $db = JFactory::getDbo(); + + $pWhere = 'AND ( '; + + for ($i = 0; $i < $idx; $i++) { + $productId = (int)$cart[$i]['product_id']; + + $pWhere .= 'FIND_IN_SET(' . $productId . ', ' . $db->qn('shipping_rate_on_product') . ')'; + + if ($i != $idx - 1) { + $pWhere .= " OR "; + } + } + + $pWhere .= ")"; + + return $pWhere; + } + + /** + * Method for get shipping rate second round + * + * @param integer $volume Volume + * @param float $weightTotal Weight total + * @param integer $orderSubtotal Order subtotal + * @param string $whereCountry Where country + * @param string $isWhere Is where + * @param string $whereState Where state + * @param string $whereShopper Where shopper + * + * @return mixed + * + * @since 2.1.0 + */ + public static function getShippingRateSecond( + $volume = 0, + $weightTotal = 0.0, + $orderSubtotal = 0, + $whereCountry = '', + $isWhere = '', + $whereState = '', + $whereShopper = '' + ) { + $cart = \Redshop\Cart\Helper::getCart(); + $idx = (int)$cart['idx']; + + if (!$idx) { + return null; + } + + $db = JFactory::getDbo(); + + $where = self::prepareCategoryWhere(); + + $sql = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') . " AS sr LEFT JOIN " . $db->qn('#__extensions') . " AS s ON " . $db->qn('sr.shipping_class') . " = " . $db->qn('s.element') . " WHERE " . $db->qn('s.folder') . " = " . $db->quote('redshop_shipping') - . " AND " . $db->qn('s.enabled') . " = 1 AND" . $whereCountry . $whereShopper . $isWhere . " + . " AND " . $db->qn('s.enabled') . " = 1 AND" . $whereCountry . $whereShopper . $isWhere . " AND ((" . $db->qn('shipping_rate_volume_start') . " <= " . $db->quote($volume) - . " AND " . $db->qn('shipping_rate_volume_end') . " >= " - . $db->quote($volume) . ") OR (" . $db->qn('shipping_rate_volume_end') . " = 0) ) - AND ((" . $db->qn('shipping_rate_ordertotal_start') . " <= " . $db->quote($orderSubtotal) - . " AND " . $db->qn('shipping_rate_ordertotal_end') . " >= " - . $db->quote($orderSubtotal) . ") OR (" . $db->qn('shipping_rate_ordertotal_end') . " = 0)) + . " AND " . $db->qn('shipping_rate_volume_end') . " >= " + . $db->quote($volume) . ") OR (" . $db->qn('shipping_rate_volume_end') . " = 0) ) + AND ((" . $db->qn('shipping_rate_ordertotal_start') . " <= " . $db->quote( + $orderSubtotal + ) + . " AND " . $db->qn('shipping_rate_ordertotal_end') . " >= " + . $db->quote($orderSubtotal) . ") OR (" . $db->qn('shipping_rate_ordertotal_end') . " = 0)) AND ((" . $db->qn('shipping_rate_weight_start') . " <= " . $db->quote($weightTotal) - . " AND " . $db->qn('shipping_rate_weight_end') . " >= " - . $db->quote($weightTotal) . ") OR (" . $db->qn('shipping_rate_weight_end') . " = 0))" ; + . " AND " . $db->qn('shipping_rate_weight_end') . " >= " + . $db->quote($weightTotal) . ") OR (" . $db->qn('shipping_rate_weight_end') . " = 0))"; - if(trim($where) && trim($whereState)) - { + if (trim($where) && trim($whereState)) { $sql .= $where . $whereState; } - $sql .=" ORDER BY " . $db->qn('s.ordering') . ", " . $db->qn('sr.shipping_rate_priority') . " LIMIT 0,1"; - - return $db->setQuery($sql)->loadObject(); - } - - /** - * Method for prepare where category - * - * @return string - * - * @since 2.1.0 - */ - public static function prepareCategoryWhere() - { - $cart = \Redshop\Cart\Helper::getCart(); - $idx = (int) $cart['idx']; - - if (!$idx) - { - return ''; - } - - $db = JFactory::getDbo(); - - $where = ''; - - for ($i = 0; $i < $idx; $i++) - { - if (!array_key_exists('product_id', $cart[$i])) - { - continue; - } - - $productId = (int) $cart[$i]['product_id']; - $product = \Redshop\Product\Product::getProductById($productId); - - if (empty($product->categories)) - { - continue; - } - - $where .= ' AND ( '; - $index = 0; - - if (is_array($product->categories) && count($product->categories) > 0) - { - foreach ($product->categories as $category) - { - $where .= " FIND_IN_SET(" . (int) $category . ", " . $db->qn('shipping_rate_on_category') . ") "; - - if ($index != count($product->categories) - 1) - { + $sql .= " ORDER BY " . $db->qn('s.ordering') . ", " . $db->qn('sr.shipping_rate_priority') . " LIMIT 0,1"; + + return $db->setQuery($sql)->loadObject(); + } + + /** + * Method for prepare where category + * + * @return string + * + * @since 2.1.0 + */ + public static function prepareCategoryWhere() + { + $cart = \Redshop\Cart\Helper::getCart(); + $idx = (int)$cart['idx']; + + if (!$idx) { + return ''; + } + + $db = JFactory::getDbo(); + + $where = ''; + + for ($i = 0; $i < $idx; $i++) { + if (!array_key_exists('product_id', $cart[$i])) { + continue; + } + + $productId = (int)$cart[$i]['product_id']; + $product = \Redshop\Product\Product::getProductById($productId); + + if (empty($product->categories)) { + continue; + } + + $where .= ' AND ( '; + $index = 0; + + if (is_array($product->categories) && count($product->categories) > 0) { + foreach ($product->categories as $category) { + $where .= " FIND_IN_SET(" . (int)$category . ", " . $db->qn('shipping_rate_on_category') . ") "; + + if ($index != count($product->categories) - 1) { $where .= " OR "; } @@ -341,58 +365,66 @@ public static function prepareCategoryWhere() } } - $where .= ")"; - } - - return $where; - } - - /** - * Method for get shipping rate base on weight and volume - * - * @param integer $volume Volume - * @param float $weightTotal Weight total - * @param integer $orderSubtotal Order subtotal - * @param string $whereCountry Where country - * @param string $isWhere Is where - * @param string $whereState Where state - * @param string $whereShopper Where shopper - * - * @return mixed - * - * @since 2.1.0 - */ - public static function getShippingRateThird($volume = 0, $weightTotal = 0.0, $orderSubtotal = 0, $whereCountry = '', $isWhere = '', - $whereState = '', $whereShopper = '') - { - $db = JFactory::getDbo(); - - $newProductWhere = str_replace("AND (", "OR (", self::prepareProductWhere()); - $newCwhere = str_replace("AND (", "OR (", self::prepareCategoryWhere()); - - - $sql = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') . " AS sr + $where .= ")"; + } + + return $where; + } + + /** + * Method for get shipping rate base on weight and volume + * + * @param integer $volume Volume + * @param float $weightTotal Weight total + * @param integer $orderSubtotal Order subtotal + * @param string $whereCountry Where country + * @param string $isWhere Is where + * @param string $whereState Where state + * @param string $whereShopper Where shopper + * + * @return mixed + * + * @since 2.1.0 + */ + public static function getShippingRateThird( + $volume = 0, + $weightTotal = 0.0, + $orderSubtotal = 0, + $whereCountry = '', + $isWhere = '', + $whereState = '', + $whereShopper = '' + ) { + $db = JFactory::getDbo(); + + $newProductWhere = str_replace("AND (", "OR (", self::prepareProductWhere()); + $newCwhere = str_replace("AND (", "OR (", self::prepareCategoryWhere()); + + + $sql = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') . " AS sr LEFT JOIN " . $db->qn('#__extensions') . " AS s ON " . $db->qn('sr.shipping_class') . " = " . $db->qn('s.element') . " - WHERE " . $db->qn('s.folder') . " = " . $db->quote('redshop_shipping') . " AND " . $db->qn('s.enabled') . " = 1 AND " - . $whereCountry . $whereShopper . $isWhere . $whereState . " + WHERE " . $db->qn('s.folder') . " = " . $db->quote('redshop_shipping') . " AND " . $db->qn( + 's.enabled' + ) . " = 1 AND " + . $whereCountry . $whereShopper . $isWhere . $whereState . " AND ((" . $db->qn('shipping_rate_volume_start') . " <= " . $db->quote($volume) - . " AND " . $db->qn('shipping_rate_volume_end') . " >= " - . $db->quote($volume) . ") OR (" . $db->qn('shipping_rate_volume_end') . " = 0) ) + . " AND " . $db->qn('shipping_rate_volume_end') . " >= " + . $db->quote($volume) . ") OR (" . $db->qn('shipping_rate_volume_end') . " = 0) ) AND ((" . $db->qn('shipping_rate_ordertotal_start') . " <= " . $db->quote($orderSubtotal) - . " AND " . $db->qn('shipping_rate_ordertotal_end') . " >= " - . $db->quote($orderSubtotal) . ") OR (" . $db->qn('shipping_rate_ordertotal_end') . " = 0)) + . " AND " . $db->qn('shipping_rate_ordertotal_end') . " >= " + . $db->quote($orderSubtotal) . ") OR (" . $db->qn('shipping_rate_ordertotal_end') . " = 0)) AND ((" . $db->qn('shipping_rate_weight_start') . " <= " . $db->quote($weightTotal) - . " AND " . $db->qn('shipping_rate_weight_end') . " >= " . $db->quote($weightTotal) . ")" - . " OR (" . $db->qn('shipping_rate_weight_end') . " = 0))"; + . " AND " . $db->qn('shipping_rate_weight_end') . " >= " . $db->quote($weightTotal) . ")" + . " OR (" . $db->qn('shipping_rate_weight_end') . " = 0))"; - if (trim($newCwhere) && trim($newProductWhere)){ - $sql .= " AND (" . $db->qn('shipping_rate_on_product') . " = '' " . $newProductWhere . ")" + if (trim($newCwhere) && trim($newProductWhere)) { + $sql .= " AND (" . $db->qn('shipping_rate_on_product') . " = '' " . $newProductWhere . ")" . " AND (" . $db->qn('shipping_rate_on_category') . " = '' " . $newCwhere . " ) "; } - $sql .= " ORDER BY " . $db->qn('s.ordering') . ", " . $db->qn('sr.shipping_rate_priority') . " LIMIT 0,1"; + $sql .= " ORDER BY " . $db->qn('s.ordering') . ", " . $db->qn('sr.shipping_rate_priority') . " LIMIT 0,1"; - return $db->setQuery($sql)->loadObject(); - } + return $db->setQuery($sql)->loadObject(); + } } diff --git a/libraries/redshop/helper/cart/tag.php b/libraries/redshop/helper/cart/tag.php index 35597795658..afd72aa73f5 100644 --- a/libraries/redshop/helper/cart/tag.php +++ b/libraries/redshop/helper/cart/tag.php @@ -1,4 +1,5 @@ get('APPLY_VAT_ON_DISCOUNT') && (float)Redshop::getConfig()->get('VAT_RATE_AFTER_DISCOUNT')) { + if (Redshop::getConfig()->get('APPLY_VAT_ON_DISCOUNT') && (float)Redshop::getConfig()->get( + 'VAT_RATE_AFTER_DISCOUNT' + )) { if ($check) { $taxAfterDiscount = $discount; } else { @@ -80,12 +69,24 @@ public static function replaceTax($template = '', $amount = 0, $discount = 0, $c } if ($taxAfterDiscount > 0) { - $template = str_replace("{tax_after_discount}", RedshopHelperProductPrice::formattedPrice($taxAfterDiscount), $template); + $template = str_replace( + "{tax_after_discount}", + RedshopHelperProductPrice::formattedPrice($taxAfterDiscount), + $template + ); } else { - $template = str_replace("{tax_after_discount}", RedshopHelperProductPrice::formattedPrice($cart['tax']), $template); + $template = str_replace( + "{tax_after_discount}", + RedshopHelperProductPrice::formattedPrice($cart['tax']), + $template + ); } } else { - $template = str_replace("{tax_after_discount}", RedshopHelperProductPrice::formattedPrice($cart['tax']), $template); + $template = str_replace( + "{tax_after_discount}", + RedshopHelperProductPrice::formattedPrice($cart['tax']), + $template + ); } } @@ -97,10 +98,24 @@ public static function replaceTax($template = '', $amount = 0, $discount = 0, $c } /** - * @param string $template Template - * @param int $discount Discount - * @param int $subTotal Subtotal - * @param int $quotationMode Quotation mode + * @param string $template Template + * @param string $beginTag Begin tag + * @param string $closeTag Close tag + * + * @return boolean + * + * @since 2.0.7 + */ + public static function isBlockTagExists($template, $beginTag, $closeTag) + { + return (strpos($template, $beginTag) !== false && strpos($template, $closeTag) !== false); + } + + /** + * @param string $template Template + * @param int $discount Discount + * @param int $subTotal Subtotal + * @param int $quotationMode Quotation mode * * @return string * @@ -117,7 +132,7 @@ public static function replaceDiscount($template = '', $discount = 0, $subTotal if ($discount <= 0) { $templateDiscountSdata = explode('{if discount}', $template); $templateDiscountEdata = explode('{discount end if}', $templateDiscountSdata[1]); - $template = $templateDiscountSdata[0] . $templateDiscountEdata[1]; + $template = $templateDiscountSdata[0] . $templateDiscountEdata[1]; } else { $template = str_replace("{if discount}", '', $template); @@ -125,8 +140,16 @@ public static function replaceDiscount($template = '', $discount = 0, $subTotal $template = str_replace("{discount}", "", $template); $template = str_replace("{discount_in_percentage}", $percentage, $template); } else { - $template = str_replace("{discount}", RedshopHelperProductPrice::formattedPrice($discount, true), $template); - $template = str_replace("{order_discount}", RedshopHelperProductPrice::formattedPrice($discount, true), $template); + $template = str_replace( + "{discount}", + RedshopHelperProductPrice::formattedPrice($discount, true), + $template + ); + $template = str_replace( + "{order_discount}", + RedshopHelperProductPrice::formattedPrice($discount, true), + $template + ); if (!empty($subTotal) && $subTotal > 0) { $percentage = round(($discount * 100 / $subTotal), 2) . " %"; @@ -143,9 +166,9 @@ public static function replaceDiscount($template = '', $discount = 0, $subTotal } /** - * @param string $template Template - * @param object $order Order data - * @param int $quotationMode Quotation mode + * @param string $template Template + * @param object $order Order data + * @param int $quotationMode Quotation mode * * @return string * @@ -159,14 +182,13 @@ public static function replaceSpecialDiscount($template, $order, $quotationMode if ($order->special_discount_amount <= 0) { $template_discount_sdata = explode('{if special_discount}', $template); $template_discount_edata = explode('{special_discount end if}', $template_discount_sdata[1]); - $template = $template_discount_sdata[0] . $template_discount_edata[1]; + $template = $template_discount_sdata[0] . $template_discount_edata[1]; } else { $template = str_replace("{if special_discount}", '', $template); if ($quotationMode && !Redshop::getConfig()->getBool('SHOW_QUOTATION_PRICE')) { $template = str_replace("{special_discount}", "", $template); $template = str_replace("{special_discount_amount}", $order->special_discount, $template); - } else { $discount = $order->special_discount_amount; diff --git a/libraries/redshop/helper/catalog.php b/libraries/redshop/helper/catalog.php index 3d872aeea94..f54cf48e1e6 100644 --- a/libraries/redshop/helper/catalog.php +++ b/libraries/redshop/helper/catalog.php @@ -18,286 +18,278 @@ */ class RedshopHelperCatalog { - /** - * Catalog mail function - * - * @return void - * - * @since 2.0.6 - */ - public static function sendMail() - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_catalog_request')) - ->where($db->qn('block') . ' = 0'); - - $catalogs = $db->setQuery($query)->loadObjectList(); - - if (empty($catalogs)) - { - return; - } - - $config = JFactory::getConfig(); - $from = $config->get('mailfrom'); - $fromName = $config->get('fromname'); - $formattedDate = JFactory::getDate()->format('Y-m-d'); - - foreach ($catalogs as $catalog) - { - self::sendFirstReminder($catalog, $formattedDate, $from, $fromName); - - if ($catalog->reminder_2 == 0) - { - self::sendSecondReminder($catalog, $formattedDate, $from, $fromName); - } - elseif ($catalog->reminder_3 == 0) - { - self::sendThirdReminder($catalog, $formattedDate, $from, $fromName); - } - } - } - - /** - * Method for send first reminder of catalog - * - * @param object $catalog Catalog data - * @param string $currentDate Current date - * @param string $from Email from for send mail - * @param string $fromName Name for send mail - * - * @return void - * - * @since 2.0.6 - */ - public static function sendFirstReminder($catalog = null, $currentDate = '', $from = '', $fromName = '') - { - if (empty($catalog) || !is_object($catalog) || $catalog->reminder_1 != 0) - { - return; - } - - $currentDate = empty($currentDate) ? JFactory::getDate()->format('Y-m-d') : $currentDate; - $sendDate = date("Y-m-d", $catalog->registerDate + (Redshop::getConfig()->get('CATALOG_REMINDER_1') * (60 * 60 * 24))); - - if ($currentDate != $sendDate) - { - return; - } - - $from = empty($from) ? JFactory::getConfig()->get('mailfrom') : $from; - $fromName = empty($fromName) ? JFactory::getConfig()->get('fromname') : $fromName; - - $mailBody = ""; - $subject = ""; - $mailBcc = null; - $mailData = Redshop\Mail\Helper::getTemplate(0, "catalog_first_reminder"); - - if (count($mailData) > 0) - { - $mailData = $mailData[0]; - $mailBody = $mailData->mail_body; - $subject = $mailData->mail_subject; - - if (trim($mailData->mail_bcc) != "") - { - $mailBcc = explode(",", $mailData->mail_bcc); - } - } - - $body = str_replace("{name}", $catalog->name, $mailBody); - $body = str_replace("{discount}", Redshop::getConfig()->get('DISCOUNT_PERCENTAGE'), $body); - - Redshop\Mail\Helper::imgInMail($body); - - if (JFactory::getMailer()->sendMail($from, $fromName, $catalog->email, $subject, $body, 1, null, $mailBcc)) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_catalog_request')) - ->set($db->qn('reminder_1') . ' = ' . $db->quote(1)) - ->where($db->qn('catalog_user_id') . ' = ' . $catalog->catalog_user_id); - - $db->setQuery($query)->execute(); - } - } - - /** - * Method for send second reminder of catalog - * - * @param object $catalog Catalog data - * @param string $currentDate Current date - * @param string $from Email from for send mail - * @param string $fromName Name for send mail - * - * @return void - * - * @since 2.0.6 - */ - public static function sendSecondReminder($catalog = null, $currentDate = '', $from = '', $fromName = '') - { - if (empty($catalog) || !is_object($catalog) || $catalog->reminder_2 != 0) - { - return; - } - - $currentDate = empty($currentDate) ? JFactory::getDate()->format('Y-m-d') : $currentDate; - $sendDate = date("Y-m-d", $catalog->registerDate + (Redshop::getConfig()->get('CATALOG_REMINDER_2') * (60 * 60 * 24))); - - if ($currentDate != $sendDate) - { - return; - } - - $from = empty($from) ? JFactory::getConfig()->get('mailfrom') : $from; - $fromName = empty($fromName) ? JFactory::getConfig()->get('fromname') : $fromName; - $token = md5(uniqid(mt_rand(), true)); - $token = substr($token, 0, 10); - $startDate = mktime(0, 0, 0, date("m"), date("d"), date("Y")); - $endDate = $startDate + (Redshop::getConfig()->get('DISCOUNT_DURATION') * 23 * 59 * 59); - - $mailBody = ""; - $subject = ""; - $mailBcc = null; - $mailData = Redshop\Mail\Helper::getTemplate(0, "catalog_second_reminder"); - - if (count($mailData) > 0) - { - $mailData = $mailData[0]; - $mailBody = $mailData->mail_body; - $subject = $mailData->mail_subject; - - if (trim($mailData->mail_bcc) != "") - { - $mailBcc = explode(",", $mailData->mail_bcc); - } - } - - $body = str_replace("{name}", $catalog->name, $mailBody); - $body = str_replace("{days}", Redshop::getConfig()->get('DISCOUNT_DURATION'), $body); - $body = str_replace("{discount}", Redshop::getConfig()->get('DISCOUNT_PERCENTAGE'), $body); - $body = str_replace("{coupon_code}", $token, $body); - Redshop\Mail\Helper::imgInMail($body); - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->qn('id')) - ->from($db->qn('#__users')) - ->where($db->qn('email') . ' = ' . $db->quote($catalog->email)); - - $uid = $db->setQuery($query)->loadResult(); - - $query->clear() - ->insert($db->qn('#__redshop_coupons')) - ->columns( - $db->qn( - array('code', 'type', 'value', 'start_date', 'end_date', 'effect', 'userid', 'published') - ) - ) - ->values( - $db->quote($token) . ',' . $db->quote(1) . ',' . $db->quote(Redshop::getConfig()->get('DISCOUNT_PERCENTAGE')) . ',' . - $db->quote($startDate) . ',' . $db->quote($endDate) . ',' . $db->quote(1) . ',' . $db->quote($uid) . ',' . $db->quote(1) - ); - - $db->setQuery($query)->execute(); - - if (JFactory::getMailer()->sendMail($from, $fromName, $catalog->email, $subject, $body, 1, null, $mailBcc)) - { - $query->clear() - ->update($db->qn('#__redshop_catalog_request')) - ->set($db->qn('reminder_2') . ' = ' . $db->quote(1)) - ->where($db->qn('catalog_user_id') . ' = ' . $catalog->catalog_user_id); - - $db->setQuery($query)->execute(); - } - } - - /** - * Method for send second reminder of catalog - * - * @param object $catalog Catalog data - * @param string $currentDate Current date - * @param string $from Email from for send mail - * @param string $fromName Name for send mail - * - * @return void - * - * @since 2.0.6 - */ - public static function sendThirdReminder($catalog = null, $currentDate = '', $from = '', $fromName = '') - { - if (empty($catalog) || !is_object($catalog) || $catalog->reminder_3 != 0) - { - return; - } - - $currentDate = empty($currentDate) ? JFactory::getDate()->format('Y-m-d') : $currentDate; - - // Coupon reminder - $sendDate = date( - "Y-m-d", - $catalog->registerDate + (Redshop::getConfig()->get('DISCOUNT_DURATION') * (60 * 60 * 24)) + (4 * 60 * 60 * 24) - ); - - if ($currentDate != $sendDate) - { - return; - } - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->qn('id')) - ->from($db->qn('#__users')) - ->where($db->qn('email') . ' = ' . $db->quote($catalog->email)); - - $uid = $db->setQuery($query)->loadResult(); - - $query->clear() - ->select($db->qn('id')) - ->from($db->qn('#__redshop_coupons')) - ->where($db->qn('userid') . ' = ' . $db->quote($uid)); - - $couponCode = $db->setQuery($query)->loadResult(); - - $from = empty($from) ? JFactory::getConfig()->get('mailfrom') : $from; - $fromName = empty($fromName) ? JFactory::getConfig()->get('fromname') : $fromName; - - $mailBody = ""; - $subject = ""; - $mailBcc = null; - $mailData = Redshop\Mail\Helper::getTemplate(0, "catalog_coupon_reminder"); - - if (count($mailData) > 0) - { - $mailData = $mailData[0]; - $mailBody = $mailData->mail_body; - $subject = $mailData->mail_subject; - - if (trim($mailData->mail_bcc) != "") - { - $mailBcc = explode(",", $mailData->mail_bcc); - } - } - - $body = str_replace("{name}", $catalog->name, $mailBody); - $body = str_replace("{discount}", Redshop::getConfig()->get('DISCOUNT_PERCENTAGE'), $body); - $body = str_replace("{coupon_code}", $couponCode, $body); - Redshop\Mail\Helper::imgInMail($body); - - if (JFactory::getMailer()->sendMail($from, $fromName, $catalog->email, $subject, $body, 1, null, $mailBcc)) - { - $query->clear() - ->update($db->qn('#__redshop_catalog_request')) - ->set($db->qn('reminder_3') . ' = ' . $db->quote(1)) - ->where($db->qn('catalog_user_id') . ' = ' . $catalog->catalog_user_id); - - $db->setQuery($query)->execute(); - } - } + /** + * Catalog mail function + * + * @return void + * + * @since 2.0.6 + */ + public static function sendMail() + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_catalog_request')) + ->where($db->qn('block') . ' = 0'); + + $catalogs = $db->setQuery($query)->loadObjectList(); + + if (empty($catalogs)) { + return; + } + + $config = JFactory::getConfig(); + $from = $config->get('mailfrom'); + $fromName = $config->get('fromname'); + $formattedDate = JFactory::getDate()->format('Y-m-d'); + + foreach ($catalogs as $catalog) { + self::sendFirstReminder($catalog, $formattedDate, $from, $fromName); + + if ($catalog->reminder_2 == 0) { + self::sendSecondReminder($catalog, $formattedDate, $from, $fromName); + } elseif ($catalog->reminder_3 == 0) { + self::sendThirdReminder($catalog, $formattedDate, $from, $fromName); + } + } + } + + /** + * Method for send first reminder of catalog + * + * @param object $catalog Catalog data + * @param string $currentDate Current date + * @param string $from Email from for send mail + * @param string $fromName Name for send mail + * + * @return void + * + * @since 2.0.6 + */ + public static function sendFirstReminder($catalog = null, $currentDate = '', $from = '', $fromName = '') + { + if (empty($catalog) || !is_object($catalog) || $catalog->reminder_1 != 0) { + return; + } + + $currentDate = empty($currentDate) ? JFactory::getDate()->format('Y-m-d') : $currentDate; + $sendDate = date( + "Y-m-d", + $catalog->registerDate + (Redshop::getConfig()->get('CATALOG_REMINDER_1') * (60 * 60 * 24)) + ); + + if ($currentDate != $sendDate) { + return; + } + + $from = empty($from) ? JFactory::getConfig()->get('mailfrom') : $from; + $fromName = empty($fromName) ? JFactory::getConfig()->get('fromname') : $fromName; + + $mailBody = ""; + $subject = ""; + $mailBcc = null; + $mailData = Redshop\Mail\Helper::getTemplate(0, "catalog_first_reminder"); + + if (count($mailData) > 0) { + $mailData = $mailData[0]; + $mailBody = $mailData->mail_body; + $subject = $mailData->mail_subject; + + if (trim($mailData->mail_bcc) != "") { + $mailBcc = explode(",", $mailData->mail_bcc); + } + } + + $body = str_replace("{name}", $catalog->name, $mailBody); + $body = str_replace("{discount}", Redshop::getConfig()->get('DISCOUNT_PERCENTAGE'), $body); + + Redshop\Mail\Helper::imgInMail($body); + + if (JFactory::getMailer()->sendMail($from, $fromName, $catalog->email, $subject, $body, 1, null, $mailBcc)) { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_catalog_request')) + ->set($db->qn('reminder_1') . ' = ' . $db->quote(1)) + ->where($db->qn('catalog_user_id') . ' = ' . $catalog->catalog_user_id); + + $db->setQuery($query)->execute(); + } + } + + /** + * Method for send second reminder of catalog + * + * @param object $catalog Catalog data + * @param string $currentDate Current date + * @param string $from Email from for send mail + * @param string $fromName Name for send mail + * + * @return void + * + * @since 2.0.6 + */ + public static function sendSecondReminder($catalog = null, $currentDate = '', $from = '', $fromName = '') + { + if (empty($catalog) || !is_object($catalog) || $catalog->reminder_2 != 0) { + return; + } + + $currentDate = empty($currentDate) ? JFactory::getDate()->format('Y-m-d') : $currentDate; + $sendDate = date( + "Y-m-d", + $catalog->registerDate + (Redshop::getConfig()->get('CATALOG_REMINDER_2') * (60 * 60 * 24)) + ); + + if ($currentDate != $sendDate) { + return; + } + + $from = empty($from) ? JFactory::getConfig()->get('mailfrom') : $from; + $fromName = empty($fromName) ? JFactory::getConfig()->get('fromname') : $fromName; + $token = md5(uniqid(mt_rand(), true)); + $token = substr($token, 0, 10); + $startDate = mktime(0, 0, 0, date("m"), date("d"), date("Y")); + $endDate = $startDate + (Redshop::getConfig()->get('DISCOUNT_DURATION') * 23 * 59 * 59); + + $mailBody = ""; + $subject = ""; + $mailBcc = null; + $mailData = Redshop\Mail\Helper::getTemplate(0, "catalog_second_reminder"); + + if (count($mailData) > 0) { + $mailData = $mailData[0]; + $mailBody = $mailData->mail_body; + $subject = $mailData->mail_subject; + + if (trim($mailData->mail_bcc) != "") { + $mailBcc = explode(",", $mailData->mail_bcc); + } + } + + $body = str_replace("{name}", $catalog->name, $mailBody); + $body = str_replace("{days}", Redshop::getConfig()->get('DISCOUNT_DURATION'), $body); + $body = str_replace("{discount}", Redshop::getConfig()->get('DISCOUNT_PERCENTAGE'), $body); + $body = str_replace("{coupon_code}", $token, $body); + Redshop\Mail\Helper::imgInMail($body); + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->qn('id')) + ->from($db->qn('#__users')) + ->where($db->qn('email') . ' = ' . $db->quote($catalog->email)); + + $uid = $db->setQuery($query)->loadResult(); + + $query->clear() + ->insert($db->qn('#__redshop_coupons')) + ->columns( + $db->qn( + array('code', 'type', 'value', 'start_date', 'end_date', 'effect', 'userid', 'published') + ) + ) + ->values( + $db->quote($token) . ',' . $db->quote(1) . ',' . $db->quote( + Redshop::getConfig()->get('DISCOUNT_PERCENTAGE') + ) . ',' . + $db->quote($startDate) . ',' . $db->quote($endDate) . ',' . $db->quote(1) . ',' . $db->quote( + $uid + ) . ',' . $db->quote(1) + ); + + $db->setQuery($query)->execute(); + + if (JFactory::getMailer()->sendMail($from, $fromName, $catalog->email, $subject, $body, 1, null, $mailBcc)) { + $query->clear() + ->update($db->qn('#__redshop_catalog_request')) + ->set($db->qn('reminder_2') . ' = ' . $db->quote(1)) + ->where($db->qn('catalog_user_id') . ' = ' . $catalog->catalog_user_id); + + $db->setQuery($query)->execute(); + } + } + + /** + * Method for send second reminder of catalog + * + * @param object $catalog Catalog data + * @param string $currentDate Current date + * @param string $from Email from for send mail + * @param string $fromName Name for send mail + * + * @return void + * + * @since 2.0.6 + */ + public static function sendThirdReminder($catalog = null, $currentDate = '', $from = '', $fromName = '') + { + if (empty($catalog) || !is_object($catalog) || $catalog->reminder_3 != 0) { + return; + } + + $currentDate = empty($currentDate) ? JFactory::getDate()->format('Y-m-d') : $currentDate; + + // Coupon reminder + $sendDate = date( + "Y-m-d", + $catalog->registerDate + (Redshop::getConfig()->get( + 'DISCOUNT_DURATION' + ) * (60 * 60 * 24)) + (4 * 60 * 60 * 24) + ); + + if ($currentDate != $sendDate) { + return; + } + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->qn('id')) + ->from($db->qn('#__users')) + ->where($db->qn('email') . ' = ' . $db->quote($catalog->email)); + + $uid = $db->setQuery($query)->loadResult(); + + $query->clear() + ->select($db->qn('id')) + ->from($db->qn('#__redshop_coupons')) + ->where($db->qn('userid') . ' = ' . $db->quote($uid)); + + $couponCode = $db->setQuery($query)->loadResult(); + + $from = empty($from) ? JFactory::getConfig()->get('mailfrom') : $from; + $fromName = empty($fromName) ? JFactory::getConfig()->get('fromname') : $fromName; + + $mailBody = ""; + $subject = ""; + $mailBcc = null; + $mailData = Redshop\Mail\Helper::getTemplate(0, "catalog_coupon_reminder"); + + if (count($mailData) > 0) { + $mailData = $mailData[0]; + $mailBody = $mailData->mail_body; + $subject = $mailData->mail_subject; + + if (trim($mailData->mail_bcc) != "") { + $mailBcc = explode(",", $mailData->mail_bcc); + } + } + + $body = str_replace("{name}", $catalog->name, $mailBody); + $body = str_replace("{discount}", Redshop::getConfig()->get('DISCOUNT_PERCENTAGE'), $body); + $body = str_replace("{coupon_code}", $couponCode, $body); + Redshop\Mail\Helper::imgInMail($body); + + if (JFactory::getMailer()->sendMail($from, $fromName, $catalog->email, $subject, $body, 1, null, $mailBcc)) { + $query->clear() + ->update($db->qn('#__redshop_catalog_request')) + ->set($db->qn('reminder_3') . ' = ' . $db->quote(1)) + ->where($db->qn('catalog_user_id') . ' = ' . $catalog->catalog_user_id); + + $db->setQuery($query)->execute(); + } + } } diff --git a/libraries/redshop/helper/category.php b/libraries/redshop/helper/category.php index a9f688478b4..4006d1a29dc 100644 --- a/libraries/redshop/helper/category.php +++ b/libraries/redshop/helper/category.php @@ -16,563 +16,565 @@ */ class RedshopHelperCategory { - protected static $categoryListReverse = array(); - - protected static $categoryChildListReverse = array(); - - /** - * Get category data - * - * @param int $cid Category id - * - * @return mixed - * - * @deprecated 2.0.6 Use RedshopEntityCategory instead - */ - public static function getCategoryById($cid) - { - return RedshopEntityCategory::getInstance($cid)->getItem(); - } - - /** - * Get Category List Reverse Array - * - * @param string $cid Category id - * - * @return array - */ - public static function getCategoryListReverseArray($cid = '0') - { - self::$categoryListReverse = array(); - - if ($category = self::getCategoryById($cid)) - { - if (isset($category->parent_id)) - { - self::getCategoryListRecursion($category->parent_id); - } - } - - return self::$categoryListReverse; - } - - /** - * Get Category List Recursion - * - * @param string $cid Category id - * - * @return void - */ - private static function getCategoryListRecursion($cid = '0') - { - if ($category = self::getCategoryById($cid)) - { - if (isset($category->parent_id)) - { - self::$categoryListReverse[] = $category; - self::getCategoryListRecursion($category->parent_id); - } - } - } - - /** - * Get Category List Array - * - * @param int $categoryId First category level in filter - * @param int $cid Current category id - * - * @return array|mixed - * - * @throws Exception - */ - public static function getCategoryListArray($categoryId = null, $cid = null) - { - global $context; - - $app = JFactory::getApplication(); - $db = JFactory::getDbo(); - $view = $app->input->getCmd('view', ''); - - $categoryMainFilter = $app->getUserStateFromRequest($context . 'category_main_filter', 'category_main_filter', 0); - - if ($categoryId) - { - $cid = (int) $categoryId; - } - - $key = $context . '_' . $view . '_' . $categoryMainFilter . '_' . $cid; - - if (array_key_exists($key, static::$categoryChildListReverse)) - { - return static::$categoryChildListReverse[$key]; - } - - $query = $db->getQuery(true) - ->select( - $db->qn( - array( - 'id', 'parent_id', 'name', 'description', - 'published', 'ordering', 'category_full_image' - ) - ) - ) - ->from($db->qn('#__redshop_category')) - ->where($db->qn('parent_id') . ' != 0') - ->where($db->qn('level') . ' > 0') - ->where($db->qn('published') . ' = 1') - ->order($db->qn('lft')); - - if ($view == 'category') - { - $filter_order = urldecode($app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'ordering')); - $filter_order_Dir = urldecode($app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', '')); - $query->order($db->escape($filter_order . ' ' . $filter_order_Dir)); - } - else - { - $query->order($db->qn('name')); - } - - if ($categoryMainFilter) - { - $query->where($db->qn('name') . ' LIKE ' . $db->q('%' . $categoryMainFilter . '%')); - } - else - { - if ($cid !== null) - { - $query->where($db->qn('parent_id') . ' = ' . (int) $cid); - } - } - - static::$categoryChildListReverse[$key] = null; - - if ($cats = $db->setQuery($query)->loadObjectList()) - { - if ($categoryMainFilter) - { - static::$categoryChildListReverse[$key] = $cats; - - return $cats; - } - - static::$categoryChildListReverse[$key] = array(); - - foreach ($cats as $cat) - { - $cat->name = '- ' . $cat->name; - - static::$categoryChildListReverse[$key][] = $cat; - self::getCategoryChildListRecursion($key, $cat->id); - } - } - - return self::$categoryChildListReverse[$key]; - } - - /** - * Get Category Child List Recursion - * - * @param string $key Key in array Child List - * @param int $cid Category id - * @param int $level Level current category - * - * @return void - */ - protected static function getCategoryChildListRecursion($key, $cid, $level = 1) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select( - $db->qn( - array( - 'id', 'parent_id', 'name', 'description', - 'published', 'ordering', 'category_full_image' - ) - ) - ) - ->from($db->qn('#__redshop_category')) - ->where('parent_id = ' . (int) $cid); - $level++; - - $cats = $db->setQuery($query)->loadObjectList(); - - if (!empty($cats)) - { - foreach ($cats as $cat) - { - $cat->name = str_repeat('- ', $level) . $cat->name; - - static::$categoryChildListReverse[$key][] = $cat; - self::getCategoryChildListRecursion($key, $cat->id, $level); - } - } - } - - /** - * List all categories and return HTML format - * - * @param string $name Name of list - * @param integer $categoryId Only category to show - * @param array $selectedCategories Only select categories from this - * @param integer $size Size of dropdown - * @param boolean $topLevel Add option '-Top-' - * @param boolean $multiple Dropdown is multiple or not - * @param array $disabledFields Fields need to be disabled - * @param integer $width Width in pixel - * - * @return string HTML of dropdown - * - * @since 2.0.0.3 - * - * @throws Exception - */ - public static function listAll($name, $categoryId, $selectedCategories = array(), $size = 1, $topLevel = false, - $multiple = false, $disabledFields = array(), $width = 250) - { - $db = JFactory::getDbo(); - $html = ''; - $query = $db->getQuery(true) - ->select($db->qn('parent_id')) - ->from($db->qn('#__redshop_category')) - ->order($db->qn('lft')); - - if ($categoryId) - { - $query->where($db->qn('id') . ' = ' . $db->q((int) $categoryId)); - } - - // Categories nested - $query->where($db->qn('level') . ' > 0'); - - $db->setQuery($query); - $cats = $db->loadObjectList(); - - if ($cats && Redshop::getConfig()->getBool('PRODUCT_DEFAULT_CATEGORY')) - { - $selectedCategories[] = $cats[0]->parent_id; - } - - $multiple = $multiple ? "multiple=\"multiple\"" : ""; - $id = str_replace('[]', '', $name); - $html .= "\n"; - - return $html; - } - - /** - * List children of category into dropdown with level, - * this is a function will be called recursively. - * - * @param array $selectedCategories Only show selected categories - * @param array $disabledFields Disable fields - * - * @return string HTML of - * - * @since 2.0.0.3 - * - * @throws Exception - */ - public static function listTree($selectedCategories = array(), $disabledFields = array()) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('DISTINCT a.id AS value, a.name AS text, a.level, a.published, a.lft'); - - $subQuery = $db->getQuery(true) - ->select('id, name, level, published, parent_id, lft, rgt') - ->from('#__redshop_category'); - - $query->from('(' . (string) $subQuery . ') AS a') - ->join('LEFT', $db->qn('#__redshop_category') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt') - ->where($db->qn('a.level') . ' > 0'); - $query->order('a.lft ASC'); - - // Get the options. - $db->setQuery($query); - - try - { - $options = $db->loadObjectList(); - } - catch (RuntimeException $exception) - { - throw new Exception($exception->getMessage(), 500); - } - - $html = ""; - - foreach ($options as $key => $option) - { - // Pad the option text with spaces using depth level as a multiplier. - if ($option->published == 1) - { - $option->text = str_repeat('- ', $option->level) . $option->text; - } - else - { - $option->text = str_repeat('- ', $option->level) . '[' . $option->text . ']'; - } - - $selected = ''; - $disabled = ''; - - if (in_array($option->value, $selectedCategories)) - { - $selected = ' selected="selected" '; - } - - if (in_array($option->value, $disabledFields)) - { - $disabled = ' disabled="disabled" '; - } - - $html .= ''; - } - - return $html; - } - - /** - * Build content order by user state from request - * - * @return string - * - * @since 2.0.0.3 - * - * @throws Exception - */ - public static function buildContentOrderBy() - { - $db = JFactory::getDbo(); - global $context; - $app = JFactory::getApplication(); - - $filterOrder = urldecode($app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'ordering')); - $filterOrderDir = urldecode($app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', '')); - - $orderBy = ' ORDER BY ' . $db->escape($filterOrder . ' ' . $filterOrderDir); - - return $orderBy; - } - - /** - * Get root parent categories - * - * @return object - * - * @since 2.0.0.3 - */ - public static function getParentCategories() - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('DISTINCT ' . $db->qn('name')) - ->select($db->qn('id')) - ->from($db->qn('#__redshop_category')) - ->where($db->qn('level') . ' = 1'); - - $db->setQuery($query); - - return $db->loadObjectList(); - } - - /** - * Get category tree - * - * @param string $cid Category ID - * - * @return array - * - * @since 2.0.0.3 - */ - public static function getCategoryTree($cid = '0') - { - if (!isset($GLOBALS['catlist'])) - { - $GLOBALS['catlist'] = array(); - } - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->qn(array('id', 'name', 'parent_id'))) - ->from($db->qn('#__redshop_category')) - ->where($db->qn('parent_id') . ' = ' . $db->q((int) $cid)); - - $db->setQuery($query); - - $cats = $db->loadObjectList(); - - for ($x = 0, $xn = count($cats); $x < $xn; $x++) - { - $cat = $cats[$x]; - $parentId = $cat->id; - $GLOBALS['catlist'][] = $cat; - self::getCategoryTree($parentId); - } - - return $GLOBALS['catlist']; - } - - /** - * Get category product list - * - * @param integer $cid Category ID - * - * @return array - * - * @since 2.0.0.3 - * - */ - public static function getCategoryProductList($cid, $includeProductsFromSubCat = false) - { - return RedshopEntityCategory::getInstance($cid)->getProducts($includeProductsFromSubCat); - } - - /** - * get Root ID - * - * @return integer - * - * @since 2.0.5 - */ - public static function getRootId() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('id')) - ->from($db->qn('#__redshop_category')) - ->where($db->qn('name') . ' = ' . $db->q('ROOT')) - ->where($db->qn('parent_id') . ' = 0') - ->where($db->qn('level') . ' = 0'); - - return $db->setQuery($query)->loadResult(); - } - - /** - * buildQueryFilterProduct - * - * @param integer $categoryId id of main category - * @param array $allCategories array of all categories id (main category or main category & its subcategories) - * @param array $filter Filter data - * - * @return bool|JDatabaseQuery $query The result query - * - * @since 2.1.2 - */ - public static function buildQueryFilterProduct($categoryId, $allCategories = array(), $filters) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('DISTINCT(p.product_id)') - ->from($db->qn('#__redshop_product', 'p')) - ->leftJoin($db->qn('#__redshop_product_category_xref', 'pc') . ' ON ' . $db->qn('pc.product_id') . ' = ' . $db->qn('p.product_id')) - ->where($db->qn('p.published') . ' = 1') - ->where($db->qn('p.expired') . ' = 0') - ->where($db->qn('p.product_parent_id') . ' = 0') - ->group($db->qn('p.product_id')); - - /* query builder for category filters */ - if (empty($allCategories)) - { - $allCategories = array($categoryId); - } - - $query->where($db->qn('pc.category_id') . ' IN (' . implode(',', $allCategories) . ')'); - $filterCategory = $filters['category']; - - if (!empty($filterCategory)) - { - $filterCategory = array_merge(array($categoryId), $filterCategory); - $query->where($db->qn('pc.category_id') . ' IN (' . implode(',', $filterCategory) . ')'); - } - - /* query builder for manufacturer filters */ - $manufacturer = $filters['manufacturer']; - - if ((int) $filters['mid'] > 0) - { - $query->where($db->qn('p.manufacturer_id') . ' = ' . (int) $filters['mid']); - } - elseif (!empty($manufacturer)) - { - $query->where($db->qn('p.manufacturer_id') . ' IN (' . implode(',', $manufacturer) . ')'); - } - - /* query builder for price range filters */ - $priceRange = $filters['filterprice']; - - if (!empty($priceRange)) - { - $min = $priceRange['min']; - $max = $priceRange['max']; - $comparePrice = $db->qn('p.product_price') . ' >= ' . $db->q($min) . ' AND ' . $db->qn('p.product_price') . ' <= ' . $db->q(($max)); - $compareDiscountPrice = $db->qn('p.discount_price') . ' >= ' . $db->q($min) . ' AND ' . $db->qn('p.discount_price') . ' <= ' . $db->q(($max)); - $saleTime = $db->qn('p.discount_stratdate') . ' AND ' . $db->qn('p.discount_enddate'); - $query->where('( CASE WHEN( ' . $db->qn('p.product_on_sale') . ' = 1 AND UNIX_TIMESTAMP() BETWEEN ' - . $saleTime . ') THEN (' - . $compareDiscountPrice . ') ELSE (' - . $comparePrice . ') END )' - ); - } - - /* query builder for attributes */ - $attribute = $filters['attribute_name']; - - foreach ($attribute as $key => $value) - { - $query->leftJoin($db->qn('#__redshop_product_attribute', 'a' . $key) - . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('a' . $key . '.product_id')) - ->where($db->qn('a' . $key . '.attribute_name') . ' = ' . $db->q($key)); - - if (empty($value['property'])) - { - continue; - } - - $query->leftJoin($db->qn('#__redshop_product_attribute_property', 'ap' . $key) - . ' ON ' . $db->qn('a' . $key . '.attribute_id') . ' = ' . $db->qn('ap' . $key . '.attribute_id')) - ->where($db->qn('ap' . $key . '.property_name') . ' IN ("' . implode('","', $value['property']) . '")'); - } - - /* query builder for product's custom fields */ - $customField = $filters['custom_field']; - $key = 0; - $subQuery = array(); - - foreach ($customField as $fieldId => $fieldValues) - { - if (empty($fieldValues)) - { - continue; - } - - foreach ($fieldValues as $value) - { - $subQuery[] = 'FIND_IN_SET("' . $value . '", ' . $db->qn('fd' . $key . '.data_txt') . ')'; - } - - $query->leftJoin($db->qn('#__redshop_fields_data', 'fd' . $key) . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('fd' . $key . '.itemid')) - ->where($db->qn('fd' . $key . '.fieldid') . ' = ' . $db->q((int) $fieldId)); - $key++; - } - - if (!empty($subQuery)) - { - $query->where('(' . implode(' OR ', $subQuery) . ')'); - } - - return $query; - } + protected static $categoryListReverse = array(); + + protected static $categoryChildListReverse = array(); + + /** + * Get Category List Reverse Array + * + * @param string $cid Category id + * + * @return array + */ + public static function getCategoryListReverseArray($cid = '0') + { + self::$categoryListReverse = array(); + + if ($category = self::getCategoryById($cid)) { + if (isset($category->parent_id)) { + self::getCategoryListRecursion($category->parent_id); + } + } + + return self::$categoryListReverse; + } + + /** + * Get category data + * + * @param int $cid Category id + * + * @return mixed + * + * @deprecated 2.0.6 Use RedshopEntityCategory instead + */ + public static function getCategoryById($cid) + { + return RedshopEntityCategory::getInstance($cid)->getItem(); + } + + /** + * Get Category List Recursion + * + * @param string $cid Category id + * + * @return void + */ + private static function getCategoryListRecursion($cid = '0') + { + if ($category = self::getCategoryById($cid)) { + if (isset($category->parent_id)) { + self::$categoryListReverse[] = $category; + self::getCategoryListRecursion($category->parent_id); + } + } + } + + /** + * Get Category List Array + * + * @param int $categoryId First category level in filter + * @param int $cid Current category id + * + * @return array|mixed + * + * @throws Exception + */ + public static function getCategoryListArray($categoryId = null, $cid = null) + { + global $context; + + $app = JFactory::getApplication(); + $db = JFactory::getDbo(); + $view = $app->input->getCmd('view', ''); + + $categoryMainFilter = $app->getUserStateFromRequest( + $context . 'category_main_filter', + 'category_main_filter', + 0 + ); + + if ($categoryId) { + $cid = (int)$categoryId; + } + + $key = $context . '_' . $view . '_' . $categoryMainFilter . '_' . $cid; + + if (array_key_exists($key, static::$categoryChildListReverse)) { + return static::$categoryChildListReverse[$key]; + } + + $query = $db->getQuery(true) + ->select( + $db->qn( + array( + 'id', + 'parent_id', + 'name', + 'description', + 'published', + 'ordering', + 'category_full_image' + ) + ) + ) + ->from($db->qn('#__redshop_category')) + ->where($db->qn('parent_id') . ' != 0') + ->where($db->qn('level') . ' > 0') + ->where($db->qn('published') . ' = 1') + ->order($db->qn('lft')); + + if ($view == 'category') { + $filter_order = urldecode( + $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'ordering') + ); + $filter_order_Dir = urldecode( + $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', '') + ); + $query->order($db->escape($filter_order . ' ' . $filter_order_Dir)); + } else { + $query->order($db->qn('name')); + } + + if ($categoryMainFilter) { + $query->where($db->qn('name') . ' LIKE ' . $db->q('%' . $categoryMainFilter . '%')); + } else { + if ($cid !== null) { + $query->where($db->qn('parent_id') . ' = ' . (int)$cid); + } + } + + static::$categoryChildListReverse[$key] = null; + + if ($cats = $db->setQuery($query)->loadObjectList()) { + if ($categoryMainFilter) { + static::$categoryChildListReverse[$key] = $cats; + + return $cats; + } + + static::$categoryChildListReverse[$key] = array(); + + foreach ($cats as $cat) { + $cat->name = '- ' . $cat->name; + + static::$categoryChildListReverse[$key][] = $cat; + self::getCategoryChildListRecursion($key, $cat->id); + } + } + + return self::$categoryChildListReverse[$key]; + } + + /** + * Get Category Child List Recursion + * + * @param string $key Key in array Child List + * @param int $cid Category id + * @param int $level Level current category + * + * @return void + */ + protected static function getCategoryChildListRecursion($key, $cid, $level = 1) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select( + $db->qn( + array( + 'id', + 'parent_id', + 'name', + 'description', + 'published', + 'ordering', + 'category_full_image' + ) + ) + ) + ->from($db->qn('#__redshop_category')) + ->where('parent_id = ' . (int)$cid); + $level++; + + $cats = $db->setQuery($query)->loadObjectList(); + + if (!empty($cats)) { + foreach ($cats as $cat) { + $cat->name = str_repeat('- ', $level) . $cat->name; + + static::$categoryChildListReverse[$key][] = $cat; + self::getCategoryChildListRecursion($key, $cat->id, $level); + } + } + } + + /** + * List all categories and return HTML format + * + * @param string $name Name of list + * @param integer $categoryId Only category to show + * @param array $selectedCategories Only select categories from this + * @param integer $size Size of dropdown + * @param boolean $topLevel Add option '-Top-' + * @param boolean $multiple Dropdown is multiple or not + * @param array $disabledFields Fields need to be disabled + * @param integer $width Width in pixel + * + * @return string HTML of dropdown + * + * @throws Exception + * @since 2.0.0.3 + * + */ + public static function listAll( + $name, + $categoryId, + $selectedCategories = array(), + $size = 1, + $topLevel = false, + $multiple = false, + $disabledFields = array(), + $width = 250 + ) { + $db = JFactory::getDbo(); + $html = ''; + $query = $db->getQuery(true) + ->select($db->qn('parent_id')) + ->from($db->qn('#__redshop_category')) + ->order($db->qn('lft')); + + if ($categoryId) { + $query->where($db->qn('id') . ' = ' . $db->q((int)$categoryId)); + } + + // Categories nested + $query->where($db->qn('level') . ' > 0'); + + $db->setQuery($query); + $cats = $db->loadObjectList(); + + if ($cats && Redshop::getConfig()->getBool('PRODUCT_DEFAULT_CATEGORY')) { + $selectedCategories[] = $cats[0]->parent_id; + } + + $multiple = $multiple ? "multiple=\"multiple\"" : ""; + $id = str_replace('[]', '', $name); + $html .= "\n"; + + return $html; + } + + /** + * List children of category into dropdown with level, + * this is a function will be called recursively. + * + * @param array $selectedCategories Only show selected categories + * @param array $disabledFields Disable fields + * + * @return string HTML of + * + * @throws Exception + * @since 2.0.0.3 + * + */ + public static function listTree($selectedCategories = array(), $disabledFields = array()) + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('DISTINCT a.id AS value, a.name AS text, a.level, a.published, a.lft'); + + $subQuery = $db->getQuery(true) + ->select('id, name, level, published, parent_id, lft, rgt') + ->from('#__redshop_category'); + + $query->from('(' . (string)$subQuery . ') AS a') + ->join('LEFT', $db->qn('#__redshop_category') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt') + ->where($db->qn('a.level') . ' > 0'); + $query->order('a.lft ASC'); + + // Get the options. + $db->setQuery($query); + + try { + $options = $db->loadObjectList(); + } catch (RuntimeException $exception) { + throw new Exception($exception->getMessage(), 500); + } + + $html = ""; + + foreach ($options as $key => $option) { + // Pad the option text with spaces using depth level as a multiplier. + if ($option->published == 1) { + $option->text = str_repeat('- ', $option->level) . $option->text; + } else { + $option->text = str_repeat('- ', $option->level) . '[' . $option->text . ']'; + } + + $selected = ''; + $disabled = ''; + + if (in_array($option->value, $selectedCategories)) { + $selected = ' selected="selected" '; + } + + if (in_array($option->value, $disabledFields)) { + $disabled = ' disabled="disabled" '; + } + + $html .= ''; + } + + return $html; + } + + /** + * Build content order by user state from request + * + * @return string + * + * @throws Exception + * @since 2.0.0.3 + * + */ + public static function buildContentOrderBy() + { + $db = JFactory::getDbo(); + global $context; + $app = JFactory::getApplication(); + + $filterOrder = urldecode( + $app->getUserStateFromRequest($context . 'filter_order', 'filter_order', 'ordering') + ); + $filterOrderDir = urldecode( + $app->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', '') + ); + + $orderBy = ' ORDER BY ' . $db->escape($filterOrder . ' ' . $filterOrderDir); + + return $orderBy; + } + + /** + * Get root parent categories + * + * @return object + * + * @since 2.0.0.3 + */ + public static function getParentCategories() + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('DISTINCT ' . $db->qn('name')) + ->select($db->qn('id')) + ->from($db->qn('#__redshop_category')) + ->where($db->qn('level') . ' = 1'); + + $db->setQuery($query); + + return $db->loadObjectList(); + } + + /** + * Get category tree + * + * @param string $cid Category ID + * + * @return array + * + * @since 2.0.0.3 + */ + public static function getCategoryTree($cid = '0') + { + if (!isset($GLOBALS['catlist'])) { + $GLOBALS['catlist'] = array(); + } + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->qn(array('id', 'name', 'parent_id'))) + ->from($db->qn('#__redshop_category')) + ->where($db->qn('parent_id') . ' = ' . $db->q((int)$cid)); + + $db->setQuery($query); + + $cats = $db->loadObjectList(); + + for ($x = 0, $xn = count($cats); $x < $xn; $x++) { + $cat = $cats[$x]; + $parentId = $cat->id; + $GLOBALS['catlist'][] = $cat; + self::getCategoryTree($parentId); + } + + return $GLOBALS['catlist']; + } + + /** + * Get category product list + * + * @param integer $cid Category ID + * + * @return array + * + * @since 2.0.0.3 + * + */ + public static function getCategoryProductList($cid, $includeProductsFromSubCat = false) + { + return RedshopEntityCategory::getInstance($cid)->getProducts($includeProductsFromSubCat); + } + + /** + * get Root ID + * + * @return integer + * + * @since 2.0.5 + */ + public static function getRootId() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('id')) + ->from($db->qn('#__redshop_category')) + ->where($db->qn('name') . ' = ' . $db->q('ROOT')) + ->where($db->qn('parent_id') . ' = 0') + ->where($db->qn('level') . ' = 0'); + + return $db->setQuery($query)->loadResult(); + } + + /** + * buildQueryFilterProduct + * + * @param integer $categoryId id of main category + * @param array $allCategories array of all categories id (main category or main category & its subcategories) + * @param array $filter Filter data + * + * @return bool|JDatabaseQuery $query The result query + * + * @since 2.1.2 + */ + public static function buildQueryFilterProduct($categoryId, $allCategories = array(), $filters) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('DISTINCT(p.product_id)') + ->from($db->qn('#__redshop_product', 'p')) + ->leftJoin( + $db->qn('#__redshop_product_category_xref', 'pc') . ' ON ' . $db->qn('pc.product_id') . ' = ' . $db->qn( + 'p.product_id' + ) + ) + ->where($db->qn('p.published') . ' = 1') + ->where($db->qn('p.expired') . ' = 0') + ->where($db->qn('p.product_parent_id') . ' = 0') + ->group($db->qn('p.product_id')); + + /* query builder for category filters */ + if (empty($allCategories)) { + $allCategories = array($categoryId); + } + + $query->where($db->qn('pc.category_id') . ' IN (' . implode(',', $allCategories) . ')'); + $filterCategory = $filters['category']; + + if (!empty($filterCategory)) { + $filterCategory = array_merge(array($categoryId), $filterCategory); + $query->where($db->qn('pc.category_id') . ' IN (' . implode(',', $filterCategory) . ')'); + } + + /* query builder for manufacturer filters */ + $manufacturer = $filters['manufacturer']; + + if ((int)$filters['mid'] > 0) { + $query->where($db->qn('p.manufacturer_id') . ' = ' . (int)$filters['mid']); + } elseif (!empty($manufacturer)) { + $query->where($db->qn('p.manufacturer_id') . ' IN (' . implode(',', $manufacturer) . ')'); + } + + /* query builder for price range filters */ + $priceRange = $filters['filterprice']; + + if (!empty($priceRange)) { + $min = $priceRange['min']; + $max = $priceRange['max']; + $comparePrice = $db->qn('p.product_price') . ' >= ' . $db->q($min) . ' AND ' . $db->qn( + 'p.product_price' + ) . ' <= ' . $db->q(($max)); + $compareDiscountPrice = $db->qn('p.discount_price') . ' >= ' . $db->q($min) . ' AND ' . $db->qn( + 'p.discount_price' + ) . ' <= ' . $db->q(($max)); + $saleTime = $db->qn('p.discount_stratdate') . ' AND ' . $db->qn('p.discount_enddate'); + $query->where( + '( CASE WHEN( ' . $db->qn('p.product_on_sale') . ' = 1 AND UNIX_TIMESTAMP() BETWEEN ' + . $saleTime . ') THEN (' + . $compareDiscountPrice . ') ELSE (' + . $comparePrice . ') END )' + ); + } + + /* query builder for attributes */ + $attribute = $filters['attribute_name']; + + foreach ($attribute as $key => $value) { + $query->leftJoin( + $db->qn('#__redshop_product_attribute', 'a' . $key) + . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('a' . $key . '.product_id') + ) + ->where($db->qn('a' . $key . '.attribute_name') . ' = ' . $db->q($key)); + + if (empty($value['property'])) { + continue; + } + + $query->leftJoin( + $db->qn('#__redshop_product_attribute_property', 'ap' . $key) + . ' ON ' . $db->qn('a' . $key . '.attribute_id') . ' = ' . $db->qn('ap' . $key . '.attribute_id') + ) + ->where($db->qn('ap' . $key . '.property_name') . ' IN ("' . implode('","', $value['property']) . '")'); + } + + /* query builder for product's custom fields */ + $customField = $filters['custom_field']; + $key = 0; + $subQuery = array(); + + foreach ($customField as $fieldId => $fieldValues) { + if (empty($fieldValues)) { + continue; + } + + foreach ($fieldValues as $value) { + $subQuery[] = 'FIND_IN_SET("' . $value . '", ' . $db->qn('fd' . $key . '.data_txt') . ')'; + } + + $query->leftJoin( + $db->qn('#__redshop_fields_data', 'fd' . $key) . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn( + 'fd' . $key . '.itemid' + ) + ) + ->where($db->qn('fd' . $key . '.fieldid') . ' = ' . $db->q((int)$fieldId)); + $key++; + } + + if (!empty($subQuery)) { + $query->where('(' . implode(' OR ', $subQuery) . ')'); + } + + return $query; + } } diff --git a/libraries/redshop/helper/clickatell.php b/libraries/redshop/helper/clickatell.php index 6196bce2fce..7f2b01b39bc 100644 --- a/libraries/redshop/helper/clickatell.php +++ b/libraries/redshop/helper/clickatell.php @@ -18,210 +18,200 @@ */ class RedshopHelperClickatell { - /** - * Method for run process on order ID - * - * @param integer $orderId ID of order - * - * @return void - * - * @since 2.0.6 - * - * @throws Exception - */ - public static function clickatellSMS($orderId) - { - if (Redshop::getConfig()->get('CLICKATELL_ENABLE') <= 0) - { - return; - } - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_order_users_info', 'oui')) - ->leftJoin($db->qn('#__redshop_orders', 'o') . ' ON ' . $db->qn('o.order_id') . ' = ' . $db->qn('oui.order_id')) - ->where($db->qn('oui.order_id') . ' = ' . (int) $orderId) - ->where($db->qn('oui.address_type') . ' = ' . $db->quote('ST')); - - $orderData = $db->setQuery($query)->loadObject(); - - $query->clear() - ->select($db->qn('op.order_payment_name')) - ->select($db->qn('op.payment_method_id')) - ->from($db->qn('#__redshop_order_payment', 'op')) - ->leftJoin($db->qn('#__redshop_orders', 'o') . ' ON ' . $db->qn('o.order_id') . ' = ' . $db->qn('op.order_id')) - ->where($db->qn('op.order_id') . ' = ' . (int) $orderId); - - $paymentData = $db->setQuery($query)->loadObject(); - - $paymentName = $paymentData->payment_method_name; - $paymentMethodId = $paymentData->payment_method_id; - $to = $orderData->phone; - $templateDetail = RedshopHelperTemplate::getTemplate("clicktell_sms_message"); - - $orderShippingClass = 0; - $orderShipping = Redshop\Shipping\Rate::decrypt($orderData->ship_method_id); - - if (isset($orderShipping[0])) - { - $orderShippingClass = $orderShipping[0]; - } - - $query->clear() - ->select('*') - ->from($db->qn('#__redshop_template', 't')) - ->where($db->qn('t.section') . ' = ' . $db->quote('clicktell_sms_message')) - ->where('FIND_IN_SET(' . $db->quote($orderData->order_status) . ', order_status)') - ->where('FIND_IN_SET(' . $db->quote($paymentMethodId) . ', payment_methods)') - ->order($db->qn('id') . ' DESC'); - - $paymentMethod = $db->setQuery($query, 0, 1)->loadObject(); - - $templateDesc = RedshopHelperTemplate::readTemplateFile($paymentMethod->section, $paymentMethod->file_name); - - $message = RedshopTagsReplacer::_( - 'clicktellsms', - $templateDesc, - array('orderData' => $orderData, 'paymentName' => $paymentName) - ); - - if ($message) - { - self::sendMessage(urlencode($message), $to); - } - - $query->clear() - ->select('*') - ->from($db->qn('#__redshop_template', 't')) - ->where($db->qn('t.section') . ' = ' . $db->quote('clicktell_sms_message')) - ->where('FIND_IN_SET(' . $db->quote($orderData->order_status) . ', order_status)') - ->where('FIND_IN_SET(' . $db->quote($orderShippingClass) . ', shipping_methods)') - ->order($db->qn('id') . ' DESC'); - - $shippingMethod = $db->setQuery($query)->loadObject(); - - $message = RedshopTagsReplacer::_( - 'clicktellsms', - $shippingMethod->template_desc, - array('orderData' => $orderData, 'paymentName' => $paymentName) - ); - - if ($message) - { - self::sendMessage(urlencode($message), $to); - } - - if (Redshop::getConfig()->get('CLICKATELL_ORDER_STATUS') == $orderData->order_status) - { - $message = RedshopTagsReplacer::_( - 'clicktellsms', - $templateDetail[0]->template_desc, - array('orderData' => $orderData, 'paymentName' => $paymentName) - ); - - if ($message) - { - self::sendMessage(urlencode($message), $to); - } - } - } - - /** - * Method for replace message - * - * @param string $message Message text - * @param object $orderData Object data - * @param string $paymentName Name of payment - * - * @return mixed - * - * @since 2.0.6 - */ - public static function replaceMessage($message, $orderData, $paymentName) - { - $shippingMethod = ''; - $details = Redshop\Shipping\Rate::decrypt($orderData->ship_method_id); - - if (count($details) > 1) - { - $text = ""; - - if (array_key_exists(2, $details)) - { - $text = " (" . $details[2] . ")"; - } - - $shippingMethod = $details[1] . $text; - } - - $userData = RedshopHelperUser::getUserInformation($orderData->user_id); - - $message = str_replace('{order_id}', $orderData->order_id, $message); - $message = str_replace('{order_status}', $orderData->order_status, $message); - $message = str_replace('{customer_name}', $userData->firstname, $message); - $message = str_replace('{payment_status}', $orderData->order_payment_status, $message); - $message = str_replace('{order_comment}', $orderData->customer_note, $message); - $message = str_replace('{shipping_method}', $shippingMethod, $message); - $message = str_replace('{payment_method}', $paymentName, $message); - - return $message; - } - - /** - * Method for send message - * - * @param string $text Message text - * @param string $to Phone number for send - * - * @return void - * - * @since 2.0.6 - */ - public static function sendMessage($text, $to) - { - // ClickATell username - $user = Redshop::getConfig()->get('CLICKATELL_USERNAME'); - - // ClickATell password - $password = Redshop::getConfig()->get('CLICKATELL_PASSWORD'); - - // Clickatell_api_id - $clickATellAPI = Redshop::getConfig()->get('CLICKATELL_API_ID'); - $baseUrl = "http://api.clickatell.com"; - - // Auth call - $url = $baseUrl . '/http/auth?user=' . $user . '&password=' . $password . '&api_id=' . $clickATellAPI; - - // Do auth call - $result = file($url); - - // Split our response. return string is on first line of the data returned - $session = explode(":", $result[0]); - - if ($session[0] == "OK") - { - // Remove any whitespace - $sessionId = trim($session[1]); - $url = $baseUrl . '/http/sendmsg?session_id=' . $sessionId . '&to=' . $to . '&text=' . $text; - - // Do send sms call - $result = file($url); - $send = explode(":", $result[0]); - - if ($send[0] == "ID") - { - echo "success message ID: " . $send[1]; - } - else - { - JError::raiseWarning(21, "send message failed: "); - } - } - else - { - JError::raiseWarning(21, "Authentication failure: " . $result[0]); - } - } + /** + * Method for run process on order ID + * + * @param integer $orderId ID of order + * + * @return void + * + * @throws Exception + * @since 2.0.6 + * + */ + public static function clickatellSMS($orderId) + { + if (Redshop::getConfig()->get('CLICKATELL_ENABLE') <= 0) { + return; + } + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_order_users_info', 'oui')) + ->leftJoin( + $db->qn('#__redshop_orders', 'o') . ' ON ' . $db->qn('o.order_id') . ' = ' . $db->qn('oui.order_id') + ) + ->where($db->qn('oui.order_id') . ' = ' . (int)$orderId) + ->where($db->qn('oui.address_type') . ' = ' . $db->quote('ST')); + + $orderData = $db->setQuery($query)->loadObject(); + + $query->clear() + ->select($db->qn('op.order_payment_name')) + ->select($db->qn('op.payment_method_id')) + ->from($db->qn('#__redshop_order_payment', 'op')) + ->leftJoin( + $db->qn('#__redshop_orders', 'o') . ' ON ' . $db->qn('o.order_id') . ' = ' . $db->qn('op.order_id') + ) + ->where($db->qn('op.order_id') . ' = ' . (int)$orderId); + + $paymentData = $db->setQuery($query)->loadObject(); + + $paymentName = $paymentData->payment_method_name; + $paymentMethodId = $paymentData->payment_method_id; + $to = $orderData->phone; + $templateDetail = RedshopHelperTemplate::getTemplate("clicktell_sms_message"); + + $orderShippingClass = 0; + $orderShipping = Redshop\Shipping\Rate::decrypt($orderData->ship_method_id); + + if (isset($orderShipping[0])) { + $orderShippingClass = $orderShipping[0]; + } + + $query->clear() + ->select('*') + ->from($db->qn('#__redshop_template', 't')) + ->where($db->qn('t.section') . ' = ' . $db->quote('clicktell_sms_message')) + ->where('FIND_IN_SET(' . $db->quote($orderData->order_status) . ', order_status)') + ->where('FIND_IN_SET(' . $db->quote($paymentMethodId) . ', payment_methods)') + ->order($db->qn('id') . ' DESC'); + + $paymentMethod = $db->setQuery($query, 0, 1)->loadObject(); + + $templateDesc = RedshopHelperTemplate::readTemplateFile($paymentMethod->section, $paymentMethod->file_name); + + $message = RedshopTagsReplacer::_( + 'clicktellsms', + $templateDesc, + array('orderData' => $orderData, 'paymentName' => $paymentName) + ); + + if ($message) { + self::sendMessage(urlencode($message), $to); + } + + $query->clear() + ->select('*') + ->from($db->qn('#__redshop_template', 't')) + ->where($db->qn('t.section') . ' = ' . $db->quote('clicktell_sms_message')) + ->where('FIND_IN_SET(' . $db->quote($orderData->order_status) . ', order_status)') + ->where('FIND_IN_SET(' . $db->quote($orderShippingClass) . ', shipping_methods)') + ->order($db->qn('id') . ' DESC'); + + $shippingMethod = $db->setQuery($query)->loadObject(); + + $message = RedshopTagsReplacer::_( + 'clicktellsms', + $shippingMethod->template_desc, + array('orderData' => $orderData, 'paymentName' => $paymentName) + ); + + if ($message) { + self::sendMessage(urlencode($message), $to); + } + + if (Redshop::getConfig()->get('CLICKATELL_ORDER_STATUS') == $orderData->order_status) { + $message = RedshopTagsReplacer::_( + 'clicktellsms', + $templateDetail[0]->template_desc, + array('orderData' => $orderData, 'paymentName' => $paymentName) + ); + + if ($message) { + self::sendMessage(urlencode($message), $to); + } + } + } + + /** + * Method for send message + * + * @param string $text Message text + * @param string $to Phone number for send + * + * @return void + * + * @since 2.0.6 + */ + public static function sendMessage($text, $to) + { + // ClickATell username + $user = Redshop::getConfig()->get('CLICKATELL_USERNAME'); + + // ClickATell password + $password = Redshop::getConfig()->get('CLICKATELL_PASSWORD'); + + // Clickatell_api_id + $clickATellAPI = Redshop::getConfig()->get('CLICKATELL_API_ID'); + $baseUrl = "http://api.clickatell.com"; + + // Auth call + $url = $baseUrl . '/http/auth?user=' . $user . '&password=' . $password . '&api_id=' . $clickATellAPI; + + // Do auth call + $result = file($url); + + // Split our response. return string is on first line of the data returned + $session = explode(":", $result[0]); + + if ($session[0] == "OK") { + // Remove any whitespace + $sessionId = trim($session[1]); + $url = $baseUrl . '/http/sendmsg?session_id=' . $sessionId . '&to=' . $to . '&text=' . $text; + + // Do send sms call + $result = file($url); + $send = explode(":", $result[0]); + + if ($send[0] == "ID") { + echo "success message ID: " . $send[1]; + } else { + JError::raiseWarning(21, "send message failed: "); + } + } else { + JError::raiseWarning(21, "Authentication failure: " . $result[0]); + } + } + + /** + * Method for replace message + * + * @param string $message Message text + * @param object $orderData Object data + * @param string $paymentName Name of payment + * + * @return mixed + * + * @since 2.0.6 + */ + public static function replaceMessage($message, $orderData, $paymentName) + { + $shippingMethod = ''; + $details = Redshop\Shipping\Rate::decrypt($orderData->ship_method_id); + + if (count($details) > 1) { + $text = ""; + + if (array_key_exists(2, $details)) { + $text = " (" . $details[2] . ")"; + } + + $shippingMethod = $details[1] . $text; + } + + $userData = RedshopHelperUser::getUserInformation($orderData->user_id); + + $message = str_replace('{order_id}', $orderData->order_id, $message); + $message = str_replace('{order_status}', $orderData->order_status, $message); + $message = str_replace('{customer_name}', $userData->firstname, $message); + $message = str_replace('{payment_status}', $orderData->order_payment_status, $message); + $message = str_replace('{order_comment}', $orderData->customer_note, $message); + $message = str_replace('{shipping_method}', $shippingMethod, $message); + $message = str_replace('{payment_method}', $paymentName, $message); + + return $message; + } } diff --git a/libraries/redshop/helper/config.php b/libraries/redshop/helper/config.php index e02885cd2fe..86332e6278c 100644 --- a/libraries/redshop/helper/config.php +++ b/libraries/redshop/helper/config.php @@ -20,374 +20,102 @@ */ class RedshopHelperConfig { - /** - * javascript strings for configuration variables - * - * @var array - * @since 1.5 - */ - protected static $jsStrings = array(); - - /** - * Check if script declaration of config js store is loaded or not. - * - * @var boolean - */ - private static $isLoadScriptDeclaration = false; - - /** - * Configuration - * - * @var Registry - */ - protected $config; - - /** - * Constructor - * - * @param mixed $namespace Namespace. - */ - public function __construct($namespace = '') - { - $this->loadConfig($namespace); - } - - /** - * Magic method to transparently use registry methods on config - * - * @param string $name Name of the function. - * @param array $arguments [0] The name of the variable [1] The default value. - * - * @return mixed - */ - public function __call($name, $arguments) - { - if (method_exists($this->config, $name)) - { - return call_user_func_array(array($this->config, $name), $arguments); - } - - trigger_error('Call to undefined method ' . __CLASS__ . '::' . $name . '()', E_USER_ERROR); - - return false; - } - - /** - * Get the path to this station configuration file - * - * @return string - */ - protected function getConfigurationFilePath() - { - return JPATH_ADMINISTRATOR . '/components/com_redshop/config/config.php'; - } - - /** - * Get the path to this configuration distinct file - * - * @return string - */ - protected function getConfigurationDistFilePath() - { - return JPATH_ADMINISTRATOR . '/components/com_redshop/config/config.dist.php'; - } - - /** - * Check config file is exist - * - * @return boolean Returns TRUE if the file or directory specified by filename exists; FALSE otherwise. - */ - public function isExists() - { - return file_exists($this->getConfigurationFilePath()); - } - - /** - * Default loading is trying to use the associated table - * - * @param mixed $namespace Namespace. - * - * @return self - */ - public function loadConfig($namespace = '') - { - $this->config = new Registry; - - $file = $this->getConfigurationFilePath(); - - if (!JFile::exists($file)) - { - return $this; - } - - include_once $file; - - // Sanitize the namespace. - $namespace = ucfirst((string) preg_replace('/[^A-Z_]/i', '', $namespace)); - - // Build the config name. - $name = 'RedshopConfig' . $namespace; - - // Handle the PHP configuration type. - if (class_exists($name)) - { - // Create the JConfig object - $class = new $name; - - // Load the configuration values into the registry - $this->config->loadObject($class); - } - - return $this; - } - - /** - * Save configuration to file - * - * @param mixed $config Null to avoid binding any data | JRegistry to bind config and save - * - * @throws Exception - * @return boolean - */ - public function save($config = null) - { - if ($config instanceof JRegistry || $config instanceof Registry) - { - $this->config->merge($config); - } - - jimport('joomla.filesystem.path'); - jimport('joomla.filesystem.file'); - - // Set the configuration file path. - $file = $this->getConfigurationFilePath(); - $configFolder = dirname($file); - - if (!is_dir($configFolder) && !mkdir($configFolder, 0755, true)) - { - throw new Exception('Unable to create configuration folder'); - } - - $app = JFactory::getApplication(); - - // Attempt to make the file writable if using FTP. - if (file_exists($file) && JPath::isOwner($file) && !JPath::setPermissions($file, '0644')) - { - $app->enqueueMessage(JText::_('LIB_REDSHOP_ERROR_CONFIGURATION_PHP_NOTWRITABLE'), 'notice'); - } - - // Attempt to write the configuration file as a PHP class named RedshopConfig. - $configuration = $config->toString('PHP', array('class' => 'RedshopConfig', 'closingtag' => false)); - - if (!JFile::write($file, $configuration)) - { - throw new RuntimeException(JText::_('LIB_REDSHOP_ERROR_WRITE_FAILED')); - } - - // Attempt to make the file unwriteable if using FTP. - if (JPath::isOwner($file) && !JPath::setPermissions($file, '0444')) - { - $app->enqueueMessage(JText::_('LIB_REDSHOP_ERROR_CONFIGURATION_PHP_NOTUNWRITABLE'), 'notice'); - } - - return true; - } - - /** - * Save new config file using legacy or legacy styled custom configuration files. - * - * @param string $configFile Path to legacy styled configuration file - * - * @throws exception Throw invalid argument and exception if file is not exist and invalid. - * @return boolean True on success - */ - public function loadLegacy($configFile = null) - { - if ($this->isExists()) - { - return false; - } - - // Try to migrate old configuration - if ($this->loadOldConfig()) - { - return true; - } - - // Check if custom file path is given and exist - if ($configFile && !file_exists($configFile)) - { - throw new InvalidArgumentException(JText::sprintf('LIB_REDSHOP_FILE_IS_NOT_EXIST', $configFile)); - } - - // Priority to custom file given in method argument - if (!$configFile) - { - $legacyConfig = new Redconfiguration; - - // Load from old version configuration - if (file_exists($legacyConfig->configPath)) - { - $configFile = $legacyConfig->configPath; - } - - // Check for distinct configuration file - elseif (file_exists($legacyConfig->configDistPath)) - { - $configFile = $legacyConfig->configDistPath; - } - else - { - throw new Exception(JText::_('LIB_REDSHOP_LEGACY_CONFIG_FILE_IS_NOT_EXIST')); - } - } - - require_once $configFile; - - $allDefinedConstants = get_defined_constants(true); - $configDataArray = $allDefinedConstants['user']; - - if (empty($configDataArray)) - { - throw new Exception(JText::sprintf('LIB_REDSHOP_LEGACY_CONFIG_FILE_IS_NOT_VALID', $configFile)); - } - - try - { - $this->save(new Registry($configDataArray)); - - return true; - } - catch (Exception $e) - { - JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error'); - - return false; - } - } - - /** - * Load Distinct configuration file - * - * @since 1.7 - * - * @return boolean True on success - */ - public function loadDist() - { - // Only load dist file when config file is not exist. - if (!$this->isExists()) - { - jimport('joomla.filesystem.file'); - - if ($this->loadOldConfig()) - { - return true; - } - - return JFile::copy($this->getConfigurationDistFilePath(), $this->getConfigurationFilePath()); - } - - return true; - } - - /** - * Load previous configuration - * - * @return boolean - * - * @throws Exception - */ - protected function loadOldConfig() - { - // Since 1.6 we started moving to new config than try to migrate it - if (version_compare(RedshopHelperJoomla::getManifestValue('version'), '1.6', '<')) - { - JFactory::getApplication()->enqueueMessage(JText::_('COM_REDSHOP_TRY_TO_MIGRATE_PREVIOUS_CONFIGURATION'), 'notice'); - - $oldConfigFile = JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/redshop.cfg.php'; - - // Old configuration file - if (JFile::exists($oldConfigFile)) - { - // New configuration file - require_once JPATH_ADMINISTRATOR . '/components/com_redshop/config/config.dist.php'; - - // Old configuration file - require_once $oldConfigFile; - - // Get new configuration properties - $configClass = new RedshopConfig; - $properties = get_object_vars($configClass); - - // Get old configiration properties - $defined = get_defined_constants(); - - // Replace new configuration values with old one - foreach ($properties as $name => $value) - { - if (in_array($name, $defined)) - { - if (isset($defined[$name])) - { - $properties[$name] = $defined[$name]; - } - } - } - - // Save to config file - $this->save(new Registry($properties)); - JFactory::getApplication()->enqueueMessage(JText::_('COM_REDSHOP_MIGRATED_PREVIOUS_CONFIGURATION'), 'notice'); - - return JFile::delete($oldConfigFile); - } - - JFactory::getApplication()->enqueueMessage(JText::_('COM_REDSHOP_PREVIOUS_CONFIGURATION_NOT_FOUND'), 'warning'); - - return false; - } - - return false; - } - - /** - * Stores redshop configuration strings in the JavaScript language store. - * - * @param string $key The Javascript config string key. - * @param string $value The Javascript config string value. - * - * @return array - * - * @since 1.5 - */ - public static function script($key = null, $value = null) - { - // Add the key to the array if not null. - if ($key !== null) - { - // Assign key to the value - self::$jsStrings[strtoupper($key)] = $value; - } - - return self::$jsStrings; - } - - /** - * Set javascript strings - * - * @return void - */ - public static function scriptDeclaration() - { - if (self::$isLoadScriptDeclaration) - { - return; - } - - // Load redshop script - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/redshop.min.js', false, true); - - JFactory::getDocument()->addScriptDeclaration(' + /** + * javascript strings for configuration variables + * + * @var array + * @since 1.5 + */ + protected static $jsStrings = array(); + + /** + * Check if script declaration of config js store is loaded or not. + * + * @var boolean + */ + private static $isLoadScriptDeclaration = false; + + /** + * Configuration + * + * @var Registry + */ + protected $config; + + /** + * Constructor + * + * @param mixed $namespace Namespace. + */ + public function __construct($namespace = '') + { + $this->loadConfig($namespace); + } + + /** + * Default loading is trying to use the associated table + * + * @param mixed $namespace Namespace. + * + * @return self + */ + public function loadConfig($namespace = '') + { + $this->config = new Registry; + + $file = $this->getConfigurationFilePath(); + + if (!JFile::exists($file)) { + return $this; + } + + include_once $file; + + // Sanitize the namespace. + $namespace = ucfirst((string)preg_replace('/[^A-Z_]/i', '', $namespace)); + + // Build the config name. + $name = 'RedshopConfig' . $namespace; + + // Handle the PHP configuration type. + if (class_exists($name)) { + // Create the JConfig object + $class = new $name; + + // Load the configuration values into the registry + $this->config->loadObject($class); + } + + return $this; + } + + /** + * Get the path to this station configuration file + * + * @return string + */ + protected function getConfigurationFilePath() + { + return JPATH_ADMINISTRATOR . '/components/com_redshop/config/config.php'; + } + + /** + * Set javascript strings + * + * @return void + */ + public static function scriptDeclaration() + { + if (self::$isLoadScriptDeclaration) { + return; + } + + // Load redshop script + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.min.js', false, true); + + JFactory::getDocument()->addScriptDeclaration( + ' (function($) { var RedshopStrings = ' . json_encode(self::script()) . '; if (typeof redSHOP == "undefined") { @@ -417,120 +145,371 @@ public static function scriptDeclaration() } }); })(jQuery); - '); - - self::$isLoadScriptDeclaration = true; - } - - /** - * Method for get config variable of redshop - * - * @param string $name Name of variable. - * @param mixed $default Default data if not found. - * - * @return mixed - * - * @since 2.0.3 - */ - public function get($name = '', $default = null) - { - return empty($this->config) ? $default : $this->config->get($name, $default); - } - - /** - * Method for get config variable of redshop - * - * @param string $name Name of variable. - * @param mixed $value Value of configuration - * - * @return void - * - * @since 2.0.6 - */ - public function set($name = '', $value = null) - { - if (empty($this->config)) - { - return; - } - - $this->config->set($name, $value); - } - - /** - * Method for get config force boolean variable of redshop - * - * @param string $name Name of variable. - * @param boolean $default Default data if not found. - * - * @return boolean - * - * @since 2.0.3 - */ - public function getBool($name = '', $default = false) - { - return empty($this->config) ? boolval($default) : boolval($this->config->get($name, $default)); - } - - /** - * Method for return all config in array format - * - * @return array - * - * @since 2.0.4 - */ - public function toArray() - { - if (empty($this->config)) - { - return array(); - } - - return $this->config->toArray(); - } - - /** - * Method for get config force integer variable of redshop - * - * @param string $name Name of variable. - * @param integer $default Default data if not found. - * - * @return integer - * - * @since 2.1.0 - */ - public function getInt($name = '', $default = 0) - { - return empty($this->config) ? (int) $default : (int) $this->config->get($name, $default); - } - - /** - * Method for get config force string variable of redshop - * - * @param string $name Name of variable. - * @param string $default Default data if not found. - * - * @return string - * - * @since 2.1.0 - */ - public function getString($name = '', $default = '') - { - return empty($this->config) ? (string) $default : (string) $this->config->get($name, $default); - } - - /** - * Method for get config force float variable of redshop - * - * @param string $name Name of variable. - * @param float $default Default data if not found. - * - * @return float - * - * @since 2.1.0 - */ - public function getFloat($name = '', $default = 0.0) - { - return empty($this->config) ? (float) $default : (float) $this->config->get($name, $default); - } + ' + ); + + self::$isLoadScriptDeclaration = true; + } + + /** + * Stores redshop configuration strings in the JavaScript language store. + * + * @param string $key The Javascript config string key. + * @param string $value The Javascript config string value. + * + * @return array + * + * @since 1.5 + */ + public static function script($key = null, $value = null) + { + // Add the key to the array if not null. + if ($key !== null) { + // Assign key to the value + self::$jsStrings[strtoupper($key)] = $value; + } + + return self::$jsStrings; + } + + /** + * Magic method to transparently use registry methods on config + * + * @param string $name Name of the function. + * @param array $arguments [0] The name of the variable [1] The default value. + * + * @return mixed + */ + public function __call($name, $arguments) + { + if (method_exists($this->config, $name)) { + return call_user_func_array(array($this->config, $name), $arguments); + } + + trigger_error('Call to undefined method ' . __CLASS__ . '::' . $name . '()', E_USER_ERROR); + + return false; + } + + /** + * Save new config file using legacy or legacy styled custom configuration files. + * + * @param string $configFile Path to legacy styled configuration file + * + * @return boolean True on success + * @throws exception Throw invalid argument and exception if file is not exist and invalid. + */ + public function loadLegacy($configFile = null) + { + if ($this->isExists()) { + return false; + } + + // Try to migrate old configuration + if ($this->loadOldConfig()) { + return true; + } + + // Check if custom file path is given and exist + if ($configFile && !file_exists($configFile)) { + throw new InvalidArgumentException(JText::sprintf('LIB_REDSHOP_FILE_IS_NOT_EXIST', $configFile)); + } + + // Priority to custom file given in method argument + if (!$configFile) { + $legacyConfig = new Redconfiguration; + + // Load from old version configuration + if (file_exists($legacyConfig->configPath)) { + $configFile = $legacyConfig->configPath; + } // Check for distinct configuration file + elseif (file_exists($legacyConfig->configDistPath)) { + $configFile = $legacyConfig->configDistPath; + } else { + throw new Exception(JText::_('LIB_REDSHOP_LEGACY_CONFIG_FILE_IS_NOT_EXIST')); + } + } + + require_once $configFile; + + $allDefinedConstants = get_defined_constants(true); + $configDataArray = $allDefinedConstants['user']; + + if (empty($configDataArray)) { + throw new Exception(JText::sprintf('LIB_REDSHOP_LEGACY_CONFIG_FILE_IS_NOT_VALID', $configFile)); + } + + try { + $this->save(new Registry($configDataArray)); + + return true; + } catch (Exception $e) { + JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error'); + + return false; + } + } + + /** + * Check config file is exist + * + * @return boolean Returns TRUE if the file or directory specified by filename exists; FALSE otherwise. + */ + public function isExists() + { + return file_exists($this->getConfigurationFilePath()); + } + + /** + * Load previous configuration + * + * @return boolean + * + * @throws Exception + */ + protected function loadOldConfig() + { + // Since 1.6 we started moving to new config than try to migrate it + if (version_compare(RedshopHelperJoomla::getManifestValue('version'), '1.6', '<')) { + JFactory::getApplication()->enqueueMessage( + JText::_('COM_REDSHOP_TRY_TO_MIGRATE_PREVIOUS_CONFIGURATION'), + 'notice' + ); + + $oldConfigFile = JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/redshop.cfg.php'; + + // Old configuration file + if (JFile::exists($oldConfigFile)) { + // New configuration file + require_once JPATH_ADMINISTRATOR . '/components/com_redshop/config/config.dist.php'; + + // Old configuration file + require_once $oldConfigFile; + + // Get new configuration properties + $configClass = new RedshopConfig; + $properties = get_object_vars($configClass); + + // Get old configiration properties + $defined = get_defined_constants(); + + // Replace new configuration values with old one + foreach ($properties as $name => $value) { + if (in_array($name, $defined)) { + if (isset($defined[$name])) { + $properties[$name] = $defined[$name]; + } + } + } + + // Save to config file + $this->save(new Registry($properties)); + JFactory::getApplication()->enqueueMessage( + JText::_('COM_REDSHOP_MIGRATED_PREVIOUS_CONFIGURATION'), + 'notice' + ); + + return JFile::delete($oldConfigFile); + } + + JFactory::getApplication()->enqueueMessage( + JText::_('COM_REDSHOP_PREVIOUS_CONFIGURATION_NOT_FOUND'), + 'warning' + ); + + return false; + } + + return false; + } + + /** + * Save configuration to file + * + * @param mixed $config Null to avoid binding any data | JRegistry to bind config and save + * + * @return boolean + * @throws Exception + */ + public function save($config = null) + { + if ($config instanceof JRegistry || $config instanceof Registry) { + $this->config->merge($config); + } + + jimport('joomla.filesystem.path'); + jimport('joomla.filesystem.file'); + + // Set the configuration file path. + $file = $this->getConfigurationFilePath(); + $configFolder = dirname($file); + + if (!is_dir($configFolder) && !mkdir($configFolder, 0755, true)) { + throw new Exception('Unable to create configuration folder'); + } + + $app = JFactory::getApplication(); + + // Attempt to make the file writable if using FTP. + if (file_exists($file) && JPath::isOwner($file) && !JPath::setPermissions($file, '0644')) { + $app->enqueueMessage(JText::_('LIB_REDSHOP_ERROR_CONFIGURATION_PHP_NOTWRITABLE'), 'notice'); + } + + // Attempt to write the configuration file as a PHP class named RedshopConfig. + $configuration = $config->toString('PHP', array('class' => 'RedshopConfig', 'closingtag' => false)); + + if (!JFile::write($file, $configuration)) { + throw new RuntimeException(JText::_('LIB_REDSHOP_ERROR_WRITE_FAILED')); + } + + // Attempt to make the file unwriteable if using FTP. + if (JPath::isOwner($file) && !JPath::setPermissions($file, '0444')) { + $app->enqueueMessage(JText::_('LIB_REDSHOP_ERROR_CONFIGURATION_PHP_NOTUNWRITABLE'), 'notice'); + } + + return true; + } + + /** + * Load Distinct configuration file + * + * @return boolean True on success + * @since 1.7 + * + */ + public function loadDist() + { + // Only load dist file when config file is not exist. + if (!$this->isExists()) { + jimport('joomla.filesystem.file'); + + if ($this->loadOldConfig()) { + return true; + } + + return JFile::copy($this->getConfigurationDistFilePath(), $this->getConfigurationFilePath()); + } + + return true; + } + + /** + * Get the path to this configuration distinct file + * + * @return string + */ + protected function getConfigurationDistFilePath() + { + return JPATH_ADMINISTRATOR . '/components/com_redshop/config/config.dist.php'; + } + + /** + * Method for get config variable of redshop + * + * @param string $name Name of variable. + * @param mixed $default Default data if not found. + * + * @return mixed + * + * @since 2.0.3 + */ + public function get($name = '', $default = null) + { + return empty($this->config) ? $default : $this->config->get($name, $default); + } + + /** + * Method for get config variable of redshop + * + * @param string $name Name of variable. + * @param mixed $value Value of configuration + * + * @return void + * + * @since 2.0.6 + */ + public function set($name = '', $value = null) + { + if (empty($this->config)) { + return; + } + + $this->config->set($name, $value); + } + + /** + * Method for get config force boolean variable of redshop + * + * @param string $name Name of variable. + * @param boolean $default Default data if not found. + * + * @return boolean + * + * @since 2.0.3 + */ + public function getBool($name = '', $default = false) + { + return empty($this->config) ? boolval($default) : boolval($this->config->get($name, $default)); + } + + /** + * Method for return all config in array format + * + * @return array + * + * @since 2.0.4 + */ + public function toArray() + { + if (empty($this->config)) { + return array(); + } + + return $this->config->toArray(); + } + + /** + * Method for get config force integer variable of redshop + * + * @param string $name Name of variable. + * @param integer $default Default data if not found. + * + * @return integer + * + * @since 2.1.0 + */ + public function getInt($name = '', $default = 0) + { + return empty($this->config) ? (int)$default : (int)$this->config->get($name, $default); + } + + /** + * Method for get config force string variable of redshop + * + * @param string $name Name of variable. + * @param string $default Default data if not found. + * + * @return string + * + * @since 2.1.0 + */ + public function getString($name = '', $default = '') + { + return empty($this->config) ? (string)$default : (string)$this->config->get($name, $default); + } + + /** + * Method for get config force float variable of redshop + * + * @param string $name Name of variable. + * @param float $default Default data if not found. + * + * @return float + * + * @since 2.1.0 + */ + public function getFloat($name = '', $default = 0.0) + { + return empty($this->config) ? (float)$default : (float)$this->config->get($name, $default); + } } diff --git a/libraries/redshop/helper/cron.php b/libraries/redshop/helper/cron.php index a3b355a4c54..30eb0161f56 100644 --- a/libraries/redshop/helper/cron.php +++ b/libraries/redshop/helper/cron.php @@ -16,345 +16,359 @@ */ class RedshopHelperCron { - /** - * Init redshop cron - * - * @return void - */ - public static function init() - { - Redshop\Cron\Product::removeExpiredSales(); - - $today = time(); - $formatDate = date('Y-m-d', $today); - - if (Redshop::getConfig()->get('DISCOUNT_MAIL_SEND')) - { - self::sendMailAfterPurchaseOrder(); - } - - // Calculation to run once in day - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('count(id)') - ->from($db->qn('#__redshop_cron')) - ->where($db->qn('date') . ' = ' . $db->quote($formatDate)); - - $result = $db->setQuery($query)->loadResult(); - - if ($result == 1) - { - return; - } - - // Default $data != 1 - $query->clear() - ->update($db->qn('#__redshop_cron')) - ->set($db->qn('date') . ' = ' . $db->quote($formatDate)) - ->where($db->qn('id') . ' = 1'); - $db->setQuery($query)->execute(); - - if (Redshop::getConfig()->get('SEND_CATALOG_REMINDER_MAIL')) - { - RedshopHelperCatalog::sendMail(); - } - - RedshopHelperSample::sendMail(); - - // Send subscription renewal mail. - self::sendSubscriptionRenewalMail(); - } - - /** - * Catalog mail function - * - * @return void - * - * @deprecated 2.0.6 - */ - public static function sendCatalogMail() - { - RedshopHelperCatalog::sendMail(); - } - - /** - * After purchased order mail function - * - * @return void - */ - public static function sendMailAfterPurchaseOrder() - { - $db = JFactory::getDbo(); - $date = JFactory::getDate(); - $formattedDate = $date->format('Y-m-d'); - $config = JFactory::getConfig(); - $from = $config->get('mailfrom'); - $fromName = $config->get('fromname'); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_orders')) - ->where($db->qn('order_payment_status') . ' = ' . $db->quote('Paid')) - ->where($db->qn('order_status') . ' = ' . $db->quote('C')); - - $mails = $db->setQuery($query)->loadObjectList(); - - JTable::addIncludePath(JPATH_SITE . '/administrator/components/com_redshop/tables'); - - foreach ($mails as $mail) - { - $mailBody = ""; - $subject = ""; - $orderId = $mail->order_id; - $mailBcc = null; - $startDate = mktime(0, 0, 0, date("m"), date("d"), date("Y")); - $endDate = $startDate + (Redshop::getConfig()->get('DISCOUPON_DURATION') * 23 * 59 * 59); - $validEndDate = RedshopHelperDatetime::convertDateFormat($endDate); - - if (Redshop::getConfig()->get('DISCOUPON_PERCENT_OR_TOTAL') == 0) - { - $discountCouponValue = Redshop::getConfig()->get('REDCURRENCY_SYMBOL') . " " - . number_format( - Redshop::getConfig()->get('DISCOUPON_VALUE'), - 2, - Redshop::getConfig()->get('PRICE_SEPERATOR'), - Redshop::getConfig()->get('THOUSAND_SEPERATOR') - ); - } - else - { - $discountCouponValue = Redshop::getConfig()->get('DISCOUPON_VALUE') . " %"; - } - - $query->clear() - ->select('CONCAT(' . $db->qn('firstname') . ',' . $db->quote(' ') . ',' . $db->qn('lastname') . ') AS ' . $db->qn('name')) - ->select($db->qn('user_email', 'email')) - ->from($db->qn('#__redshop_order_users_info')) - ->where($db->qn('order_id') . ' = ' . $orderId) - ->where($db->qn('address_type') . ' = ' . $db->quote('BT')); - - $orderUser = $db->setQuery($query)->loadObject(); - - $query->clear() - ->select($db->qn('amount_left', 'total')) - ->select($db->qn('code')) - ->select($db->qn('end_date')) - ->from($db->qn('#__redshop_coupons')) - ->where($db->qn('order_id') . ' = ' . $orderId) - ->where($db->qn('amount_left') . ' <> 0'); - - $coupon = $db->setQuery($query)->loadObject(); - - if (empty($coupon) && $mail->mail1_status != 0) - { - continue; - } - - $couponCode = ''; - $total = 0; - $couponEndDate = ''; - - if (!empty($coupon)) - { - $total = $coupon->total; - $couponCode = $coupon->code; - $couponEndDate = $coupon->end_date; - } - - $name = ""; - $recipient = ""; - - if (!empty($orderUser)) - { - $recipient = $orderUser->email; - $name = $orderUser->name; - } - - if ($mail->mail1_status == 0 && Redshop::getConfig()->get('DAYS_MAIL1')) - { - $sendDate = date("Y-m-d", $mail->cdate + (Redshop::getConfig()->get('DAYS_MAIL1') * (60 * 60 * 24))); - $firstMailData = Redshop\Mail\Helper::getTemplate(0, "first_mail_after_order_purchased"); - - if (count($firstMailData) > 0) - { - $mailBody = $firstMailData[0]->mail_body; - $subject = $firstMailData[0]->mail_subject; - - if (trim($firstMailData[0]->mail_bcc) != "") - { - $mailBcc = explode(",", $firstMailData[0]->mail_bcc); - } - } - - $pathUrl = '' . JUri::root() . ''; - $body = str_replace("{name}", $name, $mailBody); - $body = str_replace("{url}", $pathUrl, $body); - $body = str_replace("{coupon_amount}", $discountCouponValue, $body); - - if ($formattedDate == $sendDate) - { - $token = md5(uniqid(mt_rand(), true)); - $token = substr($token, 0, 10); - $body = str_replace("{coupon_code}", $token, $body); - $body = str_replace("{coupon_duration}", $validEndDate, $body); - Redshop\Mail\Helper::imgInMail($body); - - if (JFactory::getMailer()->sendMail($from, $fromName, $recipient, $subject, $body, 1, null, $mailBcc)) - { - $couponTable = RedshopTable::getAdminInstance('Coupon'); - $couponTable->code = $token; - $couponTable->type = Redshop::getConfig()->get('DISCOUPON_PERCENT_OR_TOTAL'); - $couponTable->value = Redshop::getConfig()->get('DISCOUPON_VALUE'); - $couponTable->start_date = $startDate; - $couponTable->end_date = $endDate; - $couponTable->effect = 1; - $couponTable->userid = $mail->user_id; - $couponTable->amount_left = 1; - $couponTable->published = 1; - $couponTable->order_id = $orderId; - $couponTable->store(); - - $query->clear() - ->update($db->qn('#__redshop_orders')) - ->set($db->qn('mail1_status') . ' = ' . $db->quote('1')) - ->where($db->qn('order_id') . ' = ' . $orderId); - $db->setQuery($query)->execute(); - } - } - } - elseif ($mail->mail2_status == 0 && Redshop::getConfig()->get('DAYS_MAIL2') && $total != 0) - { - $sendDate = date("Y-m-d", $mail->cdate + (Redshop::getConfig()->get('DAYS_MAIL2') * (59 * 59 * 23))); - $secondMailData = Redshop\Mail\Helper::getTemplate(0, "second_mail_after_order_purchased"); - - if (count($secondMailData) > 0) - { - $mailBody = $secondMailData[0]->mail_body; - $subject = $secondMailData[0]->mail_subject; - - if (trim($secondMailData[0]->mail_bcc) != "") - { - $mailBcc = explode(",", $secondMailData[0]->mail_bcc); - } - } - - $days = RedshopHelperStockroom::getDateDiff($couponEndDate, $startDate); - $pathUrl = '' . JUri::root() . ''; - $body = str_replace("{name}", $name, $mailBody); - $body = str_replace("{url}", $pathUrl, $body); - $body = str_replace("{coupon_amount}", $discountCouponValue, $body); - - if ($days && $formattedDate == $sendDate) - { - $validEndDate = RedshopHelperDatetime::convertDateFormat($couponEndDate); - $body = str_replace("{coupon_code}", $couponCode, $body); - $body = str_replace("{coupon_duration}", $validEndDate, $body); - Redshop\Mail\Helper::imgInMail($body); - - if (JFactory::getMailer()->sendMail($from, $fromName, $recipient, $subject, $body, 1, null, $mailBcc)) - { - $query->clear() - ->update($db->qn('#__redshop_orders')) - ->set($db->qn('mail2_status') . ' = ' . $db->quote('1')) - ->where($db->qn('order_id') . ' = ' . $orderId); - $db->setQuery($query)->execute(); - } - } - } - elseif ($mail->mail3_status == 0 - && (Redshop::getConfig()->get('DAYS_MAIL3') != 0 || Redshop::getConfig()->get('DAYS_MAIL3') != '') && $total != 0 - ) - { - // Coupon reminder - $thirdMailData = Redshop\Mail\Helper::getTemplate(0, "third_mail_after_order_purchased"); - - if (count($thirdMailData) > 0) - { - $mailBody = $thirdMailData[0]->mail_body; - $subject = $thirdMailData[0]->mail_subject; - - if (trim($thirdMailData[0]->mail_bcc) != "") - { - $mailBcc = explode(",", $thirdMailData[0]->mail_bcc); - } - } - - $sendDate = date("Y-m-d", $mail->cdate + (Redshop::getConfig()->get('DAYS_MAIL3') * (60 * 60 * 24))); - $days = RedshopHelperStockroom::getDateDiff($couponEndDate, $startDate); - $pathUrl = '' . JUri::root() . ''; - $body = str_replace("{name}", $name, $mailBody); - $body = str_replace("{url}", $pathUrl, $body); - $body = str_replace("{coupon_amount}", $discountCouponValue, $body); - - if ($days && $formattedDate == $sendDate) - { - $validEndDate = RedshopHelperDatetime::convertDateFormat($couponEndDate); - $body = str_replace("{coupon_code}", $couponCode, $body); - $body = str_replace("{coupon_duration}", $validEndDate, $body); - Redshop\Mail\Helper::imgInMail($body); - - if (JFactory::getMailer()->sendMail($from, $fromName, $recipient, $subject, $body, 1, null, $mailBcc)) - { - $query->clear() - ->update($db->qn('#__redshop_orders')) - ->set($db->qn('mail3_status') . ' = ' . $db->quote('1')) - ->where($db->qn('order_id') . ' = ' . $orderId); - $db->setQuery($query)->execute(); - } - } - } - } - } - - /** - * Color mail function. - * - * @return void - * - * @deprecated 2.0.6 - */ - public static function sendColorMail() - { - RedshopHelperSample::sendMail(); - } - - /** - * Subscription renewal mail function - * - * @return void - */ - public static function sendSubscriptionRenewalMail() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('ps.*') - ->from($db->qn('#__redshop_product_subscribe_detail', 'ps')) - ->leftJoin($db->qn('#__redshop_subscription_renewal', 'r') . ' ON ' . $db->qn('r.product_id') . ' = ' . $db->qn('ps.product_id')) - ->where($db->qn('r.before_no_days') . ' >= DATEDIFF(FROM_UNIXTIME( ps.end_date ),curdate())') - ->where($db->qn('ps.renewal_reminder') . ' = 1'); - - $subscriptions = $db->setQuery($query)->loadObjectList(); - - if (empty($subscriptions)) - { - return; - } - - $productSubscribeIds = array(); - - foreach ($subscriptions as $subscription) - { - // Subscription renewal mail - Redshop\Mail\User::sendSubscriptionRenewal($subscription); - - $productSubscribeIds[] = (int) $subscription->product_subscribe_id; - } - - // Update mail sent field to 0 - $query->clear() - ->update($db->qn('#__redshop_product_subscribe_detail')) - ->set($db->qn('renewal_reminder') . ' = 0') - ->where($db->qn('product_subscribe_id') . ' IN (' . implode(',', $productSubscribeIds) . ')'); - $db->setQuery($query)->execute(); - } + /** + * Init redshop cron + * + * @return void + */ + public static function init() + { + Redshop\Cron\Product::removeExpiredSales(); + + $today = time(); + $formatDate = date('Y-m-d', $today); + + if (Redshop::getConfig()->get('DISCOUNT_MAIL_SEND')) { + self::sendMailAfterPurchaseOrder(); + } + + // Calculation to run once in day + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('count(id)') + ->from($db->qn('#__redshop_cron')) + ->where($db->qn('date') . ' = ' . $db->quote($formatDate)); + + $result = $db->setQuery($query)->loadResult(); + + if ($result == 1) { + return; + } + + // Default $data != 1 + $query->clear() + ->update($db->qn('#__redshop_cron')) + ->set($db->qn('date') . ' = ' . $db->quote($formatDate)) + ->where($db->qn('id') . ' = 1'); + $db->setQuery($query)->execute(); + + if (Redshop::getConfig()->get('SEND_CATALOG_REMINDER_MAIL')) { + RedshopHelperCatalog::sendMail(); + } + + RedshopHelperSample::sendMail(); + + // Send subscription renewal mail. + self::sendSubscriptionRenewalMail(); + } + + /** + * After purchased order mail function + * + * @return void + */ + public static function sendMailAfterPurchaseOrder() + { + $db = JFactory::getDbo(); + $date = JFactory::getDate(); + $formattedDate = $date->format('Y-m-d'); + $config = JFactory::getConfig(); + $from = $config->get('mailfrom'); + $fromName = $config->get('fromname'); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_orders')) + ->where($db->qn('order_payment_status') . ' = ' . $db->quote('Paid')) + ->where($db->qn('order_status') . ' = ' . $db->quote('C')); + + $mails = $db->setQuery($query)->loadObjectList(); + + JTable::addIncludePath(JPATH_SITE . '/administrator/components/com_redshop/tables'); + + foreach ($mails as $mail) { + $mailBody = ""; + $subject = ""; + $orderId = $mail->order_id; + $mailBcc = null; + $startDate = mktime(0, 0, 0, date("m"), date("d"), date("Y")); + $endDate = $startDate + (Redshop::getConfig()->get('DISCOUPON_DURATION') * 23 * 59 * 59); + $validEndDate = RedshopHelperDatetime::convertDateFormat($endDate); + + if (Redshop::getConfig()->get('DISCOUPON_PERCENT_OR_TOTAL') == 0) { + $discountCouponValue = Redshop::getConfig()->get('REDCURRENCY_SYMBOL') . " " + . number_format( + Redshop::getConfig()->get('DISCOUPON_VALUE'), + 2, + Redshop::getConfig()->get('PRICE_SEPERATOR'), + Redshop::getConfig()->get('THOUSAND_SEPERATOR') + ); + } else { + $discountCouponValue = Redshop::getConfig()->get('DISCOUPON_VALUE') . " %"; + } + + $query->clear() + ->select( + 'CONCAT(' . $db->qn('firstname') . ',' . $db->quote(' ') . ',' . $db->qn( + 'lastname' + ) . ') AS ' . $db->qn('name') + ) + ->select($db->qn('user_email', 'email')) + ->from($db->qn('#__redshop_order_users_info')) + ->where($db->qn('order_id') . ' = ' . $orderId) + ->where($db->qn('address_type') . ' = ' . $db->quote('BT')); + + $orderUser = $db->setQuery($query)->loadObject(); + + $query->clear() + ->select($db->qn('amount_left', 'total')) + ->select($db->qn('code')) + ->select($db->qn('end_date')) + ->from($db->qn('#__redshop_coupons')) + ->where($db->qn('order_id') . ' = ' . $orderId) + ->where($db->qn('amount_left') . ' <> 0'); + + $coupon = $db->setQuery($query)->loadObject(); + + if (empty($coupon) && $mail->mail1_status != 0) { + continue; + } + + $couponCode = ''; + $total = 0; + $couponEndDate = ''; + + if (!empty($coupon)) { + $total = $coupon->total; + $couponCode = $coupon->code; + $couponEndDate = $coupon->end_date; + } + + $name = ""; + $recipient = ""; + + if (!empty($orderUser)) { + $recipient = $orderUser->email; + $name = $orderUser->name; + } + + if ($mail->mail1_status == 0 && Redshop::getConfig()->get('DAYS_MAIL1')) { + $sendDate = date( + "Y-m-d", + $mail->cdate + (Redshop::getConfig()->get('DAYS_MAIL1') * (60 * 60 * 24)) + ); + $firstMailData = Redshop\Mail\Helper::getTemplate(0, "first_mail_after_order_purchased"); + + if (count($firstMailData) > 0) { + $mailBody = $firstMailData[0]->mail_body; + $subject = $firstMailData[0]->mail_subject; + + if (trim($firstMailData[0]->mail_bcc) != "") { + $mailBcc = explode(",", $firstMailData[0]->mail_bcc); + } + } + + $pathUrl = '' . JUri::root() . ''; + $body = str_replace("{name}", $name, $mailBody); + $body = str_replace("{url}", $pathUrl, $body); + $body = str_replace("{coupon_amount}", $discountCouponValue, $body); + + if ($formattedDate == $sendDate) { + $token = md5(uniqid(mt_rand(), true)); + $token = substr($token, 0, 10); + $body = str_replace("{coupon_code}", $token, $body); + $body = str_replace("{coupon_duration}", $validEndDate, $body); + Redshop\Mail\Helper::imgInMail($body); + + if (JFactory::getMailer()->sendMail( + $from, + $fromName, + $recipient, + $subject, + $body, + 1, + null, + $mailBcc + )) { + $couponTable = RedshopTable::getAdminInstance('Coupon'); + $couponTable->code = $token; + $couponTable->type = Redshop::getConfig()->get('DISCOUPON_PERCENT_OR_TOTAL'); + $couponTable->value = Redshop::getConfig()->get('DISCOUPON_VALUE'); + $couponTable->start_date = $startDate; + $couponTable->end_date = $endDate; + $couponTable->effect = 1; + $couponTable->userid = $mail->user_id; + $couponTable->amount_left = 1; + $couponTable->published = 1; + $couponTable->order_id = $orderId; + $couponTable->store(); + + $query->clear() + ->update($db->qn('#__redshop_orders')) + ->set($db->qn('mail1_status') . ' = ' . $db->quote('1')) + ->where($db->qn('order_id') . ' = ' . $orderId); + $db->setQuery($query)->execute(); + } + } + } elseif ($mail->mail2_status == 0 && Redshop::getConfig()->get('DAYS_MAIL2') && $total != 0) { + $sendDate = date( + "Y-m-d", + $mail->cdate + (Redshop::getConfig()->get('DAYS_MAIL2') * (59 * 59 * 23)) + ); + $secondMailData = Redshop\Mail\Helper::getTemplate(0, "second_mail_after_order_purchased"); + + if (count($secondMailData) > 0) { + $mailBody = $secondMailData[0]->mail_body; + $subject = $secondMailData[0]->mail_subject; + + if (trim($secondMailData[0]->mail_bcc) != "") { + $mailBcc = explode(",", $secondMailData[0]->mail_bcc); + } + } + + $days = RedshopHelperStockroom::getDateDiff($couponEndDate, $startDate); + $pathUrl = '' . JUri::root() . ''; + $body = str_replace("{name}", $name, $mailBody); + $body = str_replace("{url}", $pathUrl, $body); + $body = str_replace("{coupon_amount}", $discountCouponValue, $body); + + if ($days && $formattedDate == $sendDate) { + $validEndDate = RedshopHelperDatetime::convertDateFormat($couponEndDate); + $body = str_replace("{coupon_code}", $couponCode, $body); + $body = str_replace("{coupon_duration}", $validEndDate, $body); + Redshop\Mail\Helper::imgInMail($body); + + if (JFactory::getMailer()->sendMail( + $from, + $fromName, + $recipient, + $subject, + $body, + 1, + null, + $mailBcc + )) { + $query->clear() + ->update($db->qn('#__redshop_orders')) + ->set($db->qn('mail2_status') . ' = ' . $db->quote('1')) + ->where($db->qn('order_id') . ' = ' . $orderId); + $db->setQuery($query)->execute(); + } + } + } elseif ($mail->mail3_status == 0 + && (Redshop::getConfig()->get('DAYS_MAIL3') != 0 || Redshop::getConfig()->get( + 'DAYS_MAIL3' + ) != '') && $total != 0 + ) { + // Coupon reminder + $thirdMailData = Redshop\Mail\Helper::getTemplate(0, "third_mail_after_order_purchased"); + + if (count($thirdMailData) > 0) { + $mailBody = $thirdMailData[0]->mail_body; + $subject = $thirdMailData[0]->mail_subject; + + if (trim($thirdMailData[0]->mail_bcc) != "") { + $mailBcc = explode(",", $thirdMailData[0]->mail_bcc); + } + } + + $sendDate = date("Y-m-d", $mail->cdate + (Redshop::getConfig()->get('DAYS_MAIL3') * (60 * 60 * 24))); + $days = RedshopHelperStockroom::getDateDiff($couponEndDate, $startDate); + $pathUrl = '' . JUri::root() . ''; + $body = str_replace("{name}", $name, $mailBody); + $body = str_replace("{url}", $pathUrl, $body); + $body = str_replace("{coupon_amount}", $discountCouponValue, $body); + + if ($days && $formattedDate == $sendDate) { + $validEndDate = RedshopHelperDatetime::convertDateFormat($couponEndDate); + $body = str_replace("{coupon_code}", $couponCode, $body); + $body = str_replace("{coupon_duration}", $validEndDate, $body); + Redshop\Mail\Helper::imgInMail($body); + + if (JFactory::getMailer()->sendMail( + $from, + $fromName, + $recipient, + $subject, + $body, + 1, + null, + $mailBcc + )) { + $query->clear() + ->update($db->qn('#__redshop_orders')) + ->set($db->qn('mail3_status') . ' = ' . $db->quote('1')) + ->where($db->qn('order_id') . ' = ' . $orderId); + $db->setQuery($query)->execute(); + } + } + } + } + } + + /** + * Subscription renewal mail function + * + * @return void + */ + public static function sendSubscriptionRenewalMail() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('ps.*') + ->from($db->qn('#__redshop_product_subscribe_detail', 'ps')) + ->leftJoin( + $db->qn('#__redshop_subscription_renewal', 'r') . ' ON ' . $db->qn('r.product_id') . ' = ' . $db->qn( + 'ps.product_id' + ) + ) + ->where($db->qn('r.before_no_days') . ' >= DATEDIFF(FROM_UNIXTIME( ps.end_date ),curdate())') + ->where($db->qn('ps.renewal_reminder') . ' = 1'); + + $subscriptions = $db->setQuery($query)->loadObjectList(); + + if (empty($subscriptions)) { + return; + } + + $productSubscribeIds = array(); + + foreach ($subscriptions as $subscription) { + // Subscription renewal mail + Redshop\Mail\User::sendSubscriptionRenewal($subscription); + + $productSubscribeIds[] = (int)$subscription->product_subscribe_id; + } + + // Update mail sent field to 0 + $query->clear() + ->update($db->qn('#__redshop_product_subscribe_detail')) + ->set($db->qn('renewal_reminder') . ' = 0') + ->where($db->qn('product_subscribe_id') . ' IN (' . implode(',', $productSubscribeIds) . ')'); + $db->setQuery($query)->execute(); + } + + /** + * Catalog mail function + * + * @return void + * + * @deprecated 2.0.6 + */ + public static function sendCatalogMail() + { + RedshopHelperCatalog::sendMail(); + } + + /** + * Color mail function. + * + * @return void + * + * @deprecated 2.0.6 + */ + public static function sendColorMail() + { + RedshopHelperSample::sendMail(); + } } diff --git a/libraries/redshop/helper/currency.php b/libraries/redshop/helper/currency.php index 834c3e7b25a..690f8b6f9d0 100644 --- a/libraries/redshop/helper/currency.php +++ b/libraries/redshop/helper/currency.php @@ -19,64 +19,60 @@ */ class RedshopHelperCurrency { - /** - * Initializes the global currency converter array - * - * @return mixed - * - * @since 2.0.6 - * - * @throws Exception - */ - public static function init() - { - Currency::getInstance()->init(); - } + /** + * Initializes the global currency converter array + * + * @return mixed + * + * @throws Exception + * @since 2.0.6 + * + */ + public static function init() + { + Currency::getInstance()->init(); + } - /** - * Convert currency - * - * @param float $amountA Amount to convert - * @param string $currA Base Currency code - * @param string $currB Currency code in which need amount to be converted - * - * @return float Converted amount - * - * @since 2.0.6 - */ - public static function convert($amountA, $currA = '', $currB = '') - { - JPluginHelper::importPlugin('redshop_product'); - $result = RedshopHelperUtility::getDispatcher()->trigger('onConverCurrency', array(&$amountA, $currA, $currB)); + /** + * Convert currency + * + * @param float $amountA Amount to convert + * @param string $currA Base Currency code + * @param string $currB Currency code in which need amount to be converted + * + * @return float Converted amount + * + * @since 2.0.6 + */ + public static function convert($amountA, $currA = '', $currB = '') + { + JPluginHelper::importPlugin('redshop_product'); + $result = RedshopHelperUtility::getDispatcher()->trigger('onConverCurrency', array(&$amountA, $currA, $currB)); - if (in_array(true, $result, true)) - { - return $amountA; - } + if (in_array(true, $result, true)) { + return $amountA; + } - if (Redshop::getConfig()->get('CURRENCY_LIBRARIES') == 1) - { - return CurrencyLayer::getInstance()->convert($amountA, $currA, $currB); - } - else - { - return Currency::getInstance()->convert($amountA, $currA, $currB); - } - } + if (Redshop::getConfig()->get('CURRENCY_LIBRARIES') == 1) { + return CurrencyLayer::getInstance()->convert($amountA, $currA, $currB); + } else { + return Currency::getInstance()->convert($amountA, $currA, $currB); + } + } - /** - * Method to get Currency Numeric code / ISO code - * - * @param string $code Currency Code - * - * @todo Add numeric code into table #_redshop_currency "redSHOP Currency Detail" - * - * @return string Currency Numeric Code - * - * @since 2.0.6 Use Redshop\Currency\Currency instead. - */ - public static function getISOCode($code) - { - return Currency::getInstance()->getISOCode($code); - } + /** + * Method to get Currency Numeric code / ISO code + * + * @param string $code Currency Code + * + * @return string Currency Numeric Code + * + * @todo Add numeric code into table #_redshop_currency "redSHOP Currency Detail" + * + * @since 2.0.6 Use Redshop\Currency\Currency instead. + */ + public static function getISOCode($code) + { + return Currency::getInstance()->getISOCode($code); + } } diff --git a/libraries/redshop/helper/datetime.php b/libraries/redshop/helper/datetime.php index af4805cfb3a..ea6613e571d 100644 --- a/libraries/redshop/helper/datetime.php +++ b/libraries/redshop/helper/datetime.php @@ -18,216 +18,207 @@ */ class RedshopHelperDatetime { - /** - * Generate timestamp to middle night or early morning - * - * @param int $inputTimestamp Input timestamp - * @param bool $night At middle night - * - * @return integer - */ - public static function generateTimestamp($inputTimestamp, $night = true) - { - // Convert to date string - $date = date('Y-m-d', $inputTimestamp); - - // Skip add time with $night if there are specific time. - if (empty($inputTimestamp)) - { - $date = new DateTime($date); - - return $date->getTimestamp(); - } - - if ($night) - { - $date = $date . ' 23:59:59'; - $date = new DateTime($date); - } - else - { - $date = $date . ' 00:00:01'; - $date = new DateTime($date); - } - - return $date->getTimestamp(); - } - - /** - * Method to convert date according to format - * - * @param int $date Date time (Unix format). - * - * @return string - * - * @since 2.0.3 - */ - public static function convertDateFormat($date = 0) - { - if ($date <= 0) - { - $date = time(); - } - - $format = Redshop::getConfig()->get('DEFAULT_DATEFORMAT', 'Y-m-d'); - $format = empty($format) ? 'Y-m-d' : $format; - - $convertFormat = date($format, $date); - - if (strpos($format, "M") !== false) - { - $convertFormat = str_replace("Jan", JText::_('COM_REDSHOP_JAN'), $convertFormat); - $convertFormat = str_replace("Feb", JText::_('COM_REDSHOP_FEB'), $convertFormat); - $convertFormat = str_replace("Mar", JText::_('COM_REDSHOP_MAR'), $convertFormat); - $convertFormat = str_replace("Apr", JText::_('COM_REDSHOP_APR'), $convertFormat); - $convertFormat = str_replace("May", JText::_('COM_REDSHOP_MAY'), $convertFormat); - $convertFormat = str_replace("Jun", JText::_('COM_REDSHOP_JUN'), $convertFormat); - $convertFormat = str_replace("Jul", JText::_('COM_REDSHOP_JUL'), $convertFormat); - $convertFormat = str_replace("Aug", JText::_('COM_REDSHOP_AUG'), $convertFormat); - $convertFormat = str_replace("Sep", JText::_('COM_REDSHOP_SEP'), $convertFormat); - $convertFormat = str_replace("Oct", JText::_('COM_REDSHOP_OCT'), $convertFormat); - $convertFormat = str_replace("Nov", JText::_('COM_REDSHOP_NOV'), $convertFormat); - $convertFormat = str_replace("Dec", JText::_('COM_REDSHOP_DEC'), $convertFormat); - } - - if (strpos($format, "F") !== false) - { - $convertFormat = str_replace("January", JText::_('COM_REDSHOP_JANUARY'), $convertFormat); - $convertFormat = str_replace("February", JText::_('COM_REDSHOP_FEBRUARY'), $convertFormat); - $convertFormat = str_replace("March", JText::_('COM_REDSHOP_MARCH'), $convertFormat); - $convertFormat = str_replace("April", JText::_('COM_REDSHOP_APRIL'), $convertFormat); - $convertFormat = str_replace("May", JText::_('COM_REDSHOP_MAY'), $convertFormat); - $convertFormat = str_replace("June", JText::_('COM_REDSHOP_JUNE'), $convertFormat); - $convertFormat = str_replace("July", JText::_('COM_REDSHOP_JULY'), $convertFormat); - $convertFormat = str_replace("August", JText::_('COM_REDSHOP_AUGUST'), $convertFormat); - $convertFormat = str_replace("September", JText::_('COM_REDSHOP_SEPTEMBER'), $convertFormat); - $convertFormat = str_replace("October", JText::_('COM_REDSHOP_OCTOBER'), $convertFormat); - $convertFormat = str_replace("November", JText::_('COM_REDSHOP_NOVEMBER'), $convertFormat); - $convertFormat = str_replace("December", JText::_('COM_REDSHOP_DECEMBER'), $convertFormat); - } - - if (strpos($format, "D") !== false) - { - $convertFormat = str_replace("Mon", JText::_('COM_REDSHOP_MON'), $convertFormat); - $convertFormat = str_replace("Tue", JText::_('COM_REDSHOP_TUE'), $convertFormat); - $convertFormat = str_replace("Wed", JText::_('COM_REDSHOP_WED'), $convertFormat); - $convertFormat = str_replace("Thu", JText::_('COM_REDSHOP_THU'), $convertFormat); - $convertFormat = str_replace("Fri", JText::_('COM_REDSHOP_FRI'), $convertFormat); - $convertFormat = str_replace("Sat", JText::_('COM_REDSHOP_SAT'), $convertFormat); - $convertFormat = str_replace("Sun", JText::_('COM_REDSHOP_SUN'), $convertFormat); - } - - if (strpos($format, "l") !== false) - { - $convertFormat = str_replace("Monday", JText::_('COM_REDSHOP_MONDAY'), $convertFormat); - $convertFormat = str_replace("Tuesday", JText::_('COM_REDSHOP_TUESDAY'), $convertFormat); - $convertFormat = str_replace("Wednesday", JText::_('COM_REDSHOP_WEDNESDAY'), $convertFormat); - $convertFormat = str_replace("Thursday", JText::_('COM_REDSHOP_THURSDAY'), $convertFormat); - $convertFormat = str_replace("Friday", JText::_('COM_REDSHOP_FRIDAY'), $convertFormat); - $convertFormat = str_replace("Saturday", JText::_('COM_REDSHOP_SATURDAY'), $convertFormat); - $convertFormat = str_replace("Sunday", JText::_('COM_REDSHOP_SUNDAY'), $convertFormat); - } - - return $convertFormat; - } - - /** - * Method to get date format - * - * @return array - * - * @since 2.0.6 - */ - public static function getDateFormat() - { - $option = array(); - $mon = JText::_(strtoupper(date("M"))); - $month = JText::_(strtoupper(date("F"))); - $wk = JText::_(strtoupper(date("D"))); - $week = JText::_(strtoupper(date("l"))); - - $option[] = JHtml::_('select.option', '0', JText::_('COM_REDSHOP_SELECT')); - $option[] = JHtml::_('select.option', 'Y-m-d', date("Y-m-d")); - $option[] = JHtml::_('select.option', 'd-m-Y', date("d-m-Y")); - $option[] = JHtml::_('select.option', 'd.m.Y', date("d.m.Y")); - $option[] = JHtml::_('select.option', 'Y/m/d', date("Y/m/d")); - $option[] = JHtml::_('select.option', 'd/m/Y', date("d/m/Y")); - $option[] = JHtml::_('select.option', 'm/d/y', date("m/d/y")); - $option[] = JHtml::_('select.option', 'm-d-y', date("m-d-y")); - $option[] = JHtml::_('select.option', 'm.d.y', date("m.d.y")); - $option[] = JHtml::_('select.option', 'm/d/Y', date("m/d/Y")); - $option[] = JHtml::_('select.option', 'm-d-Y', date("m-d-Y")); - $option[] = JHtml::_('select.option', 'm.d.Y', date("m.d.Y")); - $option[] = JHtml::_('select.option', 'd/M/Y', date("d/") . $mon . date("/Y")); - $option[] = JHtml::_('select.option', 'M d,Y', $mon . date(" d, Y")); - $option[] = JHtml::_('select.option', 'd M Y', date("d ") . $mon . date(" Y")); - $option[] = JHtml::_('select.option', 'd M Y, h:i:s', date("d ") . $mon . date(" Y, h:i:s")); - $option[] = JHtml::_('select.option', 'd M Y, h:i A', date("d ") . $mon . date(" Y, h:i A")); - $option[] = JHtml::_('select.option', 'd-m-Y, h:i:A', date("d-m-Y, h:i:A")); - $option[] = JHtml::_('select.option', 'd.m.Y, h:i:A', date("d.m.Y, h:i:A")); - $option[] = JHtml::_('select.option', 'd/m/Y, h:i:A', date("d/m/Y, h:i:A")); - $option[] = JHtml::_('select.option', 'd M Y, H:i:s', date("d ") . $mon . date(" Y, H:i:s")); - $option[] = JHtml::_('select.option', 'd-m-Y, H:i:s', date("d-m-Y, H:i:s")); - $option[] = JHtml::_('select.option', 'd.m.Y, H:i:s', date("d.m.Y, H:i:s")); - $option[] = JHtml::_('select.option', 'd/m/Y, H:i:s', date("d/m/Y, H:i:s")); - $option[] = JHtml::_('select.option', 'F d, Y', $month . date(" d, Y")); - $option[] = JHtml::_('select.option', 'D M d, Y', $wk . " " . $mon . date(" d, Y")); - $option[] = JHtml::_('select.option', 'l F d, Y', $week . " " . $month . date(" d, Y")); - - return $option; - } - - /** - * Method for convert PHP date format to MomentJS date format. - * - * @param string $format PHP date format - * - * @return string - * - * @since 2.1.0 - */ - public static function convertPHPToMomentFormat($format) - { - $replacements = [ - 'd' => 'DD', - 'D' => 'ddd', - 'j' => 'D', - 'l' => 'dddd', - 'N' => 'E', - 'S' => 'o', - 'w' => 'e', - 'z' => 'DDD', - 'W' => 'W', - 'F' => 'MMMM', - 'm' => 'MM', - 'M' => 'MMM', - 'n' => 'M', - 't' => '', // No equivalent - 'L' => '', // No equivalent - 'o' => 'YYYY', - 'Y' => 'YYYY', - 'y' => 'YY', - 'a' => 'a', - 'A' => 'A', - 'B' => '', // No equivalent - 'g' => 'h', - 'G' => 'H', - 'h' => 'hh', - 'H' => 'HH', - 'i' => 'mm', - 's' => 'ss', - 'u' => 'SSS', - 'e' => 'zz', // Deprecated since version 1.6.0 of moment.js - 'I' => '', // No equivalent - 'O' => '', // No equivalent - 'P' => '', // No equivalent - 'T' => '', // No equivalent - 'Z' => '', // No equivalent - 'c' => '', // No equivalent - 'r' => '', // No equivalent - 'U' => 'X', - ]; - - return strtr($format, $replacements); - } + /** + * Generate timestamp to middle night or early morning + * + * @param int $inputTimestamp Input timestamp + * @param bool $night At middle night + * + * @return integer + */ + public static function generateTimestamp($inputTimestamp, $night = true) + { + // Convert to date string + $date = date('Y-m-d', $inputTimestamp); + + // Skip add time with $night if there are specific time. + if (empty($inputTimestamp)) { + $date = new DateTime($date); + + return $date->getTimestamp(); + } + + if ($night) { + $date = $date . ' 23:59:59'; + $date = new DateTime($date); + } else { + $date = $date . ' 00:00:01'; + $date = new DateTime($date); + } + + return $date->getTimestamp(); + } + + /** + * Method to convert date according to format + * + * @param int $date Date time (Unix format). + * + * @return string + * + * @since 2.0.3 + */ + public static function convertDateFormat($date = 0) + { + if ($date <= 0) { + $date = time(); + } + + $format = Redshop::getConfig()->get('DEFAULT_DATEFORMAT', 'Y-m-d'); + $format = empty($format) ? 'Y-m-d' : $format; + + $convertFormat = date($format, $date); + + if (strpos($format, "M") !== false) { + $convertFormat = str_replace("Jan", JText::_('COM_REDSHOP_JAN'), $convertFormat); + $convertFormat = str_replace("Feb", JText::_('COM_REDSHOP_FEB'), $convertFormat); + $convertFormat = str_replace("Mar", JText::_('COM_REDSHOP_MAR'), $convertFormat); + $convertFormat = str_replace("Apr", JText::_('COM_REDSHOP_APR'), $convertFormat); + $convertFormat = str_replace("May", JText::_('COM_REDSHOP_MAY'), $convertFormat); + $convertFormat = str_replace("Jun", JText::_('COM_REDSHOP_JUN'), $convertFormat); + $convertFormat = str_replace("Jul", JText::_('COM_REDSHOP_JUL'), $convertFormat); + $convertFormat = str_replace("Aug", JText::_('COM_REDSHOP_AUG'), $convertFormat); + $convertFormat = str_replace("Sep", JText::_('COM_REDSHOP_SEP'), $convertFormat); + $convertFormat = str_replace("Oct", JText::_('COM_REDSHOP_OCT'), $convertFormat); + $convertFormat = str_replace("Nov", JText::_('COM_REDSHOP_NOV'), $convertFormat); + $convertFormat = str_replace("Dec", JText::_('COM_REDSHOP_DEC'), $convertFormat); + } + + if (strpos($format, "F") !== false) { + $convertFormat = str_replace("January", JText::_('COM_REDSHOP_JANUARY'), $convertFormat); + $convertFormat = str_replace("February", JText::_('COM_REDSHOP_FEBRUARY'), $convertFormat); + $convertFormat = str_replace("March", JText::_('COM_REDSHOP_MARCH'), $convertFormat); + $convertFormat = str_replace("April", JText::_('COM_REDSHOP_APRIL'), $convertFormat); + $convertFormat = str_replace("May", JText::_('COM_REDSHOP_MAY'), $convertFormat); + $convertFormat = str_replace("June", JText::_('COM_REDSHOP_JUNE'), $convertFormat); + $convertFormat = str_replace("July", JText::_('COM_REDSHOP_JULY'), $convertFormat); + $convertFormat = str_replace("August", JText::_('COM_REDSHOP_AUGUST'), $convertFormat); + $convertFormat = str_replace("September", JText::_('COM_REDSHOP_SEPTEMBER'), $convertFormat); + $convertFormat = str_replace("October", JText::_('COM_REDSHOP_OCTOBER'), $convertFormat); + $convertFormat = str_replace("November", JText::_('COM_REDSHOP_NOVEMBER'), $convertFormat); + $convertFormat = str_replace("December", JText::_('COM_REDSHOP_DECEMBER'), $convertFormat); + } + + if (strpos($format, "D") !== false) { + $convertFormat = str_replace("Mon", JText::_('COM_REDSHOP_MON'), $convertFormat); + $convertFormat = str_replace("Tue", JText::_('COM_REDSHOP_TUE'), $convertFormat); + $convertFormat = str_replace("Wed", JText::_('COM_REDSHOP_WED'), $convertFormat); + $convertFormat = str_replace("Thu", JText::_('COM_REDSHOP_THU'), $convertFormat); + $convertFormat = str_replace("Fri", JText::_('COM_REDSHOP_FRI'), $convertFormat); + $convertFormat = str_replace("Sat", JText::_('COM_REDSHOP_SAT'), $convertFormat); + $convertFormat = str_replace("Sun", JText::_('COM_REDSHOP_SUN'), $convertFormat); + } + + if (strpos($format, "l") !== false) { + $convertFormat = str_replace("Monday", JText::_('COM_REDSHOP_MONDAY'), $convertFormat); + $convertFormat = str_replace("Tuesday", JText::_('COM_REDSHOP_TUESDAY'), $convertFormat); + $convertFormat = str_replace("Wednesday", JText::_('COM_REDSHOP_WEDNESDAY'), $convertFormat); + $convertFormat = str_replace("Thursday", JText::_('COM_REDSHOP_THURSDAY'), $convertFormat); + $convertFormat = str_replace("Friday", JText::_('COM_REDSHOP_FRIDAY'), $convertFormat); + $convertFormat = str_replace("Saturday", JText::_('COM_REDSHOP_SATURDAY'), $convertFormat); + $convertFormat = str_replace("Sunday", JText::_('COM_REDSHOP_SUNDAY'), $convertFormat); + } + + return $convertFormat; + } + + /** + * Method to get date format + * + * @return array + * + * @since 2.0.6 + */ + public static function getDateFormat() + { + $option = array(); + $mon = JText::_(strtoupper(date("M"))); + $month = JText::_(strtoupper(date("F"))); + $wk = JText::_(strtoupper(date("D"))); + $week = JText::_(strtoupper(date("l"))); + + $option[] = JHtml::_('select.option', '0', JText::_('COM_REDSHOP_SELECT')); + $option[] = JHtml::_('select.option', 'Y-m-d', date("Y-m-d")); + $option[] = JHtml::_('select.option', 'd-m-Y', date("d-m-Y")); + $option[] = JHtml::_('select.option', 'd.m.Y', date("d.m.Y")); + $option[] = JHtml::_('select.option', 'Y/m/d', date("Y/m/d")); + $option[] = JHtml::_('select.option', 'd/m/Y', date("d/m/Y")); + $option[] = JHtml::_('select.option', 'm/d/y', date("m/d/y")); + $option[] = JHtml::_('select.option', 'm-d-y', date("m-d-y")); + $option[] = JHtml::_('select.option', 'm.d.y', date("m.d.y")); + $option[] = JHtml::_('select.option', 'm/d/Y', date("m/d/Y")); + $option[] = JHtml::_('select.option', 'm-d-Y', date("m-d-Y")); + $option[] = JHtml::_('select.option', 'm.d.Y', date("m.d.Y")); + $option[] = JHtml::_('select.option', 'd/M/Y', date("d/") . $mon . date("/Y")); + $option[] = JHtml::_('select.option', 'M d,Y', $mon . date(" d, Y")); + $option[] = JHtml::_('select.option', 'd M Y', date("d ") . $mon . date(" Y")); + $option[] = JHtml::_('select.option', 'd M Y, h:i:s', date("d ") . $mon . date(" Y, h:i:s")); + $option[] = JHtml::_('select.option', 'd M Y, h:i A', date("d ") . $mon . date(" Y, h:i A")); + $option[] = JHtml::_('select.option', 'd-m-Y, h:i:A', date("d-m-Y, h:i:A")); + $option[] = JHtml::_('select.option', 'd.m.Y, h:i:A', date("d.m.Y, h:i:A")); + $option[] = JHtml::_('select.option', 'd/m/Y, h:i:A', date("d/m/Y, h:i:A")); + $option[] = JHtml::_('select.option', 'd M Y, H:i:s', date("d ") . $mon . date(" Y, H:i:s")); + $option[] = JHtml::_('select.option', 'd-m-Y, H:i:s', date("d-m-Y, H:i:s")); + $option[] = JHtml::_('select.option', 'd.m.Y, H:i:s', date("d.m.Y, H:i:s")); + $option[] = JHtml::_('select.option', 'd/m/Y, H:i:s', date("d/m/Y, H:i:s")); + $option[] = JHtml::_('select.option', 'F d, Y', $month . date(" d, Y")); + $option[] = JHtml::_('select.option', 'D M d, Y', $wk . " " . $mon . date(" d, Y")); + $option[] = JHtml::_('select.option', 'l F d, Y', $week . " " . $month . date(" d, Y")); + + return $option; + } + + /** + * Method for convert PHP date format to MomentJS date format. + * + * @param string $format PHP date format + * + * @return string + * + * @since 2.1.0 + */ + public static function convertPHPToMomentFormat($format) + { + $replacements = [ + 'd' => 'DD', + 'D' => 'ddd', + 'j' => 'D', + 'l' => 'dddd', + 'N' => 'E', + 'S' => 'o', + 'w' => 'e', + 'z' => 'DDD', + 'W' => 'W', + 'F' => 'MMMM', + 'm' => 'MM', + 'M' => 'MMM', + 'n' => 'M', + 't' => '', // No equivalent + 'L' => '', // No equivalent + 'o' => 'YYYY', + 'Y' => 'YYYY', + 'y' => 'YY', + 'a' => 'a', + 'A' => 'A', + 'B' => '', // No equivalent + 'g' => 'h', + 'G' => 'H', + 'h' => 'hh', + 'H' => 'HH', + 'i' => 'mm', + 's' => 'ss', + 'u' => 'SSS', + 'e' => 'zz', // Deprecated since version 1.6.0 of moment.js + 'I' => '', // No equivalent + 'O' => '', // No equivalent + 'P' => '', // No equivalent + 'T' => '', // No equivalent + 'Z' => '', // No equivalent + 'c' => '', // No equivalent + 'r' => '', // No equivalent + 'U' => 'X', + ]; + + return strtr($format, $replacements); + } } diff --git a/libraries/redshop/helper/discount.php b/libraries/redshop/helper/discount.php index e64a060e38b..a471cbf46f8 100644 --- a/libraries/redshop/helper/discount.php +++ b/libraries/redshop/helper/discount.php @@ -205,34 +205,6 @@ public static function calculateAlreadyDiscount($value, $cart) return $value < 0 ? 0 : $value; } - /** - * Method for calculate discount. - * - * @param string $type Type of discount - * @param array $types List of type - * - * @return float - * - * @since 2.1.0 - */ - public static function calculate($type, $types) - { - if (empty($types)) { - return 0; - } - - $value = $type == 'voucher' ? 'voucher_value' : 'coupon_value'; - $discount = 0; - - $idx = count($types); - - for ($i = 0; $i < $idx; $i++) { - $discount += $types[$i][$value]; - } - - return $discount; - } - /** * Method for modify discount * @@ -330,10 +302,10 @@ public static function modifyDiscount($cart) $totalDiscount = $cart['cart_discount'] + $codeDiscount; \JFactory::getSession()->set('cart', $cart); - $calculations = \Redshop\Cart\Helper::calculation(); - $tax = $calculations[5]; - $discountVAT = 0; - $chktag = RedshopHelperCart::taxExemptAddToCart(); + $calculations = \Redshop\Cart\Helper::calculation(); + $tax = $calculations[5]; + $discountVAT = 0; + $chktag = RedshopHelperCart::taxExemptAddToCart(); if (Redshop::getConfig()->getFloat('VAT_RATE_AFTER_DISCOUNT') && !empty($chktag)) { if (Redshop::getConfig()->get('APPLY_VAT_ON_DISCOUNT')) { @@ -376,4 +348,32 @@ public static function modifyDiscount($cart) return $cart; } + + /** + * Method for calculate discount. + * + * @param string $type Type of discount + * @param array $types List of type + * + * @return float + * + * @since 2.1.0 + */ + public static function calculate($type, $types) + { + if (empty($types)) { + return 0; + } + + $value = $type == 'voucher' ? 'voucher_value' : 'coupon_value'; + $discount = 0; + + $idx = count($types); + + for ($i = 0; $i < $idx; $i++) { + $discount += $types[$i][$value]; + } + + return $discount; + } } diff --git a/libraries/redshop/helper/document.php b/libraries/redshop/helper/document.php index f4bd8a7a8ac..55f2d97f815 100644 --- a/libraries/redshop/helper/document.php +++ b/libraries/redshop/helper/document.php @@ -16,523 +16,496 @@ */ class RedshopHelperDocument { - /** - * Scripts marked as disabled - * - * @var array - */ - protected static $disabledScripts = array('media/jui/js/bootstrap.js', 'media/jui/js/bootstrap.min.js'); - - /** - * Stylesheets marked as disabled - * - * @var array - */ - protected static $disabledStylesheets = array(); - - /** - * Scripts that will be injected on top - * - * @var array - */ - protected static $topScripts = array(); - - /** - * Stylesheets that will be injected on top - * - * @var array - */ - protected static $topStylesheets = array(); - - /** - * Stylesheets that will be injected on bottom - * - * @var array - */ - protected static $bottomStylesheets = array(); - - /** - * Adds a linked script to the page - * This forces always use scripts versions - * - * @param string $url URL to the linked script - * @param string $type Type of script. Defaults to 'text/javascript' - * @param boolean $defer Adds the defer attribute. - * @param boolean $async Adds the async attribute. - * - * @return self Instance of $this to allow chaining - */ - public function addScript($url, $type = "text/javascript", $defer = false, $async = false) - { - $doc = JFactory::getDocument(); - $doc->addScriptVersion($url, null, $type, $defer, $async); - - return $this; - } - - /** - * Add a script to the top of the document scripts - * - * @param string $url URL to the linked script - * @param string $type Type of script. Defaults to 'text/javascript' - * @param boolean $defer Adds the defer attribute. - * @param boolean $async Adds the async attribute. - * - * @return self - */ - public function addTopScript($url, $type = "text/javascript", $defer = false, $async = false) - { - $script = array( - 'mime' => $type, - 'defer' => $defer, - 'async' => $async - ); - - static::$topScripts[$url] = $script; - - return $this; - } - - /** - * Add a script to the top of the document scripts - * - * @param string $url URL to the linked style sheet - * @param string $type Mime encoding type - * @param string $media Media type that this stylesheet applies to - * @param array $attributes Array of attributes - * - * @return self - */ - public function addTopStylesheet($url, $type = 'text/css', $media = null, $attributes = array()) - { - return self::addStylesheet('top', $url, $type, $media, $attributes); - } - - /** - * Add a script to the bottom of the document scripts - * - * @param string $url URL to the linked style sheet - * @param string $type Mime encoding type - * @param string $media Media type that this stylesheet applies to - * @param array $attributes Array of attributes - * - * @return self - */ - public function addBottomStylesheet($url, $type = 'text/css', $media = null, $attributes = array()) - { - return self::addStylesheet('bottom', $url, $type, $media, $attributes); - } - - /** - * Add a script to the bottom of the document scripts - * - * @param string $position Position for put stylesheet. - * @param string $url URL to the linked style sheet - * @param string $type Mime encoding type - * @param string $media Media type that this stylesheet applies to - * @param array $attributes Array of attributes - * - * @return self - */ - public function addStylesheet($position = 'top', $url = '', $type = 'text/css', $media = null, $attributes = array()) - { - if (version_compare(JVERSION, '3.7.0', '<')) - { - $stylesheet = array( - 'mime' => $type, - 'media' => $media, - 'attribs' => $attributes - ); - } - else - { - $stylesheet = array('mime' => $type); - - if (!is_null($media)) - { - $stylesheet['media'] = $media; - } - - if (!empty($attributes)) - { - $stylesheet['attribs'] = $attributes; - } - } - - if ($position == 'top') - { - static::$topStylesheets[$url] = $stylesheet; - } - else - { - static::$bottomStylesheets[$url] = $stylesheet; - } - - return $this; - } - - /** - * Clean header assets - * - * @return void - */ - public function cleanHeader() - { - $this->cleanHeaderScripts(); - $this->cleanHeaderStylesheets(); - $this->injectTopScripts(); - $this->injectTopStylesheets(); - $this->injectBottomStylesheets(); - } - - /** - * Injects the pending scripts on the top of the scripts - * - * @return self - */ - protected function injectTopScripts() - { - if (empty(static::$topScripts)) - { - return $this; - } - - $doc = JFactory::getDocument(); - - $doc->_scripts = array_merge(static::$topScripts, $doc->_scripts); - - return $this; - } - - /** - * Injects the top stylesheets on the top of the document stylesheets - * - * @return self - */ - protected function injectTopStylesheets() - { - if (empty(static::$topStylesheets)) - { - return $this; - } - - $doc = JFactory::getDocument(); - - $doc->_styleSheets = array_merge(static::$topStylesheets, $doc->_styleSheets); - - return $this; - } - - /** - * Injects the bottom stylesheets on the bottom of the document stylesheets - * - * @return self - */ - protected function injectBottomStylesheets() - { - if (empty(static::$bottomStylesheets)) - { - return $this; - } - - $doc = JFactory::getDocument(); - - $doc->_styleSheets = array_merge($doc->_styleSheets, static::$bottomStylesheets); - - return $this; - } - - /** - * Clear all the scripts marked as disabled - * - * @return void - */ - protected function cleanHeaderScripts() - { - if (!empty(static::$disabledScripts)) - { - foreach (static::$disabledScripts as $script) - { - $this->removeScript($script); - } - } - } - - /** - * Clear all the stylesheets marked as disabled - * - * @return void - */ - protected function cleanHeaderStylesheets() - { - if (!empty(static::$disabledStylesheets)) - { - foreach (static::$disabledStylesheets as $stylesheet) - { - $this->removeStylesheet($stylesheet); - } - } - } - - /** - * Disable Joomla Core JS mainly because before 3.2 it was using Mootools - * - * @param boolean $disableOnDebug Disable it also when debug is enabled on config - * - * @return void - */ - public function disableCoreJs($disableOnDebug = true) - { - $doc = JFactory::getDocument(); - - if ($doc->_scripts) - { - $this->disableScript('/media/system/js/core.js'); - - if ($disableOnDebug) - { - $this->disableScript('/media/system/js/core-uncompressed.js'); - } - } - } - - /** - * Avoid loading mootools in the current page - * - * @param boolean $disableCore Disable core.js scripts - * @param boolean $disableOnDebug Disable it also when debug is enabled on config - * - * @return void - */ - public function disableMootools($disableCore = false, $disableOnDebug = true) - { - $doc = JFactory::getDocument(); - - if ($doc->_scripts) - { - // Function used to replace window.addEvent() - $doc->addScriptDeclaration("function do_nothing() { return; }"); - - // Disable mootools javascript - $this->disableScript('/media/system/js/mootools-core.js'); - $this->disableScript('/media/system/js/caption.js'); - $this->disableScript('/media/system/js/modal.js'); - $this->disableScript('/media/system/js/mootools.js'); - $this->disableScript('/plugins/system/mtupgrade/mootools.js'); - - // Disabled mootools javascript when debugging site - if ($disableOnDebug) - { - $this->disableScript('/media/system/js/mootools-core-uncompressed.js'); - $this->disableScript('/media/system/js/mootools-core-uncompressed.js'); - $this->disableScript('/media/system/js/caption-uncompressed.js'); - } - - // Disable Mootools More scripts too - $this->disableMootoolsMore($disableOnDebug); - - // Core was using Mootools before v3.2 - if (version_compare(JVERSION, '3.2', 'lt')) - { - $this->disableCoreJs($disableOnDebug); - } - } - - // Disable css stylesheets - if ($doc->_styleSheets) - { - $this->disableStylesheet('/media/system/css/modal.css'); - } - } - - /** - * Disable mootools-more scripts - * - * @param boolean $disableOnDebug Disable it also when debug is enabled on config - * - * @return void - */ - public function disableMootoolsMore($disableOnDebug = true) - { - $doc = JFactory::getDocument(); - - if ($doc->_scripts) - { - $this->disableScript('/media/system/js/mootools-more.js'); - - if ($disableOnDebug) - { - $this->disableScript('/media/system/js/mootools-more-uncompressed.js'); - } - } - } - - /** - * Mark a script as disabled - * - * @param string $script Script to disable - * @param boolean $disableOnDebug Disable also uncompressed version - * - * @return void - */ - public function disableScript($script, $disableOnDebug = true) - { - $script = trim($script); - - if ($script && !in_array($script, static::$disabledScripts)) - { - array_push(static::$disabledScripts, $script); - - if ($disableOnDebug) - { - array_push(static::$disabledScripts, $this->getUncompressedPath($script)); - } - } - } - - /** - * Mark a stylesheet as disabled - * - * @param string $stylesheet Stylesheets to disable - * @param boolean $disableOnDebug Disable also uncompressed version - * - * @return void - */ - public function disableStylesheet($stylesheet, $disableOnDebug = true) - { - $stylesheet = trim($stylesheet); - - if ($stylesheet && !in_array($stylesheet, static::$disabledStylesheets)) - { - array_push(static::$disabledStylesheets, $stylesheet); - - if ($disableOnDebug) - { - array_push(static::$disabledScripts, $this->getUncompressedPath($stylesheet)); - } - } - } - - /** - * Get the route to an uncompressed asset bassed on the compressed path - * - * @param string $assetPath Path to the asset - * - * @return string - */ - protected function getUncompressedPath($assetPath) - { - $fileName = basename($assetPath); - $fileNameOnly = pathinfo($fileName, PATHINFO_FILENAME); - $fileExtension = pathinfo($assetPath, PATHINFO_EXTENSION); - - if (strrpos($fileNameOnly, '.min', '-4')) - { - $position = strrpos($fileNameOnly, '.min', '-4'); - $uncompressedFileName = str_replace('.min', '.', $fileNameOnly, $position); - $uncompressedFileName = $uncompressedFileName . $fileExtension; - } - else - { - $uncompressedFileName = $fileNameOnly . '-uncompressed.' . $fileExtension; - } - - return str_replace($fileName, $uncompressedFileName, $assetPath); - } - - /** - * Remove a script from the JDocument header - * - * @param string $script Script path - * - * @return void - */ - public function removeScript($script) - { - $doc = JFactory::getDocument(); - - $script = trim($script); - - if (!empty($script)) - { - $uri = JUri::getInstance(); - - $relativePath = trim(str_replace($uri->getPath(), '', JUri::root()), '/'); - $relativeScript = trim(str_replace($uri->getPath(), '', $script), '/'); - $relativeUrl = str_replace($relativePath, '', $script); - - $mediaVersion = $doc->getMediaVersion(); - - // Try to disable relative and full URLs - unset($doc->_scripts[$script]); - unset($doc->_scripts[$script . '?' . $mediaVersion]); - - unset($doc->_scripts[$relativeUrl]); - unset($doc->_scripts[$relativeUrl . '?' . $mediaVersion]); - - unset($doc->_scripts[JUri::root(true) . $script]); - unset($doc->_scripts[JUri::root(true) . $script . '?' . $mediaVersion]); - - unset($doc->_scripts[JUri::root(true) . '/' . $script]); - unset($doc->_scripts[JUri::root(true) . '/' . $script . '?' . $mediaVersion]); - - unset($doc->_scripts[$relativeScript]); - unset($doc->_scripts[$relativeScript . '?' . $mediaVersion]); - } - } - - /** - * Remove a stylesheet from the JDocument header - * - * @param string $stylesheet URL to the stylesheet (both global/relative should work) - * - * @return void - */ - public function removeStylesheet($stylesheet) - { - $stylesheet = trim($stylesheet); - - if (!empty($stylesheet)) - { - $doc = JFactory::getDocument(); - $uri = JUri::getInstance(); - - $relativePath = trim(str_replace($uri->getPath(), '', JUri::root()), '/'); - $relativeStylesheet = trim(str_replace($uri->getPath(), '', $stylesheet), '/'); - $relativeUrl = str_replace($relativePath, '', $stylesheet); - - $mediaVersion = $doc->getMediaVersion(); - - // Try to disable relative and full URLs - unset($doc->_styleSheets[$stylesheet]); - unset($doc->_styleSheets[$stylesheet . '?' . $mediaVersion]); - - unset($doc->_styleSheets[$relativeUrl]); - unset($doc->_styleSheets[$relativeUrl . '?' . $mediaVersion]); - - unset($doc->_styleSheets[JUri::root(true) . $stylesheet]); - unset($doc->_styleSheets[JUri::root(true) . $stylesheet . '?' . $mediaVersion]); - - unset($doc->_styleSheets[JUri::root(true) . '/' . $stylesheet]); - unset($doc->_styleSheets[JUri::root(true) . '/' . $stylesheet . '?' . $mediaVersion]); - - unset($doc->_styleSheets[$relativeStylesheet]); - unset($doc->_styleSheets[$relativeStylesheet . '?' . $mediaVersion]); - } - } - - /** - * Redirect any non-existing method to JDocument - * - * @param string $method Method called - * @param array $arguments Arguments passed to the method - * - * @return mixed - */ - public function __call($method, $arguments) - { - $doc = JFactory::getDocument(); - - return call_user_func_array(array($doc, $method), $arguments); - } + /** + * Scripts marked as disabled + * + * @var array + */ + protected static $disabledScripts = array('media/jui/js/bootstrap.js', 'media/jui/js/bootstrap.min.js'); + + /** + * Stylesheets marked as disabled + * + * @var array + */ + protected static $disabledStylesheets = array(); + + /** + * Scripts that will be injected on top + * + * @var array + */ + protected static $topScripts = array(); + + /** + * Stylesheets that will be injected on top + * + * @var array + */ + protected static $topStylesheets = array(); + + /** + * Stylesheets that will be injected on bottom + * + * @var array + */ + protected static $bottomStylesheets = array(); + + /** + * Adds a linked script to the page + * This forces always use scripts versions + * + * @param string $url URL to the linked script + * @param string $type Type of script. Defaults to 'text/javascript' + * @param boolean $defer Adds the defer attribute. + * @param boolean $async Adds the async attribute. + * + * @return self Instance of $this to allow chaining + */ + public function addScript($url, $type = "text/javascript", $defer = false, $async = false) + { + $doc = JFactory::getDocument(); + $doc->addScriptVersion($url, null, $type, $defer, $async); + + return $this; + } + + /** + * Add a script to the top of the document scripts + * + * @param string $url URL to the linked script + * @param string $type Type of script. Defaults to 'text/javascript' + * @param boolean $defer Adds the defer attribute. + * @param boolean $async Adds the async attribute. + * + * @return self + */ + public function addTopScript($url, $type = "text/javascript", $defer = false, $async = false) + { + $script = array( + 'mime' => $type, + 'defer' => $defer, + 'async' => $async + ); + + static::$topScripts[$url] = $script; + + return $this; + } + + /** + * Add a script to the top of the document scripts + * + * @param string $url URL to the linked style sheet + * @param string $type Mime encoding type + * @param string $media Media type that this stylesheet applies to + * @param array $attributes Array of attributes + * + * @return self + */ + public function addTopStylesheet($url, $type = 'text/css', $media = null, $attributes = array()) + { + return self::addStylesheet('top', $url, $type, $media, $attributes); + } + + /** + * Add a script to the bottom of the document scripts + * + * @param string $position Position for put stylesheet. + * @param string $url URL to the linked style sheet + * @param string $type Mime encoding type + * @param string $media Media type that this stylesheet applies to + * @param array $attributes Array of attributes + * + * @return self + */ + public function addStylesheet( + $position = 'top', + $url = '', + $type = 'text/css', + $media = null, + $attributes = array() + ) { + if (version_compare(JVERSION, '3.7.0', '<')) { + $stylesheet = array( + 'mime' => $type, + 'media' => $media, + 'attribs' => $attributes + ); + } else { + $stylesheet = array('mime' => $type); + + if (!is_null($media)) { + $stylesheet['media'] = $media; + } + + if (!empty($attributes)) { + $stylesheet['attribs'] = $attributes; + } + } + + if ($position == 'top') { + static::$topStylesheets[$url] = $stylesheet; + } else { + static::$bottomStylesheets[$url] = $stylesheet; + } + + return $this; + } + + /** + * Add a script to the bottom of the document scripts + * + * @param string $url URL to the linked style sheet + * @param string $type Mime encoding type + * @param string $media Media type that this stylesheet applies to + * @param array $attributes Array of attributes + * + * @return self + */ + public function addBottomStylesheet($url, $type = 'text/css', $media = null, $attributes = array()) + { + return self::addStylesheet('bottom', $url, $type, $media, $attributes); + } + + /** + * Clean header assets + * + * @return void + */ + public function cleanHeader() + { + $this->cleanHeaderScripts(); + $this->cleanHeaderStylesheets(); + $this->injectTopScripts(); + $this->injectTopStylesheets(); + $this->injectBottomStylesheets(); + } + + /** + * Clear all the scripts marked as disabled + * + * @return void + */ + protected function cleanHeaderScripts() + { + if (!empty(static::$disabledScripts)) { + foreach (static::$disabledScripts as $script) { + $this->removeScript($script); + } + } + } + + /** + * Remove a script from the JDocument header + * + * @param string $script Script path + * + * @return void + */ + public function removeScript($script) + { + $doc = JFactory::getDocument(); + + $script = trim($script); + + if (!empty($script)) { + $uri = JUri::getInstance(); + + $relativePath = trim(str_replace($uri->getPath(), '', JUri::root()), '/'); + $relativeScript = trim(str_replace($uri->getPath(), '', $script), '/'); + $relativeUrl = str_replace($relativePath, '', $script); + + $mediaVersion = $doc->getMediaVersion(); + + // Try to disable relative and full URLs + unset($doc->_scripts[$script]); + unset($doc->_scripts[$script . '?' . $mediaVersion]); + + unset($doc->_scripts[$relativeUrl]); + unset($doc->_scripts[$relativeUrl . '?' . $mediaVersion]); + + unset($doc->_scripts[JUri::root(true) . $script]); + unset($doc->_scripts[JUri::root(true) . $script . '?' . $mediaVersion]); + + unset($doc->_scripts[JUri::root(true) . '/' . $script]); + unset($doc->_scripts[JUri::root(true) . '/' . $script . '?' . $mediaVersion]); + + unset($doc->_scripts[$relativeScript]); + unset($doc->_scripts[$relativeScript . '?' . $mediaVersion]); + } + } + + /** + * Clear all the stylesheets marked as disabled + * + * @return void + */ + protected function cleanHeaderStylesheets() + { + if (!empty(static::$disabledStylesheets)) { + foreach (static::$disabledStylesheets as $stylesheet) { + $this->removeStylesheet($stylesheet); + } + } + } + + /** + * Remove a stylesheet from the JDocument header + * + * @param string $stylesheet URL to the stylesheet (both global/relative should work) + * + * @return void + */ + public function removeStylesheet($stylesheet) + { + $stylesheet = trim($stylesheet); + + if (!empty($stylesheet)) { + $doc = JFactory::getDocument(); + $uri = JUri::getInstance(); + + $relativePath = trim(str_replace($uri->getPath(), '', JUri::root()), '/'); + $relativeStylesheet = trim(str_replace($uri->getPath(), '', $stylesheet), '/'); + $relativeUrl = str_replace($relativePath, '', $stylesheet); + + $mediaVersion = $doc->getMediaVersion(); + + // Try to disable relative and full URLs + unset($doc->_styleSheets[$stylesheet]); + unset($doc->_styleSheets[$stylesheet . '?' . $mediaVersion]); + + unset($doc->_styleSheets[$relativeUrl]); + unset($doc->_styleSheets[$relativeUrl . '?' . $mediaVersion]); + + unset($doc->_styleSheets[JUri::root(true) . $stylesheet]); + unset($doc->_styleSheets[JUri::root(true) . $stylesheet . '?' . $mediaVersion]); + + unset($doc->_styleSheets[JUri::root(true) . '/' . $stylesheet]); + unset($doc->_styleSheets[JUri::root(true) . '/' . $stylesheet . '?' . $mediaVersion]); + + unset($doc->_styleSheets[$relativeStylesheet]); + unset($doc->_styleSheets[$relativeStylesheet . '?' . $mediaVersion]); + } + } + + /** + * Injects the pending scripts on the top of the scripts + * + * @return self + */ + protected function injectTopScripts() + { + if (empty(static::$topScripts)) { + return $this; + } + + $doc = JFactory::getDocument(); + + $doc->_scripts = array_merge(static::$topScripts, $doc->_scripts); + + return $this; + } + + /** + * Injects the top stylesheets on the top of the document stylesheets + * + * @return self + */ + protected function injectTopStylesheets() + { + if (empty(static::$topStylesheets)) { + return $this; + } + + $doc = JFactory::getDocument(); + + $doc->_styleSheets = array_merge(static::$topStylesheets, $doc->_styleSheets); + + return $this; + } + + /** + * Injects the bottom stylesheets on the bottom of the document stylesheets + * + * @return self + */ + protected function injectBottomStylesheets() + { + if (empty(static::$bottomStylesheets)) { + return $this; + } + + $doc = JFactory::getDocument(); + + $doc->_styleSheets = array_merge($doc->_styleSheets, static::$bottomStylesheets); + + return $this; + } + + /** + * Avoid loading mootools in the current page + * + * @param boolean $disableCore Disable core.js scripts + * @param boolean $disableOnDebug Disable it also when debug is enabled on config + * + * @return void + */ + public function disableMootools($disableCore = false, $disableOnDebug = true) + { + $doc = JFactory::getDocument(); + + if ($doc->_scripts) { + // Function used to replace window.addEvent() + $doc->addScriptDeclaration("function do_nothing() { return; }"); + + // Disable mootools javascript + $this->disableScript('/media/system/js/mootools-core.js'); + $this->disableScript('/media/system/js/caption.js'); + $this->disableScript('/media/system/js/modal.js'); + $this->disableScript('/media/system/js/mootools.js'); + $this->disableScript('/plugins/system/mtupgrade/mootools.js'); + + // Disabled mootools javascript when debugging site + if ($disableOnDebug) { + $this->disableScript('/media/system/js/mootools-core-uncompressed.js'); + $this->disableScript('/media/system/js/mootools-core-uncompressed.js'); + $this->disableScript('/media/system/js/caption-uncompressed.js'); + } + + // Disable Mootools More scripts too + $this->disableMootoolsMore($disableOnDebug); + + // Core was using Mootools before v3.2 + if (version_compare(JVERSION, '3.2', 'lt')) { + $this->disableCoreJs($disableOnDebug); + } + } + + // Disable css stylesheets + if ($doc->_styleSheets) { + $this->disableStylesheet('/media/system/css/modal.css'); + } + } + + /** + * Mark a script as disabled + * + * @param string $script Script to disable + * @param boolean $disableOnDebug Disable also uncompressed version + * + * @return void + */ + public function disableScript($script, $disableOnDebug = true) + { + $script = trim($script); + + if ($script && !in_array($script, static::$disabledScripts)) { + array_push(static::$disabledScripts, $script); + + if ($disableOnDebug) { + array_push(static::$disabledScripts, $this->getUncompressedPath($script)); + } + } + } + + /** + * Get the route to an uncompressed asset bassed on the compressed path + * + * @param string $assetPath Path to the asset + * + * @return string + */ + protected function getUncompressedPath($assetPath) + { + $fileName = basename($assetPath); + $fileNameOnly = pathinfo($fileName, PATHINFO_FILENAME); + $fileExtension = pathinfo($assetPath, PATHINFO_EXTENSION); + + if (strrpos($fileNameOnly, '.min', '-4')) { + $position = strrpos($fileNameOnly, '.min', '-4'); + $uncompressedFileName = str_replace('.min', '.', $fileNameOnly, $position); + $uncompressedFileName = $uncompressedFileName . $fileExtension; + } else { + $uncompressedFileName = $fileNameOnly . '-uncompressed.' . $fileExtension; + } + + return str_replace($fileName, $uncompressedFileName, $assetPath); + } + + /** + * Disable mootools-more scripts + * + * @param boolean $disableOnDebug Disable it also when debug is enabled on config + * + * @return void + */ + public function disableMootoolsMore($disableOnDebug = true) + { + $doc = JFactory::getDocument(); + + if ($doc->_scripts) { + $this->disableScript('/media/system/js/mootools-more.js'); + + if ($disableOnDebug) { + $this->disableScript('/media/system/js/mootools-more-uncompressed.js'); + } + } + } + + /** + * Disable Joomla Core JS mainly because before 3.2 it was using Mootools + * + * @param boolean $disableOnDebug Disable it also when debug is enabled on config + * + * @return void + */ + public function disableCoreJs($disableOnDebug = true) + { + $doc = JFactory::getDocument(); + + if ($doc->_scripts) { + $this->disableScript('/media/system/js/core.js'); + + if ($disableOnDebug) { + $this->disableScript('/media/system/js/core-uncompressed.js'); + } + } + } + + /** + * Mark a stylesheet as disabled + * + * @param string $stylesheet Stylesheets to disable + * @param boolean $disableOnDebug Disable also uncompressed version + * + * @return void + */ + public function disableStylesheet($stylesheet, $disableOnDebug = true) + { + $stylesheet = trim($stylesheet); + + if ($stylesheet && !in_array($stylesheet, static::$disabledStylesheets)) { + array_push(static::$disabledStylesheets, $stylesheet); + + if ($disableOnDebug) { + array_push(static::$disabledScripts, $this->getUncompressedPath($stylesheet)); + } + } + } + + /** + * Redirect any non-existing method to JDocument + * + * @param string $method Method called + * @param array $arguments Arguments passed to the method + * + * @return mixed + */ + public function __call($method, $arguments) + { + $doc = JFactory::getDocument(); + + return call_user_func_array(array($doc, $method), $arguments); + } } diff --git a/libraries/redshop/helper/extrafields.php b/libraries/redshop/helper/extrafields.php index 5123df36d1f..5a2230c9fbe 100644 --- a/libraries/redshop/helper/extrafields.php +++ b/libraries/redshop/helper/extrafields.php @@ -20,2008 +20,1954 @@ */ class RedshopHelperExtrafields { - /** - * Extra Field Type for Input Text Element - * - * @var int - */ - const TYPE_TEXT = 1; - - /** - * Extra Field Type for Input Text Area Element - * - * @var int - */ - const TYPE_TEXT_AREA = 2; - - /** - * Extra Field Type for Checkboxes Element - * - * @var int - */ - const TYPE_CHECK_BOX = 3; - - /** - * Extra Field Type for Input Radio Button Element - * - * @var int - */ - const TYPE_RADIO_BUTTON = 4; - - /** - * Extra Field Type for Input Single Select Element - * - * @var int - */ - const TYPE_SELECT_BOX_SINGLE = 5; - - /** - * Extra Field Type for Input Multi Select Element - * - * @var int - */ - const TYPE_SELECT_BOX_MULTIPLE = 6; - - /** - * Extra Field Type for Country Select List Element - * - * @var int - */ - const TYPE_SELECT_COUNTRY_BOX = 7; - - /** - * Extra Field Type for WYSIWYG Editor - * - * @var int - */ - const TYPE_WYSIWYG = 8; - - /** - * Extra Field Type for Input Media element - * - * @var int - */ - const TYPE_MEDIA = 9; - - /** - * Extra Field Type for Document - * - * @var int - */ - const TYPE_DOCUMENTS = 10; - - /** - * Extra Field Type for Image select - * - * @var int - */ - const TYPE_IMAGE_SELECT = 11; - - /** - * Extra Field Type for Date Picket element. - * - * @var int - */ - const TYPE_DATE_PICKER = 12; - - /** - * Extra Field Type for with link - * - * @var int - */ - const TYPE_IMAGE_WITH_LINK = 13; - - /** - * Extra Field Type for selection based on selected condition. - * - * @var int - */ - const TYPE_SELECTION_BASED_ON_SELECTED_CONDITIONS = 15; - - /** - * Extra Field Type joomla articles related - * - * @var int - */ - const TYPE_JOOMLA_RELATED_ARTICLES = 16; - - /** - * Extra Field Type for product finder date picker. - * - * @var int - */ - const TYPE_PRODUCT_FINDER_DATE_PICKER = 17; - - /** - * Extra Field Section Id for Product - * - * @var integer - */ - const SECTION_PRODUCT = 1; - - /** - * Extra Field Section Id for Category - * - * @var integer - */ - const SECTION_CATEGORY = 2; - - /** - * Extra Field Section Id for Form - * - * @var integer - */ - const SECTION_FORM = 3; - - /** - * Extra Field Section Id for Email - * - * @var integer - */ - const SECTION_EMAIL = 4; - - /** - * Extra Field Section Id for Confirmation - * - * @var integer - */ - const SECTION_CONFIRMATION = 5; - - /** - * Extra Field Section Id for User information - * - * @var integer - */ - const SECTION_USER_INFORMATIONS = 6; - - /** - * Extra Field Section Id for Private Billing Address - * - * @var integer - */ - const SECTION_PRIVATE_BILLING_ADDRESS = 7; - - /** - * Extra Field Section Id for Private Billing Address - * - * @var integer - */ - const SECTION_COMPANY_BILLING_ADDRESS = 8; - - /** - * Extra Field Section Id for Color Sample - * - * @var integer - */ - const SECTION_COLOR_SAMPLE = 9; - - /** - * Extra Field Section Id for Manufacturer - * - * @var integer - */ - const SECTION_MANUFACTURER = 10; - - /** - * Extra Field Section Id for Shipping - * - * @var integer - */ - const SECTION_SHIPPING = 11; - - /** - * Extra Field Section Id for Product User Field - * - * @var integer - */ - const SECTION_PRODUCT_USERFIELD = 12; - - /** - * Extra Field Section Id for Gift Card User Field - * - * @var integer - */ - const SECTION_GIFT_CARD_USER_FIELD = 13; - - /** - * Extra Field Section Id for Private Shipping Address - * - * @var integer - */ - const SECTION_PRIVATE_SHIPPING_ADDRESS = 14; - - /** - * Extra Field Section Id for Company Shipping Address - * - * @var integer - */ - const SECTION_COMPANY_SHIPPING_ADDRESS = 15; - - /** - * Extra Field Section Id for Quotation - * - * @var integer - */ - const SECTION_QUOTATION = 16; - - /** - * Extra Field Section Id for Date Picker - * - * @var integer - */ - const SECTION_PRODUCT_FINDER_DATE_PICKER = 17; - - /** - * Extra Field Section Id for Payment Gateways - * - * @var integer - */ - const SECTION_PAYMENT_GATEWAY = 18; - - /** - * Extra Field Section Id for Shipping Gateways - * - * @var integer - */ - const SECTION_SHIPPING_GATEWAY = 19; - - /** - * Extra Field Section Id for Order - * - * @var integer - */ - const SECTION_ORDER = 20; - - /** - * List of fields data - * - * @var array - */ - protected static $fieldsData = array(); - - /** - * All fields information - * - * @var array - */ - protected static $fieldsName = array(); - - /** - * List of fields - * - * @var array - * - * @since 2.0.3 - */ - protected static $sectionFields = array(); - - /** - * Get list of fields. - * - * @param integer $published Published Status which needs to be get. Default -1 will ignore any status. - * @param integer $limitStart Set limit start - * @param integer $limit Set limit - * - * @return array Array of all the available fields based on arguments. - */ - public static function getList($published = -1, $limitStart = 0, $limit = 0) - { - $db = JFactory::getDbo(); - - if (!empty(self::$fieldsName)) - { - return self::$fieldsName; - } - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_fields')); - - if ($published >= 0) - { - $query->where($db->qn('published') . ' = ' . (int) $published); - } - - self::$fieldsName = $db->setQuery($query, $limitStart, $limit)->loadObjectList('name'); - - return self::$fieldsName; - } - - /** - * Get field information from field name. - * - * @param string $name Field name prefixed with `rs_` - * - * @return object|null Field information object otherwise null. - */ - public static function getField($name) - { - $fields = self::getList(); - - if (array_key_exists($name, $fields)) - { - return $fields[$name]; - } - - return null; - } - - /** - * Get Section Field Data List - * - * @param int $name Name of the field - Typically contains `rs_` prefix. - * @param int $section Section id of the field. - * @param int $sectionItem Section item id - * - * @return mixed|null - */ - public static function getDataByName($name, $section, $sectionItem) - { - // Get Field id - if (!self::getField($name)) - { - return null; - } - - $fieldId = self::getField($name)->id; - - return self::getData($fieldId, $section, $sectionItem); - } - - /** - * Get Section Field Data List - * - * @param integer $fieldId Field id - * @param integer $section Section id of the field. - * @param integer $sectionItem Section item id - * - * @return mixed|null - */ - public static function getData($fieldId, $section, $sectionItem) - { - $key = $fieldId . '.' . $section . '.' . $sectionItem; - - if (array_key_exists($key, self::$fieldsData)) - { - return self::$fieldsData[$key]; - } - - // Init null. - self::$fieldsData[$key] = null; - - if ($section == 1) - { - $product = Redshop::product((int) $sectionItem); - - if ($product && isset($product->extraFields[$fieldId])) - { - self::$fieldsData[$key] = $product->extraFields[$fieldId]; - } - } - - if (($section == 1 && !self::$fieldsData[$key]) || $section != 1) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('fd.*') - ->select($db->qn('f.title')) - ->from($db->qn('#__redshop_fields_data', 'fd')) - ->leftJoin($db->qn('#__redshop_fields', 'f') . ' ON ' . $db->qn('fd.fieldid') . ' = ' . $db->qn('f.id')) - ->where($db->qn('fd.itemid') . ' = ' . (int) $sectionItem) - ->where($db->qn('fd.fieldid') . ' = ' . (int) $fieldId) - ->where($db->qn('fd.section') . ' = ' . $db->quote($section)); - self::$fieldsData[$key] = $db->setQuery($query)->loadObject(); - } - - return self::$fieldsData[$key]; - } - - /** - * List all field in product - * - * @param integer $section Section product - * - * @return array - * - * @since 2.0.3 - */ - public static function listAllFieldInProduct($section = self::SECTION_PRODUCT) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select('*') - ->from($db->qn('#__redshop_fields')) - ->where($db->qn('section') . ' = ' . (int) $section) - ->where($db->qn('display_in_product') . ' = 1') - ->where($db->qn('published') . ' = 1') - ->order($db->qn('ordering')); - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * List all fields - * - * @param string $fieldSection Field section - * @param integer $sectionId Section ID - * @param string $fieldName Field name - * @param string $templateDesc Template - * @param int $front Show field in front - * @param int $checkout Show field in checkout - * - * @return string HTML - * - * @since 2.0.3 - */ - public static function listAllField($fieldSection = '', $sectionId = 0, $fieldName = '', $templateDesc = '', $front = 0, $checkout = 0) - { - $db = JFactory::getDbo(); - - JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/models', 'RedshopModel'); - - /** @var RedshopModelFields $model */ - $model = JModelLegacy::getInstance('Fields', 'RedshopModel'); - $customFields = $model->getFieldsBySection($fieldSection, $fieldName, $front, $checkout); - - if (!count($customFields)) - { - return ''; - } - - // Grouping - $customFieldsGrouped = array(0 => array()); - - foreach ($customFields as $customField) - { - if (empty($customField->groupName)) - { - $customFieldsGrouped[0][] = $customField; - } - else - { - $customFieldsGrouped[$customField->groupName][] = $customField; - } - } - - if (empty($customFieldsGrouped[0])) - { - unset($customFieldsGrouped[0]); - } - - $active = key($customFieldsGrouped); - $active = !$active ? JText::_('COM_REDSHOP_FIELD_GROUP_NOGROUP') : $active; - $active = 'customfield-group-' . JFilterOutput::stringURLSafe($active); - $setName = 'customfields-section-' . $fieldSection . '-pane'; - $exField = '
    '; - $exField .= JHtml::_('bootstrap.startTabSet', $setName, array('active' => $active)); - - foreach ($customFieldsGrouped as $groupName => $customFieldGroup) - { - if (empty($customFieldGroup)) - { - continue; - } - - $tabName = !$groupName ? JText::_('COM_REDSHOP_FIELD_GROUP_NOGROUP') : $groupName; - $exField .= JHtml::_('bootstrap.addTab', $setName, 'customfield-group-' . JFilterOutput::stringURLSafe($tabName), $tabName); - $exField .= ''; - - foreach ($customFieldGroup as $customField) - { - $type = $customField->type; - $dataValue = self::getSectionFieldDataList($customField->id, $fieldSection, $sectionId); - $exField .= ''; - $extraFieldValue = ""; - $extraFieldLabel = JText::_($customField->title); - $required = ''; - $reqlbl = ' reqlbl="" '; - $errormsg = ' errormsg="" '; - - if ($fieldSection == self::SECTION_QUOTATION && $customField->required == 1) - { - $required = ' required="1" '; - $reqlbl = ' reqlbl="' . $extraFieldLabel . '" '; - $errormsg = ' errormsg="' . JText::_('COM_REDSHOP_THIS_FIELD_IS_REQUIRED') . '" '; - } - - switch ($type) - { - case self::TYPE_TEXT: - $textValue = ($dataValue && $dataValue->data_txt) ? $dataValue->data_txt : ''; - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.text', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'textValue' => $textValue - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - break; - - case self::TYPE_TEXT_AREA: - $textareaValue = ($dataValue && $dataValue->data_txt) ? $dataValue->data_txt : ''; - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.textarea', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'textValue' => $textareaValue - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - break; - - case self::TYPE_CHECK_BOX: - $fieldChk = RedshopEntityField::getInstance($customField->id)->getFieldValues(); - $chkData = isset($dataValue->data_txt) ? explode(",", $dataValue->data_txt) - : []; - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.checkbox', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - break; - - case self::TYPE_RADIO_BUTTON: - $fieldChk = RedshopEntityField::getInstance($customField->id)->getFieldValues(); - $chkData = explode(",", $dataValue->data_txt); - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.radio', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - break; - - case self::TYPE_SELECT_BOX_SINGLE: - $fieldChk = RedshopEntityField::getInstance($customField->id)->getFieldValues(); - $chkData = explode(",", ($dataValue->data_txt ?? '')); - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.select', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - break; - - case self::TYPE_SELECT_BOX_MULTIPLE: - $fieldChk = RedshopEntityField::getInstance($customField->id)->getFieldValues(); - $chkData = explode(",", $dataValue->data_txt); - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.multiple', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - break; - - case self::TYPE_SELECT_COUNTRY_BOX: - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_country')); - $db->setQuery($query); - $fieldChk = $db->loadObjectList(); - $chkData = array(); - - if (!empty($dataValue->data_txt)) - { - $chkData = explode(",", $dataValue->data_txt); - } - - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.multiple', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - break; - - case self::TYPE_JOOMLA_RELATED_ARTICLES: - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__content')) - ->where($db->qn('state') . ' = 1'); - $db->setQuery($query); - - $fieldChk = $db->loadObjectList(); - $chkData = explode(",", $dataValue->data_txt); - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.multiple', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - break; - - case self::TYPE_WYSIWYG: - $editor = JEditor::getInstance(JFactory::getConfig()->get('editor')); - $textareaValue = ($dataValue && $dataValue->data_txt) ? $dataValue->data_txt : ''; - - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.editor', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'textValue' => $textareaValue, - 'editor' => $editor - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - break; - - case self::TYPE_DOCUMENTS: - $dataTxt = array(); - - if (is_object($dataValue) && property_exists($dataValue, 'data_txt')) - { - // Support Legacy string. - if (preg_match('/\n/', $dataValue->data_txt)) - { - $documentExplode = explode("\n", $dataValue->data_txt); - $dataTxt = array($documentExplode[0] => $documentExplode[1]); - } - else - { - // Support for multiple file upload using JSON for better string handling - $dataTxt = json_decode($dataValue->data_txt); - } - } - - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.document', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'dataTxt' => $dataTxt, - 'dataValue' => $dataValue - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - break; - - case self::TYPE_IMAGE_SELECT: - - $fieldChk = RedshopEntityField::getInstance($customField->id)->getFieldValues(); - $dataValue = self::getSectionFieldDataList($customField->id, $fieldSection, $sectionId); - $value = ''; - - if ($dataValue) - { - $value = $dataValue->data_txt; - } - - $chkData = explode(',', $value); - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.image', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData, - 'value' => $value, - 'sectionId' => $sectionId - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - break; - - case self::TYPE_DATE_PICKER: - - $format = Redshop::getConfig()->get('DEFAULT_DATEFORMAT', 'Y-m-d'); - $date = ''; - - if ($customField->section != 17) - { - $date = date($format, time()); - } - - if ($dataValue) - { - if ($dataValue->data_txt) - { - $date = date($format, strtotime($dataValue->data_txt)); - } - } - - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.date_picker', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'date' => $date - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - - break; - - case self::TYPE_IMAGE_WITH_LINK: - - $fieldChk = RedshopEntityField::getInstance($customField->id)->getFieldValues(); - $dataValue = self::getSectionFieldDataList($customField->id, $fieldSection, $sectionId); - $value = ($dataValue) ? $dataValue->data_txt : ''; - $tmpImageHover = array(); - $tmpImageLink = array(); - - if ($dataValue->altText) - { - $tmpImageHover = explode(',,,,,', $dataValue->altText); - } - - if ($dataValue->image_link) - { - $tmpImageLink = explode(',,,,,', $dataValue->image_link); - } - - $chkData = explode(",", $dataValue->data_txt); - $imageLink = array(); - $imageHover = array(); - - if ($chkData !== false) - { - foreach ($chkData as $index => $aChkData) - { - $imageLink[$aChkData] = $tmpImageLink[$index]; - $imageHover[$aChkData] = $tmpImageHover[$index]; - } - } - - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.image_link', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData, - 'value' => $value, - 'sectionId' => $sectionId, - 'imageLink' => $imageLink, - 'imageHover' => $imageHover - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - - break; - - case self::TYPE_SELECTION_BASED_ON_SELECTED_CONDITIONS: - - if ($dataValue) - { - if ($dataValue->data_txt) - { - $mainSplitDateTotal = explode(" ", $dataValue->data_txt); - $mainSplitDate = explode(":", $mainSplitDateTotal[0]); - $mainSplitDateExtra = explode(":", $mainSplitDateTotal[1]); - $datePublish = date("d-m-Y", $mainSplitDate[0]); - $dateExpiry = date("d-m-Y", $mainSplitDate[1]); - } - else - { - $datePublish = date("d-m-Y"); - $dateExpiry = date("d-m-Y"); - $mainSplitDateExtra = array(); - } - } - else - { - $datePublish = date("d-m-Y"); - $dateExpiry = date("d-m-Y"); - $mainSplitDateExtra = array(); - } - - $exField .= RedshopLayoutHelper::render( - 'extrafields.field.selected_condition', - array( - 'rowData' => $customField, - 'extraFieldLabel' => $extraFieldLabel, - 'required' => $required, - 'requiredLabel' => $reqlbl, - 'errorMsg' => $errormsg, - 'datePublish' => $datePublish, - 'dateExpiry' => $dateExpiry, - 'mainSplitDateExtra' => $mainSplitDateExtra - ), - '', - array( - 'component' => 'com_redshop', - 'client' => 0 - ) - ); - - break; - - default: - JPluginHelper::importPlugin('redshop'); - $dispatcher = RedshopHelperUtility::getDispatcher(); - - $dispatcher->trigger('onDisplayListField', array(&$exField, $customField, $dataValue)); - } - - if (trim($templateDesc) != '') - { - if (strstr($templateDesc, "{" . $customField->name . "}")) - { - $templateDesc = str_replace("{" . $customField->name . "}", $extraFieldValue, $templateDesc); - $templateDesc = str_replace("{" . $customField->name . "_lbl}", $extraFieldLabel, $templateDesc); - } - - $templateDesc = str_replace("{" . $customField->name . "}", "", $templateDesc); - $templateDesc = str_replace("{" . $customField->name . "_lbl}", "", $templateDesc); - } - else - { - if (trim($customField->desc) == '') - { - $exField .= ''; - } - else - { - $exField .= ''; - } - } - - $exField .= ''; - } - - $exField .= '
      ' - . JHtml::tooltip($customField->desc, $customField->name, 'tooltip.png', '', '') . '
    '; - $exField .= JHtml::_('bootstrap.endTab'); - } - - $exField .= JHtml::_('bootstrap.endTabSet'); - $exField .= '
    '; - - if (trim($templateDesc) != '') - { - return $templateDesc; - } - - return $exField; - } - - /** - * Save extra fields - * - * @param array $data Data to insert - * @param integer $fieldSection Field section to match - * @param string $sectionId Section ID - * @param string $userEmail User to match by email - * - * @return void - * @throws Exception - * - * @since 2.0.3 - */ - public static function extraFieldSave($data, $fieldSection, $sectionId = "", $userEmail = "") - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select('*') - ->from($db->qn('#__redshop_fields')) - ->where($db->qn('section') . ' = ' . (int) $fieldSection) - ->where($db->qn('published') . ' = 1'); - - $rows = (array) $db->setQuery($query)->loadObjectList(); - - if (empty($rows)) - { - return; - } - - foreach ($rows as $row) - { - $dataTxt = ''; - - if (isset($data[$row->name])) - { - if ($row->type == self::TYPE_TEXT || $row->type == self::TYPE_TEXT_AREA) - { - $dataTxt = \JFilterInput::getInstance()->clean($data[$row->name]); - } - elseif ($row->type == self::TYPE_WYSIWYG) - { - $inputField = JFactory::getApplication()->input->post->get($row->name, '', 'raw'); - $dataTxt = \JFilterInput::getInstance(null, null, 1, 1)->clean($inputField, 'html'); - } - else - { - $dataTxt = $data[$row->name]; - } - } - - // Save Document Extra Field - if ($row->type == self::TYPE_DOCUMENTS) - { - $files = $_FILES[$row->name]['name']; - $texts = $data['text_' . $row->name]; - - $documentsValue = array(); - - if (isset($data[$row->name])) - { - $documentsValue = $data[$row->name]; - } - - if (is_array($files) && !empty($files)) - { - $documents = array(); - - foreach ($files as $index => $file) - { - // Editing uploaded file - if (!empty($documentsValue[$index])) - { - if (!empty(trim($texts[$index]))) - { - $documents[trim($texts[$index])] = $documentsValue[$index]; - } - else - { - $documents[$index] = $documentsValue[$index]; - } - } - - if (!empty($file)) - { - $name = RedshopHelperMedia::cleanFileName($file); - $src = $_FILES[$row->name]['tmp_name'][$index]; - $destination = REDSHOP_FRONT_DOCUMENT_RELPATH . 'extrafields/' . $name; - - JFile::upload($src, $destination); - - if (!empty(trim($texts[$index]))) - { - $documents[trim($texts[$index])] = $name; - } - else - { - $documents[$index] = $name; - } - } - } - - // Convert array into JSON string for better handler. - $dataTxt = json_encode($documents); - } - } - - if ($row->type == self::TYPE_SELECTION_BASED_ON_SELECTED_CONDITIONS && $data[$row->name] !== "" && $data[$row->name . "_expiry"] !== "") - { - $dataTxt = strtotime($data[$row->name]) . ":" . strtotime($data[$row->name . "_expiry"]) . " "; - - if (!empty($data[$row->name . "_extra_name"])) - { - foreach ($data[$row->name . "_extra_name"] as $aData) - { - $dataTxt .= strtotime($aData) . ':'; - } - } - } - - if (is_array($dataTxt)) - { - $dataTxt = implode(',', $dataTxt); - } - - $sections = explode(',', $fieldSection); - - if ($row->type == self::TYPE_IMAGE_SELECT || $row->type == self::TYPE_IMAGE_WITH_LINK) - { - $list = self::getSectionFieldDataList($row->id, $fieldSection, $sectionId, $userEmail); - $strImageHover = ''; - $strImageLink = ''; - - if ($row->type === self::TYPE_IMAGE_WITH_LINK) - { - $fieldValueArray = explode(',', $data['imgFieldId' . $row->id]); - $imageHover = array(); - $imageLink = array(); - - foreach ($fieldValueArray as $index => $fieldValue) - { - $imageHover[$index] = $data['image_hover' . $fieldValue]; - $imageLink[$index] = $data['image_link' . $fieldValue]; - } - - $strImageHover = implode(',,,,,', $imageHover); - $strImageLink = implode(',,,,,', $imageLink); - - $sql = $db->getQuery(true); - $sql->update($db->qn('#__redshop_fields_data')) - ->set($db->qn('alt_text') . ' = ' . $db->quote($strImageHover)) - ->set($db->qn('image_link') . ' = ' . $db->quote($strImageLink)) - ->where($db->qn('itemid') . ' = ' . (int) $sectionId) - ->where($db->qn('section') . ' = ' . $db->quote($fieldSection)) - ->where($db->qn('user_email') . ' = ' . $db->quote($userEmail)) - ->where($db->qn('fieldid') . ' = ' . (int) $row->id); - - $db->setQuery($sql)->execute(); - } - - // Reset $sql query - $sql = $db->getQuery(true); - - if (!empty($list)) - { - $sql->update($db->qn('#__redshop_fields_data')) - ->set($db->qn('data_txt') . ' = ' . $db->quote((string) $data['imgFieldId' . $row->id])) - ->where($db->qn('itemid') . ' = ' . (int) $sectionId) - ->where($db->qn('section') . ' = ' . $db->quote($fieldSection)) - ->where($db->qn('user_email') . ' = ' . $db->quote($userEmail)) - ->where($db->qn('fieldid') . ' = ' . (int) $row->id); - } - else - { - $sql->insert($db->qn('#__redshop_fields_data')) - ->columns($db->qn(array('fieldid', 'data_txt', 'itemid', 'section', 'alt_text', 'image_link', 'user_email'))) - ->values( - implode( - ',', - array( - (int) $row->id, - $db->quote($data['imgFieldId' . $row->id]), - (int) $sectionId, - $db->quote($fieldSection), - $db->quote($strImageHover), - $db->quote($strImageLink), - $db->quote($userEmail) - ) - ) - ); - } - - $db->setQuery($sql); - $db->execute(); - } - else - { - if ($row->type == self::TYPE_CHECK_BOX || $row->type == self::TYPE_RADIO_BUTTON) - { + /** + * Extra Field Type for Input Text Element + * + * @var int + */ + const TYPE_TEXT = 1; + + /** + * Extra Field Type for Input Text Area Element + * + * @var int + */ + const TYPE_TEXT_AREA = 2; + + /** + * Extra Field Type for Checkboxes Element + * + * @var int + */ + const TYPE_CHECK_BOX = 3; + + /** + * Extra Field Type for Input Radio Button Element + * + * @var int + */ + const TYPE_RADIO_BUTTON = 4; + + /** + * Extra Field Type for Input Single Select Element + * + * @var int + */ + const TYPE_SELECT_BOX_SINGLE = 5; + + /** + * Extra Field Type for Input Multi Select Element + * + * @var int + */ + const TYPE_SELECT_BOX_MULTIPLE = 6; + + /** + * Extra Field Type for Country Select List Element + * + * @var int + */ + const TYPE_SELECT_COUNTRY_BOX = 7; + + /** + * Extra Field Type for WYSIWYG Editor + * + * @var int + */ + const TYPE_WYSIWYG = 8; + + /** + * Extra Field Type for Input Media element + * + * @var int + */ + const TYPE_MEDIA = 9; + + /** + * Extra Field Type for Document + * + * @var int + */ + const TYPE_DOCUMENTS = 10; + + /** + * Extra Field Type for Image select + * + * @var int + */ + const TYPE_IMAGE_SELECT = 11; + + /** + * Extra Field Type for Date Picket element. + * + * @var int + */ + const TYPE_DATE_PICKER = 12; + + /** + * Extra Field Type for with link + * + * @var int + */ + const TYPE_IMAGE_WITH_LINK = 13; + + /** + * Extra Field Type for selection based on selected condition. + * + * @var int + */ + const TYPE_SELECTION_BASED_ON_SELECTED_CONDITIONS = 15; + + /** + * Extra Field Type joomla articles related + * + * @var int + */ + const TYPE_JOOMLA_RELATED_ARTICLES = 16; + + /** + * Extra Field Type for product finder date picker. + * + * @var int + */ + const TYPE_PRODUCT_FINDER_DATE_PICKER = 17; + + /** + * Extra Field Section Id for Product + * + * @var integer + */ + const SECTION_PRODUCT = 1; + + /** + * Extra Field Section Id for Category + * + * @var integer + */ + const SECTION_CATEGORY = 2; + + /** + * Extra Field Section Id for Form + * + * @var integer + */ + const SECTION_FORM = 3; + + /** + * Extra Field Section Id for Email + * + * @var integer + */ + const SECTION_EMAIL = 4; + + /** + * Extra Field Section Id for Confirmation + * + * @var integer + */ + const SECTION_CONFIRMATION = 5; + + /** + * Extra Field Section Id for User information + * + * @var integer + */ + const SECTION_USER_INFORMATIONS = 6; + + /** + * Extra Field Section Id for Private Billing Address + * + * @var integer + */ + const SECTION_PRIVATE_BILLING_ADDRESS = 7; + + /** + * Extra Field Section Id for Private Billing Address + * + * @var integer + */ + const SECTION_COMPANY_BILLING_ADDRESS = 8; + + /** + * Extra Field Section Id for Color Sample + * + * @var integer + */ + const SECTION_COLOR_SAMPLE = 9; + + /** + * Extra Field Section Id for Manufacturer + * + * @var integer + */ + const SECTION_MANUFACTURER = 10; + + /** + * Extra Field Section Id for Shipping + * + * @var integer + */ + const SECTION_SHIPPING = 11; + + /** + * Extra Field Section Id for Product User Field + * + * @var integer + */ + const SECTION_PRODUCT_USERFIELD = 12; + + /** + * Extra Field Section Id for Gift Card User Field + * + * @var integer + */ + const SECTION_GIFT_CARD_USER_FIELD = 13; + + /** + * Extra Field Section Id for Private Shipping Address + * + * @var integer + */ + const SECTION_PRIVATE_SHIPPING_ADDRESS = 14; + + /** + * Extra Field Section Id for Company Shipping Address + * + * @var integer + */ + const SECTION_COMPANY_SHIPPING_ADDRESS = 15; + + /** + * Extra Field Section Id for Quotation + * + * @var integer + */ + const SECTION_QUOTATION = 16; + + /** + * Extra Field Section Id for Date Picker + * + * @var integer + */ + const SECTION_PRODUCT_FINDER_DATE_PICKER = 17; + + /** + * Extra Field Section Id for Payment Gateways + * + * @var integer + */ + const SECTION_PAYMENT_GATEWAY = 18; + + /** + * Extra Field Section Id for Shipping Gateways + * + * @var integer + */ + const SECTION_SHIPPING_GATEWAY = 19; + + /** + * Extra Field Section Id for Order + * + * @var integer + */ + const SECTION_ORDER = 20; + + /** + * List of fields data + * + * @var array + */ + protected static $fieldsData = array(); + + /** + * All fields information + * + * @var array + */ + protected static $fieldsName = array(); + + /** + * List of fields + * + * @var array + * + * @since 2.0.3 + */ + protected static $sectionFields = array(); + + /** + * Get Section Field Data List + * + * @param int $name Name of the field - Typically contains `rs_` prefix. + * @param int $section Section id of the field. + * @param int $sectionItem Section item id + * + * @return mixed|null + */ + public static function getDataByName($name, $section, $sectionItem) + { + // Get Field id + if (!self::getField($name)) { + return null; + } + + $fieldId = self::getField($name)->id; + + return self::getData($fieldId, $section, $sectionItem); + } + + /** + * Get field information from field name. + * + * @param string $name Field name prefixed with `rs_` + * + * @return object|null Field information object otherwise null. + */ + public static function getField($name) + { + $fields = self::getList(); + + if (array_key_exists($name, $fields)) { + return $fields[$name]; + } + + return null; + } + + /** + * Get list of fields. + * + * @param integer $published Published Status which needs to be get. Default -1 will ignore any status. + * @param integer $limitStart Set limit start + * @param integer $limit Set limit + * + * @return array Array of all the available fields based on arguments. + */ + public static function getList($published = -1, $limitStart = 0, $limit = 0) + { + $db = JFactory::getDbo(); + + if (!empty(self::$fieldsName)) { + return self::$fieldsName; + } + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_fields')); + + if ($published >= 0) { + $query->where($db->qn('published') . ' = ' . (int)$published); + } + + self::$fieldsName = $db->setQuery($query, $limitStart, $limit)->loadObjectList('name'); + + return self::$fieldsName; + } + + /** + * Get Section Field Data List + * + * @param integer $fieldId Field id + * @param integer $section Section id of the field. + * @param integer $sectionItem Section item id + * + * @return mixed|null + */ + public static function getData($fieldId, $section, $sectionItem) + { + $key = $fieldId . '.' . $section . '.' . $sectionItem; + + if (array_key_exists($key, self::$fieldsData)) { + return self::$fieldsData[$key]; + } + + // Init null. + self::$fieldsData[$key] = null; + + if ($section == 1) { + $product = Redshop::product((int)$sectionItem); + + if ($product && isset($product->extraFields[$fieldId])) { + self::$fieldsData[$key] = $product->extraFields[$fieldId]; + } + } + + if (($section == 1 && !self::$fieldsData[$key]) || $section != 1) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('fd.*') + ->select($db->qn('f.title')) + ->from($db->qn('#__redshop_fields_data', 'fd')) + ->leftJoin($db->qn('#__redshop_fields', 'f') . ' ON ' . $db->qn('fd.fieldid') . ' = ' . $db->qn('f.id')) + ->where($db->qn('fd.itemid') . ' = ' . (int)$sectionItem) + ->where($db->qn('fd.fieldid') . ' = ' . (int)$fieldId) + ->where($db->qn('fd.section') . ' = ' . $db->quote($section)); + self::$fieldsData[$key] = $db->setQuery($query)->loadObject(); + } + + return self::$fieldsData[$key]; + } + + /** + * List all field in product + * + * @param integer $section Section product + * + * @return array + * + * @since 2.0.3 + */ + public static function listAllFieldInProduct($section = self::SECTION_PRODUCT) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select('*') + ->from($db->qn('#__redshop_fields')) + ->where($db->qn('section') . ' = ' . (int)$section) + ->where($db->qn('display_in_product') . ' = 1') + ->where($db->qn('published') . ' = 1') + ->order($db->qn('ordering')); + + return $db->setQuery($query)->loadObjectList(); + } + + /** + * List all fields + * + * @param string $fieldSection Field section + * @param integer $sectionId Section ID + * @param string $fieldName Field name + * @param string $templateDesc Template + * @param int $front Show field in front + * @param int $checkout Show field in checkout + * + * @return string HTML + * + * @since 2.0.3 + */ + public static function listAllField( + $fieldSection = '', + $sectionId = 0, + $fieldName = '', + $templateDesc = '', + $front = 0, + $checkout = 0 + ) { + $db = JFactory::getDbo(); + + JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/models', 'RedshopModel'); + + /** @var RedshopModelFields $model */ + $model = JModelLegacy::getInstance('Fields', 'RedshopModel'); + $customFields = $model->getFieldsBySection($fieldSection, $fieldName, $front, $checkout); + + if (!count($customFields)) { + return ''; + } + + // Grouping + $customFieldsGrouped = array(0 => array()); + + foreach ($customFields as $customField) { + if (empty($customField->groupName)) { + $customFieldsGrouped[0][] = $customField; + } else { + $customFieldsGrouped[$customField->groupName][] = $customField; + } + } + + if (empty($customFieldsGrouped[0])) { + unset($customFieldsGrouped[0]); + } + + $active = key($customFieldsGrouped); + $active = !$active ? JText::_('COM_REDSHOP_FIELD_GROUP_NOGROUP') : $active; + $active = 'customfield-group-' . JFilterOutput::stringURLSafe($active); + $setName = 'customfields-section-' . $fieldSection . '-pane'; + $exField = '
    '; + $exField .= JHtml::_('bootstrap.startTabSet', $setName, array('active' => $active)); + + foreach ($customFieldsGrouped as $groupName => $customFieldGroup) { + if (empty($customFieldGroup)) { + continue; + } + + $tabName = !$groupName ? JText::_('COM_REDSHOP_FIELD_GROUP_NOGROUP') : $groupName; + $exField .= JHtml::_( + 'bootstrap.addTab', + $setName, + 'customfield-group-' . JFilterOutput::stringURLSafe($tabName), + $tabName + ); + $exField .= ''; + + foreach ($customFieldGroup as $customField) { + $type = $customField->type; + $dataValue = self::getSectionFieldDataList($customField->id, $fieldSection, $sectionId); + $exField .= ''; + $extraFieldValue = ""; + $extraFieldLabel = JText::_($customField->title); + $required = ''; + $reqlbl = ' reqlbl="" '; + $errormsg = ' errormsg="" '; + + if ($fieldSection == self::SECTION_QUOTATION && $customField->required == 1) { + $required = ' required="1" '; + $reqlbl = ' reqlbl="' . $extraFieldLabel . '" '; + $errormsg = ' errormsg="' . JText::_('COM_REDSHOP_THIS_FIELD_IS_REQUIRED') . '" '; + } + + switch ($type) { + case self::TYPE_TEXT: + $textValue = ($dataValue && $dataValue->data_txt) ? $dataValue->data_txt : ''; + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.text', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'textValue' => $textValue + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + break; + + case self::TYPE_TEXT_AREA: + $textareaValue = ($dataValue && $dataValue->data_txt) ? $dataValue->data_txt : ''; + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.textarea', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'textValue' => $textareaValue + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + break; + + case self::TYPE_CHECK_BOX: + $fieldChk = RedshopEntityField::getInstance($customField->id)->getFieldValues(); + $chkData = isset($dataValue->data_txt) ? explode(",", $dataValue->data_txt) + : []; + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.checkbox', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + break; + + case self::TYPE_RADIO_BUTTON: + $fieldChk = RedshopEntityField::getInstance($customField->id)->getFieldValues(); + $chkData = explode(",", $dataValue->data_txt); + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.radio', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + break; + + case self::TYPE_SELECT_BOX_SINGLE: + $fieldChk = RedshopEntityField::getInstance($customField->id)->getFieldValues(); + $chkData = explode(",", ($dataValue->data_txt ?? '')); + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.select', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + break; + + case self::TYPE_SELECT_BOX_MULTIPLE: + $fieldChk = RedshopEntityField::getInstance($customField->id)->getFieldValues(); + $chkData = explode(",", $dataValue->data_txt); + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.multiple', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + break; + + case self::TYPE_SELECT_COUNTRY_BOX: + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_country')); + $db->setQuery($query); + $fieldChk = $db->loadObjectList(); + $chkData = array(); + + if (!empty($dataValue->data_txt)) { + $chkData = explode(",", $dataValue->data_txt); + } + + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.multiple', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + break; + + case self::TYPE_JOOMLA_RELATED_ARTICLES: + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__content')) + ->where($db->qn('state') . ' = 1'); + $db->setQuery($query); + + $fieldChk = $db->loadObjectList(); + $chkData = explode(",", $dataValue->data_txt); + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.multiple', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + break; + + case self::TYPE_WYSIWYG: + $editor = JEditor::getInstance(JFactory::getConfig()->get('editor')); + $textareaValue = ($dataValue && $dataValue->data_txt) ? $dataValue->data_txt : ''; + + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.editor', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'textValue' => $textareaValue, + 'editor' => $editor + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + break; + + case self::TYPE_DOCUMENTS: + $dataTxt = array(); + + if (is_object($dataValue) && property_exists($dataValue, 'data_txt')) { + // Support Legacy string. + if (preg_match('/\n/', $dataValue->data_txt)) { + $documentExplode = explode("\n", $dataValue->data_txt); + $dataTxt = array($documentExplode[0] => $documentExplode[1]); + } else { + // Support for multiple file upload using JSON for better string handling + $dataTxt = json_decode($dataValue->data_txt); + } + } + + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.document', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'dataTxt' => $dataTxt, + 'dataValue' => $dataValue + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + break; + + case self::TYPE_IMAGE_SELECT: + + $fieldChk = RedshopEntityField::getInstance($customField->id)->getFieldValues(); + $dataValue = self::getSectionFieldDataList($customField->id, $fieldSection, $sectionId); + $value = ''; + + if ($dataValue) { + $value = $dataValue->data_txt; + } + + $chkData = explode(',', $value); + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.image', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData, + 'value' => $value, + 'sectionId' => $sectionId + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + break; + + case self::TYPE_DATE_PICKER: + + $format = Redshop::getConfig()->get('DEFAULT_DATEFORMAT', 'Y-m-d'); + $date = ''; + + if ($customField->section != 17) { + $date = date($format, time()); + } + + if ($dataValue) { + if ($dataValue->data_txt) { + $date = date($format, strtotime($dataValue->data_txt)); + } + } + + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.date_picker', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'date' => $date + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + + break; + + case self::TYPE_IMAGE_WITH_LINK: + + $fieldChk = RedshopEntityField::getInstance($customField->id)->getFieldValues(); + $dataValue = self::getSectionFieldDataList($customField->id, $fieldSection, $sectionId); + $value = ($dataValue) ? $dataValue->data_txt : ''; + $tmpImageHover = array(); + $tmpImageLink = array(); + + if ($dataValue->altText) { + $tmpImageHover = explode(',,,,,', $dataValue->altText); + } + + if ($dataValue->image_link) { + $tmpImageLink = explode(',,,,,', $dataValue->image_link); + } + + $chkData = explode(",", $dataValue->data_txt); + $imageLink = array(); + $imageHover = array(); + + if ($chkData !== false) { + foreach ($chkData as $index => $aChkData) { + $imageLink[$aChkData] = $tmpImageLink[$index]; + $imageHover[$aChkData] = $tmpImageHover[$index]; + } + } + + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.image_link', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData, + 'value' => $value, + 'sectionId' => $sectionId, + 'imageLink' => $imageLink, + 'imageHover' => $imageHover + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + + break; + + case self::TYPE_SELECTION_BASED_ON_SELECTED_CONDITIONS: + + if ($dataValue) { + if ($dataValue->data_txt) { + $mainSplitDateTotal = explode(" ", $dataValue->data_txt); + $mainSplitDate = explode(":", $mainSplitDateTotal[0]); + $mainSplitDateExtra = explode(":", $mainSplitDateTotal[1]); + $datePublish = date("d-m-Y", $mainSplitDate[0]); + $dateExpiry = date("d-m-Y", $mainSplitDate[1]); + } else { + $datePublish = date("d-m-Y"); + $dateExpiry = date("d-m-Y"); + $mainSplitDateExtra = array(); + } + } else { + $datePublish = date("d-m-Y"); + $dateExpiry = date("d-m-Y"); + $mainSplitDateExtra = array(); + } + + $exField .= RedshopLayoutHelper::render( + 'extrafields.field.selected_condition', + array( + 'rowData' => $customField, + 'extraFieldLabel' => $extraFieldLabel, + 'required' => $required, + 'requiredLabel' => $reqlbl, + 'errorMsg' => $errormsg, + 'datePublish' => $datePublish, + 'dateExpiry' => $dateExpiry, + 'mainSplitDateExtra' => $mainSplitDateExtra + ), + '', + array( + 'component' => 'com_redshop', + 'client' => 0 + ) + ); + + break; + + default: + JPluginHelper::importPlugin('redshop'); + $dispatcher = RedshopHelperUtility::getDispatcher(); + + $dispatcher->trigger('onDisplayListField', array(&$exField, $customField, $dataValue)); + } + + if (trim($templateDesc) != '') { + if (strstr($templateDesc, "{" . $customField->name . "}")) { + $templateDesc = str_replace("{" . $customField->name . "}", $extraFieldValue, $templateDesc); + $templateDesc = str_replace( + "{" . $customField->name . "_lbl}", + $extraFieldLabel, + $templateDesc + ); + } + + $templateDesc = str_replace("{" . $customField->name . "}", "", $templateDesc); + $templateDesc = str_replace("{" . $customField->name . "_lbl}", "", $templateDesc); + } else { + if (trim($customField->desc) == '') { + $exField .= ''; + } else { + $exField .= ''; + } + } + + $exField .= ''; + } + + $exField .= '
      ' + . JHtml::tooltip($customField->desc, $customField->name, 'tooltip.png', '', '') . '
    '; + $exField .= JHtml::_('bootstrap.endTab'); + } + + $exField .= JHtml::_('bootstrap.endTabSet'); + $exField .= '
    '; + + if (trim($templateDesc) != '') { + return $templateDesc; + } + + return $exField; + } + + /** + * Get section field data list + * + * @param integer $fieldId Field ID + * @param integer $section Section ID + * @param integer $orderItemId Order Item ID + * @param string $userEmail User Email + * + * @return object + * + * @since 2.0.3 + */ + public static function getSectionFieldDataList($fieldId, $section = 0, $orderItemId = 0, $userEmail = "") + { + JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/models', 'RedshopModel'); + + /** @var RedshopModelFields $model */ + $model = JModelLegacy::getInstance('Fields', 'RedshopModel'); + + return $model->getFieldDataList($fieldId, $section, $orderItemId, $userEmail); + } + + /** + * Save extra fields + * + * @param array $data Data to insert + * @param integer $fieldSection Field section to match + * @param string $sectionId Section ID + * @param string $userEmail User to match by email + * + * @return void + * @throws Exception + * + * @since 2.0.3 + */ + public static function extraFieldSave($data, $fieldSection, $sectionId = "", $userEmail = "") + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select('*') + ->from($db->qn('#__redshop_fields')) + ->where($db->qn('section') . ' = ' . (int)$fieldSection) + ->where($db->qn('published') . ' = 1'); + + $rows = (array)$db->setQuery($query)->loadObjectList(); + + if (empty($rows)) { + return; + } + + foreach ($rows as $row) { + $dataTxt = ''; + + if (isset($data[$row->name])) { + if ($row->type == self::TYPE_TEXT || $row->type == self::TYPE_TEXT_AREA) { + $dataTxt = \JFilterInput::getInstance()->clean($data[$row->name]); + } elseif ($row->type == self::TYPE_WYSIWYG) { + $inputField = JFactory::getApplication()->input->post->get($row->name, '', 'raw'); + $dataTxt = \JFilterInput::getInstance(null, null, 1, 1)->clean($inputField, 'html'); + } else { + $dataTxt = $data[$row->name]; + } + } + + // Save Document Extra Field + if ($row->type == self::TYPE_DOCUMENTS) { + $files = $_FILES[$row->name]['name']; + $texts = $data['text_' . $row->name]; + + $documentsValue = array(); + + if (isset($data[$row->name])) { + $documentsValue = $data[$row->name]; + } + + if (is_array($files) && !empty($files)) { + $documents = array(); + + foreach ($files as $index => $file) { + // Editing uploaded file + if (!empty($documentsValue[$index])) { + if (!empty(trim($texts[$index]))) { + $documents[trim($texts[$index])] = $documentsValue[$index]; + } else { + $documents[$index] = $documentsValue[$index]; + } + } + + if (!empty($file)) { + $name = RedshopHelperMedia::cleanFileName($file); + $src = $_FILES[$row->name]['tmp_name'][$index]; + $destination = REDSHOP_FRONT_DOCUMENT_RELPATH . 'extrafields/' . $name; + + JFile::upload($src, $destination); + + if (!empty(trim($texts[$index]))) { + $documents[trim($texts[$index])] = $name; + } else { + $documents[$index] = $name; + } + } + } + + // Convert array into JSON string for better handler. + $dataTxt = json_encode($documents); + } + } + + if ($row->type == self::TYPE_SELECTION_BASED_ON_SELECTED_CONDITIONS && $data[$row->name] !== "" && $data[$row->name . "_expiry"] !== "") { + $dataTxt = strtotime($data[$row->name]) . ":" . strtotime($data[$row->name . "_expiry"]) . " "; + + if (!empty($data[$row->name . "_extra_name"])) { + foreach ($data[$row->name . "_extra_name"] as $aData) { + $dataTxt .= strtotime($aData) . ':'; + } + } + } + + if (is_array($dataTxt)) { + $dataTxt = implode(',', $dataTxt); + } + + $sections = explode(',', $fieldSection); + + if ($row->type == self::TYPE_IMAGE_SELECT || $row->type == self::TYPE_IMAGE_WITH_LINK) { + $list = self::getSectionFieldDataList($row->id, $fieldSection, $sectionId, $userEmail); + $strImageHover = ''; + $strImageLink = ''; + + if ($row->type === self::TYPE_IMAGE_WITH_LINK) { + $fieldValueArray = explode(',', $data['imgFieldId' . $row->id]); + $imageHover = array(); + $imageLink = array(); + + foreach ($fieldValueArray as $index => $fieldValue) { + $imageHover[$index] = $data['image_hover' . $fieldValue]; + $imageLink[$index] = $data['image_link' . $fieldValue]; + } + + $strImageHover = implode(',,,,,', $imageHover); + $strImageLink = implode(',,,,,', $imageLink); + + $sql = $db->getQuery(true); + $sql->update($db->qn('#__redshop_fields_data')) + ->set($db->qn('alt_text') . ' = ' . $db->quote($strImageHover)) + ->set($db->qn('image_link') . ' = ' . $db->quote($strImageLink)) + ->where($db->qn('itemid') . ' = ' . (int)$sectionId) + ->where($db->qn('section') . ' = ' . $db->quote($fieldSection)) + ->where($db->qn('user_email') . ' = ' . $db->quote($userEmail)) + ->where($db->qn('fieldid') . ' = ' . (int)$row->id); + + $db->setQuery($sql)->execute(); + } + + // Reset $sql query + $sql = $db->getQuery(true); + + if (!empty($list)) { + $sql->update($db->qn('#__redshop_fields_data')) + ->set($db->qn('data_txt') . ' = ' . $db->quote((string)$data['imgFieldId' . $row->id])) + ->where($db->qn('itemid') . ' = ' . (int)$sectionId) + ->where($db->qn('section') . ' = ' . $db->quote($fieldSection)) + ->where($db->qn('user_email') . ' = ' . $db->quote($userEmail)) + ->where($db->qn('fieldid') . ' = ' . (int)$row->id); + } else { + $sql->insert($db->qn('#__redshop_fields_data')) + ->columns( + $db->qn( + array( + 'fieldid', + 'data_txt', + 'itemid', + 'section', + 'alt_text', + 'image_link', + 'user_email' + ) + ) + ) + ->values( + implode( + ',', + array( + (int)$row->id, + $db->quote($data['imgFieldId' . $row->id]), + (int)$sectionId, + $db->quote($fieldSection), + $db->quote($strImageHover), + $db->quote($strImageLink), + $db->quote($userEmail) + ) + ) + ); + } + + $db->setQuery($sql); + $db->execute(); + } else { + if ($row->type == self::TYPE_CHECK_BOX || $row->type == self::TYPE_RADIO_BUTTON) { $dataTxt = urldecode($dataTxt); } - foreach ($sections as $section) - { - $list = self::getSectionFieldDataList($row->id, (int) $section, (int) $sectionId, $userEmail); - $sql = $db->getQuery(true); - - if (!empty($list)) - { - $sql->update($db->qn('#__redshop_fields_data')) - ->set($db->qn('data_txt') . ' = ' . $db->quote($dataTxt)) - ->where($db->qn('itemid') . ' = ' . (int) $sectionId) - ->where($db->qn('section') . ' = ' . (int) $section) - ->where($db->qn('user_email') . ' = ' . $db->quote($userEmail)) - ->where($db->qn('fieldid') . ' = ' . (int) $row->id); - - $db->setQuery($sql)->execute(); - - continue; - } - - if (!empty($dataTxt)) - { - $sql->insert($db->qn('#__redshop_fields_data')) - ->columns($db->qn(array('fieldid', 'data_txt', 'itemid', 'section', 'user_email'))) - ->values( - implode( - ',', - array( - (int) $row->id, - $db->quote($dataTxt), - (int) $sectionId, - (int) $section, - $db->quote($userEmail) - ) - ) - ); - - $db->setQuery($sql)->execute(); - } - } - } - } - } - - /** - * Validate Extra Field - * - * @param integer $fieldSection Field Section List - * @param integer $sectionId Section ID - * - * @return boolean - * - * @since 2.0.3 - */ - public static function CheckExtraFieldValidation($fieldSection = 0, $sectionId = 0) - { - $rowData = self::getSectionFieldList($fieldSection); - - for ($i = 0, $in = count($rowData); $i < $in; $i++) - { - $required = $rowData[$i]->required; - $dataValue = self::getSectionFieldDataList($rowData[$i]->id, $fieldSection, $sectionId); - - if (empty($dataValue) && $required) - { - return $rowData[$i]->title; - } - } - - return false; - } - - /** - * List all fields and display - * - * @param integer $fieldSection Field section - * @param integer $sectionId Section ID - * @param integer $flag Flag - * @param string $userEmail User email - * @param string $templateDesc Template description - * @param boolean $sendmail True/ False - * - * @return string - * - * @since 2.0.3 - */ - public static function listAllFieldDisplay($fieldSection = 0, $sectionId = 0, $flag = 0, $userEmail = "", $templateDesc = "", $sendmail = false) - { - $rowData = self::getSectionFieldList($fieldSection); - - $exField = ''; - - for ($i = 0, $in = count($rowData); $i < $in; $i++) - { - $type = $rowData[$i]->type; - $extraFieldValue = ""; - $extraFieldLabel = $rowData[$i]->title; - - if ($flag == 1) - { - if ($i > 0) - { - $exField .= "
    "; - } - - $exField .= JText::_($extraFieldLabel) . ' : '; - } - - $dataValue = self::getSectionFieldDataList($rowData[$i]->id, $fieldSection, $sectionId, $userEmail); - - switch ($type) - { - case self::TYPE_TEXT: - $extraFieldValue = ($dataValue && $dataValue->data_txt) ? $dataValue->data_txt : ''; - $exField .= RedshopLayoutHelper::render( - 'field_display.text', - array( - 'extraFieldLabel' => $extraFieldLabel, - 'extraFieldValue' => $extraFieldValue, - 'sendMail' => $sendmail - ), - '', - array( - 'component' => 'com_redshop' - ) - ); - break; - - case self::TYPE_TEXT_AREA: - $extraFieldValue = ($dataValue && $dataValue->data_txt) ? $dataValue->data_txt : ''; - $exField .= RedshopLayoutHelper::render( - 'field_display.textarea', - array( - 'extraFieldLabel' => $extraFieldLabel, - 'extraFieldValue' => $extraFieldValue, - 'sendMail' => $sendmail - ), - '', - array( - 'component' => 'com_redshop' - ) - ); - break; - - case self::TYPE_CHECK_BOX: - $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); - $chkData = !empty($dataValue->data_txt) ? explode(",", $dataValue->data_txt) : array(); - $extraFieldValue = []; - - foreach ($fieldChk as $key => $data) - { - if (!in_array($data->field_value, $chkData)) - { - continue; - } - - $extraFieldValue[] = $data->field_name; - } - - $exField .= RedshopLayoutHelper::render( - 'field_display.checkbox', - array( - 'extraFieldLabel' => $extraFieldLabel, - 'extraFieldValue' => implode(',', $extraFieldValue), - 'sendMail' => $sendmail - ), - '', - array( - 'component' => 'com_redshop' - ) - ); - break; - - case self::TYPE_RADIO_BUTTON: - $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); - $chkData = !empty($dataValue->data_txt) ? explode(",", $dataValue->data_txt) : array(); - $extraFieldValue = ''; - - foreach ($fieldChk as $key => $data) - { - if (!in_array($data->field_value, $chkData)) - { - continue; - } - - $extraFieldValue .= $data->field_name; - } - - $exField .= RedshopLayoutHelper::render( - 'field_display.radio', - array( - 'extraFieldLabel' => $extraFieldLabel, - 'extraFieldValue' => $extraFieldValue, - 'sendMail' => $sendmail - ), - '', - array( - 'component' => 'com_redshop' - ) - ); - break; - - case self::TYPE_SELECT_BOX_SINGLE: - $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); - $chkData = !empty($dataValue->data_txt) ? explode(",", $dataValue->data_txt) : array(); - $extraFieldValue = ''; - - foreach ($fieldChk as $key => $data) - { - if (!in_array($data->field_value, $chkData)) - { - continue; - } - - $extraFieldValue .= $data->field_name; - } - - $exField .= RedshopLayoutHelper::render( - 'field_display.select', - array( - 'extraFieldLabel' => $extraFieldLabel, - 'extraFieldValue' => $extraFieldValue, - 'sendMail' => $sendmail - ), - '', - array( - 'component' => 'com_redshop' - ) - ); - break; - - case self::TYPE_SELECT_BOX_MULTIPLE: - $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); - $chkData = !empty($dataValue->data_txt) ? explode(",", $dataValue->data_txt) : array(); - $extraFieldValue = array(); - - foreach ($fieldChk as $key => $data) - { - if (!in_array($data->field_value, $chkData)) - { - continue; - } - - $extraFieldValue[] = $data->field_name; - } - - $exField .= RedshopLayoutHelper::render( - 'field_display.multiple', - array( - 'extraFieldLabel' => $extraFieldLabel, - 'extraFieldValue' => $extraFieldValue, - 'sendMail' => $sendmail - ), - '', - array( - 'component' => 'com_redshop' - ) - ); - break; - - case self::TYPE_SELECT_COUNTRY_BOX: - $extraFieldValue = ""; - - if ($dataValue && $dataValue->data_txt) - { - $fieldChk = RedshopEntityCountry::getInstance($dataValue->data_txt); - $extraFieldValue = $fieldChk->get('country_name'); - } - - $exField .= RedshopLayoutHelper::render( - 'field_display.country', - array( - 'extraFieldLabel' => $extraFieldLabel, - 'extraFieldValue' => $extraFieldValue, - 'sendMail' => $sendmail - ), - '', - array( - 'component' => 'com_redshop' - ) - ); - break; - - // 12 :- Date Picker - case self::TYPE_DATE_PICKER: - $extraFieldValue = ($dataValue && $dataValue->data_txt) ? $dataValue->data_txt : ''; - $exField .= RedshopLayoutHelper::render( - 'field_display.datepicker', - array( - 'extraFieldLabel' => $extraFieldLabel, - 'extraFieldValue' => $extraFieldValue, - 'sendMail' => $sendmail - ), - '', - array( - 'component' => 'com_redshop' - ) - ); - break; - } - - if (trim($templateDesc) != '') - { - if (strstr($templateDesc, "{" . $rowData[$i]->name . "}")) - { - $templateDesc = str_replace("{" . $rowData[$i]->name . "}", $extraFieldValue, $templateDesc); - $templateDesc = str_replace("{" . $rowData[$i]->name . "_lbl}", $extraFieldLabel, $templateDesc); - } - - $templateDesc = str_replace("{" . $rowData[$i]->name . "}", "", $templateDesc); - $templateDesc = str_replace("{" . $rowData[$i]->name . "_lbl}", "", $templateDesc); - } - } - - if (trim($templateDesc) != '') - { - return $templateDesc; - } - - if ($flag == 0 && !empty($extraFieldLabel)) - { - $client = null; - $fieldLayout = 'fields.display'; - - if ($sendmail) - { - $fieldLayout = 'fields.mail'; - $client = array('client' => 0); - } - - return RedshopLayoutHelper::render( - $fieldLayout, - array('extraFieldValue' => $exField), - null, - $client - ); - } - - return $exField; - } - - /** - * List all user fields - * - * @param string $fieldSection Field Section - * @param integer $sectionId Section ID - * @param string $fieldType Field type - * @param string $uniqueId Unique ID - * - * @return array - * - * @since 2.0.3 - */ - public static function listAllUserFields($fieldSection = "", $sectionId = self::SECTION_PRODUCT_USERFIELD, $fieldType = '', $uniqueId = '') - { - /** @scrutinizer ignore-deprecated */ - JHtml::script('com_redshop/redshop.attribute.min.js', false, true); - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select('*') - ->from($db->qn('#__redshop_fields')) - ->where($db->qn('section') . ' = ' . (int) $sectionId) - ->where($db->qn('name') . ' = ' . $db->quote($fieldSection)) - ->where($db->qn('published') . ' = 1'); - - $rowData = $db->setQuery($query)->loadObjectList(); - $exField = ''; - $exFieldTitle = ''; - $cart = \Redshop\Cart\Helper::getCart(); - $idx = 0; - - if (isset($cart['idx'])) - { - $idx = (int) ($cart['idx']); - } - - for ($i = 0, $in = count($rowData); $i < $in; $i++) - { - $type = $rowData[$i]->type; - $asterisk = $rowData[$i]->required > 0 ? '* ' : ''; - - if ($fieldType != 'hidden') - { - $exFieldTitle .= '
    ' . $asterisk . $rowData[$i]->title . '
    '; - } - - if ($fieldType == 'hidden') - { - $exField .= ''; - } - else - { - $req = ' required = "' . $rowData[$i]->required . '"'; - - switch ($type) - { - case self::TYPE_TEXT: - $exField .= RedshopLayoutHelper::render( - 'extrafields.userfield.text', - array( - 'rowData' => $rowData[$i], - 'required' => $req, - 'uniqueId' => $uniqueId - ) - ); - break; - - case self::TYPE_TEXT_AREA: - $exField .= RedshopLayoutHelper::render( - 'extrafields.userfield.textarea', - array( - 'rowData' => $rowData[$i], - 'required' => $req, - 'uniqueId' => $uniqueId - ) - ); - break; - - case self::TYPE_CHECK_BOX: - $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); - $chkData = explode(",", $cart[$idx][$rowData[$i]->name]); - $exField .= RedshopLayoutHelper::render( - 'extrafields.userfield.checkbox', - array( - 'rowData' => $rowData[$i], - 'required' => $req, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData, - 'uniqueId' => $uniqueId - ) - ); - break; - - case self::TYPE_RADIO_BUTTON: - $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); - $chkData = explode(",", $cart[$idx][$rowData[$i]->name]); - $exField .= RedshopLayoutHelper::render( - 'extrafields.userfield.radio', - array( - 'rowData' => $rowData[$i], - 'required' => $req, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData, - 'uniqueId' => $uniqueId - ) - ); - break; - - case self::TYPE_SELECT_BOX_SINGLE: - $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); - $chkData = explode(",", $cart[$idx][$rowData[$i]->name]); - $exField .= RedshopLayoutHelper::render( - 'extrafields.userfield.select', - array( - 'rowData' => $rowData[$i], - 'required' => $req, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData, - 'uniqueId' => $uniqueId - ) - ); - break; - - case self::TYPE_SELECT_BOX_MULTIPLE: - $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); - $chkData = explode(",", $cart[$idx][$rowData[$i]->name]); - $exField .= RedshopLayoutHelper::render( - 'extrafields.userfield.multiple', - array( - 'rowData' => $rowData[$i], - 'required' => $req, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData, - 'uniqueId' => $uniqueId - ) - ); - break; - - case self::TYPE_DOCUMENTS: - $exField .= RedshopLayoutHelper::render( - 'extrafields.userfield.document', - array( - 'rowData' => $rowData[$i], - 'required' => $req, - 'fieldCheck' => $req, - 'uniqueId' => $uniqueId - ) - ); - break; - - case self::TYPE_IMAGE_SELECT: - $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); - $chkData = explode(",", $cart[$idx][$rowData[$i]->name]); - $exField .= RedshopLayoutHelper::render( - 'extrafields.userfield.image', - array( - 'rowData' => $rowData[$i], - 'required' => $req, - 'fieldCheck' => $fieldChk, - 'checkData' => $chkData, - 'uniqueId' => $uniqueId - ) - ); - break; - - case self::TYPE_DATE_PICKER: - $req = $rowData[$i]->required; - $exField .= RedshopLayoutHelper::render( - 'extrafields.userfield.date_picker', - array( - 'rowData' => $rowData[$i], - 'required' => $req, - 'fieldCheck' => $req, - 'uniqueId' => $uniqueId - ) - ); - break; - } - } - - if (trim($rowData[$i]->desc) != '' && $fieldType != 'hidden') - { - $exField .= '
      ' - . JHtml::tooltip($rowData[$i]->desc, $rowData[$i]->name, 'tooltip.png', '', '', false) - . '
    '; - } - } - - return array($exFieldTitle, $exField); - } - - /** - * Render HTML radio list - * - * @param string $name Name of radio checkbox - * @param mixed $attribs Attribute values - * @param array $selected The name of the object variable for the option text - * @param string $yes Option Days - * @param string $no Option Weeks - * @param boolean $id ID of radio checkbox - * - * @return string - * - * @since 2.0.3 - */ - public static function booleanList($name, $attribs = null, $selected = null, $yes = 'yes', $no = 'no', $id = false) - { - $arr = array( - JHtml::_('select.option', "Days", JText::_($yes)), - JHtml::_('select.option', "Weeks", JText::_($no)) - ); - - return JHtml::_('select.radiolist', $arr, $name, $attribs, 'value', 'text', $selected, $id); - } - - /** - * Render HTML radio list with options - * - * @param string $name Name of radio checkbox - * @param mixed $attribs Attribute values - * @param array $selected The name of the object variable for the option text - * @param string $yes Option Days - * @param string $no Option Weeks - * @param boolean $id ID of radio checkbox - * @param string $yesValue ID of radio checkbox - * @param string $noValue ID of radio checkbox - * - * @return string - * - * @since 2.0.3 - */ - public static function rsBooleanList($name, $attribs = null, $selected = null, $yes = 'yes', $no = 'no', $id = false, $yesValue = 'Days', $noValue = 'Weeks') - { - $arr = array( - JHtml::_('select.option', $yesValue, JText::_($yes)), - JHtml::_('select.option', $noValue, JText::_($no)) - ); - - return JHtml::_('redshopselect.radiolist', $arr, $name, $attribs, 'value', 'text', $selected, $id); - } - - /** - * Get fields value by ID - * - * @param integer $id ID of field - * - * @return array - * - * @since 2.0.3 - * - * @deprecated 2.0.6 Use RedshopEntityField::getFieldValues instead. - */ - public static function getFieldValue($id) - { - return RedshopEntityField::getInstance($id)->getFieldValues(); - } - - /** - * Get Section Field List - * - * @param integer $section Section ID - * @param integer $front Field show in front - * @param integer $published Field show in front - * @param integer $required Field show in front - * - * @return array - * - * @since 2.0.3 - */ - public static function getSectionFieldList($section = self::SECTION_PRODUCT_USERFIELD, $front = null, $published = 1, $required = 0) - { - $key = $section . '_' . $front . '_' . $published . '_' . $required; - - if (!array_key_exists($key, static::$sectionFields)) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query->select('*') - ->from($db->qn('#__redshop_fields')) - ->where($db->qn('section') . ' = ' . (int) $section) - ->order($db->qn('ordering')); - - if (null !== $front) - { - $query->where($db->qn('show_in_front') . ' = ' . (int) $front); - } - - if ($published) - { - $query->where($db->qn('published') . ' = ' . (int) $published); - } - - if ($required) - { - $query->where($db->qn('required') . ' = ' . (int) $required); - } - - static::$sectionFields[$key] = $db->setQuery($query)->loadObjectList(); - } - - return static::$sectionFields[$key]; - } - - /** - * Get section field data list - * - * @param integer $fieldId Field ID - * @param integer $section Section ID - * @param integer $orderItemId Order Item ID - * @param string $userEmail User Email - * - * @return object - * - * @since 2.0.3 - */ - public static function getSectionFieldDataList($fieldId, $section = 0, $orderItemId = 0, $userEmail = "") - { - JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/models', 'RedshopModel'); - - /** @var RedshopModelFields $model */ - $model = JModelLegacy::getInstance('Fields', 'RedshopModel'); - - return $model->getFieldDataList($fieldId, $section, $orderItemId, $userEmail); - } - - /** - * Copy product extra field - * - * @param integer $oldProductId Old Product ID - * @param integer $newPid New Product ID - * - * @return void - * - * @since 2.0.3 - */ - public static function copyProductExtraField($oldProductId, $newPid) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query->select('*') - ->from($db->qn('#__redshop_fields_data')) - ->where($db->qn('itemid') . ' = ' . (int) $oldProductId) - ->where( - '(' . $db->qn('section') . ' = ' . $db->quote('1') - . ' or ' . - $db->qn('section') . ' = ' . $db->quote('12') - . ' or ' . - $db->qn('section') . ' = ' . $db->quote('17') . ')' - ); - - $db->setQuery($query); - $list = $db->loadObjectList(); - - // Skip process if there are no custom fields. - if (empty($list)) - { - return; - } - - $query->clear() - ->insert($db->qn('#__redshop_fields_data')) - ->columns($db->qn(array('fieldid', 'data_txt', 'itemid', 'section', 'alt_text', 'image_link', 'user_email'))); - - foreach ($list as $row) - { - $query->values( - implode(',', array( - (int) $row->fieldid, - $db->quote($row->data_txt), - (int) $newPid, - (int) $row->section, - $db->quote($row->alt_text), - $db->quote($row->image_link), - $db->quote($row->user_email)) - ) - ); - } - - $db->setQuery($query)->execute(); - } - - /** - * Delete extra field data - * - * @param integer $dataId Data ID - * - * @return void - * - * @since 2.0.3 - */ - public static function deleteExtraFieldData($dataId) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->delete($db->qn('#__redshop_fields_data')) - ->where($db->qn('data_id') . ' = ' . (int) $dataId); - - $db->setQuery($query); - $db->execute(); - } - - /** - * Method for render HTML of extra fields - * - * @param integer $fieldSection Field section - * @param integer $sectionId ID of section - * @param string $fieldName Field name - * @param string $templateContent HTML template content - * @param integer $categoryPage Category page - * - * @return mixed - * @throws Exception - * - * @since 2.0.6 - * - * @deprecated 2.1.0 - */ - public static function extraFieldDisplay($fieldSection = 0, $sectionId = 0, $fieldName = "", $templateContent = "", $categoryPage = 0) - { - return ExtraFields::displayExtraFields($fieldSection, $sectionId, $fieldName, $templateContent, (boolean) $categoryPage); - } - - /** - * Method for get article joomla by id. - * - * @param string $ids Is required? - * - * @return mixed - */ - public static function getArticleJoomlaById($ids) - { - $db = \JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__content')) - ->where($db->qn('id') . ' IN (' . $ids . ')'); - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * Method get display field data - * - * @param mixed $data Is required? - * @param string $layout Is required? - * @param integer $fieldId - * @param string $dataTxt - * - * @return string - */ - public static function getDisplayFieldData($data, $layout, $fieldId = 0, $dataTxt = '') - { - if (empty($data)) - { - $fieldValues = \RedshopEntityField::getInstance($fieldId)->getFieldValues(); - $checkData = explode(',', $dataTxt); - $data = $layout == 'select' ? array() : ''; - - foreach ($fieldValues as $value) - { - if (!in_array(urlencode($value->field_value), $checkData) && !in_array($value->field_value, $checkData)) - { - continue; - } - - if ($layout == 'select') - { - $data[] = urldecode($value->field_name); - } - else - { - $data = urldecode($value->field_name); - } - } - } - - return \RedshopLayoutHelper::render( - 'extrafields.display.' . $layout, - array( - 'data' => $data - ) - ); - } + foreach ($sections as $section) { + $list = self::getSectionFieldDataList($row->id, (int)$section, (int)$sectionId, $userEmail); + $sql = $db->getQuery(true); + + if (!empty($list)) { + $sql->update($db->qn('#__redshop_fields_data')) + ->set($db->qn('data_txt') . ' = ' . $db->quote($dataTxt)) + ->where($db->qn('itemid') . ' = ' . (int)$sectionId) + ->where($db->qn('section') . ' = ' . (int)$section) + ->where($db->qn('user_email') . ' = ' . $db->quote($userEmail)) + ->where($db->qn('fieldid') . ' = ' . (int)$row->id); + + $db->setQuery($sql)->execute(); + + continue; + } + + if (!empty($dataTxt)) { + $sql->insert($db->qn('#__redshop_fields_data')) + ->columns($db->qn(array('fieldid', 'data_txt', 'itemid', 'section', 'user_email'))) + ->values( + implode( + ',', + array( + (int)$row->id, + $db->quote($dataTxt), + (int)$sectionId, + (int)$section, + $db->quote($userEmail) + ) + ) + ); + + $db->setQuery($sql)->execute(); + } + } + } + } + } + + /** + * Validate Extra Field + * + * @param integer $fieldSection Field Section List + * @param integer $sectionId Section ID + * + * @return boolean + * + * @since 2.0.3 + */ + public static function CheckExtraFieldValidation($fieldSection = 0, $sectionId = 0) + { + $rowData = self::getSectionFieldList($fieldSection); + + for ($i = 0, $in = count($rowData); $i < $in; $i++) { + $required = $rowData[$i]->required; + $dataValue = self::getSectionFieldDataList($rowData[$i]->id, $fieldSection, $sectionId); + + if (empty($dataValue) && $required) { + return $rowData[$i]->title; + } + } + + return false; + } + + /** + * Get Section Field List + * + * @param integer $section Section ID + * @param integer $front Field show in front + * @param integer $published Field show in front + * @param integer $required Field show in front + * + * @return array + * + * @since 2.0.3 + */ + public static function getSectionFieldList( + $section = self::SECTION_PRODUCT_USERFIELD, + $front = null, + $published = 1, + $required = 0 + ) { + $key = $section . '_' . $front . '_' . $published . '_' . $required; + + if (!array_key_exists($key, static::$sectionFields)) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->select('*') + ->from($db->qn('#__redshop_fields')) + ->where($db->qn('section') . ' = ' . (int)$section) + ->order($db->qn('ordering')); + + if (null !== $front) { + $query->where($db->qn('show_in_front') . ' = ' . (int)$front); + } + + if ($published) { + $query->where($db->qn('published') . ' = ' . (int)$published); + } + + if ($required) { + $query->where($db->qn('required') . ' = ' . (int)$required); + } + + static::$sectionFields[$key] = $db->setQuery($query)->loadObjectList(); + } + + return static::$sectionFields[$key]; + } + + /** + * List all fields and display + * + * @param integer $fieldSection Field section + * @param integer $sectionId Section ID + * @param integer $flag Flag + * @param string $userEmail User email + * @param string $templateDesc Template description + * @param boolean $sendmail True/ False + * + * @return string + * + * @since 2.0.3 + */ + public static function listAllFieldDisplay( + $fieldSection = 0, + $sectionId = 0, + $flag = 0, + $userEmail = "", + $templateDesc = "", + $sendmail = false + ) { + $rowData = self::getSectionFieldList($fieldSection); + + $exField = ''; + + for ($i = 0, $in = count($rowData); $i < $in; $i++) { + $type = $rowData[$i]->type; + $extraFieldValue = ""; + $extraFieldLabel = $rowData[$i]->title; + + if ($flag == 1) { + if ($i > 0) { + $exField .= "
    "; + } + + $exField .= JText::_($extraFieldLabel) . ' : '; + } + + $dataValue = self::getSectionFieldDataList($rowData[$i]->id, $fieldSection, $sectionId, $userEmail); + + switch ($type) { + case self::TYPE_TEXT: + $extraFieldValue = ($dataValue && $dataValue->data_txt) ? $dataValue->data_txt : ''; + $exField .= RedshopLayoutHelper::render( + 'field_display.text', + array( + 'extraFieldLabel' => $extraFieldLabel, + 'extraFieldValue' => $extraFieldValue, + 'sendMail' => $sendmail + ), + '', + array( + 'component' => 'com_redshop' + ) + ); + break; + + case self::TYPE_TEXT_AREA: + $extraFieldValue = ($dataValue && $dataValue->data_txt) ? $dataValue->data_txt : ''; + $exField .= RedshopLayoutHelper::render( + 'field_display.textarea', + array( + 'extraFieldLabel' => $extraFieldLabel, + 'extraFieldValue' => $extraFieldValue, + 'sendMail' => $sendmail + ), + '', + array( + 'component' => 'com_redshop' + ) + ); + break; + + case self::TYPE_CHECK_BOX: + $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); + $chkData = !empty($dataValue->data_txt) ? explode(",", $dataValue->data_txt) : array(); + $extraFieldValue = []; + + foreach ($fieldChk as $key => $data) { + if (!in_array($data->field_value, $chkData)) { + continue; + } + + $extraFieldValue[] = $data->field_name; + } + + $exField .= RedshopLayoutHelper::render( + 'field_display.checkbox', + array( + 'extraFieldLabel' => $extraFieldLabel, + 'extraFieldValue' => implode(',', $extraFieldValue), + 'sendMail' => $sendmail + ), + '', + array( + 'component' => 'com_redshop' + ) + ); + break; + + case self::TYPE_RADIO_BUTTON: + $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); + $chkData = !empty($dataValue->data_txt) ? explode(",", $dataValue->data_txt) : array(); + $extraFieldValue = ''; + + foreach ($fieldChk as $key => $data) { + if (!in_array($data->field_value, $chkData)) { + continue; + } + + $extraFieldValue .= $data->field_name; + } + + $exField .= RedshopLayoutHelper::render( + 'field_display.radio', + array( + 'extraFieldLabel' => $extraFieldLabel, + 'extraFieldValue' => $extraFieldValue, + 'sendMail' => $sendmail + ), + '', + array( + 'component' => 'com_redshop' + ) + ); + break; + + case self::TYPE_SELECT_BOX_SINGLE: + $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); + $chkData = !empty($dataValue->data_txt) ? explode(",", $dataValue->data_txt) : array(); + $extraFieldValue = ''; + + foreach ($fieldChk as $key => $data) { + if (!in_array($data->field_value, $chkData)) { + continue; + } + + $extraFieldValue .= $data->field_name; + } + + $exField .= RedshopLayoutHelper::render( + 'field_display.select', + array( + 'extraFieldLabel' => $extraFieldLabel, + 'extraFieldValue' => $extraFieldValue, + 'sendMail' => $sendmail + ), + '', + array( + 'component' => 'com_redshop' + ) + ); + break; + + case self::TYPE_SELECT_BOX_MULTIPLE: + $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); + $chkData = !empty($dataValue->data_txt) ? explode(",", $dataValue->data_txt) : array(); + $extraFieldValue = array(); + + foreach ($fieldChk as $key => $data) { + if (!in_array($data->field_value, $chkData)) { + continue; + } + + $extraFieldValue[] = $data->field_name; + } + + $exField .= RedshopLayoutHelper::render( + 'field_display.multiple', + array( + 'extraFieldLabel' => $extraFieldLabel, + 'extraFieldValue' => $extraFieldValue, + 'sendMail' => $sendmail + ), + '', + array( + 'component' => 'com_redshop' + ) + ); + break; + + case self::TYPE_SELECT_COUNTRY_BOX: + $extraFieldValue = ""; + + if ($dataValue && $dataValue->data_txt) { + $fieldChk = RedshopEntityCountry::getInstance($dataValue->data_txt); + $extraFieldValue = $fieldChk->get('country_name'); + } + + $exField .= RedshopLayoutHelper::render( + 'field_display.country', + array( + 'extraFieldLabel' => $extraFieldLabel, + 'extraFieldValue' => $extraFieldValue, + 'sendMail' => $sendmail + ), + '', + array( + 'component' => 'com_redshop' + ) + ); + break; + + // 12 :- Date Picker + case self::TYPE_DATE_PICKER: + $extraFieldValue = ($dataValue && $dataValue->data_txt) ? $dataValue->data_txt : ''; + $exField .= RedshopLayoutHelper::render( + 'field_display.datepicker', + array( + 'extraFieldLabel' => $extraFieldLabel, + 'extraFieldValue' => $extraFieldValue, + 'sendMail' => $sendmail + ), + '', + array( + 'component' => 'com_redshop' + ) + ); + break; + } + + if (trim($templateDesc) != '') { + if (strstr($templateDesc, "{" . $rowData[$i]->name . "}")) { + $templateDesc = str_replace("{" . $rowData[$i]->name . "}", $extraFieldValue, $templateDesc); + $templateDesc = str_replace("{" . $rowData[$i]->name . "_lbl}", $extraFieldLabel, $templateDesc); + } + + $templateDesc = str_replace("{" . $rowData[$i]->name . "}", "", $templateDesc); + $templateDesc = str_replace("{" . $rowData[$i]->name . "_lbl}", "", $templateDesc); + } + } + + if (trim($templateDesc) != '') { + return $templateDesc; + } + + if ($flag == 0 && !empty($extraFieldLabel)) { + $client = null; + $fieldLayout = 'fields.display'; + + if ($sendmail) { + $fieldLayout = 'fields.mail'; + $client = array('client' => 0); + } + + return RedshopLayoutHelper::render( + $fieldLayout, + array('extraFieldValue' => $exField), + null, + $client + ); + } + + return $exField; + } + + /** + * List all user fields + * + * @param string $fieldSection Field Section + * @param integer $sectionId Section ID + * @param string $fieldType Field type + * @param string $uniqueId Unique ID + * + * @return array + * + * @since 2.0.3 + */ + public static function listAllUserFields( + $fieldSection = "", + $sectionId = self::SECTION_PRODUCT_USERFIELD, + $fieldType = '', + $uniqueId = '' + ) { + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/redshop.attribute.min.js', false, true); + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select('*') + ->from($db->qn('#__redshop_fields')) + ->where($db->qn('section') . ' = ' . (int)$sectionId) + ->where($db->qn('name') . ' = ' . $db->quote($fieldSection)) + ->where($db->qn('published') . ' = 1'); + + $rowData = $db->setQuery($query)->loadObjectList(); + $exField = ''; + $exFieldTitle = ''; + $cart = \Redshop\Cart\Helper::getCart(); + $idx = 0; + + if (isset($cart['idx'])) { + $idx = (int)($cart['idx']); + } + + for ($i = 0, $in = count($rowData); $i < $in; $i++) { + $type = $rowData[$i]->type; + $asterisk = $rowData[$i]->required > 0 ? '* ' : ''; + + if ($fieldType != 'hidden') { + $exFieldTitle .= '
    ' . $asterisk . $rowData[$i]->title . '
    '; + } + + if ($fieldType == 'hidden') { + $exField .= ''; + } else { + $req = ' required = "' . $rowData[$i]->required . '"'; + + switch ($type) { + case self::TYPE_TEXT: + $exField .= RedshopLayoutHelper::render( + 'extrafields.userfield.text', + array( + 'rowData' => $rowData[$i], + 'required' => $req, + 'uniqueId' => $uniqueId + ) + ); + break; + + case self::TYPE_TEXT_AREA: + $exField .= RedshopLayoutHelper::render( + 'extrafields.userfield.textarea', + array( + 'rowData' => $rowData[$i], + 'required' => $req, + 'uniqueId' => $uniqueId + ) + ); + break; + + case self::TYPE_CHECK_BOX: + $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); + $chkData = explode(",", $cart[$idx][$rowData[$i]->name]); + $exField .= RedshopLayoutHelper::render( + 'extrafields.userfield.checkbox', + array( + 'rowData' => $rowData[$i], + 'required' => $req, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData, + 'uniqueId' => $uniqueId + ) + ); + break; + + case self::TYPE_RADIO_BUTTON: + $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); + $chkData = explode(",", $cart[$idx][$rowData[$i]->name]); + $exField .= RedshopLayoutHelper::render( + 'extrafields.userfield.radio', + array( + 'rowData' => $rowData[$i], + 'required' => $req, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData, + 'uniqueId' => $uniqueId + ) + ); + break; + + case self::TYPE_SELECT_BOX_SINGLE: + $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); + $chkData = explode(",", $cart[$idx][$rowData[$i]->name]); + $exField .= RedshopLayoutHelper::render( + 'extrafields.userfield.select', + array( + 'rowData' => $rowData[$i], + 'required' => $req, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData, + 'uniqueId' => $uniqueId + ) + ); + break; + + case self::TYPE_SELECT_BOX_MULTIPLE: + $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); + $chkData = explode(",", $cart[$idx][$rowData[$i]->name]); + $exField .= RedshopLayoutHelper::render( + 'extrafields.userfield.multiple', + array( + 'rowData' => $rowData[$i], + 'required' => $req, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData, + 'uniqueId' => $uniqueId + ) + ); + break; + + case self::TYPE_DOCUMENTS: + $exField .= RedshopLayoutHelper::render( + 'extrafields.userfield.document', + array( + 'rowData' => $rowData[$i], + 'required' => $req, + 'fieldCheck' => $req, + 'uniqueId' => $uniqueId + ) + ); + break; + + case self::TYPE_IMAGE_SELECT: + $fieldChk = RedshopEntityField::getInstance($rowData[$i]->id)->getFieldValues(); + $chkData = explode(",", $cart[$idx][$rowData[$i]->name]); + $exField .= RedshopLayoutHelper::render( + 'extrafields.userfield.image', + array( + 'rowData' => $rowData[$i], + 'required' => $req, + 'fieldCheck' => $fieldChk, + 'checkData' => $chkData, + 'uniqueId' => $uniqueId + ) + ); + break; + + case self::TYPE_DATE_PICKER: + $req = $rowData[$i]->required; + $exField .= RedshopLayoutHelper::render( + 'extrafields.userfield.date_picker', + array( + 'rowData' => $rowData[$i], + 'required' => $req, + 'fieldCheck' => $req, + 'uniqueId' => $uniqueId + ) + ); + break; + } + } + + if (trim($rowData[$i]->desc) != '' && $fieldType != 'hidden') { + $exField .= '
      ' + . JHtml::tooltip($rowData[$i]->desc, $rowData[$i]->name, 'tooltip.png', '', '', false) + . '
    '; + } + } + + return array($exFieldTitle, $exField); + } + + /** + * Render HTML radio list + * + * @param string $name Name of radio checkbox + * @param mixed $attribs Attribute values + * @param array $selected The name of the object variable for the option text + * @param string $yes Option Days + * @param string $no Option Weeks + * @param boolean $id ID of radio checkbox + * + * @return string + * + * @since 2.0.3 + */ + public static function booleanList($name, $attribs = null, $selected = null, $yes = 'yes', $no = 'no', $id = false) + { + $arr = array( + JHtml::_('select.option', "Days", JText::_($yes)), + JHtml::_('select.option', "Weeks", JText::_($no)) + ); + + return JHtml::_('select.radiolist', $arr, $name, $attribs, 'value', 'text', $selected, $id); + } + + /** + * Render HTML radio list with options + * + * @param string $name Name of radio checkbox + * @param mixed $attribs Attribute values + * @param array $selected The name of the object variable for the option text + * @param string $yes Option Days + * @param string $no Option Weeks + * @param boolean $id ID of radio checkbox + * @param string $yesValue ID of radio checkbox + * @param string $noValue ID of radio checkbox + * + * @return string + * + * @since 2.0.3 + */ + public static function rsBooleanList( + $name, + $attribs = null, + $selected = null, + $yes = 'yes', + $no = 'no', + $id = false, + $yesValue = 'Days', + $noValue = 'Weeks' + ) { + $arr = array( + JHtml::_('select.option', $yesValue, JText::_($yes)), + JHtml::_('select.option', $noValue, JText::_($no)) + ); + + return JHtml::_('redshopselect.radiolist', $arr, $name, $attribs, 'value', 'text', $selected, $id); + } + + /** + * Get fields value by ID + * + * @param integer $id ID of field + * + * @return array + * + * @since 2.0.3 + * + * @deprecated 2.0.6 Use RedshopEntityField::getFieldValues instead. + */ + public static function getFieldValue($id) + { + return RedshopEntityField::getInstance($id)->getFieldValues(); + } + + /** + * Copy product extra field + * + * @param integer $oldProductId Old Product ID + * @param integer $newPid New Product ID + * + * @return void + * + * @since 2.0.3 + */ + public static function copyProductExtraField($oldProductId, $newPid) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->select('*') + ->from($db->qn('#__redshop_fields_data')) + ->where($db->qn('itemid') . ' = ' . (int)$oldProductId) + ->where( + '(' . $db->qn('section') . ' = ' . $db->quote('1') + . ' or ' . + $db->qn('section') . ' = ' . $db->quote('12') + . ' or ' . + $db->qn('section') . ' = ' . $db->quote('17') . ')' + ); + + $db->setQuery($query); + $list = $db->loadObjectList(); + + // Skip process if there are no custom fields. + if (empty($list)) { + return; + } + + $query->clear() + ->insert($db->qn('#__redshop_fields_data')) + ->columns( + $db->qn(array('fieldid', 'data_txt', 'itemid', 'section', 'alt_text', 'image_link', 'user_email')) + ); + + foreach ($list as $row) { + $query->values( + implode( + ',', + array( + (int)$row->fieldid, + $db->quote($row->data_txt), + (int)$newPid, + (int)$row->section, + $db->quote($row->alt_text), + $db->quote($row->image_link), + $db->quote($row->user_email) + ) + ) + ); + } + + $db->setQuery($query)->execute(); + } + + /** + * Delete extra field data + * + * @param integer $dataId Data ID + * + * @return void + * + * @since 2.0.3 + */ + public static function deleteExtraFieldData($dataId) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->delete($db->qn('#__redshop_fields_data')) + ->where($db->qn('data_id') . ' = ' . (int)$dataId); + + $db->setQuery($query); + $db->execute(); + } + + /** + * Method for render HTML of extra fields + * + * @param integer $fieldSection Field section + * @param integer $sectionId ID of section + * @param string $fieldName Field name + * @param string $templateContent HTML template content + * @param integer $categoryPage Category page + * + * @return mixed + * @throws Exception + * + * @since 2.0.6 + * + * @deprecated 2.1.0 + */ + public static function extraFieldDisplay( + $fieldSection = 0, + $sectionId = 0, + $fieldName = "", + $templateContent = "", + $categoryPage = 0 + ) { + return ExtraFields::displayExtraFields( + $fieldSection, + $sectionId, + $fieldName, + $templateContent, + (boolean)$categoryPage + ); + } + + /** + * Method for get article joomla by id. + * + * @param string $ids Is required? + * + * @return mixed + */ + public static function getArticleJoomlaById($ids) + { + $db = \JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__content')) + ->where($db->qn('id') . ' IN (' . $ids . ')'); + + return $db->setQuery($query)->loadObjectList(); + } + + /** + * Method get display field data + * + * @param mixed $data Is required? + * @param string $layout Is required? + * @param integer $fieldId + * @param string $dataTxt + * + * @return string + */ + public static function getDisplayFieldData($data, $layout, $fieldId = 0, $dataTxt = '') + { + if (empty($data)) { + $fieldValues = \RedshopEntityField::getInstance($fieldId)->getFieldValues(); + $checkData = explode(',', $dataTxt); + $data = $layout == 'select' ? array() : ''; + + foreach ($fieldValues as $value) { + if (!in_array(urlencode($value->field_value), $checkData) && !in_array( + $value->field_value, + $checkData + )) { + continue; + } + + if ($layout == 'select') { + $data[] = urldecode($value->field_name); + } else { + $data = urldecode($value->field_name); + } + } + } + + return \RedshopLayoutHelper::render( + 'extrafields.display.' . $layout, + array( + 'data' => $data + ) + ); + } } diff --git a/libraries/redshop/helper/googleanalytics.php b/libraries/redshop/helper/googleanalytics.php index bf05f1278f5..8377ec09f37 100644 --- a/libraries/redshop/helper/googleanalytics.php +++ b/libraries/redshop/helper/googleanalytics.php @@ -12,81 +12,81 @@ /** * Google Analytics * - * @since 2.0 + * @since 2.0 * * @deprecated 2.0.6 Use plugin system - google analytics for redshop */ class RedshopHelperGoogleanalytics { - /** - * The analytics.js JavaScript snippet is a new way to measure how users interact with your website. - * It is similar to the previous tracking code, ga.js, - * but offers more flexibility for developers to customize their implementations. - * - * @return string PageView tracking code - * - * @deprecated 2.0.6 - */ - public function pageTrackerView() - { - return ''; - } + /** + * The analytics.js JavaScript snippet is a new way to measure how users interact with your website. + * It is similar to the previous tracking code, ga.js, + * but offers more flexibility for developers to customize their implementations. + * + * @return string PageView tracking code + * + * @deprecated 2.0.6 + */ + public function pageTrackerView() + { + return ''; + } - /** - * Once the plugin has been loaded, it creates a transparent shopping cart object. - * You can add transaction and item data to the shopping cart, and once fully configured, - * you send all the data at once. - * - * @param array $data Order Information in associative array - * - * @return string Add GA Ecommerce Transaction code - * - * @deprecated 2.0.6 - */ - public function addTrans($data) - { - return ''; - } + /** + * Once the plugin has been loaded, it creates a transparent shopping cart object. + * You can add transaction and item data to the shopping cart, and once fully configured, + * you send all the data at once. + * + * @param array $data Order Information in associative array + * + * @return string Add GA Ecommerce Transaction code + * + * @deprecated 2.0.6 + */ + public function addTrans($data) + { + return ''; + } - /** - * Add items to the shopping cart - * - * @param array $itemData Order Item information Associative Array - * - * @return string Transaction Item information. - * - * @deprecated 2.0.6 - */ - public function addItem($itemData) - { - return ''; - } + /** + * Add items to the shopping cart + * + * @param array $itemData Order Item information Associative Array + * + * @return string Transaction Item information. + * + * @deprecated 2.0.6 + */ + public function addItem($itemData) + { + return ''; + } - /** - * Finally, once we have configured all ecommerce data in the shopping cart, we will send it to GA. - * - * @return string Sending Information of ecommerce tracking. - * - * @deprecated 2.0.6 - */ - public function trackTrans() - { - return ''; - } + /** + * Finally, once we have configured all ecommerce data in the shopping cart, we will send it to GA. + * + * @return string Sending Information of ecommerce tracking. + * + * @deprecated 2.0.6 + */ + public function trackTrans() + { + return ''; + } - /** - * Code settings for Google Analytics - * - * @param array $analyticsData Analytics data in associative array which needs to be send on GA. - * - * @return void - * - * @see https://developers.google.com/analytics/devguides/collection/analyticsjs/ - * - * @deprecated 2.0.6 - */ - public function placeTrans($analyticsData = array()) - { - return; - } + /** + * Code settings for Google Analytics + * + * @param array $analyticsData Analytics data in associative array which needs to be send on GA. + * + * @return void + * + * @see https://developers.google.com/analytics/devguides/collection/analyticsjs/ + * + * @deprecated 2.0.6 + */ + public function placeTrans($analyticsData = array()) + { + return; + } } \ No newline at end of file diff --git a/libraries/redshop/helper/joomla.php b/libraries/redshop/helper/joomla.php index 9aca98bd5a2..983e8b7f38a 100644 --- a/libraries/redshop/helper/joomla.php +++ b/libraries/redshop/helper/joomla.php @@ -16,299 +16,273 @@ */ class RedshopHelperJoomla { - /** - * Get redSHOP manifest value - * - * @param string $name Name param - * @param mixed $default Default return value if value is not exists - * - * @return mixed - */ - public static function getManifestValue($name, $default = null) - { - static $oldManifest; - - if (!isset($oldManifest)) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('manifest_cache') - ->from($db->qn('#__extensions')) - ->where('type = ' . $db->q('component')) - ->where('element = ' . $db->q('com_redshop')); - $oldManifest = json_decode($db->setQuery($query)->loadResult(), true); - } - - if (isset($oldManifest[$name])) - { - return $oldManifest[$name]; - } - else - { - return $default; - } - } - - /** - * Method for create Joomla user. - * - * @param array $data User data. - * @param boolean $createUser Create user - * - * @return boolean|JUser|stdClass JUser if success. False otherwise. - * - * @since 2.0.7 - * - * @throws Exception - */ - public static function createJoomlaUser($data, $createUser = false) - { - $app = JFactory::getApplication(); - $input = $app->input; - - $createUser = isset($data['createaccount']) ? (boolean) $data['createaccount'] : $createUser; - - // Registration is without account creation REGISTER_METHOD = 1 - // Or Optional account creation - if (Redshop::getConfig()->get('REGISTER_METHOD') == 1 || (Redshop::getConfig()->get('REGISTER_METHOD') == 2 && !$createUser)) - { - $user = new stdClass; - $user->id = 0; - - return $user; - } - - $data['password'] = $input->post->get('password1', '', 'RAW'); - $data['password2'] = $input->post->get('password2', '', 'RAW'); - $data['email'] = $data['email1']; - $data['name'] = $name = $data['firstname']; - - $userParams = JComponentHelper::getParams('com_users'); - - // Prevent front-end user to change user group in the form and then being able to register on any Joomla! user group. - if ($app->isSite()) - { - $data['groups'] = array($userParams->get('new_usertype', 2)); - } - - // Do a password safety check - if (Redshop::getConfig()->get('REGISTER_METHOD') == 3) - { - // Silent registration - $betterToken = substr(uniqid(md5(rand()), true), 0, 10); - - $data['username'] = $data['email']; - $data['password'] = $betterToken; - $data['password2'] = $betterToken; - - $input->post->set('password1', $betterToken); - } - - if (trim($data['email']) == "") - { - JError::raiseWarning('', JText::_('COM_REDSHOP_EMPTY_EMAIL')); - - return false; - } - - if (trim($data['username']) == "") - { - JError::raiseWarning('', JText::_('COM_REDSHOP_EMPTY_USERNAME')); - - return false; - } - - if (RedshopHelperUser::validateUser($data['username']) > 0) - { - JError::raiseWarning('', JText::_('COM_REDSHOP_USERNAME_ALREADY_EXISTS')); - - return false; - } - - if (RedshopHelperUser::validateEmail($data['email']) > 0) - { - JError::raiseWarning('', JText::_('COM_REDSHOP_EMAIL_ALREADY_EXISTS')); - - return false; - } - - // Check: Password is empty - if (trim($data['password']) == "") - { - JError::raiseWarning('', JText::_('COM_REDSHOP_EMPTY_PASSWORD')); - - return false; - } - - // Check: Password not match - if ($data['password'] != $data['password2']) - { - JError::raiseWarning('', JText::_('COM_REDSHOP_PASSWORDS_DO_NOT_MATCH')); - - return false; - } - - JPluginHelper::importPlugin('redshop_user'); - RedshopHelperUtility::getDispatcher()->trigger('onBeforeCreateJoomlaUser', array(&$data)); - - // Get required system objects - $user = clone JFactory::getUser(); - - // If user registration is not allowed, show 403 not authorized. - if (!$user->bind($data)) - { - JError::raiseError(500, $user->getError()); - - return false; - } - - $date = JFactory::getDate(); - $user->set('id', 0); - $user->set('registerDate', $date->toSql()); + /** + * Get redSHOP manifest value + * + * @param string $name Name param + * @param mixed $default Default return value if value is not exists + * + * @return mixed + */ + public static function getManifestValue($name, $default = null) + { + static $oldManifest; + + if (!isset($oldManifest)) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('manifest_cache') + ->from($db->qn('#__extensions')) + ->where('type = ' . $db->q('component')) + ->where('element = ' . $db->q('com_redshop')); + $oldManifest = json_decode($db->setQuery($query)->loadResult(), true); + } + + if (isset($oldManifest[$name])) { + return $oldManifest[$name]; + } else { + return $default; + } + } + + /** + * Method for create Joomla user. + * + * @param array $data User data. + * @param boolean $createUser Create user + * + * @return boolean|JUser|stdClass JUser if success. False otherwise. + * + * @throws Exception + * @since 2.0.7 + * + */ + public static function createJoomlaUser($data, $createUser = false) + { + $app = JFactory::getApplication(); + $input = $app->input; + + $createUser = isset($data['createaccount']) ? (boolean)$data['createaccount'] : $createUser; + + // Registration is without account creation REGISTER_METHOD = 1 + // Or Optional account creation + if (Redshop::getConfig()->get('REGISTER_METHOD') == 1 || (Redshop::getConfig()->get( + 'REGISTER_METHOD' + ) == 2 && !$createUser)) { + $user = new stdClass; + $user->id = 0; + + return $user; + } + + $data['password'] = $input->post->get('password1', '', 'RAW'); + $data['password2'] = $input->post->get('password2', '', 'RAW'); + $data['email'] = $data['email1']; + $data['name'] = $name = $data['firstname']; + + $userParams = JComponentHelper::getParams('com_users'); + + // Prevent front-end user to change user group in the form and then being able to register on any Joomla! user group. + if ($app->isSite()) { + $data['groups'] = array($userParams->get('new_usertype', 2)); + } + + // Do a password safety check + if (Redshop::getConfig()->get('REGISTER_METHOD') == 3) { + // Silent registration + $betterToken = substr(uniqid(md5(rand()), true), 0, 10); + + $data['username'] = $data['email']; + $data['password'] = $betterToken; + $data['password2'] = $betterToken; + + $input->post->set('password1', $betterToken); + } + + if (trim($data['email']) == "") { + JError::raiseWarning('', JText::_('COM_REDSHOP_EMPTY_EMAIL')); + + return false; + } + + if (trim($data['username']) == "") { + JError::raiseWarning('', JText::_('COM_REDSHOP_EMPTY_USERNAME')); + + return false; + } + + if (RedshopHelperUser::validateUser($data['username']) > 0) { + JError::raiseWarning('', JText::_('COM_REDSHOP_USERNAME_ALREADY_EXISTS')); + + return false; + } + + if (RedshopHelperUser::validateEmail($data['email']) > 0) { + JError::raiseWarning('', JText::_('COM_REDSHOP_EMAIL_ALREADY_EXISTS')); + + return false; + } + + // Check: Password is empty + if (trim($data['password']) == "") { + JError::raiseWarning('', JText::_('COM_REDSHOP_EMPTY_PASSWORD')); + + return false; + } + + // Check: Password not match + if ($data['password'] != $data['password2']) { + JError::raiseWarning('', JText::_('COM_REDSHOP_PASSWORDS_DO_NOT_MATCH')); + + return false; + } + + JPluginHelper::importPlugin('redshop_user'); + RedshopHelperUtility::getDispatcher()->trigger('onBeforeCreateJoomlaUser', array(&$data)); + + // Get required system objects + $user = clone JFactory::getUser(); - // If user activation is turned on, we need to set the activation information - $activationMethod = $userParams->get('useractivation'); - - if ($activationMethod == '1') - { - $user->set('activation', JApplication::getHash(JUserHelper::genRandomPassword())); - $user->set('block', '0'); - } + // If user registration is not allowed, show 403 not authorized. + if (!$user->bind($data)) { + JError::raiseError(500, $user->getError()); - $user->set('name', $name); - $user->name = $name; + return false; + } - // If there was an error with registration, set the message and display form - if (!$user->save()) - { - JError::raiseWarning('', JText::_($user->getError())); + $date = JFactory::getDate(); + $user->set('id', 0); + $user->set('registerDate', $date->toSql()); - return false; - } - - $credentials = array(); - $credentials['username'] = $data['username']; - $credentials['password'] = $data['password2']; + // If user activation is turned on, we need to set the activation information + $activationMethod = $userParams->get('useractivation'); - // Perform the login action - if (!JFactory::getUser()->id) - { - $app->login($credentials); - } + if ($activationMethod == '1') { + $user->set('activation', JApplication::getHash(JUserHelper::genRandomPassword())); + $user->set('block', '0'); + } - RedshopHelperUtility::getDispatcher()->trigger('onAfterCreateJoomlaUser', array(&$user)); + $user->set('name', $name); + $user->name = $name; - return $user; - } + // If there was an error with registration, set the message and display form + if (!$user->save()) { + JError::raiseWarning('', JText::_($user->getError())); - /** - * Method for update Joomla user. - * - * @param array $data User data. - * - * @return boolean|JUser|stdClass JUser if success. False otherwise. - * - * @since 2.0.7 - * - * @throws Exception - */ - public static function updateJoomlaUser($data) - { - $app = JFactory::getApplication(); - - if ((!$app->isAdmin() && (Redshop::getConfig()->get('REGISTER_METHOD') == 1 || $data['user_id'] < 0)) - || $app->isAdmin() && $data['user_id'] < 0 && isset($data['users_info_id'])) - { - $reduser = new stdClass; - $reduser->id = $data['user_id']; + return false; + } - return $reduser; - } + $credentials = array(); + $credentials['username'] = $data['username']; + $credentials['password'] = $data['password2']; - $me = JFactory::getUser(); - - $data['name'] = $name = $data['firstname']; + // Perform the login action + if (!JFactory::getUser()->id) { + $app->login($credentials); + } - // Check: Username is not empty - if (trim($data['username']) == "") - { - JError::raiseWarning('', JText::_('COM_REDSHOP_EMPTY_USERNAME')); - - return false; - } + RedshopHelperUtility::getDispatcher()->trigger('onAfterCreateJoomlaUser', array(&$user)); - // Check: Validate username. - if (RedshopHelperUser::validateUser($data['username'], $data['user_id'])) - { - JError::raiseWarning('', JText::_('COM_REDSHOP_USERNAME_ALREADY_EXISTS')); - - return false; - } + return $user; + } - // Check: Email not empty. - if (trim($data['email']) == "") - { - JError::raiseWarning('', JText::_('EMPTY_EMAIL')); - - return false; - } - - // Check: Validate email - if (RedshopHelperUser::validateEmail($data['email'], $data['user_id'])) - { - JError::raiseWarning('', JText::_('COM_REDSHOP_EMAIL_ALREADY_EXISTS')); - - return false; - } - - // Get required system objects - $user = new JUser($data['user_id']); - - if (!$user->bind($data)) - { - JError::raiseError(500, $user->getError()); - - return false; - } - - // Initialise variables; - $pk = $user->get('id'); - - if ($user->get('block') && $pk == $me->id && !$me->block) - { - $app->enqueueMessage(JText::_('YOU_CANNOT_BLOCK_YOURSELF!'), 'error'); - - return false; - } - - // Make sure that we are not removing ourself from Super Admin group - if ($me->authorise('core.admin') && $me->get('id') == $pk) - { - // Check that at least one of our new groups is Super Admin - $stillSuperAdmin = false; - $myNewGroups = $user->groups; - - foreach ($myNewGroups as $group) - { - $stillSuperAdmin = ($stillSuperAdmin) ? ($stillSuperAdmin) : JAccess::checkGroup($group, 'core.admin'); - } - - if (!$stillSuperAdmin) - { - $app->enqueueMessage(JText::_('COM_USERS_USERS_ERROR_CANNOT_DEMOTE_SELF'), 'error'); - - return false; - } - } - - // If there was an error with registration, set the message and display form - if (!$user->save()) - { - JError::raiseWarning('', JText::_($user->getError())); - - return false; - } + /** + * Method for update Joomla user. + * + * @param array $data User data. + * + * @return boolean|JUser|stdClass JUser if success. False otherwise. + * + * @throws Exception + * @since 2.0.7 + * + */ + public static function updateJoomlaUser($data) + { + $app = JFactory::getApplication(); - return $user; - } + if ((!$app->isAdmin() && (Redshop::getConfig()->get('REGISTER_METHOD') == 1 || $data['user_id'] < 0)) + || $app->isAdmin() && $data['user_id'] < 0 && isset($data['users_info_id'])) { + $reduser = new stdClass; + $reduser->id = $data['user_id']; + + return $reduser; + } + + $me = JFactory::getUser(); + + $data['name'] = $name = $data['firstname']; + + // Check: Username is not empty + if (trim($data['username']) == "") { + JError::raiseWarning('', JText::_('COM_REDSHOP_EMPTY_USERNAME')); + + return false; + } + + // Check: Validate username. + if (RedshopHelperUser::validateUser($data['username'], $data['user_id'])) { + JError::raiseWarning('', JText::_('COM_REDSHOP_USERNAME_ALREADY_EXISTS')); + + return false; + } + + // Check: Email not empty. + if (trim($data['email']) == "") { + JError::raiseWarning('', JText::_('EMPTY_EMAIL')); + + return false; + } + + // Check: Validate email + if (RedshopHelperUser::validateEmail($data['email'], $data['user_id'])) { + JError::raiseWarning('', JText::_('COM_REDSHOP_EMAIL_ALREADY_EXISTS')); + + return false; + } + + // Get required system objects + $user = new JUser($data['user_id']); + + if (!$user->bind($data)) { + JError::raiseError(500, $user->getError()); + + return false; + } + + // Initialise variables; + $pk = $user->get('id'); + + if ($user->get('block') && $pk == $me->id && !$me->block) { + $app->enqueueMessage(JText::_('YOU_CANNOT_BLOCK_YOURSELF!'), 'error'); + + return false; + } + + // Make sure that we are not removing ourself from Super Admin group + if ($me->authorise('core.admin') && $me->get('id') == $pk) { + // Check that at least one of our new groups is Super Admin + $stillSuperAdmin = false; + $myNewGroups = $user->groups; + + foreach ($myNewGroups as $group) { + $stillSuperAdmin = ($stillSuperAdmin) ? ($stillSuperAdmin) : JAccess::checkGroup($group, 'core.admin'); + } + + if (!$stillSuperAdmin) { + $app->enqueueMessage(JText::_('COM_USERS_USERS_ERROR_CANNOT_DEMOTE_SELF'), 'error'); + + return false; + } + } + + // If there was an error with registration, set the message and display form + if (!$user->save()) { + JError::raiseWarning('', JText::_($user->getError())); + + return false; + } + + return $user; + } } diff --git a/libraries/redshop/helper/js.php b/libraries/redshop/helper/js.php index 0cafd99763e..99f237b8359 100644 --- a/libraries/redshop/helper/js.php +++ b/libraries/redshop/helper/js.php @@ -16,181 +16,176 @@ */ class RedshopHelperJs { - /** - * Init redshop js - * - * @return void - * - * @throws Exception - */ - public static function init() - { - $doc = JFactory::getDocument(); - $input = JFactory::getApplication()->input; - $session = JFactory::getSession(); - $langCode = JFactory::getLanguage()->getTag(); - $languages = JLanguageHelper::getLanguages('lang_code'); - $langSef = $languages[$langCode]->sef; - - $view = $input->getCmd('view'); - $layout = $input->getCmd('layout'); - $config = Redshop::getConfig(); - $post = $input->post->getArray(); - - $currencySymbol = $config->get('REDCURRENCY_SYMBOL', ''); - $currencyConvert = 1; - - if (isset($post['product_currency'])) - { - $session->set('product_currency', $post['product_currency']); - } - - if ($session->get('product_currency')) - { - $currencySymbol = RedshopEntityCurrency::getInstance((int) $session->get('product_currency'))->get('code'); - $currencyConvert = round(RedshopHelperCurrency::convert(1), 2); - } - - $token = JSession::getFormToken(); - - // Prepare dynamic variables to add them in javascript stack - $dynamicVars = array( - 'SITE_URL' => JUri::root(), - 'AJAX_TOKEN' => $token, - 'AJAX_BASE_URL' => JUri::root() . "index.php?tmpl=component&option=com_redshop&" . $token . "=1&lang=" . $langSef, - 'AJAX_CART_BOX' => $config->get('AJAX_CART_BOX'), - 'REDSHOP_VIEW' => $view, - 'REDSHOP_LAYOUT' => $layout, - 'CURRENCY_SYMBOL_CONVERT' => $currencySymbol, - 'CURRENCY_CONVERT' => $currencyConvert, - 'PRICE_SEPERATOR' => $config->get('PRICE_SEPERATOR'), - 'CURRENCY_SYMBOL_POSITION' => $config->get('CURRENCY_SYMBOL_POSITION'), - 'PRICE_DECIMAL' => $config->get('PRICE_DECIMAL'), - 'THOUSAND_SEPERATOR' => $config->get('THOUSAND_SEPERATOR', ''), - 'USE_STOCKROOM' => $config->get('USE_STOCKROOM'), - 'USE_AS_CATALOG' => $config->get('USE_AS_CATALOG'), - 'AJAX_CART_DISPLAY_TIME' => $config->get('AJAX_CART_DISPLAY_TIME'), - 'SHOW_PRICE' => $config->get('SHOW_PRICE'), - 'BASE_TAX' => RedshopHelperProduct::getProductTax(0, 1), - 'DEFAULT_QUOTATION_MODE' => $config->get('DEFAULT_QUOTATION_MODE'), - 'PRICE_REPLACE' => $config->get('PRICE_REPLACE'), - 'ALLOW_PRE_ORDER' => $config->get('ALLOW_PRE_ORDER'), - 'ATTRIBUTE_SCROLLER_THUMB_WIDTH' => $config->get('ATTRIBUTE_SCROLLER_THUMB_WIDTH'), - 'ATTRIBUTE_SCROLLER_THUMB_HEIGHT' => $config->get('ATTRIBUTE_SCROLLER_THUMB_HEIGHT'), - 'PRODUCT_DETAIL_IS_LIGHTBOX' => $config->get('PRODUCT_DETAIL_IS_LIGHTBOX'), - 'REQUIRED_VAT_NUMBER' => $config->get('REQUIRED_VAT_NUMBER'), - 'NOOF_SUBATTRIB_THUMB_FOR_SCROLLER' => $config->get('NOOF_SUBATTRIB_THUMB_FOR_SCROLLER'), - 'SHOW_QUOTATION_PRICE' => $config->get('SHOW_QUOTATION_PRICE'), - 'AJAX_DETAIL_BOX_WIDTH' => $config->get('AJAX_DETAIL_BOX_WIDTH'), - 'AJAX_DETAIL_BOX_HEIGHT' => $config->get('AJAX_DETAIL_BOX_HEIGHT'), - 'AJAX_BOX_WIDTH' => $config->get('AJAX_BOX_WIDTH'), - 'AJAX_BOX_HEIGHT' => $config->get('AJAX_BOX_HEIGHT'), - 'PRICE_REPLACE_URL' => $config->get('PRICE_REPLACE_URL'), - 'ZERO_PRICE_REPLACE_URL' => $config->get('ZERO_PRICE_REPLACE_URL'), - 'ZERO_PRICE_REPLACE' => $config->get('ZERO_PRICE_REPLACE'), - 'REQUIRED_POSTAL_CODE' => $config->get('REQUIRED_POSTAL_CODE'), - 'REQUIRED_ADDRESS' => $config->get('REQUIRED_ADDRESS'), - 'REQUIRED_EAN_NUMBER' => $config->get('REQUIRED_EAN_NUMBER'), - 'REQUIRED_COUNTRY_CODE' => $config->get('REQUIRED_COUNTRY_CODE'), - 'REQUIRED_PHONE' => $config->get('REQUIRED_PHONE'), - 'MINIMUM_ORDER_TOTAL' => $config->get('MINIMUM_ORDER_TOTAL') - ); - - // Current Shopper Group - Show price with VAT config - $shopperGroupData = RedshopEntityShopper_Group::getInstance(RedshopHelperUser::getShopperGroup(JFactory::getUser()->id))->getItem(); - - $dynamicVars['SHOW_PRICE_WITHOUT_VAT'] = $shopperGroupData ? (int) $shopperGroupData->show_price_without_vat : 0; - - $backwardJS = array(); - - // Now looping to add dynamic vars into javascript stack - foreach ($dynamicVars as $key => $value) - { - if (Redshop::getConfig()->get('BACKWARD_COMPATIBLE_JS') == 1) - { - $backwardJS[] = 'window.' . $key . ' = "' . $value . '";'; - } - - RedshopHelperConfig::script($key, $value); - } - - if (Redshop::getConfig()->get('BACKWARD_COMPATIBLE_JS') == 1) - { - JFactory::getDocument()->addScriptDeclaration(implode("\n", $backwardJS)); - } - - // Prepare language string to add in javascript store - $languages = array( - 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_FIRSTNAME', - 'COM_REDSHOP_USERNAME_ALREADY_EXISTS', - 'COM_REDSHOP_PRODUCT_OUTOFSTOCK_MESSAGE', - 'COM_REDSHOP_PREORDER_PRODUCT_OUTOFSTOCK_MESSAGE', - 'COM_REDSHOP_PASSWORD_MIN_CHARACTER_LIMIT', - 'COM_REDSHOP_PLEASE_ENTER_PASSWORD', - 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_VALID_PHONE', - 'COM_REDSHOP_IS_REQUIRED', - 'COM_REDSHOP_ENTER_NUMBER', - 'COM_REDSHOP_PLEASE_ENTER_COMPANY_NAME', - 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_LASTNAME', - 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_ADDRESS', - 'COM_REDSHOP_PLEASE_SELECT_COUNTRY', - 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_ZIP', - 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_CITY', - 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_PHONE', - 'COM_REDSHOP_YOU_MUST_PROVIDE_LOGIN_NAME', - 'COM_REDSHOP_PROVIDE_EMAIL_ADDRESS', - 'COM_REDSHOP_EMAIL_NOT_MATCH', - 'COM_REDSHOP_PASSWORD_NOT_MATCH', - 'COM_REDSHOP_PLEASE_SELECT_TEMS_CONDITIONS', - 'COM_REDSHOP_NOT_AVAILABLE', - 'COM_REDSHOP_PLEASE_INSERT_HEIGHT', - 'COM_REDSHOP_PLEASE_INSERT_WIDTH', - 'COM_REDSHOP_PLEASE_INSERT_DEPTH', - 'COM_REDSHOP_PLEASE_INSERT_RADIUS', - 'COM_REDSHOP_PLEASE_INSERT_UNIT', - 'COM_REDSHOP_THIS_FIELD_IS_REQUIRED', - 'COM_REDSHOP_SELECT_SUBSCRIPTION_PLAN', - 'COM_REDSHOP_USERNAME_MIN_CHARACTER_LIMIT', - 'COM_REDSHOP_EAN_MIN_CHARACTER_LIMIT', - 'COM_REDSHOP_AVAILABLE_STOCK', - 'COM_REDSHOP_PLEASE_ENTER_VALID_EMAIL_ADDRESS', - 'COM_REDSHOP_MINIMUM_ORDER_TOTAL_HAS_TO_BE_MORE_THAN', - 'COM_REDSHOP_PLEASE_SELECT_TEMS_CONDITIONS' - ); - - $backwardJS = array(); - - // Now looping to add language strings into javascript store - foreach ($languages as $value) - { - JText::script($value); - - if (Redshop::getConfig()->get('BACKWARD_COMPATIBLE_JS') == 1) - { - $backwardJS[] = 'window.' . $value . ' = "' . JText::_($value) . '";'; - } - } - - if (Redshop::getConfig()->get('BACKWARD_COMPATIBLE_JS') == 1) - { - JFactory::getDocument()->addScriptDeclaration(implode("\n", $backwardJS)); - } - - if ($view == 'product') - { - if (JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . 'slimbox/' . $config->get('PRODUCT_DETAIL_LIGHTBOX_CLOSE_BUTTON_IMAGE'))) - { - $slimboxCloseButton = "#sbox-btn-close {background: transparent url( \"" - . REDSHOP_FRONT_IMAGES_ABSPATH . "slimbox/" . $config->get('PRODUCT_DETAIL_LIGHTBOX_CLOSE_BUTTON_IMAGE') - . "\" ) no-repeat center;}"; - } - else - { - $slimboxCloseButton = "#sbox-btn-close {background: transparent url( \"" - . REDSHOP_FRONT_IMAGES_ABSPATH . "slimbox/closelabel.gif\" ) no-repeat center;}"; - } - - $doc->addStyleDeclaration($slimboxCloseButton); - } - } + /** + * Init redshop js + * + * @return void + * + * @throws Exception + */ + public static function init() + { + $doc = JFactory::getDocument(); + $input = JFactory::getApplication()->input; + $session = JFactory::getSession(); + $langCode = JFactory::getLanguage()->getTag(); + $languages = JLanguageHelper::getLanguages('lang_code'); + $langSef = $languages[$langCode]->sef; + + $view = $input->getCmd('view'); + $layout = $input->getCmd('layout'); + $config = Redshop::getConfig(); + $post = $input->post->getArray(); + + $currencySymbol = $config->get('REDCURRENCY_SYMBOL', ''); + $currencyConvert = 1; + + if (isset($post['product_currency'])) { + $session->set('product_currency', $post['product_currency']); + } + + if ($session->get('product_currency')) { + $currencySymbol = RedshopEntityCurrency::getInstance((int)$session->get('product_currency'))->get('code'); + $currencyConvert = round(RedshopHelperCurrency::convert(1), 2); + } + + $token = JSession::getFormToken(); + + // Prepare dynamic variables to add them in javascript stack + $dynamicVars = array( + 'SITE_URL' => JUri::root(), + 'AJAX_TOKEN' => $token, + 'AJAX_BASE_URL' => JUri::root( + ) . "index.php?tmpl=component&option=com_redshop&" . $token . "=1&lang=" . $langSef, + 'AJAX_CART_BOX' => $config->get('AJAX_CART_BOX'), + 'REDSHOP_VIEW' => $view, + 'REDSHOP_LAYOUT' => $layout, + 'CURRENCY_SYMBOL_CONVERT' => $currencySymbol, + 'CURRENCY_CONVERT' => $currencyConvert, + 'PRICE_SEPERATOR' => $config->get('PRICE_SEPERATOR'), + 'CURRENCY_SYMBOL_POSITION' => $config->get('CURRENCY_SYMBOL_POSITION'), + 'PRICE_DECIMAL' => $config->get('PRICE_DECIMAL'), + 'THOUSAND_SEPERATOR' => $config->get('THOUSAND_SEPERATOR', ''), + 'USE_STOCKROOM' => $config->get('USE_STOCKROOM'), + 'USE_AS_CATALOG' => $config->get('USE_AS_CATALOG'), + 'AJAX_CART_DISPLAY_TIME' => $config->get('AJAX_CART_DISPLAY_TIME'), + 'SHOW_PRICE' => $config->get('SHOW_PRICE'), + 'BASE_TAX' => RedshopHelperProduct::getProductTax(0, 1), + 'DEFAULT_QUOTATION_MODE' => $config->get('DEFAULT_QUOTATION_MODE'), + 'PRICE_REPLACE' => $config->get('PRICE_REPLACE'), + 'ALLOW_PRE_ORDER' => $config->get('ALLOW_PRE_ORDER'), + 'ATTRIBUTE_SCROLLER_THUMB_WIDTH' => $config->get('ATTRIBUTE_SCROLLER_THUMB_WIDTH'), + 'ATTRIBUTE_SCROLLER_THUMB_HEIGHT' => $config->get('ATTRIBUTE_SCROLLER_THUMB_HEIGHT'), + 'PRODUCT_DETAIL_IS_LIGHTBOX' => $config->get('PRODUCT_DETAIL_IS_LIGHTBOX'), + 'REQUIRED_VAT_NUMBER' => $config->get('REQUIRED_VAT_NUMBER'), + 'NOOF_SUBATTRIB_THUMB_FOR_SCROLLER' => $config->get('NOOF_SUBATTRIB_THUMB_FOR_SCROLLER'), + 'SHOW_QUOTATION_PRICE' => $config->get('SHOW_QUOTATION_PRICE'), + 'AJAX_DETAIL_BOX_WIDTH' => $config->get('AJAX_DETAIL_BOX_WIDTH'), + 'AJAX_DETAIL_BOX_HEIGHT' => $config->get('AJAX_DETAIL_BOX_HEIGHT'), + 'AJAX_BOX_WIDTH' => $config->get('AJAX_BOX_WIDTH'), + 'AJAX_BOX_HEIGHT' => $config->get('AJAX_BOX_HEIGHT'), + 'PRICE_REPLACE_URL' => $config->get('PRICE_REPLACE_URL'), + 'ZERO_PRICE_REPLACE_URL' => $config->get('ZERO_PRICE_REPLACE_URL'), + 'ZERO_PRICE_REPLACE' => $config->get('ZERO_PRICE_REPLACE'), + 'REQUIRED_POSTAL_CODE' => $config->get('REQUIRED_POSTAL_CODE'), + 'REQUIRED_ADDRESS' => $config->get('REQUIRED_ADDRESS'), + 'REQUIRED_EAN_NUMBER' => $config->get('REQUIRED_EAN_NUMBER'), + 'REQUIRED_COUNTRY_CODE' => $config->get('REQUIRED_COUNTRY_CODE'), + 'REQUIRED_PHONE' => $config->get('REQUIRED_PHONE'), + 'MINIMUM_ORDER_TOTAL' => $config->get('MINIMUM_ORDER_TOTAL') + ); + + // Current Shopper Group - Show price with VAT config + $shopperGroupData = RedshopEntityShopper_Group::getInstance( + RedshopHelperUser::getShopperGroup(JFactory::getUser()->id) + )->getItem(); + + $dynamicVars['SHOW_PRICE_WITHOUT_VAT'] = $shopperGroupData ? (int)$shopperGroupData->show_price_without_vat : 0; + + $backwardJS = array(); + + // Now looping to add dynamic vars into javascript stack + foreach ($dynamicVars as $key => $value) { + if (Redshop::getConfig()->get('BACKWARD_COMPATIBLE_JS') == 1) { + $backwardJS[] = 'window.' . $key . ' = "' . $value . '";'; + } + + RedshopHelperConfig::script($key, $value); + } + + if (Redshop::getConfig()->get('BACKWARD_COMPATIBLE_JS') == 1) { + JFactory::getDocument()->addScriptDeclaration(implode("\n", $backwardJS)); + } + + // Prepare language string to add in javascript store + $languages = array( + 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_FIRSTNAME', + 'COM_REDSHOP_USERNAME_ALREADY_EXISTS', + 'COM_REDSHOP_PRODUCT_OUTOFSTOCK_MESSAGE', + 'COM_REDSHOP_PREORDER_PRODUCT_OUTOFSTOCK_MESSAGE', + 'COM_REDSHOP_PASSWORD_MIN_CHARACTER_LIMIT', + 'COM_REDSHOP_PLEASE_ENTER_PASSWORD', + 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_VALID_PHONE', + 'COM_REDSHOP_IS_REQUIRED', + 'COM_REDSHOP_ENTER_NUMBER', + 'COM_REDSHOP_PLEASE_ENTER_COMPANY_NAME', + 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_LASTNAME', + 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_ADDRESS', + 'COM_REDSHOP_PLEASE_SELECT_COUNTRY', + 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_ZIP', + 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_CITY', + 'COM_REDSHOP_YOUR_MUST_PROVIDE_A_PHONE', + 'COM_REDSHOP_YOU_MUST_PROVIDE_LOGIN_NAME', + 'COM_REDSHOP_PROVIDE_EMAIL_ADDRESS', + 'COM_REDSHOP_EMAIL_NOT_MATCH', + 'COM_REDSHOP_PASSWORD_NOT_MATCH', + 'COM_REDSHOP_PLEASE_SELECT_TEMS_CONDITIONS', + 'COM_REDSHOP_NOT_AVAILABLE', + 'COM_REDSHOP_PLEASE_INSERT_HEIGHT', + 'COM_REDSHOP_PLEASE_INSERT_WIDTH', + 'COM_REDSHOP_PLEASE_INSERT_DEPTH', + 'COM_REDSHOP_PLEASE_INSERT_RADIUS', + 'COM_REDSHOP_PLEASE_INSERT_UNIT', + 'COM_REDSHOP_THIS_FIELD_IS_REQUIRED', + 'COM_REDSHOP_SELECT_SUBSCRIPTION_PLAN', + 'COM_REDSHOP_USERNAME_MIN_CHARACTER_LIMIT', + 'COM_REDSHOP_EAN_MIN_CHARACTER_LIMIT', + 'COM_REDSHOP_AVAILABLE_STOCK', + 'COM_REDSHOP_PLEASE_ENTER_VALID_EMAIL_ADDRESS', + 'COM_REDSHOP_MINIMUM_ORDER_TOTAL_HAS_TO_BE_MORE_THAN', + 'COM_REDSHOP_PLEASE_SELECT_TEMS_CONDITIONS' + ); + + $backwardJS = array(); + + // Now looping to add language strings into javascript store + foreach ($languages as $value) { + JText::script($value); + + if (Redshop::getConfig()->get('BACKWARD_COMPATIBLE_JS') == 1) { + $backwardJS[] = 'window.' . $value . ' = "' . JText::_($value) . '";'; + } + } + + if (Redshop::getConfig()->get('BACKWARD_COMPATIBLE_JS') == 1) { + JFactory::getDocument()->addScriptDeclaration(implode("\n", $backwardJS)); + } + + if ($view == 'product') { + if (JFile::exists( + REDSHOP_FRONT_IMAGES_RELPATH . 'slimbox/' . $config->get('PRODUCT_DETAIL_LIGHTBOX_CLOSE_BUTTON_IMAGE') + )) { + $slimboxCloseButton = "#sbox-btn-close {background: transparent url( \"" + . REDSHOP_FRONT_IMAGES_ABSPATH . "slimbox/" . $config->get( + 'PRODUCT_DETAIL_LIGHTBOX_CLOSE_BUTTON_IMAGE' + ) + . "\" ) no-repeat center;}"; + } else { + $slimboxCloseButton = "#sbox-btn-close {background: transparent url( \"" + . REDSHOP_FRONT_IMAGES_ABSPATH . "slimbox/closelabel.gif\" ) no-repeat center;}"; + } + + $doc->addStyleDeclaration($slimboxCloseButton); + } + } } diff --git a/libraries/redshop/helper/mail.php b/libraries/redshop/helper/mail.php index 2ab10ac9d06..aad08c0a9b7 100644 --- a/libraries/redshop/helper/mail.php +++ b/libraries/redshop/helper/mail.php @@ -18,302 +18,320 @@ */ class RedshopHelperMail { - /** - * Method to get mail section - * - * @param integer $templateId Template id - * @param string $section Template section - * @param string $extraCond Extra condition for query - * - * @return array - * - * @deprecated 2.1.0 - * @see Redshop\Mail\Helper::getTemplate - */ - public static function getMailTemplate($templateId = 0, $section = '', $extraCond = '') - { - return Redshop\Mail\Helper::getTemplate($templateId, $section, $extraCond); - } + /** + * Method to get mail section + * + * @param integer $templateId Template id + * @param string $section Template section + * @param string $extraCond Extra condition for query + * + * @return array + * + * @deprecated 2.1.0 + * @see Redshop\Mail\Helper::getTemplate + */ + public static function getMailTemplate($templateId = 0, $section = '', $extraCond = '') + { + return Redshop\Mail\Helper::getTemplate($templateId, $section, $extraCond); + } - /** - * sendOrderMail function. - * - * @param int $orderId Order ID. - * @param boolean $onlyAdmin Send mail only to admin - * - * @return boolean - * @throws \Exception - * - * @deprecated 2.1.0 - * @see Redshop\Mail\Order::sendMail - */ - public static function sendOrderMail($orderId, $onlyAdmin = false) - { - return Redshop\Mail\Order::sendMail($orderId, $onlyAdmin); - } + /** + * sendOrderMail function. + * + * @param int $orderId Order ID. + * @param boolean $onlyAdmin Send mail only to admin + * + * @return boolean + * @throws \Exception + * + * @deprecated 2.1.0 + * @see Redshop\Mail\Order::sendMail + */ + public static function sendOrderMail($orderId, $onlyAdmin = false) + { + return Redshop\Mail\Order::sendMail($orderId, $onlyAdmin); + } - /** - * send Order Special Discount Mail function. - * - * @param int $orderId Order ID. - * - * @return boolean - * @throws Exception - * - * @deprecated 2.1.0 - * @see Redshop\Mail\Order::sendOrderSpecialDiscountMail - */ - public static function sendOrderSpecialDiscountMail($orderId) - { - return Redshop\Mail\Order::sendSpecialDiscountMail($orderId); - } + /** + * send Order Special Discount Mail function. + * + * @param int $orderId Order ID. + * + * @return boolean + * @throws Exception + * + * @deprecated 2.1.0 + * @see Redshop\Mail\Order::sendOrderSpecialDiscountMail + */ + public static function sendOrderSpecialDiscountMail($orderId) + { + return Redshop\Mail\Order::sendSpecialDiscountMail($orderId); + } - /** - * Create multiple print invoice PDF - * - * @param array $orderIds Order ID List. - * - * @return string - * - * @deprecated 2.0.3 Use - */ - public static function createMultiprintInvoicePdf($orderIds) - { - return RedshopHelperPdf::createMultiInvoice($orderIds); - } + /** + * Create multiple print invoice PDF + * + * @param array $orderIds Order ID List. + * + * @return string + * + * @deprecated 2.0.3 Use + */ + public static function createMultiprintInvoicePdf($orderIds) + { + return RedshopHelperPdf::createMultiInvoice($orderIds); + } - /** - * Replace invoice mail template tags and prepare mail body and pdf html - * - * @param integer $orderId Order Information ID - * @param string $html HTML template of mail body or pdf - * @param string $subject Email Subject template, can be null for PDF - * - * @return object Object having mail body and subject. subject can be null for PDF type. - * @throws Exception - * - * @deprecated 2.1.0 - * @see Redshop\Mail\Invoice::replaceTemplate - */ - public static function replaceInvoiceMailTemplate($orderId, $html, $subject = null) - { - return Redshop\Mail\Invoice::replaceTemplate($orderId, $html, $subject); - } + /** + * Replace invoice mail template tags and prepare mail body and pdf html + * + * @param integer $orderId Order Information ID + * @param string $html HTML template of mail body or pdf + * @param string $subject Email Subject template, can be null for PDF + * + * @return object Object having mail body and subject. subject can be null for PDF type. + * @throws Exception + * + * @deprecated 2.1.0 + * @see Redshop\Mail\Invoice::replaceTemplate + */ + public static function replaceInvoiceMailTemplate($orderId, $html, $subject = null) + { + return Redshop\Mail\Invoice::replaceTemplate($orderId, $html, $subject); + } - /** - * Send Order Invoice Mail - * Email Body and Subject is from "Invoice Mail" template section. - * Contains PDF attachment. PDF html is from "Invoice Mail PDF" section. - * - * @param int $orderId Order Information Id - * @param string $email Email - * - * @return boolean True on sending email successfully. - * @throws Exception - * - * @deprecated 2.1.0 - * @see Redshop\Mail\Invoice::sendMail - */ - public static function sendInvoiceMail($orderId, $email = null) - { - return Redshop\Mail\Invoice::sendMail($orderId, $email); - } + /** + * Send Order Invoice Mail + * Email Body and Subject is from "Invoice Mail" template section. + * Contains PDF attachment. PDF html is from "Invoice Mail PDF" section. + * + * @param int $orderId Order Information Id + * @param string $email Email + * + * @return boolean True on sending email successfully. + * @throws Exception + * + * @deprecated 2.1.0 + * @see Redshop\Mail\Invoice::sendMail + */ + public static function sendInvoiceMail($orderId, $email = null) + { + return Redshop\Mail\Invoice::sendMail($orderId, $email); + } - /** - * Send registration mail - * - * @param array $data Registration data - * - * @return boolean - * - * @throws Exception - * - * @deprecated 2.1.0 - */ - public static function sendRegistrationMail(&$data) - { - return Redshop\Mail\User::sendRegistrationMail($data); - } + /** + * Send registration mail + * + * @param array $data Registration data + * + * @return boolean + * + * @throws Exception + * + * @deprecated 2.1.0 + */ + public static function sendRegistrationMail(&$data) + { + return Redshop\Mail\User::sendRegistrationMail($data); + } - /** - * Send tax exempt mail - * - * @param string $mailSection Mail section - * @param array $userInfo User info data - * @param string $email User email - * - * @return boolean - * - * @throws Exception - * - * @deprecated 2.1.0 - */ - public static function sendTaxExemptMail($mailSection, $userInfo = array(), $email = "") - { - return Redshop\Mail\User::sendTaxExempt($mailSection, $userInfo, $email); - } + /** + * Send tax exempt mail + * + * @param string $mailSection Mail section + * @param array $userInfo User info data + * @param string $email User email + * + * @return boolean + * + * @throws Exception + * + * @deprecated 2.1.0 + */ + public static function sendTaxExemptMail($mailSection, $userInfo = array(), $email = "") + { + return Redshop\Mail\User::sendTaxExempt($mailSection, $userInfo, $email); + } - /** - * Send subscriptions re-new mail - * - * @param array $data Mail data - * - * @return boolean - * - * @throws Exception - * - * @deprecated 2.1.0 - */ - public static function sendSubscriptionRenewalMail($data = array()) - { - return Redshop\Mail\User::sendSubscriptionRenewal($data); - } + /** + * Send subscriptions re-new mail + * + * @param array $data Mail data + * + * @return boolean + * + * @throws Exception + * + * @deprecated 2.1.0 + */ + public static function sendSubscriptionRenewalMail($data = array()) + { + return Redshop\Mail\User::sendSubscriptionRenewal($data); + } - /** - * Use absolute paths instead of relative ones when linking images - * - * @param string $message Text message - * - * @return string - * @deprecated 2.1.0 - * @see Redshop\Mail\Helper::imgInMail - */ - public static function imgInMail($message) - { - Redshop\Mail\Helper::imgInMail($message); + /** + * Use absolute paths instead of relative ones when linking images + * + * @param string $message Text message + * + * @return string + * @deprecated 2.1.0 + * @see Redshop\Mail\Helper::imgInMail + */ + public static function imgInMail($message) + { + Redshop\Mail\Helper::imgInMail($message); - return $message; - } + return $message; + } - /** - * Use absolute paths instead of relative ones when linking images - * - * @param int $quotationId Quotation id - * @param int $status Status - * - * @return boolean - * @throws Exception - * - * @deprecated 2.1.0 - * @see Redshop\Mail\Quotation::sendQuotationMail - */ - public static function sendQuotationMail($quotationId, $status = 0) - { - return Redshop\Mail\Quotation::sendMail($quotationId, $status); - } + /** + * Use absolute paths instead of relative ones when linking images + * + * @param int $quotationId Quotation id + * @param int $status Status + * + * @return boolean + * @throws Exception + * + * @deprecated 2.1.0 + * @see Redshop\Mail\Quotation::sendQuotationMail + */ + public static function sendQuotationMail($quotationId, $status = 0) + { + return Redshop\Mail\Quotation::sendMail($quotationId, $status); + } - /** - * Send newsletter confirmation mail - * - * @param int $subscriptionId Subscription id - * - * @return boolean - * - * @deprecated 2.1.0 - */ - public static function sendNewsletterConfirmationMail($subscriptionId) - { - return Redshop\Mail\Newsletter::sendConfirmationMail($subscriptionId); - } + /** + * Send newsletter confirmation mail + * + * @param int $subscriptionId Subscription id + * + * @return boolean + * + * @deprecated 2.1.0 + */ + public static function sendNewsletterConfirmationMail($subscriptionId) + { + return Redshop\Mail\Newsletter::sendConfirmationMail($subscriptionId); + } - /** - * Send newsletter cancellation mail - * - * @param string $email Email - * - * @return boolean - * - * @deprecated 2.1.0 - */ - public static function sendNewsletterCancellationMail($email = "") - { - return Redshop\Mail\Newsletter::sendCancellationMail($email); - } + /** + * Send newsletter cancellation mail + * + * @param string $email Email + * + * @return boolean + * + * @deprecated 2.1.0 + */ + public static function sendNewsletterCancellationMail($email = "") + { + return Redshop\Mail\Newsletter::sendCancellationMail($email); + } - /** - * Send ask question mail - * - * @param int $answerId Answer id - * - * @return boolean - * - * @deprecated 2.1.0 - */ - public static function sendAskQuestionMail($answerId) - { - return Redshop\Mail\AskQuestion::sendMail($answerId); - } + /** + * Send ask question mail + * + * @param int $answerId Answer id + * + * @return boolean + * + * @deprecated 2.1.0 + */ + public static function sendAskQuestionMail($answerId) + { + return Redshop\Mail\AskQuestion::sendMail($answerId); + } - /** - * Send economic book invoice mail - * - * @param int $orderId Order id - * @param string $bookInvoicePdf Book invoice PDF - * - * @return boolean - * - * @deprecated 2.1.0 - */ - public static function sendEconomicBookInvoiceMail($orderId = 0, $bookInvoicePdf = "") - { - return Redshop\Mail\Invoice::sendEconomicBookInvoiceMail($orderId, $bookInvoicePdf); - } + /** + * Send economic book invoice mail + * + * @param int $orderId Order id + * @param string $bookInvoicePdf Book invoice PDF + * + * @return boolean + * + * @deprecated 2.1.0 + */ + public static function sendEconomicBookInvoiceMail($orderId = 0, $bookInvoicePdf = "") + { + return Redshop\Mail\Invoice::sendEconomicBookInvoiceMail($orderId, $bookInvoicePdf); + } - /** - * Send request tax exempt mail - * - * @param object $data Mail data - * @param string $username Username - * - * @return boolean - * @deprecated 2.1.0 - */ - public static function sendRequestTaxExemptMail($data, $username = "") - { - return Redshop\Mail\User::sendRequestTaxExempt($data, $username); - } + /** + * Send request tax exempt mail + * + * @param object $data Mail data + * @param string $username Username + * + * @return boolean + * @deprecated 2.1.0 + */ + public static function sendRequestTaxExemptMail($data, $username = "") + { + return Redshop\Mail\User::sendRequestTaxExempt($data, $username); + } - /** - * Send catalog request - * - * @param array $catalog Catalog data - * - * @return boolean - * - * @deprecated 2.1.0 - * @see Redshop\Mail\Catalog::sendRequest - */ - public static function sendCatalogRequest($catalog = array()) - { - return Redshop\Mail\Catalog::sendRequest($catalog); - } + /** + * Send catalog request + * + * @param array $catalog Catalog data + * + * @return boolean + * + * @deprecated 2.1.0 + * @see Redshop\Mail\Catalog::sendRequest + */ + public static function sendCatalogRequest($catalog = array()) + { + return Redshop\Mail\Catalog::sendRequest($catalog); + } - /** - * Send catalog request - * - * @param string $from Sender email - * @param string $fromName Sender name - * @param mixed $receiver Receiver email - * @param string $subject Mail subject - * @param string $body Mail body - * @param boolean $isHtml True for use HTML for plain. - * @param mixed $mailCC List of CC emails - * @param mixed $mailBCC List of Bcc emails - * @param mixed $attachment Attachment files. - * @param string $mailSection Mail Section - * @param array $argList Function arguments - * - * @return boolean True on success. False otherwise. - * @deprecated 2.1.0 - * @see Redshop\Mail\Helper::sendEmail - */ - public static function sendEmail($from, $fromName, $receiver, $subject, $body, $isHtml = true, $mailCC = null, - $mailBCC = null, $attachment = null, $mailSection = '', $argList = array() - ) - { - return Redshop\Mail\Helper::sendEmail( - $from, $fromName, $receiver, $subject, $body, $isHtml, - $mailCC, $mailBCC, $attachment, $mailSection, $argList - ); - } + /** + * Send catalog request + * + * @param string $from Sender email + * @param string $fromName Sender name + * @param mixed $receiver Receiver email + * @param string $subject Mail subject + * @param string $body Mail body + * @param boolean $isHtml True for use HTML for plain. + * @param mixed $mailCC List of CC emails + * @param mixed $mailBCC List of Bcc emails + * @param mixed $attachment Attachment files. + * @param string $mailSection Mail Section + * @param array $argList Function arguments + * + * @return boolean True on success. False otherwise. + * @deprecated 2.1.0 + * @see Redshop\Mail\Helper::sendEmail + */ + public static function sendEmail( + $from, + $fromName, + $receiver, + $subject, + $body, + $isHtml = true, + $mailCC = null, + $mailBCC = null, + $attachment = null, + $mailSection = '', + $argList = array() + ) { + return Redshop\Mail\Helper::sendEmail( + $from, + $fromName, + $receiver, + $subject, + $body, + $isHtml, + $mailCC, + $mailBCC, + $attachment, + $mailSection, + $argList + ); + } } diff --git a/libraries/redshop/helper/manufacturer.php b/libraries/redshop/helper/manufacturer.php index ed43487829e..940fd2a2985 100644 --- a/libraries/redshop/helper/manufacturer.php +++ b/libraries/redshop/helper/manufacturer.php @@ -16,18 +16,18 @@ */ class RedshopHelperManufacturer { - /** - * Function getmanufacturers. - * - * @return array - */ - public static function getManufacturers() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn(array('id', 'name'))) - ->from($db->qn('#__redshop_manufacturer')); + /** + * Function getmanufacturers. + * + * @return array + */ + public static function getManufacturers() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn(array('id', 'name'))) + ->from($db->qn('#__redshop_manufacturer')); - return $db->setQuery($query)->loadObjectlist(); - } + return $db->setQuery($query)->loadObjectlist(); + } } diff --git a/libraries/redshop/helper/media.php b/libraries/redshop/helper/media.php index 1be80efa5b7..e259657d449 100644 --- a/libraries/redshop/helper/media.php +++ b/libraries/redshop/helper/media.php @@ -18,997 +18,994 @@ */ class RedshopHelperMedia { - /** - * @var array - * - * @since 2.0.3 - */ - protected static $medias = array(); - - /** - * Checks if the file is an image - * - * @param string $fileName The filename - * - * @return boolean - * - * @since 2.0.0.3 - */ - public static function isImage($fileName) - { - static $imageTypes = 'xcf|odg|gif|jpg|png|bmp'; - - return preg_match("/$imageTypes/i", $fileName); - } - - /** - * Checks if the file is an image - * - * @param string $fileName The filename - * - * @return boolean - * - * @since 2.0.0.3 - */ - public static function getTypeIcon($fileName) - { - // Get file extension - return strtolower(substr($fileName, strrpos($fileName, '.') + 1)); - } - - /** - * Print size of an file to Kb or Mb - * - * @param integer $size Size of file - * - * @return string - * - * @since 2.0.0.3 - */ - public static function parseSize($size) - { - if ($size < 1024) - { - return $size . ' bytes'; - } - else - { - if ($size >= 1024 && $size < 1024 * 1024) - { - return sprintf('%01.2f', $size / 1024.0) . ' Kb'; - } - - else - { - return sprintf('%01.2f', $size / (1024.0 * 1024)) . ' Mb'; - } - } - } - - /** - * Resize current resolution of an image to new width and height - * - * @param integer $width New width in pixel - * @param integer $height New height in pixel - * @param integer $target Current resolution - * - * @return array - * - * @since 2.0.0.3 - */ - public static function imageResize($width, $height, $target) - { - /** - * takes the larger size of the width and height and applies the - * formula accordingly...this is so this script will work - * dynamically with any size image - */ - if ($width > $height) - { - $percentage = ($target / $width); - } - else - { - $percentage = ($target / $height); - } - - // Gets the new value and applies the percentage, then rounds the value - $width = round($width * $percentage); - $height = round($height * $percentage); - - return array($width, $height); - } - - /** - * Checks amount of files in a directory - * - * @param string $dir Directory need to be checked - * - * @return array - * - * @since 2.0.0.3 - */ - public static function countFiles($dir) - { - return \Redshop\Environment\Directory::count($dir); - } - - /** - * Rework and standardlize file name. - * - * @param string $fileName File name - * @param integer $id ID current item - * - * @return string - * - * @since 2.0.0.3 - */ - public static function cleanFileName($fileName, $id = null) - { - $fileExt = strtolower(JFile::getExt($fileName)); - $fileNameNoExt = JFile::stripExt(basename($fileName)); - $fileNameNoExt = preg_replace("/[&'#]/", '', $fileNameNoExt); - $fileNameNoExt = JApplicationHelper::stringURLSafe($fileNameNoExt); - $fileName = JPath::clean($fileName); - $segments = explode(DIRECTORY_SEPARATOR, $fileName); - - if (strlen($fileNameNoExt) === 0) - { - $fileNameNoExt = $id; - } - - $fileNameNoExt = substr($fileNameNoExt, 0, 40); - $fileName = time() . '_' . $fileNameNoExt . '.' . $fileExt; - - if (!empty($segments)) - { - $segments[count($segments) - 1] = $fileName; - - return implode(DIRECTORY_SEPARATOR, $segments); - } - - return $fileName; - } - - /** - * Get redSHOP images live thumbnail path - * - * @param string $imageName Image Name - * @param string $dest Image Destination path - * @param string $command Commands like thumb, upload etc... - * @param string $type Thumbnail for types like, product, category, subcolor etc... - * @param integer $width Thumbnail Width - * @param integer $height Thumbnail Height - * @param integer $proportional Thumbnail Proportional sizing enable / disable. - * @param string $section Use on new structure of media folders. - * @param integer $sectionId Use on new structure of media folders. ID of section. - * - * @return string Thumbnail Live path - * @throws Exception - * - * @since 2.0.0.3 - */ - public static function getImagePath($imageName, $dest, $command = 'upload', $type = 'product', $width = 50, - $height = 50, $proportional = -1, $section = '', $sectionId = 0) - { - // Trying to set an optional argument - if ($proportional === -1) - { - $proportional = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); - } - - // Set Default Type - if (empty($type) || !$imageName) - { - return REDSHOP_FRONT_IMAGES_ABSPATH . 'noimage.jpg'; - } - - // Set Default Width - $width = $width <= 0 ? 50 : $width; - - // Set Default Height - $height = $height <= 0 ? 50 : $height; - - // Check section if in new media structure. - $filePath = JPATH_SITE . '/components/com_redshop/assets/images/' . $type . '/' . $imageName; - - if (in_array($section, array('manufacturer', 'category'))) - { - $filePath = REDSHOP_MEDIA_IMAGE_RELPATH . $section . '/' . $sectionId . '/' . $imageName; - } - - $physicalPath = self::generateImages($filePath, $dest, $width, $height, $command, $proportional); - - // Can not generate image - if (!$physicalPath) - { - return false; - } - - // Prevent space in file path - $physicalPath = str_replace(' ', '%20', $physicalPath); - - // Check section if in new media structure. - if (in_array($section, array('manufacturer', 'category'))) - { - return REDSHOP_MEDIA_IMAGE_ABSPATH . $section . '/' . $sectionId . '/thumb/' . basename($physicalPath); - } - - return REDSHOP_FRONT_IMAGES_ABSPATH . $type . '/thumb/' . basename($physicalPath); - } - - /** - * Generate thumbnail for image file - * - * @param string $filePath Path of an image - * @param string $dest Destination to generate is a new file path - * @param integer $width New width in pixel - * @param integer $height New height in pixel - * @param string $command Have 2 options: 'copy' or 'upload' - * @param integer $proportional Try to make image proportionally - * - * @return string Return destination of new thumbnail - * @throws Exception - * - * @since 2.0.0.3 - */ - public static function generateImages($filePath, $dest, $width, $height, $command = 'upload', $proportional = -1) - { - // Trying to set an optional argument - if ($proportional === -1) - { - $proportional = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); - } - - if (!JFile::exists($filePath)) - { - return false; - } - - $ret = false; - - switch (exif_imagetype($filePath)) - { - // IMAGETYPE_GIF - case '1': - - // IMAGETYPE_JPEG - case '2': - - // IMAGETYPE_PNG - case '3': - - // This method should be expanded to be usable for other purposes not just making thumbs - // But for now it just makes thumbs and proceed to the else part - if ($command != 'thumb') - { - switch ($command) - { - case 'copy': - if (!JFile::copy($filePath, $dest)) - { - return false; - } - - break; - case 'upload': - default: - if (!JFile::upload($filePath, $dest)) - { - return false; - } - break; - } - } - // Thumb - else - { - $srcPathInfo = pathinfo($filePath); - $dest = $srcPathInfo['dirname'] . '/thumb/' . $srcPathInfo['filename'] . '_w' - . $width . '_h' . $height . '.' . $srcPathInfo['extension']; - $ret = $dest; - - if (!JFile::exists($dest)) - { - $ret = self::writeImage($filePath, $dest, '', $width, $height, $proportional); - } - } - - break; - } - - return $ret; - } - - /** - * Copy an image to new destination - * - * @param string $src Source path need to copy - * @param string $dest Destination path to copy - * @param string $altDest If exist alternative path will replace destination path - * @param integer $width New width in pixel - * @param integer $height New height in pixel - * @param integer $proportional Try to make image proportionally - * - * @return string Return destination path - * @throws Exception - * - * @since 2.0.0.3 - */ - public static function writeImage($src, $dest, $altDest, $width, $height, $proportional = -1) - { - // Trying to set an optional argument - if ($proportional == -1) - { - $proportional = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); - } - - ob_start(); - self::resizeImage($src, $width, $height, $proportional, 'browser', false); - $contents = ob_get_contents(); - ob_end_clean(); - - if (JFile::exists($dest) && $altDest != '') - { - if (JFile::exists($altDest)) - { - return false; - } - - $dest = $altDest; - } - - if (!JFile::write($dest, $contents)) - { - return false; - } - - return $dest; - } - - /** - * Create a directory - * - * @param string $path New directory path - * - * @return boolean Return true or false - * - * @since 2.0.0.3 - */ - public static function createDir($path) - { - return \Redshop\Environment\Directory::create($path); - } - - /** - * Resize image to new resolution - * - * @param string $file Current image to resize - * @param integer $width Width in pixel - * @param integer $height Height in pixel - * @param integer $proportional Try to make image proportionally - * @param string $output Have 3 options: 'browser','file', 'return' - * @param boolean $deleteOriginal Default is true, delete originial file after resize - * @param boolean $useLinuxCommands Default is false use @unlink(), if true use 'rm' instead - * - * @return mixed If $output is set by 'return': Return new file path, else return boolean - * @throws Exception - * - * @since 2.0.0.3 - */ - public static function resizeImage( - $file, $width = 0, $height = 0, $proportional = -1, $output = 'file', - $deleteOriginal = true, $useLinuxCommands = false - ) - { - // Trying to set an optional argument - if ($proportional === -1) - { - $proportional = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); - } - - if ($height <= 0 && $width <= 0) - { - return false; - } - - // Setting defaults and meta - $info = getimagesize($file); - list($widthOld, $heightOld) = $info; - $horizontalCenter = 0; - $verticalCenter = 0; - - // Calculating proportionality resize - switch ($proportional) - { - case '1': - if ($width === 0) - { - $factor = $height / $heightOld; - } - elseif ($height === 0) - { - $factor = $width / $widthOld; - } - else - { - $factor = min($width / $widthOld, $height / $heightOld); - } - - $finalWidth = round($widthOld * $factor); - $finalHeight = round($heightOld * $factor); - break; - - // Resize and cropped - case '2': - $width = ($width <= 0) ? $widthOld : $width; - $height = ($height <= 0) ? $heightOld : $height; - $ratioOrig = $widthOld / $heightOld; - - if ($width / $height > $ratioOrig) - { - $finalHeight = $width / $ratioOrig; - $finalWidth = $width; - } - else - { - $finalWidth = $height * $ratioOrig; - $finalHeight = $height; - } - - $xMid = $finalWidth / 2; - $yMid = $finalHeight / 2; - $horizontalCenter = $xMid - ($width / 2); - $verticalCenter = $yMid - ($height / 2); - break; - - // Not proportionality resize - case '0': - default: - $finalWidth = ($width <= 0) ? $widthOld : $width; - $finalHeight = ($height <= 0) ? $heightOld : $height; - } - - // Loading image to memory according to type - switch ($info[2]) - { - case IMAGETYPE_GIF: - $image = imagecreatefromgif($file); - break; - case IMAGETYPE_JPEG: - $image = imagecreatefromjpeg($file); - break; - case IMAGETYPE_PNG: - $image = imagecreatefrompng($file); - break; - default: - return false; - } - - // This is the resizing/resampling/transparency-preserving magic - $imageResized = imagecreatetruecolor($finalWidth, $finalHeight); - - if ($info[2] == IMAGETYPE_GIF || $info[2] == IMAGETYPE_PNG) - { - $transparency = imagecolortransparent($image); - - if ($info[2] == IMAGETYPE_PNG) - { - imagealphablending($imageResized, false); - $color = imagecolorallocatealpha($imageResized, 0, 0, 0, 127); - imagefill($imageResized, 0, 0, $color); - imagesavealpha($imageResized, true); - } - elseif ($transparency >= 0) - { - $transparentColor = imagecolorsforindex($image, $transparency); - - $transparency = imagecolorallocate($imageResized, $transparentColor['red'], $transparentColor['green'], $transparentColor['blue']); - - imagefill($imageResized, 0, 0, $transparency); - imagecolortransparent($imageResized, $transparency); - } - } - - imagecopyresampled($imageResized, $image, 0, 0, 0, 0, $finalWidth, $finalHeight, $widthOld, $heightOld); - - if ($proportional === 2) - { - $thumb = imagecreatetruecolor($width, $height); - imagecopyresampled($thumb, $imageResized, 0, 0, $horizontalCenter, $verticalCenter, $width, $height, $width, $height); - $imageResized = $thumb; - } - - // Taking care of original, if needed - if ($deleteOriginal) - { - if ($useLinuxCommands) - { - exec('rm ' . $file); - } - - else - { - JFile::delete($file); - } - } - - // Preparing a method of providing result - switch (strtolower($output)) - { - case 'browser': - $output = null; - break; - - case 'file': - $output = $file; - break; - - case 'return': - return $imageResized; - - default: - break; - } - - // Writing image according to type to the output destination - switch ($info[2]) - { - case IMAGETYPE_GIF: - imagegif($imageResized, $output); - break; - case IMAGETYPE_JPEG: - imagejpeg($imageResized, $output, Redshop::getConfig()->get('IMAGE_QUALITY_OUTPUT')); - break; - case IMAGETYPE_PNG: - $pngQuality = (Redshop::getConfig()->get('IMAGE_QUALITY_OUTPUT') - 100) / 11.111111; - $pngQuality = round(abs($pngQuality)); - imagepng($imageResized, $output, $pngQuality); - break; - default: - self::cleanup($imageResized); - self::cleanup($image); - - return false; - } - - self::cleanup($imageResized); - self::cleanup($image); - - return true; - } - - /** - * Create thumbnail from gif/jpg/png image - * - * @param string $fileType Have 3 options: gif, png, jpg - * @param string $srcImg Source image - * @param string $destImg Destination to create thumbnail - * @param integer $nWidth Width in pixel - * @param integer $nHeight Height in pixel - * - * @return string Destination of new thumbnail - * - * @since 2.0.0.3 - */ - public static function createThumb($fileType, $srcImg, $destImg, $nWidth, $nHeight) - { - $newImg = null; - - if ($fileType === "gif") - { - $im = imagecreatefromgif($destImg); - - // Original picture width is stored - $width = imagesx($im); - - // Original picture height is stored - $height = imagesy($im); - $newImg = imagecreatetruecolor($nWidth, $nHeight); - imagecopyresized($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $width, $height); - - imagegif($newImg, $srcImg); - JPath::setPermissions($srcImg, '0644'); - } - - if ($fileType === "jpg") - { - $im = imagecreatefromjpeg($destImg); - - // Original picture width is stored - $width = imagesx($im); - - // Original picture height is stored - $height = imagesy($im); - $newImg = imagecreatetruecolor($nWidth, $nHeight); - imagecopyresized($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $width, $height); - imagejpeg($newImg, $srcImg); - JPath::setPermissions($srcImg, '0644'); - } - - if ($fileType === "png") - { - $im = imagecreatefrompng($destImg); - - // Original picture width is stored - $width = imagesx($im); - - // Original picture height is stored - $height = imagesy($im); - $newImg = imagecreatetruecolor($nWidth, $nHeight); - imagecopyresized($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $width, $height); - imagepng($newImg, $srcImg); - JPath::setPermissions($srcImg, '0644'); - } - - return $newImg; - } - - /** - * Method for get additional media images - * - * @param int $sectionId Section Id - * @param string $section Section name - * @param string $mediaType Media type - * - * @return array - * - * @since 2.0.3 - */ - public static function getAdditionMediaImage($sectionId = 0, $section = '', $mediaType = 'images') - { - $key = $sectionId . '_' . $section . '_' . $mediaType; - - if (array_key_exists($key, static::$medias)) - { - return static::$medias[$key]; - } - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('m.*') - ->from($db->qn('#__redshop_media', 'm')) - ->where($db->qn('m.media_section') . ' = ' . $db->quote($section)) - ->where($db->qn('m.media_type') . ' = ' . $db->quote($mediaType)) - ->where($db->qn('m.section_id') . ' = ' . (int) $sectionId) - ->where($db->qn('m.published') . ' = 1') - ->order($db->qn('m.ordering') . ',' . $db->qn('m.media_id') . ' ASC'); - - switch ($section) - { - case 'product': - $query->select('p.*') - ->leftJoin( - $db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('m.section_id') - ); - break; - - case 'property': - $query->select('p.*') - ->leftJoin( - $db->qn('#__redshop_product_attribute_property', 'p') - . ' ON ' . $db->qn('p.property_id') . ' = ' . $db->qn('m.section_id') - ); - break; - - case 'subproperty': - $query->select('p.*') - ->leftJoin( - $db->qn('#__redshop_product_subattribute_color', 'p') - . ' ON ' . $db->qn('p.subattribute_color_id') . ' = ' . $db->qn('m.section_id') - ); - break; - - case 'manufacturer': - $query->select('p.*') - ->leftJoin( - $db->qn('#__redshop_manufacturer', 'p') . ' ON ' . $db->qn('p.id') . ' = ' . $db->qn('m.section_id') - ); - break; - - default: - break; - } - - static::$medias[$key] = $db->setQuery($query)->loadObjectList(); - - return static::$medias[$key]; - } - - /** - * Generate thumb image with watermark - * - * @param string $section Image section - * @param string $imageName Image name - * @param string $thumbWidth Thumb width - * @param string $thumbHeight Thumb height - * @param integer $enableWatermark Enable watermark - * - * @return string - * @throws Exception - * - * @since 2.0.6 - */ - public static function watermark($section, $imageName = '', $thumbWidth = '', $thumbHeight = '', $enableWatermark = -1) - { - if ($enableWatermark == -1) - { - $enableWatermark = Redshop::getConfig()->get('WATERMARK_PRODUCT_IMAGE'); - } - - $pathMainImage = $section . '/' . $imageName; - - try - { - // If main image not exists - display noimage - if (!JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . $pathMainImage)) - { - $pathMainImage = 'noimage.jpg'; - - throw new Exception; - } - - // If watermark not exists or disable - display simple thumb - if ($enableWatermark <= 0 - || !file_exists(REDSHOP_FRONT_IMAGES_RELPATH . 'product/' . Redshop::getConfig()->get('WATERMARK_IMAGE')) - ) - { - throw new Exception; - } - - // If width and height not set - use with and height original image - if (((int) $thumbWidth == 0 && (int) $thumbHeight == 0) - || ((int) $thumbWidth != 0 && (int) $thumbHeight == 0) - || ((int) $thumbWidth == 0 && (int) $thumbHeight != 0) - ) - { - list($thumbWidth, $thumbHeight) = getimagesize(REDSHOP_FRONT_IMAGES_RELPATH . $pathMainImage); - } - - $imageNameWithPrefix = JFile::stripExt($imageName) . '_w' . (int) $thumbWidth . '_h' . (int) $thumbHeight . '_i' - . JFile::stripExt(basename(Redshop::getConfig()->get('WATERMARK_IMAGE'))) . '.' . JFile::getExt($imageName); - - $destinationFile = REDSHOP_FRONT_IMAGES_RELPATH . $section . '/thumb/' . $imageNameWithPrefix; - - if (JFile::exists($destinationFile)) - { - return REDSHOP_FRONT_IMAGES_ABSPATH . $section . '/thumb/' . $imageNameWithPrefix; - } - - $filePath = JPATH_SITE . '/components/com_redshop/assets/images/product/' . Redshop::getConfig()->get('WATERMARK_IMAGE'); - - $fileName = self::generateImages($filePath, '', $thumbWidth, $thumbHeight, 'thumb', Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING')); - - $fileInfo = pathinfo($fileName); - $watermark = REDSHOP_FRONT_IMAGES_RELPATH . 'product/thumb/' . $fileInfo['basename']; - - ob_start(); - self::resizeImage( - REDSHOP_FRONT_IMAGES_RELPATH . $pathMainImage, - $thumbWidth, - $thumbHeight, - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'), - 'browser', - false - ); - $contents = ob_get_contents(); - ob_end_clean(); - - if (!JFile::write($destinationFile, $contents)) - { - return REDSHOP_FRONT_IMAGES_ABSPATH . $section . "/" . $imageName; - } - - switch (JFile::getExt(Redshop::getConfig()->get('WATERMARK_IMAGE'))) - { - case 'gif': - $dest = imagecreatefromjpeg($destinationFile); - $src = imagecreatefromgif($watermark); - - list($width, $height) = getimagesize($destinationFile); - list($watermarkWidth, $watermarkHeight) = getimagesize($watermark); - - imagecopymerge( - $dest, $src, ($width - $watermarkWidth) >> 1, ($height - $watermarkHeight) >> 1, 0, 0, $watermarkWidth, $watermarkHeight, 50 - ); - - imagejpeg($dest, $destinationFile); - - break; - - case 'png': - $im = imagecreatefrompng($watermark); - - switch (JFile::getExt($destinationFile)) - { - case 'gif': - $im2 = imagecreatefromgif($destinationFile); - break; - case 'jpg': - $im2 = imagecreatefromjpeg($destinationFile); - break; - case 'png': - $im2 = imagecreatefrompng($destinationFile); - break; - default: - throw new Exception; - } - - imagecopy( - $im2, - $im, - (imagesx($im2) / 2) - (imagesx($im) / 2), (imagesy($im2) / 2) - (imagesy($im) / 2), - 0, - 0, - imagesx($im), - imagesy($im) - ); - - $waterless = imagesx($im2) - imagesx($im); - $rest = ceil($waterless / imagesx($im) / 2); - - for ($n = 1; $n <= $rest; $n++) - { - imagecopy( - $im2, $im, ((imagesx($im2) / 2) - (imagesx($im) / 2)) - (imagesx($im) * $n), - (imagesy($im2) / 2) - (imagesy($im) / 2), 0, 0, imagesx($im), imagesy($im) - ); - - imagecopy( - $im2, $im, ((imagesx($im2) / 2) - (imagesx($im) / 2)) + (imagesx($im) * $n), - (imagesy($im2) / 2) - (imagesy($im) / 2), 0, 0, imagesx($im), imagesy($im) - ); - } - - imagejpeg($im2, $destinationFile); - - break; - - default: - throw new Exception; - } - - return REDSHOP_FRONT_IMAGES_ABSPATH . $section . '/thumb/' . $imageNameWithPrefix; - } - catch (Exception $e) - { - if ($e->getMessage()) - { - JFactory::getApplication()->enqueueMessage($e->getMessage(), 'warning'); - } - - $fileName = REDSHOP_FRONT_IMAGES_ABSPATH . $pathMainImage; - - if ((int) $thumbWidth != 0 || (int) $thumbHeight != 0) - { - $filePath = JPATH_SITE . '/components/com_redshop/assets/images/' . $pathMainImage; - $fileName = self::generateImages( - $filePath, '', $thumbWidth, $thumbHeight, 'thumb', Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') - ); - $fileInfo = pathinfo($fileName); - $fileName = REDSHOP_FRONT_IMAGES_ABSPATH . $section . '/thumb/' . $fileInfo['basename']; - } - - return $fileName; - } - } - - /** - * Get alternative text for media - * - * @param string $mediaSection Media section - * @param int $sectionId Section id - * @param string $mediaName Media name - * @param int $mediaId Media id - * @param string $mediaType Media type - * - * @return string Alternative text from media - * - * @since 2.0.7 - * @throws Exception - */ - public static function getAlternativeText($mediaSection, $sectionId, $mediaName = '', $mediaId = 0, $mediaType = 'images') - { - if ($mediaSection == 'product' && $mediaType == 'images') - { - $productData = \Redshop\Product\Product::getProductById($sectionId); - - if ($mediaName == $productData->product_full_image || $mediaId == $productData->media_id) - { - return $productData->media_alternate_text; - } - } - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('media_alternate_text')) - ->from($db->qn('#__redshop_media')) - ->where($db->qn('media_section') . ' = ' . $db->quote($mediaSection)) - ->where($db->qn('section_id') . ' = ' . (int) $sectionId) - ->where($db->qn('media_type') . ' = ' . $db->quote($mediaType)); - - if (!empty($mediaName)) - { - $query->where($db->qn('media_name') . ' = ' . $db->q($mediaName)); - } - - if ($mediaId) - { - $query->where($db->qn('media_id') . ' = ' . (int) $mediaId); - } - - return $db->setQuery($query)->loadResult(); - } - - /** - * Method for get list of medias - * - * @param string $section Media section (product, category,...) - * @param integer $sectionId Media section ID - * @param string $scope Scope of media - * @param string $type Media type. - * - * @return mixed - * - * @since 2.1.0 - */ - public static function getMedia($section = '', $sectionId = 0, $scope = '', $type = '') - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_media')); - - if (!empty($section)) - { - $query->where($db->qn('media_section') . ' = ' . $db->quote($section)); - } - - if (!empty($sectionId)) - { - $query->where($db->qn('section_id') . ' = ' . (int) $sectionId); - } - - if (!empty($scope)) - { - $query->where($db->qn('scope') . ' = ' . $db->quote($scope)); - } - - if (!empty($type)) - { - $query->where($db->qn('media_type') . ' = ' . $db->quote($type)); - } - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * Method for clean up image resource. - * - * @param resource $res Image resource - * - * @return boolean - * @throws Exception - * - * @since 2.1.0 - */ - protected static function cleanup($res) - { - if (!is_resource($res)) - { - return false; - } - - try - { - return imagedestroy($res); - } - catch (Exception $exception) - { - JFactory::getApplication()->enqueueMessage($exception->getMessage(), 'warning'); - - return false; - } - } + /** + * @var array + * + * @since 2.0.3 + */ + protected static $medias = array(); + + /** + * Checks if the file is an image + * + * @param string $fileName The filename + * + * @return boolean + * + * @since 2.0.0.3 + */ + public static function isImage($fileName) + { + static $imageTypes = 'xcf|odg|gif|jpg|png|bmp'; + + return preg_match("/$imageTypes/i", $fileName); + } + + /** + * Checks if the file is an image + * + * @param string $fileName The filename + * + * @return boolean + * + * @since 2.0.0.3 + */ + public static function getTypeIcon($fileName) + { + // Get file extension + return strtolower(substr($fileName, strrpos($fileName, '.') + 1)); + } + + /** + * Print size of an file to Kb or Mb + * + * @param integer $size Size of file + * + * @return string + * + * @since 2.0.0.3 + */ + public static function parseSize($size) + { + if ($size < 1024) { + return $size . ' bytes'; + } else { + if ($size >= 1024 && $size < 1024 * 1024) { + return sprintf('%01.2f', $size / 1024.0) . ' Kb'; + } else { + return sprintf('%01.2f', $size / (1024.0 * 1024)) . ' Mb'; + } + } + } + + /** + * Resize current resolution of an image to new width and height + * + * @param integer $width New width in pixel + * @param integer $height New height in pixel + * @param integer $target Current resolution + * + * @return array + * + * @since 2.0.0.3 + */ + public static function imageResize($width, $height, $target) + { + /** + * takes the larger size of the width and height and applies the + * formula accordingly...this is so this script will work + * dynamically with any size image + */ + if ($width > $height) { + $percentage = ($target / $width); + } else { + $percentage = ($target / $height); + } + + // Gets the new value and applies the percentage, then rounds the value + $width = round($width * $percentage); + $height = round($height * $percentage); + + return array($width, $height); + } + + /** + * Checks amount of files in a directory + * + * @param string $dir Directory need to be checked + * + * @return array + * + * @since 2.0.0.3 + */ + public static function countFiles($dir) + { + return \Redshop\Environment\Directory::count($dir); + } + + /** + * Rework and standardlize file name. + * + * @param string $fileName File name + * @param integer $id ID current item + * + * @return string + * + * @since 2.0.0.3 + */ + public static function cleanFileName($fileName, $id = null) + { + $fileExt = strtolower(JFile::getExt($fileName)); + $fileNameNoExt = JFile::stripExt(basename($fileName)); + $fileNameNoExt = preg_replace("/[&'#]/", '', $fileNameNoExt); + $fileNameNoExt = JApplicationHelper::stringURLSafe($fileNameNoExt); + $fileName = JPath::clean($fileName); + $segments = explode(DIRECTORY_SEPARATOR, $fileName); + + if (strlen($fileNameNoExt) === 0) { + $fileNameNoExt = $id; + } + + $fileNameNoExt = substr($fileNameNoExt, 0, 40); + $fileName = time() . '_' . $fileNameNoExt . '.' . $fileExt; + + if (!empty($segments)) { + $segments[count($segments) - 1] = $fileName; + + return implode(DIRECTORY_SEPARATOR, $segments); + } + + return $fileName; + } + + /** + * Get redSHOP images live thumbnail path + * + * @param string $imageName Image Name + * @param string $dest Image Destination path + * @param string $command Commands like thumb, upload etc... + * @param string $type Thumbnail for types like, product, category, subcolor etc... + * @param integer $width Thumbnail Width + * @param integer $height Thumbnail Height + * @param integer $proportional Thumbnail Proportional sizing enable / disable. + * @param string $section Use on new structure of media folders. + * @param integer $sectionId Use on new structure of media folders. ID of section. + * + * @return string Thumbnail Live path + * @throws Exception + * + * @since 2.0.0.3 + */ + public static function getImagePath( + $imageName, + $dest, + $command = 'upload', + $type = 'product', + $width = 50, + $height = 50, + $proportional = -1, + $section = '', + $sectionId = 0 + ) { + // Trying to set an optional argument + if ($proportional === -1) { + $proportional = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); + } + + // Set Default Type + if (empty($type) || !$imageName) { + return REDSHOP_FRONT_IMAGES_ABSPATH . 'noimage.jpg'; + } + + // Set Default Width + $width = $width <= 0 ? 50 : $width; + + // Set Default Height + $height = $height <= 0 ? 50 : $height; + + // Check section if in new media structure. + $filePath = JPATH_SITE . '/components/com_redshop/assets/images/' . $type . '/' . $imageName; + + if (in_array($section, array('manufacturer', 'category'))) { + $filePath = REDSHOP_MEDIA_IMAGE_RELPATH . $section . '/' . $sectionId . '/' . $imageName; + } + + $physicalPath = self::generateImages($filePath, $dest, $width, $height, $command, $proportional); + + // Can not generate image + if (!$physicalPath) { + return false; + } + + // Prevent space in file path + $physicalPath = str_replace(' ', '%20', $physicalPath); + + // Check section if in new media structure. + if (in_array($section, array('manufacturer', 'category'))) { + return REDSHOP_MEDIA_IMAGE_ABSPATH . $section . '/' . $sectionId . '/thumb/' . basename($physicalPath); + } + + return REDSHOP_FRONT_IMAGES_ABSPATH . $type . '/thumb/' . basename($physicalPath); + } + + /** + * Generate thumbnail for image file + * + * @param string $filePath Path of an image + * @param string $dest Destination to generate is a new file path + * @param integer $width New width in pixel + * @param integer $height New height in pixel + * @param string $command Have 2 options: 'copy' or 'upload' + * @param integer $proportional Try to make image proportionally + * + * @return string Return destination of new thumbnail + * @throws Exception + * + * @since 2.0.0.3 + */ + public static function generateImages($filePath, $dest, $width, $height, $command = 'upload', $proportional = -1) + { + // Trying to set an optional argument + if ($proportional === -1) { + $proportional = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); + } + + if (!JFile::exists($filePath)) { + return false; + } + + $ret = false; + + switch (exif_imagetype($filePath)) { + // IMAGETYPE_GIF + case '1': + + // IMAGETYPE_JPEG + case '2': + + // IMAGETYPE_PNG + case '3': + + // This method should be expanded to be usable for other purposes not just making thumbs + // But for now it just makes thumbs and proceed to the else part + if ($command != 'thumb') { + switch ($command) { + case 'copy': + if (!JFile::copy($filePath, $dest)) { + return false; + } + + break; + case 'upload': + default: + if (!JFile::upload($filePath, $dest)) { + return false; + } + break; + } + } // Thumb + else { + $srcPathInfo = pathinfo($filePath); + $dest = $srcPathInfo['dirname'] . '/thumb/' . $srcPathInfo['filename'] . '_w' + . $width . '_h' . $height . '.' . $srcPathInfo['extension']; + $ret = $dest; + + if (!JFile::exists($dest)) { + $ret = self::writeImage($filePath, $dest, '', $width, $height, $proportional); + } + } + + break; + } + + return $ret; + } + + /** + * Copy an image to new destination + * + * @param string $src Source path need to copy + * @param string $dest Destination path to copy + * @param string $altDest If exist alternative path will replace destination path + * @param integer $width New width in pixel + * @param integer $height New height in pixel + * @param integer $proportional Try to make image proportionally + * + * @return string Return destination path + * @throws Exception + * + * @since 2.0.0.3 + */ + public static function writeImage($src, $dest, $altDest, $width, $height, $proportional = -1) + { + // Trying to set an optional argument + if ($proportional == -1) { + $proportional = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); + } + + ob_start(); + self::resizeImage($src, $width, $height, $proportional, 'browser', false); + $contents = ob_get_contents(); + ob_end_clean(); + + if (JFile::exists($dest) && $altDest != '') { + if (JFile::exists($altDest)) { + return false; + } + + $dest = $altDest; + } + + if (!JFile::write($dest, $contents)) { + return false; + } + + return $dest; + } + + /** + * Resize image to new resolution + * + * @param string $file Current image to resize + * @param integer $width Width in pixel + * @param integer $height Height in pixel + * @param integer $proportional Try to make image proportionally + * @param string $output Have 3 options: 'browser','file', 'return' + * @param boolean $deleteOriginal Default is true, delete originial file after resize + * @param boolean $useLinuxCommands Default is false use @unlink(), if true use 'rm' instead + * + * @return mixed If $output is set by 'return': Return new file path, else return boolean + * @throws Exception + * + * @since 2.0.0.3 + */ + public static function resizeImage( + $file, + $width = 0, + $height = 0, + $proportional = -1, + $output = 'file', + $deleteOriginal = true, + $useLinuxCommands = false + ) { + // Trying to set an optional argument + if ($proportional === -1) { + $proportional = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); + } + + if ($height <= 0 && $width <= 0) { + return false; + } + + // Setting defaults and meta + $info = getimagesize($file); + list($widthOld, $heightOld) = $info; + $horizontalCenter = 0; + $verticalCenter = 0; + + // Calculating proportionality resize + switch ($proportional) { + case '1': + if ($width === 0) { + $factor = $height / $heightOld; + } elseif ($height === 0) { + $factor = $width / $widthOld; + } else { + $factor = min($width / $widthOld, $height / $heightOld); + } + + $finalWidth = round($widthOld * $factor); + $finalHeight = round($heightOld * $factor); + break; + + // Resize and cropped + case '2': + $width = ($width <= 0) ? $widthOld : $width; + $height = ($height <= 0) ? $heightOld : $height; + $ratioOrig = $widthOld / $heightOld; + + if ($width / $height > $ratioOrig) { + $finalHeight = $width / $ratioOrig; + $finalWidth = $width; + } else { + $finalWidth = $height * $ratioOrig; + $finalHeight = $height; + } + + $xMid = $finalWidth / 2; + $yMid = $finalHeight / 2; + $horizontalCenter = $xMid - ($width / 2); + $verticalCenter = $yMid - ($height / 2); + break; + + // Not proportionality resize + case '0': + default: + $finalWidth = ($width <= 0) ? $widthOld : $width; + $finalHeight = ($height <= 0) ? $heightOld : $height; + } + + // Loading image to memory according to type + switch ($info[2]) { + case IMAGETYPE_GIF: + $image = imagecreatefromgif($file); + break; + case IMAGETYPE_JPEG: + $image = imagecreatefromjpeg($file); + break; + case IMAGETYPE_PNG: + $image = imagecreatefrompng($file); + break; + default: + return false; + } + + // This is the resizing/resampling/transparency-preserving magic + $imageResized = imagecreatetruecolor($finalWidth, $finalHeight); + + if ($info[2] == IMAGETYPE_GIF || $info[2] == IMAGETYPE_PNG) { + $transparency = imagecolortransparent($image); + + if ($info[2] == IMAGETYPE_PNG) { + imagealphablending($imageResized, false); + $color = imagecolorallocatealpha($imageResized, 0, 0, 0, 127); + imagefill($imageResized, 0, 0, $color); + imagesavealpha($imageResized, true); + } elseif ($transparency >= 0) { + $transparentColor = imagecolorsforindex($image, $transparency); + + $transparency = imagecolorallocate( + $imageResized, + $transparentColor['red'], + $transparentColor['green'], + $transparentColor['blue'] + ); + + imagefill($imageResized, 0, 0, $transparency); + imagecolortransparent($imageResized, $transparency); + } + } + + imagecopyresampled($imageResized, $image, 0, 0, 0, 0, $finalWidth, $finalHeight, $widthOld, $heightOld); + + if ($proportional === 2) { + $thumb = imagecreatetruecolor($width, $height); + imagecopyresampled( + $thumb, + $imageResized, + 0, + 0, + $horizontalCenter, + $verticalCenter, + $width, + $height, + $width, + $height + ); + $imageResized = $thumb; + } + + // Taking care of original, if needed + if ($deleteOriginal) { + if ($useLinuxCommands) { + exec('rm ' . $file); + } else { + JFile::delete($file); + } + } + + // Preparing a method of providing result + switch (strtolower($output)) { + case 'browser': + $output = null; + break; + + case 'file': + $output = $file; + break; + + case 'return': + return $imageResized; + + default: + break; + } + + // Writing image according to type to the output destination + switch ($info[2]) { + case IMAGETYPE_GIF: + imagegif($imageResized, $output); + break; + case IMAGETYPE_JPEG: + imagejpeg($imageResized, $output, Redshop::getConfig()->get('IMAGE_QUALITY_OUTPUT')); + break; + case IMAGETYPE_PNG: + $pngQuality = (Redshop::getConfig()->get('IMAGE_QUALITY_OUTPUT') - 100) / 11.111111; + $pngQuality = round(abs($pngQuality)); + imagepng($imageResized, $output, $pngQuality); + break; + default: + self::cleanup($imageResized); + self::cleanup($image); + + return false; + } + + self::cleanup($imageResized); + self::cleanup($image); + + return true; + } + + /** + * Method for clean up image resource. + * + * @param resource $res Image resource + * + * @return boolean + * @throws Exception + * + * @since 2.1.0 + */ + protected static function cleanup($res) + { + if (!is_resource($res)) { + return false; + } + + try { + return imagedestroy($res); + } catch (Exception $exception) { + JFactory::getApplication()->enqueueMessage($exception->getMessage(), 'warning'); + + return false; + } + } + + /** + * Create a directory + * + * @param string $path New directory path + * + * @return boolean Return true or false + * + * @since 2.0.0.3 + */ + public static function createDir($path) + { + return \Redshop\Environment\Directory::create($path); + } + + /** + * Create thumbnail from gif/jpg/png image + * + * @param string $fileType Have 3 options: gif, png, jpg + * @param string $srcImg Source image + * @param string $destImg Destination to create thumbnail + * @param integer $nWidth Width in pixel + * @param integer $nHeight Height in pixel + * + * @return string Destination of new thumbnail + * + * @since 2.0.0.3 + */ + public static function createThumb($fileType, $srcImg, $destImg, $nWidth, $nHeight) + { + $newImg = null; + + if ($fileType === "gif") { + $im = imagecreatefromgif($destImg); + + // Original picture width is stored + $width = imagesx($im); + + // Original picture height is stored + $height = imagesy($im); + $newImg = imagecreatetruecolor($nWidth, $nHeight); + imagecopyresized($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $width, $height); + + imagegif($newImg, $srcImg); + JPath::setPermissions($srcImg, '0644'); + } + + if ($fileType === "jpg") { + $im = imagecreatefromjpeg($destImg); + + // Original picture width is stored + $width = imagesx($im); + + // Original picture height is stored + $height = imagesy($im); + $newImg = imagecreatetruecolor($nWidth, $nHeight); + imagecopyresized($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $width, $height); + imagejpeg($newImg, $srcImg); + JPath::setPermissions($srcImg, '0644'); + } + + if ($fileType === "png") { + $im = imagecreatefrompng($destImg); + + // Original picture width is stored + $width = imagesx($im); + + // Original picture height is stored + $height = imagesy($im); + $newImg = imagecreatetruecolor($nWidth, $nHeight); + imagecopyresized($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $width, $height); + imagepng($newImg, $srcImg); + JPath::setPermissions($srcImg, '0644'); + } + + return $newImg; + } + + /** + * Method for get additional media images + * + * @param int $sectionId Section Id + * @param string $section Section name + * @param string $mediaType Media type + * + * @return array + * + * @since 2.0.3 + */ + public static function getAdditionMediaImage($sectionId = 0, $section = '', $mediaType = 'images') + { + $key = $sectionId . '_' . $section . '_' . $mediaType; + + if (array_key_exists($key, static::$medias)) { + return static::$medias[$key]; + } + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('m.*') + ->from($db->qn('#__redshop_media', 'm')) + ->where($db->qn('m.media_section') . ' = ' . $db->quote($section)) + ->where($db->qn('m.media_type') . ' = ' . $db->quote($mediaType)) + ->where($db->qn('m.section_id') . ' = ' . (int)$sectionId) + ->where($db->qn('m.published') . ' = 1') + ->order($db->qn('m.ordering') . ',' . $db->qn('m.media_id') . ' ASC'); + + switch ($section) { + case 'product': + $query->select('p.*') + ->leftJoin( + $db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn( + 'm.section_id' + ) + ); + break; + + case 'property': + $query->select('p.*') + ->leftJoin( + $db->qn('#__redshop_product_attribute_property', 'p') + . ' ON ' . $db->qn('p.property_id') . ' = ' . $db->qn('m.section_id') + ); + break; + + case 'subproperty': + $query->select('p.*') + ->leftJoin( + $db->qn('#__redshop_product_subattribute_color', 'p') + . ' ON ' . $db->qn('p.subattribute_color_id') . ' = ' . $db->qn('m.section_id') + ); + break; + + case 'manufacturer': + $query->select('p.*') + ->leftJoin( + $db->qn('#__redshop_manufacturer', 'p') . ' ON ' . $db->qn('p.id') . ' = ' . $db->qn( + 'm.section_id' + ) + ); + break; + + default: + break; + } + + static::$medias[$key] = $db->setQuery($query)->loadObjectList(); + + return static::$medias[$key]; + } + + /** + * Generate thumb image with watermark + * + * @param string $section Image section + * @param string $imageName Image name + * @param string $thumbWidth Thumb width + * @param string $thumbHeight Thumb height + * @param integer $enableWatermark Enable watermark + * + * @return string + * @throws Exception + * + * @since 2.0.6 + */ + public static function watermark( + $section, + $imageName = '', + $thumbWidth = '', + $thumbHeight = '', + $enableWatermark = -1 + ) { + if ($enableWatermark == -1) { + $enableWatermark = Redshop::getConfig()->get('WATERMARK_PRODUCT_IMAGE'); + } + + $pathMainImage = $section . '/' . $imageName; + + try { + // If main image not exists - display noimage + if (!JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . $pathMainImage)) { + $pathMainImage = 'noimage.jpg'; + + throw new Exception; + } + + // If watermark not exists or disable - display simple thumb + if ($enableWatermark <= 0 + || !file_exists( + REDSHOP_FRONT_IMAGES_RELPATH . 'product/' . Redshop::getConfig()->get('WATERMARK_IMAGE') + ) + ) { + throw new Exception; + } + + // If width and height not set - use with and height original image + if (((int)$thumbWidth == 0 && (int)$thumbHeight == 0) + || ((int)$thumbWidth != 0 && (int)$thumbHeight == 0) + || ((int)$thumbWidth == 0 && (int)$thumbHeight != 0) + ) { + list($thumbWidth, $thumbHeight) = getimagesize(REDSHOP_FRONT_IMAGES_RELPATH . $pathMainImage); + } + + $imageNameWithPrefix = JFile::stripExt( + $imageName + ) . '_w' . (int)$thumbWidth . '_h' . (int)$thumbHeight . '_i' + . JFile::stripExt(basename(Redshop::getConfig()->get('WATERMARK_IMAGE'))) . '.' . JFile::getExt( + $imageName + ); + + $destinationFile = REDSHOP_FRONT_IMAGES_RELPATH . $section . '/thumb/' . $imageNameWithPrefix; + + if (JFile::exists($destinationFile)) { + return REDSHOP_FRONT_IMAGES_ABSPATH . $section . '/thumb/' . $imageNameWithPrefix; + } + + $filePath = JPATH_SITE . '/components/com_redshop/assets/images/product/' . Redshop::getConfig()->get( + 'WATERMARK_IMAGE' + ); + + $fileName = self::generateImages( + $filePath, + '', + $thumbWidth, + $thumbHeight, + 'thumb', + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') + ); + + $fileInfo = pathinfo($fileName); + $watermark = REDSHOP_FRONT_IMAGES_RELPATH . 'product/thumb/' . $fileInfo['basename']; + + ob_start(); + self::resizeImage( + REDSHOP_FRONT_IMAGES_RELPATH . $pathMainImage, + $thumbWidth, + $thumbHeight, + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'), + 'browser', + false + ); + $contents = ob_get_contents(); + ob_end_clean(); + + if (!JFile::write($destinationFile, $contents)) { + return REDSHOP_FRONT_IMAGES_ABSPATH . $section . "/" . $imageName; + } + + switch (JFile::getExt(Redshop::getConfig()->get('WATERMARK_IMAGE'))) { + case 'gif': + $dest = imagecreatefromjpeg($destinationFile); + $src = imagecreatefromgif($watermark); + + list($width, $height) = getimagesize($destinationFile); + list($watermarkWidth, $watermarkHeight) = getimagesize($watermark); + + imagecopymerge( + $dest, + $src, + ($width - $watermarkWidth) >> 1, + ($height - $watermarkHeight) >> 1, + 0, + 0, + $watermarkWidth, + $watermarkHeight, + 50 + ); + + imagejpeg($dest, $destinationFile); + + break; + + case 'png': + $im = imagecreatefrompng($watermark); + + switch (JFile::getExt($destinationFile)) { + case 'gif': + $im2 = imagecreatefromgif($destinationFile); + break; + case 'jpg': + $im2 = imagecreatefromjpeg($destinationFile); + break; + case 'png': + $im2 = imagecreatefrompng($destinationFile); + break; + default: + throw new Exception; + } + + imagecopy( + $im2, + $im, + (imagesx($im2) / 2) - (imagesx($im) / 2), + (imagesy($im2) / 2) - (imagesy($im) / 2), + 0, + 0, + imagesx($im), + imagesy($im) + ); + + $waterless = imagesx($im2) - imagesx($im); + $rest = ceil($waterless / imagesx($im) / 2); + + for ($n = 1; $n <= $rest; $n++) { + imagecopy( + $im2, + $im, + ((imagesx($im2) / 2) - (imagesx($im) / 2)) - (imagesx($im) * $n), + (imagesy($im2) / 2) - (imagesy($im) / 2), + 0, + 0, + imagesx($im), + imagesy($im) + ); + + imagecopy( + $im2, + $im, + ((imagesx($im2) / 2) - (imagesx($im) / 2)) + (imagesx($im) * $n), + (imagesy($im2) / 2) - (imagesy($im) / 2), + 0, + 0, + imagesx($im), + imagesy($im) + ); + } + + imagejpeg($im2, $destinationFile); + + break; + + default: + throw new Exception; + } + + return REDSHOP_FRONT_IMAGES_ABSPATH . $section . '/thumb/' . $imageNameWithPrefix; + } catch (Exception $e) { + if ($e->getMessage()) { + JFactory::getApplication()->enqueueMessage($e->getMessage(), 'warning'); + } + + $fileName = REDSHOP_FRONT_IMAGES_ABSPATH . $pathMainImage; + + if ((int)$thumbWidth != 0 || (int)$thumbHeight != 0) { + $filePath = JPATH_SITE . '/components/com_redshop/assets/images/' . $pathMainImage; + $fileName = self::generateImages( + $filePath, + '', + $thumbWidth, + $thumbHeight, + 'thumb', + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') + ); + $fileInfo = pathinfo($fileName); + $fileName = REDSHOP_FRONT_IMAGES_ABSPATH . $section . '/thumb/' . $fileInfo['basename']; + } + + return $fileName; + } + } + + /** + * Get alternative text for media + * + * @param string $mediaSection Media section + * @param int $sectionId Section id + * @param string $mediaName Media name + * @param int $mediaId Media id + * @param string $mediaType Media type + * + * @return string Alternative text from media + * + * @throws Exception + * @since 2.0.7 + */ + public static function getAlternativeText( + $mediaSection, + $sectionId, + $mediaName = '', + $mediaId = 0, + $mediaType = 'images' + ) { + if ($mediaSection == 'product' && $mediaType == 'images') { + $productData = \Redshop\Product\Product::getProductById($sectionId); + + if ($mediaName == $productData->product_full_image || $mediaId == $productData->media_id) { + return $productData->media_alternate_text; + } + } + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('media_alternate_text')) + ->from($db->qn('#__redshop_media')) + ->where($db->qn('media_section') . ' = ' . $db->quote($mediaSection)) + ->where($db->qn('section_id') . ' = ' . (int)$sectionId) + ->where($db->qn('media_type') . ' = ' . $db->quote($mediaType)); + + if (!empty($mediaName)) { + $query->where($db->qn('media_name') . ' = ' . $db->q($mediaName)); + } + + if ($mediaId) { + $query->where($db->qn('media_id') . ' = ' . (int)$mediaId); + } + + return $db->setQuery($query)->loadResult(); + } + + /** + * Method for get list of medias + * + * @param string $section Media section (product, category,...) + * @param integer $sectionId Media section ID + * @param string $scope Scope of media + * @param string $type Media type. + * + * @return mixed + * + * @since 2.1.0 + */ + public static function getMedia($section = '', $sectionId = 0, $scope = '', $type = '') + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_media')); + + if (!empty($section)) { + $query->where($db->qn('media_section') . ' = ' . $db->quote($section)); + } + + if (!empty($sectionId)) { + $query->where($db->qn('section_id') . ' = ' . (int)$sectionId); + } + + if (!empty($scope)) { + $query->where($db->qn('scope') . ' = ' . $db->quote($scope)); + } + + if (!empty($type)) { + $query->where($db->qn('media_type') . ' = ' . $db->quote($type)); + } + + return $db->setQuery($query)->loadObjectList(); + } } diff --git a/libraries/redshop/helper/media/image.php b/libraries/redshop/helper/media/image.php index 23cf317c12a..59b48b1809c 100644 --- a/libraries/redshop/helper/media/image.php +++ b/libraries/redshop/helper/media/image.php @@ -18,272 +18,266 @@ */ class RedshopHelperMediaImage { - /** - * Render Drag n Drop template in site - * - * @param string $id ID of media input name - * @param string $type Type of item want to show gallery - * @param string $sectionId Section ID to show - * @param string $mediaSection Section type to show - * @param string $image URL of featured image - * @param boolean $showMedia Show pop-up of media or not. - * @param boolean $useMediaPath Use new structure of media folder or not. - * @param integer $mediaId Media ID - * - * @return string - */ - public static function render($id, $type, $sectionId, $mediaSection, $image, $showMedia = true, $useMediaPath = false, $mediaId = 0) - { - self::requireDependencies(); - - $imgUrl = $useMediaPath ? '/media/com_redshop/images/' . $type . '/' . $sectionId . '/' . $image - : '/components/com_redshop/assets/images/' . $type . '/' . $image; - $imgUrl = JRoute::_($imgUrl); - - $imgFile = $useMediaPath ? REDSHOP_MEDIA_IMAGE_RELPATH . $type . '/' . $sectionId . '/' . $image - : REDSHOP_FRONT_IMAGES_RELPATH . $type . '/' . $image; - - $file = array(); - - if (!empty($image) && file_exists($imgFile)) - { - $file = array( - 'path' => $imgUrl, - 'name' => $image, - 'size' => filesize($imgFile) ? filesize($imgFile) : 0, - 'blob' => 'data: ' . self::getMimeType($imgFile) . ';base64,' . base64_encode(file_get_contents($imgFile)) - ); - } - - return RedshopLayoutHelper::render( - 'media.dropzone', - array( - 'id' => $id, - 'type' => $type, - 'sectionId' => $sectionId, - 'mediaSection' => $mediaSection, - 'file' => $file, - 'showMedia' => $showMedia, - 'mediaId' => $mediaId - ) - ); - } - - /** - * Require dependencies from bower.js. - * Checking dependencies are existed or not then require them to header - * - * @return boolean - */ - public static function requireDependencies() - { - JHtml::stylesheet('com_redshop/dropzone.min.css', array(), true); - JHtml::stylesheet('com_redshop/cropper.min.css', array(), true); - JHtml::stylesheet('com_redshop/lightbox2/css/lightbox.min.css', array(), true); - JHtml::stylesheet('com_redshop/redshop.media.min.css', array(), true); - - JHtml::script('com_redshop/dropzone.min.js', false, true); - JHtml::script('com_redshop/cropper.min.js', false, true); - JHtml::script('com_redshop/lightbox2.min.js', false, true); - JHtml::script('com_redshop/redshop.media.min.js', false, true); - - return true; - } - - /** - * Render gallery pop-up for media - * - * @param string $id ID of media input name - * @param string $type Type of item want to show gallery - * @param string $sectionId Section ID to show - * @param string $mediaSection Section type to show - * @param string $image URL of featured image - * - * @return void - */ - public static function renderGallery($id, $type, $sectionId, $mediaSection, $image) - { - $imgUrl = JUri::root() . 'components/com_redshop/assets/images/' . $type . '/' . $image; - $imgFile = REDSHOP_FRONT_IMAGES_RELPATH . $type . '/' . $image; - - $file = array(); - - JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/models'); - $media = JModelLegacy::getInstance('Media', 'RedshopModel'); - - $listMedia = $media->all(); - $gallery = array(); - - if (!empty($listMedia)) - { - foreach ($listMedia as $lk => $lm) - { - $tmpFile = REDSHOP_FRONT_IMAGES_RELPATH . $lm->media_section . '/' . $lm->media_name; - - if (file_exists($tmpFile)) - { - $dimension = getimagesize($tmpFile); - - if ($dimension) - { - $dimension = $dimension[0] . ' x ' . $dimension[1]; - } - - $tmpImg = array( - 'id' => $lm->media_id, - 'url' => JUri::root() . 'components/com_redshop/assets/images/' . $lm->media_section . '/' . $lm->media_name, - 'name' => $lm->media_name, - 'size' => self::sizeFilter(filesize($tmpFile)), - 'dimension' => $dimension, - 'media' => $lm->media_section, - 'mime' => substr($lm->media_type, 0, -1), - 'status' => $lm->published ? '' : '-slash' - ); - - if ($image === $lm->media_name) - { - $tmpImg['attached'] = "true"; - } - else - { - $tmpImg['attached'] = "false"; - } - - $gallery[] = $tmpImg; - } - } - } - - if (!empty($image) && file_exists($imgFile)) - { - $file = array( - 'path' => $imgUrl, - 'name' => $image, - 'size' => filesize($imgFile), - 'blob' => 'data: ' . mime_content_type($imgFile) . ';base64,' . base64_encode(file_get_contents($imgFile)) - ); - } - - echo RedshopLayoutHelper::render( - 'media.gallery', - array( - 'id' => $id, - 'type' => $type, - 'sectionId' => $sectionId, - 'mediaSection' => $mediaSection, - 'file' => $file, - 'gallery' => $gallery - ) - ); - } - - /** - * Show file size in KB, MB, GB... - * - * @param integer $bytes Volume of item - * - * @return string - */ - public static function sizeFilter($bytes) - { - $label = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); - - for ($i = 0; $bytes >= 1024 && $i < (count($label) - 1); $i++) - { - $bytes /= 1024; - } - - return round($bytes, 2) . " " . $label[$i]; - } - - /** - * Method for get all media files of redSHOP - * - * @param string $selectedImage Selected file. - * - * @return array List of media files. - * - * @since 2.0.3 - */ - public static function getMediaFiles($selectedImage = '') - { - JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/models'); - $media = JModelLegacy::getInstance('Media', 'RedshopModel'); - $listMedia = $media->all(); - - if (empty($listMedia)) - { - return array(); - } - - $gallery = array(); - - foreach ($listMedia as $lk => $lm) - { - $tmpFile = REDSHOP_FRONT_IMAGES_RELPATH . $lm->media_section . '/' . $lm->media_name; - - if (file_exists($tmpFile)) - { - $dimension = getimagesize($tmpFile); - - if ($dimension) - { - $dimension = $dimension[0] . ' x ' . $dimension[1]; - } - - $tmpImg = array( - 'id' => $lm->media_id, - 'url' => JUri::root() . 'components/com_redshop/assets/images/' . $lm->media_section . '/' . $lm->media_name, - 'name' => $lm->media_name, - 'size' => self::sizeFilter(filesize($tmpFile)), - 'dimension' => $dimension, - 'media' => $lm->media_section, - 'mime' => substr($lm->media_type, 0, -1), - 'status' => $lm->published ? '' : '-slash' - ); - - if ($selectedImage === $lm->media_name) - { - $tmpImg['attached'] = "true"; - } - else - { - $tmpImg['attached'] = "false"; - } - - $gallery[] = $tmpImg; - } - } - - return $gallery; - } - - /** - * Method for get MIME Type of specific file. - * - * @param string $path Path of file. - * - * @return mixed Mime type of file. - * - * @since 2.0.3 - */ - public static function getMimeType($path) - { - if (empty($path) || !JFile::exists($path)) - { - return false; - } - - if (function_exists('mime_content_type')) - { - return mime_content_type($path); - } - - if (function_exists('finfo_file') && function_exists('finfo_open')) - { - return finfo_file(finfo_open(FILEINFO_MIME_TYPE), $path); - } - - return false; - } + /** + * Render Drag n Drop template in site + * + * @param string $id ID of media input name + * @param string $type Type of item want to show gallery + * @param string $sectionId Section ID to show + * @param string $mediaSection Section type to show + * @param string $image URL of featured image + * @param boolean $showMedia Show pop-up of media or not. + * @param boolean $useMediaPath Use new structure of media folder or not. + * @param integer $mediaId Media ID + * + * @return string + */ + public static function render( + $id, + $type, + $sectionId, + $mediaSection, + $image, + $showMedia = true, + $useMediaPath = false, + $mediaId = 0 + ) { + self::requireDependencies(); + + $imgUrl = $useMediaPath ? '/media/com_redshop/images/' . $type . '/' . $sectionId . '/' . $image + : '/components/com_redshop/assets/images/' . $type . '/' . $image; + $imgUrl = JRoute::_($imgUrl); + + $imgFile = $useMediaPath ? REDSHOP_MEDIA_IMAGE_RELPATH . $type . '/' . $sectionId . '/' . $image + : REDSHOP_FRONT_IMAGES_RELPATH . $type . '/' . $image; + + $file = array(); + + if (!empty($image) && file_exists($imgFile)) { + $file = array( + 'path' => $imgUrl, + 'name' => $image, + 'size' => filesize($imgFile) ? filesize($imgFile) : 0, + 'blob' => 'data: ' . self::getMimeType($imgFile) . ';base64,' . base64_encode( + file_get_contents($imgFile) + ) + ); + } + + return RedshopLayoutHelper::render( + 'media.dropzone', + array( + 'id' => $id, + 'type' => $type, + 'sectionId' => $sectionId, + 'mediaSection' => $mediaSection, + 'file' => $file, + 'showMedia' => $showMedia, + 'mediaId' => $mediaId + ) + ); + } + + /** + * Require dependencies from bower.js. + * Checking dependencies are existed or not then require them to header + * + * @return boolean + */ + public static function requireDependencies() + { + JHtml::stylesheet('com_redshop/dropzone.min.css', array(), true); + JHtml::stylesheet('com_redshop/cropper.min.css', array(), true); + JHtml::stylesheet('com_redshop/lightbox2/css/lightbox.min.css', array(), true); + JHtml::stylesheet('com_redshop/redshop.media.min.css', array(), true); + + JHtml::script('com_redshop/dropzone.min.js', false, true); + JHtml::script('com_redshop/cropper.min.js', false, true); + JHtml::script('com_redshop/lightbox2.min.js', false, true); + JHtml::script('com_redshop/redshop.media.min.js', false, true); + + return true; + } + + /** + * Method for get MIME Type of specific file. + * + * @param string $path Path of file. + * + * @return mixed Mime type of file. + * + * @since 2.0.3 + */ + public static function getMimeType($path) + { + if (empty($path) || !JFile::exists($path)) { + return false; + } + + if (function_exists('mime_content_type')) { + return mime_content_type($path); + } + + if (function_exists('finfo_file') && function_exists('finfo_open')) { + return finfo_file(finfo_open(FILEINFO_MIME_TYPE), $path); + } + + return false; + } + + /** + * Render gallery pop-up for media + * + * @param string $id ID of media input name + * @param string $type Type of item want to show gallery + * @param string $sectionId Section ID to show + * @param string $mediaSection Section type to show + * @param string $image URL of featured image + * + * @return void + */ + public static function renderGallery($id, $type, $sectionId, $mediaSection, $image) + { + $imgUrl = JUri::root() . 'components/com_redshop/assets/images/' . $type . '/' . $image; + $imgFile = REDSHOP_FRONT_IMAGES_RELPATH . $type . '/' . $image; + + $file = array(); + + JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/models'); + $media = JModelLegacy::getInstance('Media', 'RedshopModel'); + + $listMedia = $media->all(); + $gallery = array(); + + if (!empty($listMedia)) { + foreach ($listMedia as $lk => $lm) { + $tmpFile = REDSHOP_FRONT_IMAGES_RELPATH . $lm->media_section . '/' . $lm->media_name; + + if (file_exists($tmpFile)) { + $dimension = getimagesize($tmpFile); + + if ($dimension) { + $dimension = $dimension[0] . ' x ' . $dimension[1]; + } + + $tmpImg = array( + 'id' => $lm->media_id, + 'url' => JUri::root( + ) . 'components/com_redshop/assets/images/' . $lm->media_section . '/' . $lm->media_name, + 'name' => $lm->media_name, + 'size' => self::sizeFilter(filesize($tmpFile)), + 'dimension' => $dimension, + 'media' => $lm->media_section, + 'mime' => substr($lm->media_type, 0, -1), + 'status' => $lm->published ? '' : '-slash' + ); + + if ($image === $lm->media_name) { + $tmpImg['attached'] = "true"; + } else { + $tmpImg['attached'] = "false"; + } + + $gallery[] = $tmpImg; + } + } + } + + if (!empty($image) && file_exists($imgFile)) { + $file = array( + 'path' => $imgUrl, + 'name' => $image, + 'size' => filesize($imgFile), + 'blob' => 'data: ' . mime_content_type($imgFile) . ';base64,' . base64_encode( + file_get_contents($imgFile) + ) + ); + } + + echo RedshopLayoutHelper::render( + 'media.gallery', + array( + 'id' => $id, + 'type' => $type, + 'sectionId' => $sectionId, + 'mediaSection' => $mediaSection, + 'file' => $file, + 'gallery' => $gallery + ) + ); + } + + /** + * Show file size in KB, MB, GB... + * + * @param integer $bytes Volume of item + * + * @return string + */ + public static function sizeFilter($bytes) + { + $label = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); + + for ($i = 0; $bytes >= 1024 && $i < (count($label) - 1); $i++) { + $bytes /= 1024; + } + + return round($bytes, 2) . " " . $label[$i]; + } + + /** + * Method for get all media files of redSHOP + * + * @param string $selectedImage Selected file. + * + * @return array List of media files. + * + * @since 2.0.3 + */ + public static function getMediaFiles($selectedImage = '') + { + JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/models'); + $media = JModelLegacy::getInstance('Media', 'RedshopModel'); + $listMedia = $media->all(); + + if (empty($listMedia)) { + return array(); + } + + $gallery = array(); + + foreach ($listMedia as $lk => $lm) { + $tmpFile = REDSHOP_FRONT_IMAGES_RELPATH . $lm->media_section . '/' . $lm->media_name; + + if (file_exists($tmpFile)) { + $dimension = getimagesize($tmpFile); + + if ($dimension) { + $dimension = $dimension[0] . ' x ' . $dimension[1]; + } + + $tmpImg = array( + 'id' => $lm->media_id, + 'url' => JUri::root( + ) . 'components/com_redshop/assets/images/' . $lm->media_section . '/' . $lm->media_name, + 'name' => $lm->media_name, + 'size' => self::sizeFilter(filesize($tmpFile)), + 'dimension' => $dimension, + 'media' => $lm->media_section, + 'mime' => substr($lm->media_type, 0, -1), + 'status' => $lm->published ? '' : '-slash' + ); + + if ($selectedImage === $lm->media_name) { + $tmpImg['attached'] = "true"; + } else { + $tmpImg['attached'] = "false"; + } + + $gallery[] = $tmpImg; + } + } + + return $gallery; + } } diff --git a/libraries/redshop/helper/module.php b/libraries/redshop/helper/module.php index a18dff08185..cc2e8793dc6 100644 --- a/libraries/redshop/helper/module.php +++ b/libraries/redshop/helper/module.php @@ -18,25 +18,24 @@ */ class RedshopHelperModule { - /** - * Load payment languages - * - * @return void - * - * @since 2.0.3 - */ - public static function loadLanguages() - { - // Load modules language file - $paymentsLangList = RedshopHelperUtility::getModules(-1); - $language = JFactory::getLanguage(); + /** + * Load payment languages + * + * @return void + * + * @since 2.0.3 + */ + public static function loadLanguages() + { + // Load modules language file + $paymentsLangList = RedshopHelperUtility::getModules(-1); + $language = JFactory::getLanguage(); - foreach ($paymentsLangList as $paymentLang) - { - $extension = $paymentLang->element; - $language->load($extension, JPATH_SITE, $language->getTag(), true); - $language->load($extension, JPATH_ADMINISTRATOR, $language->getTag(), true); - $language->load($extension, JPATH_ROOT . '/modules/' . $extension, $language->getTag(), true); - } - } + foreach ($paymentsLangList as $paymentLang) { + $extension = $paymentLang->element; + $language->load($extension, JPATH_SITE, $language->getTag(), true); + $language->load($extension, JPATH_ADMINISTRATOR, $language->getTag(), true); + $language->load($extension, JPATH_ROOT . '/modules/' . $extension, $language->getTag(), true); + } + } } diff --git a/libraries/redshop/helper/newsletter.php b/libraries/redshop/helper/newsletter.php index 4644feaab46..8ab92f1567e 100644 --- a/libraries/redshop/helper/newsletter.php +++ b/libraries/redshop/helper/newsletter.php @@ -18,139 +18,125 @@ */ class RedshopHelperNewsletter { - /** - * Method for add an subscriber for Newsletter - * - * @param int $userId ID of user. - * @param array $data Data of subscriber - * @param boolean $sendMail True for send mail. - * @param null $isNew Capability for old method. - * - * @return boolean True on success. False otherwise. - * - * @since 2.0.3 - * - * @throws Exception - */ - public static function subscribe($userId = 0, $data = array(), $sendMail = false, $isNew = null) - { - $newsletter = 1; - $userId = (int) $userId; - $user = JFactory::getUser(); - - if (Redshop::getConfig()->get('DEFAULT_NEWSLETTER') > 0) - { - $newsletter = Redshop::getConfig()->get('DEFAULT_NEWSLETTER'); - } - - if (!$userId) - { - $userId = $user->id; - } - - if (empty($data)) - { - if (!$user->guest) - { - $data['user_id'] = $user->id; - $data['username'] = $user->username; - $data['email'] = $user->email; - $data['name'] = $user->name . " (" . $user->username . ")"; - } - else - { - $redshopUser = RedshopHelperUser::getUserInformation(); - - $data['user_id'] = $redshopUser->user_id; - $data['username'] = $redshopUser->username; - $data['email'] = $redshopUser->user_email; - $data['name'] = $redshopUser->firstname . ' ' . $redshopUser->lastname; - } - } - else - { - $data['user_id'] = $userId; - - if (isset($data['username'])) - { - $data['name'] = $data['username']; - } - - if ($user->id && $user->email == $data['email']) - { - $data['name'] = $user->name . " (" . $user->username . ")"; - } - } - - $data['date'] = time(); - $data['newsletter_id'] = $newsletter; - $data['published'] = 1; - - $needSendMail = Redshop::getConfig()->getBool('NEWSLETTER_CONFIRMATION') && $sendMail ? true : false; - - if ($needSendMail) - { - $data['published'] = 0; - } - - JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/tables'); - - /** @var Tablenewslettersubscr_detail $row */ - $row = JTable::getInstance('newslettersubscr_detail', 'Table'); - - if (!$row->bind($data) || !$row->store()) - { - JFactory::getApplication()->enqueueMessage($row->getError(), 'error'); - } - - if ($needSendMail) - { - Redshop\Mail\Newsletter::sendConfirmationMail($row->subscription_id); - } - - return true; - } - - /** - * Method for un-subscribe email from newsletter - * - * @param string $email Email - * - * @return boolean - * - * @since 2.0.7 - */ - public static function removeSubscribe($email = "") - { - $db = JFactory::getDbo(); - $user = JFactory::getUser(); - - // Skip if user is guest and empty email. - if (empty($email) && $user->guest) - { - return true; - } - - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_newsletter_subscription')); - - if (!$user->guest) - { - $email = $user->email; - $query->where($db->qn('user_id') . ' = ' . $user->id); - } - - $query->where($db->qn('email') . ' = ' . $db->quote($email)); - - if (Redshop::getConfig()->get('DEFAULT_NEWSLETTER') != '') - { - $query->where($db->qn('newsletter_id') . ' = ' . $db->quote(Redshop::getConfig()->get('DEFAULT_NEWSLETTER'))); - } - - $db->setQuery($query)->execute(); - - Redshop\Mail\Newsletter::sendCancellationMail($email); - - return true; - } + /** + * Method for add an subscriber for Newsletter + * + * @param int $userId ID of user. + * @param array $data Data of subscriber + * @param boolean $sendMail True for send mail. + * @param null $isNew Capability for old method. + * + * @return boolean True on success. False otherwise. + * + * @throws Exception + * @since 2.0.3 + * + */ + public static function subscribe($userId = 0, $data = array(), $sendMail = false, $isNew = null) + { + $newsletter = 1; + $userId = (int)$userId; + $user = JFactory::getUser(); + + if (Redshop::getConfig()->get('DEFAULT_NEWSLETTER') > 0) { + $newsletter = Redshop::getConfig()->get('DEFAULT_NEWSLETTER'); + } + + if (!$userId) { + $userId = $user->id; + } + + if (empty($data)) { + if (!$user->guest) { + $data['user_id'] = $user->id; + $data['username'] = $user->username; + $data['email'] = $user->email; + $data['name'] = $user->name . " (" . $user->username . ")"; + } else { + $redshopUser = RedshopHelperUser::getUserInformation(); + + $data['user_id'] = $redshopUser->user_id; + $data['username'] = $redshopUser->username; + $data['email'] = $redshopUser->user_email; + $data['name'] = $redshopUser->firstname . ' ' . $redshopUser->lastname; + } + } else { + $data['user_id'] = $userId; + + if (isset($data['username'])) { + $data['name'] = $data['username']; + } + + if ($user->id && $user->email == $data['email']) { + $data['name'] = $user->name . " (" . $user->username . ")"; + } + } + + $data['date'] = time(); + $data['newsletter_id'] = $newsletter; + $data['published'] = 1; + + $needSendMail = Redshop::getConfig()->getBool('NEWSLETTER_CONFIRMATION') && $sendMail ? true : false; + + if ($needSendMail) { + $data['published'] = 0; + } + + JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/tables'); + + /** @var Tablenewslettersubscr_detail $row */ + $row = JTable::getInstance('newslettersubscr_detail', 'Table'); + + if (!$row->bind($data) || !$row->store()) { + JFactory::getApplication()->enqueueMessage($row->getError(), 'error'); + } + + if ($needSendMail) { + Redshop\Mail\Newsletter::sendConfirmationMail($row->subscription_id); + } + + return true; + } + + /** + * Method for un-subscribe email from newsletter + * + * @param string $email Email + * + * @return boolean + * + * @since 2.0.7 + */ + public static function removeSubscribe($email = "") + { + $db = JFactory::getDbo(); + $user = JFactory::getUser(); + + // Skip if user is guest and empty email. + if (empty($email) && $user->guest) { + return true; + } + + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_newsletter_subscription')); + + if (!$user->guest) { + $email = $user->email; + $query->where($db->qn('user_id') . ' = ' . $user->id); + } + + $query->where($db->qn('email') . ' = ' . $db->quote($email)); + + if (Redshop::getConfig()->get('DEFAULT_NEWSLETTER') != '') { + $query->where( + $db->qn('newsletter_id') . ' = ' . $db->quote(Redshop::getConfig()->get('DEFAULT_NEWSLETTER')) + ); + } + + $db->setQuery($query)->execute(); + + Redshop\Mail\Newsletter::sendCancellationMail($email); + + return true; + } } diff --git a/libraries/redshop/helper/order.php b/libraries/redshop/helper/order.php index fac95485876..ea47a618429 100644 --- a/libraries/redshop/helper/order.php +++ b/libraries/redshop/helper/order.php @@ -21,846 +21,1135 @@ */ class RedshopHelperOrder { - /** - * All the published status code - * - * @var null - */ - protected static $allStatus = null; - - /** - * Order Billing user Info - * - * @var array - */ - protected static $orderBillingInfo = array(); - - /** - * Order Billing user Extra Field Info - * - * @var array - */ - protected static $orderExtraFieldData = array(); - - /** - * Order shipping user Info - * - * @var array - */ - protected static $orderShippingInfo = array(); - - /** - * Order status list - * - * @var null - * - * @since 2.0.3 - */ - public static $orderStatusList = null; - - /** - * Billing addresses - * - * @var array - * - * @since 2.0.3 - */ - protected static $billingAddresses = array(); - - /** - * Shipping addresses - * - * @var array - * - * @since 2.0.3 - */ - protected static $shippingAddresses = array(); - - /** - * Shipping methods - * - * @var array - * - * @since 2.0.3 - */ - protected static $shippingMethods = array(); - - /** - * Order items - * - * @var array - * - * @since 2.0.6 - */ - protected static $orderItems = array(); - - /** - * Order Products Download Log - * - * @var array - * - * @since 2.0.6 - */ - protected static $orderProductsDownloadLog = array(); - - /** - * Order Products Download - * - * @var array - * - * @since 2.0.6 - */ - protected static $orderProductsDownload = array(); - - /** - * Get order information from order id. - * - * @param integer $orderId Order Id - * @param boolean $force Force to get order information from DB instead of cache. - * - * @return object Order Information Object - * - * @deprecated 2.0.6 - */ - public static function getOrderDetail($orderId, $force = false) - { - if (!$orderId) - { - return null; - } - - $order = RedshopEntityOrder::getInstance($orderId); - - if ($force) - { - $order->reset(); - } - - return $order->getItem(); - } - - /** - * Generate Invoice number in chronological order - * - * @param integer $orderId Order Id - * - * @return mixed Invoice number clean and formatted value - */ - public static function generateInvoiceNumber($orderId) - { - $db = JFactory::getDbo(); - - // Use entity instead query directly. Do reset for make sure - $orderEntity = RedshopEntityOrder::getInstance($orderId); - - if (!$orderEntity->isValid()) - { - return false; - } - - $orderInfo = $orderEntity->getItem(); - - // Don't generate invoice number for free orders if disabled from config - if ($orderInfo->order_total <= 0 && !Redshop::getConfig()->getBool('INVOICE_NUMBER_FOR_FREE_ORDER')) - { - return false; - } - - $number = $orderInfo->invoice_number_chrono; - $formattedNumber = $orderInfo->invoice_number; - - // Check if number is not set and order status is confirm or number is set and order status is refund. - if (($number <= 0 && 'C' == $orderInfo->order_status && 'Paid' == $orderInfo->order_payment_status) - || ($number > 0 && ('R' == $orderInfo->order_status || 'X' == $orderInfo->order_status))) - { - $query = $db->getQuery(true) - ->select('MAX(invoice_number_chrono) as max_invoice_number') - ->from($db->qn('#__redshop_orders')); - - // Set the query and load the result. - $db->setQuery($query); - - $maxInvoiceNo = $db->loadResult(); - $firstInvoiceNo = (int) Redshop::getConfig()->get('FIRST_INVOICE_NUMBER'); - - // It will apply only for the first number ideally! - if ($maxInvoiceNo <= $firstInvoiceNo) - { - $maxInvoiceNo += $firstInvoiceNo; - } - - $number = $maxInvoiceNo + 1; - - self::updateInvoiceNumber($number, $orderId); - - $formattedNumber = self::formatInvoiceNumber($number); - } - - $invoiceNo = new stdClass; - $invoiceNo->clean = $number; - $invoiceNo->value = $formattedNumber; - - return $invoiceNo; - } - - /** - * Format the given invoice number - * - * @param integer $invoiceNo Order Invoice Number - * - * @return string Formatted invoice number - */ - public static function formatInvoiceNumber($invoiceNo) - { - if ($invoiceNo == 0) - { - return ''; - } - - if (!Redshop::getConfig()->get('REAL_INVOICE_NUMBER_TEMPLATE')) - { - return $invoiceNo; - } - - return self::parseNumberTemplate( - Redshop::getConfig()->get('REAL_INVOICE_NUMBER_TEMPLATE'), - $invoiceNo - ); - } - - /** - * Parse Invoice or Order Number template. - * - * @param string $template Number Template - * @param float $number Source number to be replaced - * - * @return string Formatted Invoice Number - */ - public static function parseNumberTemplate($template, $number) - { - $format = sprintf("%06d", $number); - $formattedInvoiceNo = str_replace("XXXXXX", $format, $template); - $formattedInvoiceNo = str_replace("xxxxxx", $format, $formattedInvoiceNo); - $formattedInvoiceNo = str_replace("######", $format, $formattedInvoiceNo); - - $format = sprintf("%05d", $number); - $formattedInvoiceNo = str_replace("XXXXX", $format, $formattedInvoiceNo); - $formattedInvoiceNo = str_replace("xxxxx", $format, $formattedInvoiceNo); - $formattedInvoiceNo = str_replace("#####", $format, $formattedInvoiceNo); - - $format = sprintf("%04d", $number); - $formattedInvoiceNo = str_replace("XXXX", $format, $formattedInvoiceNo); - $formattedInvoiceNo = str_replace("xxxx", $format, $formattedInvoiceNo); - $formattedInvoiceNo = str_replace("####", $format, $formattedInvoiceNo); - - $format = sprintf("%03d", $number); - $formattedInvoiceNo = str_replace("XXX", $format, $formattedInvoiceNo); - $formattedInvoiceNo = str_replace("xxx", $format, $formattedInvoiceNo); - $formattedInvoiceNo = str_replace("###", $format, $formattedInvoiceNo); - - $format = sprintf("%02d", $number); - $formattedInvoiceNo = str_replace("XX", $format, $formattedInvoiceNo); - $formattedInvoiceNo = str_replace("xx", $format, $formattedInvoiceNo); - $formattedInvoiceNo = str_replace("##", $format, $formattedInvoiceNo); - - return $formattedInvoiceNo; - } - - /** - * Update invoice number in database - * - * @param integer $number Order Invoice Number - * @param integer $orderId Order Id - * - * @return void - * - * @deprecated 2.0.6 - */ - public static function updateInvoiceNumber($number, $orderId) - { - $order = RedshopEntityOrder::getInstance($orderId); - - if ($order->isValid()) - { - $order->set('invoice_number_chrono', (int) $number) - ->set('invoice_number', self::formatInvoiceNumber($number)) - ->save(); - } - } - - /** - * Get all the order status code information list - * - * @return array Order Status info - */ - public static function getOrderStatusList() - { - if (!empty(self::$allStatus)) - { - return self::$allStatus; - } - - // Initialiase variables. - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select( - array( - $db->qn('order_status_code', 'value'), - $db->qn('order_status_name', 'text') - ) - ) - ->from($db->qn('#__redshop_order_status')) - ->where($db->qn('published') . ' = ' . $db->q('1')); - - // Set the query and load the result. - $db->setQuery($query); - self::$allStatus = $db->loadObjectList(); - - // Check for a database error. - if (/** @scrutinizer ignore-deprecated */ $db->getErrorNum()) - { - /** @scrutinizer ignore-deprecated */ JError::raiseWarning(500, /** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); - - return null; - } - - return self::$allStatus; - } - - /** - * Get Order Payment Information - * - * @param integer $orderId Order Id - * - * @return object Payment Information for orders - * - * @deprecated 2.0.6 - */ - public static function getPaymentInfo($orderId) - { - $payment = RedshopEntityOrder::getInstance($orderId)->getPayment(); - - if (null === $payment) - { - return null; - } - - return $payment->getItem(); - } - - /** - * Prepare Order Query - * - * @param integer $orderId Order Information Id - * - * @return object Query Object - * - * @deprecated 2.0.6 - */ - public static function getOrderUserQuery($orderId) - { - $db = JFactory::getDbo(); - - return $db->getQuery(true) - ->select('*, `user_email` as email') - ->from($db->qn('#__redshop_order_users_info')) - ->where($db->qn('order_id') . ' = ' . (int) $orderId); - } - - /** - * Get Order billing user information - * - * @param integer $orderId Order Id - * @param boolean $force Force get information - * - * @return object Order Billing information object - * - * @deprecated 2.0.6 - */ - public static function getOrderBillingUserInfo($orderId, $force = false) - { - if (!$orderId) - { - return null; - } - - /** @var RedshopEntityOrder_User $userBilling */ - $userBilling = RedshopEntityOrder::getInstance($orderId)->getBilling(); - - if ($force) - { - $userBilling->reset()->loadExtraFields(); - } - - return $userBilling->getItem(); - } - - /** - * Get Order shipping user information - * - * @param integer $orderId Order Id - * @param boolean $force Order Id - * - * @return object Order Shipping information object - * - * @deprecated 2.0.6 - */ - public static function getOrderShippingUserInfo($orderId, $force = false) - { - if (!$orderId) - { - return null; - } - - /** @var RedshopEntityOrder_User $userBilling */ - $userBilling = RedshopEntityOrder::getInstance($orderId)->getShipping(); - - if ($force) - { - $userBilling->reset()->loadExtraFields(); - } - - return $userBilling->getItem(); - } - - /** - * Get order Billing extra field information in array - * - * @param integer $orderUserInfoId Order Info id - * @param string $section Section to get information - * @param boolean $force Force to get information - * - * @return array Extra Field name as a key of an array - * - * @deprecated 2.0.6 - */ - public static function getOrderExtraFieldsData($orderUserInfoId, $section = 'billing', $force = false) - { - $key = $section . '.' . $orderUserInfoId; - - if (array_key_exists($key, self::$orderExtraFieldData) && !$force) - { - return self::$orderExtraFieldData[$key]; - } - - $privateSection = RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS; - $companySection = RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS; - - if ('shipping' == $section) - { - $privateSection = RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS; - $companySection = RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS; - } - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('f.name') . ',' . $db->qn('fd.data_txt')) - ->from($db->qn('#__redshop_fields_data', 'fd')) - ->where( - '(' - . $db->qn('fd.section') . ' = ' . $privateSection - . ' OR ' - . $db->qn('fd.section') . ' = ' . $companySection - . ')' - ) - ->where($db->qn('fd.itemid') . ' = ' . (int) $orderUserInfoId); - - $query->leftJoin( - $db->qn('#__redshop_fields', 'f') - . ' ON ' . $db->qn('f.id') . '=' . $db->qn('fd.fieldid') - ); - - // Set the query and load the result. - $fields = $db->setQuery($query)->loadObjectList(); - - // Check for a database error. - if (/** @scrutinizer ignore-deprecated */ $db->getErrorNum()) - { - /** @scrutinizer ignore-deprecated */ JError::raiseWarning(500, /** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); - - return null; - } - - $fieldsData = array(); - - if (!empty($fields)) - { - foreach ($fields as $field) - { - $fieldsData[$field->name] = $field->data_txt; - } - } - - self::$orderExtraFieldData[$key] = $fieldsData; - - return $fieldsData; - } - - /** - * Get all the items from order - * - * @param integer $orderId Valid Integer order Id - * - * @return array Order Items - * - * @deprecated 2.0.6 Use RedshopEntityOrder::getOrderItems instead - */ - public static function getItems($orderId) - { - if (!$orderId) - { - return null; - } - - return RedshopEntityOrder::getInstance($orderId)->getOrderItems()->toObjects(); - } - - /** - * Get all gift card items from order items array - * - * @param integer $orderId A valid integer Order Id - * - * @return array Contains gift card item. - */ - public static function giftCardItems($orderId) - { - $orderItems = RedshopEntityOrder::getInstance($orderId)->getOrderItems(); - - if (!$orderItems->count()) - { - return array(); - } - - return array_filter( - $orderItems->toObjects(), function ($item) { - return $item->is_giftcard; - } - ); - } - - /** - * Truncate tables orders and relatives - * - * @return void - * - * @since 2.0.3 - */ - public static function resetOrderId() - { - $db = JFactory::getDbo(); - - $db->truncateTable('#__redshop_orders'); - $db->truncateTable('#__redshop_order_item'); - $db->truncateTable('#__redshop_order_users_info'); - $db->truncateTable('#__redshop_order_status_log'); - $db->truncateTable('#__redshop_order_attribute_item'); - $db->truncateTable('#__redshop_order_payment'); - $db->truncateTable('#__redshop_product_download'); - $db->truncateTable('#__redshop_product_download_log'); - } - - /** - * Get order status title - * - * @param string $orderStatusCode Order status code to get title - * - * @return string - * - * @since 2.0.3 - */ - public static function getOrderStatusTitle($orderStatusCode) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('order_status_name')) - ->from($db->qn('#__redshop_order_status')) - ->where($db->qn('order_status_code') . ' = ' . $db->quote($orderStatusCode)); - $db->setQuery($query); - - return $db->loadResult(); - } - - /** - * Update order status - * - * @param integer $orderId Order ID to update - * @param string $newStatus New status - * - * @return void - * - * @since 2.0.3 - */ - public static function updateOrderStatus($orderId, $newStatus) - { - $order = RedshopEntityOrder::getInstance($orderId); - - if ($order->get('order_status', '') == $newStatus) - { - return; - } - - if ($order->isValid()) - { - $order->set('order_status', $newStatus) - ->set('mdate', (int) time()) - ->save(); - } - - self::generateInvoiceNumber($orderId); - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select( - $db->qn( - array( - 'e.element', 'op.order_transfee', 'op.order_payment_trans_id', 'op.order_payment_amount', 'op.authorize_status' - ) - ) - ) - ->from($db->qn('#__extensions', 'e')) - ->leftJoin($db->qn('#__redshop_order_payment', 'op') . ' ON ' . $db->qn('op.payment_method_class') . ' = ' . $db->qn('e.element')) - ->where($db->qn('op.order_id') . ' = ' . (int) $orderId) - ->where($db->qn('e.folder') . ' = ' . $db->quote('redshop_payment')); - $result = $db->setQuery($query, 0, 1)->loadObject(); - - $authorizeStatus = $result->authorize_status; - - $paymentMethod = self::getPaymentMethodInfo($result->element); - $paymentMethod = $paymentMethod[0]; - - // Getting the order details - $orderDetail = RedshopEntityOrder::getInstance($orderId)->getItem(); - $paymentParams = new Registry($paymentMethod->params); - $orderStatusCapture = $paymentParams->get('capture_status', ''); - $orderStatusCode = $orderStatusCapture; - - if ($orderStatusCapture == $newStatus - && ($authorizeStatus == "Authorized" || $authorizeStatus == "")) - { - $values["order_number"] = $orderDetail->order_number; - $values["order_id"] = $orderId; - $values["order_transactionid"] = $result->order_payment_trans_id; - $values["order_amount"] = $orderDetail->order_total + $result->order_transfee; - $values['shippinginfo'] = self::getOrderShippingUserInfo($orderId); - $values['billinginfo'] = self::getOrderBillingUserInfo($orderId); - $values["order_userid"] = $values['billinginfo']->user_id; - - JPluginHelper::importPlugin('redshop_payment'); - $data = RedshopHelperUtility::getDispatcher()->trigger('onCapture_Payment' . $result->element, array($result->element, $values)); - $results = $data[0]; - - if (!empty($data)) - { - $message = $results->message; - - $orderStatusLog = JTable::getInstance('order_status_log', 'Table'); - $orderStatusLog->order_id = $orderId; - $orderStatusLog->order_status = $orderStatusCode; - $orderStatusLog->date_changed = time(); - $orderStatusLog->customer_note = $message; - $orderStatusLog->store(); - } - } - - if (($newStatus == "X" || $newStatus == "R") - && $paymentParams->get('refund', 0) == 1) - { - $values["order_number"] = $orderDetail->order_number; - $values["order_id"] = $orderId; - $values["order_transactionid"] = $result->order_payment_trans_id; - $values["order_amount"] = $orderDetail->order_total + $result->order_transfee; - $values["order_userid"] = $values['billinginfo']->user_id; - - JPluginHelper::importPlugin('redshop_payment'); - - // Get status and refund if capture/cancel if authorize (for quickpay only) - $data = RedshopHelperUtility::getDispatcher()->trigger('onStatus_Payment' . $result->element, array($result->element, $values)); - $results = $data[0]; - - if (!empty($data)) - { - $message = $results->message; - $orderStatusLog = JTable::getInstance('order_status_log', 'Table'); - $orderStatusLog->order_id = $orderId; - $orderStatusLog->order_status = $newStatus; - $orderStatusLog->date_changed = time(); - $orderStatusLog->customer_note = $message; - $orderStatusLog->store(); - } - } - } - - /** - * Generate parcel - * - * @param integer $orderId Order ID to generate - * - * @return string 'success' or error message - * - * @since 2.0.3 - */ - public static function generateParcel($orderId) - { - $db = JFactory::getDbo(); - $orderDetail = self::getOrderDetails($orderId); - $orderProducts = self::getOrderItemDetail($orderId); - $billingInfo = self::getOrderBillingUserInfo($orderId); - $shippingInfo = self::getOrderShippingUserInfo($orderId); - $shippingRateDecryptDetail = Redshop\Shipping\Rate::decrypt($orderDetail->ship_method_id); - - // Get Shipping Delivery Type - $shippingDeliveryType = 1; - - if (isset($shippingRateDecryptDetail[8]) === true) - { - $shippingDeliveryType = (int) $shippingRateDecryptDetail[8]; - } - - $query = $db->getQuery(true) - ->select($db->qn('country_2_code')) - ->from($db->qn('#__redshop_country')) - ->where($db->qn('country_3_code') . ' = ' . $db->quote(Redshop::getConfig()->get('SHOP_COUNTRY'))); - $db->setQuery($query); - $billingInfo->country_code = $db->loadResult(); - - $query = $db->getQuery(true) - ->select($db->qn('country_2_code')) - ->from($db->qn('#__redshop_country')) - ->where($db->qn('country_3_code') . ' = ' . $db->quote($shippingInfo->country_code)); - $db->setQuery($query); - $shippingInfo->country_code = $db->loadResult(); - - // For product content - $totalWeight = 0; - $contentProducts = array(); - $qty = 0; - - for ($c = 0, $cn = count($orderProducts); $c < $cn; $c++) - { - $qty += $orderProducts [$c]->product_quantity; - $contentProducts[] = $orderProducts[$c]->order_item_name; - - // Product Weight - $query = $db->getQuery(true) - ->select($db->qn('weight')) - ->from($db->qn('#__redshop_product')) - ->where($db->qn('product_id') . ' = ' . (int) $orderProducts [$c]->product_id); - $db->setQuery($query); - $weight = $db->loadResult(); - - // Accessory Weight - $orderAccItemData = self::getOrderItemAccessoryDetail($orderProducts[$c]->order_item_id); - $accWeight = 0; - - if (count($orderAccItemData) > 0) - { - for ($a = 0, $an = count($orderAccItemData); $a < $an; $a++) - { - $accessoryQuantity = $orderAccItemData[$a]->product_quantity; - $query = $db->getQuery(true) - ->select($db->qn('weight')) - ->from($db->qn('#__redshop_product')) - ->where($db->qn('product_id') . ' = ' . (int) $orderAccItemData[$a]->product_id); - $db->setQuery($query); - $accessoryWeight = $db->loadResult(); - $accWeight += ($accessoryWeight * $accessoryQuantity); - } - } - - // Total weight - $totalWeight += (($weight * $orderProducts [$c]->product_quantity) + $accWeight); - } - - $unitRatio = \Redshop\Helper\Utility::getUnitConversation('kg', Redshop::getConfig()->get('DEFAULT_WEIGHT_UNIT')); - - if ($unitRatio != 0) - { - // Converting weight in pounds - $totalWeight = $totalWeight * $unitRatio; - } - - if (Redshop::getConfig()->get('SHOW_PRODUCT_DETAIL')) - { - $contentProducts = array_unique($contentProducts); - $contentProducts = implode(",", $contentProducts); - $contentProducts = mb_convert_encoding($contentProducts, "ISO-8859-1", "UTF-8"); - $contentProductsRemark = substr(mb_convert_encoding($contentProducts, "ISO-8859-1", "UTF-8"), 0, 29); - } - else - { - $contentProducts = " "; - $contentProductsRemark = " "; - } - - $filter = JFilterInput::getInstance(); - - // Filter name to remove special characters - // We are using $billingInfo instead $shippingInfo because $shippingInfo stored information of service point not buyer - $firstName = $filter->clean( - mb_convert_encoding($billingInfo->firstname, "ISO-8859-1", "UTF-8"), - 'username' - ); - $lastName = $filter->clean( - mb_convert_encoding($billingInfo->lastname, "ISO-8859-1", "UTF-8"), - 'username' - ); - $fullName = $firstName . " " . $lastName; - - $address = mb_convert_encoding($billingInfo->address, "ISO-8859-1", "UTF-8"); - $city = mb_convert_encoding($billingInfo->city, "ISO-8859-1", "UTF-8"); - - if ($billingInfo->is_company) - { - $companyName = mb_convert_encoding($shippingInfo->company_name, "ISO-8859-1", "UTF-8"); - $fProductCode = "PDKEP"; - $addon = ""; - $finalAddress1 = $companyName; - $finalAddress2 = $address; - } - else - { - // Post Danmark MyPack Home - $fProductCode = "PDK17"; - $addon = ""; - $finalAddress1 = $address; - $finalAddress2 = ""; - } - - // When shipping delivery set to post office don't need to send DLV or POD addon. - if ($shippingDeliveryType == 0) - { - // Post Danmark MyPack Collect - $fProductCode = "P19DK"; - $addon = ""; - } - - if (Redshop::getConfig()->get('WEBPACK_ENABLE_EMAIL_TRACK')) - { - $addon .= ''; - } - - if (Redshop::getConfig()->get('WEBPACK_ENABLE_SMS')) - { - $addon .= ''; - } - - // No pickup agent by default - $agentEle = ''; - - // Only when we have store to send parcel - i.e Pickup Location - if ('' != trim($orderDetail->shop_id)) - { - // Get shop location stored using postdanmark plugin or other similar plugin. - $shopLocation = explode('|', $orderDetail->shop_id); - - // Sending shop location id as an agent code. - $agentEle = '' . $shopLocation[0] . ''; - - // PUPOPT is stands for "Optional Service Point". - $addon .= ''; - } - - $xmlnew = ' + /** + * Order status list + * + * @var null + * + * @since 2.0.3 + */ + public static $orderStatusList = null; + /** + * All the published status code + * + * @var null + */ + protected static $allStatus = null; + /** + * Order Billing user Info + * + * @var array + */ + protected static $orderBillingInfo = array(); + /** + * Order Billing user Extra Field Info + * + * @var array + */ + protected static $orderExtraFieldData = array(); + /** + * Order shipping user Info + * + * @var array + */ + protected static $orderShippingInfo = array(); + /** + * Billing addresses + * + * @var array + * + * @since 2.0.3 + */ + protected static $billingAddresses = array(); + + /** + * Shipping addresses + * + * @var array + * + * @since 2.0.3 + */ + protected static $shippingAddresses = array(); + + /** + * Shipping methods + * + * @var array + * + * @since 2.0.3 + */ + protected static $shippingMethods = array(); + + /** + * Order items + * + * @var array + * + * @since 2.0.6 + */ + protected static $orderItems = array(); + + /** + * Order Products Download Log + * + * @var array + * + * @since 2.0.6 + */ + protected static $orderProductsDownloadLog = array(); + + /** + * Order Products Download + * + * @var array + * + * @since 2.0.6 + */ + protected static $orderProductsDownload = array(); + + /** + * Prepare Order Query + * + * @param integer $orderId Order Information Id + * + * @return object Query Object + * + * @deprecated 2.0.6 + */ + public static function getOrderUserQuery($orderId) + { + $db = JFactory::getDbo(); + + return $db->getQuery(true) + ->select('*, `user_email` as email') + ->from($db->qn('#__redshop_order_users_info')) + ->where($db->qn('order_id') . ' = ' . (int)$orderId); + } + + /** + * Get order Billing extra field information in array + * + * @param integer $orderUserInfoId Order Info id + * @param string $section Section to get information + * @param boolean $force Force to get information + * + * @return array Extra Field name as a key of an array + * + * @deprecated 2.0.6 + */ + public static function getOrderExtraFieldsData($orderUserInfoId, $section = 'billing', $force = false) + { + $key = $section . '.' . $orderUserInfoId; + + if (array_key_exists($key, self::$orderExtraFieldData) && !$force) { + return self::$orderExtraFieldData[$key]; + } + + $privateSection = RedshopHelperExtrafields::SECTION_PRIVATE_BILLING_ADDRESS; + $companySection = RedshopHelperExtrafields::SECTION_COMPANY_BILLING_ADDRESS; + + if ('shipping' == $section) { + $privateSection = RedshopHelperExtrafields::SECTION_PRIVATE_SHIPPING_ADDRESS; + $companySection = RedshopHelperExtrafields::SECTION_COMPANY_SHIPPING_ADDRESS; + } + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('f.name') . ',' . $db->qn('fd.data_txt')) + ->from($db->qn('#__redshop_fields_data', 'fd')) + ->where( + '(' + . $db->qn('fd.section') . ' = ' . $privateSection + . ' OR ' + . $db->qn('fd.section') . ' = ' . $companySection + . ')' + ) + ->where($db->qn('fd.itemid') . ' = ' . (int)$orderUserInfoId); + + $query->leftJoin( + $db->qn('#__redshop_fields', 'f') + . ' ON ' . $db->qn('f.id') . '=' . $db->qn('fd.fieldid') + ); + + // Set the query and load the result. + $fields = $db->setQuery($query)->loadObjectList(); + + // Check for a database error. + if (/** @scrutinizer ignore-deprecated */ $db->getErrorNum()) { + /** @scrutinizer ignore-deprecated */ + JError::raiseWarning(500, /** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); + + return null; + } + + $fieldsData = array(); + + if (!empty($fields)) { + foreach ($fields as $field) { + $fieldsData[$field->name] = $field->data_txt; + } + } + + self::$orderExtraFieldData[$key] = $fieldsData; + + return $fieldsData; + } + + /** + * Get all the items from order + * + * @param integer $orderId Valid Integer order Id + * + * @return array Order Items + * + * @deprecated 2.0.6 Use RedshopEntityOrder::getOrderItems instead + */ + public static function getItems($orderId) + { + if (!$orderId) { + return null; + } + + return RedshopEntityOrder::getInstance($orderId)->getOrderItems()->toObjects(); + } + + /** + * Get all gift card items from order items array + * + * @param integer $orderId A valid integer Order Id + * + * @return array Contains gift card item. + */ + public static function giftCardItems($orderId) + { + $orderItems = RedshopEntityOrder::getInstance($orderId)->getOrderItems(); + + if (!$orderItems->count()) { + return array(); + } + + return array_filter( + $orderItems->toObjects(), + function ($item) { + return $item->is_giftcard; + } + ); + } + + /** + * Truncate tables orders and relatives + * + * @return void + * + * @since 2.0.3 + */ + public static function resetOrderId() + { + $db = JFactory::getDbo(); + + $db->truncateTable('#__redshop_orders'); + $db->truncateTable('#__redshop_order_item'); + $db->truncateTable('#__redshop_order_users_info'); + $db->truncateTable('#__redshop_order_status_log'); + $db->truncateTable('#__redshop_order_attribute_item'); + $db->truncateTable('#__redshop_order_payment'); + $db->truncateTable('#__redshop_product_download'); + $db->truncateTable('#__redshop_product_download_log'); + } + + /** + * Get order status title + * + * @param string $orderStatusCode Order status code to get title + * + * @return string + * + * @since 2.0.3 + */ + public static function getOrderStatusTitle($orderStatusCode) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('order_status_name')) + ->from($db->qn('#__redshop_order_status')) + ->where($db->qn('order_status_code') . ' = ' . $db->quote($orderStatusCode)); + $db->setQuery($query); + + return $db->loadResult(); + } + + /** + * Change Order status + * + * @param object $data Data to change + * + * @return void + * + * @since 2.0.3 + */ + public static function changeOrderStatus($data) + { + $db = JFactory::getDbo(); + $orderId = $data->order_id; + + $data->order_status_code = trim($data->order_status_code); + $data->order_payment_status_code = trim($data->order_payment_status_code); + $checkUpdateOrders = self::checkUpdateOrders($data); + + if ($checkUpdateOrders == 0 && $data->order_status_code != "" && $data->order_payment_status_code != "") { + // Order status valid and change the status + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_orders')) + ->set($db->qn('order_status') . ' = ' . $db->quote($data->order_status_code)) + ->set($db->qn('order_payment_status') . ' = ' . $db->quote($data->order_payment_status_code)) + ->where($db->qn('order_id') . ' = ' . (int)$orderId); + $db->setQuery($query); + $db->execute(); + + // Generate Invoice Number + if ("C" == $data->order_status_code + && "Paid" == $data->order_payment_status_code) { + self::sendDownload($orderId); + self::generateInvoiceNumber($orderId); + } + + if (!isset($data->transfee)) { + $data->transfee = null; + } + + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_order_payment')) + ->set($db->qn('order_transfee') . ' = ' . $db->quote($data->transfee)) + ->set($db->qn('order_payment_trans_id') . ' = ' . $db->quote($data->transaction_id)) + ->where($db->qn('order_id') . ' = ' . (int)$orderId); + $db->setQuery($query); + $db->execute(); + + $query = $db->getQuery(true) + ->insert($db->qn('#__redshop_order_status_log')) + ->columns( + $db->qn(array('order_status', 'order_payment_status', 'date_changed', 'order_id', 'customer_note')) + ) + ->values( + implode( + ',', + array( + $db->quote($data->order_status_code), + $db->quote($data->order_payment_status_code), + (int)time(), + (int)$orderId, + $db->quote($data->log) + ) + ) + ); + $db->setQuery($query); + $db->execute(); + + // Send status change email only if config is set to Before order mail or Order is not confirmed. + if (!Redshop::getConfig()->get('ORDER_MAIL_AFTER') + || (Redshop::getConfig()->get('ORDER_MAIL_AFTER') && $data->order_status_code != "C")) { + self::changeOrderStatusMail($orderId, $data->order_status_code); + } + + if ($data->order_payment_status_code == "Paid") { + JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_redshop/models'); + $checkoutModelCheckout = JModelLegacy::getInstance('Checkout', 'RedshopModel'); + $checkoutModelCheckout->sendGiftCard($orderId); + + // Send the Order mail + + // Send Order Mail After Payment + if (Redshop::getConfig()->get('ORDER_MAIL_AFTER') && $data->order_status_code == "C") { + Redshop\Mail\Order::sendMail($orderId); + } // Send Invoice mail only if order mail is set to before payment. + elseif (Redshop::getConfig()->get('INVOICE_MAIL_ENABLE')) { + Redshop\Mail\Invoice::sendMail($orderId); + } + } + + // Trigger function on Order Status change + JPluginHelper::importPlugin('redshop_order'); + RedshopHelperUtility::getDispatcher()->trigger( + 'onAfterOrderStatusUpdate', + array( + self::getOrderDetails($orderId), + $data->order_status_code + ) + ); + + JPluginHelper::importPlugin('redshop_shipping'); + RedshopHelperUtility::getDispatcher()->trigger( + 'sendOrderShipping' + , + array( + $orderId, + $data->order_payment_status_code, + $data->order_status_code + ) + ); + + // For Webpack Postdk Label Generation + self::createWebPackLabel($orderId, $data->order_status_code, $data->order_payment_status_code); + self::createBookInvoice($orderId, $data->order_status_code); + } + } + + /** + * Check update Orders + * + * @param object $data Data to check + * + * @return integer + * + * @since 2.0.3 + */ + public static function checkUpdateOrders($data) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_orders')) + ->where($db->qn('order_status') . ' = ' . $db->quote($data->order_status_code)) + ->where($db->qn('order_payment_status') . ' = ' . $db->quote($data->order_payment_status_code)) + ->where($db->qn('order_id') . ' = ' . (int)$data->order_id); + $db->setQuery($query); + + if (count($db->loadObjectList()) == 0) { + return 0; + } + + return 1; + } + + /** + * Send download by email + * + * @param integer $orderId Order ID + * + * @return boolean + * + * @since 2.0.3 + */ + public static function sendDownload($orderId = 0) + { + $app = JFactory::getApplication(); + + // Getting the order status changed template from mail center end + $mailFrom = $app->get('mailfrom'); + $fromName = $app->get('fromname'); + + $mailData = ""; + $mailSubject = ""; + $mailBcc = null; + $mailInfo = Redshop\Mail\Helper::getTemplate(0, "downloadable_product_mail"); + + if (count($mailInfo) > 0) { + $mailData = $mailInfo[0]->mail_body; + $mailSubject = $mailInfo[0]->mail_subject; + + if (trim($mailInfo[0]->mail_bcc) != "") { + $mailBcc = explode(",", $mailInfo[0]->mail_bcc); + } + } + + // Get Downloadable Product + $rows = self::getDownloadProduct($orderId); + + // There is no downloadable product + if ($rows === null || count($rows) == 0) { + return false; + } + + // Getting the order details + $orderDetail = self::getOrderDetails($orderId); + $userDetail = self::getOrderBillingUserInfo($orderId); + + $userFullname = $userDetail->firstname . " " . $userDetail->lastname; + $userEmail = $userDetail->email; + + $mailData = str_replace("{fullname}", $userFullname, $mailData); + $mailData = str_replace("{order_id}", $orderDetail->order_id, $mailData); + $mailData = str_replace("{order_number}", $orderDetail->order_number, $mailData); + $mailData = str_replace( + "{order_date}", + RedshopHelperDatetime::convertDateFormat($orderDetail->cdate), + $mailData + ); + + $productStart = ""; + $productEnd = ""; + $productMiddle = ""; + $pMiddle = ""; + $mailFirst = explode("{product_serial_loop_start}", $mailData); + + if (count($mailFirst) > 1) { + $productStart = $mailFirst[0]; + $mailSec = explode("{product_serial_loop_end}", $mailFirst[1]); + + if (count($mailSec) > 1) { + $productMiddle = $mailSec[0]; + $productEnd = $mailSec[1]; + } + } + + foreach ($rows as $row) { + $dataMessage = $productMiddle; + $downloadFilename = basename($row->file_name); + + $mailToken = "" . $downloadFilename . ""; + + $dataMessage = str_replace("{product_serial_number}", $row->product_serial_number, $dataMessage); + $dataMessage = str_replace("{product_name}", $row->product_name, $dataMessage); + $dataMessage = str_replace("{token}", $mailToken, $dataMessage); + + $pMiddle .= $dataMessage; + } + + $mailData = $productStart . $pMiddle . $productEnd; + $mailBody = $mailData; + Redshop\Mail\Helper::imgInMail($mailBody); + $mailSubject = str_replace("{order_number}", $orderDetail->order_number, $mailSubject); + + if ($mailBody && $userEmail != "") { + if (!JFactory::getMailer()->sendMail( + $mailFrom, + $fromName, + $userEmail, + $mailSubject, + $mailBody, + 1, + null, + $mailBcc + )) { + $app->enqueueMessage(JText::_('COM_REDSHOP_ERROR_DOWNLOAD_MAIL_FAIL'), 'error'); + } + } + + return true; + } + + /** + * Get download product + * + * @param integer $orderId Order ID + * + * @return array + * + * @since 2.0.3 + */ + public static function getDownloadProduct($orderId) + { + if (!array_key_exists($orderId, self::$orderProductsDownload)) { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('pd.*') + ->select($db->qn('product_name')) + ->from($db->qn('#__redshop_product_download', 'pd')) + ->leftJoin( + $db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('pd.product_id') . ' = ' . $db->qn( + 'p.product_id' + ) + ) + ->where($db->qn('order_id') . ' = ' . (int)$orderId); + + + self::$orderProductsDownload[$orderId] = $db->setQuery($query)->loadObjectList(); + } + + return self::$orderProductsDownload[$orderId]; + } + + /** + * Generate Invoice number in chronological order + * + * @param integer $orderId Order Id + * + * @return mixed Invoice number clean and formatted value + */ + public static function generateInvoiceNumber($orderId) + { + $db = JFactory::getDbo(); + + // Use entity instead query directly. Do reset for make sure + $orderEntity = RedshopEntityOrder::getInstance($orderId); + + if (!$orderEntity->isValid()) { + return false; + } + + $orderInfo = $orderEntity->getItem(); + + // Don't generate invoice number for free orders if disabled from config + if ($orderInfo->order_total <= 0 && !Redshop::getConfig()->getBool('INVOICE_NUMBER_FOR_FREE_ORDER')) { + return false; + } + + $number = $orderInfo->invoice_number_chrono; + $formattedNumber = $orderInfo->invoice_number; + + // Check if number is not set and order status is confirm or number is set and order status is refund. + if (($number <= 0 && 'C' == $orderInfo->order_status && 'Paid' == $orderInfo->order_payment_status) + || ($number > 0 && ('R' == $orderInfo->order_status || 'X' == $orderInfo->order_status))) { + $query = $db->getQuery(true) + ->select('MAX(invoice_number_chrono) as max_invoice_number') + ->from($db->qn('#__redshop_orders')); + + // Set the query and load the result. + $db->setQuery($query); + + $maxInvoiceNo = $db->loadResult(); + $firstInvoiceNo = (int)Redshop::getConfig()->get('FIRST_INVOICE_NUMBER'); + + // It will apply only for the first number ideally! + if ($maxInvoiceNo <= $firstInvoiceNo) { + $maxInvoiceNo += $firstInvoiceNo; + } + + $number = $maxInvoiceNo + 1; + + self::updateInvoiceNumber($number, $orderId); + + $formattedNumber = self::formatInvoiceNumber($number); + } + + $invoiceNo = new stdClass; + $invoiceNo->clean = $number; + $invoiceNo->value = $formattedNumber; + + return $invoiceNo; + } + + /** + * Update invoice number in database + * + * @param integer $number Order Invoice Number + * @param integer $orderId Order Id + * + * @return void + * + * @deprecated 2.0.6 + */ + public static function updateInvoiceNumber($number, $orderId) + { + $order = RedshopEntityOrder::getInstance($orderId); + + if ($order->isValid()) { + $order->set('invoice_number_chrono', (int)$number) + ->set('invoice_number', self::formatInvoiceNumber($number)) + ->save(); + } + } + + /** + * Format the given invoice number + * + * @param integer $invoiceNo Order Invoice Number + * + * @return string Formatted invoice number + */ + public static function formatInvoiceNumber($invoiceNo) + { + if ($invoiceNo == 0) { + return ''; + } + + if (!Redshop::getConfig()->get('REAL_INVOICE_NUMBER_TEMPLATE')) { + return $invoiceNo; + } + + return self::parseNumberTemplate( + Redshop::getConfig()->get('REAL_INVOICE_NUMBER_TEMPLATE'), + $invoiceNo + ); + } + + /** + * Parse Invoice or Order Number template. + * + * @param string $template Number Template + * @param float $number Source number to be replaced + * + * @return string Formatted Invoice Number + */ + public static function parseNumberTemplate($template, $number) + { + $format = sprintf("%06d", $number); + $formattedInvoiceNo = str_replace("XXXXXX", $format, $template); + $formattedInvoiceNo = str_replace("xxxxxx", $format, $formattedInvoiceNo); + $formattedInvoiceNo = str_replace("######", $format, $formattedInvoiceNo); + + $format = sprintf("%05d", $number); + $formattedInvoiceNo = str_replace("XXXXX", $format, $formattedInvoiceNo); + $formattedInvoiceNo = str_replace("xxxxx", $format, $formattedInvoiceNo); + $formattedInvoiceNo = str_replace("#####", $format, $formattedInvoiceNo); + + $format = sprintf("%04d", $number); + $formattedInvoiceNo = str_replace("XXXX", $format, $formattedInvoiceNo); + $formattedInvoiceNo = str_replace("xxxx", $format, $formattedInvoiceNo); + $formattedInvoiceNo = str_replace("####", $format, $formattedInvoiceNo); + + $format = sprintf("%03d", $number); + $formattedInvoiceNo = str_replace("XXX", $format, $formattedInvoiceNo); + $formattedInvoiceNo = str_replace("xxx", $format, $formattedInvoiceNo); + $formattedInvoiceNo = str_replace("###", $format, $formattedInvoiceNo); + + $format = sprintf("%02d", $number); + $formattedInvoiceNo = str_replace("XX", $format, $formattedInvoiceNo); + $formattedInvoiceNo = str_replace("xx", $format, $formattedInvoiceNo); + $formattedInvoiceNo = str_replace("##", $format, $formattedInvoiceNo); + + return $formattedInvoiceNo; + } + + /** + * Change order status mail + * + * @param integer $orderId Order ID + * @param string $newStatus New status + * @param string $orderComment Order Comment + * + * @return void + * + * @since 2.0.3 + */ + public static function changeOrderStatusMail($orderId, $newStatus, $orderComment = '') + { + $app = JFactory::getApplication(); + + // Changes to parse all tags same as order mail end + $userDetail = self::getOrderBillingUserInfo($orderId); + + $mailFrom = $app->get('mailfrom'); + $fromName = $app->get('fromname'); + $mailBcc = null; + $mailSection = "order_status"; + $mailTemplate = Redshop\Mail\Helper::getTemplate( + 0, + '', + '`mail_section` LIKE "' . $mailSection . '" AND `mail_order_status` LIKE "' . $newStatus . '"' + ); + + if (count($mailTemplate) > 0) { + $mailData = $mailTemplate[0]->mail_body; + $mailSubject = $mailTemplate[0]->mail_subject; + + $fieldArray = RedshopHelperExtrafields::getSectionFieldList(RedshopHelperExtrafields::SECTION_ORDER, 0); + + if (count($fieldArray) > 0) { + for ($i = 0, $in = count($fieldArray); $i < $in; $i++) { + $fieldValueArray = RedshopHelperExtrafields::getSectionFieldDataList( + $fieldArray[$i]->id, + RedshopHelperExtrafields::SECTION_ORDER, + $orderId, + $userDetail->user_email + ); + + if ($fieldValueArray->data_txt != "") { + $mailData = str_replace( + '{' . $fieldArray[$i]->name . '}', + $fieldValueArray->data_txt, + $mailData + ); + $mailData = str_replace( + '{' . $fieldArray[$i]->name . '_lbl}', + $fieldArray[$i]->title, + $mailData + ); + } else { + $mailData = str_replace('{' . $fieldArray[$i]->name . '}', "", $mailData); + $mailData = str_replace('{' . $fieldArray[$i]->name . '_lbl}', "", $mailData); + } + } + } + + if (trim($mailTemplate[0]->mail_bcc) != "") { + $mailBcc = explode(",", $mailTemplate[0]->mail_bcc); + } + + // Changes to parse all tags same as order mail start + $orderDetail = self::getOrderDetails($orderId); + $mailData = str_replace( + "{order_mail_intro_text_title}", + JText::_('COM_REDSHOP_ORDER_MAIL_INTRO_TEXT_TITLE'), + $mailData + ); + $mailData = str_replace( + "{order_mail_intro_text}", + JText::_('COM_REDSHOP_ORDER_MAIL_INTRO_TEXT'), + $mailData + ); + + $mailData = Template::replaceTemplate($orderDetail, $mailData, true); + + $arrDiscount = explode('@', $orderDetail->discount_type); + $discountType = ''; + + for ($d = 0, $dn = count($arrDiscount); $d < $dn; $d++) { + if ($arrDiscount [$d]) { + $arrDiscountType = explode(':', $arrDiscount [$d]); + + if ($arrDiscountType [0] == 'c') { + $discountType .= JText::_('COM_REDSHOP_COUPON_CODE') . ' : ' . $arrDiscountType [1] . '
    '; + } + + if ($arrDiscountType [0] == 'v') { + $discountType .= JText::_('COM_REDSHOP_VOUCHER_CODE') . ' : ' . $arrDiscountType [1] . '
    '; + } + } + } + + if (!$discountType) { + $discountType = JText::_('COM_REDSHOP_NO_DISCOUNT_AVAILABLE'); + } + + $search [] = "{discount_type}"; + $replace [] = $discountType; + + // Getting the order status changed template from mail center end + $mailData = RedshopHelperBillingTag::replaceBillingAddress($mailData, $userDetail); + + // Get ShippingAddress From order Users info + $shippingAddresses = self::getOrderShippingUserInfo($orderId); + + if (count($shippingAddresses) <= 0) { + $shippingAddresses = $userDetail; + } + + $mailData = Redshop\Shipping\Tag::replaceShippingAddress($mailData, $shippingAddresses); + + $search[] = "{shopname}"; + $replace[] = Redshop::getConfig()->get('SHOP_NAME'); + + $search[] = "{fullname}"; + $replace[] = $userDetail->firstname . " " . $userDetail->lastname; + + $search[] = "{email}"; + $replace[] = $userDetail->user_email; + + $search[] = "{customer_id}"; + $replace[] = $userDetail->users_info_id; + + $search[] = "{order_id}"; + $replace[] = $orderId; + + $search[] = "{order_number}"; + $replace[] = $orderDetail->order_number; + + $search[] = "{order_date}"; + $replace[] = RedshopHelperDatetime::convertDateFormat($orderDetail->cdate); + + $search[] = "{customer_note_lbl}"; + $replace[] = JText::_('COM_REDSHOP_COMMENT'); + + $search[] = "{customer_note}"; + $replace[] = $orderComment; + + $search[] = "{order_detail_link_lbl}"; + $replace[] = JText::_('COM_REDSHOP_ORDER_DETAIL_LBL'); + + $orderDetailurl = JUri::root( + ) . 'index.php?option=com_redshop&view=order_detail&oid=' . $orderId . '&encr=' . $orderDetail->encr_key; + $search[] = "{order_detail_link}"; + $replace[] = "" . JText::_( + "COM_REDSHOP_ORDER_DETAIL_LINK_LBL" + ) . ""; + + // Todo: Move to the shipping plugin to return track no and track url + $details = Redshop\Shipping\Rate::decrypt($orderDetail->ship_method_id); + + if (count($details) <= 1) { + $details = explode("|", $orderDetail->ship_method_id); + } + + if ($details[0] == 'plgredshop_shippingdefault_shipping_gls') { + $arrLocationDetails = explode('|', $orderDetail->shop_id); + $orderDetail->track_no = $arrLocationDetails[0]; + } + + if (strpos($mailData, "{if track_no}") !== false && strpos($mailData, "{track_no end if}") !== false) { + if (empty($orderDetail->track_no)) { + $template_pd_sdata = explode('{if track_no}', $mailData); + $template_pd_edata = explode('{track_no end if}', $template_pd_sdata [1]); + $mailData = $template_pd_sdata[0] . $template_pd_edata[1]; + } + + $mailData = str_replace("{if track_no}", '', $mailData); + $mailData = str_replace("{track_no end if}", '', $mailData); + } + + $search[] = "{order_track_no}"; + $replace[] = trim($orderDetail->track_no); + + $orderTrackURL = 'http://www.pacsoftonline.com/ext.po.dk.dk.track?key=' . Redshop::getConfig()->get( + 'POSTDK_CUSTOMER_NO' + ) . '&order=' . $orderId; + + JPluginHelper::importPlugin('redshop_shipping'); + RedshopHelperUtility::getDispatcher()->trigger( + 'onReplaceTrackingUrl', + array( + $orderId, + &$orderTrackURL + ) + ); + + $search[] = "{order_track_url}"; + $replace[] = "" . JText::_("COM_REDSHOP_TRACK_LINK_LBL") . ""; + + $mailBody = str_replace($search, $replace, $mailData); + Redshop\Mail\Helper::imgInMail($mailBody); + $mailSubject = str_replace($search, $replace, $mailSubject); + + if ('' != $userDetail->thirdparty_email && $mailBody) { + Redshop\Mail\Helper::sendEmail( + $mailFrom, + $fromName, + $userDetail->thirdparty_email, + $mailSubject, + $mailBody, + true, + null, + null, + null, + $mailSection, + func_get_args() + ); + } + + if ('' != $userDetail->user_email && $mailBody) { + Redshop\Mail\Helper::sendEmail( + $mailFrom, + $fromName, + $userDetail->user_email, + $mailSubject, + $mailBody, + true, + null, + $mailBcc, + null, + $mailSection, + func_get_args() + ); + } + } + } + + /** + * Create PacSoft Label from Order Status Change functions + * + * @param integer $orderId Order Information ID + * @param string $orderStatus Order Status Code + * @param string $paymentStatus Order Payment Status Code + * + * @return void + * + * @since 2.0.3 + */ + public static function createWebPackLabel($orderId, $orderStatus, $paymentStatus) + { + // If PacSoft is not enable then return + if (!Redshop::getConfig()->get('POSTDK_INTEGRATION')) { + return; + } + + // If auto generation is disable then return + if (!Redshop::getConfig()->get('AUTO_GENERATE_LABEL')) { + return; + } + + // Only Execute this function for selected status match + if ($orderStatus == Redshop::getConfig()->get('GENERATE_LABEL_ON_STATUS') && $paymentStatus == "Paid") { + $orderDetails = self::getOrderDetails($orderId); + $details = Redshop\Shipping\Rate::decrypt($orderDetails->ship_method_id); + + $shippingParams = new Registry( + JPluginHelper::getPlugin( + 'redshop_shipping', + str_replace( + 'plgredshop_shipping', + '', + strtolower($details[0]) + ) + )->params + ); + + // Checking 'plgredshop_shippingdefault_shipping' to support backward compatibility + $allowPacsoftLabel = ($details[0] === 'plgredshop_shippingdefault_shipping' || (boolean)$shippingParams->get( + 'allowPacsoftLabel' + )); + + if ($allowPacsoftLabel && !$orderDetails->order_label_create) { + $generateLabel = self::generateParcel($orderId); + + if ($generateLabel != "success") { + JFactory::getApplication()->enqueueMessage($generateLabel, 'error'); + } + } + } + } + + /** + * Generate parcel + * + * @param integer $orderId Order ID to generate + * + * @return string 'success' or error message + * + * @since 2.0.3 + */ + public static function generateParcel($orderId) + { + $db = JFactory::getDbo(); + $orderDetail = self::getOrderDetails($orderId); + $orderProducts = self::getOrderItemDetail($orderId); + $billingInfo = self::getOrderBillingUserInfo($orderId); + $shippingInfo = self::getOrderShippingUserInfo($orderId); + $shippingRateDecryptDetail = Redshop\Shipping\Rate::decrypt($orderDetail->ship_method_id); + + // Get Shipping Delivery Type + $shippingDeliveryType = 1; + + if (isset($shippingRateDecryptDetail[8]) === true) { + $shippingDeliveryType = (int)$shippingRateDecryptDetail[8]; + } + + $query = $db->getQuery(true) + ->select($db->qn('country_2_code')) + ->from($db->qn('#__redshop_country')) + ->where($db->qn('country_3_code') . ' = ' . $db->quote(Redshop::getConfig()->get('SHOP_COUNTRY'))); + $db->setQuery($query); + $billingInfo->country_code = $db->loadResult(); + + $query = $db->getQuery(true) + ->select($db->qn('country_2_code')) + ->from($db->qn('#__redshop_country')) + ->where($db->qn('country_3_code') . ' = ' . $db->quote($shippingInfo->country_code)); + $db->setQuery($query); + $shippingInfo->country_code = $db->loadResult(); + + // For product content + $totalWeight = 0; + $contentProducts = array(); + $qty = 0; + + for ($c = 0, $cn = count($orderProducts); $c < $cn; $c++) { + $qty += $orderProducts [$c]->product_quantity; + $contentProducts[] = $orderProducts[$c]->order_item_name; + + // Product Weight + $query = $db->getQuery(true) + ->select($db->qn('weight')) + ->from($db->qn('#__redshop_product')) + ->where($db->qn('product_id') . ' = ' . (int)$orderProducts [$c]->product_id); + $db->setQuery($query); + $weight = $db->loadResult(); + + // Accessory Weight + $orderAccItemData = self::getOrderItemAccessoryDetail($orderProducts[$c]->order_item_id); + $accWeight = 0; + + if (count($orderAccItemData) > 0) { + for ($a = 0, $an = count($orderAccItemData); $a < $an; $a++) { + $accessoryQuantity = $orderAccItemData[$a]->product_quantity; + $query = $db->getQuery(true) + ->select($db->qn('weight')) + ->from($db->qn('#__redshop_product')) + ->where($db->qn('product_id') . ' = ' . (int)$orderAccItemData[$a]->product_id); + $db->setQuery($query); + $accessoryWeight = $db->loadResult(); + $accWeight += ($accessoryWeight * $accessoryQuantity); + } + } + + // Total weight + $totalWeight += (($weight * $orderProducts [$c]->product_quantity) + $accWeight); + } + + $unitRatio = \Redshop\Helper\Utility::getUnitConversation( + 'kg', + Redshop::getConfig()->get('DEFAULT_WEIGHT_UNIT') + ); + + if ($unitRatio != 0) { + // Converting weight in pounds + $totalWeight = $totalWeight * $unitRatio; + } + + if (Redshop::getConfig()->get('SHOW_PRODUCT_DETAIL')) { + $contentProducts = array_unique($contentProducts); + $contentProducts = implode(",", $contentProducts); + $contentProducts = mb_convert_encoding($contentProducts, "ISO-8859-1", "UTF-8"); + $contentProductsRemark = substr(mb_convert_encoding($contentProducts, "ISO-8859-1", "UTF-8"), 0, 29); + } else { + $contentProducts = " "; + $contentProductsRemark = " "; + } + + $filter = JFilterInput::getInstance(); + + // Filter name to remove special characters + // We are using $billingInfo instead $shippingInfo because $shippingInfo stored information of service point not buyer + $firstName = $filter->clean( + mb_convert_encoding($billingInfo->firstname, "ISO-8859-1", "UTF-8"), + 'username' + ); + $lastName = $filter->clean( + mb_convert_encoding($billingInfo->lastname, "ISO-8859-1", "UTF-8"), + 'username' + ); + $fullName = $firstName . " " . $lastName; + + $address = mb_convert_encoding($billingInfo->address, "ISO-8859-1", "UTF-8"); + $city = mb_convert_encoding($billingInfo->city, "ISO-8859-1", "UTF-8"); + + if ($billingInfo->is_company) { + $companyName = mb_convert_encoding($shippingInfo->company_name, "ISO-8859-1", "UTF-8"); + $fProductCode = "PDKEP"; + $addon = ""; + $finalAddress1 = $companyName; + $finalAddress2 = $address; + } else { + // Post Danmark MyPack Home + $fProductCode = "PDK17"; + $addon = ""; + $finalAddress1 = $address; + $finalAddress2 = ""; + } + + // When shipping delivery set to post office don't need to send DLV or POD addon. + if ($shippingDeliveryType == 0) { + // Post Danmark MyPack Collect + $fProductCode = "P19DK"; + $addon = ""; + } + + if (Redshop::getConfig()->get('WEBPACK_ENABLE_EMAIL_TRACK')) { + $addon .= ''; + } + + if (Redshop::getConfig()->get('WEBPACK_ENABLE_SMS')) { + $addon .= ''; + } + + // No pickup agent by default + $agentEle = ''; + + // Only when we have store to send parcel - i.e Pickup Location + if ('' != trim($orderDetail->shop_id)) { + // Get shop location stored using postdanmark plugin or other similar plugin. + $shopLocation = explode('|', $orderDetail->shop_id); + + // Sending shop location id as an agent code. + $agentEle = '' . $shopLocation[0] . ''; + + // PUPOPT is stands for "Optional Service Point". + $addon .= ''; + } + + $xmlnew = ' "' . date('Y-m-d H:i') . '" @@ -895,1819 +1184,1514 @@ public static function generateParcel($orderId) '; - $postURL = "https://www.pacsoftonline.com/ufoweb/order?session=po_DK" - . "&user=" . Redshop::getConfig()->get('POSTDK_CUSTOMER_NO') - . "&pin=" . Redshop::getConfig()->get('POSTDK_CUSTOMER_PASSWORD') - . "&developerid=000000075" - . "&type=xml"; - - try - { - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $postURL); - curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_VERBOSE, true); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlnew); - $response = curl_exec($ch); - curl_close($ch); - - $xmlResponse = JFactory::getXML($response, false); - - if (empty($xmlResponse) || !empty($error)) - { - return JText::_('LIB_REDSHOP_PACSOFT_ERROR_NO_RESPONSE'); - } - - $xmlResponse = $xmlResponse->val; - - if ('201' === (string) $xmlResponse[1] && 'Created' === (string) $xmlResponse[2]) - { - // Update current order success entry. - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_orders')) - ->set($db->qn('order_label_create') . ' = 1') - ->where($db->qn('order_id') . ' = ' . (int) $orderId); - - // Set the query and execute the update. - $db->setQuery($query); - $db->execute(); - - return "success"; - } - else - { - return (string) $xmlResponse[1] . "-" . (string) $xmlResponse[2] . "-" . (string) $xmlResponse[0]; - } - } - catch (Exception $e) - { - return $e->getMessage(); - } - } - - /** - * Change Order status - * - * @param object $data Data to change - * - * @return void - * - * @since 2.0.3 - */ - public static function changeOrderStatus($data) - { - $db = JFactory::getDbo(); - $orderId = $data->order_id; - - $data->order_status_code = trim($data->order_status_code); - $data->order_payment_status_code = trim($data->order_payment_status_code); - $checkUpdateOrders = self::checkUpdateOrders($data); - - if ($checkUpdateOrders == 0 && $data->order_status_code != "" && $data->order_payment_status_code != "") - { - // Order status valid and change the status - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_orders')) - ->set($db->qn('order_status') . ' = ' . $db->quote($data->order_status_code)) - ->set($db->qn('order_payment_status') . ' = ' . $db->quote($data->order_payment_status_code)) - ->where($db->qn('order_id') . ' = ' . (int) $orderId); - $db->setQuery($query); - $db->execute(); - - // Generate Invoice Number - if ("C" == $data->order_status_code - && "Paid" == $data->order_payment_status_code) - { - self::sendDownload($orderId); - self::generateInvoiceNumber($orderId); - } - - if (!isset($data->transfee)) - { - $data->transfee = null; - } - - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_order_payment')) - ->set($db->qn('order_transfee') . ' = ' . $db->quote($data->transfee)) - ->set($db->qn('order_payment_trans_id') . ' = ' . $db->quote($data->transaction_id)) - ->where($db->qn('order_id') . ' = ' . (int) $orderId); - $db->setQuery($query); - $db->execute(); - - $query = $db->getQuery(true) - ->insert($db->qn('#__redshop_order_status_log')) - ->columns($db->qn(array('order_status', 'order_payment_status', 'date_changed', 'order_id', 'customer_note'))) - ->values( - implode(',', - array( - $db->quote($data->order_status_code), - $db->quote($data->order_payment_status_code), - (int) time(), - (int) $orderId, - $db->quote($data->log) - ) - ) - ); - $db->setQuery($query); - $db->execute(); - - // Send status change email only if config is set to Before order mail or Order is not confirmed. - if (!Redshop::getConfig()->get('ORDER_MAIL_AFTER') - || (Redshop::getConfig()->get('ORDER_MAIL_AFTER') && $data->order_status_code != "C")) - { - self::changeOrderStatusMail($orderId, $data->order_status_code); - } - - if ($data->order_payment_status_code == "Paid") - { - JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_redshop/models'); - $checkoutModelCheckout = JModelLegacy::getInstance('Checkout', 'RedshopModel'); - $checkoutModelCheckout->sendGiftCard($orderId); - - // Send the Order mail - - // Send Order Mail After Payment - if (Redshop::getConfig()->get('ORDER_MAIL_AFTER') && $data->order_status_code == "C") - { - Redshop\Mail\Order::sendMail($orderId); - } - - // Send Invoice mail only if order mail is set to before payment. - elseif (Redshop::getConfig()->get('INVOICE_MAIL_ENABLE')) - { - Redshop\Mail\Invoice::sendMail($orderId); - } - } - - // Trigger function on Order Status change - JPluginHelper::importPlugin('redshop_order'); - RedshopHelperUtility::getDispatcher()->trigger( - 'onAfterOrderStatusUpdate', - array( - self::getOrderDetails($orderId), - $data->order_status_code - ) - ); - - JPluginHelper::importPlugin('redshop_shipping'); - RedshopHelperUtility::getDispatcher()->trigger( - 'sendOrderShipping' - , array( - $orderId, - $data->order_payment_status_code, - $data->order_status_code - ) - ); - - // For Webpack Postdk Label Generation - self::createWebPackLabel($orderId, $data->order_status_code, $data->order_payment_status_code); - self::createBookInvoice($orderId, $data->order_status_code); - } - } - - /** - * Update Order Payment Status - * - * @param integer $orderId Order ID - * @param string $newStatus New status - * - * @return void - * - * @since 2.0.3 - * - * @deprecated 2.0.6 - */ - public static function updateOrderPaymentStatus($orderId, $newStatus) - { - $order = RedshopEntityOrder::getInstance($orderId); - - if ($order->isValid()) - { - $order->set('order_payment_status', $newStatus) - ->set('mdate', time()) - ->save(); - } - } - - /** - * Update order comment - * - * @param integer $orderId Order ID - * @param string $comment New Comment - * - * @return void - * - * @since 2.0.3 - * - * @deprecated 2.0.6 - */ - public static function updateOrderComment($orderId, $comment = '') - { - $order = RedshopEntityOrder::getInstance($orderId); - - if ($order->isValid()) - { - $order->set('customer_note', $comment) - ->save(); - } - } - - /** - * Update Order Requisition Number - * - * @param integer $orderId Order ID - * @param string $requisitionNumber Number required - * - * @return void - * - * @since 2.0.3 - */ - public static function updateOrderRequisitionNumber($orderId, $requisitionNumber = '') - { - $order = RedshopEntityOrder::getInstance($orderId); - - if (!$order->isValid()) - { - return; - } - - $order->set('requisition_number', $requisitionNumber); - - if ($order->save()) - { - // Economic Integration start for invoice generate and book current invoice - if (Redshop::getConfig()->get('ECONOMIC_INTEGRATION') == 1) - { - RedshopEconomic::renewInvoiceInEconomic($order->getItem()); - } - } - } - - /** - * Update Order Item Status - * - * @param integer $orderId Order id - * @param integer $productId Product id - * @param string $newStatus New status - * @param string $comment Comment - * @param integer $orderItemId Order item id - * - * @return void - * - * @since 2.0.3 - */ - public static function updateOrderItemStatus($orderId = 0, $productId = 0, $newStatus = '', $comment = '', $orderItemId = 0) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_order_item')) - ->set($db->qn('order_status') . ' = ' . $db->q($newStatus)) - ->where($db->qn('order_id') . ' = ' . (int) $orderId); - - if ($productId != 0) - { - $query->set($db->qn('customer_note') . ' = ' . $db->q($comment)) - ->where($db->qn('product_id') . ' = ' . (int) $productId); - } - - if ($orderItemId != 0) - { - $query->where($db->qn('order_item_id') . ' = ' . (int) $orderItemId); - } - - $db->setQuery($query); - - if (!$db->execute()) - { - JFactory::getApplication()->enqueueMessage(/** @scrutinizer ignore-deprecated */ $db->getErrorMsg(), 'error'); - } - } - - /** - * Get status list - * - * @param string $name Name of status list - * @param string $selected Selet status name - * @param string $attributes Attributes of html - * - * @return string HTML of status list - * - * @since 2.0.3 - */ - public static function getStatusList($name = 'statuslist', $selected = '', $attributes = ' class="inputbox" size="1" ') - { - if (!self::$orderStatusList) - { - self::$orderStatusList = self::getOrderStatusList(); - } - - $types[] = JHtml::_('select.option', '0', '- ' . JText::_('COM_REDSHOP_SELECT_STATUS_LBL') . ' -'); - $types = array_merge($types, self::$orderStatusList); - $totStatus = explode(",", $selected); - - return JHtml::_('select.genericlist', $types, $name, $attributes, 'value', 'text', $totStatus); - } - - /** - * Get filter by list - * - * @param string $name Name of filter by list - * @param string $selected Select filter list - * @param string $attributes Attributes of HTML - * - * @return string HTML of filter list - * - * @since 2.0.3 - */ - public static function getFilterByList($name = 'filterbylist', $selected = 'all', $attributes = ' class="inputbox" size="1" ') - { - $filterByList = array( - 'orderid' => JText::_('COM_REDSHOP_ORDERID'), - 'ordernumber' => JText::_('COM_REDSHOP_ORDERNUMBER'), - 'fullname' => JText::_('COM_REDSHOP_FULLNAME'), - 'useremail' => JText::_('COM_REDSHOP_USEREMAIL') - ); - - $types[] = JHtml::_('select.option', '', 'All'); - $types = array_merge($types, $filterByList); - $totStatus = explode(",", $selected); - - return JHtml::_('select.genericlist', $types, $name, $attributes, 'value', 'text', $totStatus); - } - - /** - * Get payment status list - * - * @param string $name Name of payment status list - * @param string $selected Select option - * @param string $attributes Attributes of HTML - * - * @return string HTML of payment status list - * - * @since 2.0.3 - */ - public static function getPaymentStatusList($name = 'paymentstatuslist', $selected = '', $attributes = ' class="inputbox" size="1" ') - { - $types[] = JHtml::_('select.option', '', JText::_('COM_REDSHOP_SELECT_PAYMENT_STATUS')); - $types[] = JHtml::_('select.option', 'Paid', JText::_('COM_REDSHOP_PAYMENT_STA_PAID')); - $types[] = JHtml::_('select.option', 'Unpaid', JText::_('COM_REDSHOP_PAYMENT_STA_UNPAID')); - $types[] = JHtml::_('select.option', 'Partial Paid', JText::_('COM_REDSHOP_PAYMENT_STA_PARTIAL_PAID')); - - return JHtml::_('select.genericlist', $types, $name, $attributes, 'value', 'text', $selected); - } - - /** - * Update order status and trigger emails based on status. - * - * @return void - * - * @since 2.0.3 - * - * @throws Exception - */ - public static function updateStatus() - { - JPluginHelper::importPlugin('redshop_shipping'); - $app = JFactory::getApplication(); - - $newStatus = $app->input->getCmd('status'); - $paymentStatus = $app->input->getString('order_paymentstatus'); - $return = $app->input->getCmd('return'); - - $customerNote = $app->input->get('customer_note', array(), 'array'); - $customerNote = stripslashes($customerNote[0]); - - $oid = $app->input->get('order_id', array(), 'method', 'array'); - $orderId = (int) $oid[0]; - - $isProduct = $app->input->getInt('isproduct', 0); - $productId = $app->input->getInt('product_id', 0); - $orderItemId = $app->input->getInt('order_item_id', 0); - - // Get order detail before processing - $prevOrderStatus = RedshopEntityOrder::getInstance($orderId)->getItem()->order_status; - - if (isset($paymentStatus)) - { - self::updateOrderPaymentStatus($orderId, $paymentStatus); - } - - JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/tables'); - $orderLog = JTable::getInstance('order_status_log', 'Table'); - - if (!$isProduct) - { - $data['order_id'] = $orderId; - $data['order_status'] = $newStatus; - $data['order_payment_status'] = $paymentStatus; - $data['date_changed'] = time(); - $data['customer_note'] = $customerNote; - - if (!$orderLog->bind($data)) - { - JFactory::getApplication()->enqueueMessage(/** @scrutinizer ignore-deprecated */ $orderLog->getError(), 'error'); - - return; - } - - if (!$orderLog->store()) - { - throw new Exception(/** @scrutinizer ignore-deprecated */ $orderLog->getError()); - } - - self::updateOrderComment($orderId, $customerNote); - - $requisitionNumber = $app->input->getString('requisition_number', ''); - - if ('' != $requisitionNumber) - { - self::updateOrderRequisitionNumber($orderId, $requisitionNumber); - } - - // Changing the status of the order - self::updateOrderStatus($orderId, $newStatus); - - // Trigger function on Order Status change - JPluginHelper::importPlugin('redshop_order'); - - RedshopHelperUtility::getDispatcher()->trigger( - 'onAfterOrderStatusUpdate', - array( - RedshopEntityOrder::getInstance($orderId)->getItem(), - $newStatus - ) - ); - - if ($paymentStatus == "Paid") - { - JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_redshop/models'); - $checkoutModel = JModelLegacy::getInstance('Checkout', 'RedshopModel'); - $checkoutModel->sendGiftCard($orderId); - - // Send the Order mail - if (Redshop::getConfig()->get('ORDER_MAIL_AFTER') && $newStatus == 'C') - { - if ( - JFactory::getApplication()->isClient('site') || - ( - JFactory::getApplication()->isClient('administrator') && - $app->input->getCmd('order_sendordermail') === 'true' - ) - ) - { - // Only send email if order_sendordermail checked or frontend - Redshop\Mail\Order::sendMail($orderId); - } - } - elseif (Redshop::getConfig()->get('INVOICE_MAIL_ENABLE')) - { - Redshop\Mail\Invoice::sendMail($orderId); - } - } - - self::createWebPackLabel($orderId, $newStatus, $paymentStatus); - } - - self::updateOrderItemStatus($orderId, $productId, $newStatus, $customerNote, $orderItemId); - RedshopHelperClickatell::clickatellSMS($orderId); - - switch ($newStatus) - { - // Cancel & return - case 'X': - case 'R': - - $orderProducts = self::getOrderItemDetail($orderId); - - for ($i = 0, $in = count($orderProducts); $i < $in; $i++) - { - $prodid = $orderProducts[$i]->product_id; - $prodqty = $orderProducts[$i]->stockroom_quantity; - - // Do not process update stock if this order already "returned" before - if ($prevOrderStatus != 'RT') - { - // When the order is set to "cancelled",product will return to stock - RedshopHelperStockroom::manageStockAmount($prodid, $prodqty, $orderProducts[$i]->stockroom_id); - } - - RedshopHelperProduct::makeAttributeOrder($orderProducts[$i]->order_item_id, 0, $prodid, 1); - } - - break; - - // Returned - case "RT": - - if ($isProduct) - { - // Changing the status of the order item to Returned - self::updateOrderItemStatus($orderId, $productId, "RT", $customerNote, $orderItemId); - - // Changing the status of the order to Partially Returned - self::updateOrderStatus($orderId, "PRT"); - } - - break; - - case "RC": - - if ($isProduct) - { - // Changing the status of the order item to Reclamation - self::updateOrderItemStatus($orderId, $productId, "RC", $customerNote, $orderItemId); - - // Changing the status of the order to Partially Reclamation - self::updateOrderStatus($orderId, "PRC"); - } - - break; - - // Shipped - case "S": - - if ($isProduct) - { - // Changing the status of the order item to Reclamation - self::updateOrderItemStatus($orderId, $productId, "S", $customerNote, $orderItemId); - - // Changing the status of the order to Partially Reclamation - self::updateOrderStatus($orderId, "PS"); - } - - break; - - // Completed - case "C": - - // SensDownload Products - if ($paymentStatus == "Paid") - { - self::sendDownload($orderId); - } - - break; - } - - RedshopHelperUtility::getDispatcher()->trigger( - 'sendOrderShipping', - array( - $orderId, - $paymentStatus, - $newStatus - ) - ); - - if ($app->input->getCmd('order_sendordermail') == 'true' && JFactory::getApplication()->isClient('administrator')) - { - self::changeOrderStatusMail($orderId, $newStatus, $customerNote); - } - - self::createBookInvoice($orderId, $newStatus); - - $msg = JText::_('COM_REDSHOP_ORDER_STATUS_SUCCESSFULLY_SAVED_FOR_ORDER_ID') . " " . $orderId; - - $isArchive = ($app->input->getInt('isarchive')) ? '&isarchive=1' : ''; - - if ($return == 'order') - { - $app->redirect('index.php?option=com_redshop&view=' . $return . '' . $isArchive . '', $msg); - } - else - { - $tmpl = $app->input->getCmd('tmpl'); - - if ('' != $tmpl) - { - $app->redirect('index.php?option=com_redshop&view=' . $return . '&cid[]=' . $orderId . '&tmpl=' . $tmpl . '' . $isArchive . '', $msg); - } - else - { - $app->redirect('index.php?option=com_redshop&view=' . $return . '&cid[]=' . $orderId . '' . $isArchive . '', $msg); - } - } - } - - /** - * Get order details - * - * @param integer $orderId Order ID - * - * @return object - * - * @since 2.0.3 - * - * @deprecated 2.0.6 - */ - public static function getOrderDetails($orderId) - { - return self::getOrderDetail($orderId); - } - - /** - * Get list order details - * - * @param integer $orderId Order ID - * - * @return object - * - * @since 2.0.3 - * @deprecated Use RedshopEntityOrder::getInstance($orderId)->getItem(); - */ - public static function getMultiOrderDetails($orderId) - { - return RedshopEntityOrder::getInstance($orderId)->getItem(); - } - - /** - * Get User Order Details - * - * @param integer $userId User ID - * - * @return mixed - * - * @since 2.0.3 - */ - public static function getUserOrderDetails($userId = 0) - { - $db = JFactory::getDbo(); - $user = JFactory::getUser(); - - if ($userId == 0) - { - $userId = $user->id; - } - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_orders')) - ->where($db->qn('user_id') . ' = ' . (int) $userId) - ->order($db->qn('order_id')); - $db->setQuery($query); - - return $db->loadObjectlist(); - } - - /** - * Get list item of an specific order. - * - * @param mixed $orderId Order ID - * @param integer $productId Product ID - * @param integer $orderItemId Order Item ID - * - * @return mixed - * - * @since 2.0.3 - */ - public static function getOrderItemDetail($orderId = 0, $productId = 0, $orderItemId = 0, $force = false) - { - // Make sure at least one options has been pass. - if (empty($orderId) && !$productId && !$orderItemId) - { - return false; - } - - $key = $orderId . '_' . $productId . '_' . $orderItemId; - - if (!array_key_exists($key, self::$orderItems) || $force) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_order_item')); - - if (!empty($orderId)) - { - $orderId = explode(',', $orderId); - $orderId = ArrayHelper::toInteger($orderId); - $orderId = implode(',', $orderId); - - $query->where($db->qn('order_id') . ' IN (' . $orderId . ')'); - } - - if ($productId != 0) - { - $query->where($db->qn('product_id') . ' = ' . (int) $productId); - } - - if ($orderItemId != 0) - { - $query->where($db->qn('order_item_id') . ' = ' . (int) $orderItemId); - } - - self::$orderItems[$key] = $db->setQuery($query)->loadObjectList(); - } - - return self::$orderItems[$key]; - } - - /** - * Get Order Partial Payment - * - * @param integer $orderId Order ID - * - * @return array - * - * @since 2.0.3 - */ - public static function getOrderPartialPayment($orderId) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->qn('order_payment_amount')) - ->from($db->qn('#__redshop_order_payment')) - ->where($db->qn('order_id') . ' = ' . (int) $orderId); - $db->setQuery($query); - $list = $db->loadObjectlist(); - - $spiltPaymentAmount = 0; - - for ($i = 0, $in = count($list); $i < $in; $i++) - { - if ($list[$i]->order_payment_amount > 0) - { - $spiltPaymentAmount = $list[$i]->order_payment_amount; - } - } - - return $spiltPaymentAmount; - } - - /** - * Get Shipping Method Info - * - * @param string $shippingClass Shipping class - * - * @return array - * - * @since 2.0.3 - */ - public static function getShippingMethodInfo($shippingClass = '') - { - $key = (!empty($shippingClass)) ? $shippingClass : '0'; - - if (!array_key_exists($key, static::$shippingMethods)) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__extensions')) - ->where($db->qn('enabled') . ' = ' . $db->quote('1')) - ->where('LOWER(' . $db->qn('folder') . ') = ' . $db->quote('redshop_shipping')) - ->order($db->qn('ordering') . ' ASC'); - - if (!empty($shippingClass)) - { - $query->where($db->qn('element') . ' = ' . $db->quote($shippingClass)); - } - - static::$shippingMethods = $db->setQuery($query)->loadObjectList(); - } - - return static::$shippingMethods; - } - - /** - * Get payment method info - * - * @param string $paymentMethodClass Payment method class - * @param boolean $includeDiscover Include all plugins even not discover install yet - * - * @return array - * - * @since 2.0.3 - */ - public static function getPaymentMethodInfo($paymentMethodClass = '', $includeDiscover = true) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__extensions')) - ->where($db->qn('enabled') . ' = ' . $db->quote('1')) - ->where('LOWER(' . $db->qn('folder') . ') = ' . $db->quote('redshop_payment')) - ->order($db->qn('ordering') . ' ASC'); - - if ($paymentMethodClass != '') - { - $query->where($db->qn('element') . ' = ' . $db->quote($paymentMethodClass)); - } - - if (!$includeDiscover) - { - $query->where($db->qn('state') . ' >= 0'); - } - - $db->setQuery($query); - - return $db->loadObjectList(); - } - - /** - * Get billing address - * - * @param integer $userId User ID - * - * @return object|false|null Object data if success. False otherwise. - * - * @since 2.0.3 - */ - public static function getBillingAddress($userId = 0) - { - if ($userId == 0) - { - $user = JFactory::getUser(); - $userId = $user->id; - } - - if (!$userId) - { - return false; - } - - if (!array_key_exists($userId, static::$billingAddresses)) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->select('CONCAT(' . $db->qn('firstname') . '," ",' . $db->qn('lastname') . ') AS text') - ->from($db->qn('#__redshop_users_info')) - ->where($db->qn('address_type') . ' = ' . $db->quote('BT')); - - if ((int) $userId < 0) - { - $query->where($db->qn('users_info_id') . ' = ' . abs((int) $userId)); - } - else - { - $query->where($db->qn('user_id') . ' = ' . (int) $userId); - } - - - static::$billingAddresses[$userId] = $db->setQuery($query)->loadObject(); - } - - return static::$billingAddresses[$userId]; - } - - /** - * Get Shipping address - * - * @param integer $userId User Id - * - * @return array - * - * @since 2.0.3 - */ - public static function getShippingAddress($userId = 0) - { - if ($userId == 0) - { - $user = JFactory::getUser(); - $userId = $user->id; - } - - if (!$userId) - { - return false; - } - - if (!array_key_exists($userId, static::$shippingAddresses)) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->select('CONCAT(' . $db->qn('firstname') . '," ",' . $db->qn('lastname') . ') AS text') - ->from($db->qn('#__redshop_users_info')) - ->where($db->qn('address_type') . ' = ' . $db->quote('ST')) - ->where($db->qn('user_id') . ' = ' . (int) $userId); - - static::$shippingAddresses[$userId] = $db->setQuery($query)->loadObjectList(); - } - - return static::$shippingAddresses[$userId]; - } - - /** - * Get User full name - * - * @param integer $userId User ID - * - * @return string - * - * @since 2.0.3 - */ - public static function getUserFullName($userId) - { - $fullName = ""; - $user = JFactory::getUser(); - $db = JFactory::getDbo(); - - if ($userId == 0) - { - $userId = $user->id; - } - - $query = $db->getQuery(true) - ->select($db->qn(array('firstname', 'lastname'))) - ->from($db->qn('#__redshop_users_info')) - ->where($db->qn('address_type') . ' LIKE ' . $db->quote('BT')) - ->where($db->qn('user_id') . ' = ' . (int) $userId); - $db->setQuery($query); - $list = $db->loadObject(); - - if ($list) - { - $fullName = $list->firstname . " " . $list->lastname; - } - else - { - $query = $db->getQuery(true) - ->select($db->qn('name')) - ->from($db->qn('#__users')) - ->where($db->qn('id') . ' = ' . (int) $userId); - $db->setQuery($query); - $list = $db->loadObject(); - - if ($list) - { - $fullName = $list->name; - } - } - - return $fullName; - } - - /** - * Get order item accessory detail - * - * @param integer $orderItemId Order Item ID - * - * @return null|array - * - * @since 2.0.3 - */ - public static function getOrderItemAccessoryDetail($orderItemId = 0) - { - if (!$orderItemId) - { - return null; - } - - return RedshopEntityOrder_Item::getInstance($orderItemId)->getAccessoryItems()->toObjects(); - } - - /** - * Get order item attribute detail - * - * @param integer $orderItemId Order Item ID - * @param integer $isAccessory Is accessory - * @param string $section Section text - * @param integer $parentSectionId Parent section ID - * - * @return array - * - * @since 2.0.3 - */ - public static function getOrderItemAttributeDetail($orderItemId = 0, $isAccessory = 0, $section = "attribute", $parentSectionId = 0) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_order_attribute_item')) - ->where($db->qn('is_accessory_att') . ' = ' . (int) $isAccessory) - ->where($db->qn('section') . ' = ' . $db->quote($section)); - - if ($orderItemId != 0) - { - $query->where($db->qn('order_item_id') . ' = ' . (int) $orderItemId); - } - - if ($parentSectionId != 0) - { - $query->where($db->qn('parent_section_id') . ' = ' . (int) $parentSectionId); - } - - $db->setQuery($query); - - return $db->loadObjectlist(); - } - - /** - * Get Order User Field Data - * - * @param integer $orderItemId Order Item ID - * @param integer $section Section ID - * - * @return object|mixed - * - * @since 2.0.3 - */ - public static function getOrderUserFieldData($orderItemId = 0, $section = 0) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('fd.*') - ->select($db->qn(array('f.title', 'f.type', 'f.name'))) - ->from($db->qn('#__redshop_fields_data', 'fd')) - ->leftJoin($db->qn('#__redshop_fields', 'f') . ' ON ' . $db->qn('f.id') . ' = ' . $db->qn('fd.fieldid')) - ->where($db->qn('fd.itemid') . ' = ' . (int) $orderItemId) - ->where($db->qn('fd.section') . ' = ' . $db->quote($section)); - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * Generate Order Number - * - * @return integer - * - * @since 2.0.3 - */ - public static function generateOrderNumber() - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('MAX(' . $db->qn('order_id') . ')') - ->from($db->qn('#__redshop_orders')); - $db->setQuery($query); - $maxId = $db->loadResult(); - - /* - * if Economic Integration is on !!! - * We are not using Order Invoice Number Template - * Economic Order Number Only Support (int) value. - * Invoice Number May be varchar or int. - */ - if (Redshop::getConfig()->get('ECONOMIC_INTEGRATION') && JPluginHelper::isEnabled('economic')) - { - $query = $db->getQuery(true) - ->select($db->qn('order_number')) - ->from($db->qn('#__redshop_orders')) - ->where($db->qn('order_id') . ' = ' . (int) $maxId); - $db->setQuery($query); - - $maxOrderNumber = $db->loadResult(); - $maxInvoice = RedshopEconomic::getMaxOrderNumberInEconomic(); - $maxId = max((int) $maxOrderNumber, $maxInvoice); - } - elseif (Redshop::getConfig()->get('INVOICE_NUMBER_TEMPLATE')) - { - $maxId = ($maxId + Redshop::getConfig()->get('FIRST_INVOICE_NUMBER') + 1); - - return self::parseNumberTemplate( - Redshop::getConfig()->get('INVOICE_NUMBER_TEMPLATE'), - $maxId - ); - } - - return $maxId + 1; - } - - /** - * Random Generate Encrypt Key - * - * @param string $pLength Length of string - * - * @return string - * - * @since 2.0.3 - * @deprecated Use \Redshop\Crypto\Helper\Encrypt::generateCustomRandomEncryptKey - */ - public static function randomGenerateEncryptKey($pLength = '30') - { - return \Redshop\Crypto\Helper\Encrypt::generateCustomRandomEncryptKey((int) $pLength); - } - - /** - * Get Country name by 3 characters of country code - * - * @param string $cnt3 Country code - * - * @return string - * - * @since 2.0.3 - */ - public static function getCountryName($cnt3 = '') - { - if (empty($cnt3)) - { - return ''; - } - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->qn('country_3_code', 'value')) - ->select($db->qn('country_name', 'text')) - ->select($db->qn('country_jtext')) - ->from($db->qn('#__redshop_country')); - - if ($cnt3 != '') - { - $query->where($db->qn('country_3_code') . ' = ' . $db->quote($cnt3)); - } - - $countries = $db->setQuery($query)->loadObjectList(); - - $countries = RedshopHelperUtility::convertLanguageString($countries); - - if (count($countries) > 0) - { - return $countries[0]->text; - } - - return ''; - } - - /** - * Get state name - * - * @param string $st3 State code - * @param string $cnt3 Country code - * - * @return string - * - * @since 2.0.3 - */ - public static function getStateName($st3 = "", $cnt3 = "") - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->qn('s.state_name')) - ->from($db->qn('#__redshop_state', 's')) - ->leftJoin($db->qn('#__redshop_country', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('s.country_id')); - - if ($st3 != "") - { - $query->where($db->qn('s.state_2_code') . ' = ' . $db->quote($st3)); - } - - if ($cnt3 != "") - { - $query->where($db->qn('c.country_3_code') . ' = ' . $db->quote($cnt3)); - } - - $db->setQuery($query); - - return $db->loadResult(); - } - - /** - * Send download by email - * - * @param integer $orderId Order ID - * - * @return boolean - * - * @since 2.0.3 - */ - public static function sendDownload($orderId = 0) - { - $app = JFactory::getApplication(); - - // Getting the order status changed template from mail center end - $mailFrom = $app->get('mailfrom'); - $fromName = $app->get('fromname'); - - $mailData = ""; - $mailSubject = ""; - $mailBcc = null; - $mailInfo = Redshop\Mail\Helper::getTemplate(0, "downloadable_product_mail"); - - if (count($mailInfo) > 0) - { - $mailData = $mailInfo[0]->mail_body; - $mailSubject = $mailInfo[0]->mail_subject; - - if (trim($mailInfo[0]->mail_bcc) != "") - { - $mailBcc = explode(",", $mailInfo[0]->mail_bcc); - } - } - - // Get Downloadable Product - $rows = self::getDownloadProduct($orderId); - - // There is no downloadable product - if ($rows === null || count($rows) == 0) - { - return false; - } - - // Getting the order details - $orderDetail = self::getOrderDetails($orderId); - $userDetail = self::getOrderBillingUserInfo($orderId); - - $userFullname = $userDetail->firstname . " " . $userDetail->lastname; - $userEmail = $userDetail->email; - - $mailData = str_replace("{fullname}", $userFullname, $mailData); - $mailData = str_replace("{order_id}", $orderDetail->order_id, $mailData); - $mailData = str_replace("{order_number}", $orderDetail->order_number, $mailData); - $mailData = str_replace("{order_date}", RedshopHelperDatetime::convertDateFormat($orderDetail->cdate), $mailData); - - $productStart = ""; - $productEnd = ""; - $productMiddle = ""; - $pMiddle = ""; - $mailFirst = explode("{product_serial_loop_start}", $mailData); - - if (count($mailFirst) > 1) - { - $productStart = $mailFirst[0]; - $mailSec = explode("{product_serial_loop_end}", $mailFirst[1]); - - if (count($mailSec) > 1) - { - $productMiddle = $mailSec[0]; - $productEnd = $mailSec[1]; - } - } - - foreach ($rows as $row) - { - $dataMessage = $productMiddle; - $downloadFilename = basename($row->file_name); - - $mailToken = "" . $downloadFilename . ""; - - $dataMessage = str_replace("{product_serial_number}", $row->product_serial_number, $dataMessage); - $dataMessage = str_replace("{product_name}", $row->product_name, $dataMessage); - $dataMessage = str_replace("{token}", $mailToken, $dataMessage); - - $pMiddle .= $dataMessage; - } - - $mailData = $productStart . $pMiddle . $productEnd; - $mailBody = $mailData; - Redshop\Mail\Helper::imgInMail($mailBody); - $mailSubject = str_replace("{order_number}", $orderDetail->order_number, $mailSubject); - - if ($mailBody && $userEmail != "") - { - if (!JFactory::getMailer()->sendMail($mailFrom, $fromName, $userEmail, $mailSubject, $mailBody, 1, null, $mailBcc)) - { - $app->enqueueMessage(JText::_('COM_REDSHOP_ERROR_DOWNLOAD_MAIL_FAIL'), 'error'); - } - } - - return true; - } - - /** - * Get download product - * - * @param integer $orderId Order ID - * - * @return array - * - * @since 2.0.3 - */ - public static function getDownloadProduct($orderId) - { - if (!array_key_exists($orderId, self::$orderProductsDownload)) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('pd.*') - ->select($db->qn('product_name')) - ->from($db->qn('#__redshop_product_download', 'pd')) - ->leftJoin($db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('pd.product_id') . ' = ' . $db->qn('p.product_id')) - ->where($db->qn('order_id') . ' = ' . (int) $orderId); - - - self::$orderProductsDownload[$orderId] = $db->setQuery($query)->loadObjectList(); - } - - return self::$orderProductsDownload[$orderId]; - } - - /** - * Get download product log - * - * @param integer $orderId Order Id - * @param string $did Download id - * - * @return array - * - * @since 2.0.3 - */ - public static function getDownloadProductLog($orderId, $did = '') - { - $key = $orderId . '_' . $did; - - if (!array_key_exists($key, self::$orderProductsDownloadLog)) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('pdl.*') - ->select($db->qn(array('pd.order_id', 'pd.product_id', 'pd.file_name'))) - ->from($db->qn('#__redshop_product_download_log', 'pdl')) - ->leftJoin($db->qn('#__redshop_product_download', 'pd') . ' ON ' . $db->qn('pd.download_id') . ' = ' . $db->qn('pdl.download_id')) - ->where($db->qn('pd.order_id') . ' = ' . (int) $orderId); - - if ($did != '') - { - $query->where($db->qn('pdl.download_id') . ' = ' . $db->quote($did)); - } - - self::$orderProductsDownloadLog[$key] = $db->setQuery($query)->loadObjectList(); - } - - return self::$orderProductsDownloadLog[$key]; - } - - /** - * Get payment parameters - * - * @param string $payment Payment type - * - * @return array - * - * @since 2.0.3 - */ - public static function getParameters($payment) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__extensions')) - ->where($db->qn('element') . ' = ' . $db->quote($payment)); - $db->setQuery($query); - - return $db->loadObjectList(); - } - - /** - * Get payment information - * - * @param object $row Payment info row - * @param array $post payment method class - * - * @return void - * - * @since 2.0.3 - */ - public static function getPaymentInformation($row, $post) - { - $app = JFactory::getApplication(); - $pluginParameters = self::getParameters($post['payment_method_class']); - $paymentInfo = $pluginParameters[0]; - $paymentParams = new Registry($paymentInfo->params); - - $isCreditCard = $paymentParams->get('is_creditcard', ''); - - $order = self::getOrderDetails($row->order_id); - - if ($userBillingInfo = self::getOrderBillingUserInfo($row->order_id)) - { - $userBillingInfo->country_2_code = RedshopHelperWorld::getCountryCode2($userBillingInfo->country_code); - $userBillingInfo->state_2_code = RedshopHelperWorld::getStateCode2($userBillingInfo->state_code); - } - - $task = $app->input->getCmd('task'); - - if ($shippingAddress = self::getOrderShippingUserInfo($row->order_id)) - { - $shippingAddress->country_2_code = RedshopHelperWorld::getCountryCode2($shippingAddress->country_code); - $shippingAddress->state_2_code = RedshopHelperWorld::getStateCode2($shippingAddress->state_code); - } - - $values = array(); - $values['shippinginfo'] = $shippingAddress; - $values['billinginfo'] = $userBillingInfo; - $values['carttotal'] = $order->order_total; - $values['order_subtotal'] = $order->order_subtotal; - $values["order_id"] = $row->order_id; - $values['payment_plugin'] = $post['payment_method_class']; - $values['task'] = $task; - $values['order'] = $order; - - if ($isCreditCard == 0) - { - // Check for bank transfer payment type plugin - `rs_payment_banktransfer` suffixed - $isBankTransferPaymentType = RedshopHelperPayment::isPaymentType($values['payment_plugin']); - - if ($isBankTransferPaymentType) - { - $app->redirect( - JUri::base() . "index.php?option=com_redshop&view=order_detail&layout=creditcardpayment&plugin=" - . $values['payment_plugin'] . "&order_id=" . $row->order_id - ); - } - - JPluginHelper::importPlugin('redshop_payment'); - RedshopHelperUtility::getDispatcher()->trigger('onPrePayment', array($values['payment_plugin'], $values)); - - $app->redirect( - JUri::base() . "index.php?option=com_redshop&view=order_detail&task=edit&cid[]=" . $row->order_id - ); - } - else - { - $app->redirect( - JUri::base() . "index.php?option=com_redshop&view=order_detail&layout=creditcardpayment&plugin=" - . $values['payment_plugin'] . "&order_id=" . $row->order_id - ); - } - } - - /** - * Get shipping location information - * - * @param string $shippingName Shipping name - * - * @return object|mixed - * - * @since 2.0.3 - */ - public static function getShippingLocationInfo($shippingName) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->qn('shipping_location_info')) - ->from($db->qn('#__redshop_shipping_rate')) - ->where($db->qn('shipping_rate_name') . ' = ' . $db->quote($shippingName)); - - $db->setQuery($query); - - return $db->loadObjectList(); - } - - /** - * Check update Orders - * - * @param object $data Data to check - * - * @return integer - * - * @since 2.0.3 - */ - public static function checkUpdateOrders($data) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_orders')) - ->where($db->qn('order_status') . ' = ' . $db->quote($data->order_status_code)) - ->where($db->qn('order_payment_status') . ' = ' . $db->quote($data->order_payment_status_code)) - ->where($db->qn('order_id') . ' = ' . (int) $data->order_id); - $db->setQuery($query); - - if (count($db->loadObjectList()) == 0) - { - return 0; - } - - return 1; - } - - /** - * Change order status mail - * - * @param integer $orderId Order ID - * @param string $newStatus New status - * @param string $orderComment Order Comment - * - * @return void - * - * @since 2.0.3 - */ - public static function changeOrderStatusMail($orderId, $newStatus, $orderComment = '') - { - $app = JFactory::getApplication(); - - // Changes to parse all tags same as order mail end - $userDetail = self::getOrderBillingUserInfo($orderId); - - $mailFrom = $app->get('mailfrom'); - $fromName = $app->get('fromname'); - $mailBcc = null; - $mailSection = "order_status"; - $mailTemplate = Redshop\Mail\Helper::getTemplate( - 0, '', '`mail_section` LIKE "' . $mailSection . '" AND `mail_order_status` LIKE "' . $newStatus . '"' - ); - - if (count($mailTemplate) > 0) - { - $mailData = $mailTemplate[0]->mail_body; - $mailSubject = $mailTemplate[0]->mail_subject; - - $fieldArray = RedshopHelperExtrafields::getSectionFieldList(RedshopHelperExtrafields::SECTION_ORDER, 0); - - if (count($fieldArray) > 0) - { - for ($i = 0, $in = count($fieldArray); $i < $in; $i++) - { - $fieldValueArray = RedshopHelperExtrafields::getSectionFieldDataList( - $fieldArray[$i]->id, RedshopHelperExtrafields::SECTION_ORDER, $orderId, $userDetail->user_email - ); - - if ($fieldValueArray->data_txt != "") - { - $mailData = str_replace('{' . $fieldArray[$i]->name . '}', $fieldValueArray->data_txt, $mailData); - $mailData = str_replace('{' . $fieldArray[$i]->name . '_lbl}', $fieldArray[$i]->title, $mailData); - } - else - { - $mailData = str_replace('{' . $fieldArray[$i]->name . '}', "", $mailData); - $mailData = str_replace('{' . $fieldArray[$i]->name . '_lbl}', "", $mailData); - } - } - } - - if (trim($mailTemplate[0]->mail_bcc) != "") - { - $mailBcc = explode(",", $mailTemplate[0]->mail_bcc); - } - - // Changes to parse all tags same as order mail start - $orderDetail = self::getOrderDetails($orderId); - $mailData = str_replace("{order_mail_intro_text_title}", JText::_('COM_REDSHOP_ORDER_MAIL_INTRO_TEXT_TITLE'), $mailData); - $mailData = str_replace("{order_mail_intro_text}", JText::_('COM_REDSHOP_ORDER_MAIL_INTRO_TEXT'), $mailData); - - $mailData = Template::replaceTemplate($orderDetail, $mailData, true); - - $arrDiscount = explode('@', $orderDetail->discount_type); - $discountType = ''; - - for ($d = 0, $dn = count($arrDiscount); $d < $dn; $d++) - { - if ($arrDiscount [$d]) - { - $arrDiscountType = explode(':', $arrDiscount [$d]); - - if ($arrDiscountType [0] == 'c') - { - $discountType .= JText::_('COM_REDSHOP_COUPON_CODE') . ' : ' . $arrDiscountType [1] . '
    '; - } - - if ($arrDiscountType [0] == 'v') - { - $discountType .= JText::_('COM_REDSHOP_VOUCHER_CODE') . ' : ' . $arrDiscountType [1] . '
    '; - } - } - } - - if (!$discountType) - { - $discountType = JText::_('COM_REDSHOP_NO_DISCOUNT_AVAILABLE'); - } - - $search [] = "{discount_type}"; - $replace [] = $discountType; - - // Getting the order status changed template from mail center end - $mailData = RedshopHelperBillingTag::replaceBillingAddress($mailData, $userDetail); - - // Get ShippingAddress From order Users info - $shippingAddresses = self::getOrderShippingUserInfo($orderId); - - if (count($shippingAddresses) <= 0) - { - $shippingAddresses = $userDetail; - } - - $mailData = Redshop\Shipping\Tag::replaceShippingAddress($mailData, $shippingAddresses); - - $search[] = "{shopname}"; - $replace[] = Redshop::getConfig()->get('SHOP_NAME'); - - $search[] = "{fullname}"; - $replace[] = $userDetail->firstname . " " . $userDetail->lastname; - - $search[] = "{email}"; - $replace[] = $userDetail->user_email; - - $search[] = "{customer_id}"; - $replace[] = $userDetail->users_info_id; - - $search[] = "{order_id}"; - $replace[] = $orderId; - - $search[] = "{order_number}"; - $replace[] = $orderDetail->order_number; - - $search[] = "{order_date}"; - $replace[] = RedshopHelperDatetime::convertDateFormat($orderDetail->cdate); - - $search[] = "{customer_note_lbl}"; - $replace[] = JText::_('COM_REDSHOP_COMMENT'); - - $search[] = "{customer_note}"; - $replace[] = $orderComment; - - $search[] = "{order_detail_link_lbl}"; - $replace[] = JText::_('COM_REDSHOP_ORDER_DETAIL_LBL'); - - $orderDetailurl = JUri::root() . 'index.php?option=com_redshop&view=order_detail&oid=' . $orderId . '&encr=' . $orderDetail->encr_key; - $search[] = "{order_detail_link}"; - $replace[] = "" . JText::_("COM_REDSHOP_ORDER_DETAIL_LINK_LBL") . ""; - - // Todo: Move to the shipping plugin to return track no and track url - $details = Redshop\Shipping\Rate::decrypt($orderDetail->ship_method_id); - - if (count($details) <= 1) - { - $details = explode("|", $orderDetail->ship_method_id); - } - - if ($details[0] == 'plgredshop_shippingdefault_shipping_gls') - { - $arrLocationDetails = explode('|', $orderDetail->shop_id); - $orderDetail->track_no = $arrLocationDetails[0]; - } - - if (strpos($mailData, "{if track_no}") !== false && strpos($mailData, "{track_no end if}") !== false) - { - if (empty($orderDetail->track_no)) - { - $template_pd_sdata = explode('{if track_no}', $mailData); - $template_pd_edata = explode('{track_no end if}', $template_pd_sdata [1]); - $mailData = $template_pd_sdata[0] . $template_pd_edata[1]; - } - - $mailData = str_replace("{if track_no}", '', $mailData); - $mailData = str_replace("{track_no end if}", '', $mailData); - } - - $search[] = "{order_track_no}"; - $replace[] = trim($orderDetail->track_no); - - $orderTrackURL = 'http://www.pacsoftonline.com/ext.po.dk.dk.track?key=' . Redshop::getConfig()->get('POSTDK_CUSTOMER_NO') . '&order=' . $orderId; - - JPluginHelper::importPlugin('redshop_shipping'); - RedshopHelperUtility::getDispatcher()->trigger( - 'onReplaceTrackingUrl', - array( - $orderId, - &$orderTrackURL - ) - ); - - $search[] = "{order_track_url}"; - $replace[] = "" . JText::_("COM_REDSHOP_TRACK_LINK_LBL") . ""; - - $mailBody = str_replace($search, $replace, $mailData); - Redshop\Mail\Helper::imgInMail($mailBody); - $mailSubject = str_replace($search, $replace, $mailSubject); - - if ('' != $userDetail->thirdparty_email && $mailBody) - { - Redshop\Mail\Helper::sendEmail( - $mailFrom, - $fromName, - $userDetail->thirdparty_email, - $mailSubject, - $mailBody, - true, - null, - null, - null, - $mailSection, - func_get_args() - ); - } - - if ('' != $userDetail->user_email && $mailBody) - { - Redshop\Mail\Helper::sendEmail( - $mailFrom, - $fromName, - $userDetail->user_email, - $mailSubject, - $mailBody, - true, - null, - $mailBcc, - null, - $mailSection, - func_get_args() - ); - } - } - } - - /** - * Create book invoice - * - * @param integer $orderId Order ID - * @param string $orderStatus Order status - * - * @return void - * - * @since 2.0.3 - */ - public static function createBookInvoice($orderId, $orderStatus) - { - // Economic Integration start for invoice generate and book current invoice - if (Redshop::getConfig()->get('ECONOMIC_INTEGRATION') == 1 && Redshop::getConfig()->get('ECONOMIC_INVOICE_DRAFT') != 1) - { - if (Redshop::getConfig()->get('ECONOMIC_INVOICE_DRAFT') == 2 && $orderStatus == Redshop::getConfig()->get('BOOKING_ORDER_STATUS')) - { - $paymentInfo = self::getPaymentInfo($orderId); - $economicData = array(); - - if (!empty($paymentInfo)) - { - $paymentName = $paymentInfo->payment_method_class; - $paymentArr = explode("rs_payment_", $paymentInfo->payment_method_class); - - if (count($paymentArr) > 0) - { - $paymentName = $paymentArr[1]; - } - - $economicData['economic_payment_method'] = $paymentName; - $paymentMethod = self::getPaymentMethodInfo($paymentInfo->payment_method_class); - - if (count($paymentMethod) > 0) - { - $paymentParams = new Registry($paymentMethod[0]->params); - $economicData['economic_payment_terms_id'] = $paymentParams->get('economic_payment_terms_id'); - $economicData['economic_design_layout'] = $paymentParams->get('economic_design_layout'); - $economicData['economic_is_creditcard'] = $paymentParams->get('is_creditcard'); - } - } - - RedshopEconomic::createInvoiceInEconomic($orderId, $economicData); - } - - $bookInvoicePdf = RedshopEconomic::bookInvoiceInEconomic($orderId, Redshop::getConfig()->get('ECONOMIC_INVOICE_DRAFT')); - - if (JFile::exists($bookInvoicePdf)) - { - Redshop\Mail\Invoice::sendEconomicBookInvoiceMail($orderId, $bookInvoicePdf); - } - } - } - - /** - * Create Multi Print Invoice PDF - * - * @param array $orderIds Order ID - * - * @return string File name of generated pdf. - * - * @since 2.0.3 - */ - public static function createMultiPrintInvoicePdf($orderIds) - { - return RedshopHelperMail::createMultiprintInvoicePdf($orderIds); - } - - /** - * Method for generate Invoice PDF of specific Order - * - * @param int $orderId ID of order. - * @param string $code Code when generate PDF. - * @param boolean $isEmail Is generate for use in Email? - * - * @return void - * - * @since 2.0.3 - */ - public static function generateInvoicePdf($orderId, $code = 'F', $isEmail = false) - { - if (!$orderId) - { - return; - } - - $plugins = JPluginHelper::getPlugin('redshop_pdf'); - - if (empty($plugins)) - { - return; - } - - $orderDetail = self::getOrderDetails($orderId); - $orderTemplate = RedshopHelperTemplate::getTemplate('order_print'); - - if (count($orderTemplate) > 0 && $orderTemplate[0]->template_desc != "") - { - $message = $orderTemplate[0]->template_desc; - } - else - { - $message = ' + $postURL = "https://www.pacsoftonline.com/ufoweb/order?session=po_DK" + . "&user=" . Redshop::getConfig()->get('POSTDK_CUSTOMER_NO') + . "&pin=" . Redshop::getConfig()->get('POSTDK_CUSTOMER_PASSWORD') + . "&developerid=000000075" + . "&type=xml"; + + try { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $postURL); + curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_VERBOSE, true); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlnew); + $response = curl_exec($ch); + curl_close($ch); + + $xmlResponse = JFactory::getXML($response, false); + + if (empty($xmlResponse) || !empty($error)) { + return JText::_('LIB_REDSHOP_PACSOFT_ERROR_NO_RESPONSE'); + } + + $xmlResponse = $xmlResponse->val; + + if ('201' === (string)$xmlResponse[1] && 'Created' === (string)$xmlResponse[2]) { + // Update current order success entry. + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_orders')) + ->set($db->qn('order_label_create') . ' = 1') + ->where($db->qn('order_id') . ' = ' . (int)$orderId); + + // Set the query and execute the update. + $db->setQuery($query); + $db->execute(); + + return "success"; + } else { + return (string)$xmlResponse[1] . "-" . (string)$xmlResponse[2] . "-" . (string)$xmlResponse[0]; + } + } catch (Exception $e) { + return $e->getMessage(); + } + } + + /** + * Get order details + * + * @param integer $orderId Order ID + * + * @return object + * + * @since 2.0.3 + * + * @deprecated 2.0.6 + */ + public static function getOrderDetails($orderId) + { + return self::getOrderDetail($orderId); + } + + /** + * Get order information from order id. + * + * @param integer $orderId Order Id + * @param boolean $force Force to get order information from DB instead of cache. + * + * @return object Order Information Object + * + * @deprecated 2.0.6 + */ + public static function getOrderDetail($orderId, $force = false) + { + if (!$orderId) { + return null; + } + + $order = RedshopEntityOrder::getInstance($orderId); + + if ($force) { + $order->reset(); + } + + return $order->getItem(); + } + + /** + * Get list item of an specific order. + * + * @param mixed $orderId Order ID + * @param integer $productId Product ID + * @param integer $orderItemId Order Item ID + * + * @return mixed + * + * @since 2.0.3 + */ + public static function getOrderItemDetail($orderId = 0, $productId = 0, $orderItemId = 0, $force = false) + { + // Make sure at least one options has been pass. + if (empty($orderId) && !$productId && !$orderItemId) { + return false; + } + + $key = $orderId . '_' . $productId . '_' . $orderItemId; + + if (!array_key_exists($key, self::$orderItems) || $force) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_order_item')); + + if (!empty($orderId)) { + $orderId = explode(',', $orderId); + $orderId = ArrayHelper::toInteger($orderId); + $orderId = implode(',', $orderId); + + $query->where($db->qn('order_id') . ' IN (' . $orderId . ')'); + } + + if ($productId != 0) { + $query->where($db->qn('product_id') . ' = ' . (int)$productId); + } + + if ($orderItemId != 0) { + $query->where($db->qn('order_item_id') . ' = ' . (int)$orderItemId); + } + + self::$orderItems[$key] = $db->setQuery($query)->loadObjectList(); + } + + return self::$orderItems[$key]; + } + + /** + * Get Order billing user information + * + * @param integer $orderId Order Id + * @param boolean $force Force get information + * + * @return object Order Billing information object + * + * @deprecated 2.0.6 + */ + public static function getOrderBillingUserInfo($orderId, $force = false) + { + if (!$orderId) { + return null; + } + + /** @var RedshopEntityOrder_User $userBilling */ + $userBilling = RedshopEntityOrder::getInstance($orderId)->getBilling(); + + if ($force) { + $userBilling->reset()->loadExtraFields(); + } + + return $userBilling->getItem(); + } + + /** + * Get Order shipping user information + * + * @param integer $orderId Order Id + * @param boolean $force Order Id + * + * @return object Order Shipping information object + * + * @deprecated 2.0.6 + */ + public static function getOrderShippingUserInfo($orderId, $force = false) + { + if (!$orderId) { + return null; + } + + /** @var RedshopEntityOrder_User $userBilling */ + $userBilling = RedshopEntityOrder::getInstance($orderId)->getShipping(); + + if ($force) { + $userBilling->reset()->loadExtraFields(); + } + + return $userBilling->getItem(); + } + + /** + * Get order item accessory detail + * + * @param integer $orderItemId Order Item ID + * + * @return null|array + * + * @since 2.0.3 + */ + public static function getOrderItemAccessoryDetail($orderItemId = 0) + { + if (!$orderItemId) { + return null; + } + + return RedshopEntityOrder_Item::getInstance($orderItemId)->getAccessoryItems()->toObjects(); + } + + /** + * Create book invoice + * + * @param integer $orderId Order ID + * @param string $orderStatus Order status + * + * @return void + * + * @since 2.0.3 + */ + public static function createBookInvoice($orderId, $orderStatus) + { + // Economic Integration start for invoice generate and book current invoice + if (Redshop::getConfig()->get('ECONOMIC_INTEGRATION') == 1 && Redshop::getConfig()->get( + 'ECONOMIC_INVOICE_DRAFT' + ) != 1) { + if (Redshop::getConfig()->get('ECONOMIC_INVOICE_DRAFT') == 2 && $orderStatus == Redshop::getConfig()->get( + 'BOOKING_ORDER_STATUS' + )) { + $paymentInfo = self::getPaymentInfo($orderId); + $economicData = array(); + + if (!empty($paymentInfo)) { + $paymentName = $paymentInfo->payment_method_class; + $paymentArr = explode("rs_payment_", $paymentInfo->payment_method_class); + + if (count($paymentArr) > 0) { + $paymentName = $paymentArr[1]; + } + + $economicData['economic_payment_method'] = $paymentName; + $paymentMethod = self::getPaymentMethodInfo( + $paymentInfo->payment_method_class + ); + + if (count($paymentMethod) > 0) { + $paymentParams = new Registry($paymentMethod[0]->params); + $economicData['economic_payment_terms_id'] = $paymentParams->get('economic_payment_terms_id'); + $economicData['economic_design_layout'] = $paymentParams->get('economic_design_layout'); + $economicData['economic_is_creditcard'] = $paymentParams->get('is_creditcard'); + } + } + + RedshopEconomic::createInvoiceInEconomic($orderId, $economicData); + } + + $bookInvoicePdf = RedshopEconomic::bookInvoiceInEconomic( + $orderId, + Redshop::getConfig()->get('ECONOMIC_INVOICE_DRAFT') + ); + + if (JFile::exists($bookInvoicePdf)) { + Redshop\Mail\Invoice::sendEconomicBookInvoiceMail($orderId, $bookInvoicePdf); + } + } + } + + /** + * Get Order Payment Information + * + * @param integer $orderId Order Id + * + * @return object Payment Information for orders + * + * @deprecated 2.0.6 + */ + public static function getPaymentInfo($orderId) + { + $payment = RedshopEntityOrder::getInstance($orderId)->getPayment(); + + if (null === $payment) { + return null; + } + + return $payment->getItem(); + } + + /** + * Get payment method info + * + * @param string $paymentMethodClass Payment method class + * @param boolean $includeDiscover Include all plugins even not discover install yet + * + * @return array + * + * @since 2.0.3 + */ + public static function getPaymentMethodInfo($paymentMethodClass = '', $includeDiscover = true) + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__extensions')) + ->where($db->qn('enabled') . ' = ' . $db->quote('1')) + ->where('LOWER(' . $db->qn('folder') . ') = ' . $db->quote('redshop_payment')) + ->order($db->qn('ordering') . ' ASC'); + + if ($paymentMethodClass != '') { + $query->where($db->qn('element') . ' = ' . $db->quote($paymentMethodClass)); + } + + if (!$includeDiscover) { + $query->where($db->qn('state') . ' >= 0'); + } + + $db->setQuery($query); + + return $db->loadObjectList(); + } + + /** + * Get status list + * + * @param string $name Name of status list + * @param string $selected Selet status name + * @param string $attributes Attributes of html + * + * @return string HTML of status list + * + * @since 2.0.3 + */ + public static function getStatusList( + $name = 'statuslist', + $selected = '', + $attributes = ' class="inputbox" size="1" ' + ) { + if (!self::$orderStatusList) { + self::$orderStatusList = self::getOrderStatusList(); + } + + $types[] = JHtml::_('select.option', '0', '- ' . JText::_('COM_REDSHOP_SELECT_STATUS_LBL') . ' -'); + $types = array_merge($types, self::$orderStatusList); + $totStatus = explode(",", $selected); + + return JHtml::_('select.genericlist', $types, $name, $attributes, 'value', 'text', $totStatus); + } + + /** + * Get all the order status code information list + * + * @return array Order Status info + */ + public static function getOrderStatusList() + { + if (!empty(self::$allStatus)) { + return self::$allStatus; + } + + // Initialiase variables. + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select( + array( + $db->qn('order_status_code', 'value'), + $db->qn('order_status_name', 'text') + ) + ) + ->from($db->qn('#__redshop_order_status')) + ->where($db->qn('published') . ' = ' . $db->q('1')); + + // Set the query and load the result. + $db->setQuery($query); + self::$allStatus = $db->loadObjectList(); + + // Check for a database error. + if (/** @scrutinizer ignore-deprecated */ $db->getErrorNum()) { + /** @scrutinizer ignore-deprecated */ + JError::raiseWarning(500, /** @scrutinizer ignore-deprecated */ $db->getErrorMsg()); + + return null; + } + + return self::$allStatus; + } + + /** + * Get filter by list + * + * @param string $name Name of filter by list + * @param string $selected Select filter list + * @param string $attributes Attributes of HTML + * + * @return string HTML of filter list + * + * @since 2.0.3 + */ + public static function getFilterByList( + $name = 'filterbylist', + $selected = 'all', + $attributes = ' class="inputbox" size="1" ' + ) { + $filterByList = array( + 'orderid' => JText::_('COM_REDSHOP_ORDERID'), + 'ordernumber' => JText::_('COM_REDSHOP_ORDERNUMBER'), + 'fullname' => JText::_('COM_REDSHOP_FULLNAME'), + 'useremail' => JText::_('COM_REDSHOP_USEREMAIL') + ); + + $types[] = JHtml::_('select.option', '', 'All'); + $types = array_merge($types, $filterByList); + $totStatus = explode(",", $selected); + + return JHtml::_('select.genericlist', $types, $name, $attributes, 'value', 'text', $totStatus); + } + + /** + * Get payment status list + * + * @param string $name Name of payment status list + * @param string $selected Select option + * @param string $attributes Attributes of HTML + * + * @return string HTML of payment status list + * + * @since 2.0.3 + */ + public static function getPaymentStatusList( + $name = 'paymentstatuslist', + $selected = '', + $attributes = ' class="inputbox" size="1" ' + ) { + $types[] = JHtml::_('select.option', '', JText::_('COM_REDSHOP_SELECT_PAYMENT_STATUS')); + $types[] = JHtml::_('select.option', 'Paid', JText::_('COM_REDSHOP_PAYMENT_STA_PAID')); + $types[] = JHtml::_('select.option', 'Unpaid', JText::_('COM_REDSHOP_PAYMENT_STA_UNPAID')); + $types[] = JHtml::_('select.option', 'Partial Paid', JText::_('COM_REDSHOP_PAYMENT_STA_PARTIAL_PAID')); + + return JHtml::_('select.genericlist', $types, $name, $attributes, 'value', 'text', $selected); + } + + /** + * Update order status and trigger emails based on status. + * + * @return void + * + * @throws Exception + * @since 2.0.3 + * + */ + public static function updateStatus() + { + JPluginHelper::importPlugin('redshop_shipping'); + $app = JFactory::getApplication(); + + $newStatus = $app->input->getCmd('status'); + $paymentStatus = $app->input->getString('order_paymentstatus'); + $return = $app->input->getCmd('return'); + + $customerNote = $app->input->get('customer_note', array(), 'array'); + $customerNote = stripslashes($customerNote[0]); + + $oid = $app->input->get('order_id', array(), 'method', 'array'); + $orderId = (int)$oid[0]; + + $isProduct = $app->input->getInt('isproduct', 0); + $productId = $app->input->getInt('product_id', 0); + $orderItemId = $app->input->getInt('order_item_id', 0); + + // Get order detail before processing + $prevOrderStatus = RedshopEntityOrder::getInstance($orderId)->getItem()->order_status; + + if (isset($paymentStatus)) { + self::updateOrderPaymentStatus($orderId, $paymentStatus); + } + + JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/tables'); + $orderLog = JTable::getInstance('order_status_log', 'Table'); + + if (!$isProduct) { + $data['order_id'] = $orderId; + $data['order_status'] = $newStatus; + $data['order_payment_status'] = $paymentStatus; + $data['date_changed'] = time(); + $data['customer_note'] = $customerNote; + + if (!$orderLog->bind($data)) { + JFactory::getApplication()->enqueueMessage( + /** @scrutinizer ignore-deprecated */ $orderLog->getError(), + 'error' + ); + + return; + } + + if (!$orderLog->store()) { + throw new Exception(/** @scrutinizer ignore-deprecated */ $orderLog->getError()); + } + + self::updateOrderComment($orderId, $customerNote); + + $requisitionNumber = $app->input->getString('requisition_number', ''); + + if ('' != $requisitionNumber) { + self::updateOrderRequisitionNumber($orderId, $requisitionNumber); + } + + // Changing the status of the order + self::updateOrderStatus($orderId, $newStatus); + + // Trigger function on Order Status change + JPluginHelper::importPlugin('redshop_order'); + + RedshopHelperUtility::getDispatcher()->trigger( + 'onAfterOrderStatusUpdate', + array( + RedshopEntityOrder::getInstance($orderId)->getItem(), + $newStatus + ) + ); + + if ($paymentStatus == "Paid") { + JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_redshop/models'); + $checkoutModel = JModelLegacy::getInstance('Checkout', 'RedshopModel'); + $checkoutModel->sendGiftCard($orderId); + + // Send the Order mail + if (Redshop::getConfig()->get('ORDER_MAIL_AFTER') && $newStatus == 'C') { + if ( + JFactory::getApplication()->isClient('site') || + ( + JFactory::getApplication()->isClient('administrator') && + $app->input->getCmd('order_sendordermail') === 'true' + ) + ) { + // Only send email if order_sendordermail checked or frontend + Redshop\Mail\Order::sendMail($orderId); + } + } elseif (Redshop::getConfig()->get('INVOICE_MAIL_ENABLE')) { + Redshop\Mail\Invoice::sendMail($orderId); + } + } + + self::createWebPackLabel($orderId, $newStatus, $paymentStatus); + } + + self::updateOrderItemStatus($orderId, $productId, $newStatus, $customerNote, $orderItemId); + RedshopHelperClickatell::clickatellSMS($orderId); + + switch ($newStatus) { + // Cancel & return + case 'X': + case 'R': + + $orderProducts = self::getOrderItemDetail($orderId); + + for ($i = 0, $in = count($orderProducts); $i < $in; $i++) { + $prodid = $orderProducts[$i]->product_id; + $prodqty = $orderProducts[$i]->stockroom_quantity; + + // Do not process update stock if this order already "returned" before + if ($prevOrderStatus != 'RT') { + // When the order is set to "cancelled",product will return to stock + RedshopHelperStockroom::manageStockAmount($prodid, $prodqty, $orderProducts[$i]->stockroom_id); + } + + RedshopHelperProduct::makeAttributeOrder($orderProducts[$i]->order_item_id, 0, $prodid, 1); + } + + break; + + // Returned + case "RT": + + if ($isProduct) { + // Changing the status of the order item to Returned + self::updateOrderItemStatus($orderId, $productId, "RT", $customerNote, $orderItemId); + + // Changing the status of the order to Partially Returned + self::updateOrderStatus($orderId, "PRT"); + } + + break; + + case "RC": + + if ($isProduct) { + // Changing the status of the order item to Reclamation + self::updateOrderItemStatus($orderId, $productId, "RC", $customerNote, $orderItemId); + + // Changing the status of the order to Partially Reclamation + self::updateOrderStatus($orderId, "PRC"); + } + + break; + + // Shipped + case "S": + + if ($isProduct) { + // Changing the status of the order item to Reclamation + self::updateOrderItemStatus($orderId, $productId, "S", $customerNote, $orderItemId); + + // Changing the status of the order to Partially Reclamation + self::updateOrderStatus($orderId, "PS"); + } + + break; + + // Completed + case "C": + + // SensDownload Products + if ($paymentStatus == "Paid") { + self::sendDownload($orderId); + } + + break; + } + + RedshopHelperUtility::getDispatcher()->trigger( + 'sendOrderShipping', + array( + $orderId, + $paymentStatus, + $newStatus + ) + ); + + if ($app->input->getCmd('order_sendordermail') == 'true' && JFactory::getApplication()->isClient( + 'administrator' + )) { + self::changeOrderStatusMail($orderId, $newStatus, $customerNote); + } + + self::createBookInvoice($orderId, $newStatus); + + $msg = JText::_('COM_REDSHOP_ORDER_STATUS_SUCCESSFULLY_SAVED_FOR_ORDER_ID') . " " . $orderId; + + $isArchive = ($app->input->getInt('isarchive')) ? '&isarchive=1' : ''; + + if ($return == 'order') { + $app->redirect('index.php?option=com_redshop&view=' . $return . '' . $isArchive . '', $msg); + } else { + $tmpl = $app->input->getCmd('tmpl'); + + if ('' != $tmpl) { + $app->redirect( + 'index.php?option=com_redshop&view=' . $return . '&cid[]=' . $orderId . '&tmpl=' . $tmpl . '' . $isArchive . '', + $msg + ); + } else { + $app->redirect( + 'index.php?option=com_redshop&view=' . $return . '&cid[]=' . $orderId . '' . $isArchive . '', + $msg + ); + } + } + } + + /** + * Update Order Payment Status + * + * @param integer $orderId Order ID + * @param string $newStatus New status + * + * @return void + * + * @since 2.0.3 + * + * @deprecated 2.0.6 + */ + public static function updateOrderPaymentStatus($orderId, $newStatus) + { + $order = RedshopEntityOrder::getInstance($orderId); + + if ($order->isValid()) { + $order->set('order_payment_status', $newStatus) + ->set('mdate', time()) + ->save(); + } + } + + /** + * Update order comment + * + * @param integer $orderId Order ID + * @param string $comment New Comment + * + * @return void + * + * @since 2.0.3 + * + * @deprecated 2.0.6 + */ + public static function updateOrderComment($orderId, $comment = '') + { + $order = RedshopEntityOrder::getInstance($orderId); + + if ($order->isValid()) { + $order->set('customer_note', $comment) + ->save(); + } + } + + /** + * Update Order Requisition Number + * + * @param integer $orderId Order ID + * @param string $requisitionNumber Number required + * + * @return void + * + * @since 2.0.3 + */ + public static function updateOrderRequisitionNumber($orderId, $requisitionNumber = '') + { + $order = RedshopEntityOrder::getInstance($orderId); + + if (!$order->isValid()) { + return; + } + + $order->set('requisition_number', $requisitionNumber); + + if ($order->save()) { + // Economic Integration start for invoice generate and book current invoice + if (Redshop::getConfig()->get('ECONOMIC_INTEGRATION') == 1) { + RedshopEconomic::renewInvoiceInEconomic($order->getItem()); + } + } + } + + /** + * Update order status + * + * @param integer $orderId Order ID to update + * @param string $newStatus New status + * + * @return void + * + * @since 2.0.3 + */ + public static function updateOrderStatus($orderId, $newStatus) + { + $order = RedshopEntityOrder::getInstance($orderId); + + if ($order->get('order_status', '') == $newStatus) { + return; + } + + if ($order->isValid()) { + $order->set('order_status', $newStatus) + ->set('mdate', (int)time()) + ->save(); + } + + self::generateInvoiceNumber($orderId); + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select( + $db->qn( + array( + 'e.element', + 'op.order_transfee', + 'op.order_payment_trans_id', + 'op.order_payment_amount', + 'op.authorize_status' + ) + ) + ) + ->from($db->qn('#__extensions', 'e')) + ->leftJoin( + $db->qn('#__redshop_order_payment', 'op') . ' ON ' . $db->qn( + 'op.payment_method_class' + ) . ' = ' . $db->qn('e.element') + ) + ->where($db->qn('op.order_id') . ' = ' . (int)$orderId) + ->where($db->qn('e.folder') . ' = ' . $db->quote('redshop_payment')); + $result = $db->setQuery($query, 0, 1)->loadObject(); + + $authorizeStatus = $result->authorize_status; + + $paymentMethod = self::getPaymentMethodInfo($result->element); + $paymentMethod = $paymentMethod[0]; + + // Getting the order details + $orderDetail = RedshopEntityOrder::getInstance($orderId)->getItem(); + $paymentParams = new Registry($paymentMethod->params); + $orderStatusCapture = $paymentParams->get('capture_status', ''); + $orderStatusCode = $orderStatusCapture; + + if ($orderStatusCapture == $newStatus + && ($authorizeStatus == "Authorized" || $authorizeStatus == "")) { + $values["order_number"] = $orderDetail->order_number; + $values["order_id"] = $orderId; + $values["order_transactionid"] = $result->order_payment_trans_id; + $values["order_amount"] = $orderDetail->order_total + $result->order_transfee; + $values['shippinginfo'] = self::getOrderShippingUserInfo($orderId); + $values['billinginfo'] = self::getOrderBillingUserInfo($orderId); + $values["order_userid"] = $values['billinginfo']->user_id; + + JPluginHelper::importPlugin('redshop_payment'); + $data = RedshopHelperUtility::getDispatcher()->trigger( + 'onCapture_Payment' . $result->element, + array($result->element, $values) + ); + $results = $data[0]; + + if (!empty($data)) { + $message = $results->message; + + $orderStatusLog = JTable::getInstance('order_status_log', 'Table'); + $orderStatusLog->order_id = $orderId; + $orderStatusLog->order_status = $orderStatusCode; + $orderStatusLog->date_changed = time(); + $orderStatusLog->customer_note = $message; + $orderStatusLog->store(); + } + } + + if (($newStatus == "X" || $newStatus == "R") + && $paymentParams->get('refund', 0) == 1) { + $values["order_number"] = $orderDetail->order_number; + $values["order_id"] = $orderId; + $values["order_transactionid"] = $result->order_payment_trans_id; + $values["order_amount"] = $orderDetail->order_total + $result->order_transfee; + $values["order_userid"] = $values['billinginfo']->user_id; + + JPluginHelper::importPlugin('redshop_payment'); + + // Get status and refund if capture/cancel if authorize (for quickpay only) + $data = RedshopHelperUtility::getDispatcher()->trigger( + 'onStatus_Payment' . $result->element, + array($result->element, $values) + ); + $results = $data[0]; + + if (!empty($data)) { + $message = $results->message; + $orderStatusLog = JTable::getInstance('order_status_log', 'Table'); + $orderStatusLog->order_id = $orderId; + $orderStatusLog->order_status = $newStatus; + $orderStatusLog->date_changed = time(); + $orderStatusLog->customer_note = $message; + $orderStatusLog->store(); + } + } + } + + /** + * Update Order Item Status + * + * @param integer $orderId Order id + * @param integer $productId Product id + * @param string $newStatus New status + * @param string $comment Comment + * @param integer $orderItemId Order item id + * + * @return void + * + * @since 2.0.3 + */ + public static function updateOrderItemStatus( + $orderId = 0, + $productId = 0, + $newStatus = '', + $comment = '', + $orderItemId = 0 + ) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_order_item')) + ->set($db->qn('order_status') . ' = ' . $db->q($newStatus)) + ->where($db->qn('order_id') . ' = ' . (int)$orderId); + + if ($productId != 0) { + $query->set($db->qn('customer_note') . ' = ' . $db->q($comment)) + ->where($db->qn('product_id') . ' = ' . (int)$productId); + } + + if ($orderItemId != 0) { + $query->where($db->qn('order_item_id') . ' = ' . (int)$orderItemId); + } + + $db->setQuery($query); + + if (!$db->execute()) { + JFactory::getApplication()->enqueueMessage( + /** @scrutinizer ignore-deprecated */ $db->getErrorMsg(), + 'error' + ); + } + } + + /** + * Get list order details + * + * @param integer $orderId Order ID + * + * @return object + * + * @since 2.0.3 + * @deprecated Use RedshopEntityOrder::getInstance($orderId)->getItem(); + */ + public static function getMultiOrderDetails($orderId) + { + return RedshopEntityOrder::getInstance($orderId)->getItem(); + } + + /** + * Get User Order Details + * + * @param integer $userId User ID + * + * @return mixed + * + * @since 2.0.3 + */ + public static function getUserOrderDetails($userId = 0) + { + $db = JFactory::getDbo(); + $user = JFactory::getUser(); + + if ($userId == 0) { + $userId = $user->id; + } + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_orders')) + ->where($db->qn('user_id') . ' = ' . (int)$userId) + ->order($db->qn('order_id')); + $db->setQuery($query); + + return $db->loadObjectlist(); + } + + /** + * Get Order Partial Payment + * + * @param integer $orderId Order ID + * + * @return array + * + * @since 2.0.3 + */ + public static function getOrderPartialPayment($orderId) + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->qn('order_payment_amount')) + ->from($db->qn('#__redshop_order_payment')) + ->where($db->qn('order_id') . ' = ' . (int)$orderId); + $db->setQuery($query); + $list = $db->loadObjectlist(); + + $spiltPaymentAmount = 0; + + for ($i = 0, $in = count($list); $i < $in; $i++) { + if ($list[$i]->order_payment_amount > 0) { + $spiltPaymentAmount = $list[$i]->order_payment_amount; + } + } + + return $spiltPaymentAmount; + } + + /** + * Get Shipping Method Info + * + * @param string $shippingClass Shipping class + * + * @return array + * + * @since 2.0.3 + */ + public static function getShippingMethodInfo($shippingClass = '') + { + $key = (!empty($shippingClass)) ? $shippingClass : '0'; + + if (!array_key_exists($key, static::$shippingMethods)) { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__extensions')) + ->where($db->qn('enabled') . ' = ' . $db->quote('1')) + ->where('LOWER(' . $db->qn('folder') . ') = ' . $db->quote('redshop_shipping')) + ->order($db->qn('ordering') . ' ASC'); + + if (!empty($shippingClass)) { + $query->where($db->qn('element') . ' = ' . $db->quote($shippingClass)); + } + + static::$shippingMethods = $db->setQuery($query)->loadObjectList(); + } + + return static::$shippingMethods; + } + + /** + * Get billing address + * + * @param integer $userId User ID + * + * @return object|false|null Object data if success. False otherwise. + * + * @since 2.0.3 + */ + public static function getBillingAddress($userId = 0) + { + if ($userId == 0) { + $user = JFactory::getUser(); + $userId = $user->id; + } + + if (!$userId) { + return false; + } + + if (!array_key_exists($userId, static::$billingAddresses)) { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->select('CONCAT(' . $db->qn('firstname') . '," ",' . $db->qn('lastname') . ') AS text') + ->from($db->qn('#__redshop_users_info')) + ->where($db->qn('address_type') . ' = ' . $db->quote('BT')); + + if ((int)$userId < 0) { + $query->where($db->qn('users_info_id') . ' = ' . abs((int)$userId)); + } else { + $query->where($db->qn('user_id') . ' = ' . (int)$userId); + } + + + static::$billingAddresses[$userId] = $db->setQuery($query)->loadObject(); + } + + return static::$billingAddresses[$userId]; + } + + /** + * Get Shipping address + * + * @param integer $userId User Id + * + * @return array + * + * @since 2.0.3 + */ + public static function getShippingAddress($userId = 0) + { + if ($userId == 0) { + $user = JFactory::getUser(); + $userId = $user->id; + } + + if (!$userId) { + return false; + } + + if (!array_key_exists($userId, static::$shippingAddresses)) { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->select('CONCAT(' . $db->qn('firstname') . '," ",' . $db->qn('lastname') . ') AS text') + ->from($db->qn('#__redshop_users_info')) + ->where($db->qn('address_type') . ' = ' . $db->quote('ST')) + ->where($db->qn('user_id') . ' = ' . (int)$userId); + + static::$shippingAddresses[$userId] = $db->setQuery($query)->loadObjectList(); + } + + return static::$shippingAddresses[$userId]; + } + + /** + * Get User full name + * + * @param integer $userId User ID + * + * @return string + * + * @since 2.0.3 + */ + public static function getUserFullName($userId) + { + $fullName = ""; + $user = JFactory::getUser(); + $db = JFactory::getDbo(); + + if ($userId == 0) { + $userId = $user->id; + } + + $query = $db->getQuery(true) + ->select($db->qn(array('firstname', 'lastname'))) + ->from($db->qn('#__redshop_users_info')) + ->where($db->qn('address_type') . ' LIKE ' . $db->quote('BT')) + ->where($db->qn('user_id') . ' = ' . (int)$userId); + $db->setQuery($query); + $list = $db->loadObject(); + + if ($list) { + $fullName = $list->firstname . " " . $list->lastname; + } else { + $query = $db->getQuery(true) + ->select($db->qn('name')) + ->from($db->qn('#__users')) + ->where($db->qn('id') . ' = ' . (int)$userId); + $db->setQuery($query); + $list = $db->loadObject(); + + if ($list) { + $fullName = $list->name; + } + } + + return $fullName; + } + + /** + * Get order item attribute detail + * + * @param integer $orderItemId Order Item ID + * @param integer $isAccessory Is accessory + * @param string $section Section text + * @param integer $parentSectionId Parent section ID + * + * @return array + * + * @since 2.0.3 + */ + public static function getOrderItemAttributeDetail( + $orderItemId = 0, + $isAccessory = 0, + $section = "attribute", + $parentSectionId = 0 + ) { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_order_attribute_item')) + ->where($db->qn('is_accessory_att') . ' = ' . (int)$isAccessory) + ->where($db->qn('section') . ' = ' . $db->quote($section)); + + if ($orderItemId != 0) { + $query->where($db->qn('order_item_id') . ' = ' . (int)$orderItemId); + } + + if ($parentSectionId != 0) { + $query->where($db->qn('parent_section_id') . ' = ' . (int)$parentSectionId); + } + + $db->setQuery($query); + + return $db->loadObjectlist(); + } + + /** + * Get Order User Field Data + * + * @param integer $orderItemId Order Item ID + * @param integer $section Section ID + * + * @return object|mixed + * + * @since 2.0.3 + */ + public static function getOrderUserFieldData($orderItemId = 0, $section = 0) + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('fd.*') + ->select($db->qn(array('f.title', 'f.type', 'f.name'))) + ->from($db->qn('#__redshop_fields_data', 'fd')) + ->leftJoin($db->qn('#__redshop_fields', 'f') . ' ON ' . $db->qn('f.id') . ' = ' . $db->qn('fd.fieldid')) + ->where($db->qn('fd.itemid') . ' = ' . (int)$orderItemId) + ->where($db->qn('fd.section') . ' = ' . $db->quote($section)); + + return $db->setQuery($query)->loadObjectList(); + } + + /** + * Generate Order Number + * + * @return integer + * + * @since 2.0.3 + */ + public static function generateOrderNumber() + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('MAX(' . $db->qn('order_id') . ')') + ->from($db->qn('#__redshop_orders')); + $db->setQuery($query); + $maxId = $db->loadResult(); + + /* + * if Economic Integration is on !!! + * We are not using Order Invoice Number Template + * Economic Order Number Only Support (int) value. + * Invoice Number May be varchar or int. + */ + if (Redshop::getConfig()->get('ECONOMIC_INTEGRATION') && JPluginHelper::isEnabled('economic')) { + $query = $db->getQuery(true) + ->select($db->qn('order_number')) + ->from($db->qn('#__redshop_orders')) + ->where($db->qn('order_id') . ' = ' . (int)$maxId); + $db->setQuery($query); + + $maxOrderNumber = $db->loadResult(); + $maxInvoice = RedshopEconomic::getMaxOrderNumberInEconomic(); + $maxId = max((int)$maxOrderNumber, $maxInvoice); + } elseif (Redshop::getConfig()->get('INVOICE_NUMBER_TEMPLATE')) { + $maxId = ($maxId + Redshop::getConfig()->get('FIRST_INVOICE_NUMBER') + 1); + + return self::parseNumberTemplate( + Redshop::getConfig()->get('INVOICE_NUMBER_TEMPLATE'), + $maxId + ); + } + + return $maxId + 1; + } + + /** + * Random Generate Encrypt Key + * + * @param string $pLength Length of string + * + * @return string + * + * @since 2.0.3 + * @deprecated Use \Redshop\Crypto\Helper\Encrypt::generateCustomRandomEncryptKey + */ + public static function randomGenerateEncryptKey($pLength = '30') + { + return \Redshop\Crypto\Helper\Encrypt::generateCustomRandomEncryptKey((int)$pLength); + } + + /** + * Get Country name by 3 characters of country code + * + * @param string $cnt3 Country code + * + * @return string + * + * @since 2.0.3 + */ + public static function getCountryName($cnt3 = '') + { + if (empty($cnt3)) { + return ''; + } + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->qn('country_3_code', 'value')) + ->select($db->qn('country_name', 'text')) + ->select($db->qn('country_jtext')) + ->from($db->qn('#__redshop_country')); + + if ($cnt3 != '') { + $query->where($db->qn('country_3_code') . ' = ' . $db->quote($cnt3)); + } + + $countries = $db->setQuery($query)->loadObjectList(); + + $countries = RedshopHelperUtility::convertLanguageString($countries); + + if (count($countries) > 0) { + return $countries[0]->text; + } + + return ''; + } + + /** + * Get state name + * + * @param string $st3 State code + * @param string $cnt3 Country code + * + * @return string + * + * @since 2.0.3 + */ + public static function getStateName($st3 = "", $cnt3 = "") + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->qn('s.state_name')) + ->from($db->qn('#__redshop_state', 's')) + ->leftJoin($db->qn('#__redshop_country', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('s.country_id')); + + if ($st3 != "") { + $query->where($db->qn('s.state_2_code') . ' = ' . $db->quote($st3)); + } + + if ($cnt3 != "") { + $query->where($db->qn('c.country_3_code') . ' = ' . $db->quote($cnt3)); + } + + $db->setQuery($query); + + return $db->loadResult(); + } + + /** + * Get download product log + * + * @param integer $orderId Order Id + * @param string $did Download id + * + * @return array + * + * @since 2.0.3 + */ + public static function getDownloadProductLog($orderId, $did = '') + { + $key = $orderId . '_' . $did; + + if (!array_key_exists($key, self::$orderProductsDownloadLog)) { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('pdl.*') + ->select($db->qn(array('pd.order_id', 'pd.product_id', 'pd.file_name'))) + ->from($db->qn('#__redshop_product_download_log', 'pdl')) + ->leftJoin( + $db->qn('#__redshop_product_download', 'pd') . ' ON ' . $db->qn('pd.download_id') . ' = ' . $db->qn( + 'pdl.download_id' + ) + ) + ->where($db->qn('pd.order_id') . ' = ' . (int)$orderId); + + if ($did != '') { + $query->where($db->qn('pdl.download_id') . ' = ' . $db->quote($did)); + } + + self::$orderProductsDownloadLog[$key] = $db->setQuery($query)->loadObjectList(); + } + + return self::$orderProductsDownloadLog[$key]; + } + + /** + * Get payment information + * + * @param object $row Payment info row + * @param array $post payment method class + * + * @return void + * + * @since 2.0.3 + */ + public static function getPaymentInformation($row, $post) + { + $app = JFactory::getApplication(); + $pluginParameters = self::getParameters($post['payment_method_class']); + $paymentInfo = $pluginParameters[0]; + $paymentParams = new Registry($paymentInfo->params); + + $isCreditCard = $paymentParams->get('is_creditcard', ''); + + $order = self::getOrderDetails($row->order_id); + + if ($userBillingInfo = self::getOrderBillingUserInfo($row->order_id)) { + $userBillingInfo->country_2_code = RedshopHelperWorld::getCountryCode2($userBillingInfo->country_code); + $userBillingInfo->state_2_code = RedshopHelperWorld::getStateCode2($userBillingInfo->state_code); + } + + $task = $app->input->getCmd('task'); + + if ($shippingAddress = self::getOrderShippingUserInfo($row->order_id)) { + $shippingAddress->country_2_code = RedshopHelperWorld::getCountryCode2($shippingAddress->country_code); + $shippingAddress->state_2_code = RedshopHelperWorld::getStateCode2($shippingAddress->state_code); + } + + $values = array(); + $values['shippinginfo'] = $shippingAddress; + $values['billinginfo'] = $userBillingInfo; + $values['carttotal'] = $order->order_total; + $values['order_subtotal'] = $order->order_subtotal; + $values["order_id"] = $row->order_id; + $values['payment_plugin'] = $post['payment_method_class']; + $values['task'] = $task; + $values['order'] = $order; + + if ($isCreditCard == 0) { + // Check for bank transfer payment type plugin - `rs_payment_banktransfer` suffixed + $isBankTransferPaymentType = RedshopHelperPayment::isPaymentType($values['payment_plugin']); + + if ($isBankTransferPaymentType) { + $app->redirect( + JUri::base() . "index.php?option=com_redshop&view=order_detail&layout=creditcardpayment&plugin=" + . $values['payment_plugin'] . "&order_id=" . $row->order_id + ); + } + + JPluginHelper::importPlugin('redshop_payment'); + RedshopHelperUtility::getDispatcher()->trigger('onPrePayment', array($values['payment_plugin'], $values)); + + $app->redirect( + JUri::base() . "index.php?option=com_redshop&view=order_detail&task=edit&cid[]=" . $row->order_id + ); + } else { + $app->redirect( + JUri::base() . "index.php?option=com_redshop&view=order_detail&layout=creditcardpayment&plugin=" + . $values['payment_plugin'] . "&order_id=" . $row->order_id + ); + } + } + + /** + * Get payment parameters + * + * @param string $payment Payment type + * + * @return array + * + * @since 2.0.3 + */ + public static function getParameters($payment) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__extensions')) + ->where($db->qn('element') . ' = ' . $db->quote($payment)); + $db->setQuery($query); + + return $db->loadObjectList(); + } + + /** + * Get shipping location information + * + * @param string $shippingName Shipping name + * + * @return object|mixed + * + * @since 2.0.3 + */ + public static function getShippingLocationInfo($shippingName) + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->qn('shipping_location_info')) + ->from($db->qn('#__redshop_shipping_rate')) + ->where($db->qn('shipping_rate_name') . ' = ' . $db->quote($shippingName)); + + $db->setQuery($query); + + return $db->loadObjectList(); + } + + /** + * Create Multi Print Invoice PDF + * + * @param array $orderIds Order ID + * + * @return string File name of generated pdf. + * + * @since 2.0.3 + */ + public static function createMultiPrintInvoicePdf($orderIds) + { + return RedshopHelperMail::createMultiprintInvoicePdf($orderIds); + } + + /** + * Method for generate Invoice PDF of specific Order + * + * @param int $orderId ID of order. + * @param string $code Code when generate PDF. + * @param boolean $isEmail Is generate for use in Email? + * + * @return void + * + * @since 2.0.3 + */ + public static function generateInvoicePdf($orderId, $code = 'F', $isEmail = false) + { + if (!$orderId) { + return; + } + + $plugins = JPluginHelper::getPlugin('redshop_pdf'); + + if (empty($plugins)) { + return; + } + + $orderDetail = self::getOrderDetails($orderId); + $orderTemplate = RedshopHelperTemplate::getTemplate('order_print'); + + if (count($orderTemplate) > 0 && $orderTemplate[0]->template_desc != "") { + $message = $orderTemplate[0]->template_desc; + } else { + $message = '
    @@ -2734,219 +2718,156 @@ public static function generateInvoicePdf($orderId, $code = 'F', $isEmail = fals
    {order_information_lbl}{print}
    {order_id_lbl} : {order_id}
    {order_number_lbl} : {order_number}

    {total_lbl} : {order_total}



    '; - } - - $print_tag = "" - . "" . JText::_("; - - $message = str_replace("{print}", $print_tag, $message); - $message = str_replace("{order_mail_intro_text_title}", JText::_('COM_REDSHOP_ORDER_MAIL_INTRO_TEXT_TITLE'), $message); - $message = str_replace("{order_mail_intro_text}", JText::_('COM_REDSHOP_ORDER_MAIL_INTRO_TEXT'), $message); - - $message = Template::replaceTemplate($orderDetail, $message, true); - - JPluginHelper::importPlugin('redshop_pdf'); - RedshopHelperUtility::getDispatcher()->trigger('onRedshopOrderCreateInvoicePdf', array($orderId, $message, $code, $isEmail)); - } - - /** - * Create PacSoft Label from Order Status Change functions - * - * @param integer $orderId Order Information ID - * @param string $orderStatus Order Status Code - * @param string $paymentStatus Order Payment Status Code - * - * @return void - * - * @since 2.0.3 - */ - public static function createWebPackLabel($orderId, $orderStatus, $paymentStatus) - { - // If PacSoft is not enable then return - if (!Redshop::getConfig()->get('POSTDK_INTEGRATION')) - { - return; - } - - // If auto generation is disable then return - if (!Redshop::getConfig()->get('AUTO_GENERATE_LABEL')) - { - return; - } - - // Only Execute this function for selected status match - if ($orderStatus == Redshop::getConfig()->get('GENERATE_LABEL_ON_STATUS') && $paymentStatus == "Paid") - { - $orderDetails = self::getOrderDetails($orderId); - $details = Redshop\Shipping\Rate::decrypt($orderDetails->ship_method_id); - - $shippingParams = new Registry( - JPluginHelper::getPlugin( - 'redshop_shipping', - str_replace( - 'plgredshop_shipping', - '', - strtolower($details[0]) - ) - )->params - ); - - // Checking 'plgredshop_shippingdefault_shipping' to support backward compatibility - $allowPacsoftLabel = ($details[0] === 'plgredshop_shippingdefault_shipping' || (boolean) $shippingParams->get('allowPacsoftLabel')); - - if ($allowPacsoftLabel && !$orderDetails->order_label_create) - { - $generateLabel = self::generateParcel($orderId); - - if ($generateLabel != "success") - { - JFactory::getApplication()->enqueueMessage($generateLabel, 'error'); - } - } - } - } - - /** - * Order status update - * - * @param integer $orderId Order ID - * @param array $post Post array - * - * @return boolean|mixed - * - * @since 2.0.3 - */ - public static function orderStatusUpdate($orderId, $post = array()) - { - $newStatus = $post['mass_change_order_status']; - $customerNote = $post['customer_note' . $orderId]; - $isProduct = (isset($post['isproduct'])) ? $post['isproduct'] : 0; - $productId = (isset($post['product_id'])) ? $post['product_id'] : 0; - $paymentStatus = $post['mass_change_payment_status']; - - JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/tables'); - - // Add status log... - $orderLog = JTable::getInstance('order_status_log', 'Table'); - $orderLog->order_id = $customerNote; - $orderLog->customer_note = $customerNote; - $orderLog->order_status = $newStatus; - $orderLog->date_changed = time(); - - if (!$orderLog->store()) - { - return /** @scrutinizer ignore-deprecated */ JError::raiseWarning('', /** @scrutinizer ignore-deprecated */ $orderLog->getError()); - } - - // Changing the status of the order - self::updateOrderStatus($orderId, $newStatus); - - // Changing the status of the order - if (isset($paymentStatus)) - { - self::updateOrderPaymentStatus($orderId, $paymentStatus); - } - - if ($post['isPacsoft']) - { - // For Webpack Postdk Label Generation - self::createWebPackLabel($orderId, $newStatus, $paymentStatus); - } - - if (Redshop::getConfig()->get('CLICKATELL_ENABLE')) - { - // Changing the status of the order end - RedshopHelperClickatell::clickatellSMS($orderId); - } - - // If changing the status of the order then there item status need to change - if ($isProduct != 1) - { - self::updateOrderItemStatus($orderId, 0, $newStatus); - } - - // If order is cancelled then - if ($newStatus == 'X') - { - $orderProducts = self::getOrderItemDetail($orderId); - - for ($j = 0, $jn = count($orderProducts); $j < $jn; $j++) - { - $prodid = $orderProducts[$j]->product_id; - $prodqty = $orderProducts[$j]->stockroom_quantity; - - // When the order is set to "cancelled",product will return to stock - RedshopHelperStockroom::manageStockAmount($prodid, $prodqty, $orderProducts[$j]->stockroom_id); - RedshopHelperProduct::makeAttributeOrder($orderProducts[$j]->order_item_id, 0, $prodid, 1); - } - } - elseif ($newStatus == 'RT') - { - // If any of the item from the order is returuned back then, - // change the status of whole order and also put back to stock. - if ($isProduct) - { - $orderProductDetail = self::getOrderItemDetail($orderId, $productId); - $prodid = $orderProductDetail[0]->product_id; - - // Changing the status of the order item to Returned - self::updateOrderItemStatus($orderId, $prodid, "RT"); - - // Changing the status of the order to Partially Returned - self::updateOrderStatus($orderId, "PRT"); - } - } - elseif ($newStatus == 'RC') - { - // If any of the item from the order is reclamation back then, - // change the status of whole order and also put back to stock. - if ($isProduct) - { - // Changing the status of the order item to Reclamation - self::updateOrderItemStatus($orderId, $productId, "RC"); - - // Changing the status of the order to Partially Reclamation - self::updateOrderStatus($orderId, "PRC"); - } - } - elseif ($newStatus == 'S') - { - if ($isProduct) - { - // Changing the status of the order item to Reclamation - self::updateOrderItemStatus($orderId, $productId, "S"); - - // Changing the status of the order to Partially Reclamation - self::updateOrderStatus($orderId, "PS"); - } - } - - // Mail to customer of order status change - if ($post['mass_mail_sending'] == 1) - { - self::changeOrderStatusMail($orderId, $newStatus, $customerNote); - } - - self::createBookInvoice($orderId, $newStatus); - - // GENERATE PDF CODE WRITE - return true; - } - - /** - * Get Order Payment Detail - * - * @param int $orderPaymentId Payment order id - * - * @return object Order payment info - * - * @since 2.0.3 - * - * @deprecated 2.0.6 - */ - public static function getOrderPaymentDetail($orderPaymentId = 0) - { - return RedshopEntityOrder_Payment::getInstance($orderPaymentId)->getItem(); - } + } + + $print_tag = "" + . "" . JText::_("; + + $message = str_replace("{print}", $print_tag, $message); + $message = str_replace( + "{order_mail_intro_text_title}", + JText::_('COM_REDSHOP_ORDER_MAIL_INTRO_TEXT_TITLE'), + $message + ); + $message = str_replace("{order_mail_intro_text}", JText::_('COM_REDSHOP_ORDER_MAIL_INTRO_TEXT'), $message); + + $message = Template::replaceTemplate($orderDetail, $message, true); + + JPluginHelper::importPlugin('redshop_pdf'); + RedshopHelperUtility::getDispatcher()->trigger( + 'onRedshopOrderCreateInvoicePdf', + array($orderId, $message, $code, $isEmail) + ); + } + + /** + * Order status update + * + * @param integer $orderId Order ID + * @param array $post Post array + * + * @return boolean|mixed + * + * @since 2.0.3 + */ + public static function orderStatusUpdate($orderId, $post = array()) + { + $newStatus = $post['mass_change_order_status']; + $customerNote = $post['customer_note' . $orderId]; + $isProduct = (isset($post['isproduct'])) ? $post['isproduct'] : 0; + $productId = (isset($post['product_id'])) ? $post['product_id'] : 0; + $paymentStatus = $post['mass_change_payment_status']; + + JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_redshop/tables'); + + // Add status log... + $orderLog = JTable::getInstance('order_status_log', 'Table'); + $orderLog->order_id = $customerNote; + $orderLog->customer_note = $customerNote; + $orderLog->order_status = $newStatus; + $orderLog->date_changed = time(); + + if (!$orderLog->store()) { + return /** @scrutinizer ignore-deprecated */ JError::raiseWarning( + '', + /** @scrutinizer ignore-deprecated */ + $orderLog->getError() + ); + } + + // Changing the status of the order + self::updateOrderStatus($orderId, $newStatus); + + // Changing the status of the order + if (isset($paymentStatus)) { + self::updateOrderPaymentStatus($orderId, $paymentStatus); + } + + if ($post['isPacsoft']) { + // For Webpack Postdk Label Generation + self::createWebPackLabel($orderId, $newStatus, $paymentStatus); + } + + if (Redshop::getConfig()->get('CLICKATELL_ENABLE')) { + // Changing the status of the order end + RedshopHelperClickatell::clickatellSMS($orderId); + } + + // If changing the status of the order then there item status need to change + if ($isProduct != 1) { + self::updateOrderItemStatus($orderId, 0, $newStatus); + } + + // If order is cancelled then + if ($newStatus == 'X') { + $orderProducts = self::getOrderItemDetail($orderId); + + for ($j = 0, $jn = count($orderProducts); $j < $jn; $j++) { + $prodid = $orderProducts[$j]->product_id; + $prodqty = $orderProducts[$j]->stockroom_quantity; + + // When the order is set to "cancelled",product will return to stock + RedshopHelperStockroom::manageStockAmount($prodid, $prodqty, $orderProducts[$j]->stockroom_id); + RedshopHelperProduct::makeAttributeOrder($orderProducts[$j]->order_item_id, 0, $prodid, 1); + } + } elseif ($newStatus == 'RT') { + // If any of the item from the order is returuned back then, + // change the status of whole order and also put back to stock. + if ($isProduct) { + $orderProductDetail = self::getOrderItemDetail($orderId, $productId); + $prodid = $orderProductDetail[0]->product_id; + + // Changing the status of the order item to Returned + self::updateOrderItemStatus($orderId, $prodid, "RT"); + + // Changing the status of the order to Partially Returned + self::updateOrderStatus($orderId, "PRT"); + } + } elseif ($newStatus == 'RC') { + // If any of the item from the order is reclamation back then, + // change the status of whole order and also put back to stock. + if ($isProduct) { + // Changing the status of the order item to Reclamation + self::updateOrderItemStatus($orderId, $productId, "RC"); + + // Changing the status of the order to Partially Reclamation + self::updateOrderStatus($orderId, "PRC"); + } + } elseif ($newStatus == 'S') { + if ($isProduct) { + // Changing the status of the order item to Reclamation + self::updateOrderItemStatus($orderId, $productId, "S"); + + // Changing the status of the order to Partially Reclamation + self::updateOrderStatus($orderId, "PS"); + } + } + + // Mail to customer of order status change + if ($post['mass_mail_sending'] == 1) { + self::changeOrderStatusMail($orderId, $newStatus, $customerNote); + } + + self::createBookInvoice($orderId, $newStatus); + + // GENERATE PDF CODE WRITE + return true; + } + + /** + * Get Order Payment Detail + * + * @param int $orderPaymentId Payment order id + * + * @return object Order payment info + * + * @since 2.0.3 + * + * @deprecated 2.0.6 + */ + public static function getOrderPaymentDetail($orderPaymentId = 0) + { + return RedshopEntityOrder_Payment::getInstance($orderPaymentId)->getItem(); + } } diff --git a/libraries/redshop/helper/payment.php b/libraries/redshop/helper/payment.php index c022874a303..244bc1b4482 100644 --- a/libraries/redshop/helper/payment.php +++ b/libraries/redshop/helper/payment.php @@ -19,501 +19,483 @@ */ class RedshopHelperPayment { - /** - * Payment Method type constant - */ - const TYPE = 'redshop_payment'; - - /** - * Check for specific payment group type plugin - suffixed using given `type` - * Specially Checking for suffixed using `rs_payment_banktransfer` plugin - * - * @param string $name Payment Plugin Element Name - * @param string $typeSuffix Suffix to match - * - * @return boolean True when position found else false - */ - public static function isPaymentType($name, $typeSuffix = 'rs_payment_banktransfer') - { - $position = strpos($name, $typeSuffix); - - // Return false when given suffix is not found in string - if ($position === false) - { - return false; - } - - // True when position found - return true; - } - - /** - * Get payment method info - * - * @param string $name Payment Method name - Null to get all plugin info - * - * @return mixed Object is return one payment method, array for all. - * - * @throws Exception - */ - public static function info($name = '') - { - if (!JPluginHelper::isEnabled(self::TYPE, $name)) - { - throw new Exception(JText::sprintf('COM_REDSHOP_PAYMENT_IS_NOT_ENABLED', $name)); - } - - $plugins = JPluginHelper::getPlugin(self::TYPE, $name); - - if ($name == '' && is_array($plugins)) - { - array_walk($plugins, function (&$plugin) - { - $plugin->params = new Registry($plugin->params); - }); - } - else - { - $plugins->params = new Registry($plugins->params); - } - - return $plugins; - } - - /** - * Load payment languages - * - * @param boolean $all True for all (discover, enabled, disabled). False for just enabled only. - * - * @return void - * - * @since 2.0.2 - */ - public static function loadLanguages($all = false) - { - // Load payment plugin language file - if ($all) - { - $paymentsLangList = RedshopHelperUtility::getPlugins("redshop_payment"); - } - else - { - $paymentsLangList = RedshopHelperUtility::getPlugins("redshop_payment", 1); - } - - $language = JFactory::getLanguage(); - - for ($index = 0, $ln = count($paymentsLangList); $index < $ln; $index++) - { - $extension = 'plg_redshop_payment_' . $paymentsLangList[$index]->element; - $language->load($extension, JPATH_ADMINISTRATOR, $language->getTag(), true); - $language->load( - $extension, - JPATH_PLUGINS . '/' . $paymentsLangList[$index]->folder . '/' . $paymentsLangList[$index]->element, - $language->getTag(), - true - ); - } - } - - /** - * Method for check if order has this payment is update yet? - * - * @param integer $orderId Order ID - * @param mixed $transactionId Order payment transaction id - * - * @return boolean - * - * @since 2.0.6 - */ - public static function orderPaymentNotYetUpdated($orderId, $transactionId) - { - if (empty($orderId) || empty($transactionId)) - { - return false; - } - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('COUNT(*)') - ->from($db->qn('#__redshop_order_payment')) - ->where($db->qn('order_id') . ' = ' . (int) $orderId) - ->where($db->qn('order_payment_trans_id') . ' = ' . $db->quote((int) $transactionId)); - - $result = $db->setQuery($query)->loadResult(); - - if (!$result) - { - return true; - } - - return false; - } - - /** - * Replace conditional tag from Redshop payment Discount/charges - * - * @param string $template Template html - * @param integer $amount Amount of cart - * @param integer $cart Is in cart? - * @param string $paymentOprand Payment oprand - * - * @return string - * - * @since 2.0.7 - */ - public static function replaceConditionTag($template = '', $amount = 0, $cart = 0, $paymentOprand = '-') - { - if (strpos($template, '{if payment_discount}') === false || strpos($template, '{payment_discount end if}') === false) - { - return $template; - } - - if ($cart == 1 || $amount == 0) - { - $templateDiscountStart = explode('{if payment_discount}', $template); - $templateDiscountEnd = explode('{payment_discount end if}', $templateDiscountStart[1]); - - return $templateDiscountStart[0] . $templateDiscountEnd[1]; - } - - if ($amount <= 0) - { - $templateStart = explode('{if payment_discount}', $template); - $templateEnd = explode('{payment_discount end if}', $templateStart[1]); - - return $templateStart[0] . $templateEnd[1]; - } - - $template = str_replace("{payment_order_discount}", RedshopHelperProductPrice::formattedPrice($amount), $template); - $payText = ($paymentOprand == '+') ? JText::_('COM_REDSHOP_PAYMENT_CHARGES_LBL') : JText::_('COM_REDSHOP_PAYMENT_DISCOUNT_LBL'); - $template = str_replace("{payment_discount_lbl}", $payText, $template); - $template = str_replace("{payment_discount end if}", '', $template); - $template = str_replace("{if payment_discount}", '', $template); - - return $template; - } - - /** - * List all categories and return HTML format - * - * @param string $name Name of list - * @param integer $productId Only product to show - * @param integer $size Size of dropdown - * @param boolean $multiple Dropdown is multiple or not - * @param integer $width Width in pixel - * - * @return string HTML of dropdown - * - * @since 2.1.0 - * - * @throws Exception - */ - public static function listAll($name, $productId, $size = 1, $multiple = false, $width = 250) - { - $db = JFactory::getDbo(); - $html = ''; - $query = $db->getQuery(true) - ->select($db->qn('payment_id')) - ->from($db->qn('#__redshop_product_payment_xref')); - - if ($productId) - { - $query->where($db->qn('product_id') . ' = ' . $db->q((int) $productId)); - } - - $selectedPayments = $db->setQuery($query)->loadObjectList(); - - if ($selectedPayments) - { - $selectedPayments = array_column($selectedPayments, 'payment_id'); - } - - $multiple = $multiple ? "multiple=\"multiple\"" : ""; - $id = str_replace('[]', '', $name); - $html .= "\n"; - - return $html; - } - - /** - * Get payment method by id product - * - * @param integer $productId Only product to show - * - * @return array - * - * @since 2.1.0 - * - * @throws Exception - */ - public static function getPaymentByIdProduct($productId) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('payment_id')) - ->from($db->qn('#__redshop_product_payment_xref')) - ->where($db->qn('product_id') . ' = ' . $db->q((int) $productId)); - - return $db->setQuery($query)->loadColumn(); - } - - /** - * List payment into dropdown - * - * @param array $selectedPayments Only show selected payments - * @param string $html Before HTML - * - * @return string HTML of - * - * @since 2.1.0 - * - * @throws Exception - */ - public static function listTree($selectedPayments = array(), $html = '') - { - self::loadLanguages(); - - $paymentMethods = self::info(); - - if (empty($paymentMethods)) - { - return $html; - } - - $userBrowser = new Parser($_SERVER['HTTP_USER_AGENT']); - $isMsIE = $userBrowser->browser->isFamily('Internet Explorer'); - - foreach ($paymentMethods as $p => $oneMethod) - { - $paymentPath = JPATH_SITE . '/plugins/redshop_payment/' . $oneMethod->name . '/' . $oneMethod->name . '.php'; - - include_once $paymentPath; - - $value = $oneMethod->name; - $disabled = ''; - $selected = ''; - - if (in_array($oneMethod->name, $selectedPayments)) - { - $selected = "selected=\"selected\""; - } - - if (in_array($oneMethod->id, $selectedPayments)) - { - $disabled = 'disabled="disabled"'; - } - - if ($disabled != '' && $isMsIE) - { - // IE7 suffers from a bug, which makes disabled option fields selectable - $html .= ""; - } - else - { - $html .= ""; - } - } - - return $html; - } - /** - * Get payment method in Checkout, - * - * @param array $paymentMethods Array PaymentMethods - * - * @return array Common PaymentMethods - * - * @since 2.1.0 - */ - public static function getPaymentMethodInCheckOut($paymentMethods=array()) - { - $currentPaymentMethods = array(); - - if (!empty($paymentMethods)) - { - foreach ($paymentMethods as $p => $oneMethod) - { - $currentPaymentMethods[] = $oneMethod->name; - } - } - - $cart = \Redshop\Cart\Helper::getCart(); - - $idx = 0; - - if (isset($cart['idx'])) - { - $idx = $cart['idx']; - } - - $db = JFactory::getDbo(); - - $paymentMethods = array(); - $flag = true; - $commonPaymentMethod = $currentPaymentMethods; - - for ($i = 0; $i < $idx; $i++) - { - $productId = $cart[$i]['product_id']; - - $query = $db->getQuery(true) - ->select($db->qn('a.payment_id')) - ->from($db->qn('#__redshop_product_payment_xref', 'a')) - ->join('INNER', $db->qn('#__redshop_product', 'b') . ' ON (' . $db->qn('a.product_id') . ' = ' . $db->qn('b.product_id') . ')') - ->where($db->qn('b.use_individual_payment_method') . ' = 1'); - - if ($productId) - { - $query->where($db->qn('a.product_id') . ' = ' . $db->q((int) $productId)); - } - - $db->setQuery($query); - $payments = $db->loadObjectList(); - - if ($payments) - { - $payments = array_column($payments, 'payment_id'); - } - else - { - $payments = $currentPaymentMethods; - } - - if ($idx == 1) - { - return $payments; - } - - $paymentMethods[] = array('product_id' => $productId, 'payments' => $payments); - - if ($i > 0 && $flag) - { - $commonPaymentMethod = array_intersect($paymentMethods[$i - 1]['payments'], $paymentMethods[$i]['payments']); - - if (!empty($commonPaymentMethod)) - { - $flag = false; - } - } - } - - // Product in cart use these payment method - return $commonPaymentMethod; - } - /** - * List common payment methods of products cart in checkout, - * - * @param array $paymentMethods All active payment methods - * - * @return string HTML of
    - * - * @since 2.1.0 - */ - public static function displayPaymentMethodInCheckOut($paymentMethods=array()) - { - $currentPaymentMethods = array(); - - if (count($paymentMethods) > 0) - { - foreach ($paymentMethods as $p => $oneMethod) - { - $currentPaymentMethods[] = $oneMethod->name; - } - } - - $cart = \Redshop\Cart\Helper::getCart(); - $db = JFactory::getDbo(); - $html = ''; - - foreach ($cart as $index => $product) - { - if (!is_array($product) || empty($product)) - { - continue; - } - - $productId = $product['product_id']; - - $query = $db->getQuery(true); - $query - ->select($db->qn('a.payment_id')) - ->from($db->qn('#__redshop_product_payment_xref', 'a')) - ->join('INNER', $db->qn('#__redshop_product', 'b') . ' ON (' . $db->qn('a.product_id') . ' = ' . $db->qn('b.product_id') . ')') - ->where($db->qn('b.use_individual_payment_method') . ' = 1'); - - if ($productId) - { - $query->where($db->qn('a.product_id') . ' = ' . $db->q((int) $productId)); - } - - $db->setQuery($query); - $payments = $db->loadObjectList(); - - if ($payments) - { - $payments = array_column($payments, 'payment_id'); - } - else - { - $payments = $currentPaymentMethods; - } - - $product = \Redshop\Product\Product::getProductById($productId); - $html .= '
    '; - $tmp = ''; - - foreach ($payments as $p) - { - $tmp .= JText::_('PLG_' . strtoupper($p)) . ','; - } - - $tmp = rtrim($tmp, ","); - $html .= $tmp . '
    '; - } - - return $html; - } - - /** - * Calculate payment Discount/charges - * - * @param float $total Total - * @param object $payment Payment information - * @param float $finalAmount Final amount - * - * @return array - * - * @since 2.1.0 - */ - public static function calculate($total, $payment, $finalAmount) - { - $discount = 0; - - if ($payment->payment_discount_is_percent == 0) - { - $discount = $payment->payment_price; - } - elseif ($payment->payment_price > 0) - { - $discount = $total * $payment->payment_price / 100; - } - - $discount = $discount ? round($discount, 2) : 0; - - if (!$discount) - { - return array($finalAmount, 0); - } - - if ($payment->payment_oprand == '-') - { + /** + * Payment Method type constant + */ + const TYPE = 'redshop_payment'; + + /** + * Check for specific payment group type plugin - suffixed using given `type` + * Specially Checking for suffixed using `rs_payment_banktransfer` plugin + * + * @param string $name Payment Plugin Element Name + * @param string $typeSuffix Suffix to match + * + * @return boolean True when position found else false + */ + public static function isPaymentType($name, $typeSuffix = 'rs_payment_banktransfer') + { + $position = strpos($name, $typeSuffix); + + // Return false when given suffix is not found in string + if ($position === false) { + return false; + } + + // True when position found + return true; + } + + /** + * Method for check if order has this payment is update yet? + * + * @param integer $orderId Order ID + * @param mixed $transactionId Order payment transaction id + * + * @return boolean + * + * @since 2.0.6 + */ + public static function orderPaymentNotYetUpdated($orderId, $transactionId) + { + if (empty($orderId) || empty($transactionId)) { + return false; + } + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('COUNT(*)') + ->from($db->qn('#__redshop_order_payment')) + ->where($db->qn('order_id') . ' = ' . (int)$orderId) + ->where($db->qn('order_payment_trans_id') . ' = ' . $db->quote((int)$transactionId)); + + $result = $db->setQuery($query)->loadResult(); + + if (!$result) { + return true; + } + + return false; + } + + /** + * Replace conditional tag from Redshop payment Discount/charges + * + * @param string $template Template html + * @param integer $amount Amount of cart + * @param integer $cart Is in cart? + * @param string $paymentOprand Payment oprand + * + * @return string + * + * @since 2.0.7 + */ + public static function replaceConditionTag($template = '', $amount = 0, $cart = 0, $paymentOprand = '-') + { + if (strpos($template, '{if payment_discount}') === false || strpos( + $template, + '{payment_discount end if}' + ) === false) { + return $template; + } + + if ($cart == 1 || $amount == 0) { + $templateDiscountStart = explode('{if payment_discount}', $template); + $templateDiscountEnd = explode('{payment_discount end if}', $templateDiscountStart[1]); + + return $templateDiscountStart[0] . $templateDiscountEnd[1]; + } + + if ($amount <= 0) { + $templateStart = explode('{if payment_discount}', $template); + $templateEnd = explode('{payment_discount end if}', $templateStart[1]); + + return $templateStart[0] . $templateEnd[1]; + } + + $template = str_replace( + "{payment_order_discount}", + RedshopHelperProductPrice::formattedPrice($amount), + $template + ); + $payText = ($paymentOprand == '+') ? JText::_('COM_REDSHOP_PAYMENT_CHARGES_LBL') : JText::_( + 'COM_REDSHOP_PAYMENT_DISCOUNT_LBL' + ); + $template = str_replace("{payment_discount_lbl}", $payText, $template); + $template = str_replace("{payment_discount end if}", '', $template); + $template = str_replace("{if payment_discount}", '', $template); + + return $template; + } + + /** + * List all categories and return HTML format + * + * @param string $name Name of list + * @param integer $productId Only product to show + * @param integer $size Size of dropdown + * @param boolean $multiple Dropdown is multiple or not + * @param integer $width Width in pixel + * + * @return string HTML of dropdown + * + * @throws Exception + * @since 2.1.0 + * + */ + public static function listAll($name, $productId, $size = 1, $multiple = false, $width = 250) + { + $db = JFactory::getDbo(); + $html = ''; + $query = $db->getQuery(true) + ->select($db->qn('payment_id')) + ->from($db->qn('#__redshop_product_payment_xref')); + + if ($productId) { + $query->where($db->qn('product_id') . ' = ' . $db->q((int)$productId)); + } + + $selectedPayments = $db->setQuery($query)->loadObjectList(); + + if ($selectedPayments) { + $selectedPayments = array_column($selectedPayments, 'payment_id'); + } + + $multiple = $multiple ? "multiple=\"multiple\"" : ""; + $id = str_replace('[]', '', $name); + $html .= "\n"; + + return $html; + } + + /** + * List payment into dropdown + * + * @param array $selectedPayments Only show selected payments + * @param string $html Before HTML + * + * @return string HTML of + * + * @throws Exception + * @since 2.1.0 + * + */ + public static function listTree($selectedPayments = array(), $html = '') + { + self::loadLanguages(); + + $paymentMethods = self::info(); + + if (empty($paymentMethods)) { + return $html; + } + + $userBrowser = new Parser($_SERVER['HTTP_USER_AGENT']); + $isMsIE = $userBrowser->browser->isFamily('Internet Explorer'); + + foreach ($paymentMethods as $p => $oneMethod) { + $paymentPath = JPATH_SITE . '/plugins/redshop_payment/' . $oneMethod->name . '/' . $oneMethod->name . '.php'; + + include_once $paymentPath; + + $value = $oneMethod->name; + $disabled = ''; + $selected = ''; + + if (in_array($oneMethod->name, $selectedPayments)) { + $selected = "selected=\"selected\""; + } + + if (in_array($oneMethod->id, $selectedPayments)) { + $disabled = 'disabled="disabled"'; + } + + if ($disabled != '' && $isMsIE) { + // IE7 suffers from a bug, which makes disabled option fields selectable + $html .= ""; + } else { + $html .= ""; + } + } + + return $html; + } + + /** + * Load payment languages + * + * @param boolean $all True for all (discover, enabled, disabled). False for just enabled only. + * + * @return void + * + * @since 2.0.2 + */ + public static function loadLanguages($all = false) + { + // Load payment plugin language file + if ($all) { + $paymentsLangList = RedshopHelperUtility::getPlugins("redshop_payment"); + } else { + $paymentsLangList = RedshopHelperUtility::getPlugins("redshop_payment", 1); + } + + $language = JFactory::getLanguage(); + + for ($index = 0, $ln = count($paymentsLangList); $index < $ln; $index++) { + $extension = 'plg_redshop_payment_' . $paymentsLangList[$index]->element; + $language->load($extension, JPATH_ADMINISTRATOR, $language->getTag(), true); + $language->load( + $extension, + JPATH_PLUGINS . '/' . $paymentsLangList[$index]->folder . '/' . $paymentsLangList[$index]->element, + $language->getTag(), + true + ); + } + } + + /** + * Get payment method info + * + * @param string $name Payment Method name - Null to get all plugin info + * + * @return mixed Object is return one payment method, array for all. + * + * @throws Exception + */ + public static function info($name = '') + { + if (!JPluginHelper::isEnabled(self::TYPE, $name)) { + throw new Exception(JText::sprintf('COM_REDSHOP_PAYMENT_IS_NOT_ENABLED', $name)); + } + + $plugins = JPluginHelper::getPlugin(self::TYPE, $name); + + if ($name == '' && is_array($plugins)) { + array_walk( + $plugins, + function (&$plugin) { + $plugin->params = new Registry($plugin->params); + } + ); + } else { + $plugins->params = new Registry($plugins->params); + } + + return $plugins; + } + + /** + * Get payment method by id product + * + * @param integer $productId Only product to show + * + * @return array + * + * @throws Exception + * @since 2.1.0 + * + */ + public static function getPaymentByIdProduct($productId) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('payment_id')) + ->from($db->qn('#__redshop_product_payment_xref')) + ->where($db->qn('product_id') . ' = ' . $db->q((int)$productId)); + + return $db->setQuery($query)->loadColumn(); + } + + /** + * Get payment method in Checkout, + * + * @param array $paymentMethods Array PaymentMethods + * + * @return array Common PaymentMethods + * + * @since 2.1.0 + */ + public static function getPaymentMethodInCheckOut($paymentMethods = array()) + { + $currentPaymentMethods = array(); + + if (!empty($paymentMethods)) { + foreach ($paymentMethods as $p => $oneMethod) { + $currentPaymentMethods[] = $oneMethod->name; + } + } + + $cart = \Redshop\Cart\Helper::getCart(); + + $idx = 0; + + if (isset($cart['idx'])) { + $idx = $cart['idx']; + } + + $db = JFactory::getDbo(); + + $paymentMethods = array(); + $flag = true; + $commonPaymentMethod = $currentPaymentMethods; + + for ($i = 0; $i < $idx; $i++) { + $productId = $cart[$i]['product_id']; + + $query = $db->getQuery(true) + ->select($db->qn('a.payment_id')) + ->from($db->qn('#__redshop_product_payment_xref', 'a')) + ->join( + 'INNER', + $db->qn('#__redshop_product', 'b') . ' ON (' . $db->qn('a.product_id') . ' = ' . $db->qn( + 'b.product_id' + ) . ')' + ) + ->where($db->qn('b.use_individual_payment_method') . ' = 1'); + + if ($productId) { + $query->where($db->qn('a.product_id') . ' = ' . $db->q((int)$productId)); + } + + $db->setQuery($query); + $payments = $db->loadObjectList(); + + if ($payments) { + $payments = array_column($payments, 'payment_id'); + } else { + $payments = $currentPaymentMethods; + } + + if ($idx == 1) { + return $payments; + } + + $paymentMethods[] = array('product_id' => $productId, 'payments' => $payments); + + if ($i > 0 && $flag) { + $commonPaymentMethod = array_intersect( + $paymentMethods[$i - 1]['payments'], + $paymentMethods[$i]['payments'] + ); + + if (!empty($commonPaymentMethod)) { + $flag = false; + } + } + } + + // Product in cart use these payment method + return $commonPaymentMethod; + } + + /** + * List common payment methods of products cart in checkout, + * + * @param array $paymentMethods All active payment methods + * + * @return string HTML of
    + * + * @since 2.1.0 + */ + public static function displayPaymentMethodInCheckOut($paymentMethods = array()) + { + $currentPaymentMethods = array(); + + if (count($paymentMethods) > 0) { + foreach ($paymentMethods as $p => $oneMethod) { + $currentPaymentMethods[] = $oneMethod->name; + } + } + + $cart = \Redshop\Cart\Helper::getCart(); + $db = JFactory::getDbo(); + $html = ''; + + foreach ($cart as $index => $product) { + if (!is_array($product) || empty($product)) { + continue; + } + + $productId = $product['product_id']; + + $query = $db->getQuery(true); + $query + ->select($db->qn('a.payment_id')) + ->from($db->qn('#__redshop_product_payment_xref', 'a')) + ->join( + 'INNER', + $db->qn('#__redshop_product', 'b') . ' ON (' . $db->qn('a.product_id') . ' = ' . $db->qn( + 'b.product_id' + ) . ')' + ) + ->where($db->qn('b.use_individual_payment_method') . ' = 1'); + + if ($productId) { + $query->where($db->qn('a.product_id') . ' = ' . $db->q((int)$productId)); + } + + $db->setQuery($query); + $payments = $db->loadObjectList(); + + if ($payments) { + $payments = array_column($payments, 'payment_id'); + } else { + $payments = $currentPaymentMethods; + } + + $product = \Redshop\Product\Product::getProductById($productId); + $html .= '
    '; + $tmp = ''; + + foreach ($payments as $p) { + $tmp .= JText::_('PLG_' . strtoupper($p)) . ','; + } + + $tmp = rtrim($tmp, ","); + $html .= $tmp . '
    '; + } + + return $html; + } + + /** + * Calculate payment Discount/charges + * + * @param float $total Total + * @param object $payment Payment information + * @param float $finalAmount Final amount + * + * @return array + * + * @since 2.1.0 + */ + public static function calculate($total, $payment, $finalAmount) + { + $discount = 0; + + if ($payment->payment_discount_is_percent == 0) { + $discount = $payment->payment_price; + } elseif ($payment->payment_price > 0) { + $discount = $total * $payment->payment_price / 100; + } + + $discount = $discount ? round($discount, 2) : 0; + + if (!$discount) { + return array($finalAmount, 0); + } + + if ($payment->payment_oprand == '-') { $discount = $total < $discount ? $total : $discount; } - $finalAmount = $payment->payment_oprand == '+' ? $finalAmount + $discount : $finalAmount - $discount; + $finalAmount = $payment->payment_oprand == '+' ? $finalAmount + $discount : $finalAmount - $discount; - return array($finalAmount, $discount); - } + return array($finalAmount, $discount); + } } diff --git a/libraries/redshop/helper/pdf.php b/libraries/redshop/helper/pdf.php index 0eb7b24773a..892b7ac876b 100644 --- a/libraries/redshop/helper/pdf.php +++ b/libraries/redshop/helper/pdf.php @@ -20,32 +20,31 @@ */ class RedshopHelperPdf { - /** - * Get PDF Merger - * - * @return RedshopHelperPdf_Merge - */ - public static function getPDFMerger() - { - return new RedshopHelperPdf_Merge; - } + /** + * Get PDF Merger + * + * @return RedshopHelperPdf_Merge + */ + public static function getPDFMerger() + { + return new RedshopHelperPdf_Merge; + } - /** - * Create multiple print invoice PDF - * - * @param array $orderIds Order ID List. - * - * @return string - */ - public static function createMultiInvoice($orderIds) - { - if (empty($orderIds) || !self::isAvailablePdfPlugins()) - { - return ''; - } + /** + * Create multiple print invoice PDF + * + * @param array $orderIds Order ID List. + * + * @return string + */ + public static function createMultiInvoice($orderIds) + { + if (empty($orderIds) || !self::isAvailablePdfPlugins()) { + return ''; + } - $orderIds = ArrayHelper::toInteger($orderIds); - $defaultTemplate = ' + $orderIds = ArrayHelper::toInteger($orderIds); + $defaultTemplate = '
    @@ -73,41 +72,37 @@ public static function createMultiInvoice($orderIds)
    {order_information_lbl}{print}
    {order_id_lbl} : {order_id}
    {order_number_lbl} : {order_number}
    {order_total}



    '; - $orderPrintTemplate = RedshopHelperTemplate::getTemplate('order_print'); + $orderPrintTemplate = RedshopHelperTemplate::getTemplate('order_print'); - if (!empty($orderPrintTemplate) > 0 && !empty($orderPrintTemplate[0]->template_desc)) - { - $message = $orderPrintTemplate[0]->template_desc; - } - else - { - $message = $defaultTemplate; - } + if (!empty($orderPrintTemplate) > 0 && !empty($orderPrintTemplate[0]->template_desc)) { + $message = $orderPrintTemplate[0]->template_desc; + } else { + $message = $defaultTemplate; + } - JPluginHelper::importPlugin('redshop_pdf'); - $dispatcher = RedshopHelperUtility::getDispatcher(); + JPluginHelper::importPlugin('redshop_pdf'); + $dispatcher = RedshopHelperUtility::getDispatcher(); - $result = $dispatcher->trigger('onRedshopOrderCreateMultiInvoicePdf', array($orderIds, $message)); + $result = $dispatcher->trigger('onRedshopOrderCreateMultiInvoicePdf', array($orderIds, $message)); - if (!empty($result)) - { - return $result[0]; - } + if (!empty($result)) { + return $result[0]; + } - return ''; - } + return ''; + } - /** - * Method for check if there are any available PDF plugin support. - * - * @return boolean True if has available plugins. False other wise. - * - * @since 2.0.3 - */ - public static function isAvailablePdfPlugins() - { - $pdfPlugins = JPluginHelper::getPlugin('redshop_pdf'); + /** + * Method for check if there are any available PDF plugin support. + * + * @return boolean True if has available plugins. False other wise. + * + * @since 2.0.3 + */ + public static function isAvailablePdfPlugins() + { + $pdfPlugins = JPluginHelper::getPlugin('redshop_pdf'); - return empty($pdfPlugins) ? false : true; - } + return empty($pdfPlugins) ? false : true; + } } diff --git a/libraries/redshop/helper/pdf_merge.php b/libraries/redshop/helper/pdf_merge.php index 92f9ec4aebe..51928678863 100644 --- a/libraries/redshop/helper/pdf_merge.php +++ b/libraries/redshop/helper/pdf_merge.php @@ -18,183 +18,169 @@ */ class RedshopHelperPdf_Merge { - /** - * @var array ['form.pdf'] ["1,2,4, 5-19"] - */ - private $files; - - /** - * Add a PDF for inclusion in the merge with a valid file path. Pages should be formatted: 1,3,6, 12-16. - * - * @param string $filePath File path - * @param string $pages Page - * - * @return self - * - * @throws Exception - */ - public function addPDF($filePath, $pages = 'all') - { - if (!JFile::exists($filePath)) - { - throw new exception('Could not locate PDF on: ' . $filePath); - } - - if (strtolower($pages) != 'all') - { - $pages = $this->rewritePages($pages); - } - - $this->files[] = array($filePath, $pages); - - return $this; - } - - /** - * Merges your provided PDFs and outputs to specified location. - * - * @param string $outputMode Output mode - * @param string $outputPath Output path - * - * @return boolean - * - * @throws Exception - */ - public function merge($outputMode = 'browser', $outputPath = 'newfile.pdf') - { - if (!isset($this->files) || !is_array($this->files)) - { - throw new exception("No PDFs to merge."); - } - - $fpdi = new FPDI; - - // Merger operations - foreach ($this->files as $file) - { - $fileName = $file[0]; - $pages = $file[1]; - $count = $fpdi->setSourceFile($fileName); - - // Add the pages - if ($pages == 'all') - { - for ($i = 1; $i <= $count; $i++) - { - $template = $fpdi->importPage($i); - $size = $fpdi->getTemplateSize($template); - - $fpdi->AddPage('P', array($size['w'], $size['h'])); - $fpdi->useTemplate($template); - } - } - else - { - foreach ($pages as $page) - { - if (!$template = $fpdi->importPage($page)) - { - throw new exception("Could not load page '$page' in PDF '$fileName'. Check that the page exists."); - } - - $size = $fpdi->getTemplateSize($template); - - $fpdi->AddPage('P', array($size['w'], $size['h'])); - $fpdi->useTemplate($template); - } - } - } - - // Output operations - $mode = $this->switchMode($outputMode); - - return $fpdi->Output($outputPath, $mode); - } - - /** - * FPDI uses single characters for specifying the output location. Change our more descriptive string into proper format. - * - * @param string $mode Mode - * - * @return string - */ - private function switchMode($mode) - { - switch (strtolower($mode)) - { - case 'download': - return 'D'; - break; - - case 'browser': - return 'I'; - break; - - case 'file': - return 'F'; - break; - - case 'string': - return 'S'; - break; - - default: - return 'I'; - break; - } - } - - /** - * Takes our provided pages in the form of 1,3,4,16-50 and creates an array of all pages - * - * @param string $pages Page - * - * @return mixed - * - * @throws Exception - */ - private function rewritePages($pages) - { - $pages = str_replace(' ', '', $pages); - $parts = explode(',', $pages); - $newPages = array(); - - if (empty($parts)) - { - return $newPages; - } - - // Parse hyphens - foreach ($parts as $part) - { - $ind = explode('-', $part); - - if (count($ind) != 2) - { - $newPages[] = (int) $ind[0]; - - continue; - } - - // Start page - $x = $ind[0]; - - // End page - $y = $ind[1]; - - if ($x > $y) - { - throw new exception("Starting page, '$x' is greater than ending page '$y'."); - } - - // Add middle pages - while ($x <= $y) - { - $newPages[] = (int) $x; - $x++; - } - } - - return $newPages; - } + /** + * @var array ['form.pdf'] ["1,2,4, 5-19"] + */ + private $files; + + /** + * Add a PDF for inclusion in the merge with a valid file path. Pages should be formatted: 1,3,6, 12-16. + * + * @param string $filePath File path + * @param string $pages Page + * + * @return self + * + * @throws Exception + */ + public function addPDF($filePath, $pages = 'all') + { + if (!JFile::exists($filePath)) { + throw new exception('Could not locate PDF on: ' . $filePath); + } + + if (strtolower($pages) != 'all') { + $pages = $this->rewritePages($pages); + } + + $this->files[] = array($filePath, $pages); + + return $this; + } + + /** + * Takes our provided pages in the form of 1,3,4,16-50 and creates an array of all pages + * + * @param string $pages Page + * + * @return mixed + * + * @throws Exception + */ + private function rewritePages($pages) + { + $pages = str_replace(' ', '', $pages); + $parts = explode(',', $pages); + $newPages = array(); + + if (empty($parts)) { + return $newPages; + } + + // Parse hyphens + foreach ($parts as $part) { + $ind = explode('-', $part); + + if (count($ind) != 2) { + $newPages[] = (int)$ind[0]; + + continue; + } + + // Start page + $x = $ind[0]; + + // End page + $y = $ind[1]; + + if ($x > $y) { + throw new exception("Starting page, '$x' is greater than ending page '$y'."); + } + + // Add middle pages + while ($x <= $y) { + $newPages[] = (int)$x; + $x++; + } + } + + return $newPages; + } + + /** + * Merges your provided PDFs and outputs to specified location. + * + * @param string $outputMode Output mode + * @param string $outputPath Output path + * + * @return boolean + * + * @throws Exception + */ + public function merge($outputMode = 'browser', $outputPath = 'newfile.pdf') + { + if (!isset($this->files) || !is_array($this->files)) { + throw new exception("No PDFs to merge."); + } + + $fpdi = new FPDI; + + // Merger operations + foreach ($this->files as $file) { + $fileName = $file[0]; + $pages = $file[1]; + $count = $fpdi->setSourceFile($fileName); + + // Add the pages + if ($pages == 'all') { + for ($i = 1; $i <= $count; $i++) { + $template = $fpdi->importPage($i); + $size = $fpdi->getTemplateSize($template); + + $fpdi->AddPage('P', array($size['w'], $size['h'])); + $fpdi->useTemplate($template); + } + } else { + foreach ($pages as $page) { + if (!$template = $fpdi->importPage($page)) { + throw new exception( + "Could not load page '$page' in PDF '$fileName'. Check that the page exists." + ); + } + + $size = $fpdi->getTemplateSize($template); + + $fpdi->AddPage('P', array($size['w'], $size['h'])); + $fpdi->useTemplate($template); + } + } + } + + // Output operations + $mode = $this->switchMode($outputMode); + + return $fpdi->Output($outputPath, $mode); + } + + /** + * FPDI uses single characters for specifying the output location. Change our more descriptive string into proper format. + * + * @param string $mode Mode + * + * @return string + */ + private function switchMode($mode) + { + switch (strtolower($mode)) { + case 'download': + return 'D'; + break; + + case 'browser': + return 'I'; + break; + + case 'file': + return 'F'; + break; + + case 'string': + return 'S'; + break; + + default: + return 'I'; + break; + } + } } diff --git a/libraries/redshop/helper/product.php b/libraries/redshop/helper/product.php index fc13a5406ad..3ac48c356e7 100644 --- a/libraries/redshop/helper/product.php +++ b/libraries/redshop/helper/product.php @@ -60,6 +60,181 @@ class RedshopHelperProduct */ protected static $productDateRange = array(); + /** + * Replace Attribute Data + * + * @param int $productId Product id + * @param int $accessoryId Accessory id + * @param array $attributes Attribute list + * @param int $userId User id + * @param string $uniqueId Unique id + * + * @return mixed + * + * @since 2.0.3 + * + * @deprecated 2.1.0 + */ + public static function replaceAttributeData( + $productId = 0, + $accessoryId = 0, + $attributes = array(), + $userId = 0, + $uniqueId = "" + ) { + return RedshopHelperProductTag::replaceAttributeData($productId, $accessoryId, $attributes, $userId, $uniqueId); + } + + /** + * Get product item info + * + * @param integer $productId Product id + * @param integer $quantity Product quantity + * @param string $uniqueId Unique id + * @param integer $userId User id + * @param integer $newProductPrice New product price + * + * @return mixed + * + * @throws Exception + * @since 2.0.3 + * + */ + public static function getProductItemInfo( + $productId = 0, + $quantity = 1, + $uniqueId = "", + $userId = 0, + $newProductPrice = 0 + ) { + $wrapperList = ""; + $accessoryList = ""; + $attributeList = ""; + $productUserField = ""; + $productPriceExclVat = 0; + $productTax = 0; + + if ($productId) { + $productInfo = Redshop::product((int)$productId); + + if ($newProductPrice != 0) { + $productPriceExclVat = $newProductPrice; + $productTax = self::getProductTax($productId, $newProductPrice, $userId); + } else { + $productArr = RedshopHelperProductPrice::getNetPrice($productId, $userId, $quantity); + $productPriceExclVat = $productArr['productPrice']; + $productTax = $productArr['productVat']; + + // Attribute start + $attributesSet = array(); + + if ($productInfo->attribute_set_id > 0) { + $attributesSet = \Redshop\Product\Attribute::getProductAttribute( + 0, + $productInfo->attribute_set_id, + 0, + 1 + ); + } + + $attributes = \Redshop\Product\Attribute::getProductAttribute($productId); + $attributes = array_merge($attributes, $attributesSet); + $attributeList = RedshopHelperProductTag::replaceAttributeData( + $productId, + 0, + $attributes, + $userId, + $uniqueId, + true + ); + + // Accessory start + $accessory = RedshopHelperAccessory::getProductAccessories(0, $productId); + $accessoryList = self::replaceAccessoryData($productId, $accessory, $userId, $uniqueId); + + // Wrapper selection box generate + $wrapperList = self::replaceWrapperData($productId, $userId, $uniqueId, true); + $productUserField = self::replaceUserField($productId, $productInfo->product_template, $uniqueId); + } + } + + $productPrice = $productPriceExclVat + $productTax; + $total_price = $productPrice * $quantity; + $totalTax = $productTax * $quantity; + + $displayRespoce = ""; + $displayRespoce .= "
    " . $productPriceExclVat . "
    "; + $displayRespoce .= "
    " . $productTax . "
    "; + $displayRespoce .= "
    " . $productPrice . "
    "; + $displayRespoce .= "
    " . $total_price . "
    "; + $displayRespoce .= "
    " . $totalTax . "
    "; + $displayRespoce .= "
    " . $attributeList . "
    "; + $displayRespoce .= "
    " . $productUserField . "
    "; + $displayRespoce .= "
    " . $accessoryList . "
    "; + $displayRespoce .= "
    " . $wrapperList . "
    "; + + return $displayRespoce; + } + + /** + * Method for get product tax + * + * @param integer $productId Product Id + * @param float $productPrice Product price + * @param integer $userId User ID + * @param integer $taxExempt Tax exempt + * + * @return integer + * + * @since 2.0.6 + */ + public static function getProductTax($productId = 0, $productPrice = 0.0, $userId = 0, $taxExempt = 0) + { + $redshopUser = JFactory::getSession()->get('rs_user'); + $app = JFactory::getApplication(); + + if ($userId == 0 && !$app->isClient('administrator')) { + $user = JFactory::getUser(); + $userId = $user->id; + } else { + $userId = $app->input->getInt('user_id', 0); + } + + $productInfor = $productId != 0 ? \Redshop\Product\Product::getProductById($productId) : array(); + $productTax = 0; + $redshopUser = empty($redshopUser) ? array('rs_is_user_login' => 0) : $redshopUser; + + if ($redshopUser['rs_is_user_login'] == 0 && $userId != 0) { + RedshopHelperUser::createUserSession($userId); + } + + $vatRateData = RedshopHelperTax::getVatRates($productId, $userId); + $taxRate = !empty($vatRateData) ? $vatRateData->tax_rate : 0; + + $productPrice = $productPrice <= 0 && isset($productInfor->product_price) ? $productInfor->product_price : $productPrice; + $productPrice = RedshopHelperProductPrice::priceRound($productPrice); + + if ($taxExempt) { + return $productPrice * $taxRate; + } + + if (!$taxRate) { + return RedshopHelperProductPrice::priceRound($productTax); + } + + if (!$userId) { + $productTax = $productPrice * $taxRate; + } else { + $userInformation = RedshopHelperUser::getUserInformation($userId); + + if (null === $userInformation || $userInformation->requesting_tax_exempt !== 1 || !$userInformation->tax_exempt_approved) { + $productTax = $productPrice * $taxRate; + } + } + + return RedshopHelperProductPrice::priceRound($productTax); + } + /** * Replace Accessory Data * @@ -143,31 +318,6 @@ public static function replaceAccessoryData($productId = 0, $accessory = array() return $accessoryList; } - /** - * Replace Attribute Data - * - * @param int $productId Product id - * @param int $accessoryId Accessory id - * @param array $attributes Attribute list - * @param int $userId User id - * @param string $uniqueId Unique id - * - * @return mixed - * - * @since 2.0.3 - * - * @deprecated 2.1.0 - */ - public static function replaceAttributeData( - $productId = 0, - $accessoryId = 0, - $attributes = array(), - $userId = 0, - $uniqueId = "" - ) { - return RedshopHelperProductTag::replaceAttributeData($productId, $accessoryId, $attributes, $userId, $uniqueId); - } - /** * Replace Accessory Data * @@ -210,7 +360,7 @@ public static function replaceWrapperData($productId = 0, $userId = 0, $uniqueId $wrapperPrice = strip_tags($wrapperPrice); } - $wrapper[$i]->wrapper_name = $wrapper [$i]->wrapper_name . " (" . $wrapperPrice . ")"; + $wrapper[$i]->wrapper_name = $wrapper [$i]->wrapper_name . " (" . $wrapperPrice . ")"; $wrapperList .= ""; @@ -235,14 +385,50 @@ public static function replaceWrapperData($productId = 0, $userId = 0, $uniqueId return $wrapperList; } + public static function getWrapper($productId, $wrapper_id = 0, $default = 1) + { + $db = Factory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_product_category_xref')) + ->where($db->qn('product_id') . ' = ' . $db->q((int)$productId)); + + $db->setQuery($query); + $cat = $db->loadObjectList(); + $subQuery[] = " FIND_IN_SET(" . (int)$productId . ", " . $db->qn('product_id') . ") "; + + for ($i = 0, $in = count($cat); $i < $in; $i++) { + $subQuery[] = " FIND_IN_SET(" . (int)$cat[$i]->category_id . ", " . $db->qn('category_id') . ") "; + } + + if ($default != 0) { + $subQuery[] = $db->qn('wrapper_use_to_all') . ' = 1 '; + } + + $query = $db->getQuery(true); + + if ($wrapper_id != 0) { + $query->where($db->qn('wrapper_id') . ' = ' . (int)$wrapper_id); + } + + $query->select('*') + ->from($db->qn('#__redshop_wrapper')) + ->where($db->qn('published') . ' = 1') + ->where('(' . implode(' OR ', $subQuery) . ')'); + + $db->setQuery($query); + $list = $db->loadObjectList(); + + return $list; + } + /** - * Get product item info + * Replace User Field * - * @param integer $productId Product id - * @param integer $quantity Product quantity - * @param string $uniqueId Unique id - * @param integer $userId User id - * @param integer $newProductPrice New product price + * @param int $productId Product id + * @param int $templateId Template id + * @param string $uniqueId Unique id * * @return mixed * @@ -250,80 +436,38 @@ public static function replaceWrapperData($productId = 0, $userId = 0, $uniqueId * @since 2.0.3 * */ - public static function getProductItemInfo( - $productId = 0, - $quantity = 1, - $uniqueId = "", - $userId = 0, - $newProductPrice = 0 - ) { - $wrapperList = ""; - $accessoryList = ""; - $attributeList = ""; - $productUserField = ""; - $productPriceExclVat = 0; - $productTax = 0; - - if ($productId) { - $productInfo = Redshop::product((int)$productId); - - if ($newProductPrice != 0) { - $productPriceExclVat = $newProductPrice; - $productTax = self::getProductTax($productId, $newProductPrice, $userId); - } else { - $productArr = RedshopHelperProductPrice::getNetPrice($productId, $userId, $quantity); - $productPriceExclVat = $productArr['productPrice']; - $productTax = $productArr['productVat']; - - // Attribute start - $attributesSet = array(); + public static function replaceUserField($productId = 0, $templateId = 0, $uniqueId = "") + { + $templateDesc = RedshopHelperTemplate::getTemplate("product", $templateId); + $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($templateDesc[0]->template_desc); + $commonId = $productId . $uniqueId; - if ($productInfo->attribute_set_id > 0) { - $attributesSet = \Redshop\Product\Attribute::getProductAttribute( - 0, - $productInfo->attribute_set_id, - 0, - 1 - ); - } + if (empty($returnArr[1])) { + return ''; + } - $attributes = \Redshop\Product\Attribute::getProductAttribute($productId); - $attributes = array_merge($attributes, $attributesSet); - $attributeList = RedshopHelperProductTag::replaceAttributeData( - $productId, - 0, - $attributes, - $userId, - $uniqueId, - true - ); + $productUserFields = ""; - // Accessory start - $accessory = RedshopHelperAccessory::getProductAccessories(0, $productId); - $accessoryList = self::replaceAccessoryData($productId, $accessory, $userId, $uniqueId); + foreach ($returnArr[1] as $index => $return) { + $resultArr = RedshopHelperExtrafields::listAllUserFields( + $return, + RedshopHelperExtrafields::SECTION_PRODUCT_USERFIELD, + "", + $commonId + ); + $hiddenArr = RedshopHelperExtrafields::listAllUserFields( + $return, + RedshopHelperExtrafields::SECTION_PRODUCT_USERFIELD, + "hidden", + $commonId + ); - // Wrapper selection box generate - $wrapperList = self::replaceWrapperData($productId, $userId, $uniqueId, true); - $productUserField = self::replaceUserField($productId, $productInfo->product_template, $uniqueId); + if (!empty($resultArr[0])) { + $productUserFields .= ""; } } - $productPrice = $productPriceExclVat + $productTax; - $total_price = $productPrice * $quantity; - $totalTax = $productTax * $quantity; - - $displayRespoce = ""; - $displayRespoce .= "
    " . $productPriceExclVat . "
    "; - $displayRespoce .= "
    " . $productTax . "
    "; - $displayRespoce .= "
    " . $productPrice . "
    "; - $displayRespoce .= "
    " . $total_price . "
    "; - $displayRespoce .= "
    " . $totalTax . "
    "; - $displayRespoce .= "
    " . $resultArr[0] . "" . $resultArr[1] . $hiddenArr[1] . "
    " . $attributeList . "
    "; - $displayRespoce .= "
    " . $productUserField . "
    "; - $displayRespoce .= "
    " . $accessoryList . "
    "; - $displayRespoce .= "
    " . $wrapperList . "
    "; - - return $displayRespoce; + return $productUserFields . ""; } /** @@ -411,53 +555,6 @@ public static function redesignProductItem($post = array()) return Redshop\Order\Helper::redesignProductItem($post); } - /** - * Replace User Field - * - * @param int $productId Product id - * @param int $templateId Template id - * @param string $uniqueId Unique id - * - * @return mixed - * - * @throws Exception - * @since 2.0.3 - * - */ - public static function replaceUserField($productId = 0, $templateId = 0, $uniqueId = "") - { - $templateDesc = RedshopHelperTemplate::getTemplate("product", $templateId); - $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($templateDesc[0]->template_desc); - $commonId = $productId . $uniqueId; - - if (empty($returnArr[1])) { - return ''; - } - - $productUserFields = ""; - - foreach ($returnArr[1] as $index => $return) { - $resultArr = RedshopHelperExtrafields::listAllUserFields( - $return, - RedshopHelperExtrafields::SECTION_PRODUCT_USERFIELD, - "", - $commonId - ); - $hiddenArr = RedshopHelperExtrafields::listAllUserFields( - $return, - RedshopHelperExtrafields::SECTION_PRODUCT_USERFIELD, - "hidden", - $commonId - ); - - if (!empty($resultArr[0])) { - $productUserFields .= ""; - } - } - - return $productUserFields . "
    " . $resultArr[0] . "" . $resultArr[1] . $hiddenArr[1] . "
    "; - } - /** * Insert Product user field * @@ -644,65 +741,6 @@ public static function getProductQuantityPrice($productId, $userId) ); } - /** - * Method for get product tax - * - * @param integer $productId Product Id - * @param float $productPrice Product price - * @param integer $userId User ID - * @param integer $taxExempt Tax exempt - * - * @return integer - * - * @since 2.0.6 - */ - public static function getProductTax($productId = 0, $productPrice = 0.0, $userId = 0, $taxExempt = 0) - { - $redshopUser = JFactory::getSession()->get('rs_user'); - $app = JFactory::getApplication(); - - if ($userId == 0 && !$app->isClient('administrator')) { - $user = JFactory::getUser(); - $userId = $user->id; - } else { - $userId = $app->input->getInt('user_id', 0); - } - - $productInfor = $productId != 0 ? \Redshop\Product\Product::getProductById($productId) : array(); - $productTax = 0; - $redshopUser = empty($redshopUser) ? array('rs_is_user_login' => 0) : $redshopUser; - - if ($redshopUser['rs_is_user_login'] == 0 && $userId != 0) { - RedshopHelperUser::createUserSession($userId); - } - - $vatRateData = RedshopHelperTax::getVatRates($productId, $userId); - $taxRate = !empty($vatRateData) ? $vatRateData->tax_rate : 0; - - $productPrice = $productPrice <= 0 && isset($productInfor->product_price) ? $productInfor->product_price : $productPrice; - $productPrice = RedshopHelperProductPrice::priceRound($productPrice); - - if ($taxExempt) { - return $productPrice * $taxRate; - } - - if (!$taxRate) { - return RedshopHelperProductPrice::priceRound($productTax); - } - - if (!$userId) { - $productTax = $productPrice * $taxRate; - } else { - $userInformation = RedshopHelperUser::getUserInformation($userId); - - if (null === $userInformation || $userInformation->requesting_tax_exempt !== 1 || !$userInformation->tax_exempt_approved) { - $productTax = $productPrice * $taxRate; - } - } - - return RedshopHelperProductPrice::priceRound($productTax); - } - /** * Get Product Prices * @@ -792,32 +830,6 @@ public static function getProductPrices($productId, $userId, $quantity = 1) return self::$productPrices[$key]; } - /** - * Method for get child products of specific product - * - * @param integer $productId Product ID - * - * @return array - * @since 2.1.0 - */ - public static function getChildProduct($productId = 0) - { - $childProducts = RedshopEntityProduct::getInstance($productId)->getChildProducts(); - - if ($childProducts->isEmpty()) { - return array(); - } - - $results = array(); - - foreach ($childProducts->getAll() as $child) { - /** @var RedshopEntityProduct $child */ - $results[] = $child->getItem(); - } - - return $results; - } - /** * Method get videos product * @@ -1583,44 +1595,6 @@ public static function replaceProductSubCategory(&$templateDesc, $category) } } - public static function getWrapper($productId, $wrapper_id = 0, $default = 1) - { - $db = Factory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_product_category_xref')) - ->where($db->qn('product_id') . ' = ' . $db->q((int)$productId)); - - $db->setQuery($query); - $cat = $db->loadObjectList(); - $subQuery[] = " FIND_IN_SET(" . (int)$productId . ", " . $db->qn('product_id') . ") "; - - for ($i = 0, $in = count($cat); $i < $in; $i++) { - $subQuery[] = " FIND_IN_SET(" . (int)$cat[$i]->category_id . ", " . $db->qn('category_id') . ") "; - } - - if ($default != 0) { - $subQuery[] = $db->qn('wrapper_use_to_all') . ' = 1 '; - } - - $query = $db->getQuery(true); - - if ($wrapper_id != 0) { - $query->where($db->qn('wrapper_id') . ' = ' . (int)$wrapper_id); - } - - $query->select('*') - ->from($db->qn('#__redshop_wrapper')) - ->where($db->qn('published') . ' = 1') - ->where('(' . implode(' OR ', $subQuery) . ')'); - - $db->setQuery($query); - $list = $db->loadObjectList(); - - return $list; - } - public static function getProductFinderDatepickerValue( $templatedata = "", $productid = 0, @@ -1649,13 +1623,446 @@ public static function getProductFinderDatepickerValue( return $templatedata; } - public static function redunitDecimal($price) + public static function getProductMinDeliveryTime($productId = 0, $sectionId = 0, $section = '', $loadDiv = 1) + { + // Initialiase variables. + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + if (!$sectionId && !$section) { + $query + ->from($db->qn('#__redshop_product_stockroom_xref') . ' AS ps') + ->where($db->qn('ps.product_id') . ' = ' . (int)$productId); + } else { + $query + ->from($db->qn('#__redshop_product_attribute_stockroom_xref') . ' AS ps') + ->where($db->qn('ps.section_id') . ' = ' . (int)$sectionId) + ->where($db->qn('ps.section') . ' = ' . $db->q($section)); + } + + // Create the base select statement. + $query->select( + array( + 'min_del_time as deltime', + 's.max_del_time', + 's.delivery_time' + ) + ) + ->join('', $db->qn('#__redshop_stockroom') . ' AS s') + ->where($db->qn('ps.stockroom_id') . ' = ' . $db->qn('s.stockroom_id')) + ->where($db->qn('ps.quantity') . ' > 0 ') + ->order($db->qn('min_del_time') . ' ASC'); + + // Set the query and load the result. + $db->setQuery($query, 0, 1); + + try { + $result = $db->loadObject(); + } catch (RuntimeException $e) { + throw new RuntimeException($e->getMessage(), $e->getCode()); + } + + $product_delivery_time = ''; + + if ($result) { + // Append where clause to get Maximum Delivery time of Minimum Delivery stockroom + $query->where($db->qn('s.min_del_time') . ' = ' . (int)$result->deltime); + + // Set the query and load the row. + $db->setQuery($query, 0, 1); + + try { + $row = $db->loadObject(); + } catch (RuntimeException $e) { + throw new RuntimeException($e->getMessage(), $e->getCode()); + } + + if ($row->deltime == 0 || $row->deltime == ' ') { + $product_delivery_time = ''; + } else { + if ($row->delivery_time == "Days") { + $duration = JText::_('COM_REDSHOP_DAYS'); + } else { + $row->deltime = $row->deltime / 7; + $row->max_del_time = $row->max_del_time / 7; + $duration = JText::_('COM_REDSHOP_WEEKS'); + } + + $product_delivery_time = (int)$row->deltime . "-" . (int)$row->max_del_time . " " . $duration; + } + } + + if ($product_delivery_time && $loadDiv) { + $product_delivery_time = '
    ' . $product_delivery_time . '
    '; + } + + return $product_delivery_time; + } + + /** + * Get Menu Information + * + * @param int $Itemid Item id + * @param int $sectionId Section id + * @param string $sectionName Section name + * @param string $menuView Menu view + * @param bool $isRedshop Is redshop + * + * @return mixed|null + */ + public static function getMenuInformation( + $Itemid = 0, + $sectionId = 0, + $sectionName = '', + $menuView = '', + $isRedshop = true + ) { + $menu = JFactory::getApplication()->getMenu(); + $values = array(); + + if ($menuView != "") { + if ($items = explode('&', $menuView)) { + $values['view'] = $items[0]; + unset($items[0]); + + if (!empty($items)) { + foreach ($items as $item) { + $value = explode('=', $item); + $values[$value[0]] = $value[1]; + } + } + } + } + + if ($Itemid != 0) { + return $menu->getItem($Itemid); + } + + if ($isRedshop) { + $menuItems = RedshopHelperRouter::getRedshopMenuItems(); + } else { + $menuItems = $menu->getMenu(); + } + + foreach ($menuItems as $oneMenuItem) { + if (!RedshopHelperRouter::checkMenuQuery($oneMenuItem, $values)) { + break; + } + + if ($sectionName != '') { + if ($sectionId != 0) { + if ($oneMenuItem->params->get($sectionName) != $sectionId) { + break; + } + } else { + if ($oneMenuItem->params->get($sectionName, false) !== false) { + break; + } + } + } + + return $oneMenuItem; + } + + return null; + } + + public static function redunitDecimal($price) { if (Redshop::getConfig()->get('UNIT_DECIMAL') != "") { return number_format($price, Redshop::getConfig()->get('UNIT_DECIMAL'), '.', ''); } - return $price; + return $price; + } + + /** + * @param integer $productId Product id + * @param integer $relatedId Related id + * + * @return mixed + * + * @since 2.1.0 + */ + public static function getRelatedProduct($productId = 0, $relatedId = 0) + { + $db = JFactory::getDbo(); + $where = ''; + $orderby = "p.product_id ASC"; + $orderbyRelated = ""; + + if (Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD')) { + $orderby = Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD'); + $orderbyRelated = ""; + } + + if ($productId != 0) { + // Sanitize ids + $productIds = explode(',', $productId); + $productIds = Joomla\Utilities\ArrayHelper::toInteger($productIds); + + if (RedshopHelperUtility::isRedProductFinder()) { + $q = $db->getQuery(true); + $q->select($db->qn('extrafield')) + ->from($db->qn('#__redproductfinder_types')) + ->where($db->qn('type_select') . ' = ' . $db->q('Productfinder_datepicker')); + $db->setQuery($q); + $finaltypetype_result = $db->loadObject(); + } else { + $finaltypetype_result = array(); + } + + $where .= $db->qn('r.product_id') . ' IN (' . implode(',', $productIds) . ') '; + + if (Redshop::getConfig()->get('TWOWAY_RELATED_PRODUCT')) { + if (Redshop::getConfig()->get( + 'DEFAULT_RELATED_ORDERING_METHOD' + ) == "r.ordering ASC" || Redshop::getConfig()->get( + 'DEFAULT_RELATED_ORDERING_METHOD' + ) == "r.ordering DESC") { + $orderby = ""; + $orderbyRelated = Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD'); + } + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_product_related', 'r')) + ->where($db->qn('r.product_id') . ' IN (' . implode(',', $productIds) . ') ') + ->orWhere($db->qn('r.related_id') . ' IN (' . implode(',', $productIds) . ') '); + + if (!empty($orderbyRelated)) { + $query->order($orderbyRelated); + } + + $db->setQuery($query); + $list = $db->loadObjectlist(); + + $relatedArr = array(); + + for ($i = 0, $in = count($list); $i < $in; $i++) { + if ($list[$i]->product_id == $productId) { + $relatedArr[] = $list[$i]->related_id; + } else { + $relatedArr[] = $list[$i]->product_id; + } + } + + if (empty($relatedArr)) { + return array(); + } + + // Sanitize ids + $relatedArr = Joomla\Utilities\ArrayHelper::toInteger($relatedArr); + $relatedArr = array_unique($relatedArr); + + $query = $db->getQuery(true) + ->select((int)$productId . ' AS ' . $db->qn('mainproduct_id')) + ->select('p.*') + ->from($db->qn('#__redshop_product', 'p')) + ->where($db->qn('published') . ' = 1') + ->where($db->qn('p.product_id') . ' IN (' . implode(',', $relatedArr) . ') '); + + if (!empty($orderby)) { + $query->order($orderby); + } + + $db->setQuery($query); + $list = $db->loadObjectlist(); + + return $list; + } + } + + $query = $db->getQuery(true) + ->select(array($db->qn('r.product_id', 'mainproduct_id'), 'p.*')); + + if ($relatedId != 0) { + $query->where($db->qn('r.related_id') . ' = ' . (int)$relatedId); + } + + if (count($finaltypetype_result) > 0 && $finaltypetype_result->extrafield != '' + && (Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt ASC' || Redshop::getConfig( + )->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt DESC')) { + $query->select('e.*'); + } + + $query->from($db->qn('#__redshop_product_related', 'r')) + ->leftJoin( + $db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('r.related_id') + ); + + if (!empty($finaltypetype_result) && !empty($finaltypetype_result->extrafield) + && (Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt ASC' + || Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt DESC')) { + $query->leftJoin( + $db->qn('#__redshop_fields_data', 'e') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('e.itemid') + ); + } + + $query->where($db->qn('p.published') . ' = 1'); + + if (count($finaltypetype_result) > 0 && $finaltypetype_result->extrafield != '' + && (Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt ASC' || Redshop::getConfig( + )->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt DESC')) { + $query->where($db->qn('e.fieldid') . ' = ' . (int)$finaltypetype_result->extrafield) + ->where($db->qn('e.section') . ' = 17'); + } + + if (!empty($where)) { + $query->where($where); + } + + $query->group($db->qn('r.related_id')); + + if ((Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt ASC' + || Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt DESC')) { + if (Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt ASC') { + $s = "STR_TO_DATE( e.data_txt, '%d-%m-%Y' ) ASC"; + } else { + $s = "STR_TO_DATE( e.data_txt, '%d-%m-%Y' ) DESC"; + } + + $query->order($s); + } else { + $query->order($orderby); + } + + $db->setQuery($query); + + $list = $db->loadObjectlist(); + + return $list; + } + + public static function getJcommentEditor($product = array(), $data_add = "") + { + $app = JFactory::getApplication(); + $product_reviews = ""; + $productId = $product->product_id; + + if ($productId && strpos($data_add, "{jcomments off}") === false && strpos( + $data_add, + "{jcomments on}" + ) !== false) { + $comments = $app->getCfg('absolute_path') . '/components/com_jcomments/jcomments.php'; + + if (file_exists($comments)) { + require_once $comments; + $product_reviews = JComments::showComments($productId, 'com_redshop', $product->product_name); + } + + $data_add = str_replace("{jcomments on}", $product_reviews, $data_add); + } + + $data_add = str_replace("{jcomments on}", $product_reviews, $data_add); + $data_add = str_replace("{jcomments off}", "", $data_add); + + return $data_add; + } + + public static function getProductOnSaleComment($product = array(), $data_add = "") + { + if (strpos($data_add, "{if product_on_sale}") && strpos($data_add, "{product_on_sale end if}") !== false) { + if ($product->product_on_sale == 1 && (($product->discount_stratdate == 0 && $product->discount_enddate == 0) || ($product->discount_stratdate <= time( + ) && $product->discount_enddate >= time()))) { + $data_add = str_replace( + "{discount_start_date}", + RedshopHelperDatetime::convertDateFormat($product->discount_stratdate), + $data_add + ); + $data_add = str_replace( + "{discount_end_date}", + RedshopHelperDatetime::convertDateFormat($product->discount_enddate), + $data_add + ); + $data_add = str_replace("{if product_on_sale}", '', $data_add); + $data_add = str_replace("{product_on_sale end if}", '', $data_add); + } else { + $template_pd_sdata = strstr($data_add, '{if product_on_sale}', true); + $template_pd_edata = substr(strstr($data_add, '{product_on_sale end if}'), 24); + $data_add = $template_pd_sdata . $template_pd_edata; + } + + $data_add = str_replace("{discount_start_date}", '', $data_add); + $data_add = str_replace("{discount_end_date}", '', $data_add); + } + + return $data_add; + } + + public static function getProductNotForSaleComment( + $product = array(), + $data_add = "", + $attributes = array(), + $is_relatedproduct = 0, + $seoTemplate = "" + ) { + $showPrice = true; + + if ($product->expired || $product->not_for_sale == 1) { + $showPrice = false; + } + + if ($showPrice) { + // Product show price without formatted + $applytax = \Redshop\Template\Helper::isApplyVat($data_add); + + if ($applytax) { + $GLOBAL ['without_vat'] = false; + } else { + $GLOBAL ['without_vat'] = true; + } + + $data_add = RedshopHelperProductPrice::getShowPrice( + $product->product_id, + $data_add, + $seoTemplate, + 0, + $is_relatedproduct, + $attributes + ); + } else { + $relPrefix = ($is_relatedproduct) ? 'rel' : ''; + $data_add = str_replace("{" . $relPrefix . "product_price_lbl}", "", $data_add); + $data_add = str_replace("{" . $relPrefix . "product_price}", "", $data_add); + $data_add = str_replace("{" . $relPrefix . "product_price_novat}", "", $data_add); + $data_add = str_replace("{" . $relPrefix . "price_excluding_vat}", "", $data_add); + $data_add = str_replace("{" . $relPrefix . "product_price_table}", "", $data_add); + $data_add = str_replace("{" . $relPrefix . "product_old_price}", "", $data_add); + $data_add = str_replace("{" . $relPrefix . "product_price_saving}", "", $data_add); + } + + return $data_add; + } + + /* + * function to get products parent id + * + * @return: int + */ + + /** + * @param integer $productId Product id + * @param integer $totalAttribute Total attribute + * @param integer $selectedPropertyId Selected property id + * @param integer $selectedsubpropertyId Selected sub property id + * + * @return array + * + * @throws \Exception + * @since 2.1.0 + */ + public static function getproductStockStatus( + $productId = 0, + $totalAttribute = 0, + $selectedPropertyId = 0, + $selectedsubpropertyId = 0 + ) { + return RedshopEntityProduct::getInstance($productId)->getStockstatus( + $totalAttribute, + $selectedPropertyId, + $selectedsubpropertyId + ); } public static function getassociatetag($productId = 0) @@ -1747,144 +2154,14 @@ public static function getProductCaterories($productId, $displayLink = 0) } $prodCatsObject = new stdClass; - $prodCatsObject->name = $ppCat . $pspacediv . $pCat . $spacediv . $row->name; - $prodCatsObject->link = $catlink; - $prodCatsObjectArray[] = $prodCatsObject; - } - - return $prodCatsObjectArray; - } - - public static function getProductOnSaleComment($product = array(), $data_add = "") - { - if (strpos($data_add, "{if product_on_sale}") && strpos($data_add, "{product_on_sale end if}") !== false) { - if ($product->product_on_sale == 1 && (($product->discount_stratdate == 0 && $product->discount_enddate == 0) || ($product->discount_stratdate <= time( - ) && $product->discount_enddate >= time()))) { - $data_add = str_replace( - "{discount_start_date}", - RedshopHelperDatetime::convertDateFormat($product->discount_stratdate), - $data_add - ); - $data_add = str_replace( - "{discount_end_date}", - RedshopHelperDatetime::convertDateFormat($product->discount_enddate), - $data_add - ); - $data_add = str_replace("{if product_on_sale}", '', $data_add); - $data_add = str_replace("{product_on_sale end if}", '', $data_add); - } else { - $template_pd_sdata = strstr($data_add, '{if product_on_sale}', true); - $template_pd_edata = substr(strstr($data_add, '{product_on_sale end if}'), 24); - $data_add = $template_pd_sdata . $template_pd_edata; - } - - $data_add = str_replace("{discount_start_date}", '', $data_add); - $data_add = str_replace("{discount_end_date}", '', $data_add); - } - - return $data_add; - } - - public static function getSpecialProductComment($product = array(), $data_add = "") - { - if (strpos($data_add, "{if product_special}") !== false && strpos( - $data_add, - "{product_special end if}" - ) !== false) { - if ($product->product_special == 0) { - $template_pd_sdata = explode('{if product_special}', $data_add); - $template_pd_edata = explode('{product_special end if}', $template_pd_sdata [1]); - $data_add = $template_pd_sdata[0] . $template_pd_edata[1]; - } - - $data_add = str_replace("{if product_special}", '', $data_add); - $data_add = str_replace("{product_special end if}", '', $data_add); - } - - return $data_add; - } - - public static function getProductMinDeliveryTime($productId = 0, $sectionId = 0, $section = '', $loadDiv = 1) - { - // Initialiase variables. - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - if (!$sectionId && !$section) { - $query - ->from($db->qn('#__redshop_product_stockroom_xref') . ' AS ps') - ->where($db->qn('ps.product_id') . ' = ' . (int)$productId); - } else { - $query - ->from($db->qn('#__redshop_product_attribute_stockroom_xref') . ' AS ps') - ->where($db->qn('ps.section_id') . ' = ' . (int)$sectionId) - ->where($db->qn('ps.section') . ' = ' . $db->q($section)); - } - - // Create the base select statement. - $query->select( - array( - 'min_del_time as deltime', - 's.max_del_time', - 's.delivery_time' - ) - ) - ->join('', $db->qn('#__redshop_stockroom') . ' AS s') - ->where($db->qn('ps.stockroom_id') . ' = ' . $db->qn('s.stockroom_id')) - ->where($db->qn('ps.quantity') . ' > 0 ') - ->order($db->qn('min_del_time') . ' ASC'); - - // Set the query and load the result. - $db->setQuery($query, 0, 1); - - try { - $result = $db->loadObject(); - } catch (RuntimeException $e) { - throw new RuntimeException($e->getMessage(), $e->getCode()); - } - - $product_delivery_time = ''; - - if ($result) { - // Append where clause to get Maximum Delivery time of Minimum Delivery stockroom - $query->where($db->qn('s.min_del_time') . ' = ' . (int)$result->deltime); - - // Set the query and load the row. - $db->setQuery($query, 0, 1); - - try { - $row = $db->loadObject(); - } catch (RuntimeException $e) { - throw new RuntimeException($e->getMessage(), $e->getCode()); - } - - if ($row->deltime == 0 || $row->deltime == ' ') { - $product_delivery_time = ''; - } else { - if ($row->delivery_time == "Days") { - $duration = JText::_('COM_REDSHOP_DAYS'); - } else { - $row->deltime = $row->deltime / 7; - $row->max_del_time = $row->max_del_time / 7; - $duration = JText::_('COM_REDSHOP_WEEKS'); - } - - $product_delivery_time = (int)$row->deltime . "-" . (int)$row->max_del_time . " " . $duration; - } - } - - if ($product_delivery_time && $loadDiv) { - $product_delivery_time = '
    ' . $product_delivery_time . '
    '; + $prodCatsObject->name = $ppCat . $pspacediv . $pCat . $spacediv . $row->name; + $prodCatsObject->link = $catlink; + $prodCatsObjectArray[] = $prodCatsObject; } - return $product_delivery_time; + return $prodCatsObjectArray; } - /* - * function to get products parent id - * - * @return: int - */ public static function getMainParentProduct($parent_id) { $db = JFactory::getDbo(); @@ -1904,101 +2181,6 @@ public static function getMainParentProduct($parent_id) return $parent_id; } - public static function getProductNotForSaleComment( - $product = array(), - $data_add = "", - $attributes = array(), - $is_relatedproduct = 0, - $seoTemplate = "" - ) { - $showPrice = true; - - if ($product->expired || $product->not_for_sale == 1) { - $showPrice = false; - } - - if ($showPrice) { - // Product show price without formatted - $applytax = \Redshop\Template\Helper::isApplyVat($data_add); - - if ($applytax) { - $GLOBAL ['without_vat'] = false; - } else { - $GLOBAL ['without_vat'] = true; - } - - $data_add = RedshopHelperProductPrice::getShowPrice( - $product->product_id, - $data_add, - $seoTemplate, - 0, - $is_relatedproduct, - $attributes - ); - } else { - $relPrefix = ($is_relatedproduct) ? 'rel' : ''; - $data_add = str_replace("{" . $relPrefix . "product_price_lbl}", "", $data_add); - $data_add = str_replace("{" . $relPrefix . "product_price}", "", $data_add); - $data_add = str_replace("{" . $relPrefix . "product_price_novat}", "", $data_add); - $data_add = str_replace("{" . $relPrefix . "price_excluding_vat}", "", $data_add); - $data_add = str_replace("{" . $relPrefix . "product_price_table}", "", $data_add); - $data_add = str_replace("{" . $relPrefix . "product_old_price}", "", $data_add); - $data_add = str_replace("{" . $relPrefix . "product_price_saving}", "", $data_add); - } - - return $data_add; - } - - /** - * @param integer $productId Product id - * @param integer $totalAttribute Total attribute - * @param integer $selectedPropertyId Selected property id - * @param integer $selectedsubpropertyId Selected sub property id - * - * @return array - * - * @throws \Exception - * @since 2.1.0 - */ - public static function getproductStockStatus( - $productId = 0, - $totalAttribute = 0, - $selectedPropertyId = 0, - $selectedsubpropertyId = 0 - ) { - return RedshopEntityProduct::getInstance($productId)->getStockstatus( - $totalAttribute, - $selectedPropertyId, - $selectedsubpropertyId - ); - } - - public static function getJcommentEditor($product = array(), $data_add = "") - { - $app = JFactory::getApplication(); - $product_reviews = ""; - $productId = $product->product_id; - - if ($productId && strpos($data_add, "{jcomments off}") === false && strpos( - $data_add, - "{jcomments on}" - ) !== false) { - $comments = $app->getCfg('absolute_path') . '/components/com_jcomments/jcomments.php'; - - if (file_exists($comments)) { - require_once $comments; - $product_reviews = JComments::showComments($productId, 'com_redshop', $product->product_name); - } - - $data_add = str_replace("{jcomments on}", $product_reviews, $data_add); - } - - $data_add = str_replace("{jcomments on}", $product_reviews, $data_add); - $data_add = str_replace("{jcomments off}", "", $data_add); - - return $data_add; - } - public static function getProductCategoryImage($productId = 0, $category_img = '', $link = '', $width, $height) { $result = \Redshop\Product\Product::getProductById($productId); @@ -2516,6 +2698,104 @@ public static function getRelatedTemplateView($templateDesc, $productId) return $templateDesc; } + public static function getSpecialProductComment($product = array(), $data_add = "") + { + if (strpos($data_add, "{if product_special}") !== false && strpos( + $data_add, + "{product_special end if}" + ) !== false) { + if ($product->product_special == 0) { + $template_pd_sdata = explode('{if product_special}', $data_add); + $template_pd_edata = explode('{product_special end if}', $template_pd_sdata [1]); + $data_add = $template_pd_sdata[0] . $template_pd_edata[1]; + } + + $data_add = str_replace("{if product_special}", '', $data_add); + $data_add = str_replace("{product_special end if}", '', $data_add); + } + + return $data_add; + } + + /** + * replace related product attribute price list + * + * child product as related product concept is included + * New Tag : {relproduct_attribute_pricelist} = related product attribute price list + * + * @params: $id : product id + * @params: $templatedata : template data + */ + public static function replaceAttributePriceList($id, $templatedata) + { + $output = ""; + $attributes = \Redshop\Product\Attribute::getProductAttribute($id, 0, 0, 1); + + $k = 0; + + for ($i = 0, $in = count($attributes); $i < $in; $i++) { + $attribute = $attributes[$i]; + $attribute_name = $attribute->text; + $attributeId = $attribute->value; + $propertys = RedshopHelperProduct_Attribute::getAttributeProperties(0, $attributeId); + + for ($p = 0, $pn = count($propertys); $p < $pn; $p++) { + $property = $propertys[$p]; + + $propertyId = $property->value; + $property_name = $property->text; + $proprty_price = $property->property_price; + $property_formated_price = RedshopHelperProductPrice::formattedPrice($proprty_price); + $proprty_oprand = $property->oprand; + + $output .= ''; + + $subpropertys = RedshopHelperProduct_Attribute::getAttributeSubProperties(0, $propertyId); + + for ($s = 0, $sn = count($subpropertys); $s < $sn; $s++) { + $subproperty = $subpropertys[$s]; + + $subPropertyId = $subproperty->value; + $subproperty_name = $subproperty->text; + $subproprty_price = $subproperty->subattribute_color_price; + $subproprty_oprand = $subproperty->oprand; + } + + $k++; + } + } + #$output = ($output!="") ? "
    ".$output."
    " : ""; + $templatedata = str_replace("{relproduct_attribute_pricelist}", $output, $templatedata); + + return $templatedata; + } + + /** + * Method for get child products of specific product + * + * @param integer $productId Product ID + * + * @return array + * @since 2.1.0 + */ + public static function getChildProduct($productId = 0) + { + $childProducts = RedshopEntityProduct::getInstance($productId)->getChildProducts(); + + if ($childProducts->isEmpty()) { + return array(); + } + + $results = array(); + + foreach ($childProducts->getAll() as $child) { + /** @var RedshopEntityProduct $child */ + $results[] = $child->getItem(); + } + + return $results; + } + /** * Get menu detail * @@ -2549,90 +2829,38 @@ public static function getCategoryNavigationlist($category_id) $tmpItemid = $cItemid; } else { $tmpItemid = JFactory::getApplication()->input->get('Itemid'); - } - - $category_list[$i]['category_id'] = $categorylist->id; - $category_list[$i]['category_name'] = $categorylist->name; - $category_list[$i]['catItemid'] = $tmpItemid; - } - - if ($category_parent_id) { - $i++; - array_merge($category_list, self::getCategoryNavigationlist($category_parent_id)); - } - - return $category_list; - } - - /** - * Get Menu Information - * - * @param int $Itemid Item id - * @param int $sectionId Section id - * @param string $sectionName Section name - * @param string $menuView Menu view - * @param bool $isRedshop Is redshop - * - * @return mixed|null - */ - public static function getMenuInformation( - $Itemid = 0, - $sectionId = 0, - $sectionName = '', - $menuView = '', - $isRedshop = true - ) { - $menu = JFactory::getApplication()->getMenu(); - $values = array(); - - if ($menuView != "") { - if ($items = explode('&', $menuView)) { - $values['view'] = $items[0]; - unset($items[0]); - - if (!empty($items)) { - foreach ($items as $item) { - $value = explode('=', $item); - $values[$value[0]] = $value[1]; - } - } - } - } - - if ($Itemid != 0) { - return $menu->getItem($Itemid); - } + } - if ($isRedshop) { - $menuItems = RedshopHelperRouter::getRedshopMenuItems(); - } else { - $menuItems = $menu->getMenu(); + $category_list[$i]['category_id'] = $categorylist->id; + $category_list[$i]['category_name'] = $categorylist->name; + $category_list[$i]['catItemid'] = $tmpItemid; } - foreach ($menuItems as $oneMenuItem) { - if (!RedshopHelperRouter::checkMenuQuery($oneMenuItem, $values)) { - break; - } + if ($category_parent_id) { + $i++; + array_merge($category_list, self::getCategoryNavigationlist($category_parent_id)); + } - if ($sectionName != '') { - if ($sectionId != 0) { - if ($oneMenuItem->params->get($sectionName) != $sectionId) { - break; - } - } else { - if ($oneMenuItem->params->get($sectionName, false) !== false) { - break; - } - } - } + return $category_list; + } - return $oneMenuItem; + /** + * Get Parent Category + * + * @param int $id + * + * @return int parentId \ null + * + */ + public static function getParentCategory($id = 0) + { + if ($result = RedshopEntityCategory::getInstance($id)->getItem()) { + return $result->parent_id; } return null; } - /** * Get Category Product * @@ -2653,6 +2881,8 @@ public static function getCategoryProduct($productId = 0) return ''; } + // Get Product subscription price + /** * @param int $id * @@ -2911,6 +3141,36 @@ public static function makeAttributeCart( return $data; } + public static function makeTotalPriceByOprand($price = 0, $oprandArr = array(), $priceArr = array()) + { + $setEqual = true; + + for ($i = 0, $in = count($oprandArr); $i < $in; $i++) { + $oprand = $oprandArr[$i]; + $subprice = $priceArr[$i]; + + if ($oprand == "-") { + $price -= $subprice; + } elseif ($oprand == "+") { + $price += $subprice; + } elseif ($oprand == "*") { + $price *= $subprice; + } elseif ($oprand == "/") { + $price /= $subprice; + } elseif ($oprand == "=") { + $price = $subprice; + $setEqual = false; + break; + } + } + + $retArr = array(); + $retArr[0] = $setEqual; + $retArr[1] = $price; + + return $retArr; + } + public static function makeAccessoryCart($attArr = array(), $productId = 0, $user_id = 0) { $user = JFactory::getUser(); @@ -3045,235 +3305,59 @@ public static function makeAccessoryCart($attArr = array(), $productId = 0, $use '', array( 'component' => 'com_redshop' - ) - ); - } - - $accessory_total_price = $accessory_total_price - $accessory_vat_price; - - return array($displayaccessory, $accessory_total_price, $accessory_vat_price); - } - - // Get Product subscription price - public static function getProductSubscriptionDetail($productId, $subscription_id) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true); - $query->select('*') - ->from($db->qn('#__redshop_product_subscription')) - ->where($db->qn('product_id') . ' = ' . (int)$productId) - ->where($db->qn('subscription_id') . ' = ' . (int)$subscription_id); - $db->setQuery($query); - - return $db->loadObject(); - } - - /** - * Method for get property or sub object - * - * @param string $sectionId Section ID - * @param string $section Section - * - * @return object - * - */ - public static function getProperty($sectionId, $section) - { - if ($section == 'property') { - $properties = RedshopHelperProduct_Attribute::getAttributeProperties($sectionId); - - if (!empty($properties)) { - $properties[0]->product_price = $properties[0]->property_price; - - return $properties[0]; - } - } elseif ($section == 'subproperty') { - $properties = RedshopHelperProduct_Attribute::getAttributeSubProperties($sectionId); - - if (!empty($properties)) { - $properties[0]->product_price = $properties[0]->subattribute_color_price; - - return $properties[0]; - } - } - - return null; - } - - /** - * Get Parent Category - * - * @param int $id - * - * @return int parentId \ null - * - */ - public static function getParentCategory($id = 0) - { - if ($result = RedshopEntityCategory::getInstance($id)->getItem()) { - return $result->parent_id; - } - - return null; - } - - /** - * @param integer $productId Product id - * @param integer $relatedId Related id - * - * @return mixed - * - * @since 2.1.0 - */ - public static function getRelatedProduct($productId = 0, $relatedId = 0) - { - $db = JFactory::getDbo(); - $where = ''; - $orderby = "p.product_id ASC"; - $orderbyRelated = ""; - - if (Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD')) { - $orderby = Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD'); - $orderbyRelated = ""; - } - - if ($productId != 0) { - // Sanitize ids - $productIds = explode(',', $productId); - $productIds = Joomla\Utilities\ArrayHelper::toInteger($productIds); - - if (RedshopHelperUtility::isRedProductFinder()) { - $q = $db->getQuery(true); - $q->select($db->qn('extrafield')) - ->from($db->qn('#__redproductfinder_types')) - ->where($db->qn('type_select') . ' = ' . $db->q('Productfinder_datepicker')); - $db->setQuery($q); - $finaltypetype_result = $db->loadObject(); - } else { - $finaltypetype_result = array(); - } - - $where .= $db->qn('r.product_id') . ' IN (' . implode(',', $productIds) . ') '; - - if (Redshop::getConfig()->get('TWOWAY_RELATED_PRODUCT')) { - if (Redshop::getConfig()->get( - 'DEFAULT_RELATED_ORDERING_METHOD' - ) == "r.ordering ASC" || Redshop::getConfig()->get( - 'DEFAULT_RELATED_ORDERING_METHOD' - ) == "r.ordering DESC") { - $orderby = ""; - $orderbyRelated = Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD'); - } - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_product_related', 'r')) - ->where($db->qn('r.product_id') . ' IN (' . implode(',', $productIds) . ') ') - ->orWhere($db->qn('r.related_id') . ' IN (' . implode(',', $productIds) . ') '); - - if (!empty($orderbyRelated)) { - $query->order($orderbyRelated); - } - - $db->setQuery($query); - $list = $db->loadObjectlist(); - - $relatedArr = array(); - - for ($i = 0, $in = count($list); $i < $in; $i++) { - if ($list[$i]->product_id == $productId) { - $relatedArr[] = $list[$i]->related_id; - } else { - $relatedArr[] = $list[$i]->product_id; - } - } - - if (empty($relatedArr)) { - return array(); - } - - // Sanitize ids - $relatedArr = Joomla\Utilities\ArrayHelper::toInteger($relatedArr); - $relatedArr = array_unique($relatedArr); - - $query = $db->getQuery(true) - ->select((int)$productId . ' AS ' . $db->qn('mainproduct_id')) - ->select('p.*') - ->from($db->qn('#__redshop_product', 'p')) - ->where($db->qn('published') . ' = 1') - ->where($db->qn('p.product_id') . ' IN (' . implode(',', $relatedArr) . ') '); - - if (!empty($orderby)) { - $query->order($orderby); - } - - $db->setQuery($query); - $list = $db->loadObjectlist(); - - return $list; - } - } - - $query = $db->getQuery(true) - ->select(array($db->qn('r.product_id', 'mainproduct_id'), 'p.*')); - - if ($relatedId != 0) { - $query->where($db->qn('r.related_id') . ' = ' . (int)$relatedId); - } - - if (count($finaltypetype_result) > 0 && $finaltypetype_result->extrafield != '' - && (Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt ASC' || Redshop::getConfig( - )->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt DESC')) { - $query->select('e.*'); + ) + ); } - $query->from($db->qn('#__redshop_product_related', 'r')) - ->leftJoin( - $db->qn('#__redshop_product', 'p') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('r.related_id') - ); + $accessory_total_price = $accessory_total_price - $accessory_vat_price; - if (!empty($finaltypetype_result) && !empty($finaltypetype_result->extrafield) - && (Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt ASC' - || Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt DESC')) { - $query->leftJoin( - $db->qn('#__redshop_fields_data', 'e') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('e.itemid') - ); - } + return array($displayaccessory, $accessory_total_price, $accessory_vat_price); + } - $query->where($db->qn('p.published') . ' = 1'); + public static function getProductSubscriptionDetail($productId, $subscription_id) + { + $db = JFactory::getDbo(); - if (count($finaltypetype_result) > 0 && $finaltypetype_result->extrafield != '' - && (Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt ASC' || Redshop::getConfig( - )->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt DESC')) { - $query->where($db->qn('e.fieldid') . ' = ' . (int)$finaltypetype_result->extrafield) - ->where($db->qn('e.section') . ' = 17'); - } + $query = $db->getQuery(true); + $query->select('*') + ->from($db->qn('#__redshop_product_subscription')) + ->where($db->qn('product_id') . ' = ' . (int)$productId) + ->where($db->qn('subscription_id') . ' = ' . (int)$subscription_id); + $db->setQuery($query); - if (!empty($where)) { - $query->where($where); - } + return $db->loadObject(); + } - $query->group($db->qn('r.related_id')); + /** + * Method for get property or sub object + * + * @param string $sectionId Section ID + * @param string $section Section + * + * @return object + * + */ + public static function getProperty($sectionId, $section) + { + if ($section == 'property') { + $properties = RedshopHelperProduct_Attribute::getAttributeProperties($sectionId); - if ((Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt ASC' - || Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt DESC')) { - if (Redshop::getConfig()->get('DEFAULT_RELATED_ORDERING_METHOD') == 'e.data_txt ASC') { - $s = "STR_TO_DATE( e.data_txt, '%d-%m-%Y' ) ASC"; - } else { - $s = "STR_TO_DATE( e.data_txt, '%d-%m-%Y' ) DESC"; - } + if (!empty($properties)) { + $properties[0]->product_price = $properties[0]->property_price; - $query->order($s); - } else { - $query->order($orderby); - } + return $properties[0]; + } + } elseif ($section == 'subproperty') { + $properties = RedshopHelperProduct_Attribute::getAttributeSubProperties($sectionId); - $db->setQuery($query); + if (!empty($properties)) { + $properties[0]->product_price = $properties[0]->subattribute_color_price; - $list = $db->loadObjectlist(); + return $properties[0]; + } + } - return $list; + return null; } public static function getSelectedAccessoryArray($data = array()) @@ -3415,59 +3499,6 @@ public static function getSelectedAttributeArray($data = array()) return $ret; } - /** - * replace related product attribute price list - * - * child product as related product concept is included - * New Tag : {relproduct_attribute_pricelist} = related product attribute price list - * - * @params: $id : product id - * @params: $templatedata : template data - */ - public static function replaceAttributePriceList($id, $templatedata) - { - $output = ""; - $attributes = \Redshop\Product\Attribute::getProductAttribute($id, 0, 0, 1); - - $k = 0; - - for ($i = 0, $in = count($attributes); $i < $in; $i++) { - $attribute = $attributes[$i]; - $attribute_name = $attribute->text; - $attributeId = $attribute->value; - $propertys = RedshopHelperProduct_Attribute::getAttributeProperties(0, $attributeId); - - for ($p = 0, $pn = count($propertys); $p < $pn; $p++) { - $property = $propertys[$p]; - - $propertyId = $property->value; - $property_name = $property->text; - $proprty_price = $property->property_price; - $property_formated_price = RedshopHelperProductPrice::formattedPrice($proprty_price); - $proprty_oprand = $property->oprand; - - $output .= ''; - - $subpropertys = RedshopHelperProduct_Attribute::getAttributeSubProperties(0, $propertyId); - - for ($s = 0, $sn = count($subpropertys); $s < $sn; $s++) { - $subproperty = $subpropertys[$s]; - - $subPropertyId = $subproperty->value; - $subproperty_name = $subproperty->text; - $subproprty_price = $subproperty->subattribute_color_price; - $subproprty_oprand = $subproperty->oprand; - } - - $k++; - } - } - #$output = ($output!="") ? "
    ".$output."
    " : ""; - $templatedata = str_replace("{relproduct_attribute_pricelist}", $output, $templatedata); - - return $templatedata; - } - /** * Get formatted number * @@ -3570,6 +3601,12 @@ public static function getuserfield($orderitemid = 0, $sectionId = 12) ) . ""; } + /* + * load Products Under categoriesd ACL Sopper Group + * + * return : "," separated product string + */ + public static function makeAttributeOrder( $order_item_id = 0, $is_accessory = 0, @@ -3805,11 +3842,6 @@ public static function makeAttributeOrder( return $data; } - /* - * load Products Under categoriesd ACL Sopper Group - * - * return : "," separated product string - */ public static function loadAclProducts() { $db = JFactory::getDbo(); @@ -3874,6 +3906,45 @@ public static function loadAclProducts() return $aclProduct; } + public static function makeAccessoryQuotation($quotation_item_id = 0, $quotation_status = 2) + { + $displayaccessory = ""; + $Itemdata = RedshopHelperQuotation::getQuotationItemAccessoryDetail($quotation_item_id); + + if (count($Itemdata) > 0) { + $displayaccessory .= "
    " . JText::_( + "COM_REDSHOP_ACCESSORY" + ) . ":
    "; + + for ($i = 0, $in = count($Itemdata); $i < $in; $i++) { + $displayaccessory .= "
    " . urldecode( + $Itemdata[$i]->accessory_item_name + ) . " "; + + if ($quotation_status != 1 || ($quotation_status == 1 && Redshop::getConfig()->get( + 'SHOW_QUOTATION_PRICE' + ) == 1)) { + $displayaccessory .= "(" . RedshopHelperProductPrice::formattedPrice( + $Itemdata[$i]->accessory_price + $Itemdata[$i]->accessory_vat + ) . ")"; + } + + $displayaccessory .= "
    "; + $displayaccessory .= self::makeAttributeQuotation( + $quotation_item_id, + 1, + $Itemdata[$i]->accessory_id, + $quotation_status + ); + } + } else { + $Itemdata = RedshopHelperQuotation::getQuotationProduct(0, $quotation_item_id); + $displayaccessory = $Itemdata[0]->product_accessory; + } + + return $displayaccessory; + } + public static function makeAttributeQuotation( $quotation_item_id = 0, $is_accessory = 0, @@ -3919,45 +3990,6 @@ public static function makeAttributeQuotation( return $displayattribute; } - public static function makeAccessoryQuotation($quotation_item_id = 0, $quotation_status = 2) - { - $displayaccessory = ""; - $Itemdata = RedshopHelperQuotation::getQuotationItemAccessoryDetail($quotation_item_id); - - if (count($Itemdata) > 0) { - $displayaccessory .= "
    " . JText::_( - "COM_REDSHOP_ACCESSORY" - ) . ":
    "; - - for ($i = 0, $in = count($Itemdata); $i < $in; $i++) { - $displayaccessory .= "
    " . urldecode( - $Itemdata[$i]->accessory_item_name - ) . " "; - - if ($quotation_status != 1 || ($quotation_status == 1 && Redshop::getConfig()->get( - 'SHOW_QUOTATION_PRICE' - ) == 1)) { - $displayaccessory .= "(" . RedshopHelperProductPrice::formattedPrice( - $Itemdata[$i]->accessory_price + $Itemdata[$i]->accessory_vat - ) . ")"; - } - - $displayaccessory .= "
    "; - $displayaccessory .= self::makeAttributeQuotation( - $quotation_item_id, - 1, - $Itemdata[$i]->accessory_id, - $quotation_status - ); - } - } else { - $Itemdata = RedshopHelperQuotation::getQuotationProduct(0, $quotation_item_id); - $displayaccessory = $Itemdata[0]->product_accessory; - } - - return $displayaccessory; - } - public static function getValidityDate($period, $data) { $todate = mktime(0, 0, 0, (int)date('m'), (int)date('d') + $period, (int)date('Y')); @@ -4029,6 +4061,10 @@ public static function getProductMediaName($productId) return $res; } + /* + * Update used seraial number status + */ + public static function getProdcutSerialNumber($productId, $is_used = 0) { $db = JFactory::getDbo(); @@ -4052,9 +4088,6 @@ public static function getProdcutSerialNumber($productId, $is_used = 0) return $rs; } - /* - * Update used seraial number status - */ public static function updateProdcutSerialNumber($serial_id) { $db = JFactory::getDbo(); @@ -4182,36 +4215,6 @@ public static function insertProdcutUserfield($id = 'NULL', $cart = array(), $or return; } - public static function makeTotalPriceByOprand($price = 0, $oprandArr = array(), $priceArr = array()) - { - $setEqual = true; - - for ($i = 0, $in = count($oprandArr); $i < $in; $i++) { - $oprand = $oprandArr[$i]; - $subprice = $priceArr[$i]; - - if ($oprand == "-") { - $price -= $subprice; - } elseif ($oprand == "+") { - $price += $subprice; - } elseif ($oprand == "*") { - $price *= $subprice; - } elseif ($oprand == "/") { - $price /= $subprice; - } elseif ($oprand == "=") { - $price = $subprice; - $setEqual = false; - break; - } - } - - $retArr = array(); - $retArr[0] = $setEqual; - $retArr[1] = $price; - - return $retArr; - } - public static function replaceSubPropertyData( $productId = 0, $accessoryId = 0, diff --git a/libraries/redshop/helper/product/accessory.php b/libraries/redshop/helper/product/accessory.php index 7e861dd6ae6..afec33efdc3 100644 --- a/libraries/redshop/helper/product/accessory.php +++ b/libraries/redshop/helper/product/accessory.php @@ -16,231 +16,228 @@ */ class RedshopHelperProductAccessory { - /** - * Method for replace accessory data. - * - * @param integer $productId Product ID - * @param integer $relProductId Related product ID - * @param array $accessory Accessories data. - * @param string $templateContent Template content - * @param boolean $isChild True for accessory products is child. - * @param array $selectedAccessories Selected accessory. - * - * @return mixed|string - * - * @since 2.1.0 - * - * @throws Exception - */ - public static function replaceAccessoryData($productId = 0, $relProductId = 0, $accessory = array(), $templateContent = '', $isChild = false, $selectedAccessories = array()) - { - $input = JFactory::getApplication()->input; - $viewAcc = $input->get('viewacc', 1); - $layout = $input->get('layout'); - $isAjax = 0; - $prefix = ""; - - if ($layout == "viewajaxdetail") - { - $isAjax = 1; - $prefix = "ajax_"; - } - - $productId = $relProductId != 0 ? $relProductId : $productId; - - $accessoryTemplate = \Redshop\Template\Helper::getAccessory($templateContent); - - if (null === $accessoryTemplate) - { - return $templateContent; - } - - if (empty($accessory)) - { - $templateContent = str_replace("{accessory_template:" . $accessoryTemplate->name . "}", "", $templateContent); - - return $templateContent; - } - - $accessoryTemplateData2 = $accessoryTemplate->template_desc; - - $accessoryWrapper = RedshopTagsReplacer::_( - 'accessory', - $accessoryTemplateData2, - array( - 'accessory' => $accessory, - 'productId' => $productId, - 'prefix' => $prefix, - 'relProductId' => $relProductId, - 'isChild' => $isChild, - 'selectedAccessories' => $selectedAccessories, - 'isAjax' => $isAjax, - 'templateContent' => $templateContent - ) - ); - - // Attribute ajax change - if ($viewAcc != 1 && Redshop::getConfig()->getInt('AJAX_CART_BOX') != 0) - { - $accessoryWrapper = ''; - } - - $templateContent = str_replace( - "{accessory_template:" . $accessoryTemplate->name . "}", - $accessoryWrapper, - $templateContent - ); - - return $templateContent; - } - - /** - * Method for get image width height from tags in template - * - * @param string $template Template content - * @param string $imageTag Accessory image tag - * @param integer $width Return variable width - * @param integer $height Return variable height - * - * @return void - * - * @since 2.1.0 - */ - public static function getWidthHeight($template, &$imageTag, &$width, &$height) - { - if (strpos($template, "{accessory_main_image_3}") !== false) - { - $imageTag = '{accessory_main_image_3}'; - $height = Redshop::getConfig()->get('ACCESSORY_THUMB_HEIGHT_3'); - $width = Redshop::getConfig()->get('ACCESSORY_THUMB_WIDTH_3'); - } - elseif (strpos($template, "{accessory_main_image_2}") !== false) - { - $imageTag = '{accessory_main_image_2}'; - $height = Redshop::getConfig()->get('ACCESSORY_THUMB_HEIGHT_2'); - $width = Redshop::getConfig()->get('ACCESSORY_THUMB_WIDTH_2'); - } - elseif (strpos($template, "{accessory_main_image_1}") !== false) - { - $imageTag = '{accessory_main_image_1}'; - $height = Redshop::getConfig()->get('ACCESSORY_THUMB_HEIGHT'); - $width = Redshop::getConfig()->get('ACCESSORY_THUMB_WIDTH'); - } - else - { - $imageTag = '{accessory_main_image}'; - $height = Redshop::getConfig()->get('ACCESSORY_THUMB_HEIGHT'); - $width = Redshop::getConfig()->get('ACCESSORY_THUMB_WIDTH'); - } - } - - /** - * Method for replace main accessory tags. - * - * @param string $accessoryTemplate Accessory template data - * @param string $templateContent Template content - * @param object $product Product Data - * @param integer $userId User ID - * - * @return void - * - * @since 2.1.0 - */ - public static function replaceMainAccessory(&$accessoryTemplate, $templateContent, $product, $userId) - { - if (strpos($accessoryTemplate, "{if accessory_main}") === false - || strpos($accessoryTemplate, "{accessory_main end if}") === false) - { - return; - } - - $accessoryTemplate = explode('{if accessory_main}', $accessoryTemplate); - $accessoryStart = $accessoryTemplate[0]; - $accessoryTemplate = explode('{accessory_main end if}', $accessoryTemplate[1]); - $accessoryEnd = $accessoryTemplate[1]; - $accessoryMiddle = $accessoryTemplate[0]; - - if (strpos($accessoryMiddle, "{accessory_main_short_desc}") !== false) - { - $accessoryMiddle = str_replace( - "{accessory_main_short_desc}", - RedshopHelperUtility::limitText( - $product->product_s_desc, - Redshop::getConfig()->get('ACCESSORY_PRODUCT_DESC_MAX_CHARS'), - Redshop::getConfig()->get('ACCESSORY_PRODUCT_DESC_END_SUFFIX') - ), - $accessoryMiddle - ); - } - - if (strpos($accessoryMiddle, "{accessory_main_title}") !== false) - { - $accessoryMiddle = str_replace( - "{accessory_main_title}", - RedshopHelperUtility::limitText( - $product->product_name, - Redshop::getConfig()->get('ACCESSORY_PRODUCT_TITLE_MAX_CHARS'), - Redshop::getConfig()->get('ACCESSORY_PRODUCT_TITLE_END_SUFFIX') - ), - $accessoryMiddle - ); - } - - $accessoryProductDetail = "" . JText::_('COM_REDSHOP_READ_MORE') . ""; - $accessoryMiddle = str_replace("{accessory_main_readmore}", $accessoryProductDetail, $accessoryMiddle); - $accessoryMainImage = $product->product_full_image; - $accessoryMainImage2 = ''; - - self::getWidthHeight($accessoryMiddle, $accessoryImgTag, $accessoryWidthThumb, $accessoryHeightThumb); - - if (JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . "product/" . $accessoryMainImage)) - { - $thumbUrl = RedshopHelperMedia::getImagePath( - $accessoryMainImage, - '', - 'thumb', - 'product', - $accessoryWidthThumb, - $accessoryHeightThumb, - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') - ); - - if (Redshop::getConfig()->get('ACCESSORY_PRODUCT_IN_LIGHTBOX') == 1) - { - $accessoryMainImage2 = "" - . ""; - } - else - { - $accessoryMainImage2 = ""; - } - } - - $accessoryMiddle = str_replace($accessoryImgTag, $accessoryMainImage2, $accessoryMiddle); - $productPrices = array(); - - if (strpos($accessoryMiddle, "{accessory_mainproduct_price}") !== false - || strpos($templateContent, "{selected_accessory_price}") !== false) - { - $productPrices = RedshopHelperProductPrice::getNetPrice($product->product_id, $userId, 1, $templateContent); - } - - if (strpos($accessoryMiddle, "{accessory_mainproduct_price}") !== false) - { - if (Redshop::getConfig()->get('SHOW_PRICE') - && (!Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') - || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') - && Redshop::getConfig()->get('SHOW_QUOTATION_PRICE')))) - { - $accessoryMainProductPrice = RedshopHelperProductPrice::priceReplacement($productPrices['product_price']); - - $accessoryMiddle = str_replace("{accessory_mainproduct_price}", $accessoryMainProductPrice, $accessoryMiddle); - } - } - - $accessoryMiddle = Redshop\Product\Stock::replaceInStock($product->product_id, $accessoryMiddle); - $accessoryTemplate = $accessoryStart . $accessoryMiddle . $accessoryEnd; - } + /** + * Method for replace accessory data. + * + * @param integer $productId Product ID + * @param integer $relProductId Related product ID + * @param array $accessory Accessories data. + * @param string $templateContent Template content + * @param boolean $isChild True for accessory products is child. + * @param array $selectedAccessories Selected accessory. + * + * @return mixed|string + * + * @throws Exception + * @since 2.1.0 + * + */ + public static function replaceAccessoryData( + $productId = 0, + $relProductId = 0, + $accessory = array(), + $templateContent = '', + $isChild = false, + $selectedAccessories = array() + ) { + $input = JFactory::getApplication()->input; + $viewAcc = $input->get('viewacc', 1); + $layout = $input->get('layout'); + $isAjax = 0; + $prefix = ""; + + if ($layout == "viewajaxdetail") { + $isAjax = 1; + $prefix = "ajax_"; + } + + $productId = $relProductId != 0 ? $relProductId : $productId; + + $accessoryTemplate = \Redshop\Template\Helper::getAccessory($templateContent); + + if (null === $accessoryTemplate) { + return $templateContent; + } + + if (empty($accessory)) { + $templateContent = str_replace( + "{accessory_template:" . $accessoryTemplate->name . "}", + "", + $templateContent + ); + + return $templateContent; + } + + $accessoryTemplateData2 = $accessoryTemplate->template_desc; + + $accessoryWrapper = RedshopTagsReplacer::_( + 'accessory', + $accessoryTemplateData2, + array( + 'accessory' => $accessory, + 'productId' => $productId, + 'prefix' => $prefix, + 'relProductId' => $relProductId, + 'isChild' => $isChild, + 'selectedAccessories' => $selectedAccessories, + 'isAjax' => $isAjax, + 'templateContent' => $templateContent + ) + ); + + // Attribute ajax change + if ($viewAcc != 1 && Redshop::getConfig()->getInt('AJAX_CART_BOX') != 0) { + $accessoryWrapper = ''; + } + + $templateContent = str_replace( + "{accessory_template:" . $accessoryTemplate->name . "}", + $accessoryWrapper, + $templateContent + ); + + return $templateContent; + } + + /** + * Method for replace main accessory tags. + * + * @param string $accessoryTemplate Accessory template data + * @param string $templateContent Template content + * @param object $product Product Data + * @param integer $userId User ID + * + * @return void + * + * @since 2.1.0 + */ + public static function replaceMainAccessory(&$accessoryTemplate, $templateContent, $product, $userId) + { + if (strpos($accessoryTemplate, "{if accessory_main}") === false + || strpos($accessoryTemplate, "{accessory_main end if}") === false) { + return; + } + + $accessoryTemplate = explode('{if accessory_main}', $accessoryTemplate); + $accessoryStart = $accessoryTemplate[0]; + $accessoryTemplate = explode('{accessory_main end if}', $accessoryTemplate[1]); + $accessoryEnd = $accessoryTemplate[1]; + $accessoryMiddle = $accessoryTemplate[0]; + + if (strpos($accessoryMiddle, "{accessory_main_short_desc}") !== false) { + $accessoryMiddle = str_replace( + "{accessory_main_short_desc}", + RedshopHelperUtility::limitText( + $product->product_s_desc, + Redshop::getConfig()->get('ACCESSORY_PRODUCT_DESC_MAX_CHARS'), + Redshop::getConfig()->get('ACCESSORY_PRODUCT_DESC_END_SUFFIX') + ), + $accessoryMiddle + ); + } + + if (strpos($accessoryMiddle, "{accessory_main_title}") !== false) { + $accessoryMiddle = str_replace( + "{accessory_main_title}", + RedshopHelperUtility::limitText( + $product->product_name, + Redshop::getConfig()->get('ACCESSORY_PRODUCT_TITLE_MAX_CHARS'), + Redshop::getConfig()->get('ACCESSORY_PRODUCT_TITLE_END_SUFFIX') + ), + $accessoryMiddle + ); + } + + $accessoryProductDetail = "" . JText::_( + 'COM_REDSHOP_READ_MORE' + ) . ""; + $accessoryMiddle = str_replace("{accessory_main_readmore}", $accessoryProductDetail, $accessoryMiddle); + $accessoryMainImage = $product->product_full_image; + $accessoryMainImage2 = ''; + + self::getWidthHeight($accessoryMiddle, $accessoryImgTag, $accessoryWidthThumb, $accessoryHeightThumb); + + if (JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . "product/" . $accessoryMainImage)) { + $thumbUrl = RedshopHelperMedia::getImagePath( + $accessoryMainImage, + '', + 'thumb', + 'product', + $accessoryWidthThumb, + $accessoryHeightThumb, + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') + ); + + if (Redshop::getConfig()->get('ACCESSORY_PRODUCT_IN_LIGHTBOX') == 1) { + $accessoryMainImage2 = "" + . ""; + } else { + $accessoryMainImage2 = ""; + } + } + + $accessoryMiddle = str_replace($accessoryImgTag, $accessoryMainImage2, $accessoryMiddle); + $productPrices = array(); + + if (strpos($accessoryMiddle, "{accessory_mainproduct_price}") !== false + || strpos($templateContent, "{selected_accessory_price}") !== false) { + $productPrices = RedshopHelperProductPrice::getNetPrice($product->product_id, $userId, 1, $templateContent); + } + + if (strpos($accessoryMiddle, "{accessory_mainproduct_price}") !== false) { + if (Redshop::getConfig()->get('SHOW_PRICE') + && (!Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') + || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') + && Redshop::getConfig()->get('SHOW_QUOTATION_PRICE')))) { + $accessoryMainProductPrice = RedshopHelperProductPrice::priceReplacement( + $productPrices['product_price'] + ); + + $accessoryMiddle = str_replace( + "{accessory_mainproduct_price}", + $accessoryMainProductPrice, + $accessoryMiddle + ); + } + } + + $accessoryMiddle = Redshop\Product\Stock::replaceInStock($product->product_id, $accessoryMiddle); + $accessoryTemplate = $accessoryStart . $accessoryMiddle . $accessoryEnd; + } + + /** + * Method for get image width height from tags in template + * + * @param string $template Template content + * @param string $imageTag Accessory image tag + * @param integer $width Return variable width + * @param integer $height Return variable height + * + * @return void + * + * @since 2.1.0 + */ + public static function getWidthHeight($template, &$imageTag, &$width, &$height) + { + if (strpos($template, "{accessory_main_image_3}") !== false) { + $imageTag = '{accessory_main_image_3}'; + $height = Redshop::getConfig()->get('ACCESSORY_THUMB_HEIGHT_3'); + $width = Redshop::getConfig()->get('ACCESSORY_THUMB_WIDTH_3'); + } elseif (strpos($template, "{accessory_main_image_2}") !== false) { + $imageTag = '{accessory_main_image_2}'; + $height = Redshop::getConfig()->get('ACCESSORY_THUMB_HEIGHT_2'); + $width = Redshop::getConfig()->get('ACCESSORY_THUMB_WIDTH_2'); + } elseif (strpos($template, "{accessory_main_image_1}") !== false) { + $imageTag = '{accessory_main_image_1}'; + $height = Redshop::getConfig()->get('ACCESSORY_THUMB_HEIGHT'); + $width = Redshop::getConfig()->get('ACCESSORY_THUMB_WIDTH'); + } else { + $imageTag = '{accessory_main_image}'; + $height = Redshop::getConfig()->get('ACCESSORY_THUMB_HEIGHT'); + $width = Redshop::getConfig()->get('ACCESSORY_THUMB_WIDTH'); + } + } } diff --git a/libraries/redshop/helper/product/download.php b/libraries/redshop/helper/product/download.php index 0024f944454..1e2556d1af4 100644 --- a/libraries/redshop/helper/product/download.php +++ b/libraries/redshop/helper/product/download.php @@ -16,44 +16,46 @@ */ class RedshopHelperProductDownload { - /** - * Method to check product is downloadable or else - * - * @param integer $productId Product Id - * @param boolean $return If yes, return object. False return number of download - * - * @return object|integer - * - * @since 2.0.7 - */ - public static function checkDownload($productId, $return = false) - { - if (!$productId) - { - return !$return ? 0 : null; - } + /** + * Method to check product is downloadable or else + * + * @param integer $productId Product Id + * @param boolean $return If yes, return object. False return number of download + * + * @return object|integer + * + * @since 2.0.7 + */ + public static function checkDownload($productId, $return = false) + { + if (!$productId) { + return !$return ? 0 : null; + } - $db = JFactory::getDbo(); + $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select( - $db->qn( - array( - 'product_download', 'product_download_days', 'product_download_limit', 'product_download_clock', - 'product_download_clock_min', 'product_download_infinite' - ) - ) - ) - ->from($db->qn('#__redshop_product')) - ->where($db->qn('product_id') . ' = ' . (int) $productId); + $query = $db->getQuery(true) + ->select( + $db->qn( + array( + 'product_download', + 'product_download_days', + 'product_download_limit', + 'product_download_clock', + 'product_download_clock_min', + 'product_download_infinite' + ) + ) + ) + ->from($db->qn('#__redshop_product')) + ->where($db->qn('product_id') . ' = ' . (int)$productId); - $result = $db->setQuery($query)->loadObject(); + $result = $db->setQuery($query)->loadObject(); - if ($return) - { - return $result; - } + if ($return) { + return $result; + } - return !$result ? 0 : (int) $result->product_download; - } + return !$result ? 0 : (int)$result->product_download; + } } diff --git a/libraries/redshop/helper/product/price.php b/libraries/redshop/helper/product/price.php index 03f510d94a2..6b1f8e62451 100644 --- a/libraries/redshop/helper/product/price.php +++ b/libraries/redshop/helper/product/price.php @@ -18,676 +18,705 @@ */ class RedshopHelperProductPrice { - /** - * @var array - */ - protected static $productSpecialPrices = array(); - - /** - * Get Product Special Price - * - * @param float $productPrice Product price - * @param string $discountStringIds Discount ids - * @param int $productId Product id - * - * @return null|object - * - * @since 2.0.7 - */ - public static function getProductSpecialPrice($productPrice, $discountStringIds, $productId = 0) - { - $categoryProduct = $productId ? RedshopHelperProduct::getCategoryProduct($productId) : ''; - - // Get shopper group Id - $userArr = JFactory::getSession()->get('rs_user'); - - if (empty($userArr)) - { - $user = JFactory::getUser(); - $userArr = RedshopHelperUser::createUserSession($user->id); - } - - // Shopper Group Id from user session - $shopperGroupId = $userArr['rs_user_shopperGroup']; - - $key = $discountStringIds . '.' . $categoryProduct; - - if (!array_key_exists($key, self::$productSpecialPrices)) - { - $time = time(); - $db = JFactory::getDbo(); - - // Secure discount ids - $discountIds = !empty($discountStringIds) ? ArrayHelper::toInteger(explode(',', $discountStringIds)) : array(); - $discountIds = array_values(array_filter($discountIds)); - - // Secure category ids - $catIds = !empty($categoryProduct) ? ArrayHelper::toInteger(explode(',', $categoryProduct)) : array(); - $catIds = array_values(array_filter($catIds)); - - $query = $db->getQuery(true) - ->select('dp.*') - ->from($db->qn('#__redshop_discount_product', 'dp')) - ->where($db->qn('dp.published') . ' = 1'); - - if (!empty($catIds)) - { - $categoriesSub = array(); - - foreach ($catIds as $categoryId) - { - // Search by categories if configured - $categoriesSub[] = ('FIND_IN_SET(' . $categoryId . ', dp.category_ids)'); - } - - // Or just take all categories if it's not provided - $categoriesSub[] = $db->qn('dp.category_ids') . '=' . $db->quote(''); - - if (!empty($discountIds)) - { - $query->where('(dp.discount_product_id IN (' . implode(',', $discountIds) . ')'); - $query->where('((' . implode(') OR (', $categoriesSub) . ')))'); - } - else - { - $query->where('((' . implode(') OR (', $categoriesSub) . '))'); - } - } - elseif (!empty($discountIds)) - { - $query->where('dp.discount_product_id IN (' . implode(',', $discountIds) . ')'); - } - - $query->where('(' . $db->qn('dp.start_date') . ' = 0 OR ' . $db->qn('dp.start_date') . ' <= ' . (int) $time . ')') - ->where('(' . $db->qn('dp.end_date') . ' = 0 OR ' . $db->qn('dp.end_date') . ' >= ' . (int) $time . ')') - ->order($db->qn('dp.amount') . ' DESC'); - - // Get all discount based on current shopper group - $subQuery = $db->getQuery(true) - ->select('dps.discount_product_id') - ->from($db->qn('#__redshop_discount_product_shoppers', 'dps')) - ->where('dps.shopper_group_id = ' . (int) $shopperGroupId); - - // Filter by requested discounts only - $query->where($db->qn('dp.discount_product_id') . ' IN (' . $subQuery . ')'); - - self::$productSpecialPrices[$key] = $db->setQuery($query)->loadObjectList(); - } - - if (empty(self::$productSpecialPrices[$key])) - { - return null; - } - - foreach (self::$productSpecialPrices[$key] as $item) - { - if (($item->condition == 1 && $item->amount > $productPrice) - || ($item->condition == 2 && $item->amount == $productPrice) - || ($item->condition == 3 && $item->amount < $productPrice)) - { - return $item; - } - } - - return null; - } - - /** - * Method for replace price. - * - * @param float $productPrice Product price - * - * @return string - * - * @since 2.0.7 - */ - public static function priceReplacement($productPrice) - { - if ($productPrice) - { - return self::formattedPrice($productPrice); - } - - if (!Redshop::getConfig()->get('SHOW_PRICE') - || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') == '1' && Redshop::getConfig()->get('SHOW_QUOTATION_PRICE') != '1')) // && DEFAULT_QUOTATION_MODE==1) - { - return Redshop::getConfig()->get('PRICE_REPLACE_URL') ? - "" - . Redshop::getConfig()->get('PRICE_REPLACE') . "" : Redshop::getConfig()->get('PRICE_REPLACE'); - } - - if (Redshop::getConfig()->get('SHOW_PRICE')) - { - if ((Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') == '0') - || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') == '1' && Redshop::getConfig()->get('SHOW_QUOTATION_PRICE') == '1')) - { - return Redshop::getConfig()->get('ZERO_PRICE_REPLACE_URL') ? - "" - . Redshop::getConfig()->get('ZERO_PRICE_REPLACE') . "" : Redshop::getConfig()->get('ZERO_PRICE_REPLACE'); - } - } - - return ''; - } - - /** - * Format Product Price - * - * @param float $productPrice Product price - * @param boolean $convert Decide to convert price in Multi Currency - * @param string $currencySymbol Product Formatted Price - * - * @return string Formatted Product Price - * - * @since 2.0.7 - */ - public static function formattedPrice($productPrice, $convert = true, $currencySymbol = '_NON_') - { - $currencySymbol = $currencySymbol === '_NON_' ? Redshop::getConfig()->get('REDCURRENCY_SYMBOL') : $currencySymbol; - - // Get Current Currency of SHOP - $session = JFactory::getSession(); - - // If convert set true than use conversation - if ($convert && $session->get('product_currency')) - { - $productPrice = RedshopHelperCurrency::convert($productPrice); - $productCurrency = $session->get('product_currency'); - $currencySymbol = (int) $productCurrency; - $currencySymbol = !$currencySymbol - ? $productCurrency - : RedshopEntityCurrency::getInstance((int) $productCurrency)->get('code'); - } - - if (!is_numeric($productPrice)) - { - return ''; - } - - // Prepare currency symbol - $position = Redshop::getConfig()->getString('CURRENCY_SYMBOL_POSITION', 'front'); - - $priceDecimal = (int) Redshop::getConfig()->get('PRICE_DECIMAL'); - $priceSeparator = Redshop::getConfig()->get('PRICE_SEPERATOR'); - $thousandSeparator = Redshop::getConfig()->get('THOUSAND_SEPERATOR', ''); - $productPrice = (double) $productPrice; - $productPrice = number_format($productPrice, $priceDecimal, $priceSeparator, $thousandSeparator); - - switch ($position) - { - case 'behind': - return $productPrice . ' ' . $currencySymbol . ''; - - case 'none': - return $productPrice; - - case 'front': - default: - return '' . $currencySymbol . ' ' . $productPrice; - } - } - - /** - * Method for round product price - * - * @param float $productPrice Product price - * - * @return float - * - * @since 2.0.7 - */ - public static function priceRound($productPrice) - { - return round($productPrice, Redshop::getConfig()->get('CALCULATION_PRICE_DECIMAL', 4)); - } - - /** - * Method for get product net price - * - * @param integer $productId ID of product - * @param integer $userId ID of user - * @param integer $quantity Quantity for get - * @param string $templateHtml Template data - * @param array $attributes Attributes list. - * - * @return array - * @throws Exception - * - * @since 2.0.7 - */ - public static function getNetPrice($productId, $userId = 0, $quantity = 1, $templateHtml = '', $attributes = array()) - { - $row = \Redshop\Product\Product::getProductById($productId); - $productId = isset($row->product_id) ? $row->product_id : ''; - $newPrice = isset($row->product_price) ? $row->product_price : 0; - - $userId = !$userId ? JFactory::getUser()->id : $userId; - $productPrices = array(); - $priceText = JText::_('COM_REDSHOP_REGULAR_PRICE') . ""; - $productVatLabel = ''; - $priceLabel = ''; - $oldPriceLabel = ''; - $priceSavingLabel = ''; - $oldPriceExcludeVat = ''; - - $result = RedshopHelperProduct::getProductPrices($productId, $userId, $quantity); - - if (!empty($result)) - { - $newPrice = $result->product_price; - } - - // Set Product Custom Price through product plugin - $dispatcher = RedshopHelperUtility::getDispatcher(); - JPluginHelper::importPlugin('redshop_product'); - $results = $dispatcher->trigger('setProductCustomPrice', array($productId, $quantity)); - - if (count($results) > 0 && $results[0]) - { - $newPrice = $results[0]; - } - - $isApplyTax = \Redshop\Template\Helper::isApplyVat($templateHtml, $userId); - $specialPrice = self::getProductSpecialPrice($newPrice, RedshopHelperProduct::getProductSpecialId($userId), /** @scrutinizer ignore-type */$productId); - - if (!is_null($specialPrice)) - { - $discountAmount = $specialPrice->discount_type == 0 ? - $specialPrice->discount_amount : ($newPrice * $specialPrice->discount_amount) / (100); - - $newPrice = $newPrice < 0 ? 0 : $newPrice; - $regPrice = $row->product_price ?? 0; - - if ($isApplyTax && isset($row->product_id)) - { - $priceTax = RedshopHelperProduct::getProductTax($row->product_id, $newPrice, $userId); - $regPrice = $row->product_price + $priceTax; - } - - $formattedPrice = self::formattedPrice($regPrice); - $productPrice = $newPrice - $discountAmount; - $productPrice = $productPrice < 0 ? 0 : $productPrice; - - $priceText = $priceText . '' . $formattedPrice - . '
    ' . JText::_('COM_REDSHOP_SPECIAL_PRICE'); - } - else - { - $productPrice = $newPrice; - } - - $dispatcher->trigger('onSetProductPrice', array(&$productPrice, $productId)); - - $excludeVat = RedshopHelperProduct_Attribute::defaultAttributePrice(/** @scrutinizer ignore-type */$productId, $productPrice, $templateHtml, $userId, 0, $attributes); - $formattedPrice = self::formattedPrice($excludeVat); - $priceText = $priceText . '' . $formattedPrice . '' - . ''; - - $defaultTaxAmount = RedshopHelperProduct::getProductTax($productId, $productPrice, $userId, 1); - $taxAmount = RedshopHelperProduct::getProductTax($productId, $productPrice, $userId); - $productPriceExcludingVat = $productPrice; - $productPriceIncludingVat = $defaultTaxAmount + $productPriceExcludingVat; - - if ($isApplyTax) - { - $productPrice = $taxAmount + $productPrice; - } - - $productPrice = $productPrice < 0 ? 0 : $productPrice; - - if (Redshop::getConfig()->getBool('SHOW_PRICE')) - { - $priceExcludingVat = $priceText; - if (Redshop::getConfig()->getInt('DISCOUNT_ENABLE') == 0) - { - $row->product_on_sale = 0; - } - $productDiscountPriceTemp = RedshopHelperDiscount::getDiscountPriceBaseDiscountDate(/** @scrutinizer ignore-type */$productId); - $oldPriceExcludeVat = $productPriceExcludingVat; - - $dispatcher->trigger('onSetProductDiscountPrice', array(&$productDiscountPriceTemp, $productId)); - - if (isset($row->product_on_sale) && $productDiscountPriceTemp > 0) - { - $discountPriceExcludingVat = $productDiscountPriceTemp; - - $taxAmount = RedshopHelperProduct::getProductTax($productId, $productDiscountPriceTemp, $userId); - - if (intval($isApplyTax) && $productDiscountPriceTemp) - { - $productDiscountPriceTemp = $productDiscountPriceTemp + $taxAmount; - } - - if ($productPrice < $productDiscountPriceTemp) - { - $productPrice = RedshopHelperProduct_Attribute::defaultAttributePrice( - /** @scrutinizer ignore-type */$productId, $productPrice, $templateHtml, $userId, intval($isApplyTax), $attributes - ); - - $mainPrice = $productPrice; - $discountPrice = ''; - $oldPrice = ''; - $priceSaving = ''; - $priceSavingPercentage = ''; - $priceNoVAT = $productPriceExcludingVat; - $seoProductSavingPrice = ''; - $seoProductPrice = $productPrice; - $taxAmount = RedshopHelperProduct::getProductTax($productId, $priceNoVAT, $userId); - } - else - { - $priceSaving = $productPriceExcludingVat - $discountPriceExcludingVat; - - // Calculate total price saving in percentage - $priceSavingPercentage = ($priceSaving / $productPriceExcludingVat) * 100; - - // Only apply VAT if set to apply in config or tag - if (intval($isApplyTax) && $priceSaving) - { - // Adding VAT in saving price - $priceSaving += RedshopHelperProduct::getProductTax($productId, $priceSaving, $userId); - } - - $productPriceIncludingVat = $productDiscountPriceTemp + $taxAmount; - - $oldPrice = RedshopHelperProduct_Attribute::defaultAttributePrice( - $productId, $productPrice, $templateHtml, $userId, intval($isApplyTax), $attributes - ); - - $productDiscountPriceTemp = RedshopHelperProduct_Attribute::defaultAttributePrice( - $productId, $productDiscountPriceTemp, $templateHtml, $userId, intval($isApplyTax), $attributes - ); - - $discountPrice = $productDiscountPriceTemp; - $mainPrice = $productDiscountPriceTemp; - $productPrice = $productDiscountPriceTemp; - - $priceNoVAT = RedshopHelperProduct_Attribute::defaultAttributePrice( - $productId, $discountPriceExcludingVat, $templateHtml, $userId, 0, $attributes - ); - - $seoProductPrice = $productDiscountPriceTemp; - $seoProductSavingPrice = $priceSaving; - - $priceSavingLabel = JText::_('COM_REDSHOP_PRODUCT_PRICE_SAVING_LBL'); - $oldPriceLabel = JText::_('COM_REDSHOP_PRODUCT_OLD_PRICE_LBL'); - } - } - else - { - $mainPrice = $productPrice; - - $productPrice = RedshopHelperProduct_Attribute::defaultAttributePrice( - $productId, $productPrice, $templateHtml, $userId, intval($isApplyTax), $attributes - ); - - $discountPrice = ''; - $priceSaving = ''; - $priceSavingPercentage = ''; - $oldPrice = ''; - $priceNoVAT = $productPriceExcludingVat; - $seoProductPrice = $productPrice; - $seoProductSavingPrice = ''; - } - - if ($taxAmount && intval($isApplyTax)) - { - $productVatLabel = ' ' . JText::_('COM_REDSHOP_PRICE_INCLUDING_TAX'); - } - else - { - $productVatLabel = ' ' . JText::_('COM_REDSHOP_PRICE_EXCLUDING_TAX'); - } - - $priceLabel = JText::_('COM_REDSHOP_PRODUCT_PRICE'); - } - else - { - $seoProductPrice = ''; - $seoProductSavingPrice = ''; - $discountPrice = ''; - $oldPrice = ''; - $priceSaving = ''; - $priceSavingPercentage = ''; - $priceNoVAT = ''; - $mainPrice = ''; - $productPrice = ''; - $priceExcludingVat = ''; - } - - $productPrices['productPrice'] = (float) $priceNoVAT; - $productPrices['product_price'] = (float) $productPrice; - $productPrices['price_excluding_vat'] = (float) $priceExcludingVat; - $productPrices['product_main_price'] = (float) $mainPrice; - $productPrices['product_price_novat'] = (float) $priceNoVAT; - $productPrices['product_price_saving'] = (float) $priceSaving; - $productPrices['product_price_saving_percentage'] = (float) $priceSavingPercentage; - $productPrices['product_price_saving_lbl'] = $priceSavingLabel; - $productPrices['product_old_price'] = (float) $oldPrice; - $productPrices['product_discount_price'] = (float) $discountPrice; - $productPrices['seoProductSavingPrice'] = (float) $seoProductSavingPrice; - $productPrices['seoProductPrice'] = (float) $seoProductPrice; - $productPrices['product_old_price_lbl'] = $oldPriceLabel; - $productPrices['product_price_lbl'] = $priceLabel; - $productPrices['product_vat_lbl'] = $productVatLabel; - $productPrices['productVat'] = (float) $taxAmount; - $productPrices['product_old_price_excl_vat'] = (float) $oldPriceExcludeVat; - $productPrices['product_price_incl_vat'] = (float) $productPriceIncludingVat; - - return $productPrices; - } - - /** - * Method for get product show price - * - * @param integer $productId Product ID - * @param string $templateHtml Template content - * @param string $seoTemplate SEO template - * @param int $userId User ID - * @param boolean $isRel Is Rel - * @param array $attributes Attributes - * - * @return mixed|string - * @throws Exception - * - * @since 2.0.7 - */ - public static function getShowPrice($productId, $templateHtml, $seoTemplate = "", $userId = 0, $isRel = false, $attributes = array()) - { - $price = ''; - $priceNoVat = ''; - $displayPriceDiscount = ''; - $displayOldPrice = ''; - $displayPriceSaving = ''; - $displayPriceSavingPercentage = ''; - $displayPriceNoVAT = ''; - $displayPriceWithVAT = ''; - $priceSavingLabel = ''; - $oldPriceLabel = ''; - $vatLabel = ''; - $priceLabel = ''; - $seoProductPrice = ''; - $seoProductSavingPrice = ''; - $oldPriceNoVat = ''; - - $userId = !$userId ? JFactory::getUser()->id : $userId; - $relPrefix = !$isRel ? '' : 'rel'; - - $defaultQuantity = \Redshop\Cart\Helper::getDefaultQuantity($productId, $templateHtml); - $productPrices = self::getNetPrice($productId, $userId, $defaultQuantity, $templateHtml, $attributes); - - if (Redshop::getConfig()->get('SHOW_PRICE') && (!Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') - || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') && Redshop::getConfig()->get('SHOW_QUOTATION_PRICE')))) - { - $price = self::priceReplacement($productPrices['product_price'] * $defaultQuantity); - $mainPrice = self::priceReplacement($productPrices['product_main_price'] * $defaultQuantity); - $oldPrice = self::priceReplacement((float) $productPrices['product_old_price'] * $defaultQuantity); - $priceSaving = self::priceReplacement($productPrices['product_price_saving'] * $defaultQuantity); - $discountPrice = self::priceReplacement($productPrices['product_discount_price'] * $defaultQuantity); - $priceNoVAT = self::priceReplacement($productPrices['product_price_novat'] * $defaultQuantity); - $priceWithVAT = self::priceReplacement($productPrices['product_price_incl_vat'] * $defaultQuantity); - $oldPriceNoVat = self::priceReplacement($productPrices['product_old_price_excl_vat'] * $defaultQuantity); - - $isStockExists = RedshopHelperStockroom::isStockExists($productId); - - if ($isStockExists && strpos($templateHtml, "{" . $relPrefix . "product_price_table}") !== false) - { - $productPriceTable = RedshopHelperProduct::getProductQuantityPrice($productId, $userId); - $templateHtml = str_replace("{" . $relPrefix . "product_price_table}", $productPriceTable, $templateHtml); - } - - $priceNoVat = $productPrices['price_excluding_vat']; - $seoProductPrice = self::priceReplacement($productPrices['seoProductPrice'] * $defaultQuantity); - $seoProductSavingPrice = self::priceReplacement((float) $productPrices['seoProductSavingPrice'] * $defaultQuantity); - - $oldPriceLabel = $productPrices['product_old_price_lbl']; - $priceSavingLabel = $productPrices['product_price_saving_lbl']; - $priceLabel = $productPrices['product_price_lbl']; - $vatLabel = $productPrices['product_vat_lbl']; - - $displayOldPrice = $oldPrice; - $displayPriceDiscount = $discountPrice; - $displayPriceSaving = $priceSaving; - $displayPriceNoVAT = $priceNoVAT; - - if ($productPrices['product_discount_price']) - { - $displayPriceDiscount = '' . $discountPrice . ''; - } - - if ($productPrices['product_old_price']) - { - $displayOldPrice = '' . $oldPrice . ''; - } - - if ($productPrices['product_price_saving']) - { - $displayPriceSaving = '' . $priceSaving . ''; - $displayPriceSavingPercentage = '' - . JText::sprintf('COM_REDSHOP_PRODUCT_PRICE_SAVING_PERCENTAGE_LBL', round($productPrices['product_price_saving_percentage'])) - . '%'; - } - - if ($productPrices['product_price_novat'] != "") - { - $displayPriceNoVAT = '' . $priceNoVAT . ''; - } - - if ($productPrices['product_price_incl_vat'] != "") - { - $displayPriceWithVAT = '' . $priceWithVAT . ''; - } - } - - if (strpos($templateHtml, "{" . $relPrefix . "product_price_table}") !== false) - { - $templateHtml = str_replace("{" . $relPrefix . "product_price_table}", '', $templateHtml); - } - - if ($seoTemplate != "") - { - $seoTemplate = str_replace("{" . $relPrefix . "saleprice}", $seoProductPrice, $seoTemplate); - $seoTemplate = str_replace("{" . $relPrefix . "saving}", $seoProductSavingPrice, $seoTemplate); - - return $seoTemplate; - } - - if (strpos($templateHtml, "{" . $relPrefix . "lowest_price}") !== false - || strpos($templateHtml, "{" . $relPrefix . "highest_price}") !== false) - { - $productPriceMinMax = RedshopHelperProduct::getProductMinMaxPrice($productId); - - if (strpos($templateHtml, "{" . $relPrefix . "lowest_price}") !== false) - { - if (!empty($productPriceMinMax['min'])) - { - $productMinPrice = self::priceReplacement($productPriceMinMax['min'] * $defaultQuantity); - - $templateHtml = str_replace( - "{" . $relPrefix . "lowest_price}", - '' . $productMinPrice . '', - $templateHtml - ); - } - else - { - $templateHtml = str_replace( - "{" . $relPrefix . "lowest_price}", - '' . $price . '', - $templateHtml - ); - } - } - - if (strpos($templateHtml, "{" . $relPrefix . "highest_price}") !== false) - { - if (!empty($productPriceMinMax['min'])) - { - $productMaxPrice = self::priceReplacement($productPriceMinMax['max'] * $defaultQuantity); - - $templateHtml = str_replace( - "{" . $relPrefix . "highest_price}", - '' . $productMaxPrice . '', - $templateHtml - ); - } - else - { - $templateHtml = str_replace( - "{" . $relPrefix . "highest_price}", - '' . $price . '', - $templateHtml - ); - } - } - } - - $templateHtml = str_replace( - "{" . $relPrefix . "product_price}", - '' . $price . '', - $templateHtml - ); - - $templateHtml = str_replace("{" . $relPrefix . "price_excluding_vat}", $priceNoVat, $templateHtml); - $templateHtml = str_replace("{" . $relPrefix . "product_discount_price}", $displayPriceDiscount, $templateHtml); - - if ($productPrices['product_price_saving']) - { - $templateHtml = str_replace("{" . $relPrefix . "product_price_saving}", $displayPriceSaving, $templateHtml); - $templateHtml = str_replace("{" . $relPrefix . "product_price_saving_excl_vat}", $displayPriceSaving, $templateHtml); - $templateHtml = str_replace("{" . $relPrefix . "product_price_saving_lbl}", $priceSavingLabel, $templateHtml); - - $templateHtml = str_replace("{" . $relPrefix . "product_price_saving_percentage}", $displayPriceSavingPercentage, $templateHtml); - } - else - { - $templateHtml = str_replace("{" . $relPrefix . "product_price_saving}", '', $templateHtml); - $templateHtml = str_replace("{" . $relPrefix . "product_price_saving_lbl}", '', $templateHtml); - - $templateHtml = str_replace("{" . $relPrefix . "product_price_saving_percentage}", '', $templateHtml); - } - - if ($productPrices['product_old_price']) - { - $pricePercentDiscount = 100 - ($productPrices['product_discount_price'] / $productPrices['product_old_price'] * 100); - $templateHtml = str_replace("{" . $relPrefix . "product_old_price}", $displayOldPrice, $templateHtml); - $templateHtml = str_replace("{" . $relPrefix . "product_old_price_lbl}", $oldPriceLabel, $templateHtml); - } - else - { - $templateHtml = str_replace("{" . $relPrefix . "product_old_price}", '', $templateHtml); - $templateHtml = str_replace("{" . $relPrefix . "product_old_price_lbl}", '', $templateHtml); - } - - $oldPriceNoVat = '' . $oldPriceNoVat . ''; - - $templateHtml = str_replace("{" . $relPrefix . "product_old_price_excl_vat}", $oldPriceNoVat, $templateHtml); - $templateHtml = str_replace("{" . $relPrefix . "product_price_novat}", $displayPriceNoVAT, $templateHtml); - $templateHtml = str_replace("{" . $relPrefix . "product_price_incl_vat}", $displayPriceWithVAT, $templateHtml); - $templateHtml = str_replace("{" . $relPrefix . "product_vat_lbl}", $vatLabel, $templateHtml); - $templateHtml = str_replace("{" . $relPrefix . "product_price_lbl}", $priceLabel, $templateHtml); - - return $templateHtml; - } + /** + * @var array + */ + protected static $productSpecialPrices = array(); + + /** + * Method for round product price + * + * @param float $productPrice Product price + * + * @return float + * + * @since 2.0.7 + */ + public static function priceRound($productPrice) + { + return round($productPrice, Redshop::getConfig()->get('CALCULATION_PRICE_DECIMAL', 4)); + } + + /** + * Method for get product show price + * + * @param integer $productId Product ID + * @param string $templateHtml Template content + * @param string $seoTemplate SEO template + * @param int $userId User ID + * @param boolean $isRel Is Rel + * @param array $attributes Attributes + * + * @return mixed|string + * @throws Exception + * + * @since 2.0.7 + */ + public static function getShowPrice( + $productId, + $templateHtml, + $seoTemplate = "", + $userId = 0, + $isRel = false, + $attributes = array() + ) { + $price = ''; + $priceNoVat = ''; + $displayPriceDiscount = ''; + $displayOldPrice = ''; + $displayPriceSaving = ''; + $displayPriceSavingPercentage = ''; + $displayPriceNoVAT = ''; + $displayPriceWithVAT = ''; + $priceSavingLabel = ''; + $oldPriceLabel = ''; + $vatLabel = ''; + $priceLabel = ''; + $seoProductPrice = ''; + $seoProductSavingPrice = ''; + $oldPriceNoVat = ''; + + $userId = !$userId ? JFactory::getUser()->id : $userId; + $relPrefix = !$isRel ? '' : 'rel'; + + $defaultQuantity = \Redshop\Cart\Helper::getDefaultQuantity($productId, $templateHtml); + $productPrices = self::getNetPrice($productId, $userId, $defaultQuantity, $templateHtml, $attributes); + + if (Redshop::getConfig()->get('SHOW_PRICE') && (!Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') + || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') && Redshop::getConfig()->get( + 'SHOW_QUOTATION_PRICE' + )))) { + $price = self::priceReplacement($productPrices['product_price'] * $defaultQuantity); + $mainPrice = self::priceReplacement($productPrices['product_main_price'] * $defaultQuantity); + $oldPrice = self::priceReplacement((float)$productPrices['product_old_price'] * $defaultQuantity); + $priceSaving = self::priceReplacement($productPrices['product_price_saving'] * $defaultQuantity); + $discountPrice = self::priceReplacement($productPrices['product_discount_price'] * $defaultQuantity); + $priceNoVAT = self::priceReplacement($productPrices['product_price_novat'] * $defaultQuantity); + $priceWithVAT = self::priceReplacement($productPrices['product_price_incl_vat'] * $defaultQuantity); + $oldPriceNoVat = self::priceReplacement($productPrices['product_old_price_excl_vat'] * $defaultQuantity); + + $isStockExists = RedshopHelperStockroom::isStockExists($productId); + + if ($isStockExists && strpos($templateHtml, "{" . $relPrefix . "product_price_table}") !== false) { + $productPriceTable = RedshopHelperProduct::getProductQuantityPrice($productId, $userId); + $templateHtml = str_replace( + "{" . $relPrefix . "product_price_table}", + $productPriceTable, + $templateHtml + ); + } + + $priceNoVat = $productPrices['price_excluding_vat']; + $seoProductPrice = self::priceReplacement($productPrices['seoProductPrice'] * $defaultQuantity); + $seoProductSavingPrice = self::priceReplacement( + (float)$productPrices['seoProductSavingPrice'] * $defaultQuantity + ); + + $oldPriceLabel = $productPrices['product_old_price_lbl']; + $priceSavingLabel = $productPrices['product_price_saving_lbl']; + $priceLabel = $productPrices['product_price_lbl']; + $vatLabel = $productPrices['product_vat_lbl']; + + $displayOldPrice = $oldPrice; + $displayPriceDiscount = $discountPrice; + $displayPriceSaving = $priceSaving; + $displayPriceNoVAT = $priceNoVAT; + + if ($productPrices['product_discount_price']) { + $displayPriceDiscount = '' . $discountPrice . ''; + } + + if ($productPrices['product_old_price']) { + $displayOldPrice = '' . $oldPrice . ''; + } + + if ($productPrices['product_price_saving']) { + $displayPriceSaving = '' . $priceSaving . ''; + $displayPriceSavingPercentage = '' + . JText::sprintf( + 'COM_REDSHOP_PRODUCT_PRICE_SAVING_PERCENTAGE_LBL', + round($productPrices['product_price_saving_percentage']) + ) + . '%'; + } + + if ($productPrices['product_price_novat'] != "") { + $displayPriceNoVAT = '' . $priceNoVAT . ''; + } + + if ($productPrices['product_price_incl_vat'] != "") { + $displayPriceWithVAT = '' . $priceWithVAT . ''; + } + } + + if (strpos($templateHtml, "{" . $relPrefix . "product_price_table}") !== false) { + $templateHtml = str_replace("{" . $relPrefix . "product_price_table}", '', $templateHtml); + } + + if ($seoTemplate != "") { + $seoTemplate = str_replace("{" . $relPrefix . "saleprice}", $seoProductPrice, $seoTemplate); + $seoTemplate = str_replace("{" . $relPrefix . "saving}", $seoProductSavingPrice, $seoTemplate); + + return $seoTemplate; + } + + if (strpos($templateHtml, "{" . $relPrefix . "lowest_price}") !== false + || strpos($templateHtml, "{" . $relPrefix . "highest_price}") !== false) { + $productPriceMinMax = RedshopHelperProduct::getProductMinMaxPrice($productId); + + if (strpos($templateHtml, "{" . $relPrefix . "lowest_price}") !== false) { + if (!empty($productPriceMinMax['min'])) { + $productMinPrice = self::priceReplacement($productPriceMinMax['min'] * $defaultQuantity); + + $templateHtml = str_replace( + "{" . $relPrefix . "lowest_price}", + '' . $productMinPrice . '', + $templateHtml + ); + } else { + $templateHtml = str_replace( + "{" . $relPrefix . "lowest_price}", + '' . $price . '', + $templateHtml + ); + } + } + + if (strpos($templateHtml, "{" . $relPrefix . "highest_price}") !== false) { + if (!empty($productPriceMinMax['min'])) { + $productMaxPrice = self::priceReplacement($productPriceMinMax['max'] * $defaultQuantity); + + $templateHtml = str_replace( + "{" . $relPrefix . "highest_price}", + '' . $productMaxPrice . '', + $templateHtml + ); + } else { + $templateHtml = str_replace( + "{" . $relPrefix . "highest_price}", + '' . $price . '', + $templateHtml + ); + } + } + } + + $templateHtml = str_replace( + "{" . $relPrefix . "product_price}", + '' . $price . '', + $templateHtml + ); + + $templateHtml = str_replace("{" . $relPrefix . "price_excluding_vat}", $priceNoVat, $templateHtml); + $templateHtml = str_replace("{" . $relPrefix . "product_discount_price}", $displayPriceDiscount, $templateHtml); + + if ($productPrices['product_price_saving']) { + $templateHtml = str_replace("{" . $relPrefix . "product_price_saving}", $displayPriceSaving, $templateHtml); + $templateHtml = str_replace( + "{" . $relPrefix . "product_price_saving_excl_vat}", + $displayPriceSaving, + $templateHtml + ); + $templateHtml = str_replace( + "{" . $relPrefix . "product_price_saving_lbl}", + $priceSavingLabel, + $templateHtml + ); + + $templateHtml = str_replace( + "{" . $relPrefix . "product_price_saving_percentage}", + $displayPriceSavingPercentage, + $templateHtml + ); + } else { + $templateHtml = str_replace("{" . $relPrefix . "product_price_saving}", '', $templateHtml); + $templateHtml = str_replace("{" . $relPrefix . "product_price_saving_lbl}", '', $templateHtml); + + $templateHtml = str_replace("{" . $relPrefix . "product_price_saving_percentage}", '', $templateHtml); + } + + if ($productPrices['product_old_price']) { + $pricePercentDiscount = 100 - ($productPrices['product_discount_price'] / $productPrices['product_old_price'] * 100); + $templateHtml = str_replace( + "{" . $relPrefix . "product_old_price}", + $displayOldPrice, + $templateHtml + ); + $templateHtml = str_replace( + "{" . $relPrefix . "product_old_price_lbl}", + $oldPriceLabel, + $templateHtml + ); + } else { + $templateHtml = str_replace("{" . $relPrefix . "product_old_price}", '', $templateHtml); + $templateHtml = str_replace("{" . $relPrefix . "product_old_price_lbl}", '', $templateHtml); + } + + $oldPriceNoVat = '' . $oldPriceNoVat . ''; + + $templateHtml = str_replace("{" . $relPrefix . "product_old_price_excl_vat}", $oldPriceNoVat, $templateHtml); + $templateHtml = str_replace("{" . $relPrefix . "product_price_novat}", $displayPriceNoVAT, $templateHtml); + $templateHtml = str_replace("{" . $relPrefix . "product_price_incl_vat}", $displayPriceWithVAT, $templateHtml); + $templateHtml = str_replace("{" . $relPrefix . "product_vat_lbl}", $vatLabel, $templateHtml); + $templateHtml = str_replace("{" . $relPrefix . "product_price_lbl}", $priceLabel, $templateHtml); + + return $templateHtml; + } + + /** + * Method for get product net price + * + * @param integer $productId ID of product + * @param integer $userId ID of user + * @param integer $quantity Quantity for get + * @param string $templateHtml Template data + * @param array $attributes Attributes list. + * + * @return array + * @throws Exception + * + * @since 2.0.7 + */ + public static function getNetPrice( + $productId, + $userId = 0, + $quantity = 1, + $templateHtml = '', + $attributes = array() + ) { + $row = \Redshop\Product\Product::getProductById($productId); + $productId = isset($row->product_id) ? $row->product_id : ''; + $newPrice = isset($row->product_price) ? $row->product_price : 0; + + $userId = !$userId ? JFactory::getUser()->id : $userId; + $productPrices = array(); + $priceText = JText::_('COM_REDSHOP_REGULAR_PRICE') . ""; + $productVatLabel = ''; + $priceLabel = ''; + $oldPriceLabel = ''; + $priceSavingLabel = ''; + $oldPriceExcludeVat = ''; + + $result = RedshopHelperProduct::getProductPrices($productId, $userId, $quantity); + + if (!empty($result)) { + $newPrice = $result->product_price; + } + + // Set Product Custom Price through product plugin + $dispatcher = RedshopHelperUtility::getDispatcher(); + JPluginHelper::importPlugin('redshop_product'); + $results = $dispatcher->trigger('setProductCustomPrice', array($productId, $quantity)); + + if (count($results) > 0 && $results[0]) { + $newPrice = $results[0]; + } + + $isApplyTax = \Redshop\Template\Helper::isApplyVat($templateHtml, $userId); + $specialPrice = self::getProductSpecialPrice( + $newPrice, + RedshopHelperProduct::getProductSpecialId($userId), + /** @scrutinizer ignore-type */ + $productId + ); + + if (!is_null($specialPrice)) { + $discountAmount = $specialPrice->discount_type == 0 ? + $specialPrice->discount_amount : ($newPrice * $specialPrice->discount_amount) / (100); + + $newPrice = $newPrice < 0 ? 0 : $newPrice; + $regPrice = $row->product_price ?? 0; + + if ($isApplyTax && isset($row->product_id)) { + $priceTax = RedshopHelperProduct::getProductTax($row->product_id, $newPrice, $userId); + $regPrice = $row->product_price + $priceTax; + } + + $formattedPrice = self::formattedPrice($regPrice); + $productPrice = $newPrice - $discountAmount; + $productPrice = $productPrice < 0 ? 0 : $productPrice; + + $priceText = $priceText . '' . $formattedPrice + . '
    ' . JText::_('COM_REDSHOP_SPECIAL_PRICE'); + } else { + $productPrice = $newPrice; + } + + $dispatcher->trigger('onSetProductPrice', array(&$productPrice, $productId)); + + $excludeVat = RedshopHelperProduct_Attribute::defaultAttributePrice( + /** @scrutinizer ignore-type */ $productId, + $productPrice, + $templateHtml, + $userId, + 0, + $attributes + ); + $formattedPrice = self::formattedPrice($excludeVat); + $priceText = $priceText . '' . $formattedPrice . '' + . ''; + + $defaultTaxAmount = RedshopHelperProduct::getProductTax($productId, $productPrice, $userId, 1); + $taxAmount = RedshopHelperProduct::getProductTax($productId, $productPrice, $userId); + $productPriceExcludingVat = $productPrice; + $productPriceIncludingVat = $defaultTaxAmount + $productPriceExcludingVat; + + if ($isApplyTax) { + $productPrice = $taxAmount + $productPrice; + } + + $productPrice = $productPrice < 0 ? 0 : $productPrice; + + if (Redshop::getConfig()->getBool('SHOW_PRICE')) { + $priceExcludingVat = $priceText; + if (Redshop::getConfig()->getInt('DISCOUNT_ENABLE') == 0) { + $row->product_on_sale = 0; + } + $productDiscountPriceTemp = RedshopHelperDiscount::getDiscountPriceBaseDiscountDate( + /** @scrutinizer ignore-type */ $productId + ); + $oldPriceExcludeVat = $productPriceExcludingVat; + + $dispatcher->trigger('onSetProductDiscountPrice', array(&$productDiscountPriceTemp, $productId)); + + if (isset($row->product_on_sale) && $productDiscountPriceTemp > 0) { + $discountPriceExcludingVat = $productDiscountPriceTemp; + + $taxAmount = RedshopHelperProduct::getProductTax($productId, $productDiscountPriceTemp, $userId); + + if (intval($isApplyTax) && $productDiscountPriceTemp) { + $productDiscountPriceTemp = $productDiscountPriceTemp + $taxAmount; + } + + if ($productPrice < $productDiscountPriceTemp) { + $productPrice = RedshopHelperProduct_Attribute::defaultAttributePrice( + /** @scrutinizer ignore-type */ $productId, + $productPrice, + $templateHtml, + $userId, + intval($isApplyTax), + $attributes + ); + + $mainPrice = $productPrice; + $discountPrice = ''; + $oldPrice = ''; + $priceSaving = ''; + $priceSavingPercentage = ''; + $priceNoVAT = $productPriceExcludingVat; + $seoProductSavingPrice = ''; + $seoProductPrice = $productPrice; + $taxAmount = RedshopHelperProduct::getProductTax($productId, $priceNoVAT, $userId); + } else { + $priceSaving = $productPriceExcludingVat - $discountPriceExcludingVat; + + // Calculate total price saving in percentage + $priceSavingPercentage = ($priceSaving / $productPriceExcludingVat) * 100; + + // Only apply VAT if set to apply in config or tag + if (intval($isApplyTax) && $priceSaving) { + // Adding VAT in saving price + $priceSaving += RedshopHelperProduct::getProductTax($productId, $priceSaving, $userId); + } + + $productPriceIncludingVat = $productDiscountPriceTemp + $taxAmount; + + $oldPrice = RedshopHelperProduct_Attribute::defaultAttributePrice( + $productId, + $productPrice, + $templateHtml, + $userId, + intval($isApplyTax), + $attributes + ); + + $productDiscountPriceTemp = RedshopHelperProduct_Attribute::defaultAttributePrice( + $productId, + $productDiscountPriceTemp, + $templateHtml, + $userId, + intval($isApplyTax), + $attributes + ); + + $discountPrice = $productDiscountPriceTemp; + $mainPrice = $productDiscountPriceTemp; + $productPrice = $productDiscountPriceTemp; + + $priceNoVAT = RedshopHelperProduct_Attribute::defaultAttributePrice( + $productId, + $discountPriceExcludingVat, + $templateHtml, + $userId, + 0, + $attributes + ); + + $seoProductPrice = $productDiscountPriceTemp; + $seoProductSavingPrice = $priceSaving; + + $priceSavingLabel = JText::_('COM_REDSHOP_PRODUCT_PRICE_SAVING_LBL'); + $oldPriceLabel = JText::_('COM_REDSHOP_PRODUCT_OLD_PRICE_LBL'); + } + } else { + $mainPrice = $productPrice; + + $productPrice = RedshopHelperProduct_Attribute::defaultAttributePrice( + $productId, + $productPrice, + $templateHtml, + $userId, + intval($isApplyTax), + $attributes + ); + + $discountPrice = ''; + $priceSaving = ''; + $priceSavingPercentage = ''; + $oldPrice = ''; + $priceNoVAT = $productPriceExcludingVat; + $seoProductPrice = $productPrice; + $seoProductSavingPrice = ''; + } + + if ($taxAmount && intval($isApplyTax)) { + $productVatLabel = ' ' . JText::_('COM_REDSHOP_PRICE_INCLUDING_TAX'); + } else { + $productVatLabel = ' ' . JText::_('COM_REDSHOP_PRICE_EXCLUDING_TAX'); + } + + $priceLabel = JText::_('COM_REDSHOP_PRODUCT_PRICE'); + } else { + $seoProductPrice = ''; + $seoProductSavingPrice = ''; + $discountPrice = ''; + $oldPrice = ''; + $priceSaving = ''; + $priceSavingPercentage = ''; + $priceNoVAT = ''; + $mainPrice = ''; + $productPrice = ''; + $priceExcludingVat = ''; + } + + $productPrices['productPrice'] = (float)$priceNoVAT; + $productPrices['product_price'] = (float)$productPrice; + $productPrices['price_excluding_vat'] = (float)$priceExcludingVat; + $productPrices['product_main_price'] = (float)$mainPrice; + $productPrices['product_price_novat'] = (float)$priceNoVAT; + $productPrices['product_price_saving'] = (float)$priceSaving; + $productPrices['product_price_saving_percentage'] = (float)$priceSavingPercentage; + $productPrices['product_price_saving_lbl'] = $priceSavingLabel; + $productPrices['product_old_price'] = (float)$oldPrice; + $productPrices['product_discount_price'] = (float)$discountPrice; + $productPrices['seoProductSavingPrice'] = (float)$seoProductSavingPrice; + $productPrices['seoProductPrice'] = (float)$seoProductPrice; + $productPrices['product_old_price_lbl'] = $oldPriceLabel; + $productPrices['product_price_lbl'] = $priceLabel; + $productPrices['product_vat_lbl'] = $productVatLabel; + $productPrices['productVat'] = (float)$taxAmount; + $productPrices['product_old_price_excl_vat'] = (float)$oldPriceExcludeVat; + $productPrices['product_price_incl_vat'] = (float)$productPriceIncludingVat; + + return $productPrices; + } + + /** + * Get Product Special Price + * + * @param float $productPrice Product price + * @param string $discountStringIds Discount ids + * @param int $productId Product id + * + * @return null|object + * + * @since 2.0.7 + */ + public static function getProductSpecialPrice($productPrice, $discountStringIds, $productId = 0) + { + $categoryProduct = $productId ? RedshopHelperProduct::getCategoryProduct($productId) : ''; + + // Get shopper group Id + $userArr = JFactory::getSession()->get('rs_user'); + + if (empty($userArr)) { + $user = JFactory::getUser(); + $userArr = RedshopHelperUser::createUserSession($user->id); + } + + // Shopper Group Id from user session + $shopperGroupId = $userArr['rs_user_shopperGroup']; + + $key = $discountStringIds . '.' . $categoryProduct; + + if (!array_key_exists($key, self::$productSpecialPrices)) { + $time = time(); + $db = JFactory::getDbo(); + + // Secure discount ids + $discountIds = !empty($discountStringIds) ? ArrayHelper::toInteger( + explode(',', $discountStringIds) + ) : array(); + $discountIds = array_values(array_filter($discountIds)); + + // Secure category ids + $catIds = !empty($categoryProduct) ? ArrayHelper::toInteger(explode(',', $categoryProduct)) : array(); + $catIds = array_values(array_filter($catIds)); + + $query = $db->getQuery(true) + ->select('dp.*') + ->from($db->qn('#__redshop_discount_product', 'dp')) + ->where($db->qn('dp.published') . ' = 1'); + + if (!empty($catIds)) { + $categoriesSub = array(); + + foreach ($catIds as $categoryId) { + // Search by categories if configured + $categoriesSub[] = ('FIND_IN_SET(' . $categoryId . ', dp.category_ids)'); + } + + // Or just take all categories if it's not provided + $categoriesSub[] = $db->qn('dp.category_ids') . '=' . $db->quote(''); + + if (!empty($discountIds)) { + $query->where('(dp.discount_product_id IN (' . implode(',', $discountIds) . ')'); + $query->where('((' . implode(') OR (', $categoriesSub) . ')))'); + } else { + $query->where('((' . implode(') OR (', $categoriesSub) . '))'); + } + } elseif (!empty($discountIds)) { + $query->where('dp.discount_product_id IN (' . implode(',', $discountIds) . ')'); + } + + $query->where( + '(' . $db->qn('dp.start_date') . ' = 0 OR ' . $db->qn('dp.start_date') . ' <= ' . (int)$time . ')' + ) + ->where('(' . $db->qn('dp.end_date') . ' = 0 OR ' . $db->qn('dp.end_date') . ' >= ' . (int)$time . ')') + ->order($db->qn('dp.amount') . ' DESC'); + + // Get all discount based on current shopper group + $subQuery = $db->getQuery(true) + ->select('dps.discount_product_id') + ->from($db->qn('#__redshop_discount_product_shoppers', 'dps')) + ->where('dps.shopper_group_id = ' . (int)$shopperGroupId); + + // Filter by requested discounts only + $query->where($db->qn('dp.discount_product_id') . ' IN (' . $subQuery . ')'); + + self::$productSpecialPrices[$key] = $db->setQuery($query)->loadObjectList(); + } + + if (empty(self::$productSpecialPrices[$key])) { + return null; + } + + foreach (self::$productSpecialPrices[$key] as $item) { + if (($item->condition == 1 && $item->amount > $productPrice) + || ($item->condition == 2 && $item->amount == $productPrice) + || ($item->condition == 3 && $item->amount < $productPrice)) { + return $item; + } + } + + return null; + } + + /** + * Format Product Price + * + * @param float $productPrice Product price + * @param boolean $convert Decide to convert price in Multi Currency + * @param string $currencySymbol Product Formatted Price + * + * @return string Formatted Product Price + * + * @since 2.0.7 + */ + public static function formattedPrice($productPrice, $convert = true, $currencySymbol = '_NON_') + { + $currencySymbol = $currencySymbol === '_NON_' ? Redshop::getConfig()->get( + 'REDCURRENCY_SYMBOL' + ) : $currencySymbol; + + // Get Current Currency of SHOP + $session = JFactory::getSession(); + + // If convert set true than use conversation + if ($convert && $session->get('product_currency')) { + $productPrice = RedshopHelperCurrency::convert($productPrice); + $productCurrency = $session->get('product_currency'); + $currencySymbol = (int)$productCurrency; + $currencySymbol = !$currencySymbol + ? $productCurrency + : RedshopEntityCurrency::getInstance((int)$productCurrency)->get('code'); + } + + if (!is_numeric($productPrice)) { + return ''; + } + + // Prepare currency symbol + $position = Redshop::getConfig()->getString('CURRENCY_SYMBOL_POSITION', 'front'); + + $priceDecimal = (int)Redshop::getConfig()->get('PRICE_DECIMAL'); + $priceSeparator = Redshop::getConfig()->get('PRICE_SEPERATOR'); + $thousandSeparator = Redshop::getConfig()->get('THOUSAND_SEPERATOR', ''); + $productPrice = (double)$productPrice; + $productPrice = number_format($productPrice, $priceDecimal, $priceSeparator, $thousandSeparator); + + switch ($position) { + case 'behind': + return $productPrice . ' ' . $currencySymbol . ''; + + case 'none': + return $productPrice; + + case 'front': + default: + return '' . $currencySymbol . ' ' . $productPrice; + } + } + + /** + * Method for replace price. + * + * @param float $productPrice Product price + * + * @return string + * + * @since 2.0.7 + */ + public static function priceReplacement($productPrice) + { + if ($productPrice) { + return self::formattedPrice($productPrice); + } + + if (!Redshop::getConfig()->get('SHOW_PRICE') + || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') == '1' && Redshop::getConfig()->get( + 'SHOW_QUOTATION_PRICE' + ) != '1')) // && DEFAULT_QUOTATION_MODE==1) + { + return Redshop::getConfig()->get('PRICE_REPLACE_URL') ? + "" + . Redshop::getConfig()->get('PRICE_REPLACE') . "" : Redshop::getConfig()->get('PRICE_REPLACE'); + } + + if (Redshop::getConfig()->get('SHOW_PRICE')) { + if ((Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') == '0') + || (Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE') == '1' && Redshop::getConfig()->get( + 'SHOW_QUOTATION_PRICE' + ) == '1')) { + return Redshop::getConfig()->get('ZERO_PRICE_REPLACE_URL') ? + "" + . Redshop::getConfig()->get('ZERO_PRICE_REPLACE') . "" : Redshop::getConfig()->get( + 'ZERO_PRICE_REPLACE' + ); + } + } + + return ''; + } } diff --git a/libraries/redshop/helper/product/tag.php b/libraries/redshop/helper/product/tag.php index c2f0ae36dee..16280f5a1dc 100644 --- a/libraries/redshop/helper/product/tag.php +++ b/libraries/redshop/helper/product/tag.php @@ -26,39 +26,54 @@ class RedshopHelperProductTag /** * Parse extra fields for template for according to section. * - * @param array $fieldNames List of field names - * @param integer $productId ID of product - * @param integer $section Section - * @param string $templateContent Template content - * @param integer $categoryPage Argument for product section extra field for category page + * @param array $fieldNames List of field names + * @param integer $productId ID of product + * @param integer $section Section + * @param string $templateContent Template content + * @param integer $categoryPage Argument for product section extra field for category page * * @return string * * @since 2.0.7 */ - public static function getExtraSectionTag($fieldNames = array(), $productId = 0, $section = 0, $templateContent = '', $categoryPage = 0) - { - $fieldName = RedshopHelperTemplate::getExtraFieldsForCurrentTemplate($fieldNames, $templateContent, $categoryPage); + public static function getExtraSectionTag( + $fieldNames = array(), + $productId = 0, + $section = 0, + $templateContent = '', + $categoryPage = 0 + ) { + $fieldName = RedshopHelperTemplate::getExtraFieldsForCurrentTemplate( + $fieldNames, + $templateContent, + $categoryPage + ); if (empty($fieldName)) { return $templateContent; } - return ExtraFields::displayExtraFields($section, $productId, $fieldName, $templateContent, (boolean)$categoryPage); + return ExtraFields::displayExtraFields( + $section, + $productId, + $fieldName, + $templateContent, + (boolean)$categoryPage + ); } /** * Method for get additional images of product. * - * @param integer $productId Id of product - * @param integer $accessoryId Accessory Id - * @param integer $relatedProductId Related product ID - * @param integer $propertyId Property ID - * @param integer $subPropertyId Sub-property ID - * @param integer $mainImgWidth Main image width - * @param integer $mainImgHeight Main image height - * @param string $redView redshop View - * @param string $redLayout redshop layout + * @param integer $productId Id of product + * @param integer $accessoryId Accessory Id + * @param integer $relatedProductId Related product ID + * @param integer $propertyId Property ID + * @param integer $subPropertyId Sub-property ID + * @param integer $mainImgWidth Main image width + * @param integer $mainImgHeight Main image height + * @param string $redView redshop View + * @param string $redLayout redshop layout * * @return array * @@ -67,10 +82,16 @@ public static function getExtraSectionTag($fieldNames = array(), $productId = 0, * */ public static function displayAdditionalImage( - $productId = 0, $accessoryId = 0, $relatedProductId = 0, $propertyId = 0, $subPropertyId = 0, - $mainImgWidth = 0, $mainImgHeight = 0, $redView = "", $redLayout = "" - ) - { + $productId = 0, + $accessoryId = 0, + $relatedProductId = 0, + $propertyId = 0, + $subPropertyId = 0, + $mainImgWidth = 0, + $mainImgHeight = 0, + $redView = "", + $redLayout = "" + ) { if ($accessoryId != 0) { $accessory = RedshopHelperAccessory::getProductAccessories($accessoryId); $productId = $accessory[0]->child_product_id; @@ -95,93 +116,104 @@ public static function displayAdditionalImage( if ($redLayout == 'categoryproduct' || $redLayout == 'detail') { if (strpos($productTemplate, "{product_thumb_image_3}") !== false) { - $productImgTag = '{product_thumb_image_3}'; + $productImgTag = '{product_thumb_image_3}'; $productImgThumbHeight = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_3'); - $productImgThumbWidth = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_3'); + $productImgThumbWidth = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_3'); } elseif (strpos($productTemplate, "{product_thumb_image_2}") !== false) { - $productImgTag = '{product_thumb_image_2}'; + $productImgTag = '{product_thumb_image_2}'; $productImgThumbHeight = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT_2'); - $productImgThumbWidth = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_2'); + $productImgThumbWidth = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH_2'); } elseif (strpos($productTemplate, "{product_thumb_image_1}") !== false) { - $productImgTag = '{product_thumb_image_1}'; + $productImgTag = '{product_thumb_image_1}'; $productImgThumbHeight = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); - $productImgThumbWidth = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); + $productImgThumbWidth = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); } else { - $productImgTag = '{product_thumb_image}'; + $productImgTag = '{product_thumb_image}'; $productImgThumbHeight = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_HEIGHT'); - $productImgThumbWidth = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); + $productImgThumbWidth = Redshop::getConfig()->get('CATEGORY_PRODUCT_THUMB_WIDTH'); } } else { if (strpos($productTemplate, "{product_thumb_image_3}") !== false) { - $productImgTag = '{product_thumb_image_3}'; + $productImgTag = '{product_thumb_image_3}'; $productImgThumbHeight = Redshop::getConfig()->get('PRODUCT_MAIN_IMAGE_HEIGHT_3'); - $productImgThumbWidth = Redshop::getConfig()->get('PRODUCT_MAIN_IMAGE_3'); + $productImgThumbWidth = Redshop::getConfig()->get('PRODUCT_MAIN_IMAGE_3'); } elseif (strpos($productTemplate, "{product_thumb_image_2}") !== false) { - $productImgTag = '{product_thumb_image_2}'; + $productImgTag = '{product_thumb_image_2}'; $productImgThumbHeight = Redshop::getConfig()->get('PRODUCT_MAIN_IMAGE_HEIGHT_2'); - $productImgThumbWidth = Redshop::getConfig()->get('PRODUCT_MAIN_IMAGE_2'); + $productImgThumbWidth = Redshop::getConfig()->get('PRODUCT_MAIN_IMAGE_2'); } elseif (strpos($productTemplate, "{product_thumb_image_1}") !== false) { - $productImgTag = '{product_thumb_image_1}'; + $productImgTag = '{product_thumb_image_1}'; $productImgThumbHeight = Redshop::getConfig()->get('PRODUCT_MAIN_IMAGE_HEIGHT'); - $productImgThumbWidth = Redshop::getConfig()->get('PRODUCT_MAIN_IMAGE'); + $productImgThumbWidth = Redshop::getConfig()->get('PRODUCT_MAIN_IMAGE'); } else { - $productImgTag = '{product_thumb_image}'; + $productImgTag = '{product_thumb_image}'; $productImgThumbHeight = Redshop::getConfig()->get('PRODUCT_MAIN_IMAGE_HEIGHT'); - $productImgThumbWidth = Redshop::getConfig()->get('PRODUCT_MAIN_IMAGE'); + $productImgThumbWidth = Redshop::getConfig()->get('PRODUCT_MAIN_IMAGE'); } } if (strpos($productTemplate, "{more_images_3}") !== false) { $moreProductsImgThumbHeight = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_HEIGHT_3'); - $moreProductsImgThumbWidth = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_3'); + $moreProductsImgThumbWidth = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_3'); } elseif (strpos($productTemplate, "{more_images_2}") !== false) { $moreProductsImgThumbHeight = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_HEIGHT_2'); - $moreProductsImgThumbWidth = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_2'); + $moreProductsImgThumbWidth = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_2'); } elseif (strpos($productTemplate, "{more_images_1}") !== false) { $moreProductsImgThumbHeight = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_HEIGHT'); - $moreProductsImgThumbWidth = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE'); + $moreProductsImgThumbWidth = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE'); } else { $moreProductsImgThumbHeight = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE_HEIGHT'); - $moreProductsImgThumbWidth = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE'); + $moreProductsImgThumbWidth = Redshop::getConfig()->get('PRODUCT_ADDITIONAL_IMAGE'); } if ($mainImgWidth != 0 || $mainImgHeight != 0) { - $productImgThumbWidth = $mainImgWidth; + $productImgThumbWidth = $mainImgWidth; $productImgThumbHeight = $mainImgHeight; } $imageAttributes = Redshop\Product\Image\Image::getDisplayMain( - $productId, $propertyId, $subPropertyId, $productImgThumbWidth, $productImgThumbHeight, $redView + $productId, + $propertyId, + $subPropertyId, + $productImgThumbWidth, + $productImgThumbHeight, + $redView ); - $aHrefImageResponse = $imageAttributes['aHrefImageResponse']; - $mainImageResponse = $imageAttributes['mainImageResponse']; - $productMainImg = $imageAttributes['productmainimg']; + $aHrefImageResponse = $imageAttributes['aHrefImageResponse']; + $mainImageResponse = $imageAttributes['mainImageResponse']; + $productMainImg = $imageAttributes['productmainimg']; $aTitleImageResponse = $imageAttributes['aTitleImageResponse']; - $imgName = $imageAttributes['imagename']; + $imgName = $imageAttributes['imagename']; // $ImageAttributes['type'] = $type; - $attributeImg = $imageAttributes['attrbimg']; + $attributeImg = $imageAttributes['attrbimg']; $productNumber = $imageAttributes['pr_number']; // $view = $ImageAttributes['view']; - $propertyAdditionalImages = ""; - $subPropertyAdditionalImages = ""; - $propertyAdditionalVideos = ""; - $subPropertyAdditionalVideos = ""; + $propertyAdditionalImages = ""; + $subPropertyAdditionalImages = ""; + $propertyAdditionalVideos = ""; + $subPropertyAdditionalVideos = ""; $productAvailabilityDateLabel = ''; - $productAvailabilityDate = ''; - $mediaImages = RedshopHelperMedia::getAdditionMediaImage($productId, "product"); - $mediaVideos = RedshopHelperMedia::getAdditionMediaImage($productId, "product", "youtube"); + $productAvailabilityDate = ''; + $mediaImages = RedshopHelperMedia::getAdditionMediaImage($productId, "product"); + $mediaVideos = RedshopHelperMedia::getAdditionMediaImage($productId, "product", "youtube"); // Prepare additional media images. $productAdditionalImages = self::prepareAdditionalImages( - $mediaImages, $product, $productImgThumbWidth, $productImgThumbHeight, $moreProductsImgThumbWidth, $moreProductsImgThumbHeight, true + $mediaImages, + $product, + $productImgThumbWidth, + $productImgThumbHeight, + $moreProductsImgThumbWidth, + $moreProductsImgThumbHeight, + true ); - $tmpProductImages = $productAdditionalImages; + $tmpProductImages = $productAdditionalImages; // Prepare additional media videos. $productAdditionalVideos = self::prepareAdditionalVideos($mediaVideos); - $tmpProductVideos = $productAdditionalVideos; + $tmpProductVideos = $productAdditionalVideos; // Prepare for property if necessary if ($propertyId > 0) { @@ -189,10 +221,17 @@ public static function displayAdditionalImage( $mediaVideos = RedshopHelperMedia::getAdditionMediaImage($propertyId, "property", "youtube"); $propertyAdditionalImages = empty($mediaImages) ? $tmpProductImages : self::preparePropertyAdditionalImages( - $mediaImages, $product, $productImgThumbWidth, $productImgThumbHeight, $moreProductsImgThumbWidth, $moreProductsImgThumbHeight + $mediaImages, + $product, + $productImgThumbWidth, + $productImgThumbHeight, + $moreProductsImgThumbWidth, + $moreProductsImgThumbHeight ); - $propertyAdditionalVideos = empty($mediaVideos) ? $tmpProductVideos : self::preparePropertyAdditionalVideos($mediaVideos); + $propertyAdditionalVideos = empty($mediaVideos) ? $tmpProductVideos : self::preparePropertyAdditionalVideos( + $mediaVideos + ); } // Prepare for sub-property if necessary @@ -201,13 +240,18 @@ public static function displayAdditionalImage( $mediaVideos = RedshopHelperMedia::getAdditionMediaImage($subPropertyId, "subproperty", "youtube"); $subPropertyAdditionalImages = self::prepareSubPropertyAdditionalImages( - $mediaImages, $product, $productImgThumbWidth, $productImgThumbHeight, $moreProductsImgThumbWidth, $moreProductsImgThumbHeight + $mediaImages, + $product, + $productImgThumbWidth, + $productImgThumbHeight, + $moreProductsImgThumbWidth, + $moreProductsImgThumbHeight ); $subPropertyAdditionalVideos = self::prepareSubPropertyAdditionalVideos($mediaVideos); } - $response = ""; + $response = ""; $additionalVideos = ""; if (!empty($subPropertyAdditionalImages)) { @@ -227,7 +271,7 @@ public static function displayAdditionalImage( } $productAttributeDelivery = ""; - $attributeFlag = false; + $attributeFlag = false; if (empty($accessoryId)) { if ($subPropertyId) { @@ -257,36 +301,40 @@ public static function displayAdditionalImage( } } - $stockStatus = ''; + $stockStatus = ''; $stockAmountTooltip = ""; - $productInStock = 0; - $stockAmountSrc = ""; - $stockImgFlag = false; - $notifyStock = ''; + $productInStock = 0; + $stockAmountSrc = ""; + $stockImgFlag = false; + $notifyStock = ''; if (Redshop::getConfig()->get('USE_STOCKROOM') == 1 && empty($accessoryId)) { $stockAmounts = array(); if ($subPropertyId) { $productInStock = RedshopHelperStockroom::getStockAmountWithReserve($subPropertyId, "subproperty"); - $stockAmounts = RedshopHelperStockroom::getStockAmountImage($subPropertyId, "subproperty", $productInStock); - $stockImgFlag = true; + $stockAmounts = RedshopHelperStockroom::getStockAmountImage( + $subPropertyId, + "subproperty", + $productInStock + ); + $stockImgFlag = true; } if ($propertyId && $stockImgFlag == false) { $productInStock = RedshopHelperStockroom::getStockAmountWithReserve($propertyId, "property"); - $stockAmounts = RedshopHelperStockroom::getStockAmountImage($propertyId, "property", $productInStock); - $stockImgFlag = true; + $stockAmounts = RedshopHelperStockroom::getStockAmountImage($propertyId, "property", $productInStock); + $stockImgFlag = true; } if ($productId && $stockImgFlag == false) { $productInStock = RedshopHelperStockroom::getStockAmountWithReserve($productId); - $stockAmounts = RedshopHelperStockroom::getStockAmountImage($productId, "product", $productInStock); + $stockAmounts = RedshopHelperStockroom::getStockAmountImage($productId, "product", $productInStock); } if (!empty($stockAmounts)) { $stockAmountTooltip = $stockAmounts[0]->stock_amount_image_tooltip; - $stockAmountSrc = REDSHOP_FRONT_IMAGES_ABSPATH . 'stockroom/' . $stockAmounts[0]->stock_amount_image; + $stockAmountSrc = REDSHOP_FRONT_IMAGES_ABSPATH . 'stockroom/' . $stockAmounts[0]->stock_amount_image; } } @@ -301,8 +349,8 @@ public static function displayAdditionalImage( $attributeSets = \Redshop\Product\Attribute::getProductAttribute(0, $product->attribute_set_id, 0, 1); } - $attributes = \Redshop\Product\Attribute::getProductAttribute($product->product_id); - $attributes = array_merge($attributes, $attributeSets); + $attributes = \Redshop\Product\Attribute::getProductAttribute($product->product_id); + $attributes = array_merge($attributes, $attributeSets); $productStockStatus = RedshopHelperProduct::getproductStockStatus( $product->product_id, count($attributes), @@ -311,10 +359,10 @@ public static function displayAdditionalImage( ); if (strpos($templateHtml, "{stock_status") !== false) { - $stockTags = strstr($templateHtml, "{stock_status:"); + $stockTags = strstr($templateHtml, "{stock_status:"); $newStockTag = explode("}", $stockTags); - $stockTag = substr($newStockTag[0], 1); + $stockTag = substr($newStockTag[0], 1); $stockTagList = explode(":", $stockTag); $availableClass = "available_stock_cls"; @@ -346,10 +394,11 @@ public static function displayAdditionalImage( $stockStatus = "
    " . JText::_('COM_REDSHOP_PRE_ORDER') . "
    "; } - } else { $stockStatus = "
    " . JText::_('COM_REDSHOP_AVAILABLE_STOCK') . "
    "; + . "' class='" . $availableClass . "'>" . JText::_( + 'COM_REDSHOP_AVAILABLE_STOCK' + ) . ""; } } @@ -358,64 +407,73 @@ public static function displayAdditionalImage( $templateHtml, 'product', array( - 'productId' => $productId, - 'propertyId' => $propertyId, - 'subPropertyId' => $subPropertyId, + 'productId' => $productId, + 'propertyId' => $propertyId, + 'subPropertyId' => $subPropertyId, 'productStockStatus' => $productStockStatus, - 'isAjax' => true + 'isAjax' => true ) ); if (strpos($templateHtml, "{product_availability_date}") !== false) { $productAvailabilityDateLabel = ""; - $productAvailabilityDate = ""; + $productAvailabilityDate = ""; if ((!isset($productStockStatus['regular_stock']) || !$productStockStatus['regular_stock']) && $productStockStatus['preorder'] && $product->product_availability_date != "") { $productAvailabilityDateLabel = JText::_('COM_REDSHOP_PRODUCT_AVAILABILITY_DATE_LBL') . ": "; - $productAvailabilityDate = RedshopHelperDatetime::convertDateFormat($product->product_availability_date); + $productAvailabilityDate = RedshopHelperDatetime::convertDateFormat( + $product->product_availability_date + ); } } } return array( - 'response' => $response, - 'aHrefImageResponse' => $aHrefImageResponse, - 'aTitleImageResponse' => $aTitleImageResponse, - 'mainImageResponse' => $mainImageResponse, - 'stockamountSrc' => $stockAmountSrc, - 'stockamountTooltip' => $stockAmountTooltip, - 'ProductAttributeDelivery' => $productAttributeDelivery, - 'attrbimg' => $attributeImg, - 'pr_number' => $productNumber, - 'productinstock' => $productInStock, - 'stock_status' => $stockStatus, - 'product_mainimg' => $productMainImg, - 'ImageName' => $imgName, - 'notifyStock' => $notifyStock, + 'response' => $response, + 'aHrefImageResponse' => $aHrefImageResponse, + 'aTitleImageResponse' => $aTitleImageResponse, + 'mainImageResponse' => $mainImageResponse, + 'stockamountSrc' => $stockAmountSrc, + 'stockamountTooltip' => $stockAmountTooltip, + 'ProductAttributeDelivery' => $productAttributeDelivery, + 'attrbimg' => $attributeImg, + 'pr_number' => $productNumber, + 'productinstock' => $productInStock, + 'stock_status' => $stockStatus, + 'product_mainimg' => $productMainImg, + 'ImageName' => $imgName, + 'notifyStock' => $notifyStock, 'product_availability_date_lbl' => $productAvailabilityDateLabel, - 'product_availability_date' => $productAvailabilityDate, - 'additional_vids' => $additionalVideos + 'product_availability_date' => $productAvailabilityDate, + 'additional_vids' => $additionalVideos ); } /** * Method for prepare additional images for product. * - * @param array $images Array of media images. - * @param object $product Product data. - * @param integer $thumbWidth Product image thumb width. - * @param integer $thumbHeight Product image thumb height. - * @param integer $moreThumbWidth More image thumb width. - * @param integer $moreThumbHeight More image thumb height. - * @param boolean $includeProductFullImage Include product full images in list? + * @param array $images Array of media images. + * @param object $product Product data. + * @param integer $thumbWidth Product image thumb width. + * @param integer $thumbHeight Product image thumb height. + * @param integer $moreThumbWidth More image thumb width. + * @param integer $moreThumbHeight More image thumb height. + * @param boolean $includeProductFullImage Include product full images in list? * * @return string * * @since 2.0.7 */ - public static function prepareAdditionalImages($images, $product, $thumbWidth, $thumbHeight, $moreThumbWidth, $moreThumbHeight, $includeProductFullImage = false) - { + public static function prepareAdditionalImages( + $images, + $product, + $thumbWidth, + $thumbHeight, + $moreThumbWidth, + $moreThumbHeight, + $includeProductFullImage = false + ) { if (empty($images)) { return ''; } @@ -423,14 +481,14 @@ public static function prepareAdditionalImages($images, $product, $thumbWidth, $ $return = ''; $isWaterMarkProductAdditionalImage = Redshop::getConfig()->get('WATERMARK_PRODUCT_ADDITIONAL_IMAGE'); - $isWaterMarkProductThumbImage = Redshop::getConfig()->get('WATERMARK_PRODUCT_THUMB_IMAGE'); - $additionalHoverImgWidth = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_WIDTH'); - $additionalHoverImgHeight = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_WIDTH'); - $isUseImageSizeSwapping = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); - $productAddingIsLightbox = Redshop::getConfig()->get('PRODUCT_ADDIMG_IS_LIGHTBOX'); - $defaultProductImage = Redshop::getConfig()->get('PRODUCT_DEFAULT_IMAGE'); - $isAdditionalHoverImage = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_ENABLE'); - $productFullImage = null; + $isWaterMarkProductThumbImage = Redshop::getConfig()->get('WATERMARK_PRODUCT_THUMB_IMAGE'); + $additionalHoverImgWidth = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_WIDTH'); + $additionalHoverImgHeight = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_WIDTH'); + $isUseImageSizeSwapping = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); + $productAddingIsLightbox = Redshop::getConfig()->get('PRODUCT_ADDIMG_IS_LIGHTBOX'); + $defaultProductImage = Redshop::getConfig()->get('PRODUCT_DEFAULT_IMAGE'); + $isAdditionalHoverImage = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_ENABLE'); + $productFullImage = null; // Process image list foreach ($images as $index => $image) { @@ -461,13 +519,19 @@ public static function prepareAdditionalImages($images, $product, $thumbWidth, $ // Prepare additional media images. foreach ($images as $index => $image) { - $thumb = $image->media_name; + $thumb = $image->media_name; $altText = RedshopHelperMedia::getAlternativeText('product', $image->section_id, '', $image->media_id); $altText = !$altText ? $image->media_name : $altText; if ($isWaterMarkProductAdditionalImage) { - $productImg = RedshopHelperMedia::watermark('product', $thumb, $moreThumbWidth, $moreThumbHeight, "1"); - $linkImage = RedshopHelperMedia::watermark('product', $thumb, '', '', "0"); + $productImg = RedshopHelperMedia::watermark( + 'product', + $thumb, + $moreThumbWidth, + $moreThumbHeight, + "1" + ); + $linkImage = RedshopHelperMedia::watermark('product', $thumb, '', '', "0"); $imageHoverPath = RedshopHelperMedia::watermark( 'product', $thumb, @@ -502,10 +566,10 @@ public static function prepareAdditionalImages($images, $product, $thumbWidth, $ if ($productAddingIsLightbox) { $productAdditionalImageDivStart = '"; - $return .= $productAdditionalImageDivStart; - $return .= '' . $altText . ''; - $productHrefEnd = ""; + $productAdditionalImageDivEnd = ""; + $return .= $productAdditionalImageDivStart; + $return .= '' . $altText . ''; + $productHrefEnd = ""; } else { if ($isWaterMarkProductAdditionalImage) { $imagePath = RedshopHelperMedia::watermark('product', $thumb, $thumbWidth, $thumbHeight, '0'); @@ -521,7 +585,7 @@ public static function prepareAdditionalImages($images, $product, $thumbWidth, $ ); } - $thumbFileName = REDSHOP_FRONT_IMAGES_RELPATH . "product/" . $product->product_thumb_image; + $thumbFileName = REDSHOP_FRONT_IMAGES_RELPATH . "product/" . $product->product_thumb_image; $originalFileName = REDSHOP_FRONT_IMAGES_RELPATH . "product/" . $image->product_full_image; if (JFile::exists($thumbFileName)) { @@ -555,10 +619,10 @@ public static function prepareAdditionalImages($images, $product, $thumbWidth, $ $productAdditionalImageDivStart = '
    '; - $productAdditionalImageDivEnd = "
    "; - $return .= $productAdditionalImageDivStart; - $return .= '' . $altText . ''; - $productHrefEnd = ""; + $productAdditionalImageDivEnd = ""; + $return .= $productAdditionalImageDivStart; + $return .= '' . $altText . ''; + $productHrefEnd = ""; } if ($isAdditionalHoverImage) { @@ -575,7 +639,7 @@ public static function prepareAdditionalImages($images, $product, $thumbWidth, $ /** * Method for prepare additional videos for product. * - * @param array $videos Array of media images. + * @param array $videos Array of media images. * * @return string * @@ -603,36 +667,44 @@ public static function prepareAdditionalVideos($videos = array()) /** * Method for prepare additional images for product property. * - * @param array $images Array of media images. - * @param object $product Product data. - * @param integer $thumbWidth Product image thumb width. - * @param integer $thumbHeight Product image thumb height. - * @param integer $moreThumbWidth More image thumb width. - * @param integer $moreThumbHeight More image thumb height. + * @param array $images Array of media images. + * @param object $product Product data. + * @param integer $thumbWidth Product image thumb width. + * @param integer $thumbHeight Product image thumb height. + * @param integer $moreThumbWidth More image thumb width. + * @param integer $moreThumbHeight More image thumb height. * * @return string * * @since 2.0.7 */ - public static function preparePropertyAdditionalImages($images, $product, $thumbWidth, $thumbHeight, $moreThumbWidth, $moreThumbHeight) - { + public static function preparePropertyAdditionalImages( + $images, + $product, + $thumbWidth, + $thumbHeight, + $moreThumbWidth, + $moreThumbHeight + ) { if (empty($images)) { return ''; } $return = ''; - $productAddingIsLightbox = Redshop::getConfig()->get('PRODUCT_ADDIMG_IS_LIGHTBOX'); - $defaultProductImage = Redshop::getConfig()->get('PRODUCT_DEFAULT_IMAGE'); - $isUseImageSizeSwapping = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); - $isAdditionalHoverImage = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_ENABLE'); - $additionalHoverImgWidth = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_WIDTH'); + $productAddingIsLightbox = Redshop::getConfig()->get('PRODUCT_ADDIMG_IS_LIGHTBOX'); + $defaultProductImage = Redshop::getConfig()->get('PRODUCT_DEFAULT_IMAGE'); + $isUseImageSizeSwapping = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); + $isAdditionalHoverImage = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_ENABLE'); + $additionalHoverImgWidth = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_WIDTH'); $additionalHoverImgHeight = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_WIDTH'); foreach ($images as $image) { $thumb = $image->media_name; - if (empty($thumb) || $thumb == $image->property_main_image || !JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . 'property/' . $thumb)) { + if (empty($thumb) || $thumb == $image->property_main_image || !JFile::exists( + REDSHOP_FRONT_IMAGES_RELPATH . 'property/' . $thumb + )) { continue; } @@ -652,10 +724,10 @@ public static function preparePropertyAdditionalImages($images, $product, $thumb $propAdditionImgDivStart = '"; - $return .= $propAdditionImgDivStart; - $return .= "" . $altText . ""; - $propHrefEnd = ""; + $propAdditionImgDivEnd = ""; + $return .= $propAdditionImgDivStart; + $return .= "" . $altText . ""; + $propHrefEnd = ""; } else { $imagePath = RedshopHelperMedia::getImagePath( $thumb, @@ -694,7 +766,7 @@ public static function preparePropertyAdditionalImages($images, $product, $thumb $propAdditionImgDivStart = '
    '; - $propAdditionImgDivEnd = "
    "; + $propAdditionImgDivEnd = ""; $thumbUrl = RedshopHelperMedia::getImagePath( $thumb, @@ -737,7 +809,7 @@ public static function preparePropertyAdditionalImages($images, $product, $thumb /** * Method for prepare additional videos for product property. * - * @param array $videos Array of media images. + * @param array $videos Array of media images. * * @return string * @@ -765,35 +837,43 @@ public static function preparePropertyAdditionalVideos($videos = array()) /** * Method for prepare additional images for product sub-property. * - * @param array $images Array of media images. - * @param object $product Product data. - * @param integer $thumbWidth Product image thumb width. - * @param integer $thumbHeight Product image thumb height. - * @param integer $moreThumbWidth More image thumb width. - * @param integer $moreThumbHeight More image thumb height. + * @param array $images Array of media images. + * @param object $product Product data. + * @param integer $thumbWidth Product image thumb width. + * @param integer $thumbHeight Product image thumb height. + * @param integer $moreThumbWidth More image thumb width. + * @param integer $moreThumbHeight More image thumb height. * * @return string * * @since 2.0.7 */ - public static function prepareSubPropertyAdditionalImages($images, $product, $thumbWidth, $thumbHeight, $moreThumbWidth, $moreThumbHeight) - { + public static function prepareSubPropertyAdditionalImages( + $images, + $product, + $thumbWidth, + $thumbHeight, + $moreThumbWidth, + $moreThumbHeight + ) { if (empty($images)) { return ''; } $result = ''; - $productAddingIsLightbox = Redshop::getConfig()->get('PRODUCT_ADDIMG_IS_LIGHTBOX'); - $defaultProductImage = Redshop::getConfig()->get('PRODUCT_DEFAULT_IMAGE'); - $useImgSizeSwapping = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); - $isAdditionalHoverImage = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_ENABLE'); - $additionalHoverImgWidth = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_WIDTH'); + $productAddingIsLightbox = Redshop::getConfig()->get('PRODUCT_ADDIMG_IS_LIGHTBOX'); + $defaultProductImage = Redshop::getConfig()->get('PRODUCT_DEFAULT_IMAGE'); + $useImgSizeSwapping = Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING'); + $isAdditionalHoverImage = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_ENABLE'); + $additionalHoverImgWidth = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_WIDTH'); $additionalHoverImgHeight = Redshop::getConfig()->get('ADDITIONAL_HOVER_IMAGE_WIDTH'); foreach ($images as $image) { - $thumb = $image->media_name; - $folder = JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . "subproperty/" . $thumb) ? 'subproperty' : 'property'; + $thumb = $image->media_name; + $folder = JFile::exists( + REDSHOP_FRONT_IMAGES_RELPATH . "subproperty/" . $thumb + ) ? 'subproperty' : 'property'; if (empty($thumb) || $thumb == $image->subattribute_color_main_image || !JFile::exists(REDSHOP_FRONT_IMAGES_RELPATH . $folder . "/" . $thumb)) { @@ -806,16 +886,32 @@ public static function prepareSubPropertyAdditionalImages($images, $product, $th if ($productAddingIsLightbox) { $divStart = '"; + $divEnd = ""; - $thumbUrl = RedshopHelperMedia::getImagePath($thumb, '', 'thumb', $folder, $moreThumbWidth, $moreThumbHeight, $useImgSizeSwapping); + $thumbUrl = RedshopHelperMedia::getImagePath( + $thumb, + '', + 'thumb', + $folder, + $moreThumbWidth, + $moreThumbHeight, + $useImgSizeSwapping + ); $result .= $divStart; $result .= "" . $altText . ""; $hrefEnd = ""; } else { - $imagePath = RedshopHelperMedia::getImagePath($thumb, '', 'thumb', $folder, $thumbWidth, $thumbHeight, $useImgSizeSwapping); + $imagePath = RedshopHelperMedia::getImagePath( + $thumb, + '', + 'thumb', + $folder, + $thumbWidth, + $thumbHeight, + $useImgSizeSwapping + ); $subPropertyFileNameOriginal = REDSHOP_FRONT_IMAGES_RELPATH . "subproperty/" . $thumb; @@ -835,7 +931,7 @@ public static function prepareSubPropertyAdditionalImages($images, $product, $th $divStart = '
    '; - $divEnd = "
    "; + $divEnd = ""; $thumbUrl = RedshopHelperMedia::getImagePath( $thumb, @@ -847,8 +943,8 @@ public static function prepareSubPropertyAdditionalImages($images, $product, $th $useImgSizeSwapping ); - $result .= $divStart; - $result .= '' + $result .= $divStart; + $result .= '' . '' . $altText . ''; $hrefEnd = ""; } @@ -863,7 +959,7 @@ public static function prepareSubPropertyAdditionalImages($images, $product, $th $additionalHoverImgHeight, $useImgSizeSwapping ); - $result .= '' . $altText . ''; + $result .= '' . $altText . ''; } $result .= $hrefEnd; @@ -876,7 +972,7 @@ public static function prepareSubPropertyAdditionalImages($images, $product, $th /** * Method for prepare additional videos for product sub-property. * - * @param array $videos Array of media images. + * @param array $videos Array of media images. * * @return string * @@ -904,18 +1000,24 @@ public static function prepareSubPropertyAdditionalVideos($videos = array()) /** * Replace Attribute Data * - * @param integer $productId Product id - * @param integer $accessoryId Accessory id - * @param array $attributes Attribute list - * @param integer $userId User id - * @param string $uniqueId Unique id + * @param integer $productId Product id + * @param integer $accessoryId Accessory id + * @param array $attributes Attribute list + * @param integer $userId User id + * @param string $uniqueId Unique id * * @return mixed * * @since 2.1.0 */ - public static function replaceAttributeData($productId = 0, $accessoryId = 0, $attributes = array(), $userId = 0, $uniqueId = "", $isTripTags = false) - { + public static function replaceAttributeData( + $productId = 0, + $accessoryId = 0, + $attributes = array(), + $userId = 0, + $uniqueId = "", + $isTripTags = false + ) { $attributeList = ""; $prefix = $accessoryId != 0 ? $uniqueId . "acc_" : $uniqueId . "prd_"; @@ -930,30 +1032,35 @@ public static function replaceAttributeData($productId = 0, $accessoryId = 0, $a continue; } - $commonId = $prefix . $productId . '_' . $accessoryId . '_' . $attribute->attribute_id; + $commonId = $prefix . $productId . '_' . $accessoryId . '_' . $attribute->attribute_id; $hiddenAttId = 'attribute_id_' . $prefix . $productId . '_' . $accessoryId; - $propertyId = 'property_id_' . $commonId; + $propertyId = 'property_id_' . $commonId; foreach ($properties as $property) { $attributesPropertyVat = 0; if ($property->property_price > 0) { $propertyOprand = $property->oprand; - $propertyPrice = RedshopHelperProductPrice::formattedPrice($property->property_price); + $propertyPrice = RedshopHelperProductPrice::formattedPrice($property->property_price); // Get product vat to include. - $attributesPropertyVat = RedshopHelperProduct::getProductTax($productId, $property->property_price, $userId); + $attributesPropertyVat = RedshopHelperProduct::getProductTax( + $productId, + $property->property_price, + $userId + ); $property->property_price += $attributesPropertyVat; $propertyPriceWithVat = RedshopHelperProductPrice::formattedPrice($property->property_price); - if ($isTripTags) - { + if ($isTripTags) { $propertyPriceWithVat = strip_tags($propertyPriceWithVat); $propertyPrice = strip_tags($propertyPrice); } - $property->text = urldecode($property->property_name) . ' (' . $propertyOprand . ' ' . $propertyPrice + $property->text = urldecode( + $property->property_name + ) . ' (' . $propertyOprand . ' ' . $propertyPrice . "excl. vat / " . $propertyPriceWithVat . ")"; } else { @@ -968,13 +1075,13 @@ public static function replaceAttributeData($productId = 0, $accessoryId = 0, $a . $propertyId . '_proprice' . $property->value . '" value="' . $property->property_price . '" />'; } - $tmpArray = array(); - $tmpArray[0] = new stdClass; + $tmpArray = array(); + $tmpArray[0] = new stdClass; $tmpArray[0]->value = 0; - $tmpArray[0]->text = JText::_('COM_REDSHOP_SELECT') . " " . urldecode($attribute->text); + $tmpArray[0]->text = JText::_('COM_REDSHOP_SELECT') . " " . urldecode($attribute->text); $newProperty = array_merge($tmpArray, $properties); - $checkList = ""; + $checkList = ""; if ($attribute->allow_multiple_selection) { foreach ($properties as $property) { @@ -992,11 +1099,17 @@ public static function replaceAttributeData($productId = 0, $accessoryId = 0, $a } } else { $checkList = JHtml::_( - 'select.genericlist', $newProperty, $propertyId . '[]', 'id="' . $propertyId + 'select.genericlist', + $newProperty, + $propertyId . '[]', + 'id="' . $propertyId . '" class="inputbox" size="1" attribute_name="' . $attribute->attribute_name . '" required="' . $attribute->attribute_required . '" onchange="javascript:changeOfflinePropertyDropdown(\'' . $productId . '\',\'' . $accessoryId . '\',\'' . $attribute->attribute_id . '\',\'' . $uniqueId - . '\');" ', 'value', 'text', '' + . '\');" ', + 'value', + 'text', + '' ); } @@ -1005,7 +1118,7 @@ public static function replaceAttributeData($productId = 0, $accessoryId = 0, $a $attributeList .= ""; if ($attribute->attribute_required > 0) { - $pos = Redshop::getConfig()->get('ASTERISK_POSITION') > 0 ? urldecode($attribute->text) + $pos = Redshop::getConfig()->get('ASTERISK_POSITION') > 0 ? urldecode($attribute->text) . " * " : "* " . urldecode($attribute->text); $attrTitle = $pos; diff --git a/libraries/redshop/helper/product_attribute.php b/libraries/redshop/helper/product_attribute.php index 9b5477285d6..4f6e9a7769c 100644 --- a/libraries/redshop/helper/product_attribute.php +++ b/libraries/redshop/helper/product_attribute.php @@ -49,10 +49,10 @@ abstract class RedshopHelperProduct_Attribute /** * Method for get property price with discount * - * @param integer $sectionId Section ID - * @param string $quantity Quantity - * @param string $section Section - * @param integer $userId User ID + * @param integer $sectionId Section ID + * @param string $quantity Quantity + * @param string $section Section + * @param integer $userId User ID * * @return object * @throws Exception @@ -152,12 +152,12 @@ public static function getPropertyPrice($sectionId = 0, $quantity = '', $section /** * Method for display attribute price * - * @param integer $productId Product IID - * @param float $showPrice Show price - * @param string $templateHtml Template HTML - * @param integer $userId User ID - * @param integer $applyTax Is apply tax - * @param array $attributes Attributes data. + * @param integer $productId Product IID + * @param float $showPrice Show price + * @param string $templateHtml Template HTML + * @param integer $userId User ID + * @param integer $applyTax Is apply tax + * @param array $attributes Attributes data. * * @return float * @throws Exception @@ -279,12 +279,12 @@ public static function defaultAttributePrice( /** * Get Attribute Properties of specific product. * - * @param integer $propertyId Property id - * @param integer $attributeId Attribute id - * @param integer $productId Product id - * @param string $attributeSetId Attribute set id - * @param integer $required Required - * @param integer $notPropertyId Not property id + * @param integer $propertyId Property id + * @param integer $attributeId Attribute id + * @param integer $productId Product id + * @param string $attributeSetId Attribute set id + * @param integer $required Required + * @param integer $notPropertyId Not property id * * @return mixed * @throws Exception @@ -434,8 +434,8 @@ public static function getAttributeProperties( /** * Method for get sub properties * - * @param integer $subPropertyId Sub-Property ID - * @param integer $propertyId Property ID + * @param integer $subPropertyId Sub-Property ID + * @param integer $propertyId Property ID * * @return mixed List of sub-properties data. * diff --git a/libraries/redshop/helper/quotation.php b/libraries/redshop/helper/quotation.php index 66030a56fbe..53b5fa503f7 100644 --- a/libraries/redshop/helper/quotation.php +++ b/libraries/redshop/helper/quotation.php @@ -20,544 +20,530 @@ */ class RedshopHelperQuotation { - /** - * Get list of quotation status - * - * @return array An array of status options - * - * @since 2.0.3 - */ - public static function getQuotationStatusList() - { - $status = array(); - $status[] = JHtml::_('select.option', 0, JText::_('COM_REDSHOP_SELECT')); - $status[] = JHtml::_('select.option', 1, JText::_('COM_REDSHOP_REQUESTED')); - $status[] = JHtml::_('select.option', 2, JText::_('COM_REDSHOP_REPLIED')); - $status[] = JHtml::_('select.option', 3, JText::_('COM_REDSHOP_ACCEPTED')); - $status[] = JHtml::_('select.option', 4, JText::_('COM_REDSHOP_REJECTED')); - $status[] = JHtml::_('select.option', 5, JText::_('COM_REDSHOP_ORDERED')); - - return $status; - } - - /** - * Get name of quotation status - * - * @param integer $value Have 5 options: REQUESTED/REPLIED/ACCEPTED/REJECTED/ORDERED - * - * @return string Name of Quotation status - * - * @since 2.0.3 - */ - public static function getQuotationStatusName($value = 0) - { - $name = "-"; - - switch ($value) - { - case 1: - $name = JText::_('COM_REDSHOP_REQUESTED'); - break; - case 2: - $name = JText::_('COM_REDSHOP_REPLIED'); - break; - case 3: - $name = JText::_('COM_REDSHOP_ACCEPTED'); - break; - case 4: - $name = JText::_('COM_REDSHOP_REJECTED'); - break; - case 5: - $name = JText::_('COM_REDSHOP_ORDERED'); - break; - } - - return $name; - } - - /** - * Get quotation product - * - * @param mixed $quotationId List of Quotation ID - * @param integer $quotationItemId Quotation Item ID - * - * @return array - * - * @since 2.0.3 - */ - public static function getQuotationProduct($quotationId, $quotationItemId = 0) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('q.*') - ->from($db->qn('#__redshop_quotation_item', 'q')) - ->where('1 = 1'); - - if (!empty($quotationId)) - { - // Sanitize ids - $quotationId = is_string($quotationId) ? explode(',', $quotationId) : $quotationId; - $quotationId = !is_array($quotationId) ? array($quotationId) : $quotationId; - $quotationId = ArrayHelper::toInteger($quotationId); - - $query->where($db->qn('q.quotation_id') . " IN (" . implode(',', $quotationId) . ")"); - } - - if ($quotationItemId != 0) - { - $query->where($db->qn('q.quotation_item_id') . " = " . (int) $quotationItemId); - } - - $db->setQuery($query); - - return $db->loadObjectList(); - } - - /** - * Get quotation detail by quotation ID - * - * @param integer $quotationId Quotation ID - * - * @return object - * - * @since 2.0.3 - */ - public static function getQuotationDetail($quotationId) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('q.*') - ->select($db->qn('q.user_email', 'quotation_email')) - ->select('u.*') - ->from($db->qn('#__redshop_quotation', 'q')) - ->leftJoin( - $db->qn('#__redshop_users_info', 'u') . ' ON ' . $db->qn('u.user_id') . ' = ' . $db->qn('q.user_id') - . ' AND ' . $db->qn('u.address_type') . ' LIKE ' . $db->quote('BT') - ) - ->where($db->qn('q.quotation_id') . ' = ' . (int) $quotationId); - - $db->setQuery($query); - - return $db->loadObject(); - } - - /** - * Generate a unique quotation number - * - * @return integer - * - * @since 2.0.3 - */ - public static function generateQuotationNumber() - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('COUNT(' . $db->qn('quotation_id') . ')') - ->from($db->qn('#__redshop_quotation', 'q')); - - $db->setQuery($query); - - $maxId = $db->loadResult(); - - return $maxId + 1; - } - - /** - * Update Quotation Status - * - * @param integer $quotationId Quotation ID - * @param integer $status Quotation Change status - * - * @return void - * - * @since 2.0.3 - */ - public static function updateQuotationStatus($quotationId, $status = 1) - { - if (!$quotationId) - { - return; - } - - // Initialize variables. - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - // Create the base update statement. - $query->update($db->qn('#__redshop_quotation', 'q')) - ->set($db->qn('q.quotation_status') . ' = ' . (int) $status) - ->where($db->qn('q.quotation_id') . ' = ' . (int) $quotationId); - - // Set the query and execute the update. - $db->setQuery($query); - - try - { - $db->execute(); - } - catch (RuntimeException $e) - { - throw new RuntimeException($e->getMessage(), $e->getCode()); - } - } - - /** - * Get list of quotation users - * - * @return array - * - * @since 2.0.3 - */ - public static function getQuotationUserList() - { - $user = JFactory::getUser(); - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select('q.*') - ->from($db->qn('#__redshop_quotation', 'q')) - ->where('1=1'); - - if ($user->id) - { - $query->where($db->qn('q.user_id') . ' = ' . (int) $user->id); - } - - $query->order($db->qn('q.quotation_cdate') . ' DESC'); - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * Generate a random encrytion key for quotation - * - * @param string $pLength Length of string to generate - * - * @return string - * - * @since 2.0.3 - */ - public static function randomQuotationEncryptKey($pLength = '30') - { - // Generated a unique order number - $charList = "abcdefghijklmnopqrstuvwxyz"; - $charList .= "1234567890123456789012345678901234567890123456789012345678901234567890"; - - $random = ""; - srand((double) microtime() * 1000000); - - for ($i = 0; $i < $pLength; $i++) - { - $random .= substr($charList, (rand() % (strlen($charList))), 1); - } - - return $random; - } - - /** - * Inserting quotation user's fields - * - * @param array $cart Array of fields to insert - * @param integer $quotationItemId Item ID of Quotation to match - * @param integer $sectionId Section to get field list - * - * @return boolean true/false when inserting success or fail - * - * @since 2.0.3 - */ - public static function manageQuotationUserField($cart = array(), $quotationItemId = 0, $sectionId = 12) - { - $rowData = RedshopHelperExtrafields::getSectionFieldList($sectionId, 1); - - if (empty($rowData)) - { - return false; - } - - for ($i = 0, $in = count($rowData); $i < $in; $i++) - { - if (array_key_exists($rowData[$i]->name, $cart) && $cart[$rowData[$i]->name]) - { - $userFields = $cart[$rowData[$i]->name]; - - if ($userFields != '') - { - self::insertQuotationUserField($rowData[$i]->id, $quotationItemId, $sectionId, $userFields); - } - } - } - - return true; - } - - /** - * Insert quotation field with value - * - * @param integer $fieldId Field ID - * @param integer $quotationItemId Quotation Item ID - * @param integer $sectionId Section ID - * @param string $value Value to insert - * - * @return void - * - * @since 2.0.3 - */ - public static function insertQuotationUserField($fieldId = 0, $quotationItemId = 0, $sectionId = 12, $value = '') - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->insert($db->qn('#__redshop_quotation_fields_data')) - ->columns($db->qn(array('fieldid', 'data_txt', 'quotation_item_id', 'section'))) - ->values(implode(',', array($db->quote((int) $fieldId), $db->quote($value), $db->quote((int) $quotationItemId), $db->quote((int) $sectionId)))); - - $db->setQuery($query)->execute(); - } - - /** - * Get quotation item fields by field ID - * - * @param integer $quotationItemId Quotation Item ID - * - * @return object - * - * @since 2.0.3 - */ - public static function getQuotationUserField($quotationItemId) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select('qf.*') - ->select('f.*') - ->from($db->qn('#__redshop_quotation_fields_data', 'qf')) - ->leftJoin($db->qn('#__redshop_fields', 'f') . ' ON ' . $db->qn('f.id') . ' = ' . $db->qn('qf.fieldid')) - ->where($db->qn('qf.quotation_item_id') . ' = ' . (int) $quotationItemId); - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * Display quotation user fields - * - * @param integer $quotationItemId Quotation Item ID - * @param integer $sectionId Section ID - * - * @return string HTML to display - * - * @since 2.0.3 - * - * @throws Exception - */ - public static function displayQuotationUserField($quotationItemId = 0, $sectionId = 12) - { - /** - * @TODO: ProductHelper will be deprecated, - * replace them with approriated classes - */ - - $resultArr = array(); - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select('fd.*') - ->select($db->qn(array('f.title', 'f.type', 'f.name'))) - ->from($db->qn('#__redshop_quotation_fields_data', 'fd')) - ->leftJoin($db->qn('#__redshop_fields', 'f') . ' ON ' . $db->qn('f.id') . ' = ' . $db->qn('fd.fieldid')) - ->where($db->qn('fd.quotation_item_id') . ' = ' . $db->q((int) $quotationItemId)) - ->where($db->qn('fd.section') . ' = ' . $db->q((int) $sectionId)); - - $db->setQuery($query); - $userField = $db->loadObjectList(); - - if (count($userField) > 0) - { - $quotationItem = self::getQuotationProduct(0, $quotationItemId); - $productId = $quotationItem[0]->product_id; - - $productDetail = Redshop::product((int) $productId); - $productTemplate = RedshopHelperTemplate::getTemplate("product", $productDetail->product_template); - - $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate($productTemplate[0]->template_desc); - $userFieldTag = $returnArr[1]; - - for ($i = 0, $in = count($userFieldTag); $i < $in; $i++) - { - for ($j = 0, $jn = count($userField); $j < $jn; $j++) - { - if ($userField[$j]->name == $userFieldTag[$i]) - { - if ($userField[$j]->type == 10) - { - $files = explode(",", $userField[$j]->data_txt); - $dataTxt = ""; - - for ($f = 0, $fn = count($files); $f < $fn; $f++) - { - $uLink = REDSHOP_FRONT_DOCUMENT_ABSPATH . "product/" . $files[$f]; - $dataTxt .= "" . $files[$f] . " "; - } - - $resultArr[] = $userField[$j]->title . " : " . $dataTxt; - } - else - { - $resultArr[] = $userField[$j]->title . " : " . $userField[$j]->data_txt; - } - } - } - } - } - - if (empty($resultArr)) - { - return ''; - } - - return '
    ' . implode('
    ', $resultArr); - } - - /** - * Update quotation with order ID - * - * @param integer $quotationId Quotation ID - * @param integer $orderId Order ID - * - * @return boolean/void Return true if success, alert error if fail - * - * @since 2.0.3 - */ - public static function updateQuotationWithOrder($quotationId, $orderId) - { - // Initialize variables. - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - // Create the base update statement. - $query->update($db->qn('#__redshop_quotation', 'q')) - ->set($db->qn('q.order_id') . ' = ' . (int) $orderId) - ->where($db->qn('q.quotation_id') . ' = ' . (int) $quotationId); - - // Set the query and execute the update. - $db->setQuery($query); - - try - { - $db->execute(); - self::updateQuotationStatus($quotationId, 5); - } - catch (RuntimeException $e) - { - throw new RuntimeException($e->getMessage(), $e->getCode()); - } - - return true; - } - - /** - * Get quotation by order id - * - * @param integer /array $orderId OrderID - * - * @return object - * - * @since 2.0.3 - */ - public static function getQuotationWithOrder($orderId = 0) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select('q.*') - ->from($db->qn('#__redshop_quotation', 'q')) - ->where('1=1'); - - if ($orderId != 0) - { - // Sanitize ids - $orderId = explode(',', $orderId); - $orderId = ArrayHelper::toInteger($orderId); - - if (is_array($orderId)) - { - $orderId = implode(',', $orderId); - } - - $query->where($db->qn('q.order_id') . ' IN (' . $orderId . ')'); - } - - $query->order($db->qn('q.quotation_cdate') . ' DESC'); - - $db->setQuery($query); - - return $db->loadObjectList(); - } - - /** - * Get quotation accesory item by ID - * - * @param integer $quotationItemId Quotation Item ID - * - * @return object - * - * @since 2.0.3 - */ - public static function getQuotationItemAccessoryDetail($quotationItemId = 0) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select('qa.*') - ->from($db->qn('#__redshop_quotation_accessory_item', 'qa')) - ->where('1 = 1'); - - if ($quotationItemId != 0) - { - $query->where($db->qn('qa.quotation_item_id') . ' = ' . (int) $quotationItemId); - } - - $db->setQuery($query); - - return $db->loadObjectList(); - } - - /** - * Get Quotation Item Attribute Detail - * - * @param integer $quotationItemId Quotation Item ID - * @param integer $isAccessory Check Accessory Attribute - * @param string $section Section: default is "attribute" - * @param integer $parentSectionId Parent section ID - * - * @return object - * - * @since 2.0.3 - */ - public static function getQuotationItemAttributeDetail($quotationItemId = 0, $isAccessory = 0, $section = "attribute", $parentSectionId = 0) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select('qat.*') - ->from($db->qn('#__redshop_quotation_attribute_item', 'qat')) - ->where($db->qn('qat.is_accessory_att') . ' = ' . (int) $isAccessory) - ->where($db->qn('qat.section') . ' = ' . $db->quote($section)); - - if ($quotationItemId != 0) - { - $query->where($db->qn('qat.quotation_item_id') . ' = ' . (int) $quotationItemId); - } - - if ($parentSectionId != 0) - { - $query->where($db->qn('qat.parent_section_id') . ' = ' . (int) $parentSectionId); - } - - $db->setQuery($query); - - return $db->loadObjectList(); - } + /** + * Get list of quotation status + * + * @return array An array of status options + * + * @since 2.0.3 + */ + public static function getQuotationStatusList() + { + $status = array(); + $status[] = JHtml::_('select.option', 0, JText::_('COM_REDSHOP_SELECT')); + $status[] = JHtml::_('select.option', 1, JText::_('COM_REDSHOP_REQUESTED')); + $status[] = JHtml::_('select.option', 2, JText::_('COM_REDSHOP_REPLIED')); + $status[] = JHtml::_('select.option', 3, JText::_('COM_REDSHOP_ACCEPTED')); + $status[] = JHtml::_('select.option', 4, JText::_('COM_REDSHOP_REJECTED')); + $status[] = JHtml::_('select.option', 5, JText::_('COM_REDSHOP_ORDERED')); + + return $status; + } + + /** + * Get name of quotation status + * + * @param integer $value Have 5 options: REQUESTED/REPLIED/ACCEPTED/REJECTED/ORDERED + * + * @return string Name of Quotation status + * + * @since 2.0.3 + */ + public static function getQuotationStatusName($value = 0) + { + $name = "-"; + + switch ($value) { + case 1: + $name = JText::_('COM_REDSHOP_REQUESTED'); + break; + case 2: + $name = JText::_('COM_REDSHOP_REPLIED'); + break; + case 3: + $name = JText::_('COM_REDSHOP_ACCEPTED'); + break; + case 4: + $name = JText::_('COM_REDSHOP_REJECTED'); + break; + case 5: + $name = JText::_('COM_REDSHOP_ORDERED'); + break; + } + + return $name; + } + + /** + * Get quotation detail by quotation ID + * + * @param integer $quotationId Quotation ID + * + * @return object + * + * @since 2.0.3 + */ + public static function getQuotationDetail($quotationId) + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('q.*') + ->select($db->qn('q.user_email', 'quotation_email')) + ->select('u.*') + ->from($db->qn('#__redshop_quotation', 'q')) + ->leftJoin( + $db->qn('#__redshop_users_info', 'u') . ' ON ' . $db->qn('u.user_id') . ' = ' . $db->qn('q.user_id') + . ' AND ' . $db->qn('u.address_type') . ' LIKE ' . $db->quote('BT') + ) + ->where($db->qn('q.quotation_id') . ' = ' . (int)$quotationId); + + $db->setQuery($query); + + return $db->loadObject(); + } + + /** + * Generate a unique quotation number + * + * @return integer + * + * @since 2.0.3 + */ + public static function generateQuotationNumber() + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('COUNT(' . $db->qn('quotation_id') . ')') + ->from($db->qn('#__redshop_quotation', 'q')); + + $db->setQuery($query); + + $maxId = $db->loadResult(); + + return $maxId + 1; + } + + /** + * Get list of quotation users + * + * @return array + * + * @since 2.0.3 + */ + public static function getQuotationUserList() + { + $user = JFactory::getUser(); + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select('q.*') + ->from($db->qn('#__redshop_quotation', 'q')) + ->where('1=1'); + + if ($user->id) { + $query->where($db->qn('q.user_id') . ' = ' . (int)$user->id); + } + + $query->order($db->qn('q.quotation_cdate') . ' DESC'); + + return $db->setQuery($query)->loadObjectList(); + } + + /** + * Generate a random encrytion key for quotation + * + * @param string $pLength Length of string to generate + * + * @return string + * + * @since 2.0.3 + */ + public static function randomQuotationEncryptKey($pLength = '30') + { + // Generated a unique order number + $charList = "abcdefghijklmnopqrstuvwxyz"; + $charList .= "1234567890123456789012345678901234567890123456789012345678901234567890"; + + $random = ""; + srand((double)microtime() * 1000000); + + for ($i = 0; $i < $pLength; $i++) { + $random .= substr($charList, (rand() % (strlen($charList))), 1); + } + + return $random; + } + + /** + * Inserting quotation user's fields + * + * @param array $cart Array of fields to insert + * @param integer $quotationItemId Item ID of Quotation to match + * @param integer $sectionId Section to get field list + * + * @return boolean true/false when inserting success or fail + * + * @since 2.0.3 + */ + public static function manageQuotationUserField($cart = array(), $quotationItemId = 0, $sectionId = 12) + { + $rowData = RedshopHelperExtrafields::getSectionFieldList($sectionId, 1); + + if (empty($rowData)) { + return false; + } + + for ($i = 0, $in = count($rowData); $i < $in; $i++) { + if (array_key_exists($rowData[$i]->name, $cart) && $cart[$rowData[$i]->name]) { + $userFields = $cart[$rowData[$i]->name]; + + if ($userFields != '') { + self::insertQuotationUserField($rowData[$i]->id, $quotationItemId, $sectionId, $userFields); + } + } + } + + return true; + } + + /** + * Insert quotation field with value + * + * @param integer $fieldId Field ID + * @param integer $quotationItemId Quotation Item ID + * @param integer $sectionId Section ID + * @param string $value Value to insert + * + * @return void + * + * @since 2.0.3 + */ + public static function insertQuotationUserField($fieldId = 0, $quotationItemId = 0, $sectionId = 12, $value = '') + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->insert($db->qn('#__redshop_quotation_fields_data')) + ->columns($db->qn(array('fieldid', 'data_txt', 'quotation_item_id', 'section'))) + ->values( + implode( + ',', + array( + $db->quote((int)$fieldId), + $db->quote($value), + $db->quote((int)$quotationItemId), + $db->quote((int)$sectionId) + ) + ) + ); + + $db->setQuery($query)->execute(); + } + + /** + * Get quotation item fields by field ID + * + * @param integer $quotationItemId Quotation Item ID + * + * @return object + * + * @since 2.0.3 + */ + public static function getQuotationUserField($quotationItemId) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select('qf.*') + ->select('f.*') + ->from($db->qn('#__redshop_quotation_fields_data', 'qf')) + ->leftJoin($db->qn('#__redshop_fields', 'f') . ' ON ' . $db->qn('f.id') . ' = ' . $db->qn('qf.fieldid')) + ->where($db->qn('qf.quotation_item_id') . ' = ' . (int)$quotationItemId); + + return $db->setQuery($query)->loadObjectList(); + } + + /** + * Display quotation user fields + * + * @param integer $quotationItemId Quotation Item ID + * @param integer $sectionId Section ID + * + * @return string HTML to display + * + * @throws Exception + * @since 2.0.3 + * + */ + public static function displayQuotationUserField($quotationItemId = 0, $sectionId = 12) + { + /** + * @TODO: ProductHelper will be deprecated, + * replace them with approriated classes + */ + + $resultArr = array(); + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select('fd.*') + ->select($db->qn(array('f.title', 'f.type', 'f.name'))) + ->from($db->qn('#__redshop_quotation_fields_data', 'fd')) + ->leftJoin($db->qn('#__redshop_fields', 'f') . ' ON ' . $db->qn('f.id') . ' = ' . $db->qn('fd.fieldid')) + ->where($db->qn('fd.quotation_item_id') . ' = ' . $db->q((int)$quotationItemId)) + ->where($db->qn('fd.section') . ' = ' . $db->q((int)$sectionId)); + + $db->setQuery($query); + $userField = $db->loadObjectList(); + + if (count($userField) > 0) { + $quotationItem = self::getQuotationProduct(0, $quotationItemId); + $productId = $quotationItem[0]->product_id; + + $productDetail = Redshop::product((int)$productId); + $productTemplate = RedshopHelperTemplate::getTemplate("product", $productDetail->product_template); + + $returnArr = \Redshop\Product\Product::getProductUserfieldFromTemplate( + $productTemplate[0]->template_desc + ); + $userFieldTag = $returnArr[1]; + + for ($i = 0, $in = count($userFieldTag); $i < $in; $i++) { + for ($j = 0, $jn = count($userField); $j < $jn; $j++) { + if ($userField[$j]->name == $userFieldTag[$i]) { + if ($userField[$j]->type == 10) { + $files = explode(",", $userField[$j]->data_txt); + $dataTxt = ""; + + for ($f = 0, $fn = count($files); $f < $fn; $f++) { + $uLink = REDSHOP_FRONT_DOCUMENT_ABSPATH . "product/" . $files[$f]; + $dataTxt .= "" . $files[$f] . " "; + } + + $resultArr[] = $userField[$j]->title . " : " . $dataTxt; + } else { + $resultArr[] = $userField[$j]->title . " : " . $userField[$j]->data_txt; + } + } + } + } + } + + if (empty($resultArr)) { + return ''; + } + + return '
    ' . implode('
    ', $resultArr); + } + + /** + * Get quotation product + * + * @param mixed $quotationId List of Quotation ID + * @param integer $quotationItemId Quotation Item ID + * + * @return array + * + * @since 2.0.3 + */ + public static function getQuotationProduct($quotationId, $quotationItemId = 0) + { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('q.*') + ->from($db->qn('#__redshop_quotation_item', 'q')) + ->where('1 = 1'); + + if (!empty($quotationId)) { + // Sanitize ids + $quotationId = is_string($quotationId) ? explode(',', $quotationId) : $quotationId; + $quotationId = !is_array($quotationId) ? array($quotationId) : $quotationId; + $quotationId = ArrayHelper::toInteger($quotationId); + + $query->where($db->qn('q.quotation_id') . " IN (" . implode(',', $quotationId) . ")"); + } + + if ($quotationItemId != 0) { + $query->where($db->qn('q.quotation_item_id') . " = " . (int)$quotationItemId); + } + + $db->setQuery($query); + + return $db->loadObjectList(); + } + + /** + * Update quotation with order ID + * + * @param integer $quotationId Quotation ID + * @param integer $orderId Order ID + * + * @return boolean/void Return true if success, alert error if fail + * + * @since 2.0.3 + */ + public static function updateQuotationWithOrder($quotationId, $orderId) + { + // Initialize variables. + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + // Create the base update statement. + $query->update($db->qn('#__redshop_quotation', 'q')) + ->set($db->qn('q.order_id') . ' = ' . (int)$orderId) + ->where($db->qn('q.quotation_id') . ' = ' . (int)$quotationId); + + // Set the query and execute the update. + $db->setQuery($query); + + try { + $db->execute(); + self::updateQuotationStatus($quotationId, 5); + } catch (RuntimeException $e) { + throw new RuntimeException($e->getMessage(), $e->getCode()); + } + + return true; + } + + /** + * Update Quotation Status + * + * @param integer $quotationId Quotation ID + * @param integer $status Quotation Change status + * + * @return void + * + * @since 2.0.3 + */ + public static function updateQuotationStatus($quotationId, $status = 1) + { + if (!$quotationId) { + return; + } + + // Initialize variables. + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + // Create the base update statement. + $query->update($db->qn('#__redshop_quotation', 'q')) + ->set($db->qn('q.quotation_status') . ' = ' . (int)$status) + ->where($db->qn('q.quotation_id') . ' = ' . (int)$quotationId); + + // Set the query and execute the update. + $db->setQuery($query); + + try { + $db->execute(); + } catch (RuntimeException $e) { + throw new RuntimeException($e->getMessage(), $e->getCode()); + } + } + + /** + * Get quotation by order id + * + * @param integer /array $orderId OrderID + * + * @return object + * + * @since 2.0.3 + */ + public static function getQuotationWithOrder($orderId = 0) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select('q.*') + ->from($db->qn('#__redshop_quotation', 'q')) + ->where('1=1'); + + if ($orderId != 0) { + // Sanitize ids + $orderId = explode(',', $orderId); + $orderId = ArrayHelper::toInteger($orderId); + + if (is_array($orderId)) { + $orderId = implode(',', $orderId); + } + + $query->where($db->qn('q.order_id') . ' IN (' . $orderId . ')'); + } + + $query->order($db->qn('q.quotation_cdate') . ' DESC'); + + $db->setQuery($query); + + return $db->loadObjectList(); + } + + /** + * Get quotation accesory item by ID + * + * @param integer $quotationItemId Quotation Item ID + * + * @return object + * + * @since 2.0.3 + */ + public static function getQuotationItemAccessoryDetail($quotationItemId = 0) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select('qa.*') + ->from($db->qn('#__redshop_quotation_accessory_item', 'qa')) + ->where('1 = 1'); + + if ($quotationItemId != 0) { + $query->where($db->qn('qa.quotation_item_id') . ' = ' . (int)$quotationItemId); + } + + $db->setQuery($query); + + return $db->loadObjectList(); + } + + /** + * Get Quotation Item Attribute Detail + * + * @param integer $quotationItemId Quotation Item ID + * @param integer $isAccessory Check Accessory Attribute + * @param string $section Section: default is "attribute" + * @param integer $parentSectionId Parent section ID + * + * @return object + * + * @since 2.0.3 + */ + public static function getQuotationItemAttributeDetail( + $quotationItemId = 0, + $isAccessory = 0, + $section = "attribute", + $parentSectionId = 0 + ) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select('qat.*') + ->from($db->qn('#__redshop_quotation_attribute_item', 'qat')) + ->where($db->qn('qat.is_accessory_att') . ' = ' . (int)$isAccessory) + ->where($db->qn('qat.section') . ' = ' . $db->quote($section)); + + if ($quotationItemId != 0) { + $query->where($db->qn('qat.quotation_item_id') . ' = ' . (int)$quotationItemId); + } + + if ($parentSectionId != 0) { + $query->where($db->qn('qat.parent_section_id') . ' = ' . (int)$parentSectionId); + } + + $db->setQuery($query); + + return $db->loadObjectList(); + } } diff --git a/libraries/redshop/helper/router.php b/libraries/redshop/helper/router.php index 602e1c22020..cfb49fce22f 100644 --- a/libraries/redshop/helper/router.php +++ b/libraries/redshop/helper/router.php @@ -16,310 +16,289 @@ */ class RedshopHelperRouter { - /** - * @var array - * - * @since 2.1.0 - */ - protected static $menuItems; - - /** - * @var array - * - * @since 2.1.0 - */ - protected static $menuItemAssociation = array(); - - /** - * Get Redshop Menu Items - * - * @return array - * - * @since 2.1.0 - * - * @throws Exception - */ - public static function getRedshopMenuItems() - { - if (is_null(self::$menuItems)) - { - self::$menuItems = JFactory::getApplication()->getMenu('site')->getItems('component', 'com_redshop'); - } - - return self::$menuItems; - } - - /** - * Check Menu Query - * - * @param object $oneMenuItem Values current menu item - * @param array $queryItems Name query check - * - * @return boolean - * - * @since 2.1.0 - */ - public static function checkMenuQuery($oneMenuItem, $queryItems) - { - if (empty($oneMenuItem) || empty($queryItems)) - { - return false; - } - - foreach ($queryItems as $key => $value) - { - if (!isset($oneMenuItem->query[$key]) - || (is_array($value) && !in_array($oneMenuItem->query[$key], $value)) - || (!is_array($value) && $oneMenuItem->query[$key] != $value) - ) - { - return false; - } - } - - return true; - } - - /** - * Get RedShop Menu Item - * - * @param array $queryItems Values query - * - * @return mixed - * - * @since 2.1.0 - * - * @throws Exception - */ - public static function getRedShopMenuItem($queryItems) - { - $serializeItem = md5(serialize($queryItems)); - - if (!array_key_exists($serializeItem, self::$menuItemAssociation)) - { - self::$menuItemAssociation[$serializeItem] = false; - - foreach (self::getRedshopMenuItems() as $oneMenuItem) - { - if (self::checkMenuQuery($oneMenuItem, $queryItems)) - { - self::$menuItemAssociation[$serializeItem] = $oneMenuItem->id; - break; - } - } - } - - return self::$menuItemAssociation[$serializeItem]; - } - - /** - * Get Item Id - * - * @param int $productId Product Id - * @param int $categoryId Category Id - * - * @return mixed - * - * @throws Exception - * - * @since 2.1.0 - */ - public static function getItemId($productId = 0, $categoryId = 0) - { - // Get Itemid from Product detail - if ($productId) - { - $result = self::getRedShopMenuItem(array('option' => 'com_redshop', 'view' => 'product', 'pid' => (int) $productId)); - - if ($result) - { - return $result; - } - } - - // Get Itemid from Category detail - if ($categoryId) - { - $result = self::getCategoryItemid($categoryId); - - if ($result) - { - return $result; - } - } - - $input = JFactory::getApplication()->input; - - if ($input->getCmd('option', '') != 'com_redshop') - { - $result = self::getRedShopMenuItem(array('option' => 'com_redshop', 'view' => 'category')); - - if ($result) - { - return $result; - } - - $result = self::getRedShopMenuItem(array('option' => 'com_redshop')); - - if ($result) - { - return $result; - } - } - - return $input->getInt('Itemid', 0); - } - - /** - * Get Category Itemid - * - * @param int $categoryId Category id - * - * @return mixed - * - * @since 2.1.0 - * - * @throws Exception - */ - public static function getCategoryItemid($categoryId = 0) - { - if (!$categoryId) - { - $result = self::getRedShopMenuItem(array('option' => 'com_redshop', 'view' => 'category')); - - if ($result) - { - return $result; - } - - return null; - } - - $categories = explode(',', $categoryId); - - if ($categories) - { - foreach ($categories as $category) - { - $result = self::getRedShopMenuItem( - array('option' => 'com_redshop', 'view' => 'category', 'layout' => 'detail', 'cid' => (int) $category) - ); - - if ($result) - { - return $result; - } - } - } - - // Get from Parents - $categories = RedshopHelperCategory::getCategoryListReverseArray($categoryId); - - if ($categories) - { - foreach ($categories as $category) - { - $result = self::getCategoryItemid($category->id); - - if ($result) - { - return $result; - } - } - } - - return null; - } - - /** - * Method for get menu item id of checkout page - * - * @return integer - * - * @since 2.1.0 - * - * @throws Exception - */ - public static function getCheckoutItemId() - { - $itemId = Redshop::getConfig()->get('DEFAULT_CART_CHECKOUT_ITEMID'); - $shopperGroup = RedshopHelperUser::getShopperGroupData(); - - if (!empty($shopperGroup) && $shopperGroup->shopper_group_cart_checkout_itemid != 0) - { - $itemId = $shopperGroup->shopper_group_cart_checkout_itemid; - } - - if ($itemId == 0) - { - $itemId = JFactory::getApplication()->input->getInt('Itemid'); - } - - return $itemId; - } - - /** - * Method for get menu item id of cart page - * - * @return integer - * - * @since 2.1.0 - */ - public static function getCartItemId() - { - $itemId = Redshop::getConfig()->get('DEFAULT_CART_CHECKOUT_ITEMID'); - $shopperGroupData = RedshopHelperUser::getShopperGroupData(); - - if (!empty($shopperGroupData) && $shopperGroupData->shopper_group_cart_itemid != 0) - { - $itemId = $shopperGroupData->shopper_group_cart_itemid; - } - - return $itemId; - } - - /** - * Get the URL route for a product from a product ID, product category ID and product manufacturer ID - * - * @param int $id The id of the product - * @param int $catId The id of the product's category - * @param string $language Language - * @param integer $manufacturerId The id of the product's manufacturer - * - * @return string The link to the product - * - * @throws Exception - * @since 2.1.5 - */ - public static function getProductRoute($id, $catId, $language, $manufacturerId = 0) - { - // Create the link - $link = 'index.php?option=com_redshop&view=product&pid=' . $id; - - if ((int) $catId > 0) - { - $link .= '&cid=' . $catId; - } - - // Find the menu item for the search - $app = JFactory::getApplication(); - $menu = $app->getMenu(); - $items = $menu->getItems( - 'link', - 'index.php?option=com_redshop&view=category&layout=detail&cid=' . $catId . - '&manufacturer_id=' . $manufacturerId - ); - - if (isset($items[0])) - { - $link .= '&Itemid=' . (int) $items[0]->id; - } - - if ($language && $language !== '*' && JLanguageMultilang::isEnabled()) - { - $link .= '&lang=' . $language; - } - - return $link; - } + /** + * @var array + * + * @since 2.1.0 + */ + protected static $menuItems; + + /** + * @var array + * + * @since 2.1.0 + */ + protected static $menuItemAssociation = array(); + + /** + * Get Item Id + * + * @param int $productId Product Id + * @param int $categoryId Category Id + * + * @return mixed + * + * @throws Exception + * + * @since 2.1.0 + */ + public static function getItemId($productId = 0, $categoryId = 0) + { + // Get Itemid from Product detail + if ($productId) { + $result = self::getRedShopMenuItem( + array('option' => 'com_redshop', 'view' => 'product', 'pid' => (int)$productId) + ); + + if ($result) { + return $result; + } + } + + // Get Itemid from Category detail + if ($categoryId) { + $result = self::getCategoryItemid($categoryId); + + if ($result) { + return $result; + } + } + + $input = JFactory::getApplication()->input; + + if ($input->getCmd('option', '') != 'com_redshop') { + $result = self::getRedShopMenuItem(array('option' => 'com_redshop', 'view' => 'category')); + + if ($result) { + return $result; + } + + $result = self::getRedShopMenuItem(array('option' => 'com_redshop')); + + if ($result) { + return $result; + } + } + + return $input->getInt('Itemid', 0); + } + + /** + * Get RedShop Menu Item + * + * @param array $queryItems Values query + * + * @return mixed + * + * @throws Exception + * @since 2.1.0 + * + */ + public static function getRedShopMenuItem($queryItems) + { + $serializeItem = md5(serialize($queryItems)); + + if (!array_key_exists($serializeItem, self::$menuItemAssociation)) { + self::$menuItemAssociation[$serializeItem] = false; + + foreach (self::getRedshopMenuItems() as $oneMenuItem) { + if (self::checkMenuQuery($oneMenuItem, $queryItems)) { + self::$menuItemAssociation[$serializeItem] = $oneMenuItem->id; + break; + } + } + } + + return self::$menuItemAssociation[$serializeItem]; + } + + /** + * Get Redshop Menu Items + * + * @return array + * + * @throws Exception + * @since 2.1.0 + * + */ + public static function getRedshopMenuItems() + { + if (is_null(self::$menuItems)) { + self::$menuItems = JFactory::getApplication()->getMenu('site')->getItems('component', 'com_redshop'); + } + + return self::$menuItems; + } + + /** + * Check Menu Query + * + * @param object $oneMenuItem Values current menu item + * @param array $queryItems Name query check + * + * @return boolean + * + * @since 2.1.0 + */ + public static function checkMenuQuery($oneMenuItem, $queryItems) + { + if (empty($oneMenuItem) || empty($queryItems)) { + return false; + } + + foreach ($queryItems as $key => $value) { + if (!isset($oneMenuItem->query[$key]) + || (is_array($value) && !in_array($oneMenuItem->query[$key], $value)) + || (!is_array($value) && $oneMenuItem->query[$key] != $value) + ) { + return false; + } + } + + return true; + } + + /** + * Get Category Itemid + * + * @param int $categoryId Category id + * + * @return mixed + * + * @throws Exception + * @since 2.1.0 + * + */ + public static function getCategoryItemid($categoryId = 0) + { + if (!$categoryId) { + $result = self::getRedShopMenuItem(array('option' => 'com_redshop', 'view' => 'category')); + + if ($result) { + return $result; + } + + return null; + } + + $categories = explode(',', $categoryId); + + if ($categories) { + foreach ($categories as $category) { + $result = self::getRedShopMenuItem( + array( + 'option' => 'com_redshop', + 'view' => 'category', + 'layout' => 'detail', + 'cid' => (int)$category + ) + ); + + if ($result) { + return $result; + } + } + } + + // Get from Parents + $categories = RedshopHelperCategory::getCategoryListReverseArray($categoryId); + + if ($categories) { + foreach ($categories as $category) { + $result = self::getCategoryItemid($category->id); + + if ($result) { + return $result; + } + } + } + + return null; + } + + /** + * Method for get menu item id of checkout page + * + * @return integer + * + * @throws Exception + * @since 2.1.0 + * + */ + public static function getCheckoutItemId() + { + $itemId = Redshop::getConfig()->get('DEFAULT_CART_CHECKOUT_ITEMID'); + $shopperGroup = RedshopHelperUser::getShopperGroupData(); + + if (!empty($shopperGroup) && $shopperGroup->shopper_group_cart_checkout_itemid != 0) { + $itemId = $shopperGroup->shopper_group_cart_checkout_itemid; + } + + if ($itemId == 0) { + $itemId = JFactory::getApplication()->input->getInt('Itemid'); + } + + return $itemId; + } + + /** + * Method for get menu item id of cart page + * + * @return integer + * + * @since 2.1.0 + */ + public static function getCartItemId() + { + $itemId = Redshop::getConfig()->get('DEFAULT_CART_CHECKOUT_ITEMID'); + $shopperGroupData = RedshopHelperUser::getShopperGroupData(); + + if (!empty($shopperGroupData) && $shopperGroupData->shopper_group_cart_itemid != 0) { + $itemId = $shopperGroupData->shopper_group_cart_itemid; + } + + return $itemId; + } + + /** + * Get the URL route for a product from a product ID, product category ID and product manufacturer ID + * + * @param int $id The id of the product + * @param int $catId The id of the product's category + * @param string $language Language + * @param integer $manufacturerId The id of the product's manufacturer + * + * @return string The link to the product + * + * @throws Exception + * @since 2.1.5 + */ + public static function getProductRoute($id, $catId, $language, $manufacturerId = 0) + { + // Create the link + $link = 'index.php?option=com_redshop&view=product&pid=' . $id; + + if ((int)$catId > 0) { + $link .= '&cid=' . $catId; + } + + // Find the menu item for the search + $app = JFactory::getApplication(); + $menu = $app->getMenu(); + $items = $menu->getItems( + 'link', + 'index.php?option=com_redshop&view=category&layout=detail&cid=' . $catId . + '&manufacturer_id=' . $manufacturerId + ); + + if (isset($items[0])) { + $link .= '&Itemid=' . (int)$items[0]->id; + } + + if ($language && $language !== '*' && JLanguageMultilang::isEnabled()) { + $link .= '&lang=' . $language; + } + + return $link; + } } diff --git a/libraries/redshop/helper/sample.php b/libraries/redshop/helper/sample.php index 0de93b192e8..7e34b29852c 100644 --- a/libraries/redshop/helper/sample.php +++ b/libraries/redshop/helper/sample.php @@ -18,315 +18,342 @@ */ class RedshopHelperSample { - /** - * Color mail function. - * - * @return void - * - * @since 2.0.6 - */ - public static function sendMail() - { - $date = JFactory::getDate(); - $today = time(); - $formattedDate = $date->format('Y-m-d'); - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_sample_request')) - ->where($db->qn('block') . ' = 0'); - - $sampleRequests = $db->setQuery($query)->loadObjectList(); - - if (empty($sampleRequests)) - { - return; - } - - $config = JFactory::getConfig(); - $from = $config->get('mailfrom'); - $fromName = $config->get('fromname'); - - foreach ($sampleRequests as $sampleRequest) - { - self::sendFirstReminder($sampleRequest, $today, $from, $fromName); - - self::sendSecondReminder($sampleRequest, $formattedDate, $from, $fromName); - - self::sendThirdReminder($sampleRequest, $formattedDate, $from, $fromName); - } - } - - /** - * Method for send first reminder of sample request - * - * @param object $sampleRequest Sample request data - * @param integer $currentDate Current date - * @param string $from Email from for send mail - * @param string $fromName Name for send mail - * - * @return void - * - * @since 2.0.6 - */ - public static function sendFirstReminder($sampleRequest = null, $currentDate = 0, $from = '', $fromName = '') - { - if (empty($sampleRequest) || !is_object($sampleRequest) || $sampleRequest->reminder_1 != 0) - { - return; - } - - $sendDate = $sampleRequest->registerdate + (Redshop::getConfig()->get('COLOUR_SAMPLE_REMAINDER_1') * 60); - - if ($currentDate < $sendDate) - { - return; - } - - $from = empty($from) ? JFactory::getConfig()->get('mailfrom') : $from; - $fromName = empty($fromName) ? JFactory::getConfig()->get('fromname') : $fromName; - - $mailBody = ""; - $subject = ""; - $mailBcc = null; - $mailData = Redshop\Mail\Helper::getTemplate(0, 'colour_sample_first_reminder'); - - if (count($mailData) > 0) - { - $mailData = $mailData[0]; - $mailBody = $mailData->mail_body; - $subject = $mailData->mail_subject; - - if (trim($mailData->mail_bcc) != "") - { - $mailBcc = explode(",", $mailData->mail_bcc); - } - } - - $body = str_replace("{name}", $sampleRequest->name, $mailBody); - Redshop\Mail\Helper::imgInMail($body); - - if (JFactory::getMailer()->sendMail($from, $fromName, $sampleRequest->email, $subject, $body, 1, null, $mailBcc)) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_sample_request')) - ->set($db->qn('reminder_1') . ' = 1') - ->where($db->qn('request_id') . ' = ' . $sampleRequest->request_id); - - $db->setQuery($query)->execute(); - } - } - - /** - * Method for send second reminder of sample request - * - * @param object $sampleRequest Sample request data - * @param string $currentDate Current date - * @param string $from Email from for send mail - * @param string $fromName Name for send mail - * - * @return void - * - * @since 2.0.6 - */ - public static function sendSecondReminder($sampleRequest = null, $currentDate = '', $from = '', $fromName = '') - { - if (empty($sampleRequest) || !is_object($sampleRequest) || $sampleRequest->reminder_2 != 0) - { - return; - } - - $currentDate = empty($currentDate) ? JFactory::getDate()->format('Y-m-d') : $currentDate; - $sendDate = date("Y-m-d", $sampleRequest->registerdate + (Redshop::getConfig()->get('COLOUR_SAMPLE_REMAINDER_2') * (60 * 60 * 24))); - - if ($currentDate != $sendDate) - { - return; - } - - $from = empty($from) ? JFactory::getConfig()->get('mailfrom') : $from; - $fromName = empty($fromName) ? JFactory::getConfig()->get('fromname') : $fromName; - - $mailBody = ""; - $subject = ""; - $mailBcc = null; - $mailData = Redshop\Mail\Helper::getTemplate(0, 'colour_sample_second_reminder'); - - if (count($mailData) > 0) - { - $mailData = $mailData[0]; - $mailBody = $mailData->mail_body; - $subject = $mailData->mail_subject; - - if (trim($mailData->mail_bcc) != "") - { - $mailBcc = explode(",", $mailData->mail_bcc); - } - } - - $body = str_replace("{name}", $sampleRequest->name, $mailBody); - Redshop\Mail\Helper::imgInMail($body); - - if (JFactory::getMailer()->sendMail($from, $fromName, $sampleRequest->email, $subject, $body, 1, null, $mailBcc)) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_sample_request')) - ->set($db->qn('reminder_2') . ' = 1') - ->where($db->qn('request_id') . ' = ' . $sampleRequest->request_id); - $db->setQuery($query)->execute(); - } - } - - /** - * Method for send third reminder of sample request - * - * @param object $sampleRequest Sample request data - * @param string $currentDate Current date - * @param string $from Email from for send mail - * @param string $fromName Name for send mail - * - * @return void - * - * @since 2.0.6 - */ - public static function sendThirdReminder($sampleRequest = null, $currentDate = '', $from = '', $fromName = '') - { - if (empty($sampleRequest) || !is_object($sampleRequest) || ($sampleRequest->reminder_3 != 0 && $sampleRequest->reminder_coupon != 0)) - { - return; - } - - $currentDate = empty($currentDate) ? JFactory::getDate()->format('Y-m-d') : $currentDate; - $db = JFactory::getDbo(); - - if ($sampleRequest->reminder_3 == 0) - { - $sendDate = date("Y-m-d", $sampleRequest->registerdate + (Redshop::getConfig()->get('COLOUR_SAMPLE_REMAINDER_3') * 60 * 60 * 24)); - $goodToken = md5(uniqid(mt_rand(), true)); - $token = substr($goodToken, 0, 10); - $startDate = mktime(0, 0, 0, date("m"), date("d"), date("Y")); - $endDate = $startDate + (Redshop::getConfig()->get('COLOUR_COUPON_DURATION') * 23 * 59 * 59); - - if ($currentDate != $sendDate) - { - return; - } - - $mailBody = ""; - $subject = ""; - $mailBcc = null; - $mailData = Redshop\Mail\Helper::getTemplate(0, 'colour_sample_third_reminder'); - - if (count($mailData) > 0) - { - $mailData = $mailData[0]; - $mailBody = $mailData->mail_body; - $subject = $mailData->mail_subject; - - if (trim($mailData->mail_bcc) != "") - { - $mailBcc = explode(",", $mailData->mail_bcc); - } - } - - $body = str_replace("{name}", $sampleRequest->name, $mailBody); - $body = str_replace("{days}", Redshop::getConfig()->get('COLOUR_COUPON_DURATION'), $body); - $body = str_replace("{discount}", Redshop::getConfig()->get('COLOUR_DISCOUNT_PERCENTAGE'), $body); - $body = str_replace("{coupon_code}", $token, $body); - Redshop\Mail\Helper::imgInMail($body); - - $query = $db->getQuery(true) - ->select($db->qn('id')) - ->from($db->qn('#__users')) - ->where($db->qn('email') . ' = ' . $db->quote($sampleRequest->email)); - $uid = $db->setQuery($query)->loadResult(); - - if (!empty($uid)) - { - $query->clear() - ->insert($db->qn('#__redshop_coupons')) - ->columns( - $db->qn( - array('code', 'type', 'value', 'start_date', 'end_date', 'effect', 'userid', 'published') - ) - ) - ->values( - $db->quote($token) . ',' . $db->quote(1) . ',' . $db->quote(Redshop::getConfig()->get('DISCOUNT_PERCENTAGE')) . ',' . - $db->quote($startDate) . ',' . $db->quote($endDate) . ',' . $db->quote(1) . ',' . $db->quote($uid) . ',' . $db->quote(1) - ); - - $db->setQuery($query)->execute(); - } - - if (JFactory::getMailer()->sendMail($from, $fromName, $sampleRequest->email, $subject, $body, 1, null, $mailBcc)) - { - $query->clear() - ->update($db->qn('#__redshop_sample_request')) - ->set($db->qn('reminder_3') . ' = 1') - ->where($db->qn('request_id') . ' = ' . $sampleRequest->request_id); - - $db->setQuery($query)->execute(); - } - } - elseif ($sampleRequest->reminder_coupon == 0) - { - $sendDate = date("Y-m-d", $sampleRequest->registerdate + (4 * (60 * 60 * 24))); - - if ($currentDate != $sendDate) - { - return; - } - - $query = $db->getQuery(true) - ->select($db->qn('id')) - ->from($db->qn('#__users')) - ->where($db->qn('email') . ' = ' . $db->quote($sampleRequest->email)); - $uid = $db->setQuery($query)->loadResult(); - - $query->clear() - ->select($db->qn('id')) - ->from($db->qn('#__redshop_coupons')) - ->where($db->qn('userid') . ' = ' . $db->quote($uid)); - $couponCode = $db->setQuery($query)->loadResult(); - - $mailBody = ""; - $subject = ""; - $mailBcc = null; - $mailData = Redshop\Mail\Helper::getTemplate(0, 'colour_sample_third_reminder'); - - if (count($mailData) > 0) - { - $mailData = $mailData[0]; - $mailBody = $mailData->mail_body; - $subject = $mailData->mail_subject; - - if (trim($mailData->mail_bcc) != "") - { - $mailBcc = explode(",", $mailData->mail_bcc); - } - } - - $body = str_replace("{name}", $sampleRequest->name, $mailBody); - $body = str_replace("{days}", Redshop::getConfig()->get('COLOUR_COUPON_DURATION'), $body); - $body = str_replace("{discount}", Redshop::getConfig()->get('COLOUR_DISCOUNT_PERCENTAGE'), $body); - $body = str_replace("{coupon_code}", $couponCode, $body); - Redshop\Mail\Helper::imgInMail($body); - - if (JFactory::getMailer()->sendMail($from, $fromName, $sampleRequest->email, $subject, $body, 1, null, $mailBcc)) - { - $query->clear() - ->update($db->qn('#__redshop_sample_request')) - ->set($db->qn('reminder_coupon') . ' = 1') - ->where($db->qn('request_id') . ' = ' . $sampleRequest->request_id); - - $db->setQuery($query)->execute(); - } - } - } + /** + * Color mail function. + * + * @return void + * + * @since 2.0.6 + */ + public static function sendMail() + { + $date = JFactory::getDate(); + $today = time(); + $formattedDate = $date->format('Y-m-d'); + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_sample_request')) + ->where($db->qn('block') . ' = 0'); + + $sampleRequests = $db->setQuery($query)->loadObjectList(); + + if (empty($sampleRequests)) { + return; + } + + $config = JFactory::getConfig(); + $from = $config->get('mailfrom'); + $fromName = $config->get('fromname'); + + foreach ($sampleRequests as $sampleRequest) { + self::sendFirstReminder($sampleRequest, $today, $from, $fromName); + + self::sendSecondReminder($sampleRequest, $formattedDate, $from, $fromName); + + self::sendThirdReminder($sampleRequest, $formattedDate, $from, $fromName); + } + } + + /** + * Method for send first reminder of sample request + * + * @param object $sampleRequest Sample request data + * @param integer $currentDate Current date + * @param string $from Email from for send mail + * @param string $fromName Name for send mail + * + * @return void + * + * @since 2.0.6 + */ + public static function sendFirstReminder($sampleRequest = null, $currentDate = 0, $from = '', $fromName = '') + { + if (empty($sampleRequest) || !is_object($sampleRequest) || $sampleRequest->reminder_1 != 0) { + return; + } + + $sendDate = $sampleRequest->registerdate + (Redshop::getConfig()->get('COLOUR_SAMPLE_REMAINDER_1') * 60); + + if ($currentDate < $sendDate) { + return; + } + + $from = empty($from) ? JFactory::getConfig()->get('mailfrom') : $from; + $fromName = empty($fromName) ? JFactory::getConfig()->get('fromname') : $fromName; + + $mailBody = ""; + $subject = ""; + $mailBcc = null; + $mailData = Redshop\Mail\Helper::getTemplate(0, 'colour_sample_first_reminder'); + + if (count($mailData) > 0) { + $mailData = $mailData[0]; + $mailBody = $mailData->mail_body; + $subject = $mailData->mail_subject; + + if (trim($mailData->mail_bcc) != "") { + $mailBcc = explode(",", $mailData->mail_bcc); + } + } + + $body = str_replace("{name}", $sampleRequest->name, $mailBody); + Redshop\Mail\Helper::imgInMail($body); + + if (JFactory::getMailer()->sendMail( + $from, + $fromName, + $sampleRequest->email, + $subject, + $body, + 1, + null, + $mailBcc + )) { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_sample_request')) + ->set($db->qn('reminder_1') . ' = 1') + ->where($db->qn('request_id') . ' = ' . $sampleRequest->request_id); + + $db->setQuery($query)->execute(); + } + } + + /** + * Method for send second reminder of sample request + * + * @param object $sampleRequest Sample request data + * @param string $currentDate Current date + * @param string $from Email from for send mail + * @param string $fromName Name for send mail + * + * @return void + * + * @since 2.0.6 + */ + public static function sendSecondReminder($sampleRequest = null, $currentDate = '', $from = '', $fromName = '') + { + if (empty($sampleRequest) || !is_object($sampleRequest) || $sampleRequest->reminder_2 != 0) { + return; + } + + $currentDate = empty($currentDate) ? JFactory::getDate()->format('Y-m-d') : $currentDate; + $sendDate = date( + "Y-m-d", + $sampleRequest->registerdate + (Redshop::getConfig()->get( + 'COLOUR_SAMPLE_REMAINDER_2' + ) * (60 * 60 * 24)) + ); + + if ($currentDate != $sendDate) { + return; + } + + $from = empty($from) ? JFactory::getConfig()->get('mailfrom') : $from; + $fromName = empty($fromName) ? JFactory::getConfig()->get('fromname') : $fromName; + + $mailBody = ""; + $subject = ""; + $mailBcc = null; + $mailData = Redshop\Mail\Helper::getTemplate(0, 'colour_sample_second_reminder'); + + if (count($mailData) > 0) { + $mailData = $mailData[0]; + $mailBody = $mailData->mail_body; + $subject = $mailData->mail_subject; + + if (trim($mailData->mail_bcc) != "") { + $mailBcc = explode(",", $mailData->mail_bcc); + } + } + + $body = str_replace("{name}", $sampleRequest->name, $mailBody); + Redshop\Mail\Helper::imgInMail($body); + + if (JFactory::getMailer()->sendMail( + $from, + $fromName, + $sampleRequest->email, + $subject, + $body, + 1, + null, + $mailBcc + )) { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_sample_request')) + ->set($db->qn('reminder_2') . ' = 1') + ->where($db->qn('request_id') . ' = ' . $sampleRequest->request_id); + $db->setQuery($query)->execute(); + } + } + + /** + * Method for send third reminder of sample request + * + * @param object $sampleRequest Sample request data + * @param string $currentDate Current date + * @param string $from Email from for send mail + * @param string $fromName Name for send mail + * + * @return void + * + * @since 2.0.6 + */ + public static function sendThirdReminder($sampleRequest = null, $currentDate = '', $from = '', $fromName = '') + { + if (empty($sampleRequest) || !is_object( + $sampleRequest + ) || ($sampleRequest->reminder_3 != 0 && $sampleRequest->reminder_coupon != 0)) { + return; + } + + $currentDate = empty($currentDate) ? JFactory::getDate()->format('Y-m-d') : $currentDate; + $db = JFactory::getDbo(); + + if ($sampleRequest->reminder_3 == 0) { + $sendDate = date( + "Y-m-d", + $sampleRequest->registerdate + (Redshop::getConfig()->get( + 'COLOUR_SAMPLE_REMAINDER_3' + ) * 60 * 60 * 24) + ); + $goodToken = md5(uniqid(mt_rand(), true)); + $token = substr($goodToken, 0, 10); + $startDate = mktime(0, 0, 0, date("m"), date("d"), date("Y")); + $endDate = $startDate + (Redshop::getConfig()->get('COLOUR_COUPON_DURATION') * 23 * 59 * 59); + + if ($currentDate != $sendDate) { + return; + } + + $mailBody = ""; + $subject = ""; + $mailBcc = null; + $mailData = Redshop\Mail\Helper::getTemplate(0, 'colour_sample_third_reminder'); + + if (count($mailData) > 0) { + $mailData = $mailData[0]; + $mailBody = $mailData->mail_body; + $subject = $mailData->mail_subject; + + if (trim($mailData->mail_bcc) != "") { + $mailBcc = explode(",", $mailData->mail_bcc); + } + } + + $body = str_replace("{name}", $sampleRequest->name, $mailBody); + $body = str_replace("{days}", Redshop::getConfig()->get('COLOUR_COUPON_DURATION'), $body); + $body = str_replace("{discount}", Redshop::getConfig()->get('COLOUR_DISCOUNT_PERCENTAGE'), $body); + $body = str_replace("{coupon_code}", $token, $body); + Redshop\Mail\Helper::imgInMail($body); + + $query = $db->getQuery(true) + ->select($db->qn('id')) + ->from($db->qn('#__users')) + ->where($db->qn('email') . ' = ' . $db->quote($sampleRequest->email)); + $uid = $db->setQuery($query)->loadResult(); + + if (!empty($uid)) { + $query->clear() + ->insert($db->qn('#__redshop_coupons')) + ->columns( + $db->qn( + array('code', 'type', 'value', 'start_date', 'end_date', 'effect', 'userid', 'published') + ) + ) + ->values( + $db->quote($token) . ',' . $db->quote(1) . ',' . $db->quote( + Redshop::getConfig()->get('DISCOUNT_PERCENTAGE') + ) . ',' . + $db->quote($startDate) . ',' . $db->quote($endDate) . ',' . $db->quote(1) . ',' . $db->quote( + $uid + ) . ',' . $db->quote(1) + ); + + $db->setQuery($query)->execute(); + } + + if (JFactory::getMailer()->sendMail( + $from, + $fromName, + $sampleRequest->email, + $subject, + $body, + 1, + null, + $mailBcc + )) { + $query->clear() + ->update($db->qn('#__redshop_sample_request')) + ->set($db->qn('reminder_3') . ' = 1') + ->where($db->qn('request_id') . ' = ' . $sampleRequest->request_id); + + $db->setQuery($query)->execute(); + } + } elseif ($sampleRequest->reminder_coupon == 0) { + $sendDate = date("Y-m-d", $sampleRequest->registerdate + (4 * (60 * 60 * 24))); + + if ($currentDate != $sendDate) { + return; + } + + $query = $db->getQuery(true) + ->select($db->qn('id')) + ->from($db->qn('#__users')) + ->where($db->qn('email') . ' = ' . $db->quote($sampleRequest->email)); + $uid = $db->setQuery($query)->loadResult(); + + $query->clear() + ->select($db->qn('id')) + ->from($db->qn('#__redshop_coupons')) + ->where($db->qn('userid') . ' = ' . $db->quote($uid)); + $couponCode = $db->setQuery($query)->loadResult(); + + $mailBody = ""; + $subject = ""; + $mailBcc = null; + $mailData = Redshop\Mail\Helper::getTemplate(0, 'colour_sample_third_reminder'); + + if (count($mailData) > 0) { + $mailData = $mailData[0]; + $mailBody = $mailData->mail_body; + $subject = $mailData->mail_subject; + + if (trim($mailData->mail_bcc) != "") { + $mailBcc = explode(",", $mailData->mail_bcc); + } + } + + $body = str_replace("{name}", $sampleRequest->name, $mailBody); + $body = str_replace("{days}", Redshop::getConfig()->get('COLOUR_COUPON_DURATION'), $body); + $body = str_replace("{discount}", Redshop::getConfig()->get('COLOUR_DISCOUNT_PERCENTAGE'), $body); + $body = str_replace("{coupon_code}", $couponCode, $body); + Redshop\Mail\Helper::imgInMail($body); + + if (JFactory::getMailer()->sendMail( + $from, + $fromName, + $sampleRequest->email, + $subject, + $body, + 1, + null, + $mailBcc + )) { + $query->clear() + ->update($db->qn('#__redshop_sample_request')) + ->set($db->qn('reminder_coupon') . ' = 1') + ->where($db->qn('request_id') . ' = ' . $sampleRequest->request_id); + + $db->setQuery($query)->execute(); + } + } + } } diff --git a/libraries/redshop/helper/shipping.php b/libraries/redshop/helper/shipping.php index 66203f6f7b6..2a5e1c415e6 100644 --- a/libraries/redshop/helper/shipping.php +++ b/libraries/redshop/helper/shipping.php @@ -18,1537 +18,1531 @@ */ class RedshopHelperShipping { - /** - * @var array - * - * @since 2.0.0.3 - */ - protected static $shippingBoxes; - - /** - * @var array - * - * @since 2.0.0.3 - */ - protected static $users = array(); - - /** - * Get Shipping rate for xmlexport - * - * @param array $data Shipping data - * - * @return array - * - * @since 2.0.0.3 - */ - public static function getDefaultShippingXmlExport($data) - { - $orderSubtotal = $data['order_subtotal']; - $user = JFactory::getUser(); - $userId = $user->id; - $db = JFactory::getDbo(); - - $data = Redshop::product((int) $data['product_id']); - $weightTotal = $data->weight; - $volume = $data->product_volume; - $userInfo = self::getShippingAddress($data['users_info_id']); - $productId = $data['product_id']; - $country = ''; - $state = ''; - $isCompany = ''; - $newCwhere = ''; - $whereState = ''; - $whereShopper = ''; - - if ($userInfo) - { - $country = $userInfo->country_code; - $isCompany = $userInfo->is_company; - $userId = $userInfo->user_id; - $state = $userInfo->state_code; - } - - $shopperGroup = RedshopHelperUser::getShopperGroupData($userId); - - if (count($shopperGroup) > 0) - { - $shopperGroupId = $shopperGroup->shopper_group_id; - $whereShopper = ' AND (FIND_IN_SET(' . $db->quote((int) $shopperGroupId) . ', ' - . $db->qn('shipping_rate_on_shopper_group') . ') OR ' - . $db->qn('shipping_rate_on_shopper_group') . ' = "") '; - } - - if ($country) - { - $whereCountry = '(FIND_IN_SET(' . $db->quote($country) . ', ' - . $db->qn('shipping_rate_country') . ') OR ' - . $db->qn('shipping_rate_country') . ' = ' . $db->quote(0) . ' OR ' - . $db->qn('shipping_rate_country') . ' = "")'; - } - else - { - $whereCountry = '(FIND_IN_SET(' . $db->quote(Redshop::getConfig()->get('DEFAULT_SHIPPING_COUNTRY')) . ', ' - . $db->qn('shipping_rate_country') . ') OR ' - . $db->qn('shipping_rate_country') . ' = ' . $db->quote(0) . ' OR ' - . $db->qn('shipping_rate_country') . ' = "")'; - } - - if ($state) - { - $whereState = ' AND (FIND_IN_SET(' . $db->quote($state) . ', ' - . $db->qn('shipping_rate_state') . ') OR ' - . $db->qn('shipping_rate_state') . ' = ' . $db->quote(0) . ' OR ' - . $db->qn('shipping_rate_state') . ' = "")'; - } - - if (!$isCompany) - { - $isWhere = " AND ( " . $db->qn('company_only') . " = 2 OR " . $db->qn('company_only') . " = 0) "; - } - else - { - $isWhere = " AND ( " . $db->qn('company_only') . " = 1 OR " . $db->qn('company_only') . " = 0) "; - } - - $shippingArr = self::getShopperGroupDefaultShipping(); - - if (empty($shippingArr)) - { - $pWhere = 'AND ( FIND_IN_SET(' . $db->quote((int) $productId) . ', ' . $db->qn('shipping_rate_on_product') . ') )'; - $newPwhere = str_replace("AND (", "OR (", $pWhere); - - $sql = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') . " AS sr " - . "LEFT JOIN " . $db->qn('#__extensions') . " AS s ON " . $db->qn('sr.shipping_class') . " = " . $db->qn('s.element') - . " WHERE " . $db->qn('s.folder') . " = " . $db->quote('redshop_shipping') . " AND " - . $whereCountry . $isWhere . " + /** + * @var array + * + * @since 2.0.0.3 + */ + protected static $shippingBoxes; + + /** + * @var array + * + * @since 2.0.0.3 + */ + protected static $users = array(); + + /** + * Get Shipping rate for xmlexport + * + * @param array $data Shipping data + * + * @return array + * + * @since 2.0.0.3 + */ + public static function getDefaultShippingXmlExport($data) + { + $orderSubtotal = $data['order_subtotal']; + $user = JFactory::getUser(); + $userId = $user->id; + $db = JFactory::getDbo(); + + $data = Redshop::product((int)$data['product_id']); + $weightTotal = $data->weight; + $volume = $data->product_volume; + $userInfo = self::getShippingAddress($data['users_info_id']); + $productId = $data['product_id']; + $country = ''; + $state = ''; + $isCompany = ''; + $newCwhere = ''; + $whereState = ''; + $whereShopper = ''; + + if ($userInfo) { + $country = $userInfo->country_code; + $isCompany = $userInfo->is_company; + $userId = $userInfo->user_id; + $state = $userInfo->state_code; + } + + $shopperGroup = RedshopHelperUser::getShopperGroupData($userId); + + if (count($shopperGroup) > 0) { + $shopperGroupId = $shopperGroup->shopper_group_id; + $whereShopper = ' AND (FIND_IN_SET(' . $db->quote((int)$shopperGroupId) . ', ' + . $db->qn('shipping_rate_on_shopper_group') . ') OR ' + . $db->qn('shipping_rate_on_shopper_group') . ' = "") '; + } + + if ($country) { + $whereCountry = '(FIND_IN_SET(' . $db->quote($country) . ', ' + . $db->qn('shipping_rate_country') . ') OR ' + . $db->qn('shipping_rate_country') . ' = ' . $db->quote(0) . ' OR ' + . $db->qn('shipping_rate_country') . ' = "")'; + } else { + $whereCountry = '(FIND_IN_SET(' . $db->quote(Redshop::getConfig()->get('DEFAULT_SHIPPING_COUNTRY')) . ', ' + . $db->qn('shipping_rate_country') . ') OR ' + . $db->qn('shipping_rate_country') . ' = ' . $db->quote(0) . ' OR ' + . $db->qn('shipping_rate_country') . ' = "")'; + } + + if ($state) { + $whereState = ' AND (FIND_IN_SET(' . $db->quote($state) . ', ' + . $db->qn('shipping_rate_state') . ') OR ' + . $db->qn('shipping_rate_state') . ' = ' . $db->quote(0) . ' OR ' + . $db->qn('shipping_rate_state') . ' = "")'; + } + + if (!$isCompany) { + $isWhere = " AND ( " . $db->qn('company_only') . " = 2 OR " . $db->qn('company_only') . " = 0) "; + } else { + $isWhere = " AND ( " . $db->qn('company_only') . " = 1 OR " . $db->qn('company_only') . " = 0) "; + } + + $shippingArr = self::getShopperGroupDefaultShipping(); + + if (empty($shippingArr)) { + $pWhere = 'AND ( FIND_IN_SET(' . $db->quote((int)$productId) . ', ' . $db->qn( + 'shipping_rate_on_product' + ) . ') )'; + $newPwhere = str_replace("AND (", "OR (", $pWhere); + + $sql = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') . " AS sr " + . "LEFT JOIN " . $db->qn('#__extensions') . " AS s ON " . $db->qn( + 'sr.shipping_class' + ) . " = " . $db->qn('s.element') + . " WHERE " . $db->qn('s.folder') . " = " . $db->quote('redshop_shipping') . " AND " + . $whereCountry . $isWhere . " AND ((" . $db->qn('shipping_rate_volume_start') . " <= " . $db->quote($volume) . " AND " - . $db->qn('shipping_rate_volume_end') . " >= " - . $db->quote($volume) . ") OR (" . $db->qn('shipping_rate_volume_end') . " = 0) ) - AND ((" . $db->qn('shipping_rate_ordertotal_start') . " <= " . $db->quote($orderSubtotal) . " AND " - . $db->qn('shipping_rate_ordertotal_end') . " >= " - . $db->quote($orderSubtotal) . ") OR (" . $db->qn('shipping_rate_ordertotal_end') . " = 0)) + . $db->qn('shipping_rate_volume_end') . " >= " + . $db->quote($volume) . ") OR (" . $db->qn('shipping_rate_volume_end') . " = 0) ) + AND ((" . $db->qn('shipping_rate_ordertotal_start') . " <= " . $db->quote( + $orderSubtotal + ) . " AND " + . $db->qn('shipping_rate_ordertotal_end') . " >= " + . $db->quote($orderSubtotal) . ") OR (" . $db->qn('shipping_rate_ordertotal_end') . " = 0)) AND ((" . $db->qn('shipping_rate_weight_start') . " <= " . $db->quote($weightTotal) . " AND " - . $db->qn('shipping_rate_weight_end') . " >= " - . $db->quote($weightTotal) . ") OR (" . $db->qn('shipping_rate_weight_end') . " = 0))" - . $pWhere . $whereState . $whereShopper . " + . $db->qn('shipping_rate_weight_end') . " >= " + . $db->quote($weightTotal) . ") OR (" . $db->qn('shipping_rate_weight_end') . " = 0))" + . $pWhere . $whereState . $whereShopper . " ORDER BY " . $db->qn('sr.shipping_rate_priority') . " LIMIT 0,1"; - $shippingRate = $db->setQuery($sql)->loadObject(); + $shippingRate = $db->setQuery($sql)->loadObject(); - if (!$shippingRate) - { - $query = $db->getQuery(true) - ->select($db->qn('category_id')) - ->from($db->qn('#__redshop_product_category_xref')) - ->where($db->qn('product_id') . ' = ' . $db->quote((int) $productId)); + if (!$shippingRate) { + $query = $db->getQuery(true) + ->select($db->qn('category_id')) + ->from($db->qn('#__redshop_product_category_xref')) + ->where($db->qn('product_id') . ' = ' . $db->quote((int)$productId)); - $categoryData = $db->setQuery($query)->loadObjectList(); + $categoryData = $db->setQuery($query)->loadObjectList(); - if ($categoryData) - { - $where = 'AND ( '; + if ($categoryData) { + $where = 'AND ( '; - foreach ($categoryData as $c => $categoryDatum) - { - $where .= " FIND_IN_SET(" . $db->quote((int) $categoryDatum->category_id) . "," - . $db->qn('shipping_rate_on_category') . ") "; + foreach ($categoryData as $c => $categoryDatum) { + $where .= " FIND_IN_SET(" . $db->quote((int)$categoryDatum->category_id) . "," + . $db->qn('shipping_rate_on_category') . ") "; - if ($c != count($categoryData) - 1) - { - $where .= " OR "; - } - } + if ($c != count($categoryData) - 1) { + $where .= " OR "; + } + } - $where .= ")"; - $newCwhere = str_replace("AND (", "OR (", $where); - $sql = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') . " AS sr + $where .= ")"; + $newCwhere = str_replace("AND (", "OR (", $where); + $sql = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') . " AS sr LEFT JOIN " . $db->qn('#__extensions') . " AS s ON " . $db->qn('sr.shipping_class') . " = " . $db->qn('s.element') . " WHERE " . $db->qn('s.folder') . " = " . $db->quote('redshop_shipping') . " AND " - . $whereCountry . $whereShopper . $isWhere . " - AND ((" . $db->qn('shipping_rate_volume_start') . " <= " . $db->quote($volume) . " AND " - . $db->qn('shipping_rate_volume_end') . " >= " - . $db->quote($volume) . ") OR (" . $db->qn('shipping_rate_volume_end') . " = 0) ) - AND ((" . $db->qn('shipping_rate_ordertotal_start') . " <= " . $db->quote($orderSubtotal) . " AND " - . $db->qn('shipping_rate_ordertotal_end') . " >= " - . $db->quote($orderSubtotal) . ") OR (" . $db->qn('shipping_rate_ordertotal_end') . " = 0)) - AND ((" . $db->qn('shipping_rate_weight_start') . " <= " . $db->quote($weightTotal) . " AND " - . $db->qn('shipping_rate_weight_end') . " >= " - . $db->quote($weightTotal) . " OR (" . $db->qn('shipping_rate_weight_end') . " = 0))" - . $where . $whereState . " + . $whereCountry . $whereShopper . $isWhere . " + AND ((" . $db->qn('shipping_rate_volume_start') . " <= " . $db->quote( + $volume + ) . " AND " + . $db->qn('shipping_rate_volume_end') . " >= " + . $db->quote($volume) . ") OR (" . $db->qn('shipping_rate_volume_end') . " = 0) ) + AND ((" . $db->qn('shipping_rate_ordertotal_start') . " <= " . $db->quote( + $orderSubtotal + ) . " AND " + . $db->qn('shipping_rate_ordertotal_end') . " >= " + . $db->quote($orderSubtotal) . ") OR (" . $db->qn('shipping_rate_ordertotal_end') . " = 0)) + AND ((" . $db->qn('shipping_rate_weight_start') . " <= " . $db->quote( + $weightTotal + ) . " AND " + . $db->qn('shipping_rate_weight_end') . " >= " + . $db->quote($weightTotal) . " OR (" . $db->qn('shipping_rate_weight_end') . " = 0))" + . $where . $whereState . " ORDER BY " . $db->qn('sr.shipping_rate_priority') . " LIMIT 0,1"; - $shippingRate = $db->setQuery($sql)->loadObject(); - } - } + $shippingRate = $db->setQuery($sql)->loadObject(); + } + } - if (!$shippingRate) - { - $sql = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') . " AS sr + if (!$shippingRate) { + $sql = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') . " AS sr LEFT JOIN " . $db->qn('#__extensions') . " AS s ON " . $db->qn('sr.shipping_class') . " = " . $db->qn('s.element') . " WHERE " . $db->qn('s.folder') . " = " . $db->quote('redshop_shipping') . " AND " - . $whereCountry . $whereShopper . $isWhere . $whereState . " + . $whereCountry . $whereShopper . $isWhere . $whereState . " AND ((" . $db->qn('shipping_rate_volume_start') . " <= " . $db->quote($volume) . " AND " - . $db->qn('shipping_rate_volume_end') . " >= " - . $db->quote($volume) . ") OR (" - . $db->qn('shipping_rate_volume_end') . " = 0) ) - AND ((" . $db->qn('shipping_rate_ordertotal_start') . " <= " . $db->quote($orderSubtotal) . " AND " - . $db->qn('shipping_rate_ordertotal_end') . " >= " - . $db->quote($orderSubtotal) . ") OR (" . $db->qn('shipping_rate_ordertotal_end') . " = 0)) + . $db->qn('shipping_rate_volume_end') . " >= " + . $db->quote($volume) . ") OR (" + . $db->qn('shipping_rate_volume_end') . " = 0) ) + AND ((" . $db->qn('shipping_rate_ordertotal_start') . " <= " . $db->quote( + $orderSubtotal + ) . " AND " + . $db->qn('shipping_rate_ordertotal_end') . " >= " + . $db->quote($orderSubtotal) . ") OR (" . $db->qn('shipping_rate_ordertotal_end') . " = 0)) AND ((" . $db->qn('shipping_rate_weight_start') . " <= " . $db->quote($weightTotal) . " AND " - . $db->qn('shipping_rate_weight_end') . " >= " - . $db->quote($weightTotal) . ") OR (" . $db->qn('shipping_rate_weight_end') . " = 0)) + . $db->qn('shipping_rate_weight_end') . " >= " + . $db->quote($weightTotal) . ") OR (" . $db->qn('shipping_rate_weight_end') . " = 0)) AND (" . $db->qn('shipping_rate_on_product') . " = '' " . $newPwhere . ") AND (" - . $db->qn('shipping_rate_on_category') . " = '' " . $newCwhere . ") + . $db->qn('shipping_rate_on_category') . " = '' " . $newCwhere . ") ORDER BY " . $db->qn('sr.shipping_rate_priority') . " LIMIT 0,1"; - $shippingRate = $db->setQuery($sql)->loadObject(); - } - - $total = 0; - $shippingVat = 0; - - if ($shippingRate) - { - $total = $shippingRate->shipping_rate_value; - - if ($shippingRate->apply_vat == 1) - { - $result = self::getShippingVatRates($shippingRate->shipping_tax_group_id, $data); - $addVat = RedshopHelperCart::taxExemptAddToCart($userId); - - if (!empty($result) && $addVat) - { - if ($result->tax_rate > 0) - { - $shippingVat = $total * $result->tax_rate; - $total = $shippingVat + $total; - } - } - } - } - - $shipArr['shipping_rate'] = $total; - $shipArr['shipping_vat'] = $shippingVat; - - return $shipArr; - } - else - { - return $shippingArr; - } - } - - /** - * Return only one shipping rate on cart page. This function is called by ajax - * - * @return string - * - * @since 2.0.0.3 - * - * @throws Exception - * - * @deprecated 2.1.0 Redshop\Shipping\Rate::calculate() - * @see Redshop\Shipping\Rate::calculate - */ - public static function getShippingRateCalc() - { - return Redshop\Shipping\Rate::calculate(); - } - - /** - * Encrypt Shipping - * - * @param string $strMessage String to encrypt - * - * @return string Encrypt shipping rate - * - * @since 2.0.0.3 - * - * @deprecated 2.1.0 Redshop\Shipping\Rate::encrypt - * @see Redshop\Shipping\Rate::encrypt - */ - public static function encryptShipping($strMessage) - { - return Redshop\Shipping\Rate::encrypt(array($strMessage)); - } - - /** - * Decrypt Shipping - * - * @param string $strMessage String to decrypt - * - * @return array Decrypt shipping rate - * - * @since 2.0.0.3 - * - * @deprecated 2.1.0 Redshop\Shipping\Rate::decrypt - * @see Redshop\Shipping\Rate::decrypt - */ - public static function decryptShipping($strMessage) - { - return Redshop\Shipping\Rate::decrypt($strMessage); - } - - /** - * Get shipping address - * - * @param int $userInfoId User info id - * - * @return object - * - * @since 2.0.0.3 - */ - public static function getShippingAddress($userInfoId) - { - if (!$userInfoId) - { - return null; - } - - if (!array_key_exists($userInfoId, static::$users)) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_users_info')) - ->where($db->qn('users_info_id') . ' = ' . $db->quote((int) $userInfoId)); - - static::$users[$userInfoId] = $db->setQuery($query)->loadObject(); - } - - return static::$users[$userInfoId]; - } - - /** - * Get shipping method class - * - * @param string $shippingClass Shipping class - * - * @return object - * - * @since 2.0.0.3 - */ - public static function getShippingMethodByClass($shippingClass = '') - { - $folder = strtolower('redshop_shipping'); - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__extensions')) - ->where('LOWER(' . $db->qn('folder') . ')' . ' = ' . $db->quote($folder)) - ->where($db->qn('element') . ' = ' . $db->quote($shippingClass)); - - return $db->setQuery($query)->loadObject(); - } - - /** - * Get shipping method by id - * - * @param integer $id Shipping id - * - * @return object - * - * @since 2.0.0.3 - */ - public static function getShippingMethodById($id = 0) - { - $folder = strtolower('redshop_shipping'); - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->select($db->qn('extension_id', 'id')) - ->from($db->qn('#__extensions')) - ->where('LOWER(' . $db->qn('folder') . ') = ' . $db->quote($folder)) - ->where($db->qn('extension_id') . ' = ' . $db->quote((int) $id)); - - return $db->setQuery($query)->loadObject(); - } - - /** - * Get shipping rates - * - * @param string $shippingClass Shipping class - * - * @return array - * - * @since 2.0.0.3 - */ - public static function getShippingRates($shippingClass) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_shipping_rate')) - ->where($db->qn('shipping_class') . ' = ' . $db->quote($shippingClass)); - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * Apply VAT on shipping rate - * - * @param object $shippingRate Shipping Rate information - * @param array $data Shipping Rate user information from cart or checkout selection. - * - * @return float Shipping Rate - * - * @since 2.0.0.3 - * - * @deprecated 2.1.0 - * @see Redshop\Shipping\Rate::applyVat - * - * @throws InvalidArgumentException - */ - public static function applyVatOnShippingRate($shippingRate, $data) - { - return Redshop\Shipping\Rate::applyVat($shippingRate, $data); - } - - /** - * List shipping rates - * - * @param object $shippingClass Shipping class - * @param integer $usersInfoId User info id - * @param array $data Shipping data - * - * @return array Shipping Rates - * - * @since 2.0.0.3 - * - * @throws Exception - */ - public static function listShippingRates($shippingClass, $usersInfoId, &$data) - { - $app = JFactory::getApplication(); - $isAdmin = $app->isAdmin(); - $orderSubtotal = $data['order_subtotal']; - $totalDimention = self::getCartItemDimension(); - $weightTotal = $totalDimention['totalweight']; - $volume = $totalDimention['totalvolume']; - $session = JFactory::getSession(); - $db = JFactory::getDbo(); - $cart = $session->get('cart'); - $idx = (int) ($cart ['idx'] ?? 0); - - // Product volume based shipping - $volumeShipping = self::getProductVolumeShipping(); - $whereShippingVolume = ""; - - if (count($volumeShipping) > 0) - { - $whereShippingVolume .= " AND ( "; - - for ($g = 0, $gn = count($volumeShipping); $g < $gn; $g++) - { - $length = $volumeShipping[$g]['length']; - $width = $volumeShipping[$g]['width']; - $height = $volumeShipping[$g]['height']; - - if ($g != 0) - { - $whereShippingVolume .= " OR "; - } - - $whereShippingVolume .= "( + $shippingRate = $db->setQuery($sql)->loadObject(); + } + + $total = 0; + $shippingVat = 0; + + if ($shippingRate) { + $total = $shippingRate->shipping_rate_value; + + if ($shippingRate->apply_vat == 1) { + $result = self::getShippingVatRates($shippingRate->shipping_tax_group_id, $data); + $addVat = RedshopHelperCart::taxExemptAddToCart($userId); + + if (!empty($result) && $addVat) { + if ($result->tax_rate > 0) { + $shippingVat = $total * $result->tax_rate; + $total = $shippingVat + $total; + } + } + } + } + + $shipArr['shipping_rate'] = $total; + $shipArr['shipping_vat'] = $shippingVat; + + return $shipArr; + } else { + return $shippingArr; + } + } + + /** + * Get shipping address + * + * @param int $userInfoId User info id + * + * @return object + * + * @since 2.0.0.3 + */ + public static function getShippingAddress($userInfoId) + { + if (!$userInfoId) { + return null; + } + + if (!array_key_exists($userInfoId, static::$users)) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_users_info')) + ->where($db->qn('users_info_id') . ' = ' . $db->quote((int)$userInfoId)); + + static::$users[$userInfoId] = $db->setQuery($query)->loadObject(); + } + + return static::$users[$userInfoId]; + } + + /** + * Get shopper group default shipping + * + * @param int $userId User id + * + * @return array + * + * @since 2.0.0.3 + */ + public static function getShopperGroupDefaultShipping($userId = 0) + { + $shippingArr = array(); + $user = JFactory::getUser(); + + // FOR OFFLINE ORDER + if ($userId == 0) { + $userId = $user->id; + } + + if (!$userId) { + return array(); + } + + $result = RedshopHelperUser::getUserInformation($userId); + + if (!empty($result) && $result->default_shipping == 1) { + $shippingArr['shipping_rate'] = 0; + $shippingArr['shipping_vat'] = 0; + + $row = self::getShippingVatRates(0); + + if (!empty($row)) { + $total = 0; + $shippingVat = 0; + + if ($row->tax_rate > 0) { + $shippingVat = $result->default_shipping_rate * $row->tax_rate; + $total += $shippingVat + $result->default_shipping_rate; + $shippingVat .= '
    '; + } + + $shippingArr['shipping_vat'] = $shippingVat; + $shippingArr['shipping_rate'] = $total; + + return $shippingArr; + } + + $shippingArr['shipping_rate'] = $result->default_shipping_rate; + + return $shippingArr; + } + + return $shippingArr; + } + + /** + * Get shipping vat rates based on either billing or shipping user + * + * @param int $shippingTaxGroupId Shipping Default Tax Gorup ID + * @param array $data Shipping User Information array + * + * @return object Shipping VAT rates + * + * @since 2.0.0.3 + */ + public static function getShippingVatRates($shippingTaxGroupId, $data = array()) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + if (!empty($data) && ((!empty($data['user_id']) && $data['user_id'] > 0) || $data['users_info_id'] > 0)) { + if ('BT' == Redshop::getConfig()->get('CALCULATE_VAT_ON')) { + $userData = RedshopHelperUser::getUserInformation($data['user_id'], 'BT', 0, true, true); + } else { + $userData = RedshopHelperUser::getUserInformation(0, '', $data['users_info_id'], false); + } + + if (count($userData) > 0) { + if (!$userData->country_code) { + $userData->country_code = Redshop::getConfig()->get('DEFAULT_VAT_COUNTRY'); + } + + if (!$userData->state_code) { + $userData->state_code = Redshop::getConfig()->get('DEFAULT_VAT_STATE'); + } + + /* + * VAT_BASED_ON = 0 // webshop mode + * VAT_BASED_ON = 1 // customer mode + * VAT_BASED_ON = 2 // EU mode + */ + if (0 == Redshop::getConfig()->getInt('VAT_BASED_ON')) { + $userData->country_code = Redshop::getConfig()->get('DEFAULT_VAT_COUNTRY'); + $userData->state_code = Redshop::getConfig()->get('DEFAULT_VAT_STATE'); + } + } + + if (Redshop::getConfig()->get('VAT_BASED_ON') == 2) { + $query->where($db->qn('tr.is_eu_country') . " = 1"); + } + } else { + $session = JFactory::getSession(); + $auth = $session->get('auth'); + $usersInfoId = $auth['users_info_id']; + $userData = new stdClass; + $userData->country_code = Redshop::getConfig()->get('DEFAULT_VAT_COUNTRY'); + $userData->state_code = Redshop::getConfig()->get('DEFAULT_VAT_STATE'); + + if ($usersInfoId && (Redshop::getConfig()->get('REGISTER_METHOD') == 1 || Redshop::getConfig()->get( + 'REGISTER_METHOD' + ) == 2) + && (Redshop::getConfig()->get('VAT_BASED_ON') == 2 || Redshop::getConfig()->get('VAT_BASED_ON') == 1) + ) { + $userQuery = $db->getQuery(true) + ->select($db->qn('country_code')) + ->select($db->qn('state_code')) + ->from($db->qn('#__redshop_users_info', 'u')) + ->leftJoin( + $db->qn('#__redshop_shopper_group', 'sh') + . ' ON ' . $db->qn('sh.shopper_group_id') . ' = ' . $db->qn('u.shopper_group_id') + ) + ->where($db->qn('u.users_info_id') . ' = ' . $db->quote((int)$usersInfoId)) + ->order($db->qn('u.users_info_id') . ' ASC'); + $userData = $db->setQuery($userQuery)->loadObject(); + } + } + + if ($shippingTaxGroupId == 0) { + $query->where( + $db->qn('tr.tax_group_id') . ' = ' . $db->quote((int)Redshop::getConfig()->get('DEFAULT_VAT_GROUP')) + ); + } elseif ($shippingTaxGroupId > 0) { + $query->leftJoin( + $db->qn('#__redshop_shipping_rate', 's') + . ' ON ' . $db->qn('tr.tax_group_id') . ' = ' . $db->qn('s.shipping_tax_group_id') + ) + ->where($db->qn('s.shipping_tax_group_id') . ' = ' . $db->quote((int)$shippingTaxGroupId)); + } else { + $query->where( + $db->qn('tr.tax_group_id') . ' = ' . $db->quote((int)Redshop::getConfig()->get('DEFAULT_VAT_GROUP')) + ); + } + + $query->select('tr.*') + ->from($db->qn('#__redshop_tax_rate', 'tr')) + ->where( + $db->qn('tr.tax_country') . ' = ' . $db->quote($userData->country_code) . ' OR' . $db->qn( + 'tr.tax_country' + ) . ' = ""' + ) + ->where( + $db->qn('tr.tax_rate') . ' = ' . $db->quote($userData->state_code) . ' OR ' . $db->qn( + 'tr.tax_rate' + ) . ' = ""' + ) + ->order($db->qn('tr.tax_rate') . 'DESC'); + + return $db->setQuery($query)->loadObject(); + } + + /** + * Return only one shipping rate on cart page. This function is called by ajax + * + * @return string + * + * @throws Exception + * + * @since 2.0.0.3 + * + * @deprecated 2.1.0 Redshop\Shipping\Rate::calculate() + * @see Redshop\Shipping\Rate::calculate + */ + public static function getShippingRateCalc() + { + return Redshop\Shipping\Rate::calculate(); + } + + /** + * Encrypt Shipping + * + * @param string $strMessage String to encrypt + * + * @return string Encrypt shipping rate + * + * @since 2.0.0.3 + * + * @deprecated 2.1.0 Redshop\Shipping\Rate::encrypt + * @see Redshop\Shipping\Rate::encrypt + */ + public static function encryptShipping($strMessage) + { + return Redshop\Shipping\Rate::encrypt(array($strMessage)); + } + + /** + * Decrypt Shipping + * + * @param string $strMessage String to decrypt + * + * @return array Decrypt shipping rate + * + * @since 2.0.0.3 + * + * @deprecated 2.1.0 Redshop\Shipping\Rate::decrypt + * @see Redshop\Shipping\Rate::decrypt + */ + public static function decryptShipping($strMessage) + { + return Redshop\Shipping\Rate::decrypt($strMessage); + } + + /** + * Get shipping method class + * + * @param string $shippingClass Shipping class + * + * @return object + * + * @since 2.0.0.3 + */ + public static function getShippingMethodByClass($shippingClass = '') + { + $folder = strtolower('redshop_shipping'); + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__extensions')) + ->where('LOWER(' . $db->qn('folder') . ')' . ' = ' . $db->quote($folder)) + ->where($db->qn('element') . ' = ' . $db->quote($shippingClass)); + + return $db->setQuery($query)->loadObject(); + } + + /** + * Get shipping method by id + * + * @param integer $id Shipping id + * + * @return object + * + * @since 2.0.0.3 + */ + public static function getShippingMethodById($id = 0) + { + $folder = strtolower('redshop_shipping'); + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->select($db->qn('extension_id', 'id')) + ->from($db->qn('#__extensions')) + ->where('LOWER(' . $db->qn('folder') . ') = ' . $db->quote($folder)) + ->where($db->qn('extension_id') . ' = ' . $db->quote((int)$id)); + + return $db->setQuery($query)->loadObject(); + } + + /** + * Get shipping rates + * + * @param string $shippingClass Shipping class + * + * @return array + * + * @since 2.0.0.3 + */ + public static function getShippingRates($shippingClass) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_shipping_rate')) + ->where($db->qn('shipping_class') . ' = ' . $db->quote($shippingClass)); + + return $db->setQuery($query)->loadObjectList(); + } + + /** + * Apply VAT on shipping rate + * + * @param object $shippingRate Shipping Rate information + * @param array $data Shipping Rate user information from cart or checkout selection. + * + * @return float Shipping Rate + * + * @throws InvalidArgumentException + * @deprecated 2.1.0 + * @see Redshop\Shipping\Rate::applyVat + * + * @since 2.0.0.3 + * + */ + public static function applyVatOnShippingRate($shippingRate, $data) + { + return Redshop\Shipping\Rate::applyVat($shippingRate, $data); + } + + /** + * List shipping rates + * + * @param object $shippingClass Shipping class + * @param integer $usersInfoId User info id + * @param array $data Shipping data + * + * @return array Shipping Rates + * + * @throws Exception + * @since 2.0.0.3 + * + */ + public static function listShippingRates($shippingClass, $usersInfoId, &$data) + { + $app = JFactory::getApplication(); + $isAdmin = $app->isAdmin(); + $orderSubtotal = $data['order_subtotal']; + $totalDimention = self::getCartItemDimension(); + $weightTotal = $totalDimention['totalweight']; + $volume = $totalDimention['totalvolume']; + $session = JFactory::getSession(); + $db = JFactory::getDbo(); + $cart = $session->get('cart'); + $idx = (int)($cart ['idx'] ?? 0); + + // Product volume based shipping + $volumeShipping = self::getProductVolumeShipping(); + $whereShippingVolume = ""; + + if (count($volumeShipping) > 0) { + $whereShippingVolume .= " AND ( "; + + for ($g = 0, $gn = count($volumeShipping); $g < $gn; $g++) { + $length = $volumeShipping[$g]['length']; + $width = $volumeShipping[$g]['width']; + $height = $volumeShipping[$g]['height']; + + if ($g != 0) { + $whereShippingVolume .= " OR "; + } + + $whereShippingVolume .= "( ((" . $db->quote($length) . " BETWEEN " . $db->qn('shipping_rate_length_start') - . " AND " . $db->qn('shipping_rate_length_end') . ") + . " AND " . $db->qn('shipping_rate_length_end') . ") OR (" . $db->qn('shipping_rate_length_start') . " = 0 AND " - . $db->qn('shipping_rate_length_end') . " = 0)) + . $db->qn('shipping_rate_length_end') . " = 0)) AND ((" . $db->quote($width) . " BETWEEN " . $db->qn('shipping_rate_width_start') - . " AND " . $db->qn('shipping_rate_width_end') . ") + . " AND " . $db->qn('shipping_rate_width_end') . ") OR (" . $db->qn('shipping_rate_width_start') . " = 0 AND " - . $db->qn('shipping_rate_width_end') . " = 0)) + . $db->qn('shipping_rate_width_end') . " = 0)) AND ((" . $db->quote($height) . " BETWEEN " . $db->qn('shipping_rate_height_start') - . " AND " . $db->qn('shipping_rate_height_end') . ") + . " AND " . $db->qn('shipping_rate_height_end') . ") OR (" . $db->qn('shipping_rate_height_start') . " = 0 AND " - . $db->qn('shipping_rate_height_end') . "= 0)) + . $db->qn('shipping_rate_height_end') . "= 0)) ) "; - } - - $whereShippingVolume .= " ) "; - } - - $userInfo = self::getShippingAddress($usersInfoId); - $country = ''; - $state = isset($data['state_code']) ? $data['state_code'] : ''; - $isCompany = false; - $shippingRate = array(); - $zip = ''; - $whereState = ''; - $whereShopper = ''; - - if ($userInfo) - { - $country = $userInfo->country_code; - $state = $userInfo->state_code; - $zip = $userInfo->zipcode; - $isCompany = (bool) $userInfo->is_company; - - $shopperGroup = RedshopHelperUser::getShopperGroupData($userInfo->user_id); - - if (!empty($shopperGroup)) - { - $shopperGroupId = $shopperGroup->shopper_group_id; - $whereShopper = " AND (FIND_IN_SET(" . (int) $shopperGroupId . ", " . $db->qn('shipping_rate_on_shopper_group') . ") + } + + $whereShippingVolume .= " ) "; + } + + $userInfo = self::getShippingAddress($usersInfoId); + $country = ''; + $state = isset($data['state_code']) ? $data['state_code'] : ''; + $isCompany = false; + $shippingRate = array(); + $zip = ''; + $whereState = ''; + $whereShopper = ''; + + if ($userInfo) { + $country = $userInfo->country_code; + $state = $userInfo->state_code; + $zip = $userInfo->zipcode; + $isCompany = (bool)$userInfo->is_company; + + $shopperGroup = RedshopHelperUser::getShopperGroupData($userInfo->user_id); + + if (!empty($shopperGroup)) { + $shopperGroupId = $shopperGroup->shopper_group_id; + $whereShopper = " AND (FIND_IN_SET(" . (int)$shopperGroupId . ", " . $db->qn( + 'shipping_rate_on_shopper_group' + ) . ") OR " . $db->qn('shipping_rate_on_shopper_group') . "= '') "; - } - } - elseif (empty($userInfo) && Redshop::getConfig()->get('ONESTEP_CHECKOUT_ENABLE')) - { - if (!empty($data['post']['anonymous'])) - { - $anonymousUser = $data['post']['anonymous']; - $isCompany = ($anonymousUser['billing_type'] == 'company'); - - $country = $anonymousUser['BT']['country_code']; - $state = $anonymousUser['BT']['state_code']; - $zip = $anonymousUser['BT']['zip_code']; - - if ($anonymousUser['bill_is_ship'] == 0) - { - $country = $anonymousUser['ST']['country_code_ST']; - $state = $anonymousUser['ST']['state_code_ST']; - $zip = $anonymousUser['ST']['zip_code_ST']; - } - - switch ($anonymousUser['billing_type']) - { - case 'private': - $shopperGroupId = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_PRIVATE'); - break; - case 'company': - $shopperGroupId = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_COMPANY'); - break; - default: - $shopperGroupId = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_UNREGISTERED'); - break; - } - - $whereShopper = " AND (FIND_IN_SET(" . (int) $shopperGroupId . ", " . $db->qn('shipping_rate_on_shopper_group') . ") + } + } elseif (empty($userInfo) && Redshop::getConfig()->get('ONESTEP_CHECKOUT_ENABLE')) { + if (!empty($data['post']['anonymous'])) { + $anonymousUser = $data['post']['anonymous']; + $isCompany = ($anonymousUser['billing_type'] == 'company'); + + $country = $anonymousUser['BT']['country_code']; + $state = $anonymousUser['BT']['state_code']; + $zip = $anonymousUser['BT']['zip_code']; + + if ($anonymousUser['bill_is_ship'] == 0) { + $country = $anonymousUser['ST']['country_code_ST']; + $state = $anonymousUser['ST']['state_code_ST']; + $zip = $anonymousUser['ST']['zip_code_ST']; + } + + switch ($anonymousUser['billing_type']) { + case 'private': + $shopperGroupId = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_PRIVATE'); + break; + case 'company': + $shopperGroupId = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_COMPANY'); + break; + default: + $shopperGroupId = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_UNREGISTERED'); + break; + } + + $whereShopper = " AND (FIND_IN_SET(" . (int)$shopperGroupId . ", " . $db->qn( + 'shipping_rate_on_shopper_group' + ) . ") OR " . $db->qn('shipping_rate_on_shopper_group') . "= '') "; - } - } - - if ($isCompany === false) - { - $where = " AND ( " . $db->qn('company_only') . " = 2 OR " . $db->qn('company_only') . " = 0) "; - } - else - { - $where = " AND ( " . $db->qn('company_only') . " = 1 OR " . $db->qn('company_only') . " = 0) "; - } - - if ($country) - { - $whereCountry = "AND (FIND_IN_SET(" . $db->quote($country) . ", " . $db->qn('shipping_rate_country') . ")" - . " OR " . $db->qn('shipping_rate_country') . " = " . $db->quote(0) - . " OR " . $db->qn('shipping_rate_country') . " = " . $db->quote('') - . " )"; - } - else - { - $whereCountry = "AND (FIND_IN_SET(" . $db->quote(Redshop::getConfig()->get('DEFAULT_SHIPPING_COUNTRY')) . ", " . $db->qn('shipping_rate_country') . ")" - . " OR " . $db->qn('shipping_rate_country') . " = " . $db->quote(0) - . " OR " . $db->qn('shipping_rate_country') . " = " . $db->quote('') - . " )"; - } - - if ($state) - { - $whereState = " AND (FIND_IN_SET(" . $db->quote($state) . ", " . $db->qn('shipping_rate_state') . ") OR " - . $db->qn('shipping_rate_state') . " = " . $db->quote(0) . " OR " . $db->qn('shipping_rate_state') . " = '')"; - } - - $pWhere = ""; - $cWhere = ""; - - if ($idx) - { - $pWhere = 'OR ( '; - - for ($i = 0; $i < $idx; $i++) - { - $productId = $cart[$i]['product_id']; - $pWhere .= "FIND_IN_SET(" . $db->quote((int) $productId) . ", " . $db->qn('shipping_rate_on_product') . ")"; - - if ($i != $idx - 1) - { - $pWhere .= " OR "; - } - } - - $pWhere .= ")"; - } - - if (!$shippingRate) - { - for ($i = 0; $i < $idx; $i++) - { - $productId = $cart[$i]['product_id']; - $query = $db->getQuery(true) - ->select($db->qn('category_id')) - ->from($db->qn('#__redshop_product_category_xref')) - ->where($db->qn('product_id') . ' = ' . $db->quote((int) $productId)); - - $categoryData = $db->setQuery($query)->loadColumn(); - - if (!empty($categoryData)) - { - foreach ($categoryData as $categoryDatum) - { - $acWhere[] = " FIND_IN_SET(" . $db->quote((int) $categoryDatum) . "," . $db->qn('shipping_rate_on_category') . ") "; - } - } - } - - if (isset($acWhere) && count($acWhere) > 0) - { - $acWhere = implode(' OR ', $acWhere); - $cWhere = ' OR (' . $acWhere . ')'; - } - } - - $numbers = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " " - ); - - if (!$shippingRate) - { - $zipCond = ""; - $zip = trim($zip); - - if (strlen(str_replace($numbers, '', $zip)) == 0 && $zip != "") - { - $zipCond = " AND ( ( " . $db->qn('shipping_rate_zip_start') . " <= " . $db->quote($zip) . " AND " - . $db->qn('shipping_rate_zip_end') . " >= " . $db->quote($zip) . " ) - OR (" . $db->qn('shipping_rate_zip_start') . " = " . $db->quote(0) . " AND " . $db->qn('shipping_rate_zip_end') . " = " . $db->quote(0) . ") - OR (" . $db->qn('shipping_rate_zip_start') . " = '' AND " . $db->qn('shipping_rate_zip_end') . " = '') ) "; - } - - $sql = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') . " WHERE " . $db->qn('shipping_class') . " = " - . $db->quote($shippingClass) - . $whereCountry - . $whereState - . $whereShopper - . $zipCond . " + } + } + + if ($isCompany === false) { + $where = " AND ( " . $db->qn('company_only') . " = 2 OR " . $db->qn('company_only') . " = 0) "; + } else { + $where = " AND ( " . $db->qn('company_only') . " = 1 OR " . $db->qn('company_only') . " = 0) "; + } + + if ($country) { + $whereCountry = "AND (FIND_IN_SET(" . $db->quote($country) . ", " . $db->qn('shipping_rate_country') . ")" + . " OR " . $db->qn('shipping_rate_country') . " = " . $db->quote(0) + . " OR " . $db->qn('shipping_rate_country') . " = " . $db->quote('') + . " )"; + } else { + $whereCountry = "AND (FIND_IN_SET(" . $db->quote( + Redshop::getConfig()->get('DEFAULT_SHIPPING_COUNTRY') + ) . ", " . $db->qn('shipping_rate_country') . ")" + . " OR " . $db->qn('shipping_rate_country') . " = " . $db->quote(0) + . " OR " . $db->qn('shipping_rate_country') . " = " . $db->quote('') + . " )"; + } + + if ($state) { + $whereState = " AND (FIND_IN_SET(" . $db->quote($state) . ", " . $db->qn('shipping_rate_state') . ") OR " + . $db->qn('shipping_rate_state') . " = " . $db->quote(0) . " OR " . $db->qn( + 'shipping_rate_state' + ) . " = '')"; + } + + $pWhere = ""; + $cWhere = ""; + + if ($idx) { + $pWhere = 'OR ( '; + + for ($i = 0; $i < $idx; $i++) { + $productId = $cart[$i]['product_id']; + $pWhere .= "FIND_IN_SET(" . $db->quote((int)$productId) . ", " . $db->qn( + 'shipping_rate_on_product' + ) . ")"; + + if ($i != $idx - 1) { + $pWhere .= " OR "; + } + } + + $pWhere .= ")"; + } + + if (!$shippingRate) { + for ($i = 0; $i < $idx; $i++) { + $productId = $cart[$i]['product_id']; + $query = $db->getQuery(true) + ->select($db->qn('category_id')) + ->from($db->qn('#__redshop_product_category_xref')) + ->where($db->qn('product_id') . ' = ' . $db->quote((int)$productId)); + + $categoryData = $db->setQuery($query)->loadColumn(); + + if (!empty($categoryData)) { + foreach ($categoryData as $categoryDatum) { + $acWhere[] = " FIND_IN_SET(" . $db->quote((int)$categoryDatum) . "," . $db->qn( + 'shipping_rate_on_category' + ) . ") "; + } + } + } + + if (isset($acWhere) && count($acWhere) > 0) { + $acWhere = implode(' OR ', $acWhere); + $cWhere = ' OR (' . $acWhere . ')'; + } + } + + $numbers = array( + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "0", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + " " + ); + + if (!$shippingRate) { + $zipCond = ""; + $zip = trim($zip); + + if (strlen(str_replace($numbers, '', $zip)) == 0 && $zip != "") { + $zipCond = " AND ( ( " . $db->qn('shipping_rate_zip_start') . " <= " . $db->quote($zip) . " AND " + . $db->qn('shipping_rate_zip_end') . " >= " . $db->quote($zip) . " ) + OR (" . $db->qn('shipping_rate_zip_start') . " = " . $db->quote(0) . " AND " . $db->qn( + 'shipping_rate_zip_end' + ) . " = " . $db->quote(0) . ") + OR (" . $db->qn('shipping_rate_zip_start') . " = '' AND " . $db->qn( + 'shipping_rate_zip_end' + ) . " = '') ) "; + } + + $sql = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') . " WHERE " . $db->qn( + 'shipping_class' + ) . " = " + . $db->quote($shippingClass) + . $whereCountry + . $whereState + . $whereShopper + . $zipCond . " AND (( " . $db->quote($volume) . " BETWEEN " . $db->qn('shipping_rate_volume_start') - . " AND " . $db->qn('shipping_rate_volume_end') . ") OR ( " . $db->qn('shipping_rate_volume_end') . " = 0) ) + . " AND " . $db->qn('shipping_rate_volume_end') . ") OR ( " . $db->qn('shipping_rate_volume_end') . " = 0) ) AND (( " . $db->quote($orderSubtotal) . " BETWEEN " . $db->qn('shipping_rate_ordertotal_start') - . " AND " . $db->qn('shipping_rate_ordertotal_end') . ") OR (" . $db->qn('shipping_rate_ordertotal_end') . " = 0)) + . " AND " . $db->qn('shipping_rate_ordertotal_end') . ") OR (" . $db->qn( + 'shipping_rate_ordertotal_end' + ) . " = 0)) AND (( " . $db->quote($weightTotal) . " BETWEEN " . $db->qn('shipping_rate_weight_start') - . " AND " . $db->qn('shipping_rate_weight_end') . ") OR (" - . $db->qn('shipping_rate_weight_end') . " = 0)) " . $whereShippingVolume . " + . " AND " . $db->qn('shipping_rate_weight_end') . ") OR (" + . $db->qn('shipping_rate_weight_end') . " = 0)) " . $whereShippingVolume . " AND (" . $db->qn('shipping_rate_on_product') . " = '' " . $pWhere . ") AND (" - . $db->qn('shipping_rate_on_category') . " = '' " . $cWhere . ")" . $where . " + . $db->qn('shipping_rate_on_category') . " = '' " . $cWhere . ")" . $where . " ORDER BY " . $db->qn('shipping_rate_priority'); - $shippingRate = $db->setQuery($sql)->loadObjectList(); - } - - /* - * Rearrange shipping rates array - * after filtering zipcode - * check character condition for zip code.. - */ - $shipping = array(); - - if (strlen(str_replace($numbers, '', $zip)) != 0 && $zip != "") - { - $k = 0; - $userZipLen = (self::strposa($zip, $numbers) !== false) ? (self::strposa($zip, $numbers)) : strlen($zip); - - for ($i = 0, $countShippingRate = count($shippingRate); $i < $countShippingRate; $i++) - { - $flag = false; - $tmpShippingRate = $shippingRate[$i]; - $start = $tmpShippingRate->shipping_rate_zip_start; - $end = $tmpShippingRate->shipping_rate_zip_end; - - if (trim($start) == "" && trim($end) == "") - { - $shipping[$k++] = $tmpShippingRate; - } - - else - { - $startZipLen = (self::strposa($start, $numbers) !== false) ? (self::strposa($start, $numbers)) : strlen($start); - $endZipLen = (self::strposa($end, $numbers) !== false) ? (self::strposa($end, $numbers)) : strlen($end); - - if ($startZipLen != $endZipLen || $userZipLen != $endZipLen) - { - continue; - } - - $len = $userZipLen; - - for ($j = 0; $j < $len; $j++) - { - if (ord(strtoupper($zip[$j])) >= ord(strtoupper($start[$j])) - && ord(strtoupper($zip[$j])) <= ord(strtoupper($end[$j])) - ) - { - $flag = true; - } - else - { - $flag = false; - break; - } - } - - if ($flag) - { - $shipping[$k++] = $tmpShippingRate; - } - } - } - - if ($isAdmin == false) - { - $shipping = Redshop\Shipping\Rate::filterRatesByPriority($shipping); - } - - return $shipping; - } - else - { - if ($isAdmin == false) - { - $shippingRate = Redshop\Shipping\Rate::filterRatesByPriority($shippingRate); - } - - return $shippingRate; - } - } - - /** - * Get shipping vat rates based on either billing or shipping user - * - * @param int $shippingTaxGroupId Shipping Default Tax Gorup ID - * @param array $data Shipping User Information array - * - * @return object Shipping VAT rates - * - * @since 2.0.0.3 - */ - public static function getShippingVatRates($shippingTaxGroupId, $data = array()) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - if (!empty($data) && ((!empty($data['user_id']) && $data['user_id'] > 0) || $data['users_info_id'] > 0)) - { - if ('BT' == Redshop::getConfig()->get('CALCULATE_VAT_ON')) - { - $userData = RedshopHelperUser::getUserInformation($data['user_id'], 'BT', 0, true, true); - } - else - { - $userData = RedshopHelperUser::getUserInformation(0, '', $data['users_info_id'], false); - } - - if (count($userData) > 0) - { - if (!$userData->country_code) - { - $userData->country_code = Redshop::getConfig()->get('DEFAULT_VAT_COUNTRY'); - } - - if (!$userData->state_code) - { - $userData->state_code = Redshop::getConfig()->get('DEFAULT_VAT_STATE'); - } - - /* - * VAT_BASED_ON = 0 // webshop mode - * VAT_BASED_ON = 1 // customer mode - * VAT_BASED_ON = 2 // EU mode - */ - if (0 == Redshop::getConfig()->getInt('VAT_BASED_ON')) - { - $userData->country_code = Redshop::getConfig()->get('DEFAULT_VAT_COUNTRY'); - $userData->state_code = Redshop::getConfig()->get('DEFAULT_VAT_STATE'); - } - } - - if (Redshop::getConfig()->get('VAT_BASED_ON') == 2) - { - $query->where($db->qn('tr.is_eu_country') . " = 1"); - } - } - else - { - $session = JFactory::getSession(); - $auth = $session->get('auth'); - $usersInfoId = $auth['users_info_id']; - $userData = new stdClass; - $userData->country_code = Redshop::getConfig()->get('DEFAULT_VAT_COUNTRY'); - $userData->state_code = Redshop::getConfig()->get('DEFAULT_VAT_STATE'); - - if ($usersInfoId && (Redshop::getConfig()->get('REGISTER_METHOD') == 1 || Redshop::getConfig()->get('REGISTER_METHOD') == 2) - && (Redshop::getConfig()->get('VAT_BASED_ON') == 2 || Redshop::getConfig()->get('VAT_BASED_ON') == 1) - ) - { - $userQuery = $db->getQuery(true) - ->select($db->qn('country_code')) - ->select($db->qn('state_code')) - ->from($db->qn('#__redshop_users_info', 'u')) - ->leftJoin( - $db->qn('#__redshop_shopper_group', 'sh') - . ' ON ' . $db->qn('sh.shopper_group_id') . ' = ' . $db->qn('u.shopper_group_id') - ) - ->where($db->qn('u.users_info_id') . ' = ' . $db->quote((int) $usersInfoId)) - ->order($db->qn('u.users_info_id') . ' ASC'); - $userData = $db->setQuery($userQuery)->loadObject(); - } - } - - if ($shippingTaxGroupId == 0) - { - $query->where($db->qn('tr.tax_group_id') . ' = ' . $db->quote((int) Redshop::getConfig()->get('DEFAULT_VAT_GROUP'))); - } - elseif ($shippingTaxGroupId > 0) - { - $query->leftJoin( - $db->qn('#__redshop_shipping_rate', 's') - . ' ON ' . $db->qn('tr.tax_group_id') . ' = ' . $db->qn('s.shipping_tax_group_id') - ) - ->where($db->qn('s.shipping_tax_group_id') . ' = ' . $db->quote((int) $shippingTaxGroupId)); - } - else - { - $query->where($db->qn('tr.tax_group_id') . ' = ' . $db->quote((int) Redshop::getConfig()->get('DEFAULT_VAT_GROUP'))); - } - - $query->select('tr.*') - ->from($db->qn('#__redshop_tax_rate', 'tr')) - ->where($db->qn('tr.tax_country') . ' = ' . $db->quote($userData->country_code) . ' OR' . $db->qn('tr.tax_country') . ' = ""') - ->where($db->qn('tr.tax_rate') . ' = ' . $db->quote($userData->state_code) . ' OR ' . $db->qn('tr.tax_rate') . ' = ""') - ->order($db->qn('tr.tax_rate') . 'DESC'); - - return $db->setQuery($query)->loadObject(); - } - - /** - * Get shopper group default shipping - * - * @param int $userId User id - * - * @return array - * - * @since 2.0.0.3 - */ - public static function getShopperGroupDefaultShipping($userId = 0) - { - $shippingArr = array(); - $user = JFactory::getUser(); - - // FOR OFFLINE ORDER - if ($userId == 0) - { - $userId = $user->id; - } - - if (!$userId) - { - return array(); - } - - $result = RedshopHelperUser::getUserInformation($userId); - - if (!empty($result) && $result->default_shipping == 1) - { - $shippingArr['shipping_rate'] = 0; - $shippingArr['shipping_vat'] = 0; - - $row = self::getShippingVatRates(0); - - if (!empty($row)) - { - $total = 0; - $shippingVat = 0; - - if ($row->tax_rate > 0) - { - $shippingVat = $result->default_shipping_rate * $row->tax_rate; - $total += $shippingVat + $result->default_shipping_rate; - $shippingVat .= '
    '; - } - - $shippingArr['shipping_vat'] = $shippingVat; - $shippingArr['shipping_rate'] = $total; - - return $shippingArr; - } - - $shippingArr['shipping_rate'] = $result->default_shipping_rate; - - return $shippingArr; - } - - return $shippingArr; - } - - /** - * Find first number position - * - * @param string $haystack string to find - * @param array $needles array to find - * @param int $offset position - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function strposa($haystack, $needles = array(), $offset = 0) - { - $chr = array(); - - foreach ($needles as $needle) - { - if (strpos($haystack, $needle, $offset) !== false) - { - $chr[] = strpos($haystack, $needle, $offset); - } - } - - if (empty($chr)) - { - return false; - } - - return min($chr); - } - - /** - * Filter Shipping rates based on their priority - * Only show Higher priority rates (In [1,2,3,4] take 1 as a high priority) - * Rates with same priority will shown as radio button list in checkout - * - * @param array $shippingRates Array shipping rates - * - * @return array - * - * @deprecated 2.1.0 - * @see Redshop\Shipping\Rate::filterRatesByPriority - */ - public static function filterRatesByPriority($shippingRates) - { - return Redshop\Shipping\Rate::filterRatesByPriority($shippingRates); - } - - /** - * Function to get product volume shipping - * - * @return array $cases , 3cases of shipping - * - * @since 2.0.0.3 - */ - public static function getProductVolumeShipping() - { - $session = \JFactory::getSession(); - $cart = $session->get('cart'); - $idx = (int) ($cart['idx'] ?? 0); - - $length = []; - $width = []; - $height = []; - $lengthQ = []; - $widthQ = []; - $heightQ = []; - $lMax = 0; - $lTotal = 0; - $wMax = 0; - $wTotal = 0; - $hMax = 0; - $hTotal = 0; - - // Cart loop - for ($i = 0; $i < $idx; $i++) - { - if (isset($cart[$i]['giftcard_id']) && $cart[$i]['giftcard_id']) - { - continue; - } - - $data = \Redshop::product((int) $cart[$i]['product_id']); - $length[$i] = $data->product_length; - $width[$i] = $data->product_width; - $height[$i] = $data->product_height; - $tmpArr = array($length[$i], $width[$i], $height[$i]); - $switch = array_search(min($tmpArr), $tmpArr); - - switch ($switch) - { - case 0: - $lengthQ[$i] = $data->product_length * $cart[$i]['quantity']; - $widthQ[$i] = $data->product_width; - $heightQ[$i] = $data->product_height; - break; - case 1: - $lengthQ[$i] = $data->product_length; - $widthQ[$i] = $data->product_width * $cart[$i]['quantity']; - $heightQ[$i] = $data->product_height; - break; - case 2: - $lengthQ[$i] = $data->product_length; - $widthQ[$i] = $data->product_width; - $heightQ[$i] = $data->product_height * $cart[$i]['quantity']; - break; - } - } - - // Get maximum length - if (count($length) > 0) - { - $lMax = max($length); - } - - // Get total length - if (count($lengthQ) > 0) - { - $lTotal = array_sum($lengthQ); - } - - // Get maximum width - if (count($width) > 0) - { - $wMax = max($width); - } - - // Get total width - if (count($widthQ) > 0) - { - $wTotal = array_sum($widthQ); - } - - // Get maximum height - if (count($height) > 0) - { - $hMax = max($height); - } - - // Get total height - if (count($heightQ) > 0) - { - $hTotal = array_sum($heightQ); - } - - // 3 cases are available for shipping boxes - $cases = array(); - $cases[0]['length'] = $lMax; - $cases[0]['width'] = $wMax; - $cases[0]['height'] = $hTotal; - - $cases[1]['length'] = $lMax; - $cases[1]['width'] = $wTotal; - $cases[1]['height'] = $hMax; - - $cases[2]['length'] = $lTotal; - $cases[2]['width'] = $wMax; - $cases[2]['height'] = $hMax; - - return $cases; - } - - /** - * Function to get cart item dimension - * - * @return array - * - * @since 2.0.0.3 - */ - public static function getCartItemDimension() - { - $session = JFactory::getSession(); - $cart = $session->get('cart'); - $idx = $cart['idx'] ?? 0; - $idx = (int) $idx; - - $totalQnt = 0; - $totalWeight = 0; - $totalVolume = 0; - $totalLength = 0; - $totalHeight = 0; - $totalWidth = 0; - - for ($i = 0; $i < $idx; $i++) - { - if (isset($cart[$i]['giftcard_id']) && $cart[$i]['giftcard_id']) - { - continue; - } - - $data = Redshop::product((int) $cart[$i]['product_id']); - $accWeight = 0; - - if (isset($cart[$i]['cart_accessory']) && count($cart[$i]['cart_accessory']) > 0) - { - foreach ($cart[$i]['cart_accessory'] as $index => $cartAccessory) - { - $accId = $cartAccessory['accessory_id']; - $accQty = 1; - - if (isset($cartAccessory['accessory_quantity'])) - { - $accQty = $cartAccessory['accessory_quantity']; - } - - if ($accData = \Redshop\Product\Product::getProductById($accId)) - { - $accWeight += ($accData->weight * $accQty); - } - } - } - - $totalQnt += $cart[$i]['quantity']; - $totalWeight += (($data->weight * $cart[$i]['quantity']) + $accWeight); - $totalVolume += ($data->product_volume * $cart[$i]['quantity']); - $totalLength += ($data->product_length * $cart[$i]['quantity']); - $totalHeight += ($data->product_height * $cart[$i]['quantity']); - $totalWidth += ($data->product_width * $cart[$i]['quantity']); - } - - $ret = array( - "totalquantity" => $totalQnt, - "totalweight" => $totalWeight, - "totalvolume" => $totalVolume, - "totallength" => $totalLength, - "totalheight" => $totalHeight, - "totalwidth" => $totalWidth - ); - - return $ret; - } - - /** - * Get available shipping boxes according to cart items - * - * @return array - * - * @since 2.0.0.3 - */ - public static function getShippingBox() - { - if (is_null(static::$shippingBoxes)) - { - $volumesShipping = self::getProductVolumeShipping(); - $db = JFactory::getDbo(); - $whereShippingVolume = ""; - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_shipping_boxes')) - ->where($db->qn('published') . ' = 1') - ->order($db->qn('shipping_box_priority') . ' ASC'); - - if (!empty($volumesShipping)) - { - $whereShippingVolume .= '( '; - $index = 0; - - foreach ($volumesShipping as $volumeShipping) - { - $length = $volumeShipping['length']; - $width = $volumeShipping['width']; - $height = $volumeShipping['height']; - - if ($index != 0) - { - $whereShippingVolume .= " OR "; - } - - $whereShippingVolume .= " ( " . $db->qn('shipping_box_length') . " >= " . $length . " AND " - . $db->qn('shipping_box_width') . " >= " . $width . " AND " . $db->qn('shipping_box_height') . " >= " . $height . ") "; - - $index++; - } - - $whereShippingVolume .= " ) "; - - $query->where($whereShippingVolume); - } - - static::$shippingBoxes = $db->setQuery($query)->loadObjectList(); - } - - return static::$shippingBoxes; - } - - /** - * Get selected shipping BOX dimensions - * - * @param int $boxId Shipping Box id - * - * @return array box dimensions - * - * @since 2.0.0.3 - */ - public static function getBoxDimensions($boxId = 0) - { - $db = JFactory::getDbo(); - $whereShippingBoxes = array(); - - if ($boxId) - { - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_shipping_boxes')) - ->where($db->qn('published') . ' = 1') - ->where($db->qn('shipping_box_id') . ' = ' . $db->quote((int) $boxId)); - - $boxDetail = $db->setQuery($query)->loadObject(); - - if (count($boxDetail) > 0) - { - $whereShippingBoxes['box_length'] = $boxDetail->shipping_box_length; - $whereShippingBoxes['box_width'] = $boxDetail->shipping_box_width; - $whereShippingBoxes['box_height'] = $boxDetail->shipping_box_height; - } - } - - return $whereShippingBoxes; - } - - /** - * Get Shipping rate error - * - * @param array $data Shipping rate data - * - * @return string Error text - * - * @since 2.0.0.3 - */ - public static function getShippingRateError(&$data) - { - $bool = self::isCartDimensionMatch($data); - - if ($bool) - { - $bool = self::isUserInfoMatch($data); - - if ($bool) - { - $bool = self::isProductDetailMatch(); - - if ($bool) - { - return ''; - } - - return JText::_("COM_REDSHOP_PRODUCT_DETAIL_NOT_MATCH"); - } - - return JText::_("COM_REDSHOP_USER_INFORMATION_NOT_MATCH"); - } - - return JText::_("COM_REDSHOP_CART_DIMENTION_NOT_MATCH"); - } - - /** - * Check cart dimension is matched - * - * @param array $data Cart data - * - * @return boolean - * - * @since 2.0.0.3 - */ - public static function isCartDimensionMatch(&$data) - { - $orderSubtotal = $data['order_subtotal']; - $db = JFactory::getDbo(); - $totalDimention = self::getCartItemDimension(); - $weightTotal = $totalDimention['totalweight']; - $volume = $totalDimention['totalvolume']; - - // Product volume based shipping - $volumeShipping = self::getProductVolumeShipping(); - $whereShippingVolume = ""; - - if (count($volumeShipping) > 0) - { - $whereShippingVolume .= " AND ( "; - - for ($g = 0, $gn = count($volumeShipping); $g < $gn; $g++) - { - $length = $volumeShipping[$g]['length']; - $width = $volumeShipping[$g]['width']; - $height = $volumeShipping[$g]['height']; - - if ($g != 0) - { - $whereShippingVolume .= " OR "; - } - - $whereShippingVolume .= "( + $shippingRate = $db->setQuery($sql)->loadObjectList(); + } + + /* + * Rearrange shipping rates array + * after filtering zipcode + * check character condition for zip code.. + */ + $shipping = array(); + + if (strlen(str_replace($numbers, '', $zip)) != 0 && $zip != "") { + $k = 0; + $userZipLen = (self::strposa($zip, $numbers) !== false) ? (self::strposa($zip, $numbers)) : strlen($zip); + + for ($i = 0, $countShippingRate = count($shippingRate); $i < $countShippingRate; $i++) { + $flag = false; + $tmpShippingRate = $shippingRate[$i]; + $start = $tmpShippingRate->shipping_rate_zip_start; + $end = $tmpShippingRate->shipping_rate_zip_end; + + if (trim($start) == "" && trim($end) == "") { + $shipping[$k++] = $tmpShippingRate; + } else { + $startZipLen = (self::strposa($start, $numbers) !== false) ? (self::strposa( + $start, + $numbers + )) : strlen($start); + $endZipLen = (self::strposa($end, $numbers) !== false) ? (self::strposa($end, $numbers)) : strlen( + $end + ); + + if ($startZipLen != $endZipLen || $userZipLen != $endZipLen) { + continue; + } + + $len = $userZipLen; + + for ($j = 0; $j < $len; $j++) { + if (ord(strtoupper($zip[$j])) >= ord(strtoupper($start[$j])) + && ord(strtoupper($zip[$j])) <= ord(strtoupper($end[$j])) + ) { + $flag = true; + } else { + $flag = false; + break; + } + } + + if ($flag) { + $shipping[$k++] = $tmpShippingRate; + } + } + } + + if ($isAdmin == false) { + $shipping = Redshop\Shipping\Rate::filterRatesByPriority($shipping); + } + + return $shipping; + } else { + if ($isAdmin == false) { + $shippingRate = Redshop\Shipping\Rate::filterRatesByPriority($shippingRate); + } + + return $shippingRate; + } + } + + /** + * Function to get cart item dimension + * + * @return array + * + * @since 2.0.0.3 + */ + public static function getCartItemDimension() + { + $session = JFactory::getSession(); + $cart = $session->get('cart'); + $idx = $cart['idx'] ?? 0; + $idx = (int)$idx; + + $totalQnt = 0; + $totalWeight = 0; + $totalVolume = 0; + $totalLength = 0; + $totalHeight = 0; + $totalWidth = 0; + + for ($i = 0; $i < $idx; $i++) { + if (isset($cart[$i]['giftcard_id']) && $cart[$i]['giftcard_id']) { + continue; + } + + $data = Redshop::product((int)$cart[$i]['product_id']); + $accWeight = 0; + + if (isset($cart[$i]['cart_accessory']) && count($cart[$i]['cart_accessory']) > 0) { + foreach ($cart[$i]['cart_accessory'] as $index => $cartAccessory) { + $accId = $cartAccessory['accessory_id']; + $accQty = 1; + + if (isset($cartAccessory['accessory_quantity'])) { + $accQty = $cartAccessory['accessory_quantity']; + } + + if ($accData = \Redshop\Product\Product::getProductById($accId)) { + $accWeight += ($accData->weight * $accQty); + } + } + } + + $totalQnt += $cart[$i]['quantity']; + $totalWeight += (($data->weight * $cart[$i]['quantity']) + $accWeight); + $totalVolume += ($data->product_volume * $cart[$i]['quantity']); + $totalLength += ($data->product_length * $cart[$i]['quantity']); + $totalHeight += ($data->product_height * $cart[$i]['quantity']); + $totalWidth += ($data->product_width * $cart[$i]['quantity']); + } + + $ret = array( + "totalquantity" => $totalQnt, + "totalweight" => $totalWeight, + "totalvolume" => $totalVolume, + "totallength" => $totalLength, + "totalheight" => $totalHeight, + "totalwidth" => $totalWidth + ); + + return $ret; + } + + /** + * Function to get product volume shipping + * + * @return array $cases , 3cases of shipping + * + * @since 2.0.0.3 + */ + public static function getProductVolumeShipping() + { + $session = \JFactory::getSession(); + $cart = $session->get('cart'); + $idx = (int)($cart['idx'] ?? 0); + + $length = []; + $width = []; + $height = []; + $lengthQ = []; + $widthQ = []; + $heightQ = []; + $lMax = 0; + $lTotal = 0; + $wMax = 0; + $wTotal = 0; + $hMax = 0; + $hTotal = 0; + + // Cart loop + for ($i = 0; $i < $idx; $i++) { + if (isset($cart[$i]['giftcard_id']) && $cart[$i]['giftcard_id']) { + continue; + } + + $data = \Redshop::product((int)$cart[$i]['product_id']); + $length[$i] = $data->product_length; + $width[$i] = $data->product_width; + $height[$i] = $data->product_height; + $tmpArr = array($length[$i], $width[$i], $height[$i]); + $switch = array_search(min($tmpArr), $tmpArr); + + switch ($switch) { + case 0: + $lengthQ[$i] = $data->product_length * $cart[$i]['quantity']; + $widthQ[$i] = $data->product_width; + $heightQ[$i] = $data->product_height; + break; + case 1: + $lengthQ[$i] = $data->product_length; + $widthQ[$i] = $data->product_width * $cart[$i]['quantity']; + $heightQ[$i] = $data->product_height; + break; + case 2: + $lengthQ[$i] = $data->product_length; + $widthQ[$i] = $data->product_width; + $heightQ[$i] = $data->product_height * $cart[$i]['quantity']; + break; + } + } + + // Get maximum length + if (count($length) > 0) { + $lMax = max($length); + } + + // Get total length + if (count($lengthQ) > 0) { + $lTotal = array_sum($lengthQ); + } + + // Get maximum width + if (count($width) > 0) { + $wMax = max($width); + } + + // Get total width + if (count($widthQ) > 0) { + $wTotal = array_sum($widthQ); + } + + // Get maximum height + if (count($height) > 0) { + $hMax = max($height); + } + + // Get total height + if (count($heightQ) > 0) { + $hTotal = array_sum($heightQ); + } + + // 3 cases are available for shipping boxes + $cases = array(); + $cases[0]['length'] = $lMax; + $cases[0]['width'] = $wMax; + $cases[0]['height'] = $hTotal; + + $cases[1]['length'] = $lMax; + $cases[1]['width'] = $wTotal; + $cases[1]['height'] = $hMax; + + $cases[2]['length'] = $lTotal; + $cases[2]['width'] = $wMax; + $cases[2]['height'] = $hMax; + + return $cases; + } + + /** + * Find first number position + * + * @param string $haystack string to find + * @param array $needles array to find + * @param int $offset position + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function strposa($haystack, $needles = array(), $offset = 0) + { + $chr = array(); + + foreach ($needles as $needle) { + if (strpos($haystack, $needle, $offset) !== false) { + $chr[] = strpos($haystack, $needle, $offset); + } + } + + if (empty($chr)) { + return false; + } + + return min($chr); + } + + /** + * Filter Shipping rates based on their priority + * Only show Higher priority rates (In [1,2,3,4] take 1 as a high priority) + * Rates with same priority will shown as radio button list in checkout + * + * @param array $shippingRates Array shipping rates + * + * @return array + * + * @deprecated 2.1.0 + * @see Redshop\Shipping\Rate::filterRatesByPriority + */ + public static function filterRatesByPriority($shippingRates) + { + return Redshop\Shipping\Rate::filterRatesByPriority($shippingRates); + } + + /** + * Get available shipping boxes according to cart items + * + * @return array + * + * @since 2.0.0.3 + */ + public static function getShippingBox() + { + if (is_null(static::$shippingBoxes)) { + $volumesShipping = self::getProductVolumeShipping(); + $db = JFactory::getDbo(); + $whereShippingVolume = ""; + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_shipping_boxes')) + ->where($db->qn('published') . ' = 1') + ->order($db->qn('shipping_box_priority') . ' ASC'); + + if (!empty($volumesShipping)) { + $whereShippingVolume .= '( '; + $index = 0; + + foreach ($volumesShipping as $volumeShipping) { + $length = $volumeShipping['length']; + $width = $volumeShipping['width']; + $height = $volumeShipping['height']; + + if ($index != 0) { + $whereShippingVolume .= " OR "; + } + + $whereShippingVolume .= " ( " . $db->qn('shipping_box_length') . " >= " . $length . " AND " + . $db->qn('shipping_box_width') . " >= " . $width . " AND " . $db->qn( + 'shipping_box_height' + ) . " >= " . $height . ") "; + + $index++; + } + + $whereShippingVolume .= " ) "; + + $query->where($whereShippingVolume); + } + + static::$shippingBoxes = $db->setQuery($query)->loadObjectList(); + } + + return static::$shippingBoxes; + } + + /** + * Get selected shipping BOX dimensions + * + * @param int $boxId Shipping Box id + * + * @return array box dimensions + * + * @since 2.0.0.3 + */ + public static function getBoxDimensions($boxId = 0) + { + $db = JFactory::getDbo(); + $whereShippingBoxes = array(); + + if ($boxId) { + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_shipping_boxes')) + ->where($db->qn('published') . ' = 1') + ->where($db->qn('shipping_box_id') . ' = ' . $db->quote((int)$boxId)); + + $boxDetail = $db->setQuery($query)->loadObject(); + + if (count($boxDetail) > 0) { + $whereShippingBoxes['box_length'] = $boxDetail->shipping_box_length; + $whereShippingBoxes['box_width'] = $boxDetail->shipping_box_width; + $whereShippingBoxes['box_height'] = $boxDetail->shipping_box_height; + } + } + + return $whereShippingBoxes; + } + + /** + * Get Shipping rate error + * + * @param array $data Shipping rate data + * + * @return string Error text + * + * @since 2.0.0.3 + */ + public static function getShippingRateError(&$data) + { + $bool = self::isCartDimensionMatch($data); + + if ($bool) { + $bool = self::isUserInfoMatch($data); + + if ($bool) { + $bool = self::isProductDetailMatch(); + + if ($bool) { + return ''; + } + + return JText::_("COM_REDSHOP_PRODUCT_DETAIL_NOT_MATCH"); + } + + return JText::_("COM_REDSHOP_USER_INFORMATION_NOT_MATCH"); + } + + return JText::_("COM_REDSHOP_CART_DIMENTION_NOT_MATCH"); + } + + /** + * Check cart dimension is matched + * + * @param array $data Cart data + * + * @return boolean + * + * @since 2.0.0.3 + */ + public static function isCartDimensionMatch(&$data) + { + $orderSubtotal = $data['order_subtotal']; + $db = JFactory::getDbo(); + $totalDimention = self::getCartItemDimension(); + $weightTotal = $totalDimention['totalweight']; + $volume = $totalDimention['totalvolume']; + + // Product volume based shipping + $volumeShipping = self::getProductVolumeShipping(); + $whereShippingVolume = ""; + + if (count($volumeShipping) > 0) { + $whereShippingVolume .= " AND ( "; + + for ($g = 0, $gn = count($volumeShipping); $g < $gn; $g++) { + $length = $volumeShipping[$g]['length']; + $width = $volumeShipping[$g]['width']; + $height = $volumeShipping[$g]['height']; + + if ($g != 0) { + $whereShippingVolume .= " OR "; + } + + $whereShippingVolume .= "( ( (" . $db->quote($length) . " BETWEEN " . $db->qn('shipping_rate_length_start') - . " AND " . $db->qn('shipping_rate_length_end') . ") + . " AND " . $db->qn('shipping_rate_length_end') . ") OR (" . $db->qn('shipping_rate_length_start') . " = 0 AND " - . $db->qn('shipping_rate_length_end') . " = 0)) + . $db->qn('shipping_rate_length_end') . " = 0)) AND ((" . $db->quote($width) . " BETWEEN " . $db->qn('shipping_rate_width_start') - . " AND " . $db->qn('shipping_rate_width_end') . ") + . " AND " . $db->qn('shipping_rate_width_end') . ") OR (" . $db->qn('shipping_rate_width_start') . " = 0 AND " - . $db->qn('shipping_rate_width_end') . " = 0)) + . $db->qn('shipping_rate_width_end') . " = 0)) AND ((" . $db->quote($height) . " BETWEEN " . $db->qn('shipping_rate_height_start') - . " AND " . $db->qn('shipping_rate_height_end') . ") + . " AND " . $db->qn('shipping_rate_height_end') . ") OR (" . $db->qn('shipping_rate_height_start') . " = 0 AND " - . $db->qn('shipping_rate_height_end') . " = 0)) + . $db->qn('shipping_rate_height_end') . " = 0)) ) "; - } - - $whereShippingVolume .= " ) "; - } - - $query = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') - . "WHERE (" . $db->qn('shipping_class') . " = " . $db->quote('default_shipping') . " OR " - . $db->qn('shipping_class') . " = " . $db->quote('shipper') . ") " - . "AND ((" . $db->quote($volume) . " BETWEEN " . $db->qn('shipping_rate_volume_start') - . " AND " . $db->qn('shipping_rate_volume_end') . ") OR (" . $db->qn('shipping_rate_volume_end') . " = 0) ) " - . "AND ((" . $db->quote($orderSubtotal) . " BETWEEN " . $db->qn('shipping_rate_ordertotal_start') - . " AND " . $db->qn('shipping_rate_ordertotal_end') . ") OR (" . $db->qn('shipping_rate_ordertotal_end') . " = 0)) " - . "AND ((" . $db->quote($weightTotal) . " BETWEEN " . $db->qn('shipping_rate_weight_start') - . " AND " . $db->qn('shipping_rate_weight_end') . ") OR (" . $db->qn('shipping_rate_weight_end') . " = 0)) " - . $whereShippingVolume - . " ORDER BY " . $db->qn('shipping_rate_priority'); - - $shippingRate = $db->setQuery($query)->loadObjectList(); - - if (count($shippingRate) > 0) - { - return true; - } - - return false; - } - - /** - * Check user info is matched - * - * @param array &$data Cart data - * - * @return boolean - * - * @since 2.0.0.3 - */ - public static function isUserInfoMatch(&$data) - { - if (!isset($data['users_info_id']) || $data['users_info_id'] == 0) - { - return false; - } - - $db = JFactory::getDbo(); - $userInfo = self::getShippingAddress($data['users_info_id']); - $country = $userInfo->country_code; - $state = $userInfo->state_code; - $zip = $userInfo->zipcode; - $isCompany = $userInfo->is_company; - $whereShopper = ''; - $whereState = ''; - - if ($isCompany) - { - $where = "AND ( " . $db->qn('company_only') . " = 1 OR " . $db->qn('company_only') . " = 0) "; - } - else - { - $where = "AND ( " . $db->qn('company_only') . " = 2 OR " . $db->qn('company_only') . " = 0) "; - } - - if ($country) - { - $whereCountry = "AND (FIND_IN_SET(" . (string) $db->quote($country) . ", " . $db->qn('shipping_rate_country') . " ) OR " - . $db->qn('shipping_rate_country') . " = " . $db->quote(0) . " OR " - . $db->qn('shipping_rate_country') . " = '') "; - } - else - { - $whereCountry = "AND (FIND_IN_SET(" . $db->quote(Redshop::getConfig()->get('DEFAULT_SHIPPING_COUNTRY')) . ", " . $db->qn('shipping_rate_country') . ")" - . " OR " . $db->qn('shipping_rate_country') . " = " . $db->quote(0) - . " OR " . $db->qn('shipping_rate_country') . " = " . $db->quote('') - . " )"; - } - - $shopperGroup = RedshopHelperUser::getShopperGroupData($userInfo->user_id); - - if (count($shopperGroup) > 0) - { - $shopperGroupId = $shopperGroup->shopper_group_id; - $whereShopper = " AND (FIND_IN_SET(" . $db->quote((int) $shopperGroupId) . ", " - . $db->qn('shipping_rate_on_shopper_group') . " ) OR " - . $db->qn('shipping_rate_on_shopper_group') . " = '') "; - } - - if ($state) - { - $whereState = "AND (FIND_IN_SET(" . (string) $db->quote($state) . ", " . $db->qn('shipping_rate_state') . " ) OR " - . $db->qn('shipping_rate_state') . " = " . $db->quote(0) . " OR " - . $db->qn('shipping_rate_state') . " = '') "; - } - - $numbers = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", " "); - $zipCond = ""; - $zip = trim($zip); - - if (strlen(str_replace($numbers, '', $zip)) == 0 && $zip != "") - { - $zipCond = "AND ( ( " . $db->qn('shipping_rate_zip_start') . " <= " . $db->quote($zip) . " AND " - . $db->qn('shipping_rate_zip_end') . " >= " . $db->quote($zip) . " ) " - . "OR (" . $db->qn('shipping_rate_zip_start') . " = " . $db->quote(0) . " AND " . $db->qn('shipping_rate_zip_end') . " = " . $db->quote(0) . ") " - . "OR (" . $db->qn('shipping_rate_zip_start') . " = '' AND " . $db->qn('shipping_rate_zip_end') . " = '') ) "; - } - - $query = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') - . "WHERE (" . $db->qn('shipping_class') . " = " . $db->quote('default_shipping') - . " OR " . $db->qn('shipping_class') . " = " . $db->quote('shipper') . ") " - . $whereCountry - . $whereState - . $whereShopper - . $zipCond - . $where - . " ORDER BY " . $db->qn('shipping_rate_priority'); - - $shippingRate = $db->setQuery($query)->loadObjectList(); - - if (count($shippingRate) > 0) - { - return true; - } - - return false; - } - - /** - * Check product detail is matched - * - * @return boolean - * - * @since 2.0.0.3 - */ - public static function isProductDetailMatch() - { - $db = JFactory::getDbo(); - $session = JFactory::getSession(); - $cart = $session->get('cart'); - $idx = (int) ($cart['idx']); - $pWhere = ""; - $cWhere = ""; - - if ($idx) - { - $pWhere = 'OR ( '; - - for ($i = 0; $i < $idx; $i++) - { - $productId = $cart[$i]['product_id']; - $pWhere .= "FIND_IN_SET(" . $db->quote((int) $productId) . ", " . $db->qn('shipping_rate_on_product') . ")"; - - if ($i != $idx - 1) - { - $pWhere .= " OR "; - } - } - - $pWhere .= ")"; - } - - $acWhere = array(); - - for ($i = 0; $i < $idx; $i++) - { - $productId = $cart[$i]['product_id']; - $query = $db->getQuery(true) - ->select($db->qn('category_id')) - ->from($db->qn('#__redshop_product_category_xref')) - ->where($db->qn('product_id') . ' = ' . $db->quote((int) $productId)); - - $categoryData = $db->setQuery($query)->loadObjectList(); - - for ($c = 0, $cn = count($categoryData); $c < $cn; $c++) - { - $acWhere[] = " FIND_IN_SET(" . $db->quote((int) $categoryData [$c]->category_id) . ", " . $db->qn('shipping_rate_on_category') . ") "; - } - } - - if (isset($acWhere) && count($acWhere) > 0) - { - $acWhere = implode(' OR ', $acWhere); - $cWhere = ' OR (' . $acWhere . ')'; - } - - $query = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') - . "WHERE (" . $db->qn('shipping_class') . " = " . $db->quote('default_shipping') - . " OR " . $db->qn('shipping_class') . " = " . $db->quote('shipper') . " )" - . "AND (" . $db->qn('shipping_rate_on_product') . " = '' " . $pWhere . ") AND (" - . $db->qn('shipping_rate_on_category') . " = '' " . $cWhere . ") " - . "ORDER BY " . $db->qn('shipping_rate_priority'); - - $shippingRate = $db->setQuery($query)->loadObjectList(); - - if (count($shippingRate) > 0) - { - return true; - } - - return false; - } - - /** - * Get free shipping rate - * - * @param int $shippingRateId Shipping rate ID - * - * @return string - * - * @since 2.0.0.3 - * @throws Exception - * - * @deprecated 2.1.0 - * @see Redshop\Shipping\Rate::getFreeShippingRate - */ - public static function getFreeShippingRate($shippingRateId = 0) - { - return Redshop\Shipping\Rate::getFreeShippingRate($shippingRateId); - } - - /** - * Load payment languages - * - * @param boolean $all True for all (discover, enabled, disabled). False for just enabled only. - * - * @return void - * - * @since 2.0.3 - */ - public static function loadLanguages($all = false) - { - // Load shipping plugin language file - if ($all) - { - $paymentsLangList = RedshopHelperUtility::getPlugins("redshop_shipping"); - } - else - { - $paymentsLangList = RedshopHelperUtility::getPlugins("redshop_shipping", 1); - } - - $language = JFactory::getLanguage(); - - for ($index = 0, $ln = count($paymentsLangList); $index < $ln; $index++) - { - $extension = 'plg_redshop_shipping_' . $paymentsLangList[$index]->element; - $language->load($extension, JPATH_ADMINISTRATOR, $language->getTag(), true); - $language->load( - $extension, JPATH_PLUGINS . '/' . $paymentsLangList[$index]->folder . '/' . $paymentsLangList[$index]->element, - $language->getTag(), - true - ); - } - } + } + + $whereShippingVolume .= " ) "; + } + + $query = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') + . "WHERE (" . $db->qn('shipping_class') . " = " . $db->quote('default_shipping') . " OR " + . $db->qn('shipping_class') . " = " . $db->quote('shipper') . ") " + . "AND ((" . $db->quote($volume) . " BETWEEN " . $db->qn('shipping_rate_volume_start') + . " AND " . $db->qn('shipping_rate_volume_end') . ") OR (" . $db->qn( + 'shipping_rate_volume_end' + ) . " = 0) ) " + . "AND ((" . $db->quote($orderSubtotal) . " BETWEEN " . $db->qn('shipping_rate_ordertotal_start') + . " AND " . $db->qn('shipping_rate_ordertotal_end') . ") OR (" . $db->qn( + 'shipping_rate_ordertotal_end' + ) . " = 0)) " + . "AND ((" . $db->quote($weightTotal) . " BETWEEN " . $db->qn('shipping_rate_weight_start') + . " AND " . $db->qn('shipping_rate_weight_end') . ") OR (" . $db->qn('shipping_rate_weight_end') . " = 0)) " + . $whereShippingVolume + . " ORDER BY " . $db->qn('shipping_rate_priority'); + + $shippingRate = $db->setQuery($query)->loadObjectList(); + + if (count($shippingRate) > 0) { + return true; + } + + return false; + } + + /** + * Check user info is matched + * + * @param array &$data Cart data + * + * @return boolean + * + * @since 2.0.0.3 + */ + public static function isUserInfoMatch(&$data) + { + if (!isset($data['users_info_id']) || $data['users_info_id'] == 0) { + return false; + } + + $db = JFactory::getDbo(); + $userInfo = self::getShippingAddress($data['users_info_id']); + $country = $userInfo->country_code; + $state = $userInfo->state_code; + $zip = $userInfo->zipcode; + $isCompany = $userInfo->is_company; + $whereShopper = ''; + $whereState = ''; + + if ($isCompany) { + $where = "AND ( " . $db->qn('company_only') . " = 1 OR " . $db->qn('company_only') . " = 0) "; + } else { + $where = "AND ( " . $db->qn('company_only') . " = 2 OR " . $db->qn('company_only') . " = 0) "; + } + + if ($country) { + $whereCountry = "AND (FIND_IN_SET(" . (string)$db->quote($country) . ", " . $db->qn( + 'shipping_rate_country' + ) . " ) OR " + . $db->qn('shipping_rate_country') . " = " . $db->quote(0) . " OR " + . $db->qn('shipping_rate_country') . " = '') "; + } else { + $whereCountry = "AND (FIND_IN_SET(" . $db->quote( + Redshop::getConfig()->get('DEFAULT_SHIPPING_COUNTRY') + ) . ", " . $db->qn('shipping_rate_country') . ")" + . " OR " . $db->qn('shipping_rate_country') . " = " . $db->quote(0) + . " OR " . $db->qn('shipping_rate_country') . " = " . $db->quote('') + . " )"; + } + + $shopperGroup = RedshopHelperUser::getShopperGroupData($userInfo->user_id); + + if (count($shopperGroup) > 0) { + $shopperGroupId = $shopperGroup->shopper_group_id; + $whereShopper = " AND (FIND_IN_SET(" . $db->quote((int)$shopperGroupId) . ", " + . $db->qn('shipping_rate_on_shopper_group') . " ) OR " + . $db->qn('shipping_rate_on_shopper_group') . " = '') "; + } + + if ($state) { + $whereState = "AND (FIND_IN_SET(" . (string)$db->quote($state) . ", " . $db->qn( + 'shipping_rate_state' + ) . " ) OR " + . $db->qn('shipping_rate_state') . " = " . $db->quote(0) . " OR " + . $db->qn('shipping_rate_state') . " = '') "; + } + + $numbers = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", " "); + $zipCond = ""; + $zip = trim($zip); + + if (strlen(str_replace($numbers, '', $zip)) == 0 && $zip != "") { + $zipCond = "AND ( ( " . $db->qn('shipping_rate_zip_start') . " <= " . $db->quote($zip) . " AND " + . $db->qn('shipping_rate_zip_end') . " >= " . $db->quote($zip) . " ) " + . "OR (" . $db->qn('shipping_rate_zip_start') . " = " . $db->quote(0) . " AND " . $db->qn( + 'shipping_rate_zip_end' + ) . " = " . $db->quote(0) . ") " + . "OR (" . $db->qn('shipping_rate_zip_start') . " = '' AND " . $db->qn( + 'shipping_rate_zip_end' + ) . " = '') ) "; + } + + $query = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') + . "WHERE (" . $db->qn('shipping_class') . " = " . $db->quote('default_shipping') + . " OR " . $db->qn('shipping_class') . " = " . $db->quote('shipper') . ") " + . $whereCountry + . $whereState + . $whereShopper + . $zipCond + . $where + . " ORDER BY " . $db->qn('shipping_rate_priority'); + + $shippingRate = $db->setQuery($query)->loadObjectList(); + + if (count($shippingRate) > 0) { + return true; + } + + return false; + } + + /** + * Check product detail is matched + * + * @return boolean + * + * @since 2.0.0.3 + */ + public static function isProductDetailMatch() + { + $db = JFactory::getDbo(); + $session = JFactory::getSession(); + $cart = $session->get('cart'); + $idx = (int)($cart['idx']); + $pWhere = ""; + $cWhere = ""; + + if ($idx) { + $pWhere = 'OR ( '; + + for ($i = 0; $i < $idx; $i++) { + $productId = $cart[$i]['product_id']; + $pWhere .= "FIND_IN_SET(" . $db->quote((int)$productId) . ", " . $db->qn( + 'shipping_rate_on_product' + ) . ")"; + + if ($i != $idx - 1) { + $pWhere .= " OR "; + } + } + + $pWhere .= ")"; + } + + $acWhere = array(); + + for ($i = 0; $i < $idx; $i++) { + $productId = $cart[$i]['product_id']; + $query = $db->getQuery(true) + ->select($db->qn('category_id')) + ->from($db->qn('#__redshop_product_category_xref')) + ->where($db->qn('product_id') . ' = ' . $db->quote((int)$productId)); + + $categoryData = $db->setQuery($query)->loadObjectList(); + + for ($c = 0, $cn = count($categoryData); $c < $cn; $c++) { + $acWhere[] = " FIND_IN_SET(" . $db->quote((int)$categoryData [$c]->category_id) . ", " . $db->qn( + 'shipping_rate_on_category' + ) . ") "; + } + } + + if (isset($acWhere) && count($acWhere) > 0) { + $acWhere = implode(' OR ', $acWhere); + $cWhere = ' OR (' . $acWhere . ')'; + } + + $query = "SELECT * FROM " . $db->qn('#__redshop_shipping_rate') + . "WHERE (" . $db->qn('shipping_class') . " = " . $db->quote('default_shipping') + . " OR " . $db->qn('shipping_class') . " = " . $db->quote('shipper') . " )" + . "AND (" . $db->qn('shipping_rate_on_product') . " = '' " . $pWhere . ") AND (" + . $db->qn('shipping_rate_on_category') . " = '' " . $cWhere . ") " + . "ORDER BY " . $db->qn('shipping_rate_priority'); + + $shippingRate = $db->setQuery($query)->loadObjectList(); + + if (count($shippingRate) > 0) { + return true; + } + + return false; + } + + /** + * Get free shipping rate + * + * @param int $shippingRateId Shipping rate ID + * + * @return string + * + * @throws Exception + * + * @since 2.0.0.3 + * @deprecated 2.1.0 + * @see Redshop\Shipping\Rate::getFreeShippingRate + */ + public static function getFreeShippingRate($shippingRateId = 0) + { + return Redshop\Shipping\Rate::getFreeShippingRate($shippingRateId); + } + + /** + * Load payment languages + * + * @param boolean $all True for all (discover, enabled, disabled). False for just enabled only. + * + * @return void + * + * @since 2.0.3 + */ + public static function loadLanguages($all = false) + { + // Load shipping plugin language file + if ($all) { + $paymentsLangList = RedshopHelperUtility::getPlugins("redshop_shipping"); + } else { + $paymentsLangList = RedshopHelperUtility::getPlugins("redshop_shipping", 1); + } + + $language = JFactory::getLanguage(); + + for ($index = 0, $ln = count($paymentsLangList); $index < $ln; $index++) { + $extension = 'plg_redshop_shipping_' . $paymentsLangList[$index]->element; + $language->load($extension, JPATH_ADMINISTRATOR, $language->getTag(), true); + $language->load( + $extension, + JPATH_PLUGINS . '/' . $paymentsLangList[$index]->folder . '/' . $paymentsLangList[$index]->element, + $language->getTag(), + true + ); + } + } } diff --git a/libraries/redshop/helper/shipping/tag.php b/libraries/redshop/helper/shipping/tag.php index 8dafa4579f6..7e13e8643bc 100644 --- a/libraries/redshop/helper/shipping/tag.php +++ b/libraries/redshop/helper/shipping/tag.php @@ -16,35 +16,35 @@ */ class RedshopHelperShippingTag { - /** - * Replace shipping method - * - * @param stdClass $shipping Shipping data - * @param string $content Template content - * - * @return string - * - * @deprecated 2.1.0 - */ - public static function replaceShippingMethod($shipping, $content = "") - { - return Redshop\Shipping\Tag::replaceShippingMethod($shipping, $content); - } + /** + * Replace shipping method + * + * @param stdClass $shipping Shipping data + * @param string $content Template content + * + * @return string + * + * @deprecated 2.1.0 + */ + public static function replaceShippingMethod($shipping, $content = "") + { + return Redshop\Shipping\Tag::replaceShippingMethod($shipping, $content); + } - /** - * Replace Shipping Address - * - * @param string $templateHtml Template content - * @param object $shippingAddress Shipping address - * @param boolean $sendMail Is in send mail - * - * @return string - * @throws Exception - * - * @deprecated 2.1.0 - */ - public static function replaceShippingAddress($templateHtml, $shippingAddress, $sendMail = false) - { - return Redshop\Shipping\Tag::replaceShippingAddress($templateHtml, $shippingAddress, $sendMail); - } + /** + * Replace Shipping Address + * + * @param string $templateHtml Template content + * @param object $shippingAddress Shipping address + * @param boolean $sendMail Is in send mail + * + * @return string + * @throws Exception + * + * @deprecated 2.1.0 + */ + public static function replaceShippingAddress($templateHtml, $shippingAddress, $sendMail = false) + { + return Redshop\Shipping\Tag::replaceShippingAddress($templateHtml, $shippingAddress, $sendMail); + } } diff --git a/libraries/redshop/helper/shopper_group.php b/libraries/redshop/helper/shopper_group.php index 6e7a5104107..1b9c545a460 100644 --- a/libraries/redshop/helper/shopper_group.php +++ b/libraries/redshop/helper/shopper_group.php @@ -20,338 +20,335 @@ */ class RedshopHelperShopper_Group { - /** - * List all shopper group as dropdown list - * - * @param string $name Name of dropdown list - * @param integer $shopperGroupId ID of shopper group to display - * @param array $selectedGroups Array of selected group - * @param integer $size Size of dropdown list - * @param boolean $topLevel Position align from top - * @param boolean $multiple Is multiple select or not - * @param array $disabledFields Disable some groups - * - * @return string HTML of dropdown list to render - * - * @since 2.0.3 - */ - public static function listAll($name, $shopperGroupId, $selectedGroups = array(), $size = 1, $topLevel = true, $multiple = false, - $disabledFields = array()) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $html = ''; - - $query->select($db->qn('parent_id')) - ->select($db->qn('shopper_group_id')) - ->from($db->qn('#__redshop_shopper_group')); - - if ($shopperGroupId) - { - $query->where($db->qn('shopper_group_id') . ' = ' . (int) $shopperGroupId); - } - - $db->setQuery($query); - $groups = $db->loadObjectList(); - - if ($groups) - { - $selectedGroups[] = $groups[0]->parent_id; - } - - $multiple = $multiple ? "multiple=\"multiple\"" : ""; - $id = str_replace('[]', '', $name); - $html .= "\n"; - - return $html; - } - - /** - * List shopper group as option of dropdown list - * - * @param integer $shopperGroupId Shopper group ID to display - * @param integer $cid Parent ID - * @param integer $level Position - * @param array $selectedGroups Selected groups will be marked selected - * @param array $disabledFields Disable groups - * @param string $html Previous HTML - * - * @return string HTML to render - * - * @since 2.0.3 - */ - public static function listTree($shopperGroupId = 0, $cid = 0, $level = 0, $selectedGroups = array(), $disabledFields = array(), $html = '') - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $level++; - - $query->select($db->qn(array('shopper_group_id', 'shopper_group_name', 'parent_id'))) - ->from($db->qn('#__redshop_shopper_group')) - ->where($db->qn('parent_id') . ' = ' . (int) $cid) - ->where($db->qn('shopper_group_id') . ' != ' . (int) $shopperGroupId); - - $db->setQuery($query); - $groups = $db->loadObjectList(); - - for ($x = 0, $xn = count($groups); $x < $xn; $x++) - { - $group = $groups[$x]; - $childId = $group->shopper_group_id; - - $selected = ""; - - if (is_array($selectedGroups)) - { - if (in_array($childId, $selectedGroups)) - { - $selected = "selected=\"selected\""; - } - - $disabled = ''; - - if (in_array($childId, $disabledFields)) - { - $disabled = 'disabled="disabled"'; - } - - $html .= ""; - } - - $html .= self::listTree($shopperGroupId, $childId, $level, $selectedGroups, $disabledFields); - } - - return $html; - } - - /** - * Get Shopper Group List as Array - * - * @param integer $shopperGroupId Shopper Group ID to display - * @param integer $cid Parent ID - * @param integer $level Position - * - * @return array - * - * @since 2.0.3 - * - * @throws Exception - */ - public static function getShopperGroupListArray($shopperGroupId = 0, $cid = 0, $level = 0) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $level++; - - $app = JFactory::getApplication(); + /** + * List all shopper group as dropdown list + * + * @param string $name Name of dropdown list + * @param integer $shopperGroupId ID of shopper group to display + * @param array $selectedGroups Array of selected group + * @param integer $size Size of dropdown list + * @param boolean $topLevel Position align from top + * @param boolean $multiple Is multiple select or not + * @param array $disabledFields Disable some groups + * + * @return string HTML of dropdown list to render + * + * @since 2.0.3 + */ + public static function listAll( + $name, + $shopperGroupId, + $selectedGroups = array(), + $size = 1, + $topLevel = true, + $multiple = false, + $disabledFields = array() + ) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $html = ''; + + $query->select($db->qn('parent_id')) + ->select($db->qn('shopper_group_id')) + ->from($db->qn('#__redshop_shopper_group')); + + if ($shopperGroupId) { + $query->where($db->qn('shopper_group_id') . ' = ' . (int)$shopperGroupId); + } + + $db->setQuery($query); + $groups = $db->loadObjectList(); + + if ($groups) { + $selectedGroups[] = $groups[0]->parent_id; + } + + $multiple = $multiple ? "multiple=\"multiple\"" : ""; + $id = str_replace('[]', '', $name); + $html .= "\n"; + + return $html; + } + + /** + * List shopper group as option of dropdown list + * + * @param integer $shopperGroupId Shopper group ID to display + * @param integer $cid Parent ID + * @param integer $level Position + * @param array $selectedGroups Selected groups will be marked selected + * @param array $disabledFields Disable groups + * @param string $html Previous HTML + * + * @return string HTML to render + * + * @since 2.0.3 + */ + public static function listTree( + $shopperGroupId = 0, + $cid = 0, + $level = 0, + $selectedGroups = array(), + $disabledFields = array(), + $html = '' + ) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $level++; + + $query->select($db->qn(array('shopper_group_id', 'shopper_group_name', 'parent_id'))) + ->from($db->qn('#__redshop_shopper_group')) + ->where($db->qn('parent_id') . ' = ' . (int)$cid) + ->where($db->qn('shopper_group_id') . ' != ' . (int)$shopperGroupId); + + $db->setQuery($query); + $groups = $db->loadObjectList(); + + for ($x = 0, $xn = count($groups); $x < $xn; $x++) { + $group = $groups[$x]; + $childId = $group->shopper_group_id; + + $selected = ""; + + if (is_array($selectedGroups)) { + if (in_array($childId, $selectedGroups)) { + $selected = "selected=\"selected\""; + } + + $disabled = ''; + + if (in_array($childId, $disabledFields)) { + $disabled = 'disabled="disabled"'; + } + + $html .= ""; + } + + $html .= self::listTree($shopperGroupId, $childId, $level, $selectedGroups, $disabledFields); + } + + return $html; + } + + /** + * Get Shopper Group List as Array + * + * @param integer $shopperGroupId Shopper Group ID to display + * @param integer $cid Parent ID + * @param integer $level Position + * + * @return array + * + * @throws Exception + * @since 2.0.3 + * + */ + public static function getShopperGroupListArray($shopperGroupId = 0, $cid = 0, $level = 0) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $level++; + + $app = JFactory::getApplication(); $filterOrder = $app->getUserStateFromRequest('filter_order', 'filter_order', 'shopper_group_id'); $filterOrderDir = $app->getUserStateFromRequest('filter_order_Dir', 'filter_order_Dir', ''); - $query->select('*') - ->from($db->qn('#__redshop_shopper_group')) - ->where($db->qn('parent_id') . ' = ' . (int) $cid) - ->order($filterOrder . ' ' . $filterOrderDir); - - $db->setQuery($query); - $groups = $db->loadObjectList(); - - for ($x = 0, $xn = count($groups); $x < $xn; $x++) - { - $html = ''; - $group = $groups[$x]; - $childId = $group->shopper_group_id; - - if ($childId != $cid) - { - for ($i = 0; $i < $level; $i++) - { - $html .= "| — "; - } - - $html .= $group->shopper_group_name; - } - - $group->shopper_group_name = $html; - $GLOBALS['grouplist'][] = $group; - self::getShopperGroupListArray($shopperGroupId, $childId, $level); - } - - if (isset($GLOBALS['grouplist'])) - { - return $GLOBALS['grouplist']; - } - - return array(); - } - - /** - * Get Category List Reverce Array - * - * @param integer $cid Parent ID - * - * @return array - * - * @since 2.0.3 - */ - public static function getCategoryListReverceArray($cid = 0) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select($db->qn(array('c.shopper_group_id', 'cx.shopper_group_categories', 'cx.shopper_group_id', 'cx.parent_id'))) - ->from($db->qn('#__redshop_shopper_group', 'cx')) - ->leftJoin( - $db->qn('#__redshop_shopper_group', 'c') - . ' ON ' . - $db->qn('c.shopper_group_id') . ' = ' . $db->qn('cx.parent_id') - ) - ->where($db->qn('cx.shopper_group_id') . ' = ' . (int) $cid); - - $db->setQuery($query); - $groups = $db->loadObjectList(); - - for ($x = 0, $xn = count($groups); $x < $xn; $x++) - { - $group = $groups[$x]; - $parent_id = $group->parent_id; - - $GLOBALS['catlist_reverse'][] = $group; - self::getCategoryListReverceArray($parent_id); - } - - return $GLOBALS['catlist_reverse']; - } - - /** - * shopper Group portal info - * - * @return mixed Shopper Group Ids Object - * - * @since 2.0.6 - */ - public static function getShopperGroupPortal() - { - $user = JFactory::getUser(); - $shopperGroupId = RedshopHelperUser::getShopperGroup($user->id); - - $result = Redshop\Helper\ShopperGroup::generateList($shopperGroupId); - - return !empty($result) ? $result[0] : false; - } - - /** - * Shopper Group category ACL - * - * @param int $cid Category id - * - * @return mixed - * - * @since 2.0.6 - */ - public static function getShopperGroupCategory($cid = 0) - { - $user = JFactory::getUser(); - $shopperGroupId = RedshopHelperUser::getShopperGroup($user->id); - $shopperGroupData = Redshop\Helper\ShopperGroup::generateList($shopperGroupId); - - if (!empty($shopperGroupData)) - { - if (isset($shopperGroupData[0]) && $shopperGroupData[0]->shopper_group_categories) - { - $categories = explode(',', $shopperGroupData[0]->shopper_group_categories); - - if (array_search((int) $cid, $categories) !== false) - { - return $shopperGroupData[0]; - } - } - } - - return null; - } - - /** - * Shopper Group product category ACL - * - * @param int $productId Category id - * - * @return mixed - * - * @since 2.0.6 - */ - public static function getShopperGroupProductCategory($productId = 0) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('p.product_id')) - ->select($db->qn('cx.category_id')) - ->from($db->qn('#__redshop_product', 'p')) - ->leftJoin($db->qn('#__redshop_product_category_xref', 'cx') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn('cx.product_id')) - ->where($db->qn('p.product_id') . ' = ' . $productId); - - $productCategories = $db->setQuery($query)->loadObjectList(); - - if (empty($productCategories)) - { - return false; - } - - $flag = false; - - foreach ($productCategories as $productCategory) - { - $shopperCategory = self::getShopperGroupCategory($productCategory->category_id); - - if (count($shopperCategory) <= 0 && $flag == false) - { - $flag = true; - } - } - - return $flag; - } - - /** - * Method for get shopper group manufacturers of specific user. - * - * @param integer $userId Joomla user id. - * - * @return string List of manufacturer Ids. - * - * @since 2.0.7 - */ - public static function getShopperGroupManufacturers($userId = 0) - { - if (!$userId) - { - $userId = JFactory::getUser()->id; - } - - $shopperGroupId = RedshopHelperUser::getShopperGroup($userId); - $shopperGroups = ShopperGroup::generateList($shopperGroupId); - - if (empty($shopperGroups)) - { - return ''; - } - - return $shopperGroups[0]->shopper_group_manufactures; - } + $query->select('*') + ->from($db->qn('#__redshop_shopper_group')) + ->where($db->qn('parent_id') . ' = ' . (int)$cid) + ->order($filterOrder . ' ' . $filterOrderDir); + + $db->setQuery($query); + $groups = $db->loadObjectList(); + + for ($x = 0, $xn = count($groups); $x < $xn; $x++) { + $html = ''; + $group = $groups[$x]; + $childId = $group->shopper_group_id; + + if ($childId != $cid) { + for ($i = 0; $i < $level; $i++) { + $html .= "| — "; + } + + $html .= $group->shopper_group_name; + } + + $group->shopper_group_name = $html; + $GLOBALS['grouplist'][] = $group; + self::getShopperGroupListArray($shopperGroupId, $childId, $level); + } + + if (isset($GLOBALS['grouplist'])) { + return $GLOBALS['grouplist']; + } + + return array(); + } + + /** + * Get Category List Reverce Array + * + * @param integer $cid Parent ID + * + * @return array + * + * @since 2.0.3 + */ + public static function getCategoryListReverceArray($cid = 0) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select( + $db->qn(array('c.shopper_group_id', 'cx.shopper_group_categories', 'cx.shopper_group_id', 'cx.parent_id')) + ) + ->from($db->qn('#__redshop_shopper_group', 'cx')) + ->leftJoin( + $db->qn('#__redshop_shopper_group', 'c') + . ' ON ' . + $db->qn('c.shopper_group_id') . ' = ' . $db->qn('cx.parent_id') + ) + ->where($db->qn('cx.shopper_group_id') . ' = ' . (int)$cid); + + $db->setQuery($query); + $groups = $db->loadObjectList(); + + for ($x = 0, $xn = count($groups); $x < $xn; $x++) { + $group = $groups[$x]; + $parent_id = $group->parent_id; + + $GLOBALS['catlist_reverse'][] = $group; + self::getCategoryListReverceArray($parent_id); + } + + return $GLOBALS['catlist_reverse']; + } + + /** + * shopper Group portal info + * + * @return mixed Shopper Group Ids Object + * + * @since 2.0.6 + */ + public static function getShopperGroupPortal() + { + $user = JFactory::getUser(); + $shopperGroupId = RedshopHelperUser::getShopperGroup($user->id); + + $result = Redshop\Helper\ShopperGroup::generateList($shopperGroupId); + + return !empty($result) ? $result[0] : false; + } + + /** + * Shopper Group product category ACL + * + * @param int $productId Category id + * + * @return mixed + * + * @since 2.0.6 + */ + public static function getShopperGroupProductCategory($productId = 0) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('p.product_id')) + ->select($db->qn('cx.category_id')) + ->from($db->qn('#__redshop_product', 'p')) + ->leftJoin( + $db->qn('#__redshop_product_category_xref', 'cx') . ' ON ' . $db->qn('p.product_id') . ' = ' . $db->qn( + 'cx.product_id' + ) + ) + ->where($db->qn('p.product_id') . ' = ' . $productId); + + $productCategories = $db->setQuery($query)->loadObjectList(); + + if (empty($productCategories)) { + return false; + } + + $flag = false; + + foreach ($productCategories as $productCategory) { + $shopperCategory = self::getShopperGroupCategory($productCategory->category_id); + + if (count($shopperCategory) <= 0 && $flag == false) { + $flag = true; + } + } + + return $flag; + } + + /** + * Shopper Group category ACL + * + * @param int $cid Category id + * + * @return mixed + * + * @since 2.0.6 + */ + public static function getShopperGroupCategory($cid = 0) + { + $user = JFactory::getUser(); + $shopperGroupId = RedshopHelperUser::getShopperGroup($user->id); + $shopperGroupData = Redshop\Helper\ShopperGroup::generateList($shopperGroupId); + + if (!empty($shopperGroupData)) { + if (isset($shopperGroupData[0]) && $shopperGroupData[0]->shopper_group_categories) { + $categories = explode(',', $shopperGroupData[0]->shopper_group_categories); + + if (array_search((int)$cid, $categories) !== false) { + return $shopperGroupData[0]; + } + } + } + + return null; + } + + /** + * Method for get shopper group manufacturers of specific user. + * + * @param integer $userId Joomla user id. + * + * @return string List of manufacturer Ids. + * + * @since 2.0.7 + */ + public static function getShopperGroupManufacturers($userId = 0) + { + if (!$userId) { + $userId = JFactory::getUser()->id; + } + + $shopperGroupId = RedshopHelperUser::getShopperGroup($userId); + $shopperGroups = ShopperGroup::generateList($shopperGroupId); + + if (empty($shopperGroups)) { + return ''; + } + + return $shopperGroups[0]->shopper_group_manufactures; + } } diff --git a/libraries/redshop/helper/statistic.php b/libraries/redshop/helper/statistic.php index 9541b5530a4..e5d380abed0 100644 --- a/libraries/redshop/helper/statistic.php +++ b/libraries/redshop/helper/statistic.php @@ -16,95 +16,6 @@ */ abstract class RedshopHelperStatistic { - /** - * Method for store view of page. - * - * @return bool True on success. False otherwise. - * - * @since 2.0.3 - * - * @throws Exception - */ - public static function recordPage() - { - $input = JFactory::getApplication()->input; - $sessionId = JFactory::getSession()->getId(); - $user = JFactory::getUser(); - - $view = $input->getCmd('view', ''); - $section = ''; - $sectionId = 0; - - switch ($view) - { - case 'product': - $section = $view; - $sectionId = $input->getInt('pid', 0); - break; - - case 'category': - $section = $view; - $sectionId = $input->getInt('cid', 0); - break; - - case 'manufacturers': - $section = $view; - $sectionId = $input->getInt('mid', 0); - break; - - default: - break; - } - - if (empty($section)) - { - return false; - } - - $table = RedshopTable::getInstance('Page_Viewer', 'RedshopTable'); - - if ($table->load(array('session_id' => $sessionId, 'section' => $section, 'section_id' => $sectionId))) - { - return true; - } - - $table->id = null; - $table->session_id = $sessionId; - $table->user_id = $user->id; - $table->section = $section; - $table->section_id = $sectionId; - $table->created_date = JFactory::getDate()->toUnix(); - - return $table->store(); - } - - /** - * Method for store visitor. - * - * @return bool True on success. False otherwise. - * - * @since 2.0.3 - */ - public static function recordVisitor() - { - $sessionId = JFactory::getSession()->getId(); - $user = JFactory::getUser(); - - $table = RedshopTable::getInstance('Site_Viewer', 'RedshopTable'); - - if ($table->load(array('session_id' => $sessionId))) - { - return true; - } - - $table->id = null; - $table->user_id = $user->id; - $table->session_id = $sessionId; - $table->created_date = JFactory::getDate()->toUnix(); - - return $table->store(); - } - /** * @throws Exception * @since 3.0 @@ -112,10 +23,94 @@ public static function recordVisitor() public static function track() { // Only when enabled in configuration - if (\Redshop::getConfig()->get('STATISTICS_ENABLE')) - { - self::recordVisitor(); - self::recordPage(); + if (\Redshop::getConfig()->get('STATISTICS_ENABLE')) { + self::recordVisitor(); + self::recordPage(); + } + } + + /** + * Method for store visitor. + * + * @return bool True on success. False otherwise. + * + * @since 2.0.3 + */ + public static function recordVisitor() + { + $sessionId = JFactory::getSession()->getId(); + $user = JFactory::getUser(); + + $table = RedshopTable::getInstance('Site_Viewer', 'RedshopTable'); + + if ($table->load(array('session_id' => $sessionId))) { + return true; + } + + $table->id = null; + $table->user_id = $user->id; + $table->session_id = $sessionId; + $table->created_date = JFactory::getDate()->toUnix(); + + return $table->store(); + } + + /** + * Method for store view of page. + * + * @return bool True on success. False otherwise. + * + * @throws Exception + * @since 2.0.3 + * + */ + public static function recordPage() + { + $input = JFactory::getApplication()->input; + $sessionId = JFactory::getSession()->getId(); + $user = JFactory::getUser(); + + $view = $input->getCmd('view', ''); + $section = ''; + $sectionId = 0; + + switch ($view) { + case 'product': + $section = $view; + $sectionId = $input->getInt('pid', 0); + break; + + case 'category': + $section = $view; + $sectionId = $input->getInt('cid', 0); + break; + + case 'manufacturers': + $section = $view; + $sectionId = $input->getInt('mid', 0); + break; + + default: + break; + } + + if (empty($section)) { + return false; + } + + $table = RedshopTable::getInstance('Page_Viewer', 'RedshopTable'); + + if ($table->load(array('session_id' => $sessionId, 'section' => $section, 'section_id' => $sectionId))) { + return true; } + + $table->id = null; + $table->session_id = $sessionId; + $table->user_id = $user->id; + $table->section = $section; + $table->section_id = $sectionId; + $table->created_date = JFactory::getDate()->toUnix(); + + return $table->store(); } } diff --git a/libraries/redshop/helper/stockroom.php b/libraries/redshop/helper/stockroom.php index b1ca4946a91..7d47105e142 100644 --- a/libraries/redshop/helper/stockroom.php +++ b/libraries/redshop/helper/stockroom.php @@ -18,1526 +18,1398 @@ */ class RedshopHelperStockroom { - /** - * @var array - */ - public static $stock = array(); - - /** - * @var array - */ - public static $stockReserve = array(); - - /** - * Check already notified user - * - * @param int $userId User id - * @param int $productId Product id - * @param int $propertyId Property id - * @param int $subPropertyId Sub property id - * - * @return mixed - */ - public static function isAlreadyNotifiedUser($userId, $productId, $propertyId, $subPropertyId) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('id') - ->from($db->qn('#__redshop_notifystock_users')) - ->where('product_id = ' . (int) $productId) - ->where('property_id = ' . (int) $propertyId) - ->where('subproperty_id = ' . (int) $subPropertyId) - ->where('user_id = ' . (int) $userId) - ->where('notification_status = 0'); - - return $db->setQuery($query)->loadResult(); - } - - /** - * Get stockroom - * - * @param mixed $stockroomId stockroom id - * @param int $published published/unpublished - * @param boolean $isChecked checked use stockroom - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function getStockroom($stockroomId = null, $published = null, $isChecked = false) - { - /** - * Check: If "Check stockroom config" is true, skip process if stockroom config is not use stockroom. - */ - if ($isChecked === true && Redshop::getConfig()->get('USE_STOCKROOM') != 1) - { - return array(); - } - - $db = JFactory::getDBO(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_stockroom')); - - // Convert stockroom ID to array - if (!empty($stockroomId)) - { - if (is_string($stockroomId)) - { - $stockroomId = explode(',', $stockroomId); - } - elseif (is_int($stockroomId)) - { - $stockroomId = array($stockroomId); - } - - $query->where($db->qn('stockroom_id') . ' IN (' . implode(',', $stockroomId) . ')'); - } - - if (!empty($published)) - { - $query->where($db->qn('published') . ' = ' . $db->quote((int) $published)); - } - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * Check is stock exists - * - * @param mixed $sectionId Section id - * @param string $section Section - * @param integer $stockroomId Stockroom id - * - * @return boolean True if exist. False otherwise. - * - * @since 2.0.0.3 - */ - public static function isStockExists($sectionId = 0, $section = "product", $stockroomId = 0) - { - if (!Redshop::getConfig()->getBool('USE_STOCKROOM')) - { - return true; - } - - $stock = self::getStockAmountwithReserve($sectionId, $section, $stockroomId); - - JPluginHelper::importPlugin('redshop_product'); - RedshopHelperUtility::getDispatcher()->trigger('onIsStockExists', array($sectionId, $section, $stockroomId, &$stock)); - - return $stock > 0; - } - - /** - * Check is attribute stock exists - * - * @param int $productId Product id - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function isAttributeStockExists($productId) - { - $isStockExists = false; - $properties = RedshopHelperProduct_Attribute::getAttributeProperties(0, 0, $productId); - - foreach ($properties as $property) - { - $isSubpropertyStock = false; - $subProperties = RedshopHelperProduct_Attribute::getAttributeSubProperties(0, $property->property_id); - - foreach ($subProperties as $subProperty) - { - $isSubpropertyStock = self::isStockExists($subProperty->subattribute_color_id, 'subproperty'); - - if ($isSubpropertyStock) - { - $isStockExists = $isSubpropertyStock; - - return $isStockExists; - } - } - - if ($isSubpropertyStock) - { - return $isStockExists; - } - else - { - $isPropertystock = self::isStockExists($property->property_id, "property"); - - if ($isPropertystock) - { - $isStockExists = $isPropertystock; - - return $isStockExists; - } - } - } - - return $isStockExists; - } - - /** - * Check is pre-order stock exists - * - * @param int $sectionId Section id - * @param string $section Section - * @param int $stockroomId Stockroom id - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function isPreorderStockExists($sectionId = 0, $section = "product", $stockroomId = 0) - { - if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) - { - $stock = self::getPreorderStockAmountwithReserve($sectionId, $section, $stockroomId); - - if ($stock > 0) - { - return true; - } - - return false; - } - - return true; - } - - /** - * Check is attribute pre-order stock exists - * - * @param int $productId Product id - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function isAttributePreorderStockExists($productId) - { - $properties = RedshopHelperProduct_Attribute::getAttributeProperties(0, 0, $productId); - $isPreorderStockExists = false; - - foreach ($properties as $property) - { - $isSubpropertyStock = false; - $subProperties = RedshopHelperProduct_Attribute::getAttributeSubProperties(0, $property->property_id); - - foreach ($subProperties as $subProperty) - { - $isSubpropertyStock = self::isPreorderStockExists($subProperty->subattribute_color_id, 'subproperty'); - - if ($isSubpropertyStock) - { - $isPreorderStockExists = $isSubpropertyStock; - - return $isPreorderStockExists; - } - } - - if ($isSubpropertyStock) - { - return $isPreorderStockExists; - } - else - { - $isPropertystock = self::isPreorderStockExists($property->property_id, "property"); - - if ($isPropertystock) - { - $isPreorderStockExists = $isPropertystock; - - return $isPreorderStockExists; - } - } - } - - return $isPreorderStockExists; - } - - /** - * Get Stockroom Total amount - * - * @param int $sectionId Section id - * @param string $section Section - * @param int $stockroomId Stockroom id - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function getStockroomTotalAmount($sectionId = 0, $section = "product", $stockroomId = 0) - { - $quantity = 1; - - if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) - { - $quantity = self::getStockAmountwithReserve($sectionId, $section, $stockroomId); - $reserveQuantity = self::getReservedStock($sectionId, $section); - $quantity = $quantity - $reserveQuantity; - - if ($quantity < 0) - { - $quantity = 0; - } - } - - return $quantity; - } - - /** - * Get pre-order stockroom total amount - * - * @param int $sectionId Section id - * @param string $section Section - * @param int $stockroomId Stockroom id - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function getPreorderStockroomTotalAmount($sectionId = 0, $section = "product", $stockroomId = 0) - { - $quantity = 1; - - if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) - { - $quantity = self::getPreorderStockAmountwithReserve($sectionId, $section, $stockroomId); - - $reserveQuantity = self::getReservedStock($sectionId, $section); - $quantity = $quantity - $reserveQuantity; - - if ($quantity < 0) - { - $quantity = 0; - } - } - - return $quantity; - } - - /** - * Get Stock Amount with Reserve - * - * @param mixed $sectionId Section id - * @param string $section Section - * @param integer $stockroomId Stockroom id - * - * @return mixed - */ - public static function getStockAmountWithReserve($sectionId = 0, $section = 'product', $stockroomId = 0) - { - $quantity = 1; - - if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) - { - if ($section == 'product' && $stockroomId == 0 && $sectionId) - { - $sectionId = explode(',', $sectionId); - $sectionId = ArrayHelper::toInteger($sectionId); - $quantity = 0; - - foreach ($sectionId as $item) - { - $productData = Redshop::product((int) $item); - - if (isset($productData->sum_quanity)) - { - $quantity += $productData->sum_quanity; - } - } - } - else - { - $key = md5($section . '-' . $sectionId . '-' . $stockroomId); - - if (!array_key_exists($key, self::$stockReserve)) - { - $table = 'product'; - $db = JFactory::getDbo(); - - if ($section != 'product') - { - $table = 'product_attribute'; - } - - $query = $db->getQuery(true) - ->select('SUM(x.quantity)') - ->from($db->qn('#__redshop_' . $table . '_stockroom_xref', 'x')) - ->leftJoin($db->qn('#__redshop_stockroom', 's') . ' ON s.stockroom_id = x.stockroom_id') - ->where('x.quantity >= 0'); - - if ($sectionId != 0) - { - $sectionId = explode(',', $sectionId); - $sectionId = ArrayHelper::toInteger($sectionId); - - if ($section != 'product') - { - $query->where('x.section = ' . $db->quote($section)) - ->where('x.section_id IN (' . implode(',', $sectionId) . ')'); - } - else - { - $query->where('x.product_id IN (' . implode(',', $sectionId) . ')'); - } - } - - if ($stockroomId != 0) - { - $query->where('x.stockroom_id = ' . (int) $stockroomId); - } - - self::$stockReserve[$key] = $db->setQuery($query)->loadResult(); - } - - $quantity = self::$stockReserve[$key]; - } - - $quantity = $quantity < 0 ? 0 : $quantity; - } - - if ($quantity == null) - { - $quantity = (Redshop::getConfig()->get('USE_BLANK_AS_INFINITE')) ? 1000000000 : 0; - } - - return $quantity; - } - - /** - * Get pre-order stockroom amount with reserve - * - * @param integer $sectionId Section id - * @param string $section Section - * @param integer $stockroomId Stockroom id - * - * @return integer - * - * @since 2.0.0.3 - */ - public static function getPreorderStockAmountWithReserve($sectionId = 0, $section = "product", $stockroomId = 0) - { - if (!Redshop::getConfig()->get('USE_STOCKROOM')) - { - return 1; - } - - $key = md5($sectionId . '-' . $section . '-' . $stockroomId); - - if (!array_key_exists($key, self::$stock)) - { - $table = "#__redshop_product_stockroom_xref"; - - if ($section != "product") - { - $table = "#__redshop_product_attribute_stockroom_xref"; - } - - $db = JFactory::getDBO(); - $query = $db->getQuery(true) - ->select('SUM(x.preorder_stock) AS preorder_stock') - ->select('SUM(x.ordered_preorder) AS ordered_preorder') - ->from($db->qn($table, 'x')) - ->leftJoin( - $db->qn('#__redshop_stockroom', 's') . ' ON ' - . $db->qn('x.stockroom_id') . ' = ' . $db->qn('s.stockroom_id') - ) - ->where($db->qn('x.quantity') . ' >= 0') - ->order($db->qn('s.min_del_time')); - - if ($sectionId != 0) - { - // Sanitize ids - $sectionId = explode(',', $sectionId); - $sectionId = ArrayHelper::toInteger($sectionId); - - if ($section != "product") - { - $query->where($db->qn('x.section') . ' = ' . $db->q($section)) - ->where($db->qn('x.section_id') . ' IN (' . implode(',', $sectionId) . ')'); - } - else - { - $query->where($db->qn('x.product_id') . ' IN (' . implode(',', $sectionId) . ')'); - } - } - - if ($stockroomId != 0) - { - $query->where($db->qn('x.stockroom_id') . ' = ' . $db->q((int) $stockroomId)); - } - - $preOrderStock = $db->setQuery($query)->loadObjectList(); - - if ($preOrderStock[0]->ordered_preorder == $preOrderStock[0]->preorder_stock - || $preOrderStock[0]->ordered_preorder > $preOrderStock[0]->preorder_stock) - { - $quantity = 0; - } - else - { - $quantity = $preOrderStock[0]->preorder_stock - $preOrderStock[0]->ordered_preorder; - } - - self::$stock[$key] = $quantity; - } - - return self::$stock[$key]; - } - - /** - * Get stockroom amount detail list - * - * @param int $sectionId Section id - * @param string $section Section - * @param int $stockroomId Stockroom id - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function getStockroomAmountDetailList($sectionId = 0, $section = "product", $stockroomId = 0) - { - $list = array(); - - if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) - { - $table = "#__redshop_product_stockroom_xref"; - - if ($section != "product") - { - $table = "#__redshop_product_attribute_stockroom_xref"; - } - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('DISTINCT(s.stockroom_id), s.*, x.*') - ->from($db->qn($table, 'x')) - ->leftJoin( - $db->qn('#__redshop_stockroom', 's') . ' ON ' - . $db->qn('x.stockroom_id') . ' = ' . $db->qn('s.stockroom_id') - ) - ->order($db->qn('s.min_del_time')); - - if ($sectionId != 0) - { - if ($section != "product") - { - $query->where($db->qn('x.section') . ' = ' . $db->q($section)) - ->where($db->qn('x.section_id') . ' = ' . $db->q((int) $sectionId)); - } - else - { - $query->where($db->qn('x.product_id') . ' =' . $db->q((int) $sectionId)); - } - } - - if ($stockroomId != 0) - { - $query->where($db->qn('x.stockroom_id') . ' = ' . $db->q((int) $stockroomId)); - } - - $list = $db->setQuery($query)->loadObjectList(); - } - - return $list; - } - - /** - * Get pre-order stockroom amount detail list - * - * @param int $sectionId Section id - * @param string $section Section - * @param int $stockroomId Stockroom id - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function getPreorderStockroomAmountDetailList($sectionId = 0, $section = "product", $stockroomId = 0) - { - $list = array(); - - if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) - { - $table = "#__redshop_product_stockroom_xref"; - - if ($section != "product") - { - $table = "#__redshop_product_attribute_stockroom_xref"; - } - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('DISTINCT(s.stockroom_id), s.*, x.*') - ->from($db->qn($table, 'x')) - ->leftJoin( - $db->qn('#__redshop_stockroom', 's') . ' ON ' - . $db->qn('x.stockroom_id') . ' = ' . $db->qn('s.stockroom_id') - ) - ->where($db->qn('x.preorder_stock') . ' >= ' . $db->qn('x.ordered_preorder')) - ->order($db->qn('s.min_del_time')); - - if ($sectionId != 0) - { - if ($section != "product") - { - $query->where($db->qn('x.section') . ' = ' . $db->q($section)) - ->where($db->qn('x.section_id') . ' = ' . $db->q((int) $sectionId)); - } - else - { - $query->where($db->qn('x.product_id') . ' =' . $db->q((int) $sectionId)); - } - } - - if ($stockroomId != 0) - { - $query->where($db->qn('x.stockroom_id') . ' = ' . $db->q((int) $stockroomId)); - } - - $list = $db->setQuery($query)->loadObjectList(); - } - - return $list; - } - - /** - * Update stockroom quantity - * - * @param int $sectionId Section id - * @param int $quantity Stockroom quantity - * @param string $section Section - * @param int $productId Product id - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function updateStockroomQuantity($sectionId = 0, $quantity = 0, $section = "product", $productId = 0) - { - $affectedRow = array(); - $stockroomQuantity = array(); - - if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) - { - $stockrooms = self::getStockroomAmountDetailList($sectionId, $section); - - foreach ($stockrooms as $stockroom) - { - if ($stockroom->quantity < $quantity) - { - $quantity = $quantity - $stockroom->quantity; - $remainingQuantity = $stockroom->quantity; - } - else - { - $remainingQuantity = $quantity; - $quantity -= $remainingQuantity; - } - - if ($remainingQuantity > 0) - { - self::updateStockAmount($sectionId, $remainingQuantity, $stockroom->stockroom_id, $section); - $affectedRow[] = $stockroom->stockroom_id; - $stockroomQuantity[] = $remainingQuantity; - } - - $stockroomDetail = self::getStockroomAmountDetailList($sectionId, $section, $stockroom->stockroom_id); - $remaining = $stockroomDetail[0]->quantity - $quantity; - - if (Redshop::getConfig()->get('ENABLE_STOCKROOM_NOTIFICATION') == 1 - && $remaining <= Redshop::getConfig()->get('DEFAULT_STOCKROOM_BELOW_AMOUNT_NUMBER')) - { - $dispatcher = RedshopHelperUtility::getDispatcher(); - JPluginHelper::importPlugin('redshop_alert'); - $productId = ($section == "product") ? $sectionId : $productId; - $productData = Redshop::product((int) $productId); - - $message = JText::sprintf( - 'COM_REDSHOP_ALERT_STOCKROOM_BELOW_AMOUNT_NUMBER', - $productData->product_id, - $productData->product_name, - $productData->product_number, - $remaining, - $stockroomDetail[0]->stockroom_name - ); - - $dispatcher->trigger('storeAlert', array($message)); - $dispatcher->trigger('sendEmail', array($message)); - } - } - - // For pre-order stock - if ($quantity > 0) - { - $preOrderStockrooms = self::getPreorderStockroomAmountDetailList($sectionId, $section); - - if ($section == "product") - { - $productData = Redshop::product((int) $sectionId); - } - else - { - $productData = Redshop::product((int) $productId); - } - - if ($productData->preorder == "yes" || ($productData->preorder == "global" && Redshop::getConfig()->get('ALLOW_PRE_ORDER')) - || ($productData->preorder == "" && Redshop::getConfig()->get('ALLOW_PRE_ORDER'))) - { - foreach ($preOrderStockrooms as $preOrderStockroom) - { - if ($preOrderStockroom->preorder_stock < $quantity) - { - $quantity = $quantity - $preOrderStockroom->preorder_stock; - $remainingQuantity = $preOrderStockroom->preorder_stock; - } - else - { - $remainingQuantity = $quantity; - $quantity -= $remainingQuantity; - } - - if ($remainingQuantity <= 0) - { - continue; - } - - $dispatcher = RedshopHelperUtility::getDispatcher(); - JPluginHelper::importPlugin('redshop_stockroom'); - $dispatcher->trigger('onUpdateStockroomQuantity', array($section, $productData)); - self::updatePreorderStockAmount($sectionId, $remainingQuantity, $preOrderStockroom->stockroom_id, $section); - } - } - } - } - - $list = implode(",", $affectedRow); - $stockroomQuantityList = implode(",", $stockroomQuantity); - $resultArray = array(); - $resultArray['stockroom_list'] = $list; - $resultArray['stockroom_quantity_list'] = $stockroomQuantityList; - - return $resultArray; - } - - /** - * Update stockroom amount - * - * @param int $sectionId Section id - * @param int $quantity Stockroom quantity - * @param int $stockroomId Stockroom id - * @param string $section Section - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function updateStockAmount($sectionId = 0, $quantity = 0, $stockroomId = 0, $section = "product") - { - if (!Redshop::getConfig()->get('USE_STOCKROOM') || !$sectionId) - { - return true; - } - - $table = "#__redshop_product_stockroom_xref"; - - if ($section != "product") - { - $table = "#__redshop_product_attribute_stockroom_xref"; - } - - $db = JFactory::getDbo(); - - $fields = array( - $db->qn('quantity') . ' = ' . $db->qn('quantity') . ' - ' . (int) $quantity - ); - - $conditions = array( - $db->qn('stockroom_id') . ' = ' . (int) $stockroomId, - $db->qn('quantity') . ' > 0' - ); - - if ($section != "product") - { - $conditions[] = $db->qn('section') . ' = ' . $db->quote($section); - $conditions[] = $db->qn('section_id') . ' = ' . (int) $sectionId; - } - else - { - $conditions[] = $db->qn('product_id') . ' = ' . (int) $sectionId; - } - - $query = $db->getQuery(true) - ->update($db->qn($table)) - ->set($fields) - ->where($conditions); - - return $db->setQuery($query)->execute(); - } - - /** - * Update pre-order stock amount - * - * @param int $sectionId Section id - * @param int $quantity Stockroom quantity - * @param int $stockroomId Stockroom id - * @param string $section Section - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function updatePreorderStockAmount($sectionId = 0, $quantity = 0, $stockroomId = 0, $section = "product") - { - if (Redshop::getConfig()->get('USE_STOCKROOM') == 1 && $sectionId != 0 && trim($sectionId) != "") - { - $table = "#__redshop_product_stockroom_xref"; - - if ($section != "product") - { - $table = "#__redshop_product_attribute_stockroom_xref"; - } - - $db = JFactory::getDbo(); - - $fields = array( - $db->qn('ordered_preorder') . ' = ' . $db->qn('ordered_preorder') . ' + ' . $db->q((int) $quantity) - ); - - $conditions = array( - $db->qn('stockroom_id') . ' = ' . $db->q((int) $stockroomId) - ); - - if ($section != "product") - { - $conditions[] = $db->qn('section') . ' = ' . $db->q($section); - $conditions[] = $db->qn('section_id') . ' = ' . $db->q((int) $sectionId); - } - else - { - $conditions[] = $db->qn('product_id') . ' = ' . $db->q((int) $sectionId); - } - - $query = $db->getQuery(true) - ->update($db->qn($table)) - ->set($fields) - ->where($conditions); - - $db->setQuery($query)->execute(); - } - - return true; - } - - /** - * Manage stock amount - * - * @param int $sectionId Section id - * @param int $quantity Stockroom quantity - * @param int $stockroomId Stockroom id - * @param string $section Section - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function manageStockAmount($sectionId = 0, $quantity = 0, $stockroomId = 0, $section = "product") - { - if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) - { - $table = "#__redshop_product_stockroom_xref"; - - if ($section != "product") - { - $table = "#__redshop_product_attribute_stockroom_xref"; - } - - $db = JFactory::getDbo(); - $conditions = array(); - - if ($sectionId != 0 && trim($sectionId) != "") - { - if ($section != "product") - { - $conditions[] = $db->qn('section') . ' = ' . $db->q($section); - $conditions[] = $db->qn('section_id') . ' = ' . $db->q((int) $sectionId); - } - else - { - $conditions[] = $db->qn('product_id') . ' = ' . $db->q((int) $sectionId); - } - } - - $stockId = explode(",", $stockroomId); - $stockQty = explode(",", $quantity); - - for ($i = 0, $in = count($stockId); $i < $in; $i++) - { - if ($stockId[$i] != "" && $sectionId != "" && $sectionId != 0) - { - $fields = array( - $db->qn('quantity') . ' = ' . $db->qn('quantity') . ' + ' . $db->q((int) $stockQty[$i]) - ); - - $conditions[] = $db->qn('stockroom_id') . ' = ' . $db->q((int) $stockId[$i]); - - $query = $db->getQuery(true) - ->update($db->qn($table)) - ->set($fields) - ->where($conditions); - - $db->setQuery($query)->execute(); - - $affectedRow = $db->getAffectedRows(); - - if ($affectedRow > 0) - { - break; - } - } - } - } - - return true; - } - - /** - * Replace stockroom amount detail - * - * @param string $templateDesc Template content - * @param int $sectionId Section id - * @param string $section Section - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function replaceStockroomAmountDetail($templateDesc = "", $sectionId = 0, $section = "product") - { - if (strpos($templateDesc, '{stockroom_detail}') !== false) - { - $productInStock = ""; - - if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) - { - $list = self::getStockroomAmountDetailList($sectionId, $section); - - $productInStock = RedshopLayoutHelper::render( - 'product.stockroom_detail', - array( - 'stockroomDetails' => $list - ) - ); - } - - $templateDesc = str_replace('{stockroom_detail}', $productInStock, $templateDesc); - } - - return $templateDesc; - } - - /** - * Get stock amount image - * - * @param int $sectionId Section id - * @param string $section Section - * @param int $stockAmount Stockroom amount - * - * @return array - * - * @since 2.0.0.3 - */ - public static function getStockAmountImage($sectionId = 0, $section = "product", $stockAmount = 0) - { - $list = array(); - - if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('DISTINCT(sm.stock_amount_id), sm.*') - ->from($db->qn('#__redshop_stockroom_amount_image', 'sm')) - ->innerJoin( - $db->qn('#__redshop_product_stockroom_xref', 'sx') . ' ON ' - . $db->qn('sx.stockroom_id') . ' = ' . $db->qn('sm.stockroom_id') - ) - ->innerJoin( - $db->qn('#__redshop_stockroom', 's') . ' ON ' - . $db->qn('sx.stockroom_id') . ' = ' . $db->qn('s.stockroom_id') - ) - ->where($db->qn('stock_option') . ' = 2') - ->where($db->qn('stock_quantity') . ' = ' . (int) $stockAmount); - - $list = $db->setQuery($query)->loadObjectList(); - - if (count($list) <= 0) - { - $query->clear('where') - ->where($db->qn('stock_option') . ' = 1') - ->where($db->qn('stock_quantity') . ' < ' . $db->q((int) $stockAmount)) - ->order($db->qn('stock_quantity') . ' ASC') - ->order($db->qn('s.max_del_time') . ' ASC'); - - $list = $db->setQuery($query)->loadObjectList(); - - if (count($list) <= 0) - { - $query->clear('where') - ->where($db->qn('stock_option') . ' = 3') - ->where($db->qn('stock_quantity') . ' > ' . $db->q((int) $stockAmount)) - ->order($db->qn('stock_quantity') . ' ASC') - ->order($db->qn('s.max_del_time') . ' ASC'); - - $list = $db->setQuery($query)->loadObjectList(); - } - } - } - - return $list; - } - - /** - * Get reserved Stock - * - * @param int $sectionId Section id - * @param string $section Section - * - * @return integer - * - * @since 2.0.0.3 - */ - public static function getReservedStock($sectionId, $section = "product") - { - if (!Redshop::getConfig()->get('IS_PRODUCT_RESERVE') || !Redshop::getConfig()->get('USE_STOCKROOM')) - { - return 0; - } - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('SUM(qty)') - ->from($db->qn('#__redshop_cart')) - ->where($db->qn('product_id') . ' = ' . $db->q((int) $sectionId)) - ->where($db->qn('section') . ' = ' . $db->q($section)); - - return (int) $db->setQuery($query)->loadResult(); - } - - /** - * Get current User reserved stock - * - * @param int $sectionId Section id - * @param string $section Section - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function getCurrentUserReservedStock($sectionId, $section = "product") - { - if (Redshop::getConfig()->get('IS_PRODUCT_RESERVE') && Redshop::getConfig()->get('USE_STOCKROOM')) - { - $db = JFactory::getDbo(); - $sessionId = session_id(); - - $query = $db->getQuery(true) - ->select('SUM(qty)') - ->from($db->qn('#__redshop_cart')) - ->where($db->qn('product_id') . ' = ' . (int) $sectionId) - ->where($db->qn('session_id') . ' = ' . $db->q($sessionId)) - ->where($db->qn('section') . ' = ' . $db->q($section)); - - return (int) $db->setQuery($query)->loadResult(); - } - - return 0; - } - - /** - * Delete expired cart product - * - * @return boolean - * - * @since 2.0.0.3 - */ - public static function deleteExpiredCartProduct() - { - if (!Redshop::getConfig()->get('IS_PRODUCT_RESERVE') || !Redshop::getConfig()->get('USE_STOCKROOM')) - { - return false; - } - - $db = JFactory::getDBO(); - $time = time() - (Redshop::getConfig()->get('CART_TIMEOUT') * 60); - - $query = $db->getQuery(true) - ->delete($db->qn('#__redshop_cart')) - ->where($db->qn('time') . ' < ' . $db->quote($time)); - - return (boolean) $db->setQuery($query)->execute(); - } - - /** - * Delete cart after empty - * - * @param int $sectionId Section id - * @param string $section Section - * @param int $quantity Stockroom quantity - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function deleteCartAfterEmpty($sectionId = 0, $section = "product", $quantity = 0) - { - if (Redshop::getConfig()->get('IS_PRODUCT_RESERVE') && Redshop::getConfig()->get('USE_STOCKROOM')) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->where($db->qn('session_id') . ' = ' . $db->q(session_id())); - - if ($sectionId != 0) - { - $query->where($db->qn('product_id') . ' = ' . $db->q((int) $sectionId)) - ->where($db->qn('section') . ' = ' . $db->q($section)); - } - - if ($quantity) - { - $query->select($db->qn('qty')) - ->from($db->qn('#__redshop_cart')); - - $qty = (int) $db->setQuery($query)->loadResult(); - $query->clear('select') - ->clear('from'); - - if ($qty - (int) $quantity > 0) - { - $query->update($db->qn('#__redshop_cart')) - ->set($db->qn('qty') . ' = ' . $db->q(($qty - (int) $quantity))); - } - else - { - $query->delete($db->qn('#__redshop_cart')); - } - } - else - { - $query->delete($db->qn('#__redshop_cart')); - } - - $db->setQuery($query)->execute(); - } - - return true; - } - - /** - * Add reserved stock - * - * @param int $sectionId Section id - * @param int $quantity Stockroom quantity - * @param string $section Section - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function addReservedStock($sectionId, $quantity = 0, $section = "product") - { - if (Redshop::getConfig()->get('IS_PRODUCT_RESERVE') && Redshop::getConfig()->get('USE_STOCKROOM')) - { - $db = JFactory::getDBO(); - $sessionId = session_id(); - $time = time(); - - $query = $db->getQuery(true) - ->select($db->qn('qty')) - ->from($db->qn('#__redshop_cart')) - ->where($db->qn('session_id') . ' = ' . $db->q($sessionId)) - ->where($db->qn('product_id') . ' = ' . $db->q((int) $sectionId)) - ->where($db->qn('section') . ' = ' . $db->q($section)); - - $qty = $db->setQuery($query)->loadResult(); - - if ($qty !== null) - { - $query = $db->getQuery(true) - ->update($db->qn('#__redshop_cart')) - ->set($db->qn('qty') . ' = ' . $db->q((int) $quantity)) - ->set($db->qn('time') . ' = ' . $db->q($time)) - ->where($db->qn('session_id') . ' = ' . $db->q($sessionId)) - ->where($db->qn('product_id') . ' = ' . $db->q((int) $sectionId)) - ->where($db->qn('section') . ' = ' . $db->q($section)); - } - else - { - $query = $db->getQuery(true) - ->insert($db->qn('#__redshop_cart')) - ->columns(array($db->qn('session_id'), $db->qn('product_id'), $db->qn('qty'), $db->qn('time'), $db->qn('section'))) - ->values($db->q($sessionId) . ',' . $db->q((int) $sectionId) . ',' . $db->q((int) $quantity) . ',' . $db->q($time) . ',' . $db->q($section)); - } - - $db->setQuery($query)->execute(); - } - - return true; - } - - /** - * Get min delivery time - * - * @param mixed $stockroomId Stockroom id - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function getStockroomMaxDelivery($stockroomId) - { - // Sanitize ids - $stockroomId = explode(',', $stockroomId); - $stockroomId = ArrayHelper::toInteger($stockroomId); - - $db = JFactory::getDBO(); - $query = $db->getQuery(true) - ->select($db->qn('max_del_time')) - ->select($db->qn('delivery_time')) - ->from($db->qn('#__redshop_stockroom')) - ->where($db->qn('stockroom_id') . ' IN (' . implode(',', $stockroomId) . ')') - ->where($db->qn('published') . ' = 1') - ->order($db->qn('max_del_time') . ' DESC'); - - return $db->setQuery($query)->loadObjectlist(); - } - - /** - * Get date diff - * - * @param int $endDate End date - * @param int $beginDate Begin date - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function getDateDiff($endDate, $beginDate) - { - $epoch_1 = mktime(0, 0, 0, date("m", $endDate), date("d", $endDate), date("Y", $endDate)); - $epoch_2 = mktime(0, 0, 0, date("m", $beginDate), date("d", $beginDate), date("Y", $beginDate)); - $dateDiff = $epoch_1 - $epoch_2; - $fullDays = floor($dateDiff / (60 * 60 * 24)); - - return $fullDays; - } - - /** - * Get final stock of product - * - * @param int $productId Product id - * @param int $totalAtt Total attribute - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function getFinalStockofProduct($productId, $totalAtt) - { - $isStockExists = self::isStockExists($productId); - - if ($totalAtt > 0 && !$isStockExists) - { - $properties = RedshopHelperProduct_Attribute::getAttributeProperties(0, 0, $productId); - - foreach ($properties as $property) - { - $isSubpropertyStock = false; - $subProperties = RedshopHelperProduct_Attribute::getAttributeSubProperties(0, $property->property_id); - - foreach ($subProperties as $subProperty) - { - $isSubpropertyStock = self::isStockExists($subProperty->subattribute_color_id, 'subproperty'); - - if ($isSubpropertyStock) - { - $isStockExists = $isSubpropertyStock; - break; - } - } - - if ($isSubpropertyStock) - { - break; - } - else - { - $isPropertystock = self::isStockExists($property->property_id, "property"); - - if ($isPropertystock) - { - $isStockExists = $isPropertystock; - break; - } - } - } - } - - return $isStockExists; - } - - /** - * Get final pre-order stock of product - * - * @param int $productId Product id - * @param int $totalAtt Total attribute - * - * @return mixed - * - * @since 2.0.0.3 - */ - public static function getFinalPreorderStockofProduct($productId, $totalAtt) - { - $isStockExists = self::isPreorderStockExists($productId); - - if ($totalAtt > 0 && !$isStockExists) - { - $properties = RedshopHelperProduct_Attribute::getAttributeProperties(0, 0, $productId); - - foreach ($properties as $property) - { - $isSubpropertyStock = false; - $subProperties = RedshopHelperProduct_Attribute::getAttributeSubProperties(0, $property->property_id); - - foreach ($subProperties as $subProperty) - { - $isSubpropertyStock = self::isPreorderStockExists($subProperty->subattribute_color_id, 'subproperty'); - - if ($isSubpropertyStock) - { - $isStockExists = $isSubpropertyStock; - break; - } - } - - if ($isSubpropertyStock) - { - break; - } - else - { - $isPropertystock = self::isPreorderStockExists($property->property_id, "property"); - - if ($isPropertystock) - { - $isStockExists = $isPropertystock; - break; - } - } - } - } - - return $isStockExists; - } - - /** - * Get Stock Amount with Reserve - * - * @param array $sectionIds Array of section id. - * @param string $section Section - * @param int $stockroomId Stockroom id - * - * @return array - * - * @since 2.0.4 - */ - public static function getMultiSectionsStock($sectionIds = array(), $section = 'product', $stockroomId = 0) - { - if (empty($sectionIds)) - { - return array(); - } - - $quantities = array(); - $sectionIds = ArrayHelper::toInteger($sectionIds); - - if ($section == 'product' && $stockroomId == 0 && $sectionIds) - { - foreach ($sectionIds as $item) - { - $productData = Redshop::product((int) $item); - $quantities[$item] = !empty($productData->sum_quanity) ? (int) $productData->sum_quanity : 0; - } - } - else - { - if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) - { - $db = JFactory::getDbo(); - $isInfinite = (boolean) Redshop::getConfig()->get('USE_BLANK_AS_INFINITE', 0); - $query = $db->getQuery(true); - - $column = 'p.product_id'; - $table = '#__redshop_product'; - $stockTable = '#__redshop_product_stockroom_xref'; - $stockColumn = 'x.product_id'; - - if ($section == 'property') - { - $column = 'p.property_id'; - $table = '#__redshop_product_attribute_property'; - $stockTable = '#__redshop_product_attribute_stockroom_xref'; - $stockColumn = 'x.section_id'; - } - elseif ($section == 'subproperty') - { - $column = 'p.subattribute_color_id'; - $table = '#__redshop_product_subattribute_color'; - $stockTable = '#__redshop_product_attribute_stockroom_xref'; - $stockColumn = 'x.section_id'; - } - - $query->select($db->qn($column, 'id')) - ->from($db->qn($table, 'p')) - ->group($db->qn('id')); - - if ($section != 'product') - { - $query->leftJoin( - $db->qn($stockTable, 'x') . ' ON ' . $db->qn($stockColumn) . ' = ' . $db->qn($column) - . ' AND ' . $db->qn('x.section') . ' = ' . $db->quote($section) - ); - } - else - { - $query->leftJoin($db->qn($stockTable, 'x') . ' ON ' . $db->qn($stockColumn) . ' = ' . $db->qn($column)); - } - - $query->leftJoin($db->qn('#__redshop_stockroom', 's') . ' ON ' . $db->qn('s.stockroom_id') . ' = ' . $db->qn('x.stockroom_id')); - - if ($sectionIds) - { - $query->where($db->qn($column) . ' IN (' . implode(',', $sectionIds) . ')'); - } - - if (!$isInfinite) - { - $query->select($db->qn('x.quantity')) - ->where($db->qn('x.quantity') . ' >= 0'); - } - else - { - $query->select( - 'IF(SUM(' . $db->qn('x.quantity') . ') IS NULL, 1000000000, SUM(' . $db->qn('x.quantity') . ')) AS ' . $db->qn('quantity') - ); - } - - if ($stockroomId != 0) - { - $query->where($db->qn('x.stockroom_id') . ' = ' . (int) $stockroomId); - } - - $db->setQuery($query); - $results = $db->loadObjectList(); - - if (!empty($results)) - { - foreach ($results as $result) - { - $quantities[$result->id] = $result->quantity; - } - } - } - else - { - foreach ($sectionIds as $item) - { - $quantities[$item] = 1; - } - } - } - - return $quantities; - } - - /** - * Get pre-order stockroom amount with reserve - * - * @param array $sectionIds Section id - * @param string $section Section - * @param int $stockroomId Stockroom id - * - * @return mixed - * @throws Exception - * - * @since 2.0.4 - */ - public static function getMultiSectionsPreOrderStock($sectionIds = array(), $section = 'product', $stockroomId = 0) - { - if (empty($sectionIds) || !Redshop::getConfig()->getBool('USE_STOCKROOM')) - { - return array(); - } - - $stockroomId = (int) $stockroomId; - $quantities = array(); - $sectionIds = ArrayHelper::toInteger($sectionIds); - $table = $section !== 'product' ? '#__redshop_product_attribute_stockroom_xref' : '#__redshop_product_stockroom_xref'; - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('SUM(x.preorder_stock) AS preorder_stock') - ->select('SUM(x.ordered_preorder) AS ordered_preorder') - ->select($db->qn('x.section_id')) - ->from($db->qn($table, 'x')) - ->leftJoin( - $db->qn('#__redshop_stockroom', 's') . ' ON ' - . $db->qn('x.stockroom_id') . ' = ' . $db->qn('s.stockroom_id') - ) - ->order($db->qn('s.min_del_time')); - - if (!empty($sectionIds)) - { - if ($section !== 'product') - { - $query->where($db->qn('x.section') . ' = ' . $db->q($section)) - ->where($db->qn('x.section_id') . ' IN (' . implode(',', $sectionIds) . ')'); - } - else - { - $query->where($db->qn('x.product_id') . ' IN (' . implode(',', $sectionIds) . ')'); - } - } - - if ($stockroomId) - { - $query->where($db->qn('x.stockroom_id') . ' = ' . $stockroomId); - } - - $query->group($db->qn('x.section_id')); - - $results = $db->setQuery($query)->loadObjectList('section_id'); - - if (!empty($results)) - { - foreach ($results as $result) - { - if ($result->ordered_preorder == $result->preorder_stock || $result->ordered_preorder > $result->preorder_stock) - { - $quantity = 0; - } - else - { - $quantity = $result->preorder_stock - $results->ordered_preorder; - } - - $quantities[$result->section_id] = $quantity; - } - } - - return $quantities; - } + /** + * @var array + */ + public static $stock = array(); + + /** + * @var array + */ + public static $stockReserve = array(); + + /** + * Check already notified user + * + * @param int $userId User id + * @param int $productId Product id + * @param int $propertyId Property id + * @param int $subPropertyId Sub property id + * + * @return mixed + */ + public static function isAlreadyNotifiedUser($userId, $productId, $propertyId, $subPropertyId) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('id') + ->from($db->qn('#__redshop_notifystock_users')) + ->where('product_id = ' . (int)$productId) + ->where('property_id = ' . (int)$propertyId) + ->where('subproperty_id = ' . (int)$subPropertyId) + ->where('user_id = ' . (int)$userId) + ->where('notification_status = 0'); + + return $db->setQuery($query)->loadResult(); + } + + /** + * Get stockroom + * + * @param mixed $stockroomId stockroom id + * @param int $published published/unpublished + * @param boolean $isChecked checked use stockroom + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function getStockroom($stockroomId = null, $published = null, $isChecked = false) + { + /** + * Check: If "Check stockroom config" is true, skip process if stockroom config is not use stockroom. + */ + if ($isChecked === true && Redshop::getConfig()->get('USE_STOCKROOM') != 1) { + return array(); + } + + $db = JFactory::getDBO(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_stockroom')); + + // Convert stockroom ID to array + if (!empty($stockroomId)) { + if (is_string($stockroomId)) { + $stockroomId = explode(',', $stockroomId); + } elseif (is_int($stockroomId)) { + $stockroomId = array($stockroomId); + } + + $query->where($db->qn('stockroom_id') . ' IN (' . implode(',', $stockroomId) . ')'); + } + + if (!empty($published)) { + $query->where($db->qn('published') . ' = ' . $db->quote((int)$published)); + } + + return $db->setQuery($query)->loadObjectList(); + } + + /** + * Check is attribute stock exists + * + * @param int $productId Product id + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function isAttributeStockExists($productId) + { + $isStockExists = false; + $properties = RedshopHelperProduct_Attribute::getAttributeProperties(0, 0, $productId); + + foreach ($properties as $property) { + $isSubpropertyStock = false; + $subProperties = RedshopHelperProduct_Attribute::getAttributeSubProperties(0, $property->property_id); + + foreach ($subProperties as $subProperty) { + $isSubpropertyStock = self::isStockExists($subProperty->subattribute_color_id, 'subproperty'); + + if ($isSubpropertyStock) { + $isStockExists = $isSubpropertyStock; + + return $isStockExists; + } + } + + if ($isSubpropertyStock) { + return $isStockExists; + } else { + $isPropertystock = self::isStockExists($property->property_id, "property"); + + if ($isPropertystock) { + $isStockExists = $isPropertystock; + + return $isStockExists; + } + } + } + + return $isStockExists; + } + + /** + * Check is stock exists + * + * @param mixed $sectionId Section id + * @param string $section Section + * @param integer $stockroomId Stockroom id + * + * @return boolean True if exist. False otherwise. + * + * @since 2.0.0.3 + */ + public static function isStockExists($sectionId = 0, $section = "product", $stockroomId = 0) + { + if (!Redshop::getConfig()->getBool('USE_STOCKROOM')) { + return true; + } + + $stock = self::getStockAmountwithReserve($sectionId, $section, $stockroomId); + + JPluginHelper::importPlugin('redshop_product'); + RedshopHelperUtility::getDispatcher()->trigger( + 'onIsStockExists', + array($sectionId, $section, $stockroomId, &$stock) + ); + + return $stock > 0; + } + + /** + * Get Stock Amount with Reserve + * + * @param mixed $sectionId Section id + * @param string $section Section + * @param integer $stockroomId Stockroom id + * + * @return mixed + */ + public static function getStockAmountWithReserve($sectionId = 0, $section = 'product', $stockroomId = 0) + { + $quantity = 1; + + if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) { + if ($section == 'product' && $stockroomId == 0 && $sectionId) { + $sectionId = explode(',', $sectionId); + $sectionId = ArrayHelper::toInteger($sectionId); + $quantity = 0; + + foreach ($sectionId as $item) { + $productData = Redshop::product((int)$item); + + if (isset($productData->sum_quanity)) { + $quantity += $productData->sum_quanity; + } + } + } else { + $key = md5($section . '-' . $sectionId . '-' . $stockroomId); + + if (!array_key_exists($key, self::$stockReserve)) { + $table = 'product'; + $db = JFactory::getDbo(); + + if ($section != 'product') { + $table = 'product_attribute'; + } + + $query = $db->getQuery(true) + ->select('SUM(x.quantity)') + ->from($db->qn('#__redshop_' . $table . '_stockroom_xref', 'x')) + ->leftJoin($db->qn('#__redshop_stockroom', 's') . ' ON s.stockroom_id = x.stockroom_id') + ->where('x.quantity >= 0'); + + if ($sectionId != 0) { + $sectionId = explode(',', $sectionId); + $sectionId = ArrayHelper::toInteger($sectionId); + + if ($section != 'product') { + $query->where('x.section = ' . $db->quote($section)) + ->where('x.section_id IN (' . implode(',', $sectionId) . ')'); + } else { + $query->where('x.product_id IN (' . implode(',', $sectionId) . ')'); + } + } + + if ($stockroomId != 0) { + $query->where('x.stockroom_id = ' . (int)$stockroomId); + } + + self::$stockReserve[$key] = $db->setQuery($query)->loadResult(); + } + + $quantity = self::$stockReserve[$key]; + } + + $quantity = $quantity < 0 ? 0 : $quantity; + } + + if ($quantity == null) { + $quantity = (Redshop::getConfig()->get('USE_BLANK_AS_INFINITE')) ? 1000000000 : 0; + } + + return $quantity; + } + + /** + * Check is attribute pre-order stock exists + * + * @param int $productId Product id + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function isAttributePreorderStockExists($productId) + { + $properties = RedshopHelperProduct_Attribute::getAttributeProperties(0, 0, $productId); + $isPreorderStockExists = false; + + foreach ($properties as $property) { + $isSubpropertyStock = false; + $subProperties = RedshopHelperProduct_Attribute::getAttributeSubProperties(0, $property->property_id); + + foreach ($subProperties as $subProperty) { + $isSubpropertyStock = self::isPreorderStockExists($subProperty->subattribute_color_id, 'subproperty'); + + if ($isSubpropertyStock) { + $isPreorderStockExists = $isSubpropertyStock; + + return $isPreorderStockExists; + } + } + + if ($isSubpropertyStock) { + return $isPreorderStockExists; + } else { + $isPropertystock = self::isPreorderStockExists($property->property_id, "property"); + + if ($isPropertystock) { + $isPreorderStockExists = $isPropertystock; + + return $isPreorderStockExists; + } + } + } + + return $isPreorderStockExists; + } + + /** + * Check is pre-order stock exists + * + * @param int $sectionId Section id + * @param string $section Section + * @param int $stockroomId Stockroom id + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function isPreorderStockExists($sectionId = 0, $section = "product", $stockroomId = 0) + { + if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) { + $stock = self::getPreorderStockAmountwithReserve($sectionId, $section, $stockroomId); + + if ($stock > 0) { + return true; + } + + return false; + } + + return true; + } + + /** + * Get pre-order stockroom amount with reserve + * + * @param integer $sectionId Section id + * @param string $section Section + * @param integer $stockroomId Stockroom id + * + * @return integer + * + * @since 2.0.0.3 + */ + public static function getPreorderStockAmountWithReserve($sectionId = 0, $section = "product", $stockroomId = 0) + { + if (!Redshop::getConfig()->get('USE_STOCKROOM')) { + return 1; + } + + $key = md5($sectionId . '-' . $section . '-' . $stockroomId); + + if (!array_key_exists($key, self::$stock)) { + $table = "#__redshop_product_stockroom_xref"; + + if ($section != "product") { + $table = "#__redshop_product_attribute_stockroom_xref"; + } + + $db = JFactory::getDBO(); + $query = $db->getQuery(true) + ->select('SUM(x.preorder_stock) AS preorder_stock') + ->select('SUM(x.ordered_preorder) AS ordered_preorder') + ->from($db->qn($table, 'x')) + ->leftJoin( + $db->qn('#__redshop_stockroom', 's') . ' ON ' + . $db->qn('x.stockroom_id') . ' = ' . $db->qn('s.stockroom_id') + ) + ->where($db->qn('x.quantity') . ' >= 0') + ->order($db->qn('s.min_del_time')); + + if ($sectionId != 0) { + // Sanitize ids + $sectionId = explode(',', $sectionId); + $sectionId = ArrayHelper::toInteger($sectionId); + + if ($section != "product") { + $query->where($db->qn('x.section') . ' = ' . $db->q($section)) + ->where($db->qn('x.section_id') . ' IN (' . implode(',', $sectionId) . ')'); + } else { + $query->where($db->qn('x.product_id') . ' IN (' . implode(',', $sectionId) . ')'); + } + } + + if ($stockroomId != 0) { + $query->where($db->qn('x.stockroom_id') . ' = ' . $db->q((int)$stockroomId)); + } + + $preOrderStock = $db->setQuery($query)->loadObjectList(); + + if ($preOrderStock[0]->ordered_preorder == $preOrderStock[0]->preorder_stock + || $preOrderStock[0]->ordered_preorder > $preOrderStock[0]->preorder_stock) { + $quantity = 0; + } else { + $quantity = $preOrderStock[0]->preorder_stock - $preOrderStock[0]->ordered_preorder; + } + + self::$stock[$key] = $quantity; + } + + return self::$stock[$key]; + } + + /** + * Get Stockroom Total amount + * + * @param int $sectionId Section id + * @param string $section Section + * @param int $stockroomId Stockroom id + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function getStockroomTotalAmount($sectionId = 0, $section = "product", $stockroomId = 0) + { + $quantity = 1; + + if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) { + $quantity = self::getStockAmountwithReserve($sectionId, $section, $stockroomId); + $reserveQuantity = self::getReservedStock($sectionId, $section); + $quantity = $quantity - $reserveQuantity; + + if ($quantity < 0) { + $quantity = 0; + } + } + + return $quantity; + } + + /** + * Get reserved Stock + * + * @param int $sectionId Section id + * @param string $section Section + * + * @return integer + * + * @since 2.0.0.3 + */ + public static function getReservedStock($sectionId, $section = "product") + { + if (!Redshop::getConfig()->get('IS_PRODUCT_RESERVE') || !Redshop::getConfig()->get('USE_STOCKROOM')) { + return 0; + } + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('SUM(qty)') + ->from($db->qn('#__redshop_cart')) + ->where($db->qn('product_id') . ' = ' . $db->q((int)$sectionId)) + ->where($db->qn('section') . ' = ' . $db->q($section)); + + return (int)$db->setQuery($query)->loadResult(); + } + + /** + * Get pre-order stockroom total amount + * + * @param int $sectionId Section id + * @param string $section Section + * @param int $stockroomId Stockroom id + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function getPreorderStockroomTotalAmount($sectionId = 0, $section = "product", $stockroomId = 0) + { + $quantity = 1; + + if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) { + $quantity = self::getPreorderStockAmountwithReserve($sectionId, $section, $stockroomId); + + $reserveQuantity = self::getReservedStock($sectionId, $section); + $quantity = $quantity - $reserveQuantity; + + if ($quantity < 0) { + $quantity = 0; + } + } + + return $quantity; + } + + /** + * Update stockroom quantity + * + * @param int $sectionId Section id + * @param int $quantity Stockroom quantity + * @param string $section Section + * @param int $productId Product id + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function updateStockroomQuantity($sectionId = 0, $quantity = 0, $section = "product", $productId = 0) + { + $affectedRow = array(); + $stockroomQuantity = array(); + + if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) { + $stockrooms = self::getStockroomAmountDetailList($sectionId, $section); + + foreach ($stockrooms as $stockroom) { + if ($stockroom->quantity < $quantity) { + $quantity = $quantity - $stockroom->quantity; + $remainingQuantity = $stockroom->quantity; + } else { + $remainingQuantity = $quantity; + $quantity -= $remainingQuantity; + } + + if ($remainingQuantity > 0) { + self::updateStockAmount($sectionId, $remainingQuantity, $stockroom->stockroom_id, $section); + $affectedRow[] = $stockroom->stockroom_id; + $stockroomQuantity[] = $remainingQuantity; + } + + $stockroomDetail = self::getStockroomAmountDetailList($sectionId, $section, $stockroom->stockroom_id); + $remaining = $stockroomDetail[0]->quantity - $quantity; + + if (Redshop::getConfig()->get('ENABLE_STOCKROOM_NOTIFICATION') == 1 + && $remaining <= Redshop::getConfig()->get('DEFAULT_STOCKROOM_BELOW_AMOUNT_NUMBER')) { + $dispatcher = RedshopHelperUtility::getDispatcher(); + JPluginHelper::importPlugin('redshop_alert'); + $productId = ($section == "product") ? $sectionId : $productId; + $productData = Redshop::product((int)$productId); + + $message = JText::sprintf( + 'COM_REDSHOP_ALERT_STOCKROOM_BELOW_AMOUNT_NUMBER', + $productData->product_id, + $productData->product_name, + $productData->product_number, + $remaining, + $stockroomDetail[0]->stockroom_name + ); + + $dispatcher->trigger('storeAlert', array($message)); + $dispatcher->trigger('sendEmail', array($message)); + } + } + + // For pre-order stock + if ($quantity > 0) { + $preOrderStockrooms = self::getPreorderStockroomAmountDetailList($sectionId, $section); + + if ($section == "product") { + $productData = Redshop::product((int)$sectionId); + } else { + $productData = Redshop::product((int)$productId); + } + + if ($productData->preorder == "yes" || ($productData->preorder == "global" && Redshop::getConfig()->get( + 'ALLOW_PRE_ORDER' + )) + || ($productData->preorder == "" && Redshop::getConfig()->get('ALLOW_PRE_ORDER'))) { + foreach ($preOrderStockrooms as $preOrderStockroom) { + if ($preOrderStockroom->preorder_stock < $quantity) { + $quantity = $quantity - $preOrderStockroom->preorder_stock; + $remainingQuantity = $preOrderStockroom->preorder_stock; + } else { + $remainingQuantity = $quantity; + $quantity -= $remainingQuantity; + } + + if ($remainingQuantity <= 0) { + continue; + } + + $dispatcher = RedshopHelperUtility::getDispatcher(); + JPluginHelper::importPlugin('redshop_stockroom'); + $dispatcher->trigger('onUpdateStockroomQuantity', array($section, $productData)); + self::updatePreorderStockAmount( + $sectionId, + $remainingQuantity, + $preOrderStockroom->stockroom_id, + $section + ); + } + } + } + } + + $list = implode(",", $affectedRow); + $stockroomQuantityList = implode(",", $stockroomQuantity); + $resultArray = array(); + $resultArray['stockroom_list'] = $list; + $resultArray['stockroom_quantity_list'] = $stockroomQuantityList; + + return $resultArray; + } + + /** + * Get stockroom amount detail list + * + * @param int $sectionId Section id + * @param string $section Section + * @param int $stockroomId Stockroom id + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function getStockroomAmountDetailList($sectionId = 0, $section = "product", $stockroomId = 0) + { + $list = array(); + + if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) { + $table = "#__redshop_product_stockroom_xref"; + + if ($section != "product") { + $table = "#__redshop_product_attribute_stockroom_xref"; + } + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('DISTINCT(s.stockroom_id), s.*, x.*') + ->from($db->qn($table, 'x')) + ->leftJoin( + $db->qn('#__redshop_stockroom', 's') . ' ON ' + . $db->qn('x.stockroom_id') . ' = ' . $db->qn('s.stockroom_id') + ) + ->order($db->qn('s.min_del_time')); + + if ($sectionId != 0) { + if ($section != "product") { + $query->where($db->qn('x.section') . ' = ' . $db->q($section)) + ->where($db->qn('x.section_id') . ' = ' . $db->q((int)$sectionId)); + } else { + $query->where($db->qn('x.product_id') . ' =' . $db->q((int)$sectionId)); + } + } + + if ($stockroomId != 0) { + $query->where($db->qn('x.stockroom_id') . ' = ' . $db->q((int)$stockroomId)); + } + + $list = $db->setQuery($query)->loadObjectList(); + } + + return $list; + } + + /** + * Update stockroom amount + * + * @param int $sectionId Section id + * @param int $quantity Stockroom quantity + * @param int $stockroomId Stockroom id + * @param string $section Section + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function updateStockAmount($sectionId = 0, $quantity = 0, $stockroomId = 0, $section = "product") + { + if (!Redshop::getConfig()->get('USE_STOCKROOM') || !$sectionId) { + return true; + } + + $table = "#__redshop_product_stockroom_xref"; + + if ($section != "product") { + $table = "#__redshop_product_attribute_stockroom_xref"; + } + + $db = JFactory::getDbo(); + + $fields = array( + $db->qn('quantity') . ' = ' . $db->qn('quantity') . ' - ' . (int)$quantity + ); + + $conditions = array( + $db->qn('stockroom_id') . ' = ' . (int)$stockroomId, + $db->qn('quantity') . ' > 0' + ); + + if ($section != "product") { + $conditions[] = $db->qn('section') . ' = ' . $db->quote($section); + $conditions[] = $db->qn('section_id') . ' = ' . (int)$sectionId; + } else { + $conditions[] = $db->qn('product_id') . ' = ' . (int)$sectionId; + } + + $query = $db->getQuery(true) + ->update($db->qn($table)) + ->set($fields) + ->where($conditions); + + return $db->setQuery($query)->execute(); + } + + /** + * Get pre-order stockroom amount detail list + * + * @param int $sectionId Section id + * @param string $section Section + * @param int $stockroomId Stockroom id + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function getPreorderStockroomAmountDetailList($sectionId = 0, $section = "product", $stockroomId = 0) + { + $list = array(); + + if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) { + $table = "#__redshop_product_stockroom_xref"; + + if ($section != "product") { + $table = "#__redshop_product_attribute_stockroom_xref"; + } + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('DISTINCT(s.stockroom_id), s.*, x.*') + ->from($db->qn($table, 'x')) + ->leftJoin( + $db->qn('#__redshop_stockroom', 's') . ' ON ' + . $db->qn('x.stockroom_id') . ' = ' . $db->qn('s.stockroom_id') + ) + ->where($db->qn('x.preorder_stock') . ' >= ' . $db->qn('x.ordered_preorder')) + ->order($db->qn('s.min_del_time')); + + if ($sectionId != 0) { + if ($section != "product") { + $query->where($db->qn('x.section') . ' = ' . $db->q($section)) + ->where($db->qn('x.section_id') . ' = ' . $db->q((int)$sectionId)); + } else { + $query->where($db->qn('x.product_id') . ' =' . $db->q((int)$sectionId)); + } + } + + if ($stockroomId != 0) { + $query->where($db->qn('x.stockroom_id') . ' = ' . $db->q((int)$stockroomId)); + } + + $list = $db->setQuery($query)->loadObjectList(); + } + + return $list; + } + + /** + * Update pre-order stock amount + * + * @param int $sectionId Section id + * @param int $quantity Stockroom quantity + * @param int $stockroomId Stockroom id + * @param string $section Section + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function updatePreorderStockAmount( + $sectionId = 0, + $quantity = 0, + $stockroomId = 0, + $section = "product" + ) { + if (Redshop::getConfig()->get('USE_STOCKROOM') == 1 && $sectionId != 0 && trim($sectionId) != "") { + $table = "#__redshop_product_stockroom_xref"; + + if ($section != "product") { + $table = "#__redshop_product_attribute_stockroom_xref"; + } + + $db = JFactory::getDbo(); + + $fields = array( + $db->qn('ordered_preorder') . ' = ' . $db->qn('ordered_preorder') . ' + ' . $db->q((int)$quantity) + ); + + $conditions = array( + $db->qn('stockroom_id') . ' = ' . $db->q((int)$stockroomId) + ); + + if ($section != "product") { + $conditions[] = $db->qn('section') . ' = ' . $db->q($section); + $conditions[] = $db->qn('section_id') . ' = ' . $db->q((int)$sectionId); + } else { + $conditions[] = $db->qn('product_id') . ' = ' . $db->q((int)$sectionId); + } + + $query = $db->getQuery(true) + ->update($db->qn($table)) + ->set($fields) + ->where($conditions); + + $db->setQuery($query)->execute(); + } + + return true; + } + + /** + * Manage stock amount + * + * @param int $sectionId Section id + * @param int $quantity Stockroom quantity + * @param int $stockroomId Stockroom id + * @param string $section Section + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function manageStockAmount($sectionId = 0, $quantity = 0, $stockroomId = 0, $section = "product") + { + if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) { + $table = "#__redshop_product_stockroom_xref"; + + if ($section != "product") { + $table = "#__redshop_product_attribute_stockroom_xref"; + } + + $db = JFactory::getDbo(); + $conditions = array(); + + if ($sectionId != 0 && trim($sectionId) != "") { + if ($section != "product") { + $conditions[] = $db->qn('section') . ' = ' . $db->q($section); + $conditions[] = $db->qn('section_id') . ' = ' . $db->q((int)$sectionId); + } else { + $conditions[] = $db->qn('product_id') . ' = ' . $db->q((int)$sectionId); + } + } + + $stockId = explode(",", $stockroomId); + $stockQty = explode(",", $quantity); + + for ($i = 0, $in = count($stockId); $i < $in; $i++) { + if ($stockId[$i] != "" && $sectionId != "" && $sectionId != 0) { + $fields = array( + $db->qn('quantity') . ' = ' . $db->qn('quantity') . ' + ' . $db->q((int)$stockQty[$i]) + ); + + $conditions[] = $db->qn('stockroom_id') . ' = ' . $db->q((int)$stockId[$i]); + + $query = $db->getQuery(true) + ->update($db->qn($table)) + ->set($fields) + ->where($conditions); + + $db->setQuery($query)->execute(); + + $affectedRow = $db->getAffectedRows(); + + if ($affectedRow > 0) { + break; + } + } + } + } + + return true; + } + + /** + * Replace stockroom amount detail + * + * @param string $templateDesc Template content + * @param int $sectionId Section id + * @param string $section Section + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function replaceStockroomAmountDetail($templateDesc = "", $sectionId = 0, $section = "product") + { + if (strpos($templateDesc, '{stockroom_detail}') !== false) { + $productInStock = ""; + + if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) { + $list = self::getStockroomAmountDetailList($sectionId, $section); + + $productInStock = RedshopLayoutHelper::render( + 'product.stockroom_detail', + array( + 'stockroomDetails' => $list + ) + ); + } + + $templateDesc = str_replace('{stockroom_detail}', $productInStock, $templateDesc); + } + + return $templateDesc; + } + + /** + * Get stock amount image + * + * @param int $sectionId Section id + * @param string $section Section + * @param int $stockAmount Stockroom amount + * + * @return array + * + * @since 2.0.0.3 + */ + public static function getStockAmountImage($sectionId = 0, $section = "product", $stockAmount = 0) + { + $list = array(); + + if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('DISTINCT(sm.stock_amount_id), sm.*') + ->from($db->qn('#__redshop_stockroom_amount_image', 'sm')) + ->innerJoin( + $db->qn('#__redshop_product_stockroom_xref', 'sx') . ' ON ' + . $db->qn('sx.stockroom_id') . ' = ' . $db->qn('sm.stockroom_id') + ) + ->innerJoin( + $db->qn('#__redshop_stockroom', 's') . ' ON ' + . $db->qn('sx.stockroom_id') . ' = ' . $db->qn('s.stockroom_id') + ) + ->where($db->qn('stock_option') . ' = 2') + ->where($db->qn('stock_quantity') . ' = ' . (int)$stockAmount); + + $list = $db->setQuery($query)->loadObjectList(); + + if (count($list) <= 0) { + $query->clear('where') + ->where($db->qn('stock_option') . ' = 1') + ->where($db->qn('stock_quantity') . ' < ' . $db->q((int)$stockAmount)) + ->order($db->qn('stock_quantity') . ' ASC') + ->order($db->qn('s.max_del_time') . ' ASC'); + + $list = $db->setQuery($query)->loadObjectList(); + + if (count($list) <= 0) { + $query->clear('where') + ->where($db->qn('stock_option') . ' = 3') + ->where($db->qn('stock_quantity') . ' > ' . $db->q((int)$stockAmount)) + ->order($db->qn('stock_quantity') . ' ASC') + ->order($db->qn('s.max_del_time') . ' ASC'); + + $list = $db->setQuery($query)->loadObjectList(); + } + } + } + + return $list; + } + + /** + * Get current User reserved stock + * + * @param int $sectionId Section id + * @param string $section Section + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function getCurrentUserReservedStock($sectionId, $section = "product") + { + if (Redshop::getConfig()->get('IS_PRODUCT_RESERVE') && Redshop::getConfig()->get('USE_STOCKROOM')) { + $db = JFactory::getDbo(); + $sessionId = session_id(); + + $query = $db->getQuery(true) + ->select('SUM(qty)') + ->from($db->qn('#__redshop_cart')) + ->where($db->qn('product_id') . ' = ' . (int)$sectionId) + ->where($db->qn('session_id') . ' = ' . $db->q($sessionId)) + ->where($db->qn('section') . ' = ' . $db->q($section)); + + return (int)$db->setQuery($query)->loadResult(); + } + + return 0; + } + + /** + * Delete expired cart product + * + * @return boolean + * + * @since 2.0.0.3 + */ + public static function deleteExpiredCartProduct() + { + if (!Redshop::getConfig()->get('IS_PRODUCT_RESERVE') || !Redshop::getConfig()->get('USE_STOCKROOM')) { + return false; + } + + $db = JFactory::getDBO(); + $time = time() - (Redshop::getConfig()->get('CART_TIMEOUT') * 60); + + $query = $db->getQuery(true) + ->delete($db->qn('#__redshop_cart')) + ->where($db->qn('time') . ' < ' . $db->quote($time)); + + return (boolean)$db->setQuery($query)->execute(); + } + + /** + * Delete cart after empty + * + * @param int $sectionId Section id + * @param string $section Section + * @param int $quantity Stockroom quantity + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function deleteCartAfterEmpty($sectionId = 0, $section = "product", $quantity = 0) + { + if (Redshop::getConfig()->get('IS_PRODUCT_RESERVE') && Redshop::getConfig()->get('USE_STOCKROOM')) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->where($db->qn('session_id') . ' = ' . $db->q(session_id())); + + if ($sectionId != 0) { + $query->where($db->qn('product_id') . ' = ' . $db->q((int)$sectionId)) + ->where($db->qn('section') . ' = ' . $db->q($section)); + } + + if ($quantity) { + $query->select($db->qn('qty')) + ->from($db->qn('#__redshop_cart')); + + $qty = (int)$db->setQuery($query)->loadResult(); + $query->clear('select') + ->clear('from'); + + if ($qty - (int)$quantity > 0) { + $query->update($db->qn('#__redshop_cart')) + ->set($db->qn('qty') . ' = ' . $db->q(($qty - (int)$quantity))); + } else { + $query->delete($db->qn('#__redshop_cart')); + } + } else { + $query->delete($db->qn('#__redshop_cart')); + } + + $db->setQuery($query)->execute(); + } + + return true; + } + + /** + * Add reserved stock + * + * @param int $sectionId Section id + * @param int $quantity Stockroom quantity + * @param string $section Section + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function addReservedStock($sectionId, $quantity = 0, $section = "product") + { + if (Redshop::getConfig()->get('IS_PRODUCT_RESERVE') && Redshop::getConfig()->get('USE_STOCKROOM')) { + $db = JFactory::getDBO(); + $sessionId = session_id(); + $time = time(); + + $query = $db->getQuery(true) + ->select($db->qn('qty')) + ->from($db->qn('#__redshop_cart')) + ->where($db->qn('session_id') . ' = ' . $db->q($sessionId)) + ->where($db->qn('product_id') . ' = ' . $db->q((int)$sectionId)) + ->where($db->qn('section') . ' = ' . $db->q($section)); + + $qty = $db->setQuery($query)->loadResult(); + + if ($qty !== null) { + $query = $db->getQuery(true) + ->update($db->qn('#__redshop_cart')) + ->set($db->qn('qty') . ' = ' . $db->q((int)$quantity)) + ->set($db->qn('time') . ' = ' . $db->q($time)) + ->where($db->qn('session_id') . ' = ' . $db->q($sessionId)) + ->where($db->qn('product_id') . ' = ' . $db->q((int)$sectionId)) + ->where($db->qn('section') . ' = ' . $db->q($section)); + } else { + $query = $db->getQuery(true) + ->insert($db->qn('#__redshop_cart')) + ->columns( + array( + $db->qn('session_id'), + $db->qn('product_id'), + $db->qn('qty'), + $db->qn('time'), + $db->qn('section') + ) + ) + ->values( + $db->q($sessionId) . ',' . $db->q((int)$sectionId) . ',' . $db->q( + (int)$quantity + ) . ',' . $db->q($time) . ',' . $db->q($section) + ); + } + + $db->setQuery($query)->execute(); + } + + return true; + } + + /** + * Get min delivery time + * + * @param mixed $stockroomId Stockroom id + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function getStockroomMaxDelivery($stockroomId) + { + // Sanitize ids + $stockroomId = explode(',', $stockroomId); + $stockroomId = ArrayHelper::toInteger($stockroomId); + + $db = JFactory::getDBO(); + $query = $db->getQuery(true) + ->select($db->qn('max_del_time')) + ->select($db->qn('delivery_time')) + ->from($db->qn('#__redshop_stockroom')) + ->where($db->qn('stockroom_id') . ' IN (' . implode(',', $stockroomId) . ')') + ->where($db->qn('published') . ' = 1') + ->order($db->qn('max_del_time') . ' DESC'); + + return $db->setQuery($query)->loadObjectlist(); + } + + /** + * Get date diff + * + * @param int $endDate End date + * @param int $beginDate Begin date + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function getDateDiff($endDate, $beginDate) + { + $epoch_1 = mktime(0, 0, 0, date("m", $endDate), date("d", $endDate), date("Y", $endDate)); + $epoch_2 = mktime(0, 0, 0, date("m", $beginDate), date("d", $beginDate), date("Y", $beginDate)); + $dateDiff = $epoch_1 - $epoch_2; + $fullDays = floor($dateDiff / (60 * 60 * 24)); + + return $fullDays; + } + + /** + * Get final stock of product + * + * @param int $productId Product id + * @param int $totalAtt Total attribute + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function getFinalStockofProduct($productId, $totalAtt) + { + $isStockExists = self::isStockExists($productId); + + if ($totalAtt > 0 && !$isStockExists) { + $properties = RedshopHelperProduct_Attribute::getAttributeProperties(0, 0, $productId); + + foreach ($properties as $property) { + $isSubpropertyStock = false; + $subProperties = RedshopHelperProduct_Attribute::getAttributeSubProperties( + 0, + $property->property_id + ); + + foreach ($subProperties as $subProperty) { + $isSubpropertyStock = self::isStockExists($subProperty->subattribute_color_id, 'subproperty'); + + if ($isSubpropertyStock) { + $isStockExists = $isSubpropertyStock; + break; + } + } + + if ($isSubpropertyStock) { + break; + } else { + $isPropertystock = self::isStockExists($property->property_id, "property"); + + if ($isPropertystock) { + $isStockExists = $isPropertystock; + break; + } + } + } + } + + return $isStockExists; + } + + /** + * Get final pre-order stock of product + * + * @param int $productId Product id + * @param int $totalAtt Total attribute + * + * @return mixed + * + * @since 2.0.0.3 + */ + public static function getFinalPreorderStockofProduct($productId, $totalAtt) + { + $isStockExists = self::isPreorderStockExists($productId); + + if ($totalAtt > 0 && !$isStockExists) { + $properties = RedshopHelperProduct_Attribute::getAttributeProperties(0, 0, $productId); + + foreach ($properties as $property) { + $isSubpropertyStock = false; + $subProperties = RedshopHelperProduct_Attribute::getAttributeSubProperties( + 0, + $property->property_id + ); + + foreach ($subProperties as $subProperty) { + $isSubpropertyStock = self::isPreorderStockExists( + $subProperty->subattribute_color_id, + 'subproperty' + ); + + if ($isSubpropertyStock) { + $isStockExists = $isSubpropertyStock; + break; + } + } + + if ($isSubpropertyStock) { + break; + } else { + $isPropertystock = self::isPreorderStockExists($property->property_id, "property"); + + if ($isPropertystock) { + $isStockExists = $isPropertystock; + break; + } + } + } + } + + return $isStockExists; + } + + /** + * Get Stock Amount with Reserve + * + * @param array $sectionIds Array of section id. + * @param string $section Section + * @param int $stockroomId Stockroom id + * + * @return array + * + * @since 2.0.4 + */ + public static function getMultiSectionsStock($sectionIds = array(), $section = 'product', $stockroomId = 0) + { + if (empty($sectionIds)) { + return array(); + } + + $quantities = array(); + $sectionIds = ArrayHelper::toInteger($sectionIds); + + if ($section == 'product' && $stockroomId == 0 && $sectionIds) { + foreach ($sectionIds as $item) { + $productData = Redshop::product((int)$item); + $quantities[$item] = !empty($productData->sum_quanity) ? (int)$productData->sum_quanity : 0; + } + } else { + if (Redshop::getConfig()->get('USE_STOCKROOM') == 1) { + $db = JFactory::getDbo(); + $isInfinite = (boolean)Redshop::getConfig()->get('USE_BLANK_AS_INFINITE', 0); + $query = $db->getQuery(true); + + $column = 'p.product_id'; + $table = '#__redshop_product'; + $stockTable = '#__redshop_product_stockroom_xref'; + $stockColumn = 'x.product_id'; + + if ($section == 'property') { + $column = 'p.property_id'; + $table = '#__redshop_product_attribute_property'; + $stockTable = '#__redshop_product_attribute_stockroom_xref'; + $stockColumn = 'x.section_id'; + } elseif ($section == 'subproperty') { + $column = 'p.subattribute_color_id'; + $table = '#__redshop_product_subattribute_color'; + $stockTable = '#__redshop_product_attribute_stockroom_xref'; + $stockColumn = 'x.section_id'; + } + + $query->select($db->qn($column, 'id')) + ->from($db->qn($table, 'p')) + ->group($db->qn('id')); + + if ($section != 'product') { + $query->leftJoin( + $db->qn($stockTable, 'x') . ' ON ' . $db->qn($stockColumn) . ' = ' . $db->qn($column) + . ' AND ' . $db->qn('x.section') . ' = ' . $db->quote($section) + ); + } else { + $query->leftJoin( + $db->qn($stockTable, 'x') . ' ON ' . $db->qn($stockColumn) . ' = ' . $db->qn($column) + ); + } + + $query->leftJoin( + $db->qn('#__redshop_stockroom', 's') . ' ON ' . $db->qn('s.stockroom_id') . ' = ' . $db->qn( + 'x.stockroom_id' + ) + ); + + if ($sectionIds) { + $query->where($db->qn($column) . ' IN (' . implode(',', $sectionIds) . ')'); + } + + if (!$isInfinite) { + $query->select($db->qn('x.quantity')) + ->where($db->qn('x.quantity') . ' >= 0'); + } else { + $query->select( + 'IF(SUM(' . $db->qn('x.quantity') . ') IS NULL, 1000000000, SUM(' . $db->qn( + 'x.quantity' + ) . ')) AS ' . $db->qn('quantity') + ); + } + + if ($stockroomId != 0) { + $query->where($db->qn('x.stockroom_id') . ' = ' . (int)$stockroomId); + } + + $db->setQuery($query); + $results = $db->loadObjectList(); + + if (!empty($results)) { + foreach ($results as $result) { + $quantities[$result->id] = $result->quantity; + } + } + } else { + foreach ($sectionIds as $item) { + $quantities[$item] = 1; + } + } + } + + return $quantities; + } + + /** + * Get pre-order stockroom amount with reserve + * + * @param array $sectionIds Section id + * @param string $section Section + * @param int $stockroomId Stockroom id + * + * @return mixed + * @throws Exception + * + * @since 2.0.4 + */ + public static function getMultiSectionsPreOrderStock($sectionIds = array(), $section = 'product', $stockroomId = 0) + { + if (empty($sectionIds) || !Redshop::getConfig()->getBool('USE_STOCKROOM')) { + return array(); + } + + $stockroomId = (int)$stockroomId; + $quantities = array(); + $sectionIds = ArrayHelper::toInteger($sectionIds); + $table = $section !== 'product' ? '#__redshop_product_attribute_stockroom_xref' : '#__redshop_product_stockroom_xref'; + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('SUM(x.preorder_stock) AS preorder_stock') + ->select('SUM(x.ordered_preorder) AS ordered_preorder') + ->select($db->qn('x.section_id')) + ->from($db->qn($table, 'x')) + ->leftJoin( + $db->qn('#__redshop_stockroom', 's') . ' ON ' + . $db->qn('x.stockroom_id') . ' = ' . $db->qn('s.stockroom_id') + ) + ->order($db->qn('s.min_del_time')); + + if (!empty($sectionIds)) { + if ($section !== 'product') { + $query->where($db->qn('x.section') . ' = ' . $db->q($section)) + ->where($db->qn('x.section_id') . ' IN (' . implode(',', $sectionIds) . ')'); + } else { + $query->where($db->qn('x.product_id') . ' IN (' . implode(',', $sectionIds) . ')'); + } + } + + if ($stockroomId) { + $query->where($db->qn('x.stockroom_id') . ' = ' . $stockroomId); + } + + $query->group($db->qn('x.section_id')); + + $results = $db->setQuery($query)->loadObjectList('section_id'); + + if (!empty($results)) { + foreach ($results as $result) { + if ($result->ordered_preorder == $result->preorder_stock || $result->ordered_preorder > $result->preorder_stock) { + $quantity = 0; + } else { + $quantity = $result->preorder_stock - $results->ordered_preorder; + } + + $quantities[$result->section_id] = $quantity; + } + } + + return $quantities; + } } diff --git a/libraries/redshop/helper/tax.php b/libraries/redshop/helper/tax.php index aa62e0bb47a..c18c990f555 100644 --- a/libraries/redshop/helper/tax.php +++ b/libraries/redshop/helper/tax.php @@ -18,120 +18,123 @@ */ class RedshopHelperTax { - /** - * @var array - */ - protected static $vatRate = array(); - - /** - * Method for replace tags about VAT information - * - * @param string $templateData Template data. - * - * @return string - * - * @since 2.0.6 - */ - public static function replaceVatInformation($templateData) - { - if (strpos($templateData, "{vat_info}") !== false) - { - $strVat = \Redshop\Template\Helper::isApplyVat($templateData) ? - Redshop::getConfig()->get('WITH_VAT_TEXT_INFO') : Redshop::getConfig()->get('WITHOUT_VAT_TEXT_INFO'); - - $templateData = str_replace("{vat_info}", $strVat, $templateData); - } - - return $templateData; - } - - /** - * get VAT rates from product or global - * - * @param int $productId Id current product - * @param int $userId Id current user - * - * @return object|null VAT rates information - * - * @since 2.0.7 - */ - public static function getVatRates($productId = 0, $userId = 0) - { - $userId = !$userId ? JFactory::getUser()->id : $userId; - $productInfo = (object) \Redshop\Product\Product::getProductById($productId); - $taxGroupId = 0; - $session = JFactory::getSession(); - $userData = RedshopHelperUser::getVatUserInformation($userId); - $userArr = $session->get('rs_user'); - $taxGroup = Redshop::getConfig()->getInt('DEFAULT_VAT_GROUP'); - - if (!empty($userArr) && array_key_exists('vatCountry', $userArr) && !empty($userArr['taxData'])) - { - if (empty($productInfo->product_tax_group_id)) - { - $productInfo->product_tax_group_id = Redshop::getConfig()->get('DEFAULT_VAT_GROUP'); - } - - if ($userArr['vatCountry'] == $userData->country_code - && $userArr['vatState'] == $userData->state_code - && $userArr['vatGroup'] == $productInfo->product_tax_group_id) - { - return $userArr['taxData']; - } - } - - if (isset($productInfo->product_tax_group_id) && $productInfo->product_tax_group_id > 0) - { - $taxGroup = $productInfo->product_tax_group_id; - } - - $key = $taxGroup . '.' . $userId; - - if (!array_key_exists($key, self::$vatRate)) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('tr.*') - ->from($db->qn('#__redshop_tax_rate', 'tr')) - ->leftJoin($db->qn('#__redshop_tax_group', 'tg') . ' ON ' . $db->qn('tg.id') . ' = ' . $db->qn('tr.tax_group_id')) - ->leftJoin($db->qn('#__redshop_country', 'c') . ' ON ' . $db->qn('tr.tax_country') . ' = ' . $db->qn('c.country_3_code') - . ' AND ' . $db->qn('c.country_3_code') . ' = ' . $db->quote($userData->country_code) - ) - ->leftJoin($db->qn('#__redshop_state', 's') . ' ON ' . $db->qn('tr.tax_state') . ' = ' . $db->qn('s.state_3_code')) - ->where($db->qn('tg.published') . ' = 1') - ->where( - '(' . $db->qn('s.state_2_code') . ' = ' . $db->quote($userData->state_code) . ' OR ' - . '(' . $db->qn('tr.tax_state') . ' = ' . $db->quote('') - . ' OR ' . $db->qn('tr.tax_state') . ' IS NULL))' - ) - ->where( - '(' . $db->qn('tr.tax_country') . ' = ' . $db->quote($userData->country_code) . ' OR ' - . '(' . $db->qn('tr.tax_country') . ' = ' . $db->quote('') - . ' OR ' . $db->qn('tr.tax_country') . ' IS NULL))' - ) - ->where('tr.tax_group_id = ' . (int) $taxGroup) - ->order('tax_rate'); - - if (Redshop::getConfig()->get('VAT_BASED_ON') == 2) - { - $query->where('tr.is_eu_country = 1'); - } - - self::$vatRate[$key] = $db->setQuery($query)->loadObject(); - } - - $userArr['taxData'] = self::$vatRate[$key]; - $userArr['vatCountry'] = $userData->country_code; - $userArr['vatState'] = $userData->state_code; - - if (!empty($userArr['taxData'])) - { - $taxGroupId = $userArr['taxData']->tax_group_id; - } - - $userArr['vatGroup'] = $taxGroupId; - $session->set('rs_user', $userArr); - - return self::$vatRate[$key]; - } + /** + * @var array + */ + protected static $vatRate = array(); + + /** + * Method for replace tags about VAT information + * + * @param string $templateData Template data. + * + * @return string + * + * @since 2.0.6 + */ + public static function replaceVatInformation($templateData) + { + if (strpos($templateData, "{vat_info}") !== false) { + $strVat = \Redshop\Template\Helper::isApplyVat($templateData) ? + Redshop::getConfig()->get('WITH_VAT_TEXT_INFO') : Redshop::getConfig()->get('WITHOUT_VAT_TEXT_INFO'); + + $templateData = str_replace("{vat_info}", $strVat, $templateData); + } + + return $templateData; + } + + /** + * get VAT rates from product or global + * + * @param int $productId Id current product + * @param int $userId Id current user + * + * @return object|null VAT rates information + * + * @since 2.0.7 + */ + public static function getVatRates($productId = 0, $userId = 0) + { + $userId = !$userId ? JFactory::getUser()->id : $userId; + $productInfo = (object)\Redshop\Product\Product::getProductById($productId); + $taxGroupId = 0; + $session = JFactory::getSession(); + $userData = RedshopHelperUser::getVatUserInformation($userId); + $userArr = $session->get('rs_user'); + $taxGroup = Redshop::getConfig()->getInt('DEFAULT_VAT_GROUP'); + + if (!empty($userArr) && array_key_exists('vatCountry', $userArr) && !empty($userArr['taxData'])) { + if (empty($productInfo->product_tax_group_id)) { + $productInfo->product_tax_group_id = Redshop::getConfig()->get('DEFAULT_VAT_GROUP'); + } + + if ($userArr['vatCountry'] == $userData->country_code + && $userArr['vatState'] == $userData->state_code + && $userArr['vatGroup'] == $productInfo->product_tax_group_id) { + return $userArr['taxData']; + } + } + + if (isset($productInfo->product_tax_group_id) && $productInfo->product_tax_group_id > 0) { + $taxGroup = $productInfo->product_tax_group_id; + } + + $key = $taxGroup . '.' . $userId; + + if (!array_key_exists($key, self::$vatRate)) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('tr.*') + ->from($db->qn('#__redshop_tax_rate', 'tr')) + ->leftJoin( + $db->qn('#__redshop_tax_group', 'tg') . ' ON ' . $db->qn('tg.id') . ' = ' . $db->qn( + 'tr.tax_group_id' + ) + ) + ->leftJoin( + $db->qn('#__redshop_country', 'c') . ' ON ' . $db->qn('tr.tax_country') . ' = ' . $db->qn( + 'c.country_3_code' + ) + . ' AND ' . $db->qn('c.country_3_code') . ' = ' . $db->quote($userData->country_code) + ) + ->leftJoin( + $db->qn('#__redshop_state', 's') . ' ON ' . $db->qn('tr.tax_state') . ' = ' . $db->qn( + 's.state_3_code' + ) + ) + ->where($db->qn('tg.published') . ' = 1') + ->where( + '(' . $db->qn('s.state_2_code') . ' = ' . $db->quote($userData->state_code) . ' OR ' + . '(' . $db->qn('tr.tax_state') . ' = ' . $db->quote('') + . ' OR ' . $db->qn('tr.tax_state') . ' IS NULL))' + ) + ->where( + '(' . $db->qn('tr.tax_country') . ' = ' . $db->quote($userData->country_code) . ' OR ' + . '(' . $db->qn('tr.tax_country') . ' = ' . $db->quote('') + . ' OR ' . $db->qn('tr.tax_country') . ' IS NULL))' + ) + ->where('tr.tax_group_id = ' . (int)$taxGroup) + ->order('tax_rate'); + + if (Redshop::getConfig()->get('VAT_BASED_ON') == 2) { + $query->where('tr.is_eu_country = 1'); + } + + self::$vatRate[$key] = $db->setQuery($query)->loadObject(); + } + + $userArr['taxData'] = self::$vatRate[$key]; + $userArr['vatCountry'] = $userData->country_code; + $userArr['vatState'] = $userData->state_code; + + if (!empty($userArr['taxData'])) { + $taxGroupId = $userArr['taxData']->tax_group_id; + } + + $userArr['vatGroup'] = $taxGroupId; + $session->set('rs_user', $userArr); + + return self::$vatRate[$key]; + } } diff --git a/libraries/redshop/helper/template.php b/libraries/redshop/helper/template.php index 4c62972a905..7fe9c7c9af8 100644 --- a/libraries/redshop/helper/template.php +++ b/libraries/redshop/helper/template.php @@ -19,676 +19,643 @@ */ class RedshopHelperTemplate { - /** - * Template array - * - * @var array - */ - protected static $templates = array(); - - /** - * Get Template Values - * - * @param string $name Name template hint - * @param string $templateSection Template section - * @param string $descriptionSeparator Description separator - * @param string $lineSeparator Line separator - * - * @return array|string - * - * @since 2.0.0.3 - */ - public static function getTemplateValues($name, $templateSection = '', $descriptionSeparator = '-', $lineSeparator = '
    ') - { - $lang = JFactory::getLanguage(); - $path = 'template_tag'; - - if ($templateSection == 'mail') - { - $path = 'mail_template_tag'; - } - - $result = RedshopLayoutHelper::render('templates.' . $path, array('name' => $name)); - $jTextPrefix = 'COM_REDSHOP_' . strtoupper($path) . '_' . strtoupper($name) . '_'; - - if ($matches = explode('{', $result)) - { - foreach ($matches as $key => $match) - { - $str = strpos($match, '}'); - - if ($str !== false) - { - $matches[$key] = substr($match, 0, $str); - } - else - { - unset($matches[$key]); - } - } - - if (count($matches) > 0) - { - $countItems = 0; - - foreach ($matches as $match) - { - $replace = ''; - $matchFix = strtoupper(str_replace(array(' ', ':'), '_', $match)); - - if ($lang->hasKey($jTextPrefix . $matchFix)) - { - $replace = $jTextPrefix . $matchFix; - } - elseif ($lang->hasKey('COM_REDSHOP_TEMPLATE_TAG_' . $matchFix)) - { - $replace = 'COM_REDSHOP_TEMPLATE_TAG_' . $matchFix; - } - - if ($replace) - { - $result = str_replace( - '{' . $match . '}', - str_replace(array('{', '}'), array('_AA_', '_BB_'), JText::sprintf($replace, $descriptionSeparator)) . $lineSeparator, - $result - ); - - $countItems++; - } - } - - $result = str_replace(array('_AA_', '_BB_'), array('{', '}'), $result); - } - } - - return $result; - } - - /** - * Get Template Values - * - * @param string $name Name template hint - * @param string $templateSection Template section - * - * @return array - * - * @since 2.0.7 - */ - public static function getTemplateTags($name, $templateSection = '') - { - $lang = JFactory::getLanguage(); - $path = 'template_tag'; - - if ($templateSection == 'mail') - { - $path = 'mail_template_tag'; - } - - $result = RedshopLayoutHelper::render('templates.' . $path, array('name' => $name)); - $jTextPrefix = 'COM_REDSHOP_' . strtoupper($path) . '_' . strtoupper($name) . '_'; - $tags = array(); - - if ($matches = explode('{', $result)) - { - foreach ($matches as $key => $match) - { - $str = strpos($match, '}'); - - if ($str !== false) - { - $matches[$key] = substr($match, 0, $str); - } - else - { - unset($matches[$key]); - } - } - - if (count($matches) > 0) - { - foreach ($matches as $match) - { - $replace = ''; - $matchFix = strtoupper(str_replace(array(' ', ':'), '_', $match)); - - if ($lang->hasKey($jTextPrefix . $matchFix)) - { - $replace = $jTextPrefix . $matchFix; - } - elseif ($lang->hasKey('COM_REDSHOP_TEMPLATE_TAG_' . $matchFix)) - { - $replace = 'COM_REDSHOP_TEMPLATE_TAG_' . $matchFix; - } - - $tags[$match] = trim(str_replace('{' . $match . '}', '', JText::sprintf($replace, ''))); - } - } - } - - return $tags; - } - - /** - * Method to get Template - * - * @param string $section Set section Template - * @param int $templateId Template Id - * @param string $name Template Name - * - * @return array Template array or null if the query failed - * - * @since 2.0.0.3 - * - * @throws Exception - */ - public static function getTemplate($section = '', $templateId = 0, $name = "") - { - JFactory::getLanguage()->load('com_redshop', JPATH_SITE); - - $key = $section . '_' . $templateId . '_' . $name; - - if (!array_key_exists($key, self::$templates)) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_template')) - ->where($db->qn('section') . ' = ' . $db->quote($section)) - ->where($db->qn('published') . ' = 1') - ->order($db->qn('id') . ' ASC'); - - if ($templateId != 0) - { - // Sanitize ids - $arrayTid = explode(',', $templateId); - $arrayTid = ArrayHelper::toInteger($arrayTid); - - $query->where('id IN (' . implode(',', $arrayTid) . ')'); - } - - if ($name != '') - { - $query->where('name = ' . $db->quote($name)); - } - - $db->setQuery($query); - - self::$templates[$key] = $db->loadObjectList(); - - foreach (self::$templates[$key] as $index => $template) - { - $userContent = self::readTemplateFile($template->section, $template->file_name); - - if ($userContent !== false) - { - self::$templates[$key][$index]->template_desc = $userContent; - } - } - } - - return self::$templates[$key]; - } - - /** - * Method to read Template from file - * - * @param string $section Template Section - * @param string $fileName Template File Name - * - * @return string Template Content - * - * @since 2.0.0.3 - * - * @throws Exception - */ - public static function readTemplateFile($section, $fileName) - { - $filePath = self::getTemplateFilePath($section, $fileName); - - if (file_exists($filePath)) - { - $content = implode('', file($filePath)); - - return $content; - } - - return false; - } - - /** - * Method to get Template file path - * - * @param string $section Template Section - * @param string $fileName Template File Name - * - * @return string Template File Path - * - * @since 2.0.0.3 - * - * @throws Exception - */ - public static function getTemplateFilePath($section, $fileName) - { - return JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $section . '/' . $fileName . '.php'); - } - - /** - * Template View selector - * - * @param string $section Template Section - * - * @return string Template Joomla view name - * - * @since 2.0.0.3 - * - * @deprecated 2.1.0 - */ - public static function getTemplateView($section) - { - return ''; - } - - /** - * Method to parse joomla content plugin onContentPrepare event - * - * @param string $string Joomla content - * - * @return string Modified content - * - * @since 2.0.0.3 - */ - public static function parseRedshopPlugin($string = "") - { - global $context; - - $content = new stdClass; - $content->text = $string; - $temp = array(); - - JPluginHelper::importPlugin('content'); - RedshopHelperUtility::getDispatcher()->trigger('onContentPrepare', array($context, &$content, &$temp, 0)); - - return $content->text; - } - - /** - * Collect Template Sections for installation - * - * @param string $templateName Template Name - * @param boolean $setFlag Set true if you want html special character in template content - * - * @return string redSHOP Template Contents - * - * @since 2.0.0.3 - */ - public static function getInstallSectionTemplate($templateName, $setFlag = false) - { - $templateFile = JPATH_SITE . "/components/com_redshop/templates/rsdefaulttemplates/$templateName.php"; - - if (!file_exists($templateFile)) - { - return ''; - } - - $handle = fopen($templateFile, "r"); - - if ($handle === false) - { - return ''; - } - - $contents = fread($handle, filesize($templateFile)); - - if ($contents === false) - { - return ''; - } - - fclose($handle); - - if ($setFlag) - { - return "
    " . htmlspecialchars($contents) . "
    "; - } - - return $contents; - } - - /** - * Get default template content of specific template section - * - * @param string $section Template section - * @param boolean $setFlag Set true if you want html special character in template content - * - * @return string HTML of template content. - * - * @since 2.1.0 - */ - public static function getDefaultTemplateContent($section = '', $setFlag = false) - { - $templateFile = JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $section . '/default.php'); - - if (!JFile::exists($templateFile)) - { - return ''; - } - - $handle = fopen($templateFile, "r"); - $contents = fread($handle, filesize($templateFile)); - fclose($handle); - - if ($setFlag) - { - return "
    " . htmlspecialchars($contents) . "
    "; - } - - return false === $contents ? '' : $contents; - } - - /** - * Collect list of redSHOP Template - * - * @param string $sectionValue Template Section selected value - * - * @return array Template Section List options - * - * @since 2.0.0.3 - */ - public static function getTemplateSections($sectionValue = "") - { - $options = array( - 'product' => JText::_('COM_REDSHOP_PRODUCT'), - 'related_product' => JText::_('COM_REDSHOP_RELATED_PRODUCT'), - 'category' => JText::_('COM_REDSHOP_CATEGORY'), - 'manufacturer' => JText::_('COM_REDSHOP_MANUFACTURER'), - 'manufacturer_detail' => JText::_('COM_REDSHOP_MANUFACTURER_DETAIL'), - 'manufacturer_products' => JText::_('COM_REDSHOP_MANUFACTURER_PRODUCTS'), - 'newsletter' => JText::_('COM_REDSHOP_NEWSLETTER'), - 'newsletter_product' => JText::_('COM_REDSHOP_NEWSLETTER_PRODUCTS'), - 'empty_cart' => JText::_('COM_REDSHOP_EMPTY_CART'), - 'cart' => JText::_('COM_REDSHOP_CART'), - 'add_to_cart' => JText::_('COM_REDSHOP_ADD_TO_CART'), - 'catalog' => JText::_('COM_REDSHOP_CATALOG'), - 'product_sample' => JText::_('COM_REDSHOP_PRODUCT_SAMPLE'), - 'order_list' => JText::_('COM_REDSHOP_ORDER_LIST'), - 'order_detail' => JText::_('COM_REDSHOP_ORDER_DETAIL'), - 'order_receipt' => JText::_('COM_REDSHOP_ORDER_RECEIPT'), - 'review' => JText::_('COM_REDSHOP_REVIEW'), - 'frontpage_category' => JText::_('COM_REDSHOP_FRONTPAGE_CATEGORY'), - 'attribute_template' => JText::_('COM_REDSHOP_ATTRIBUTE_TEMPLATE'), - 'attributewithcart_template' => JText::_('COM_REDSHOP_ATTRIBUTE_WITH_CART_TEMPLATE'), - 'accessory_template' => JText::_('COM_REDSHOP_ACCESSORY_TEMPLATE'), - 'account_template' => JText::_('COM_REDSHOP_ACCOUNT_TEMPLATE'), - 'wishlist_template' => JText::_('COM_REDSHOP_WISHLIST_TEMPLATE'), - 'wishlist_mail_template' => JText::_('COM_REDSHOP_WISHLIST_MAIL_TEMPLATE'), - 'wrapper_template' => JText::_('COM_REDSHOP_WRAPPER_TEMPLATE'), - 'ajax_cart_detail_box' => JText::_('COM_REDSHOP_AJAX_CART_DETAIL_BOX'), - 'ajax_cart_box' => JText::_('COM_REDSHOP_AJAX_CART_BOX_TMP'), - 'ask_question_template' => JText::_('COM_REDSHOP_ASK_QUESTION_TEMPLATE'), - 'giftcard_list' => JText::_('COM_REDSHOP_GIFTCARD_LIST_TEMPLATE'), - 'giftcard' => JText::_('COM_REDSHOP_GIFTCARD_TEMPLATE'), - 'shipping_pdf' => JText::_('COM_REDSHOP_SHIPPING_PDF_TEMPLATE'), - 'clicktell_sms_message' => JText::_('COM_REDSHOP_CLICKTELL_SMS_MESSAGE'), - 'order_print' => JText::_('COM_REDSHOP_ORDER_PRINT_TEMPLATE'), - 'redproductfinder' => JText::_('COM_REDSHOP_redPRODUCTFINDER'), - 'quotation_detail' => JText::_('COM_REDSHOP_QUOTATION_DETAIL_TEMPLATE'), - 'quotation_cart' => JText::_('COM_REDSHOP_QUOTATION_CART'), - 'quotation_request' => JText::_('COM_REDSHOP_QUOTATION_REQUEST_TEMPLATE'), - 'catalogue_cart' => JText::_('COM_REDSHOP_CATALOGUE_CART_TEMPLATE'), - 'catalogue_order_detail' => JText::_('COM_REDSHOP_CATALOGUE_ORDER_DETAIL_TEMPLATE'), - 'catalogue_order_receipt' => JText::_('COM_REDSHOP_CATALOGUE_ORDER_RECEIPT_TEMPLATE'), - 'compare_product' => JText::_('COM_REDSHOP_COMPARE_PRODUCT_TEMPLATE'), - 'clickatell' => JText::_('COM_REDSHOP_CLICKATELL'), - 'redshop_payment' => JText::_('COM_REDSHOP_PAYMENT_METHOD_TEMPLATE'), - 'redshop_shipping' => JText::_('COM_REDSHOP_SHIPPING_METHOD_TEMPLATE'), - 'shippingbox' => JText::_('COM_REDSHOP_SHIPPING_BOX_TEMPLATE'), - 'onestep_checkout' => JText::_('COM_REDSHOP_ONESTEP_CHECKOUT_TEMPLATE'), - 'categoryproduct' => JText::_('COM_REDSHOP_PRODUCT_CATEGORY_TEMPLATE'), - 'change_cart_attribute' => JText::_('COM_REDSHOP_CHANGE_CART_ATTRIBUTE_TEMPLATE'), - 'checkout' => JText::_('COM_REDSHOP_CHECKOUT_TEMPLATE'), - 'product_content_template' => JText::_('COM_REDSHOP_PRODUCT_CONTENT'), - 'billing_template' => JText::_('COM_REDSHOP_BILLING_TEMPLATE'), - 'private_billing_template' => JText::_('COM_REDSHOP_PRIVATE_BILLING_TEMPLATE'), - 'company_billing_template' => JText::_('COM_REDSHOP_COMPANY_BILLING_TEMPLATE'), - 'shipping_template' => JText::_('COM_REDSHOP_SHIPPING_TEMPLATE'), - 'stock_note' => JText::_('COM_REDSHOP_STOCK_NOTE_TEMPLATE'), - 'login' => JText::_('COM_REDSHOP_LOGIN_TEMPLATE') - ); - - JPluginHelper::importPlugin('system'); - RedshopHelperUtility::getDispatcher()->trigger('onTemplateSections', array(&$options)); - - return self::prepareSectionOptions($options, $sectionValue); - } - - /** - * Collect Mail Template Section Select Option Value - * - * @param string $sectionValue Selected Section Name - * - * @return array Mail Template Select list options - * - * @since 2.0.0.3 - */ - public static function getMailSections($sectionValue = "") - { - $options = array( - 'order' => JText::_('COM_REDSHOP_ORDER_MAIL'), - 'catalogue_order' => JText::_('COM_REDSHOP_CATALOGUE_ORDER_MAIL'), - 'order_special_discount' => JText::_('COM_REDSHOP_ORDER_SPECIAL_DISCOUNT_MAIL'), - 'order_status' => JText::_('COM_REDSHOP_ORDER_STATUS_CHANGE'), - 'register' => JText::_('COM_REDSHOP_REGISTRATION_MAIL'), - 'product' => JText::_('COM_REDSHOP_PRODUCT_INFORMATION'), - 'tax_exempt_approval_mail' => JText::_('COM_REDSHOP_TAX_EXEMPT_APPROVAL_MAIL'), - 'tax_exempt_disapproval_mail' => JText::_('COM_REDSHOP_TAX_EXEMPT_DISAPPROVAL_MAIL'), - 'tax_exempt_waiting_approval_mail' => JText::_('COM_REDSHOP_TAX_EXEMPT_WAITING_APPROVAL_MAIL'), - 'catalog' => JText::_('COM_REDSHOP_CATALOG_SEND_MAIL'), - 'catalog_first_reminder' => JText::_('COM_REDSHOP_CATALOG_FIRST_REMINDER'), - 'catalog_second_reminder' => JText::_('COM_REDSHOP_CATALOG_SECOND_REMINDER'), - 'catalog_coupon_reminder' => JText::_('COM_REDSHOP_CATALOG_COUPON_REMINDER'), - 'colour_sample_first_reminder' => JText::_('COM_REDSHOP_CATALOG_SAMPLE_FIRST_REMINDER'), - 'colour_sample_second_reminder' => JText::_('COM_REDSHOP_CATALOG_SAMPLE_SECOND_REMINDER'), - 'colour_sample_third_reminder' => JText::_('COM_REDSHOP_CATALOG_SAMPLE_THIRD_REMINDER'), - 'colour_sample_coupon_reminder' => JText::_('COM_REDSHOP_CATALOG_SAMPLE_COUPON_REMINDER'), - 'first_mail_after_order_purchased' => JText::_('COM_REDSHOP_FIRST_MAIL_AFTER_ORDER_PURCHASED'), - 'second_mail_after_order_purchased' => JText::_('COM_REDSHOP_SECOND_MAIL_AFTER_ORDER_PURCHASED'), - 'third_mail_after_order_purchased' => JText::_('COM_REDSHOP_THIRD_MAIL_AFTER_ORDER_PURCHASED'), - 'economic_inoice' => JText::_('COM_REDSHOP_ECONOMIC_INVOICE'), - 'newsletter_confirmation' => JText::_('COM_REDSHOP_NEWSLETTER_CONFIRMTION'), - 'newsletter_cancellation' => JText::_('COM_REDSHOP_NEWSLETTER_CANCELLATION'), - 'mywishlist_mail' => JText::_('COM_REDSHOP_WISHLIST_MAIL'), - 'ask_question_mail' => JText::_('COM_REDSHOP_ASK_QUESTION_MAIL'), - 'downloadable_product_mail' => JText::_('COM_REDSHOP_DOWNLOADABLE_PRODUCT_MAIL'), - 'giftcard_mail' => JText::_('COM_REDSHOP_GIFTCARD_MAIL'), - 'invoice_mail' => JText::_('COM_REDSHOP_INVOICE_MAIL'), - 'quotation_mail' => JText::_('COM_REDSHOP_QUOTATION_MAIL'), - 'quotation_user_register' => JText::_('COM_REDSHOP_QUOTATION_USER_REGISTER_MAIL'), - 'request_tax_exempt_mail' => JText::_('COM_REDSHOP_REQUEST_TAX_EXEMPT_MAIL'), - 'subscription_renewal_mail' => JText::_('COM_REDSHOP_SUBSCRIPTION_RENEWAL_MAIL'), - 'review_mail' => JText::_('COM_REDSHOP_REVIEW_MAIL'), - 'notify_stock_mail' => JText::_('COM_REDSHOP_NOTIFY_STOCK'), - 'invoicefile_mail' => JText::_('COM_REDSHOP_INVOICE_FILE_MAIL') - ); - - JPluginHelper::importPlugin('system'); - RedshopHelperUtility::getDispatcher()->trigger('onMailSections', array(&$options)); - - return self::prepareSectionOptions($options, $sectionValue); - } - - /** - * Collect redSHOP costume field section select list option - * - * @param string $sectionValue Selected option Value - * - * @return array Costume field Select list options - * - * @since 2.0.0.3 - */ - public static function getFieldSections($sectionValue = "") - { - $options = array( - '1' => JText::_('COM_REDSHOP_PRODUCT'), - '2' => JText::_('COM_REDSHOP_CATEGORY'), - '7' => JText::_('COM_REDSHOP_CUSTOMER_ADDRESS'), - '8' => JText::_('COM_REDSHOP_COMPANY_ADDRESS'), - '9' => JText::_('COM_REDSHOP_COLOR_SAMPLE'), - '10' => JText::_('COM_REDSHOP_MANUFACTURER'), - '11' => JText::_('COM_REDSHOP_SHIPPING'), - '12' => JText::_('COM_REDSHOP_PRODUCT_USERFIELD'), - '13' => JText::_('COM_REDSHOP_GIFTCARD_USERFIELD'), - '14' => JText::_('COM_REDSHOP_CUSTOMER_SHIPPING_ADDRESS'), - '15' => JText::_('COM_REDSHOP_COMPANY_SHIPPING_ADDRESS'), - '17' => JText::_('COM_REDSHOP_PRODUCTFINDER_DATEPICKER'), - '16' => JText::_('COM_REDSHOP_QUOTATION'), - '18' => JText::_('COM_REDSHOP_PAYMENT_GATEWAY'), - '19' => JText::_('COM_REDSHOP_SHIPPING_GATEWAY'), - '20' => JText::_('COM_REDSHOP_ORDER') - ); - - JPluginHelper::importPlugin('system'); - RedshopHelperUtility::getDispatcher()->trigger('onFieldSection', array(&$options)); - - return self::prepareSectionOptions($options, $sectionValue); - } - - /** - * Collect Costume field type select list options - * - * @param string $sectionValue Selected field type section - * - * @return array Costume field type option list - * - * @since 2.0.0.3 - */ - public static function getFieldTypeSections($sectionValue = "") - { - $options = array( - '1' => JText::_('COM_REDSHOP_TEXT_FIELD'), - '2' => JText::_('COM_REDSHOP_TEXT_AREA'), - '3' => JText::_('COM_REDSHOP_CHECKBOX'), - '4' => JText::_('COM_REDSHOP_RADIOBOX'), - '5' => JText::_('COM_REDSHOP_SINGLE_SELECT_BOX'), - '6' => JText::_('COM_REDSHOP_MULTI_SELECT_BOX'), - '7' => JText::_('COM_REDSHOP_SELECT_COUNTRY_BOX'), - '8' => JText::_('COM_REDSHOP_WYSIWYG'), - '9' => JText::_('COM_REDSHOP_MEDIA'), - '10' => JText::_('COM_REDSHOP_DOCUMENTS'), - '11' => JText::_('COM_REDSHOP_IMAGE'), - '12' => JText::_('COM_REDSHOP_DATE_PICKER'), - '13' => JText::_('COM_REDSHOP_IMAGE_WITH_LINK'), - '15' => JText::_('COM_REDSHOP_SELECTION_BASED_ON_SELECTED_CONDITIONS'), - '16' => JText::_('COM_REDSHOP_JOOMLA_RELATED_ARTICLES') - ); - - JPluginHelper::importPlugin('system'); - RedshopHelperUtility::getDispatcher()->trigger('onFieldTypeSections', array(&$options)); - - return self::prepareSectionOptions($options, $sectionValue); - } - - /** - * Prepare Options for Select list - * - * @param array $options Associative Options array - * @param string $sectionValue Get single Section name - * - * @return mixed String or array based on $sectionValue - * - * @since 2.0.0.3 - */ - public static function prepareSectionOptions($options, $sectionValue) - { - // Sort array alphabetically - asort($options); - - $optionSection = array(); - $optionSection[] = JHtml::_('select.option', '', JText::_('COM_REDSHOP_SELECT')); - - if (empty($options)) - { - return $optionSection; - } - - foreach ($options as $key => $value) - { - $optionSection[] = JHtml::_('select.option', $key, $value); - - if ($sectionValue != "" && $key == $sectionValue) - { - return $value; - } - } - - return $optionSection; - } - - /** - * Get ExtraFields For Current Template - * - * @param array $fieldNames Field name list - * @param string $templateData Template data - * @param int $isCategoryPage Flag change extra fields in category page - * - * @return string - * - * @since 2.0.6 - */ - public static function getExtraFieldsForCurrentTemplate($fieldNames = array(), $templateData = '', $isCategoryPage = 0) - { - $prefix = '{'; - - if ($isCategoryPage) - { - $prefix = '{producttag:'; - } - - if (empty($fieldNames)) - { - return ''; - } - - $findFields = array(); - - foreach ($fieldNames as $filedName) - { - if (strpos($templateData, $prefix . $filedName . "}") !== false) - { - $findFields[] = $filedName; - } - } - - if (empty($findFields)) - { - return ''; - } - - return implode(',', RedshopHelperUtility::quote($findFields)); - } - - /** - * Method for render hints of field in specific section - * - * @param integer $fieldSection Field section. - * @param string $heading Heading. - * - * @return string - * - * @since 2.0.7 - */ - public static function renderFieldTagHints($fieldSection = 0, $heading = '') - { - $tagsSite = RedshopHelperExtrafields::getSectionFieldList($fieldSection, 1); - $tagsAdmin = RedshopHelperExtrafields::getSectionFieldList($fieldSection, 0); - $tags = array_merge((array) $tagsAdmin, (array) $tagsSite); - - $fieldTags = array(); - - foreach ($tags as $tag) - { - $fieldTags[$tag->name] = $tag->title; - } - - return RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $fieldTags, 'header' => $heading)); - } + /** + * Template array + * + * @var array + */ + protected static $templates = array(); + + /** + * Get Template Values + * + * @param string $name Name template hint + * @param string $templateSection Template section + * @param string $descriptionSeparator Description separator + * @param string $lineSeparator Line separator + * + * @return array|string + * + * @since 2.0.0.3 + */ + public static function getTemplateValues( + $name, + $templateSection = '', + $descriptionSeparator = '-', + $lineSeparator = '
    ' + ) { + $lang = JFactory::getLanguage(); + $path = 'template_tag'; + + if ($templateSection == 'mail') { + $path = 'mail_template_tag'; + } + + $result = RedshopLayoutHelper::render('templates.' . $path, array('name' => $name)); + $jTextPrefix = 'COM_REDSHOP_' . strtoupper($path) . '_' . strtoupper($name) . '_'; + + if ($matches = explode('{', $result)) { + foreach ($matches as $key => $match) { + $str = strpos($match, '}'); + + if ($str !== false) { + $matches[$key] = substr($match, 0, $str); + } else { + unset($matches[$key]); + } + } + + if (count($matches) > 0) { + $countItems = 0; + + foreach ($matches as $match) { + $replace = ''; + $matchFix = strtoupper(str_replace(array(' ', ':'), '_', $match)); + + if ($lang->hasKey($jTextPrefix . $matchFix)) { + $replace = $jTextPrefix . $matchFix; + } elseif ($lang->hasKey('COM_REDSHOP_TEMPLATE_TAG_' . $matchFix)) { + $replace = 'COM_REDSHOP_TEMPLATE_TAG_' . $matchFix; + } + + if ($replace) { + $result = str_replace( + '{' . $match . '}', + str_replace( + array('{', '}'), + array('_AA_', '_BB_'), + JText::sprintf($replace, $descriptionSeparator) + ) . $lineSeparator, + $result + ); + + $countItems++; + } + } + + $result = str_replace(array('_AA_', '_BB_'), array('{', '}'), $result); + } + } + + return $result; + } + + /** + * Get Template Values + * + * @param string $name Name template hint + * @param string $templateSection Template section + * + * @return array + * + * @since 2.0.7 + */ + public static function getTemplateTags($name, $templateSection = '') + { + $lang = JFactory::getLanguage(); + $path = 'template_tag'; + + if ($templateSection == 'mail') { + $path = 'mail_template_tag'; + } + + $result = RedshopLayoutHelper::render('templates.' . $path, array('name' => $name)); + $jTextPrefix = 'COM_REDSHOP_' . strtoupper($path) . '_' . strtoupper($name) . '_'; + $tags = array(); + + if ($matches = explode('{', $result)) { + foreach ($matches as $key => $match) { + $str = strpos($match, '}'); + + if ($str !== false) { + $matches[$key] = substr($match, 0, $str); + } else { + unset($matches[$key]); + } + } + + if (count($matches) > 0) { + foreach ($matches as $match) { + $replace = ''; + $matchFix = strtoupper(str_replace(array(' ', ':'), '_', $match)); + + if ($lang->hasKey($jTextPrefix . $matchFix)) { + $replace = $jTextPrefix . $matchFix; + } elseif ($lang->hasKey('COM_REDSHOP_TEMPLATE_TAG_' . $matchFix)) { + $replace = 'COM_REDSHOP_TEMPLATE_TAG_' . $matchFix; + } + + $tags[$match] = trim(str_replace('{' . $match . '}', '', JText::sprintf($replace, ''))); + } + } + } + + return $tags; + } + + /** + * Method to get Template + * + * @param string $section Set section Template + * @param int $templateId Template Id + * @param string $name Template Name + * + * @return array Template array or null if the query failed + * + * @throws Exception + * @since 2.0.0.3 + * + */ + public static function getTemplate($section = '', $templateId = 0, $name = "") + { + JFactory::getLanguage()->load('com_redshop', JPATH_SITE); + + $key = $section . '_' . $templateId . '_' . $name; + + if (!array_key_exists($key, self::$templates)) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_template')) + ->where($db->qn('section') . ' = ' . $db->quote($section)) + ->where($db->qn('published') . ' = 1') + ->order($db->qn('id') . ' ASC'); + + if ($templateId != 0) { + // Sanitize ids + $arrayTid = explode(',', $templateId); + $arrayTid = ArrayHelper::toInteger($arrayTid); + + $query->where('id IN (' . implode(',', $arrayTid) . ')'); + } + + if ($name != '') { + $query->where('name = ' . $db->quote($name)); + } + + $db->setQuery($query); + + self::$templates[$key] = $db->loadObjectList(); + + foreach (self::$templates[$key] as $index => $template) { + $userContent = self::readTemplateFile($template->section, $template->file_name); + + if ($userContent !== false) { + self::$templates[$key][$index]->template_desc = $userContent; + } + } + } + + return self::$templates[$key]; + } + + /** + * Method to read Template from file + * + * @param string $section Template Section + * @param string $fileName Template File Name + * + * @return string Template Content + * + * @throws Exception + * @since 2.0.0.3 + * + */ + public static function readTemplateFile($section, $fileName) + { + $filePath = self::getTemplateFilePath($section, $fileName); + + if (file_exists($filePath)) { + $content = implode('', file($filePath)); + + return $content; + } + + return false; + } + + /** + * Method to get Template file path + * + * @param string $section Template Section + * @param string $fileName Template File Name + * + * @return string Template File Path + * + * @throws Exception + * @since 2.0.0.3 + * + */ + public static function getTemplateFilePath($section, $fileName) + { + return JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $section . '/' . $fileName . '.php'); + } + + /** + * Template View selector + * + * @param string $section Template Section + * + * @return string Template Joomla view name + * + * @since 2.0.0.3 + * + * @deprecated 2.1.0 + */ + public static function getTemplateView($section) + { + return ''; + } + + /** + * Method to parse joomla content plugin onContentPrepare event + * + * @param string $string Joomla content + * + * @return string Modified content + * + * @since 2.0.0.3 + */ + public static function parseRedshopPlugin($string = "") + { + global $context; + + $content = new stdClass; + $content->text = $string; + $temp = array(); + + JPluginHelper::importPlugin('content'); + RedshopHelperUtility::getDispatcher()->trigger('onContentPrepare', array($context, &$content, &$temp, 0)); + + return $content->text; + } + + /** + * Collect Template Sections for installation + * + * @param string $templateName Template Name + * @param boolean $setFlag Set true if you want html special character in template content + * + * @return string redSHOP Template Contents + * + * @since 2.0.0.3 + */ + public static function getInstallSectionTemplate($templateName, $setFlag = false) + { + $templateFile = JPATH_SITE . "/components/com_redshop/templates/rsdefaulttemplates/$templateName.php"; + + if (!file_exists($templateFile)) { + return ''; + } + + $handle = fopen($templateFile, "r"); + + if ($handle === false) { + return ''; + } + + $contents = fread($handle, filesize($templateFile)); + + if ($contents === false) { + return ''; + } + + fclose($handle); + + if ($setFlag) { + return "
    " . htmlspecialchars($contents) . "
    "; + } + + return $contents; + } + + /** + * Get default template content of specific template section + * + * @param string $section Template section + * @param boolean $setFlag Set true if you want html special character in template content + * + * @return string HTML of template content. + * + * @since 2.1.0 + */ + public static function getDefaultTemplateContent($section = '', $setFlag = false) + { + $templateFile = JPath::clean(JPATH_REDSHOP_TEMPLATE . '/' . $section . '/default.php'); + + if (!JFile::exists($templateFile)) { + return ''; + } + + $handle = fopen($templateFile, "r"); + $contents = fread($handle, filesize($templateFile)); + fclose($handle); + + if ($setFlag) { + return "
    " . htmlspecialchars($contents) . "
    "; + } + + return false === $contents ? '' : $contents; + } + + /** + * Collect list of redSHOP Template + * + * @param string $sectionValue Template Section selected value + * + * @return array Template Section List options + * + * @since 2.0.0.3 + */ + public static function getTemplateSections($sectionValue = "") + { + $options = array( + 'product' => JText::_('COM_REDSHOP_PRODUCT'), + 'related_product' => JText::_('COM_REDSHOP_RELATED_PRODUCT'), + 'category' => JText::_('COM_REDSHOP_CATEGORY'), + 'manufacturer' => JText::_('COM_REDSHOP_MANUFACTURER'), + 'manufacturer_detail' => JText::_('COM_REDSHOP_MANUFACTURER_DETAIL'), + 'manufacturer_products' => JText::_('COM_REDSHOP_MANUFACTURER_PRODUCTS'), + 'newsletter' => JText::_('COM_REDSHOP_NEWSLETTER'), + 'newsletter_product' => JText::_('COM_REDSHOP_NEWSLETTER_PRODUCTS'), + 'empty_cart' => JText::_('COM_REDSHOP_EMPTY_CART'), + 'cart' => JText::_('COM_REDSHOP_CART'), + 'add_to_cart' => JText::_('COM_REDSHOP_ADD_TO_CART'), + 'catalog' => JText::_('COM_REDSHOP_CATALOG'), + 'product_sample' => JText::_('COM_REDSHOP_PRODUCT_SAMPLE'), + 'order_list' => JText::_('COM_REDSHOP_ORDER_LIST'), + 'order_detail' => JText::_('COM_REDSHOP_ORDER_DETAIL'), + 'order_receipt' => JText::_('COM_REDSHOP_ORDER_RECEIPT'), + 'review' => JText::_('COM_REDSHOP_REVIEW'), + 'frontpage_category' => JText::_('COM_REDSHOP_FRONTPAGE_CATEGORY'), + 'attribute_template' => JText::_('COM_REDSHOP_ATTRIBUTE_TEMPLATE'), + 'attributewithcart_template' => JText::_('COM_REDSHOP_ATTRIBUTE_WITH_CART_TEMPLATE'), + 'accessory_template' => JText::_('COM_REDSHOP_ACCESSORY_TEMPLATE'), + 'account_template' => JText::_('COM_REDSHOP_ACCOUNT_TEMPLATE'), + 'wishlist_template' => JText::_('COM_REDSHOP_WISHLIST_TEMPLATE'), + 'wishlist_mail_template' => JText::_('COM_REDSHOP_WISHLIST_MAIL_TEMPLATE'), + 'wrapper_template' => JText::_('COM_REDSHOP_WRAPPER_TEMPLATE'), + 'ajax_cart_detail_box' => JText::_('COM_REDSHOP_AJAX_CART_DETAIL_BOX'), + 'ajax_cart_box' => JText::_('COM_REDSHOP_AJAX_CART_BOX_TMP'), + 'ask_question_template' => JText::_('COM_REDSHOP_ASK_QUESTION_TEMPLATE'), + 'giftcard_list' => JText::_('COM_REDSHOP_GIFTCARD_LIST_TEMPLATE'), + 'giftcard' => JText::_('COM_REDSHOP_GIFTCARD_TEMPLATE'), + 'shipping_pdf' => JText::_('COM_REDSHOP_SHIPPING_PDF_TEMPLATE'), + 'clicktell_sms_message' => JText::_('COM_REDSHOP_CLICKTELL_SMS_MESSAGE'), + 'order_print' => JText::_('COM_REDSHOP_ORDER_PRINT_TEMPLATE'), + 'redproductfinder' => JText::_('COM_REDSHOP_redPRODUCTFINDER'), + 'quotation_detail' => JText::_('COM_REDSHOP_QUOTATION_DETAIL_TEMPLATE'), + 'quotation_cart' => JText::_('COM_REDSHOP_QUOTATION_CART'), + 'quotation_request' => JText::_('COM_REDSHOP_QUOTATION_REQUEST_TEMPLATE'), + 'catalogue_cart' => JText::_('COM_REDSHOP_CATALOGUE_CART_TEMPLATE'), + 'catalogue_order_detail' => JText::_('COM_REDSHOP_CATALOGUE_ORDER_DETAIL_TEMPLATE'), + 'catalogue_order_receipt' => JText::_('COM_REDSHOP_CATALOGUE_ORDER_RECEIPT_TEMPLATE'), + 'compare_product' => JText::_('COM_REDSHOP_COMPARE_PRODUCT_TEMPLATE'), + 'clickatell' => JText::_('COM_REDSHOP_CLICKATELL'), + 'redshop_payment' => JText::_('COM_REDSHOP_PAYMENT_METHOD_TEMPLATE'), + 'redshop_shipping' => JText::_('COM_REDSHOP_SHIPPING_METHOD_TEMPLATE'), + 'shippingbox' => JText::_('COM_REDSHOP_SHIPPING_BOX_TEMPLATE'), + 'onestep_checkout' => JText::_('COM_REDSHOP_ONESTEP_CHECKOUT_TEMPLATE'), + 'categoryproduct' => JText::_('COM_REDSHOP_PRODUCT_CATEGORY_TEMPLATE'), + 'change_cart_attribute' => JText::_('COM_REDSHOP_CHANGE_CART_ATTRIBUTE_TEMPLATE'), + 'checkout' => JText::_('COM_REDSHOP_CHECKOUT_TEMPLATE'), + 'product_content_template' => JText::_('COM_REDSHOP_PRODUCT_CONTENT'), + 'billing_template' => JText::_('COM_REDSHOP_BILLING_TEMPLATE'), + 'private_billing_template' => JText::_('COM_REDSHOP_PRIVATE_BILLING_TEMPLATE'), + 'company_billing_template' => JText::_('COM_REDSHOP_COMPANY_BILLING_TEMPLATE'), + 'shipping_template' => JText::_('COM_REDSHOP_SHIPPING_TEMPLATE'), + 'stock_note' => JText::_('COM_REDSHOP_STOCK_NOTE_TEMPLATE'), + 'login' => JText::_('COM_REDSHOP_LOGIN_TEMPLATE') + ); + + JPluginHelper::importPlugin('system'); + RedshopHelperUtility::getDispatcher()->trigger('onTemplateSections', array(&$options)); + + return self::prepareSectionOptions($options, $sectionValue); + } + + /** + * Prepare Options for Select list + * + * @param array $options Associative Options array + * @param string $sectionValue Get single Section name + * + * @return mixed String or array based on $sectionValue + * + * @since 2.0.0.3 + */ + public static function prepareSectionOptions($options, $sectionValue) + { + // Sort array alphabetically + asort($options); + + $optionSection = array(); + $optionSection[] = JHtml::_('select.option', '', JText::_('COM_REDSHOP_SELECT')); + + if (empty($options)) { + return $optionSection; + } + + foreach ($options as $key => $value) { + $optionSection[] = JHtml::_('select.option', $key, $value); + + if ($sectionValue != "" && $key == $sectionValue) { + return $value; + } + } + + return $optionSection; + } + + /** + * Collect Mail Template Section Select Option Value + * + * @param string $sectionValue Selected Section Name + * + * @return array Mail Template Select list options + * + * @since 2.0.0.3 + */ + public static function getMailSections($sectionValue = "") + { + $options = array( + 'order' => JText::_('COM_REDSHOP_ORDER_MAIL'), + 'catalogue_order' => JText::_('COM_REDSHOP_CATALOGUE_ORDER_MAIL'), + 'order_special_discount' => JText::_('COM_REDSHOP_ORDER_SPECIAL_DISCOUNT_MAIL'), + 'order_status' => JText::_('COM_REDSHOP_ORDER_STATUS_CHANGE'), + 'register' => JText::_('COM_REDSHOP_REGISTRATION_MAIL'), + 'product' => JText::_('COM_REDSHOP_PRODUCT_INFORMATION'), + 'tax_exempt_approval_mail' => JText::_('COM_REDSHOP_TAX_EXEMPT_APPROVAL_MAIL'), + 'tax_exempt_disapproval_mail' => JText::_('COM_REDSHOP_TAX_EXEMPT_DISAPPROVAL_MAIL'), + 'tax_exempt_waiting_approval_mail' => JText::_('COM_REDSHOP_TAX_EXEMPT_WAITING_APPROVAL_MAIL'), + 'catalog' => JText::_('COM_REDSHOP_CATALOG_SEND_MAIL'), + 'catalog_first_reminder' => JText::_('COM_REDSHOP_CATALOG_FIRST_REMINDER'), + 'catalog_second_reminder' => JText::_('COM_REDSHOP_CATALOG_SECOND_REMINDER'), + 'catalog_coupon_reminder' => JText::_('COM_REDSHOP_CATALOG_COUPON_REMINDER'), + 'colour_sample_first_reminder' => JText::_('COM_REDSHOP_CATALOG_SAMPLE_FIRST_REMINDER'), + 'colour_sample_second_reminder' => JText::_('COM_REDSHOP_CATALOG_SAMPLE_SECOND_REMINDER'), + 'colour_sample_third_reminder' => JText::_('COM_REDSHOP_CATALOG_SAMPLE_THIRD_REMINDER'), + 'colour_sample_coupon_reminder' => JText::_('COM_REDSHOP_CATALOG_SAMPLE_COUPON_REMINDER'), + 'first_mail_after_order_purchased' => JText::_('COM_REDSHOP_FIRST_MAIL_AFTER_ORDER_PURCHASED'), + 'second_mail_after_order_purchased' => JText::_('COM_REDSHOP_SECOND_MAIL_AFTER_ORDER_PURCHASED'), + 'third_mail_after_order_purchased' => JText::_('COM_REDSHOP_THIRD_MAIL_AFTER_ORDER_PURCHASED'), + 'economic_inoice' => JText::_('COM_REDSHOP_ECONOMIC_INVOICE'), + 'newsletter_confirmation' => JText::_('COM_REDSHOP_NEWSLETTER_CONFIRMTION'), + 'newsletter_cancellation' => JText::_('COM_REDSHOP_NEWSLETTER_CANCELLATION'), + 'mywishlist_mail' => JText::_('COM_REDSHOP_WISHLIST_MAIL'), + 'ask_question_mail' => JText::_('COM_REDSHOP_ASK_QUESTION_MAIL'), + 'downloadable_product_mail' => JText::_('COM_REDSHOP_DOWNLOADABLE_PRODUCT_MAIL'), + 'giftcard_mail' => JText::_('COM_REDSHOP_GIFTCARD_MAIL'), + 'invoice_mail' => JText::_('COM_REDSHOP_INVOICE_MAIL'), + 'quotation_mail' => JText::_('COM_REDSHOP_QUOTATION_MAIL'), + 'quotation_user_register' => JText::_('COM_REDSHOP_QUOTATION_USER_REGISTER_MAIL'), + 'request_tax_exempt_mail' => JText::_('COM_REDSHOP_REQUEST_TAX_EXEMPT_MAIL'), + 'subscription_renewal_mail' => JText::_('COM_REDSHOP_SUBSCRIPTION_RENEWAL_MAIL'), + 'review_mail' => JText::_('COM_REDSHOP_REVIEW_MAIL'), + 'notify_stock_mail' => JText::_('COM_REDSHOP_NOTIFY_STOCK'), + 'invoicefile_mail' => JText::_('COM_REDSHOP_INVOICE_FILE_MAIL') + ); + + JPluginHelper::importPlugin('system'); + RedshopHelperUtility::getDispatcher()->trigger('onMailSections', array(&$options)); + + return self::prepareSectionOptions($options, $sectionValue); + } + + /** + * Collect redSHOP costume field section select list option + * + * @param string $sectionValue Selected option Value + * + * @return array Costume field Select list options + * + * @since 2.0.0.3 + */ + public static function getFieldSections($sectionValue = "") + { + $options = array( + '1' => JText::_('COM_REDSHOP_PRODUCT'), + '2' => JText::_('COM_REDSHOP_CATEGORY'), + '7' => JText::_('COM_REDSHOP_CUSTOMER_ADDRESS'), + '8' => JText::_('COM_REDSHOP_COMPANY_ADDRESS'), + '9' => JText::_('COM_REDSHOP_COLOR_SAMPLE'), + '10' => JText::_('COM_REDSHOP_MANUFACTURER'), + '11' => JText::_('COM_REDSHOP_SHIPPING'), + '12' => JText::_('COM_REDSHOP_PRODUCT_USERFIELD'), + '13' => JText::_('COM_REDSHOP_GIFTCARD_USERFIELD'), + '14' => JText::_('COM_REDSHOP_CUSTOMER_SHIPPING_ADDRESS'), + '15' => JText::_('COM_REDSHOP_COMPANY_SHIPPING_ADDRESS'), + '17' => JText::_('COM_REDSHOP_PRODUCTFINDER_DATEPICKER'), + '16' => JText::_('COM_REDSHOP_QUOTATION'), + '18' => JText::_('COM_REDSHOP_PAYMENT_GATEWAY'), + '19' => JText::_('COM_REDSHOP_SHIPPING_GATEWAY'), + '20' => JText::_('COM_REDSHOP_ORDER') + ); + + JPluginHelper::importPlugin('system'); + RedshopHelperUtility::getDispatcher()->trigger('onFieldSection', array(&$options)); + + return self::prepareSectionOptions($options, $sectionValue); + } + + /** + * Collect Costume field type select list options + * + * @param string $sectionValue Selected field type section + * + * @return array Costume field type option list + * + * @since 2.0.0.3 + */ + public static function getFieldTypeSections($sectionValue = "") + { + $options = array( + '1' => JText::_('COM_REDSHOP_TEXT_FIELD'), + '2' => JText::_('COM_REDSHOP_TEXT_AREA'), + '3' => JText::_('COM_REDSHOP_CHECKBOX'), + '4' => JText::_('COM_REDSHOP_RADIOBOX'), + '5' => JText::_('COM_REDSHOP_SINGLE_SELECT_BOX'), + '6' => JText::_('COM_REDSHOP_MULTI_SELECT_BOX'), + '7' => JText::_('COM_REDSHOP_SELECT_COUNTRY_BOX'), + '8' => JText::_('COM_REDSHOP_WYSIWYG'), + '9' => JText::_('COM_REDSHOP_MEDIA'), + '10' => JText::_('COM_REDSHOP_DOCUMENTS'), + '11' => JText::_('COM_REDSHOP_IMAGE'), + '12' => JText::_('COM_REDSHOP_DATE_PICKER'), + '13' => JText::_('COM_REDSHOP_IMAGE_WITH_LINK'), + '15' => JText::_('COM_REDSHOP_SELECTION_BASED_ON_SELECTED_CONDITIONS'), + '16' => JText::_('COM_REDSHOP_JOOMLA_RELATED_ARTICLES') + ); + + JPluginHelper::importPlugin('system'); + RedshopHelperUtility::getDispatcher()->trigger('onFieldTypeSections', array(&$options)); + + return self::prepareSectionOptions($options, $sectionValue); + } + + /** + * Get ExtraFields For Current Template + * + * @param array $fieldNames Field name list + * @param string $templateData Template data + * @param int $isCategoryPage Flag change extra fields in category page + * + * @return string + * + * @since 2.0.6 + */ + public static function getExtraFieldsForCurrentTemplate( + $fieldNames = array(), + $templateData = '', + $isCategoryPage = 0 + ) { + $prefix = '{'; + + if ($isCategoryPage) { + $prefix = '{producttag:'; + } + + if (empty($fieldNames)) { + return ''; + } + + $findFields = array(); + + foreach ($fieldNames as $filedName) { + if (strpos($templateData, $prefix . $filedName . "}") !== false) { + $findFields[] = $filedName; + } + } + + if (empty($findFields)) { + return ''; + } + + return implode(',', RedshopHelperUtility::quote($findFields)); + } + + /** + * Method for render hints of field in specific section + * + * @param integer $fieldSection Field section. + * @param string $heading Heading. + * + * @return string + * + * @since 2.0.7 + */ + public static function renderFieldTagHints($fieldSection = 0, $heading = '') + { + $tagsSite = RedshopHelperExtrafields::getSectionFieldList($fieldSection, 1); + $tagsAdmin = RedshopHelperExtrafields::getSectionFieldList($fieldSection, 0); + $tags = array_merge((array)$tagsAdmin, (array)$tagsSite); + + $fieldTags = array(); + + foreach ($tags as $tag) { + $fieldTags[$tag->name] = $tag->title; + } + + return RedshopLayoutHelper::render('templates.tags_hint', array('tags' => $fieldTags, 'header' => $heading)); + } } diff --git a/libraries/redshop/helper/text.php b/libraries/redshop/helper/text.php index 94562aead10..68dbadb8aba 100644 --- a/libraries/redshop/helper/text.php +++ b/libraries/redshop/helper/text.php @@ -18,88 +18,82 @@ */ class RedshopHelperText { - /** - * @var array - */ - protected static $data = array(); + /** + * @var array + */ + protected static $data = array(); - /** - * Get data of text library - * - * @param string $section Section of text library - * - * @return array - * - * @since 2.0.3 - */ - public static function getTextLibraryData($section = null) - { - $key = null === $section ? '0' : $section; + /** + * Get array of tag for text library + * + * @return array + * + * @since 2.0.3 + */ + public static function getTextLibraryTagArray() + { + $result = array(); + $textData = self::getTextLibraryData(); - if (!array_key_exists($key, self::$data)) - { - $db = JFactory::getDbo(); + if (!empty($textData)) { + foreach ($textData as $oneData) { + $result[] = $oneData->name; + } + } - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_textlibrary')) - ->where($db->qn('published') . ' = 1'); + return $result; + } - if (null !== $section) - { - $query->where($db->qn('section') . ' = ' . $db->q($section)); - } + /** + * Get data of text library + * + * @param string $section Section of text library + * + * @return array + * + * @since 2.0.3 + */ + public static function getTextLibraryData($section = null) + { + $key = null === $section ? '0' : $section; - self::$data[$key] = $db->setQuery($query)->loadObjectList(); - } + if (!array_key_exists($key, self::$data)) { + $db = JFactory::getDbo(); - return self::$data[$key]; - } + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_textlibrary')) + ->where($db->qn('published') . ' = 1'); - /** - * Get array of tag for text library - * - * @return array - * - * @since 2.0.3 - */ - public static function getTextLibraryTagArray() - { - $result = array(); - $textData = self::getTextLibraryData(); + if (null !== $section) { + $query->where($db->qn('section') . ' = ' . $db->q($section)); + } - if (!empty($textData)) - { - foreach ($textData as $oneData) - { - $result[] = $oneData->name; - } - } + self::$data[$key] = $db->setQuery($query)->loadObjectList(); + } - return $result; - } + return self::$data[$key]; + } - /** - * Replace data with data of text library - * - * @param string $data Data to replace with - * - * @return string - * - * @since 2.0.3 - */ - public static function replaceTexts($data) - { - $textData = self::getTextLibraryData(); + /** + * Replace data with data of text library + * + * @param string $data Data to replace with + * + * @return string + * + * @since 2.0.3 + */ + public static function replaceTexts($data) + { + $textData = self::getTextLibraryData(); - if (!empty($textData)) - { - foreach ($textData as $oneData) - { - $data = str_replace("{" . $oneData->name . "}", $oneData->content, $data); - } - } + if (!empty($textData)) { + foreach ($textData as $oneData) { + $data = str_replace("{" . $oneData->name . "}", $oneData->content, $data); + } + } - return $data; - } + return $data; + } } diff --git a/libraries/redshop/helper/user.php b/libraries/redshop/helper/user.php index 8c347dd343e..fb181b146a1 100644 --- a/libraries/redshop/helper/user.php +++ b/libraries/redshop/helper/user.php @@ -39,178 +39,6 @@ class RedshopHelperUser */ protected static $totalSales = array(); - /** - * Get redshop user information - * - * @param int $userId Id joomla user - * @param string $addressType Type user address BT (Billing Type) or ST (Shipping Type) - * @param int $userInfoId Id redshop user - * @param bool $useAddressType Select user info relate with address type - * @param bool $force Force to get user information from DB instead of cache - * - * @return object Redshop user information - */ - public static function getUserInformation( - $userId = 0, - $addressType = 'BT', - $userInfoId = 0, - $useAddressType = true, - $force = false - ) { - if (0 == $userId && 0 == $userInfoId) { - $userId = JFactory::getUser()->id; - $auth = JFactory::getSession()->get('auth'); - $userInfoId = $auth['users_info_id']; - } - - // If both is not set return, as we also have silent user creating where joomla user id is not set - if (!$userId && !$userInfoId) { - return (new stdClass); - } - - if (!$useAddressType) { - $addressType = 'NA'; - } elseif ($addressType == '') { - $addressType = 'BT'; - } - - $key = $userId . '.' . $addressType . '.' . $userInfoId; - - if (!array_key_exists($key, self::$redshopUserInfo) || $force) { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select(array('sh.*', 'u.*')) - ->from($db->qn('#__redshop_users_info', 'u')) - ->leftJoin($db->qn('#__redshop_shopper_group', 'sh') . ' ON sh.shopper_group_id = u.shopper_group_id'); - - // Not necessary that all user is registered with joomla id. We have silent user creation too. - if ($userId) { - $query->where('u.user_id = ' . (int)$userId); - } - - if ($useAddressType) { - $query->where('u.address_type = ' . $db->quote($addressType)); - } - - if ($userInfoId) { - $query->where('u.users_info_id = ' . (int)$userInfoId); - } - - self::$redshopUserInfo[$key] = $db->setQuery($query)->loadObject(); - } - - return self::$redshopUserInfo[$key]; - } - - /** - * Create redshop user session - * - * @param int $userId Joomla user id - * - * @return array|mixed - */ - public static function createUserSession($userId = 0) - { - $session = JFactory::getSession(); - $userArr = $session->get('rs_user'); - - if (!$userId) { - $userId = JFactory::getUser()->id; - } - - if (empty($userArr)) { - $userArr = array(); - } - - $userArr['rs_userid'] = $userId; - - if ($userId) { - $userArr['rs_is_user_login'] = 1; - - if (!isset($userArr['rs_user_info_id'])) { - $userInformation = self::getUserInformation($userId); - $shippingAddress = RedshopHelperOrder::getShippingAddress($userId); - - if (count($shippingAddress) > 0 && Redshop::getConfig()->get('CALCULATE_VAT_ON') == 'ST') { - $redshopUserInforId = $shippingAddress[0]->users_info_id; - $userInformation = self::getUserInformation($userId, 'ST', $redshopUserInforId); - } - - $userArr['rs_user_info_id'] = isset($userInformation->users_info_id) ? $userInformation->users_info_id : 0; - } - } else { - $userArr['rs_is_user_login'] = 0; - } - - $userArr['rs_user_shopperGroup'] = self::getShopperGroup($userId); - $session->set('rs_user', $userArr); - - return $userArr; - } - - /** - * Replace Conditional tag from Redshop tax - * - * @param integer $userId User identifier - * - * @return integer User group - */ - public static function getShopperGroup($userId = 0) - { - $shopperGroupData = self::getShopperGroupData($userId); - - if (!is_null($shopperGroupData)) { - return $shopperGroupData->shopper_group_id; - } - - return Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_UNREGISTERED'); - } - - /** - * Get Shopper Group Data - * - * @param int $userId User id - * - * @return mixed - */ - public static function getShopperGroupData($userId = 0) - { - $userId = !$userId ? JFactory::getUser()->id : $userId; - - // If user is guest. Try to get redshop user id. - if (!$userId) { - $auth = JFactory::getSession()->get('auth'); - - if (is_array($auth) && array_key_exists('users_info_id', $auth)) { - $userId -= $auth['users_info_id']; - } - } - - // In case user doesn't not entered any information yet. Get from default config. - if (!$userId) { - $shopperGroupId = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_UNREGISTERED'); - - return RedshopEntityShopper_Group::getInstance($shopperGroupId)->getItem(); - } - - // In case user is not guest. - if (!array_key_exists($userId, self::$userShopperGroupData)) { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('sg.*') - ->from($db->qn('#__redshop_shopper_group', 'sg')) - ->leftJoin($db->qn('#__redshop_users_info', 'ui') . ' ON ui.shopper_group_id = sg.shopper_group_id') - ->where('ui.user_id = ' . (int)$userId) - ->where('ui.address_type = ' . $db->q('BT')); - - $db->setQuery($query); - - self::$userShopperGroupData[$userId] = $db->loadObject(); - } - - return self::$userShopperGroupData[$userId]; - } - /** * Get Shopper Group Data using shopper group id * @@ -450,6 +278,178 @@ public static function getVatUserInformation($userId = 0) return $userInformation; } + /** + * Create redshop user session + * + * @param int $userId Joomla user id + * + * @return array|mixed + */ + public static function createUserSession($userId = 0) + { + $session = JFactory::getSession(); + $userArr = $session->get('rs_user'); + + if (!$userId) { + $userId = JFactory::getUser()->id; + } + + if (empty($userArr)) { + $userArr = array(); + } + + $userArr['rs_userid'] = $userId; + + if ($userId) { + $userArr['rs_is_user_login'] = 1; + + if (!isset($userArr['rs_user_info_id'])) { + $userInformation = self::getUserInformation($userId); + $shippingAddress = RedshopHelperOrder::getShippingAddress($userId); + + if (count($shippingAddress) > 0 && Redshop::getConfig()->get('CALCULATE_VAT_ON') == 'ST') { + $redshopUserInforId = $shippingAddress[0]->users_info_id; + $userInformation = self::getUserInformation($userId, 'ST', $redshopUserInforId); + } + + $userArr['rs_user_info_id'] = isset($userInformation->users_info_id) ? $userInformation->users_info_id : 0; + } + } else { + $userArr['rs_is_user_login'] = 0; + } + + $userArr['rs_user_shopperGroup'] = self::getShopperGroup($userId); + $session->set('rs_user', $userArr); + + return $userArr; + } + + /** + * Get redshop user information + * + * @param int $userId Id joomla user + * @param string $addressType Type user address BT (Billing Type) or ST (Shipping Type) + * @param int $userInfoId Id redshop user + * @param bool $useAddressType Select user info relate with address type + * @param bool $force Force to get user information from DB instead of cache + * + * @return object Redshop user information + */ + public static function getUserInformation( + $userId = 0, + $addressType = 'BT', + $userInfoId = 0, + $useAddressType = true, + $force = false + ) { + if (0 == $userId && 0 == $userInfoId) { + $userId = JFactory::getUser()->id; + $auth = JFactory::getSession()->get('auth'); + $userInfoId = $auth['users_info_id']; + } + + // If both is not set return, as we also have silent user creating where joomla user id is not set + if (!$userId && !$userInfoId) { + return (new stdClass); + } + + if (!$useAddressType) { + $addressType = 'NA'; + } elseif ($addressType == '') { + $addressType = 'BT'; + } + + $key = $userId . '.' . $addressType . '.' . $userInfoId; + + if (!array_key_exists($key, self::$redshopUserInfo) || $force) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select(array('sh.*', 'u.*')) + ->from($db->qn('#__redshop_users_info', 'u')) + ->leftJoin($db->qn('#__redshop_shopper_group', 'sh') . ' ON sh.shopper_group_id = u.shopper_group_id'); + + // Not necessary that all user is registered with joomla id. We have silent user creation too. + if ($userId) { + $query->where('u.user_id = ' . (int)$userId); + } + + if ($useAddressType) { + $query->where('u.address_type = ' . $db->quote($addressType)); + } + + if ($userInfoId) { + $query->where('u.users_info_id = ' . (int)$userInfoId); + } + + self::$redshopUserInfo[$key] = $db->setQuery($query)->loadObject(); + } + + return self::$redshopUserInfo[$key]; + } + + /** + * Replace Conditional tag from Redshop tax + * + * @param integer $userId User identifier + * + * @return integer User group + */ + public static function getShopperGroup($userId = 0) + { + $shopperGroupData = self::getShopperGroupData($userId); + + if (!is_null($shopperGroupData)) { + return $shopperGroupData->shopper_group_id; + } + + return Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_UNREGISTERED'); + } + + /** + * Get Shopper Group Data + * + * @param int $userId User id + * + * @return mixed + */ + public static function getShopperGroupData($userId = 0) + { + $userId = !$userId ? JFactory::getUser()->id : $userId; + + // If user is guest. Try to get redshop user id. + if (!$userId) { + $auth = JFactory::getSession()->get('auth'); + + if (is_array($auth) && array_key_exists('users_info_id', $auth)) { + $userId -= $auth['users_info_id']; + } + } + + // In case user doesn't not entered any information yet. Get from default config. + if (!$userId) { + $shopperGroupId = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_UNREGISTERED'); + + return RedshopEntityShopper_Group::getInstance($shopperGroupId)->getItem(); + } + + // In case user is not guest. + if (!array_key_exists($userId, self::$userShopperGroupData)) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('sg.*') + ->from($db->qn('#__redshop_shopper_group', 'sg')) + ->leftJoin($db->qn('#__redshop_users_info', 'ui') . ' ON ui.shopper_group_id = sg.shopper_group_id') + ->where('ui.user_id = ' . (int)$userId) + ->where('ui.address_type = ' . $db->q('BT')); + + $db->setQuery($query); + + self::$userShopperGroupData[$userId] = $db->loadObject(); + } + + return self::$userShopperGroupData[$userId]; + } + /** * Method for store redshop user. * @@ -678,10 +678,10 @@ public static function storeRedshopUserShipping($data = array()) } $userTable->user_id = $data['user_id'] > 0 ? $data['user_id'] : \JFactory::getApplication( - )->input->getInt( - 'user_id', - 0 - ); + )->input->getInt( + 'user_id', + 0 + ); $userTable->address_type = 'ST'; $userTable->country_code = $data['country_code_ST']; $userTable->state_code = (isset($data['state_code_ST'])) ? $data['state_code_ST'] : ""; diff --git a/libraries/redshop/helper/utility.php b/libraries/redshop/helper/utility.php index cdbd42b83ba..8972da0e22e 100644 --- a/libraries/redshop/helper/utility.php +++ b/libraries/redshop/helper/utility.php @@ -18,1177 +18,1139 @@ */ class RedshopHelperUtility { - /** - * The dispatcher. - * - * @var JEventDispatcher - */ - public static $dispatcher = null; - - /** - * @var boolean - */ - protected static $isRedProductFinder; - - /** - * @var array - */ - protected static $menuItemAssociation = array(); - - /** - * Get SSL link for backend or applied for ssl link - * - * @param string $link Link to be converted into ssl - * @param integer $applySSL SSL should be apply or not - * - * @return string Return converted - */ - public static function getSSLLink($link, $applySSL = 1) - { - $link = JUri::getInstance(JUri::base() . $link); - - if (Redshop::getConfig()->get('SSL_ENABLE_IN_BACKEND') && $applySSL) - { - $link->setScheme('https'); - } - else - { - $link->setScheme('http'); - } - - return $link; - } - - /** - * Get the event dispatcher - * - * @return JEventDispatcher - */ - public static function getDispatcher() - { - if (!self::$dispatcher) - { - self::$dispatcher = version_compare(JVERSION, '3.0', 'lt') ? JDispatcher::getInstance() : JEventDispatcher::getInstance(); - } - - return self::$dispatcher; - } - - /** - * Quote an array of values. - * - * @param array $values The values. - * - * @return array The quoted values - */ - public static function quote(array $values) - { - $db = JFactory::getDbo(); - - return array_map( - function ($value) use ($db) - { - return $db->quote($value); - }, - $values - ); - } - - /** - * Quote name an array of values. - * - * @param array $values The values. - * - * @return array The quoted values - * - * @since 2.0.6 - */ - public static function quoteName(array $values) - { - $db = JFactory::getDbo(); - - return array_map( - function ($value) use ($db) - { - return $db->qn($value); - }, - $values - ); - } - - /** - * Method for convert utf8 string with special chars to normal ASCII char. - * - * @param string $text String for convert - * @param boolean $isUrlEncode Target for convert. True for url alias, False for normal. - * - * @return string Normal ASCI string. - * - * @since 2.0.3 - */ - public static function convertToNonSymbol($text = '', $isUrlEncode = true) - { - if (empty($text)) - { - return ''; - } - - if ($isUrlEncode === false) - { - return Transliterator::utf8ToAscii($text); - } - - return Transliterator::transliterate($text); - } - - /** - * Convert associative array into attributes. - * Example: - * array('size' => '50', 'name' => 'myfield') - * would be: - * size="50" name="myfield" - * - * @param array $array Associative array to convert - * - * @return string - */ - public static function toAttributes(array $array) - { - $attributes = ''; - - foreach ($array as $attribute => $value) - { - if (null !== $value) - { - $attributes .= ' ' . $attribute . '="' . (string) $value . '"'; - } - } - - return trim($attributes); - } - - /** - * We are using file for saving configuration variables - * We need some variables that can be uses as dynamically - * Here is the logic to define that variables - * - * IMPORTANT: we need to call this function in plugin or module manually to see the effect of this variables - * - * @return void - */ - public static function defineDynamicVariables() - { - $config = Redshop::getConfig(); - - $config->set('SHOW_PRICE', self::showPrice()); - $config->set('USE_AS_CATALOG', self::getCatalog()); - - $quotationModePre = (int) $config->get('DEFAULT_QUOTATION_MODE_PRE'); - - $config->set('DEFAULT_QUOTATION_MODE', $quotationModePre); - - if ($quotationModePre == 1) - { - $config->set('DEFAULT_QUOTATION_MODE', (int) self::setQuotationMode()); - } - } - - /** - * Define "Show Price" dynamic vars - * - * @return integer "1" for show price. "0" for hide. - */ - protected static function showPrice() - { - $user = JFactory::getUser(); - $shopperGroupId = RedshopHelperUser::getShopperGroup($user->id); - $shopperGroups = \Redshop\Helper\ShopperGroup::generateList($shopperGroupId); - - if (empty($shopperGroups)) - { - return Redshop::getConfig()->get('SHOW_PRICE_PRE'); - } - - $shopperGroups = $shopperGroups[0]; - - if ($shopperGroups->show_price == "yes" - || ($shopperGroups->show_price == "global" && Redshop::getConfig()->get('SHOW_PRICE_PRE') == 1) - || ($shopperGroups->show_price == "" && Redshop::getConfig()->get('SHOW_PRICE_PRE') == 1)) - { - return 1; - } - - return 0; - } - - /** - * Define catalog variables - * - * @return integer - */ - protected static function getCatalog() - { - $user = JFactory::getUser(); - $shopperGroupId = RedshopHelperUser::getShopperGroup($user->id); - $shopperGroup = Redshop\Helper\ShopperGroup::generateList($shopperGroupId); - - if (empty($shopperGroup)) - { - return Redshop::getConfig()->get('PRE_USE_AS_CATALOG'); - } - - $shopperGroup = $shopperGroup[0]; - - if ($shopperGroup->use_as_catalog == "yes" - || ($shopperGroup->use_as_catalog == "global" && Redshop::getConfig()->get('PRE_USE_AS_CATALOG') == 1) - || ($shopperGroup->use_as_catalog == "" && Redshop::getConfig()->get('PRE_USE_AS_CATALOG') == 1)) - { - return 1; - } - - return 0; - } - - /** - * Method for get quotation mode. - * - * @return boolean - * - * @since 2.0.6 - */ - protected static function setQuotationMode() - { - $db = JFactory::getDbo(); - $user = JFactory::getUser(); - $shopperGroupId = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_UNREGISTERED'); - - if ($user->id) - { - $userShopperGroupId = RedshopHelperUser::getShopperGroup($user->id); - - if ($userShopperGroupId) - { - $shopperGroupId = $userShopperGroupId; - } - } - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_shopper_group')) - ->where($db->qn('shopper_group_id') . ' = ' . $shopperGroupId); - - $shopperGroupData = $db->setQuery($query)->loadObject(); - - if ($shopperGroupData) - { - if ($shopperGroupData->shopper_group_quotation_mode) - { - return true; - } - - return false; - } - - return Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE_PRE'); - } - - /** - * Method for limit chars - * - * @param string $desc Description - * @param int $maxChars Maximum chars - * @param string $suffix Suffix - * - * @return string - * - * @since 2.0.6 - */ - public static function maxChars($desc = '', $maxChars = 0, $suffix = '') - { - $maxChars = (int) $maxChars; - - if (!$maxChars) - { - return $desc; - } - - return self::limitText($desc, $maxChars, $suffix); - } - - /** - * Method for sub-string with length. - * - * @param string $text Text for sub-string - * @param int $length Maximum chars - * @param string $ending Ending text - * @param boolean $exact Exact - * @param boolean $considerHtml Consider HTML - * - * @return string - * - * @since 2.0.6 - */ - public static function limitText($text, $length = 50, $ending = '...', $exact = false, $considerHtml = true) - { - $openTags = array(); - - if ($considerHtml) - { - if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) - { - return $text; - } - - $totalLength = strlen(strip_tags($ending)); - $truncate = ''; - - preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER); - - foreach ($tags as $tag) - { - if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) - { - if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) - { - array_unshift($openTags, $tag[2]); - } - elseif (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) - { - $pos = array_search($closeTag[1], $openTags); - - if ($pos !== false) - { - array_splice($openTags, $pos, 1); - } - } - } - - $truncate .= $tag[1]; - - $contentLength = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3])); - - if ($contentLength + $totalLength > $length) - { - $left = $length - $totalLength; - $entitiesLength = 0; - - if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE)) - { - foreach ($entities[0] as $entity) - { - if ($entity[1] + 1 - $entitiesLength > $left) - { - break; - } - - $left--; - $entitiesLength += strlen($entity[0]); - } - } - - $truncate .= substr($tag[3], 0, $left + $entitiesLength); - break; - } - else - { - $truncate .= $tag[3]; - $totalLength = $contentLength; - } - - if ($totalLength >= $length) - { - break; - } - } - } - else - { - if (strlen($text) <= $length) - { - return $text; - } - - $truncate = substr($text, 0, $length - strlen($ending)); - } - - if (!$exact) - { - $spacePosition = strrpos($truncate, ' '); - - if ($spacePosition > -1) - { - if ($considerHtml) - { - $bits = substr($truncate, $spacePosition); - preg_match_all('/<\/([a-z])>/', $bits, $droppedTags, PREG_SET_ORDER); - - if (!empty($droppedTags)) - { - foreach ($droppedTags as $closingTag) - { - if (!in_array($closingTag[1], $openTags)) - { - array_unshift($openTags, $closingTag[1]); - } - } - } - } - - $truncate = substr($truncate, 0, $spacePosition); - } - } - - $truncate .= $ending; - - if (!$considerHtml) - { - return $truncate; - } - - foreach ($openTags as $tag) - { - $truncate .= ''; - } - - return $truncate; - } - - /** - * Method for check country in EU area or not - * - * @param string $country Country code - * - * @return boolean - * - * @since 2.0.6 - */ - public static function isCountryInEurope($country) - { - $euCountries = array('AUT', 'BGR', 'BEL', 'CYP', 'CZE', 'DEU', 'DNK', 'ESP', 'EST', - 'FIN', 'FRA', 'FXX', 'GBR', 'GRC', 'HUN', 'IRL', 'ITA', 'LVA', 'LTU', - 'LUX', 'MLT', 'NLD', 'POL', 'PRT', 'ROM', 'SVK', 'SVN', 'SWE'); - - return in_array($country, $euCountries); - } - - /** - * Set Operand For Values - * - * @param float $leftValue Left value - * @param string $operand Operand - * @param float $rightValue Right value - * - * @return float - * - * @since 2.0.6 - */ - public static function setOperandForValues($leftValue, $operand, $rightValue) - { - switch ($operand) - { - case '+': - $leftValue += $rightValue; - break; - - case '-': - $leftValue -= $rightValue; - break; - - case '*': - $leftValue *= $rightValue; - break; - - case '/': - $leftValue /= $rightValue; - break; - - case '=': - $leftValue = $rightValue; - break; - - default: - break; - } - - return $leftValue; - } - - /** - * Add item to cart from db ... - * - * @return void - * - * @since 2.0.6 - */ - public static function databaseToCart() - { - $session = JFactory::getSession(); - $cart = $session->get('cart'); - $user = JFactory::getUser(); - - if ($user->id && !isset($cart['idx'])) - { - RedshopHelperCart::databaseToCart(); - } - } - - /** - * Get plugins - * - * @param string $folder Group of plugins - * @param string $enabled -1: All, 0: not enable, 1: enabled - * - * @return array - * - * @since 2.0.6 - */ - public static function getPlugins($folder = 'redshop', $enabled = null) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select('*') - ->from('#__extensions') - ->where('LOWER(' . $db->qn('folder') . ') = ' . $db->quote(strtolower($folder))) - ->order($db->qn('ordering') . ' ASC'); - - if (!is_null($enabled)) - { - $query->where($db->qn('enabled') . ' = ' . $db->quote($enabled)); - } - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * Method for get modules - * - * @param string $enabled [-1: All, 0: not enable, 1: enabled] - * - * @return array - * - * @since 2.0.6 - */ - public static function getModules($enabled = '1') - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $oldStyleName = array( - 'mod_redcategoryscroller', 'mod_redmasscart', 'mod_redfeaturedproduct', 'mod_redproducts3d', 'mod_redproductscroller', - 'mod_redproducttab', 'mod_redmanufacturer' - ); - - $query->select('*') - ->from('#__extensions') - ->where($db->qn('type') . ' = ' . $db->quote('module')) - ->where( - 'LOWER(' . $db->qn('element') . ') LIKE ' . $db->quote('mod_redshop%') - . ' OR LOWER(' . $db->qn('element') . ') IN (' . implode(',', self::quote($oldStyleName)) . ')' - ) - ->order($db->qn('ordering') . ' ASC'); - - if ($enabled > 0) - { - $query->where($db->qn('enabled') . ' = ' . $db->q($enabled)); - } - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * Check Menu Query - * - * @param object $oneMenuItem Values current menu item - * @param array $queryItems Name query check - * - * @return boolean - * - * @since 2.0.6 - */ - public static function checkMenuQuery($oneMenuItem, $queryItems) - { - if (empty($oneMenuItem) || empty($queryItems)) - { - return false; - } - - foreach ($queryItems as $key => $value) - { - if (!isset($oneMenuItem->query[$key]) - || (is_array($value) && !in_array($oneMenuItem->query[$key], $value)) - || (!is_array($value) && $oneMenuItem->query[$key] != $value) - ) - { - return false; - } - } - - return true; - } - - /** - * Get RedShop Menu Item - * - * @param array $queryItems Values query - * - * @return mixed - * @throws Exception - * - * @since 2.0.6 - */ - public static function getRedShopMenuItem($queryItems) - { - $serializeItem = md5(serialize($queryItems)); - - if (!array_key_exists($serializeItem, self::$menuItemAssociation)) - { - self::$menuItemAssociation[$serializeItem] = false; - - foreach (RedshopHelperRouter::getRedshopMenuItems() as $oneMenuItem) - { - if (self::checkMenuQuery($oneMenuItem, $queryItems)) - { - self::$menuItemAssociation[$serializeItem] = $oneMenuItem->id; - break; - } - } - } - - return self::$menuItemAssociation[$serializeItem]; - } - - /** - * Get Item Id - * - * @param int $productId Product Id - * @param int $categoryId Category Id - * - * @return mixed - * - * @throws Exception - * - * @since 2.0.6 - */ - public static function getItemId($productId = 0, $categoryId = 0) - { - // Get Itemid from Product detail - if ($productId) - { - $result = self::getRedShopMenuItem(array('option' => 'com_redshop', 'view' => 'product', 'pid' => (int) $productId)); - - if ($result) - { - return $result; - } - } - - // Get Itemid from Category detail - if ($categoryId) - { - $result = self::getCategoryItemid($categoryId); - - if ($result) - { - return $result; - } - } - - $input = JFactory::getApplication()->input; - - if ($input->getCmd('option', '') != 'com_redshop') - { - $result = self::getRedShopMenuItem(array('option' => 'com_redshop', 'view' => 'category')); - - if ($result) - { - return $result; - } - - $result = self::getRedShopMenuItem(array('option' => 'com_redshop')); - - if ($result) - { - return $result; - } - } - - return $input->getInt('Itemid', 0); - } - - /** - * Get Category Itemid - * - * @param int $categoryId Category id - * - * @return mixed - * - * @since 2.0.6 - */ - public static function getCategoryItemid($categoryId = 0) - { - if (!$categoryId) - { - $result = self::getRedShopMenuItem(array('option' => 'com_redshop', 'view' => 'category')); - - if ($result) - { - return $result; - } - - return null; - } - - $categories = explode(',', $categoryId); - - if (!empty($categories)) - { - foreach ($categories as $category) - { - $result = self::getRedShopMenuItem( - array('option' => 'com_redshop', 'view' => 'category', 'layout' => 'detail', 'cid' => (int) $category) - ); - - if ($result) - { - return $result; - } - } - } - - // Get from Parents - $categories = RedshopHelperCategory::getCategoryListReverseArray($categoryId); - - if (!empty($categories)) - { - foreach ($categories as $category) - { - $result = self::getCategoryItemid($category->id); - - if ($result) - { - return $result; - } - } - } - - return null; - } - - /** - * Method for convert array of string - * - * @param array $data Language array - * - * @return mixed - * - * @since 2.0.6 - */ - public static function convertLanguageString($data) - { - for ($i = 0, $in = count($data); $i < $in; $i++) - { - $txt = $data[$i]->text; - $ltext = JText::_($txt); - - if ($ltext != $txt) - { - $data[$i]->text = $ltext; - } - elseif ($data[$i]->country_jtext != "") - { - $data[$i]->text = $data[$i]->country_jtext; - } - } - - $tmpArray = array(); - - for ($i = 0, $in = count($data); $i < $in; $i++) - { - $txt = $data[$i]->text; - $val = $data[$i]->value; - $tmpArray[$val] = $txt; - } - - asort($tmpArray); - $x = 0; - - foreach ($tmpArray AS $val => $txt) - { - $data[$x]->text = $txt; - $data[$x]->value = $val; - $x++; - } - - return $data; - } - - /** - * Method for get order by list - * - * @return array - * - * @since 2.0.6 - */ - public static function getOrderByList() - { - $orderBy = array( - JHtml::_('select.option', 'name', JText::_('COM_REDSHOP_PRODUCT_NAME_ASC')), - JHtml::_('select.option', 'name_desc', JText::_('COM_REDSHOP_PRODUCT_NAME_DESC')), - JHtml::_('select.option', 'price', JText::_('COM_REDSHOP_PRODUCT_PRICE_ASC')), - JHtml::_('select.option', 'price_desc', JText::_('COM_REDSHOP_PRODUCT_PRICE_DESC')), - JHtml::_('select.option', 'number', JText::_('COM_REDSHOP_PRODUCT_NUMBER_ASC')), - JHtml::_('select.option', 'number_desc', JText::_('COM_REDSHOP_PRODUCT_NUMBER_DESC')), - JHtml::_('select.option', 'id', JText::_('COM_REDSHOP_NEWEST')), - JHtml::_('select.option', 'ordering', JText::_('COM_REDSHOP_ORDERING_ASC')), - JHtml::_('select.option', 'ordering_desc', JText::_('COM_REDSHOP_ORDERING_DESC')) - ); - - JPluginHelper::importPlugin('system'); - RedshopHelperUtility::getDispatcher()->trigger('onGetOrderByList', array(&$orderBy)); - - return $orderBy; - } - - /** - * Prepare order by object for ordering from string. - * - * @param string $case Order By string generated in getOrderByList method - * - * @return stdClass Parsed strings in ordering and direction object key. - * - * @since 2.0.6 - */ - public static function prepareOrderBy($case) - { - $orderBy = new stdClass; - - switch ($case) - { - case 'name_desc': - $orderBy->ordering = 'p.product_name'; - $orderBy->direction = 'DESC'; - - break; - - case 'price': - $orderBy->ordering = 'p.product_price'; - $orderBy->direction = 'ASC'; - - break; - - case 'price_desc': - $orderBy->ordering = 'p.product_price'; - $orderBy->direction = 'DESC'; - - break; - - case 'number': - $orderBy->ordering = 'p.product_number'; - $orderBy->direction = 'ASC'; - - break; - - case 'number_desc': - $orderBy->ordering = 'p.product_number'; - $orderBy->direction = 'DESC'; - - break; - - case 'id': - $orderBy->ordering = 'p.product_id'; - $orderBy->direction = 'DESC'; - - break; - - case 'ordering': - $orderBy->ordering = 'pc.ordering'; - $orderBy->direction = 'ASC'; - - break; - - case 'ordering_desc': - $orderBy->ordering = 'pc.ordering'; - $orderBy->direction = 'DESC'; - - break; - - case 'name': - default: - $orderBy->ordering = 'p.product_name'; - $orderBy->direction = 'ASC'; - - break; - } - - JPluginHelper::importPlugin('system'); - RedshopHelperUtility::getDispatcher()->trigger('onPrepareOrderBy', array(&$orderBy, $case)); - - return $orderBy; - } - - /** - * Method for get manufacturer order by list - * - * @return array List of order - * - * @since 2.0.6 - */ - public static function getManufacturerOrderByList() - { - $order = array(); - - $order[0] = new stdClass; - $order[0]->value = "mn.name ASC"; - $order[0]->text = JText::_('COM_REDSHOP_ALPHABETICALLY'); - - $order[1] = new stdClass; - $order[1]->value = "mn.id DESC"; - $order[1]->text = JText::_('COM_REDSHOP_NEWEST'); - - $order[2] = new stdClass; - $order[2]->value = "mn.ordering ASC"; - $order[2]->text = JText::_('COM_REDSHOP_ORDERING'); - - return $order; - } - - /** - * Method for get product related order by list - * - * @return array List of order - * - * @since 2.0.6 - */ - public static function getRelatedOrderByList() - { - $order = array(); - - $order[0] = new stdClass; - $order[0]->value = "p.product_name ASC"; - $order[0]->text = JText::_('COM_REDSHOP_PRODUCT_NAME_ASC'); - - $order[1] = new stdClass; - $order[1]->value = "p.product_name DESC"; - $order[1]->text = JText::_('COM_REDSHOP_PRODUCT_NAME_DESC'); - - $order[2] = new stdClass; - $order[2]->value = "p.product_price ASC"; - $order[2]->text = JText::_('COM_REDSHOP_PRODUCT_PRICE_ASC'); - - $order[3] = new stdClass; - $order[3]->value = "p.product_price DESC"; - $order[3]->text = JText::_('COM_REDSHOP_PRODUCT_PRICE_DESC'); - - $order[4] = new stdClass; - $order[4]->value = "p.product_number ASC"; - $order[4]->text = JText::_('COM_REDSHOP_PRODUCT_NUMBER_ASC'); - - $order[5] = new stdClass; - $order[5]->value = "p.product_number DESC"; - $order[5]->text = JText::_('COM_REDSHOP_PRODUCT_NUMBER_DESC'); - - $order[6] = new stdClass; - $order[6]->value = "r.ordering ASC"; - $order[6]->text = JText::_('COM_REDSHOP_ORDERING_ASC'); - - $order[7] = new stdClass; - $order[7]->value = "r.ordering DESC"; - $order[7]->text = JText::_('COM_REDSHOP_ORDERING_DESC'); - - if (self::isRedProductFinder()) - { - $order[8] = new stdClass; - $order[8]->value = "e.data_txt ASC"; - $order[8]->text = JText::_('COM_REDSHOP_DATEPICKER_ASC'); - - $order[9] = new stdClass; - $order[9]->value = "e.data_txt DESC"; - $order[9]->text = JText::_('COM_REDSHOP_DATEPICKER_DESC'); - } - - return $order; - } - - /** - * Method for get accessory order by list - * - * @return array List of order - * - * @since 2.0.6 - */ - public static function getAccessoryOrderByList() - { - $order = array(); - - $order[0] = new stdClass; - $order[0]->value = "child_product_id ASC"; - $order[0]->text = JText::_('COM_REDSHOP_PRODUCT_ID_ASC'); - - $order[1] = new stdClass; - $order[1]->value = "child_product_id DESC"; - $order[1]->text = JText::_('COM_REDSHOP_PRODUCT_ID_DESC'); - - $order[2] = new stdClass; - $order[2]->value = "accessory_id ASC"; - $order[2]->text = JText::_('COM_REDSHOP_ACCESSORY_ID_ASC'); - - $order[3] = new stdClass; - $order[3]->value = "accessory_id DESC"; - $order[3]->text = JText::_('COM_REDSHOP_ACCESSORY_ID_DESC'); - - $order[4] = new stdClass; - $order[4]->value = "newaccessory_price ASC"; - $order[4]->text = JText::_('COM_REDSHOP_ACCESSORY_PRICE_ASC'); - - $order[5] = new stdClass; - $order[5]->value = "newaccessory_price DESC"; - $order[5]->text = JText::_('COM_REDSHOP_ACCESSORY_PRICE_DESC'); - - $order[6] = new stdClass; - $order[6]->value = "ordering ASC"; - $order[6]->text = JText::_('COM_REDSHOP_ORDERING_ASC'); - - $order[7] = new stdClass; - $order[7]->value = "ordering DESC"; - $order[7]->text = JText::_('COM_REDSHOP_ORDERING_DESC'); - - return $order; - } - - /** - * Method for get pre-order by list - * - * @return array List of order - * - * @since 2.0.6 - */ - public static function getPreOrderByList() - { - $preOrder = array(); - - $preOrder[0] = new stdClass; - $preOrder[0]->value = "global"; - $preOrder[0]->text = JText::_('COM_REDSHOP_GLOBAL'); - - $preOrder[1] = new stdClass; - $preOrder[1]->value = "yes"; - $preOrder[1]->text = JText::_('COM_REDSHOP_YES'); - - $preOrder[2] = new stdClass; - $preOrder[2]->value = "no"; - $preOrder[2]->text = JText::_('COM_REDSHOP_NO'); - - return $preOrder; - } - - /** - * Method for get child product order by list - * - * @return array List of order - * - * @since 2.0.6 - */ - public static function getChildProductOption() - { - $childProduct = array(); - - $childProduct[0] = new stdClass; - $childProduct[0]->value = "product_name"; - $childProduct[0]->text = JText::_('COM_REDSHOP_CHILD_PRODUCT_NAME'); - - $childProduct[1] = new stdClass; - $childProduct[1]->value = "product_number"; - $childProduct[1]->text = JText::_('COM_REDSHOP_CHILD_PRODUCT_NUMBER'); - - return $childProduct; - } - - /** - * Method for get child product order by list - * - * @return array List of order - * - * @since 2.0.6 - */ - public static function getStateAbbreviationsByList() - { - $stateData = array(); - - $stateData[0] = new stdClass; - $stateData[0]->value = "2"; - $stateData[0]->text = JText::_('COM_REDSHOP_TWO_LETTER_ABBRIVATION'); - - $stateData[1] = new stdClass; - $stateData[1]->value = "3"; - $stateData[1]->text = JText::_('COM_REDSHOP_THREE_LETTER_ABBRIVATION'); - - return $stateData; - } - - /** - * Method for check if ProductFinder is available or not. - * - * @return boolean - * - * @since 2.0.6 - */ - public static function isRedProductFinder() - { - if (self::$isRedProductFinder === null) - { - // Get redshop from joomla component table - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select($db->qn('enabled')) - ->from($db->qn('#__extensions')) - ->where('element = ' . $db->q('com_redproductfinder')); - - $redProductFinderPath = JPATH_ADMINISTRATOR . '/components/com_redproductfinder'; - - if (!is_dir($redProductFinderPath) || $db->setQuery($query)->loadResult() == 0) - { - self::$isRedProductFinder = false; - } - else - { - self::$isRedProductFinder = true; - } - } - - return self::$isRedProductFinder; - } - - /** - * Method for get Economic Account Group - * - * @param integer $accountGroupId Account group ID - * @param integer $front Is front or not - * - * @return array - * - * @since 2.0.6 - */ - public static function getEconomicAccountGroup($accountGroupId = 0, $front = 0) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('ea.*') - ->select($db->qn('ea.accountgroup_id', 'value')) - ->select($db->qn('ea.accountgroup_name', 'text')) - ->from($db->qn('#__redshop_economic_accountgroup', 'ea')); - - if ($accountGroupId) - { - $query->where($db->qn('ea.accountgroup_id') . ' = ' . (int) $accountGroupId); - } - - if ($front) - { - $query->where($db->qn('ea.published') . ' = 1'); - } - - return $db->setQuery($query)->loadObjectList(); - } + /** + * The dispatcher. + * + * @var JEventDispatcher + */ + public static $dispatcher = null; + + /** + * @var boolean + */ + protected static $isRedProductFinder; + + /** + * @var array + */ + protected static $menuItemAssociation = array(); + + /** + * Get SSL link for backend or applied for ssl link + * + * @param string $link Link to be converted into ssl + * @param integer $applySSL SSL should be apply or not + * + * @return string Return converted + */ + public static function getSSLLink($link, $applySSL = 1) + { + $link = JUri::getInstance(JUri::base() . $link); + + if (Redshop::getConfig()->get('SSL_ENABLE_IN_BACKEND') && $applySSL) { + $link->setScheme('https'); + } else { + $link->setScheme('http'); + } + + return $link; + } + + /** + * Quote name an array of values. + * + * @param array $values The values. + * + * @return array The quoted values + * + * @since 2.0.6 + */ + public static function quoteName(array $values) + { + $db = JFactory::getDbo(); + + return array_map( + function ($value) use ($db) { + return $db->qn($value); + }, + $values + ); + } + + /** + * Method for convert utf8 string with special chars to normal ASCII char. + * + * @param string $text String for convert + * @param boolean $isUrlEncode Target for convert. True for url alias, False for normal. + * + * @return string Normal ASCI string. + * + * @since 2.0.3 + */ + public static function convertToNonSymbol($text = '', $isUrlEncode = true) + { + if (empty($text)) { + return ''; + } + + if ($isUrlEncode === false) { + return Transliterator::utf8ToAscii($text); + } + + return Transliterator::transliterate($text); + } + + /** + * Convert associative array into attributes. + * Example: + * array('size' => '50', 'name' => 'myfield') + * would be: + * size="50" name="myfield" + * + * @param array $array Associative array to convert + * + * @return string + */ + public static function toAttributes(array $array) + { + $attributes = ''; + + foreach ($array as $attribute => $value) { + if (null !== $value) { + $attributes .= ' ' . $attribute . '="' . (string)$value . '"'; + } + } + + return trim($attributes); + } + + /** + * We are using file for saving configuration variables + * We need some variables that can be uses as dynamically + * Here is the logic to define that variables + * + * IMPORTANT: we need to call this function in plugin or module manually to see the effect of this variables + * + * @return void + */ + public static function defineDynamicVariables() + { + $config = Redshop::getConfig(); + + $config->set('SHOW_PRICE', self::showPrice()); + $config->set('USE_AS_CATALOG', self::getCatalog()); + + $quotationModePre = (int)$config->get('DEFAULT_QUOTATION_MODE_PRE'); + + $config->set('DEFAULT_QUOTATION_MODE', $quotationModePre); + + if ($quotationModePre == 1) { + $config->set('DEFAULT_QUOTATION_MODE', (int)self::setQuotationMode()); + } + } + + /** + * Define "Show Price" dynamic vars + * + * @return integer "1" for show price. "0" for hide. + */ + protected static function showPrice() + { + $user = JFactory::getUser(); + $shopperGroupId = RedshopHelperUser::getShopperGroup($user->id); + $shopperGroups = \Redshop\Helper\ShopperGroup::generateList($shopperGroupId); + + if (empty($shopperGroups)) { + return Redshop::getConfig()->get('SHOW_PRICE_PRE'); + } + + $shopperGroups = $shopperGroups[0]; + + if ($shopperGroups->show_price == "yes" + || ($shopperGroups->show_price == "global" && Redshop::getConfig()->get('SHOW_PRICE_PRE') == 1) + || ($shopperGroups->show_price == "" && Redshop::getConfig()->get('SHOW_PRICE_PRE') == 1)) { + return 1; + } + + return 0; + } + + /** + * Define catalog variables + * + * @return integer + */ + protected static function getCatalog() + { + $user = JFactory::getUser(); + $shopperGroupId = RedshopHelperUser::getShopperGroup($user->id); + $shopperGroup = Redshop\Helper\ShopperGroup::generateList($shopperGroupId); + + if (empty($shopperGroup)) { + return Redshop::getConfig()->get('PRE_USE_AS_CATALOG'); + } + + $shopperGroup = $shopperGroup[0]; + + if ($shopperGroup->use_as_catalog == "yes" + || ($shopperGroup->use_as_catalog == "global" && Redshop::getConfig()->get('PRE_USE_AS_CATALOG') == 1) + || ($shopperGroup->use_as_catalog == "" && Redshop::getConfig()->get('PRE_USE_AS_CATALOG') == 1)) { + return 1; + } + + return 0; + } + + /** + * Method for get quotation mode. + * + * @return boolean + * + * @since 2.0.6 + */ + protected static function setQuotationMode() + { + $db = JFactory::getDbo(); + $user = JFactory::getUser(); + $shopperGroupId = Redshop::getConfig()->get('SHOPPER_GROUP_DEFAULT_UNREGISTERED'); + + if ($user->id) { + $userShopperGroupId = RedshopHelperUser::getShopperGroup($user->id); + + if ($userShopperGroupId) { + $shopperGroupId = $userShopperGroupId; + } + } + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_shopper_group')) + ->where($db->qn('shopper_group_id') . ' = ' . $shopperGroupId); + + $shopperGroupData = $db->setQuery($query)->loadObject(); + + if ($shopperGroupData) { + if ($shopperGroupData->shopper_group_quotation_mode) { + return true; + } + + return false; + } + + return Redshop::getConfig()->get('DEFAULT_QUOTATION_MODE_PRE'); + } + + /** + * Method for limit chars + * + * @param string $desc Description + * @param int $maxChars Maximum chars + * @param string $suffix Suffix + * + * @return string + * + * @since 2.0.6 + */ + public static function maxChars($desc = '', $maxChars = 0, $suffix = '') + { + $maxChars = (int)$maxChars; + + if (!$maxChars) { + return $desc; + } + + return self::limitText($desc, $maxChars, $suffix); + } + + /** + * Method for sub-string with length. + * + * @param string $text Text for sub-string + * @param int $length Maximum chars + * @param string $ending Ending text + * @param boolean $exact Exact + * @param boolean $considerHtml Consider HTML + * + * @return string + * + * @since 2.0.6 + */ + public static function limitText($text, $length = 50, $ending = '...', $exact = false, $considerHtml = true) + { + $openTags = array(); + + if ($considerHtml) { + if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) { + return $text; + } + + $totalLength = strlen(strip_tags($ending)); + $truncate = ''; + + preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER); + + foreach ($tags as $tag) { + if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) { + if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) { + array_unshift($openTags, $tag[2]); + } elseif (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) { + $pos = array_search($closeTag[1], $openTags); + + if ($pos !== false) { + array_splice($openTags, $pos, 1); + } + } + } + + $truncate .= $tag[1]; + + $contentLength = strlen( + preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3]) + ); + + if ($contentLength + $totalLength > $length) { + $left = $length - $totalLength; + $entitiesLength = 0; + + if (preg_match_all( + '/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', + $tag[3], + $entities, + PREG_OFFSET_CAPTURE + )) { + foreach ($entities[0] as $entity) { + if ($entity[1] + 1 - $entitiesLength > $left) { + break; + } + + $left--; + $entitiesLength += strlen($entity[0]); + } + } + + $truncate .= substr($tag[3], 0, $left + $entitiesLength); + break; + } else { + $truncate .= $tag[3]; + $totalLength = $contentLength; + } + + if ($totalLength >= $length) { + break; + } + } + } else { + if (strlen($text) <= $length) { + return $text; + } + + $truncate = substr($text, 0, $length - strlen($ending)); + } + + if (!$exact) { + $spacePosition = strrpos($truncate, ' '); + + if ($spacePosition > -1) { + if ($considerHtml) { + $bits = substr($truncate, $spacePosition); + preg_match_all('/<\/([a-z])>/', $bits, $droppedTags, PREG_SET_ORDER); + + if (!empty($droppedTags)) { + foreach ($droppedTags as $closingTag) { + if (!in_array($closingTag[1], $openTags)) { + array_unshift($openTags, $closingTag[1]); + } + } + } + } + + $truncate = substr($truncate, 0, $spacePosition); + } + } + + $truncate .= $ending; + + if (!$considerHtml) { + return $truncate; + } + + foreach ($openTags as $tag) { + $truncate .= ''; + } + + return $truncate; + } + + /** + * Method for check country in EU area or not + * + * @param string $country Country code + * + * @return boolean + * + * @since 2.0.6 + */ + public static function isCountryInEurope($country) + { + $euCountries = array( + 'AUT', + 'BGR', + 'BEL', + 'CYP', + 'CZE', + 'DEU', + 'DNK', + 'ESP', + 'EST', + 'FIN', + 'FRA', + 'FXX', + 'GBR', + 'GRC', + 'HUN', + 'IRL', + 'ITA', + 'LVA', + 'LTU', + 'LUX', + 'MLT', + 'NLD', + 'POL', + 'PRT', + 'ROM', + 'SVK', + 'SVN', + 'SWE' + ); + + return in_array($country, $euCountries); + } + + /** + * Set Operand For Values + * + * @param float $leftValue Left value + * @param string $operand Operand + * @param float $rightValue Right value + * + * @return float + * + * @since 2.0.6 + */ + public static function setOperandForValues($leftValue, $operand, $rightValue) + { + switch ($operand) { + case '+': + $leftValue += $rightValue; + break; + + case '-': + $leftValue -= $rightValue; + break; + + case '*': + $leftValue *= $rightValue; + break; + + case '/': + $leftValue /= $rightValue; + break; + + case '=': + $leftValue = $rightValue; + break; + + default: + break; + } + + return $leftValue; + } + + /** + * Add item to cart from db ... + * + * @return void + * + * @since 2.0.6 + */ + public static function databaseToCart() + { + $session = JFactory::getSession(); + $cart = $session->get('cart'); + $user = JFactory::getUser(); + + if ($user->id && !isset($cart['idx'])) { + RedshopHelperCart::databaseToCart(); + } + } + + /** + * Get plugins + * + * @param string $folder Group of plugins + * @param string $enabled -1: All, 0: not enable, 1: enabled + * + * @return array + * + * @since 2.0.6 + */ + public static function getPlugins($folder = 'redshop', $enabled = null) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select('*') + ->from('#__extensions') + ->where('LOWER(' . $db->qn('folder') . ') = ' . $db->quote(strtolower($folder))) + ->order($db->qn('ordering') . ' ASC'); + + if (!is_null($enabled)) { + $query->where($db->qn('enabled') . ' = ' . $db->quote($enabled)); + } + + return $db->setQuery($query)->loadObjectList(); + } + + /** + * Method for get modules + * + * @param string $enabled [-1: All, 0: not enable, 1: enabled] + * + * @return array + * + * @since 2.0.6 + */ + public static function getModules($enabled = '1') + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $oldStyleName = array( + 'mod_redcategoryscroller', + 'mod_redmasscart', + 'mod_redfeaturedproduct', + 'mod_redproducts3d', + 'mod_redproductscroller', + 'mod_redproducttab', + 'mod_redmanufacturer' + ); + + $query->select('*') + ->from('#__extensions') + ->where($db->qn('type') . ' = ' . $db->quote('module')) + ->where( + 'LOWER(' . $db->qn('element') . ') LIKE ' . $db->quote('mod_redshop%') + . ' OR LOWER(' . $db->qn('element') . ') IN (' . implode(',', self::quote($oldStyleName)) . ')' + ) + ->order($db->qn('ordering') . ' ASC'); + + if ($enabled > 0) { + $query->where($db->qn('enabled') . ' = ' . $db->q($enabled)); + } + + return $db->setQuery($query)->loadObjectList(); + } + + /** + * Quote an array of values. + * + * @param array $values The values. + * + * @return array The quoted values + */ + public static function quote(array $values) + { + $db = JFactory::getDbo(); + + return array_map( + function ($value) use ($db) { + return $db->quote($value); + }, + $values + ); + } + + /** + * Get Item Id + * + * @param int $productId Product Id + * @param int $categoryId Category Id + * + * @return mixed + * + * @throws Exception + * + * @since 2.0.6 + */ + public static function getItemId($productId = 0, $categoryId = 0) + { + // Get Itemid from Product detail + if ($productId) { + $result = self::getRedShopMenuItem( + array('option' => 'com_redshop', 'view' => 'product', 'pid' => (int)$productId) + ); + + if ($result) { + return $result; + } + } + + // Get Itemid from Category detail + if ($categoryId) { + $result = self::getCategoryItemid($categoryId); + + if ($result) { + return $result; + } + } + + $input = JFactory::getApplication()->input; + + if ($input->getCmd('option', '') != 'com_redshop') { + $result = self::getRedShopMenuItem(array('option' => 'com_redshop', 'view' => 'category')); + + if ($result) { + return $result; + } + + $result = self::getRedShopMenuItem(array('option' => 'com_redshop')); + + if ($result) { + return $result; + } + } + + return $input->getInt('Itemid', 0); + } + + /** + * Get RedShop Menu Item + * + * @param array $queryItems Values query + * + * @return mixed + * @throws Exception + * + * @since 2.0.6 + */ + public static function getRedShopMenuItem($queryItems) + { + $serializeItem = md5(serialize($queryItems)); + + if (!array_key_exists($serializeItem, self::$menuItemAssociation)) { + self::$menuItemAssociation[$serializeItem] = false; + + foreach (RedshopHelperRouter::getRedshopMenuItems() as $oneMenuItem) { + if (self::checkMenuQuery($oneMenuItem, $queryItems)) { + self::$menuItemAssociation[$serializeItem] = $oneMenuItem->id; + break; + } + } + } + + return self::$menuItemAssociation[$serializeItem]; + } + + /** + * Check Menu Query + * + * @param object $oneMenuItem Values current menu item + * @param array $queryItems Name query check + * + * @return boolean + * + * @since 2.0.6 + */ + public static function checkMenuQuery($oneMenuItem, $queryItems) + { + if (empty($oneMenuItem) || empty($queryItems)) { + return false; + } + + foreach ($queryItems as $key => $value) { + if (!isset($oneMenuItem->query[$key]) + || (is_array($value) && !in_array($oneMenuItem->query[$key], $value)) + || (!is_array($value) && $oneMenuItem->query[$key] != $value) + ) { + return false; + } + } + + return true; + } + + /** + * Get Category Itemid + * + * @param int $categoryId Category id + * + * @return mixed + * + * @since 2.0.6 + */ + public static function getCategoryItemid($categoryId = 0) + { + if (!$categoryId) { + $result = self::getRedShopMenuItem(array('option' => 'com_redshop', 'view' => 'category')); + + if ($result) { + return $result; + } + + return null; + } + + $categories = explode(',', $categoryId); + + if (!empty($categories)) { + foreach ($categories as $category) { + $result = self::getRedShopMenuItem( + array( + 'option' => 'com_redshop', + 'view' => 'category', + 'layout' => 'detail', + 'cid' => (int)$category + ) + ); + + if ($result) { + return $result; + } + } + } + + // Get from Parents + $categories = RedshopHelperCategory::getCategoryListReverseArray($categoryId); + + if (!empty($categories)) { + foreach ($categories as $category) { + $result = self::getCategoryItemid($category->id); + + if ($result) { + return $result; + } + } + } + + return null; + } + + /** + * Method for convert array of string + * + * @param array $data Language array + * + * @return mixed + * + * @since 2.0.6 + */ + public static function convertLanguageString($data) + { + for ($i = 0, $in = count($data); $i < $in; $i++) { + $txt = $data[$i]->text; + $ltext = JText::_($txt); + + if ($ltext != $txt) { + $data[$i]->text = $ltext; + } elseif ($data[$i]->country_jtext != "") { + $data[$i]->text = $data[$i]->country_jtext; + } + } + + $tmpArray = array(); + + for ($i = 0, $in = count($data); $i < $in; $i++) { + $txt = $data[$i]->text; + $val = $data[$i]->value; + $tmpArray[$val] = $txt; + } + + asort($tmpArray); + $x = 0; + + foreach ($tmpArray AS $val => $txt) { + $data[$x]->text = $txt; + $data[$x]->value = $val; + $x++; + } + + return $data; + } + + /** + * Method for get order by list + * + * @return array + * + * @since 2.0.6 + */ + public static function getOrderByList() + { + $orderBy = array( + JHtml::_('select.option', 'name', JText::_('COM_REDSHOP_PRODUCT_NAME_ASC')), + JHtml::_('select.option', 'name_desc', JText::_('COM_REDSHOP_PRODUCT_NAME_DESC')), + JHtml::_('select.option', 'price', JText::_('COM_REDSHOP_PRODUCT_PRICE_ASC')), + JHtml::_('select.option', 'price_desc', JText::_('COM_REDSHOP_PRODUCT_PRICE_DESC')), + JHtml::_('select.option', 'number', JText::_('COM_REDSHOP_PRODUCT_NUMBER_ASC')), + JHtml::_('select.option', 'number_desc', JText::_('COM_REDSHOP_PRODUCT_NUMBER_DESC')), + JHtml::_('select.option', 'id', JText::_('COM_REDSHOP_NEWEST')), + JHtml::_('select.option', 'ordering', JText::_('COM_REDSHOP_ORDERING_ASC')), + JHtml::_('select.option', 'ordering_desc', JText::_('COM_REDSHOP_ORDERING_DESC')) + ); + + JPluginHelper::importPlugin('system'); + RedshopHelperUtility::getDispatcher()->trigger('onGetOrderByList', array(&$orderBy)); + + return $orderBy; + } + + /** + * Get the event dispatcher + * + * @return JEventDispatcher + */ + public static function getDispatcher() + { + if (!self::$dispatcher) { + self::$dispatcher = version_compare(JVERSION, '3.0', 'lt') ? JDispatcher::getInstance( + ) : JEventDispatcher::getInstance(); + } + + return self::$dispatcher; + } + + /** + * Prepare order by object for ordering from string. + * + * @param string $case Order By string generated in getOrderByList method + * + * @return stdClass Parsed strings in ordering and direction object key. + * + * @since 2.0.6 + */ + public static function prepareOrderBy($case) + { + $orderBy = new stdClass; + + switch ($case) { + case 'name_desc': + $orderBy->ordering = 'p.product_name'; + $orderBy->direction = 'DESC'; + + break; + + case 'price': + $orderBy->ordering = 'p.product_price'; + $orderBy->direction = 'ASC'; + + break; + + case 'price_desc': + $orderBy->ordering = 'p.product_price'; + $orderBy->direction = 'DESC'; + + break; + + case 'number': + $orderBy->ordering = 'p.product_number'; + $orderBy->direction = 'ASC'; + + break; + + case 'number_desc': + $orderBy->ordering = 'p.product_number'; + $orderBy->direction = 'DESC'; + + break; + + case 'id': + $orderBy->ordering = 'p.product_id'; + $orderBy->direction = 'DESC'; + + break; + + case 'ordering': + $orderBy->ordering = 'pc.ordering'; + $orderBy->direction = 'ASC'; + + break; + + case 'ordering_desc': + $orderBy->ordering = 'pc.ordering'; + $orderBy->direction = 'DESC'; + + break; + + case 'name': + default: + $orderBy->ordering = 'p.product_name'; + $orderBy->direction = 'ASC'; + + break; + } + + JPluginHelper::importPlugin('system'); + RedshopHelperUtility::getDispatcher()->trigger('onPrepareOrderBy', array(&$orderBy, $case)); + + return $orderBy; + } + + /** + * Method for get manufacturer order by list + * + * @return array List of order + * + * @since 2.0.6 + */ + public static function getManufacturerOrderByList() + { + $order = array(); + + $order[0] = new stdClass; + $order[0]->value = "mn.name ASC"; + $order[0]->text = JText::_('COM_REDSHOP_ALPHABETICALLY'); + + $order[1] = new stdClass; + $order[1]->value = "mn.id DESC"; + $order[1]->text = JText::_('COM_REDSHOP_NEWEST'); + + $order[2] = new stdClass; + $order[2]->value = "mn.ordering ASC"; + $order[2]->text = JText::_('COM_REDSHOP_ORDERING'); + + return $order; + } + + /** + * Method for get product related order by list + * + * @return array List of order + * + * @since 2.0.6 + */ + public static function getRelatedOrderByList() + { + $order = array(); + + $order[0] = new stdClass; + $order[0]->value = "p.product_name ASC"; + $order[0]->text = JText::_('COM_REDSHOP_PRODUCT_NAME_ASC'); + + $order[1] = new stdClass; + $order[1]->value = "p.product_name DESC"; + $order[1]->text = JText::_('COM_REDSHOP_PRODUCT_NAME_DESC'); + + $order[2] = new stdClass; + $order[2]->value = "p.product_price ASC"; + $order[2]->text = JText::_('COM_REDSHOP_PRODUCT_PRICE_ASC'); + + $order[3] = new stdClass; + $order[3]->value = "p.product_price DESC"; + $order[3]->text = JText::_('COM_REDSHOP_PRODUCT_PRICE_DESC'); + + $order[4] = new stdClass; + $order[4]->value = "p.product_number ASC"; + $order[4]->text = JText::_('COM_REDSHOP_PRODUCT_NUMBER_ASC'); + + $order[5] = new stdClass; + $order[5]->value = "p.product_number DESC"; + $order[5]->text = JText::_('COM_REDSHOP_PRODUCT_NUMBER_DESC'); + + $order[6] = new stdClass; + $order[6]->value = "r.ordering ASC"; + $order[6]->text = JText::_('COM_REDSHOP_ORDERING_ASC'); + + $order[7] = new stdClass; + $order[7]->value = "r.ordering DESC"; + $order[7]->text = JText::_('COM_REDSHOP_ORDERING_DESC'); + + if (self::isRedProductFinder()) { + $order[8] = new stdClass; + $order[8]->value = "e.data_txt ASC"; + $order[8]->text = JText::_('COM_REDSHOP_DATEPICKER_ASC'); + + $order[9] = new stdClass; + $order[9]->value = "e.data_txt DESC"; + $order[9]->text = JText::_('COM_REDSHOP_DATEPICKER_DESC'); + } + + return $order; + } + + /** + * Method for check if ProductFinder is available or not. + * + * @return boolean + * + * @since 2.0.6 + */ + public static function isRedProductFinder() + { + if (self::$isRedProductFinder === null) { + // Get redshop from joomla component table + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select($db->qn('enabled')) + ->from($db->qn('#__extensions')) + ->where('element = ' . $db->q('com_redproductfinder')); + + $redProductFinderPath = JPATH_ADMINISTRATOR . '/components/com_redproductfinder'; + + if (!is_dir($redProductFinderPath) || $db->setQuery($query)->loadResult() == 0) { + self::$isRedProductFinder = false; + } else { + self::$isRedProductFinder = true; + } + } + + return self::$isRedProductFinder; + } + + /** + * Method for get accessory order by list + * + * @return array List of order + * + * @since 2.0.6 + */ + public static function getAccessoryOrderByList() + { + $order = array(); + + $order[0] = new stdClass; + $order[0]->value = "child_product_id ASC"; + $order[0]->text = JText::_('COM_REDSHOP_PRODUCT_ID_ASC'); + + $order[1] = new stdClass; + $order[1]->value = "child_product_id DESC"; + $order[1]->text = JText::_('COM_REDSHOP_PRODUCT_ID_DESC'); + + $order[2] = new stdClass; + $order[2]->value = "accessory_id ASC"; + $order[2]->text = JText::_('COM_REDSHOP_ACCESSORY_ID_ASC'); + + $order[3] = new stdClass; + $order[3]->value = "accessory_id DESC"; + $order[3]->text = JText::_('COM_REDSHOP_ACCESSORY_ID_DESC'); + + $order[4] = new stdClass; + $order[4]->value = "newaccessory_price ASC"; + $order[4]->text = JText::_('COM_REDSHOP_ACCESSORY_PRICE_ASC'); + + $order[5] = new stdClass; + $order[5]->value = "newaccessory_price DESC"; + $order[5]->text = JText::_('COM_REDSHOP_ACCESSORY_PRICE_DESC'); + + $order[6] = new stdClass; + $order[6]->value = "ordering ASC"; + $order[6]->text = JText::_('COM_REDSHOP_ORDERING_ASC'); + + $order[7] = new stdClass; + $order[7]->value = "ordering DESC"; + $order[7]->text = JText::_('COM_REDSHOP_ORDERING_DESC'); + + return $order; + } + + /** + * Method for get pre-order by list + * + * @return array List of order + * + * @since 2.0.6 + */ + public static function getPreOrderByList() + { + $preOrder = array(); + + $preOrder[0] = new stdClass; + $preOrder[0]->value = "global"; + $preOrder[0]->text = JText::_('COM_REDSHOP_GLOBAL'); + + $preOrder[1] = new stdClass; + $preOrder[1]->value = "yes"; + $preOrder[1]->text = JText::_('COM_REDSHOP_YES'); + + $preOrder[2] = new stdClass; + $preOrder[2]->value = "no"; + $preOrder[2]->text = JText::_('COM_REDSHOP_NO'); + + return $preOrder; + } + + /** + * Method for get child product order by list + * + * @return array List of order + * + * @since 2.0.6 + */ + public static function getChildProductOption() + { + $childProduct = array(); + + $childProduct[0] = new stdClass; + $childProduct[0]->value = "product_name"; + $childProduct[0]->text = JText::_('COM_REDSHOP_CHILD_PRODUCT_NAME'); + + $childProduct[1] = new stdClass; + $childProduct[1]->value = "product_number"; + $childProduct[1]->text = JText::_('COM_REDSHOP_CHILD_PRODUCT_NUMBER'); + + return $childProduct; + } + + /** + * Method for get child product order by list + * + * @return array List of order + * + * @since 2.0.6 + */ + public static function getStateAbbreviationsByList() + { + $stateData = array(); + + $stateData[0] = new stdClass; + $stateData[0]->value = "2"; + $stateData[0]->text = JText::_('COM_REDSHOP_TWO_LETTER_ABBRIVATION'); + + $stateData[1] = new stdClass; + $stateData[1]->value = "3"; + $stateData[1]->text = JText::_('COM_REDSHOP_THREE_LETTER_ABBRIVATION'); + + return $stateData; + } + + /** + * Method for get Economic Account Group + * + * @param integer $accountGroupId Account group ID + * @param integer $front Is front or not + * + * @return array + * + * @since 2.0.6 + */ + public static function getEconomicAccountGroup($accountGroupId = 0, $front = 0) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('ea.*') + ->select($db->qn('ea.accountgroup_id', 'value')) + ->select($db->qn('ea.accountgroup_name', 'text')) + ->from($db->qn('#__redshop_economic_accountgroup', 'ea')); + + if ($accountGroupId) { + $query->where($db->qn('ea.accountgroup_id') . ' = ' . (int)$accountGroupId); + } + + if ($front) { + $query->where($db->qn('ea.published') . ' = 1'); + } + + return $db->setQuery($query)->loadObjectList(); + } } diff --git a/libraries/redshop/helper/virtuemart.php b/libraries/redshop/helper/virtuemart.php index 991dfd9903a..d15d2ac9fef 100644 --- a/libraries/redshop/helper/virtuemart.php +++ b/libraries/redshop/helper/virtuemart.php @@ -18,76 +18,71 @@ */ class RedshopHelperVirtuemart { - /** - * @var array - * - * @since 2.1.0 - */ - protected static $vmShopperGroups = array(); + /** + * @var array + * + * @since 2.1.0 + */ + protected static $vmShopperGroups = array(); - /** - * @var array - * - * @since 2.1.0 - */ - protected static $shopperGroups = array(); + /** + * @var array + * + * @since 2.1.0 + */ + protected static $shopperGroups = array(); - /** - * Method for get shopper group ID - * - * @param integer $id ID of virtue mart shopper group - * - * @return string Name of virtue mart. - * - * @since 2.1.0 - */ - public static function getVirtuemartShopperGroups($id) - { - if (!array_key_exists($id, self::$vmShopperGroups)) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('shopper_group_name')) - ->from($db->qn('#__virtuemart_shoppergroups')) - ->where($db->qn('virtuemart_shoppergroup_id') . ' = ' . $id); + /** + * Method for get shopper group ID + * + * @param integer $id ID of virtue mart shopper group + * + * @return string Name of virtue mart. + * + * @since 2.1.0 + */ + public static function getVirtuemartShopperGroups($id) + { + if (!array_key_exists($id, self::$vmShopperGroups)) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('shopper_group_name')) + ->from($db->qn('#__virtuemart_shoppergroups')) + ->where($db->qn('virtuemart_shoppergroup_id') . ' = ' . $id); - self::$vmShopperGroups[$id] = $db->setQuery($query)->loadResult(); - } + self::$vmShopperGroups[$id] = $db->setQuery($query)->loadResult(); + } - return self::$vmShopperGroups[$id]; - } + return self::$vmShopperGroups[$id]; + } - /** - * Method for get redshop shopper group base on name - * - * @param string $name ID of virtue mart shopper group - * - * @return string Name of redshop shopper group. - * - * @since 2.1.0 - */ - public static function getRedshopShopperGroups($name = '') - { - if ($name == 'COM_VIRTUEMART_SHOPPERGROUP_DEFAULT') - { - $name = JText::_('COM_REDSHOP_IMPORT_VM_SHOPPERGROUP_DEFAULT'); - } - elseif ($name == 'COM_VIRTUEMART_SHOPPERGROUP_GUEST') - { - $name = JText::_('COM_REDSHOP_IMPORT_VM_SHOPPERGROUP_GUEST'); - } + /** + * Method for get redshop shopper group base on name + * + * @param string $name ID of virtue mart shopper group + * + * @return string Name of redshop shopper group. + * + * @since 2.1.0 + */ + public static function getRedshopShopperGroups($name = '') + { + if ($name == 'COM_VIRTUEMART_SHOPPERGROUP_DEFAULT') { + $name = JText::_('COM_REDSHOP_IMPORT_VM_SHOPPERGROUP_DEFAULT'); + } elseif ($name == 'COM_VIRTUEMART_SHOPPERGROUP_GUEST') { + $name = JText::_('COM_REDSHOP_IMPORT_VM_SHOPPERGROUP_GUEST'); + } - if (!array_key_exists($name, self::$shopperGroups)) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn('shopper_group_id', 'id')) - ->from($db->qn('#__redshop_shopper_group')) - ->where($db->qn('shopper_group_name') . ' = ' . $db->quote($name)); + if (!array_key_exists($name, self::$shopperGroups)) { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn('shopper_group_id', 'id')) + ->from($db->qn('#__redshop_shopper_group')) + ->where($db->qn('shopper_group_name') . ' = ' . $db->quote($name)); - self::$shopperGroups[$name] = $db->setQuery($query)->loadResult(); - } + self::$shopperGroups[$name] = $db->setQuery($query)->loadResult(); + } - return self::$shopperGroups[$name]; - } + return self::$shopperGroups[$name]; + } } diff --git a/libraries/redshop/helper/wishlist.php b/libraries/redshop/helper/wishlist.php index b6d14407e63..a668c563468 100644 --- a/libraries/redshop/helper/wishlist.php +++ b/libraries/redshop/helper/wishlist.php @@ -16,320 +16,305 @@ */ class RedshopHelperWishlist { - /** - * List of Wishlist. - * - * @var array - * - * @since 2.0.3 - */ - protected static $wishLists = array(); - - /** - * List of Wishlist. - * - * @var array - * - * @since 2.0.3 - */ - protected static $usersWishlist = array(); - - /** - * Method for replace wishlist tag in template. - * - * @param int $productId Product ID - * @param string $templateContent HTML data of template content - * @param string $formId DOM ID of add to cart form. - * - * @return string HTML data of replaced content. - * - * @since 2.0.3 - */ - public static function replaceWishlistTag($productId = 0, $templateContent = '', $formId = '') - { - if (Redshop::getConfig()->get('MY_WISHLIST') == 0) - { - $templateContent = str_replace('{wishlist_button}', '', $templateContent); - $templateContent = str_replace('{wishlist_link}', '', $templateContent); - $templateContent = str_replace('{property_wishlist_link}', '', $templateContent); - - return $templateContent; - } - - return RedshopTagsReplacer::_('wishlist', $templateContent, array('productId' => $productId, 'formId' => $formId)); - } - - /** - * Method for get product items of specific Wishlist Product. - * - * @param int $wishlistId ID of Wishlist ID. - * - * @return mixed Data if success. False otherwise. - * - * @since 2.0.3 - */ - public static function getWishlist($wishlistId = 0) - { - $wishlistId = (int) $wishlistId; - - if (!$wishlistId) - { - return false; - } - - if (!array_key_exists($wishlistId, static::$wishLists)) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_wishlist')) - ->where($db->qn('wishlist_id') . ' = ' . $wishlistId); - - $wishlist = $db->setQuery($query)->loadObject(); - $wishlist->products = array(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_wishlist_product')) - ->where($db->qn('wishlist_id') . ' = ' . $wishlistId); - - $wishlistProducts = $db->setQuery($query)->loadObjectList(); - - if (empty($wishlistProducts) || !Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE')) - { - static::$wishLists[$wishlistId] = $wishlist; - - return static::$wishLists[$wishlistId]; - } - - $query->clear() - ->select($db->qn('wpi.ref_id')) - ->select($db->qn('wpi.attribute_id')) - ->select($db->qn('wpi.property_id')) - ->select($db->qn('wpi.subattribute_id')) - ->from($db->qn('#__redshop_wishlist_product_item', 'wpi')) - ->leftJoin($db->qn('#__redshop_wishlist_product', 'wp') . ' ON ' . $db->qn('wp.wishlist_product_id') . ' = ' . $db->qn('wpi.ref_id')) - ->where($db->qn('wp.wishlist_id') . ' = ' . $wishlistId); - $wishlistProductItems = $db->setQuery($query)->loadObjectList(); - - foreach ($wishlistProducts as $wishlistProduct) - { - if (!array_key_exists($wishlistProduct->product_id, $wishlist->products)) - { - $wishlist->products[$wishlistProduct->product_id] = array(); - } - - $wishlistProduct->product_items = array(); - $wishlistProduct->attributes = array(); - $wishlistProduct->properties = array(); - $wishlistProduct->subAttributes = array(); - - foreach ($wishlistProductItems as $key => $wishlistProductItem) - { - if ($wishlistProductItem->ref_id == $wishlistProduct->wishlist_product_id) - { - $wishlistProduct->product_items[$wishlistProductItem->attribute_id] = $wishlistProductItem; - - unset($wishlistProductItems[$key]); - } - } - - foreach ($wishlistProduct->product_items as $productItem) - { - $wishlistProduct->attributes[] = $productItem->attribute_id; - $wishlistProduct->properties[] = $productItem->property_id; - $wishlistProduct->subAttributes[] = $productItem->subattribute_id; - } - - $wishlistProduct->attributes = array_filter($wishlistProduct->attributes); - $wishlistProduct->properties = array_filter($wishlistProduct->properties); - $wishlistProduct->subAttributes = array_filter($wishlistProduct->subAttributes); - - $wishlist->products[$wishlistProduct->product_id][] = $wishlistProduct; - } - - static::$wishLists[$wishlistId] = $wishlist; - } - - return static::$wishLists[$wishlistId]; - } - - /** - * Method for get Wishlist data of specific user. - * - * @param int $userId ID of user. - * - * @return mixed - * - * @since 2.0.3 - */ - public static function getUserWishlist($userId = 0) - { - $userId = (int) $userId; - - if (!$userId) - { - $userId = JFactory::getUser()->id; - } - - if (!$userId) - { - return false; - } - - if (!array_key_exists($userId, static::$usersWishlist)) - { - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('wishlist_id') - ->from($db->qn('#__redshop_wishlist')) - ->where($db->qn('user_id') . ' = ' . $userId); - - $wishList = $db->setQuery($query)->loadObjectList(); - - if (empty($wishList)) - { - $wishList = array(self::createWishlistDefault($userId)); - } - - if (empty($wishList)) - { - static::$usersWishlist[$userId] = array(); - - return static::$usersWishlist[$userId]; - } - - foreach ($wishList as $wish) - { - static::$usersWishlist[$userId][$wish->wishlist_id] = self::getWishlist($wish->wishlist_id); - } - } - - return static::$usersWishlist[$userId]; - } - - /** - * Method for check product exist in wishlist. - * - * @param int $productId ID of Product. - * - * @return mixed Data if success. False otherwise. - * - * @since 2.0.3 - */ - public static function checkWishlistExist($productId = 0) - { - $productId = (int) $productId; - - if (!$productId) - { - return false; - } - - $userWishlists = self::getUserWishlist(); - - if (empty($userWishlists)) - { - return false; - } - - foreach ($userWishlists as $wishListId => $userWishlist) - { - if (!empty($userWishlist->products) && array_key_exists($productId, $userWishlist->products)) - { - return true; - } - } - - return false; - } - - /** - * Method for get Wishlist module base in element name - * - * @param string $elementName Element name - * - * @return object|null - * - * @since 2.0.6 - */ - public static function getWishlistModule($elementName) - { - if (empty($elementName)) - { - return null; - } - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__extensions')) - ->where($db->qn('element') . ' = ' . $db->quote($elementName)); - - return $db->setQuery($query)->loadObject(); - } - - /** - * Method for get Wishlist user field data - * - * @param integer $wishlistId Wish list id - * @param integer $productId Product Id - * - * @return array - * - * @since 2.0.6 - */ - public static function getUserFieldData($wishlistId, $productId) - { - if (empty($wishlistId) || empty($productId)) - { - return array(); - } - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select('*') - ->from($db->qn('#__redshop_wishlist_userfielddata')) - ->where($db->qn('wishlist_id') . ' = ' . $db->quote($wishlistId)) - ->where($db->qn('product_id') . ' = ' . (int) $productId) - ->order($db->qn('fieldid') . ' ASC'); - - return $db->setQuery($query)->loadObjectList(); - } - - /** - * Create Default wishlist list - * - * @param int $userId ID of user. - * - * @return object|null - */ - private static function createWishlistDefault($userId) - { - if (!$userId) - { - return null; - } - - $db = JFactory::getDbo(); - - $wishlist = new stdClass; - $wishlist->wishlist_name = 'Default'; - $wishlist->user_id = $userId; - $wishlist->cdate = $db->quote(time()); - - // Insert the object into the user profile table. - if ($db->insertObject('#__redshop_wishlist', $wishlist)) - { - $wishlist->wishlist_id = $db->insertid(); - - return $wishlist; - } - - return null; - } + /** + * List of Wishlist. + * + * @var array + * + * @since 2.0.3 + */ + protected static $wishLists = array(); + + /** + * List of Wishlist. + * + * @var array + * + * @since 2.0.3 + */ + protected static $usersWishlist = array(); + + /** + * Method for replace wishlist tag in template. + * + * @param int $productId Product ID + * @param string $templateContent HTML data of template content + * @param string $formId DOM ID of add to cart form. + * + * @return string HTML data of replaced content. + * + * @since 2.0.3 + */ + public static function replaceWishlistTag($productId = 0, $templateContent = '', $formId = '') + { + if (Redshop::getConfig()->get('MY_WISHLIST') == 0) { + $templateContent = str_replace('{wishlist_button}', '', $templateContent); + $templateContent = str_replace('{wishlist_link}', '', $templateContent); + $templateContent = str_replace('{property_wishlist_link}', '', $templateContent); + + return $templateContent; + } + + return RedshopTagsReplacer::_( + 'wishlist', + $templateContent, + array('productId' => $productId, 'formId' => $formId) + ); + } + + /** + * Method for check product exist in wishlist. + * + * @param int $productId ID of Product. + * + * @return mixed Data if success. False otherwise. + * + * @since 2.0.3 + */ + public static function checkWishlistExist($productId = 0) + { + $productId = (int)$productId; + + if (!$productId) { + return false; + } + + $userWishlists = self::getUserWishlist(); + + if (empty($userWishlists)) { + return false; + } + + foreach ($userWishlists as $wishListId => $userWishlist) { + if (!empty($userWishlist->products) && array_key_exists($productId, $userWishlist->products)) { + return true; + } + } + + return false; + } + + /** + * Method for get Wishlist data of specific user. + * + * @param int $userId ID of user. + * + * @return mixed + * + * @since 2.0.3 + */ + public static function getUserWishlist($userId = 0) + { + $userId = (int)$userId; + + if (!$userId) { + $userId = JFactory::getUser()->id; + } + + if (!$userId) { + return false; + } + + if (!array_key_exists($userId, static::$usersWishlist)) { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('wishlist_id') + ->from($db->qn('#__redshop_wishlist')) + ->where($db->qn('user_id') . ' = ' . $userId); + + $wishList = $db->setQuery($query)->loadObjectList(); + + if (empty($wishList)) { + $wishList = array(self::createWishlistDefault($userId)); + } + + if (empty($wishList)) { + static::$usersWishlist[$userId] = array(); + + return static::$usersWishlist[$userId]; + } + + foreach ($wishList as $wish) { + static::$usersWishlist[$userId][$wish->wishlist_id] = self::getWishlist($wish->wishlist_id); + } + } + + return static::$usersWishlist[$userId]; + } + + /** + * Create Default wishlist list + * + * @param int $userId ID of user. + * + * @return object|null + */ + private static function createWishlistDefault($userId) + { + if (!$userId) { + return null; + } + + $db = JFactory::getDbo(); + + $wishlist = new stdClass; + $wishlist->wishlist_name = 'Default'; + $wishlist->user_id = $userId; + $wishlist->cdate = $db->quote(time()); + + // Insert the object into the user profile table. + if ($db->insertObject('#__redshop_wishlist', $wishlist)) { + $wishlist->wishlist_id = $db->insertid(); + + return $wishlist; + } + + return null; + } + + /** + * Method for get product items of specific Wishlist Product. + * + * @param int $wishlistId ID of Wishlist ID. + * + * @return mixed Data if success. False otherwise. + * + * @since 2.0.3 + */ + public static function getWishlist($wishlistId = 0) + { + $wishlistId = (int)$wishlistId; + + if (!$wishlistId) { + return false; + } + + if (!array_key_exists($wishlistId, static::$wishLists)) { + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_wishlist')) + ->where($db->qn('wishlist_id') . ' = ' . $wishlistId); + + $wishlist = $db->setQuery($query)->loadObject(); + $wishlist->products = array(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_wishlist_product')) + ->where($db->qn('wishlist_id') . ' = ' . $wishlistId); + + $wishlistProducts = $db->setQuery($query)->loadObjectList(); + + if (empty($wishlistProducts) || !Redshop::getConfig()->get('INDIVIDUAL_ADD_TO_CART_ENABLE')) { + static::$wishLists[$wishlistId] = $wishlist; + + return static::$wishLists[$wishlistId]; + } + + $query->clear() + ->select($db->qn('wpi.ref_id')) + ->select($db->qn('wpi.attribute_id')) + ->select($db->qn('wpi.property_id')) + ->select($db->qn('wpi.subattribute_id')) + ->from($db->qn('#__redshop_wishlist_product_item', 'wpi')) + ->leftJoin( + $db->qn('#__redshop_wishlist_product', 'wp') . ' ON ' . $db->qn( + 'wp.wishlist_product_id' + ) . ' = ' . $db->qn('wpi.ref_id') + ) + ->where($db->qn('wp.wishlist_id') . ' = ' . $wishlistId); + $wishlistProductItems = $db->setQuery($query)->loadObjectList(); + + foreach ($wishlistProducts as $wishlistProduct) { + if (!array_key_exists($wishlistProduct->product_id, $wishlist->products)) { + $wishlist->products[$wishlistProduct->product_id] = array(); + } + + $wishlistProduct->product_items = array(); + $wishlistProduct->attributes = array(); + $wishlistProduct->properties = array(); + $wishlistProduct->subAttributes = array(); + + foreach ($wishlistProductItems as $key => $wishlistProductItem) { + if ($wishlistProductItem->ref_id == $wishlistProduct->wishlist_product_id) { + $wishlistProduct->product_items[$wishlistProductItem->attribute_id] = $wishlistProductItem; + + unset($wishlistProductItems[$key]); + } + } + + foreach ($wishlistProduct->product_items as $productItem) { + $wishlistProduct->attributes[] = $productItem->attribute_id; + $wishlistProduct->properties[] = $productItem->property_id; + $wishlistProduct->subAttributes[] = $productItem->subattribute_id; + } + + $wishlistProduct->attributes = array_filter($wishlistProduct->attributes); + $wishlistProduct->properties = array_filter($wishlistProduct->properties); + $wishlistProduct->subAttributes = array_filter($wishlistProduct->subAttributes); + + $wishlist->products[$wishlistProduct->product_id][] = $wishlistProduct; + } + + static::$wishLists[$wishlistId] = $wishlist; + } + + return static::$wishLists[$wishlistId]; + } + + /** + * Method for get Wishlist module base in element name + * + * @param string $elementName Element name + * + * @return object|null + * + * @since 2.0.6 + */ + public static function getWishlistModule($elementName) + { + if (empty($elementName)) { + return null; + } + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__extensions')) + ->where($db->qn('element') . ' = ' . $db->quote($elementName)); + + return $db->setQuery($query)->loadObject(); + } + + /** + * Method for get Wishlist user field data + * + * @param integer $wishlistId Wish list id + * @param integer $productId Product Id + * + * @return array + * + * @since 2.0.6 + */ + public static function getUserFieldData($wishlistId, $productId) + { + if (empty($wishlistId) || empty($productId)) { + return array(); + } + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select('*') + ->from($db->qn('#__redshop_wishlist_userfielddata')) + ->where($db->qn('wishlist_id') . ' = ' . $db->quote($wishlistId)) + ->where($db->qn('product_id') . ' = ' . (int)$productId) + ->order($db->qn('fieldid') . ' ASC'); + + return $db->setQuery($query)->loadObjectList(); + } } diff --git a/libraries/redshop/helper/world.php b/libraries/redshop/helper/world.php index ad0b81adb8d..7a4b1ecb481 100644 --- a/libraries/redshop/helper/world.php +++ b/libraries/redshop/helper/world.php @@ -16,423 +16,407 @@ */ class RedshopHelperWorld { - /** - * Static instance of class - * - * @var null - */ - protected static $instance = null; - - /** - * Countries supported in shop - * - * @var array - */ - protected static $countries = array(); - - /** - * States based on given country - * - * @var array - */ - protected static $states = array(); - - /** - * Returns the RedshopHelperWorld object, only creating it - * if it does not already exist. - * - * @return RedshopHelperWorld The RedshopHelperWorld object - * - * @since 1.6 - */ - public static function getInstance() - { - if (self::$instance === null) - { - self::$instance = new self; - } - - return self::$instance; - } - - /** - * Get all the countries supported by shop - * - * @return array Countries - */ - public static function countries() - { - if (!empty(self::$countries)) - { - return self::$countries; - } - - $db = JFactory::getDbo(); - - // Load allowed countries from config - $countries = Redshop::getConfig()->get('COUNTRY_LIST'); - - if (!empty($countries)) - { - // Covert them into an array - $countries = explode(',', $countries); - - if (!empty($countries)) - { - // Quote them and prepare for query - $countries = self::quoteArray($countries); - - $query = $db->getQuery(true) - ->select( - array( - $db->qn('country_3_code', 'value'), - $db->qn('country_name', 'text'), - $db->qn('country_jtext'), - ) - ) - ->from($db->qn('#__redshop_country')) - ->where($db->qn('country_3_code') . ' IN (' . implode(',', $countries) . ')') - ->order($db->qn('country_name')); - - // Set the query and load the result. - $db->setQuery($query); - - self::$countries = RedshopHelperUtility::convertLanguageString($db->loadObjectList()); - - // Check for a database error. - if ($db->getErrorNum()) - { - JError::raiseWarning(500, $db->getErrorMsg()); - - return null; - } - } - } - - return self::$countries; - } - - /** - * Get states based on country - * - * @param string $country Country Code - * @param string $fieldValue State field column for value - * - * @return array States information - */ - public static function getStates($country, $fieldValue = 'state_2_code') - { - $key = $country . '_' . $fieldValue; - - if (array_key_exists($key, self::$states)) - { - return self::$states[$key]; - } - - $db = JFactory::getDbo(); - - $query = $db->getQuery(true) - ->select( - array( - $db->qn('s.' . $fieldValue, 'value'), - $db->qn('s.state_name', 'text') - ) - ) - ->from($db->qn('#__redshop_state', 's')) - ->leftJoin($db->qn('#__redshop_country', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('s.country_id')) - ->where($db->qn('c.country_3_code') . ' = ' . $db->quote($country)) - ->order($db->qn('s.state_name')); - - // Set the query and load the result. - $db->setQuery($query); - $states = $db->loadObjectList(); - - // Check for a database error. - if ($db->getErrorNum()) - { - JError::raiseWarning(500, $db->getErrorMsg()); - - return null; - } - - // Store in states array - self::$states[$key] = $states; - - return self::$states[$key]; - } - - /** - * Get country dropdown - * - * @param array $post Information from post data - * @param string $countryListName Name of the select element - * @param string $addressType Address type. BT or ST - * @param string $class Country select list class name - * @param string $stateListId State list. - * - * @return array Country list information - */ - public static function getCountryList($post = array(), $countryListName = "country_code", $addressType = "BT", $class = "inputbox form-control", - $stateListId = "state_code") - { - $addressType = ($addressType == "ST") ? "_ST" : ""; - $countries = self::countries(); - $totalCountries = count($countries); - $selectedCountry = Redshop::getConfig()->get('SHOP_COUNTRY'); - - if ($totalCountries == 1) - { - $selectedCountry = $countries[0]->value; - } - - if (isset($post['country_code' . $addressType])) - { - $selectedCountry = $post['country_code' . $addressType]; - } - - // Only offer please select hint if more than one countries. - if ($totalCountries > 1) - { - $countries = array_merge( - array(JHtml::_('select.option', '', JText::_('COM_REDSHOP_SELECT'))), - $countries - ); - } - - $countryCode = ''; - - foreach ($countries as $country) - { - if ($country->value == $selectedCountry) - { - $countryCode = $selectedCountry; - - break; - } - } - - return array( - 'countrylist' => $countries, - 'country_code' . $addressType => $countryCode, - 'country_dropdown' => JHTML::_( - 'select.genericlist', - $countries, - $countryListName, - array('class' => $class, 'stateId' => 'rs_state_' . $stateListId), - 'value', - 'text', - $selectedCountry, - 'rs_country_' . $countryListName - ) - ); - } - - /** - * This function will get state list from country code and return HTML of state (both billing and shipping) - * - * @param array $post $post get from $_POST request - * @param string $stateListName State Code from billing or Shipping - * @param string $addressType Distinguish billing or shipping - * @param string $class Class of state of selected field - * @param string $fieldValue Field column for value - * - * @return array - */ - public static function getStateList($post = array(), $stateListName = "state_code", $addressType = "BT", $class = "inputbox form-control", - $fieldValue = 'state_2_code') - { - $selectedCountryCode = Redshop::getConfig()->get('SHOP_COUNTRY'); - - if (isset($post['country_code'])) - { - $selectedCountryCode = $post['country_code']; - } - elseif (isset($post['country_code_ST'])) - { - $selectedCountryCode = $post['country_code_ST']; - } - - $selectedStateCode = ""; - - if (isset($post['state_code'])) - { - $selectedStateCode = $post['state_code']; - } - elseif (isset($post['state_code_ST'])) - { - $selectedStateCode = $post['state_code_ST']; - } - - $states = self::getStates($selectedCountryCode, $fieldValue); - - $totalStates = count($states); - - if ($totalStates > 1) - { - $states = array_merge( - array(JHtml::_('select.option', '', JText::_("COM_REDSHOP_SELECT"))), - $states - ); - } - - return array( - 'statelist' => $states, - 'is_states' => $totalStates, - 'state_dropdown' => JHTML::_( - 'select.genericlist', - $states, - $stateListName, - array('class' => $class), - 'value', - 'text', - $selectedStateCode, - 'rs_state_' . $stateListName - ) - ); - } - - /** - * AJAX Task to get states list - * - * @param string $countryCode Country code. - * - * @return string JSON encoded string of states list. - */ - public static function getStatesAjax($countryCode) - { - $states = self::getStates($countryCode); - - if (!empty($states)) - { - $states = array_merge( - array(JHtml::_('select.option', '', JText::_("COM_REDSHOP_SELECT"))), - $states - ); - } - - return json_encode($states); - } - - /** - * Method for quote array - * - * @param array $list List of item for quote. - * - * @return array - * - * @since 2.0.3 - */ - protected static function quoteArray($list = array()) - { - if (empty($list) || !is_array($list)) - { - return array(); - } - - $db = JFactory::getDbo(); - - foreach ($list as $key => $item) - { - $list[$key] = $db->quote($item); - } - - return $list; - } - - /** - * Method to get Country ID by country 3 code. - * - * @param int $country3code Country 3 code - * - * @return int - * - * @since 2.0.6 - */ - public static function getCountryId($country3code) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select($db->qn('id')) - ->from($db->qn('#__redshop_country')) - ->where($db->qn('country_3_code') . ' LIKE ' . $db->quote($country3code)); - - return $db->setQuery($query)->loadResult(); - } - - /** - * Method to get Country 2 code by Country 3 code. - * - * @param int $country3code Country 3 code - * - * @return string - * - * @since 2.0.6 - */ - public static function getCountryCode2($country3code) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select($db->qn('country_2_code')) - ->from($db->qn('#__redshop_country')) - ->where($db->qn('country_3_code') . ' LIKE ' . $db->quote($country3code)); - - return $db->setQuery($query)->loadResult(); - } - - /** - * Method to get State code 2 by State code 3. - * - * @param int $stateCode State 3 code - * - * @return string - * - * @since 2.0.6 - */ - public static function getStateCode2($stateCode) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select($db->qn('state_2_code')) - ->from($db->qn('#__redshop_state')) - ->where($db->qn('state_3_code') . ' LIKE ' . $db->quote($stateCode)); - - return $db->setQuery($query)->loadResult(); - } - - /** - * Method for get State Code - * - * @param int $id ID of state. - * @param string $stateCode State code 2 - * - * @return string - * - * @since 2.0.6 - */ - public static function getStateCode($id, $stateCode) - { - if (empty($stateCode)) - { - return null; - } - - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select($db->qn(array('state_3_code', 'show_state'))) - ->from($db->qn('#__redshop_state')) - ->where($db->qn('state_2_code') . ' LIKE ' . $db->quote($stateCode)) - ->where($db->qn('id') . ' = ' . (int) $id); - - $result = $db->setQuery($query)->loadObject(); - - if ($result && $result->show_state == 3) - { - return $result->state_3_code; - } - - return $stateCode; - } + /** + * Static instance of class + * + * @var null + */ + protected static $instance = null; + + /** + * Countries supported in shop + * + * @var array + */ + protected static $countries = array(); + + /** + * States based on given country + * + * @var array + */ + protected static $states = array(); + + /** + * Returns the RedshopHelperWorld object, only creating it + * if it does not already exist. + * + * @return RedshopHelperWorld The RedshopHelperWorld object + * + * @since 1.6 + */ + public static function getInstance() + { + if (self::$instance === null) { + self::$instance = new self; + } + + return self::$instance; + } + + /** + * Get country dropdown + * + * @param array $post Information from post data + * @param string $countryListName Name of the select element + * @param string $addressType Address type. BT or ST + * @param string $class Country select list class name + * @param string $stateListId State list. + * + * @return array Country list information + */ + public static function getCountryList( + $post = array(), + $countryListName = "country_code", + $addressType = "BT", + $class = "inputbox form-control", + $stateListId = "state_code" + ) { + $addressType = ($addressType == "ST") ? "_ST" : ""; + $countries = self::countries(); + $totalCountries = count($countries); + $selectedCountry = Redshop::getConfig()->get('SHOP_COUNTRY'); + + if ($totalCountries == 1) { + $selectedCountry = $countries[0]->value; + } + + if (isset($post['country_code' . $addressType])) { + $selectedCountry = $post['country_code' . $addressType]; + } + + // Only offer please select hint if more than one countries. + if ($totalCountries > 1) { + $countries = array_merge( + array(JHtml::_('select.option', '', JText::_('COM_REDSHOP_SELECT'))), + $countries + ); + } + + $countryCode = ''; + + foreach ($countries as $country) { + if ($country->value == $selectedCountry) { + $countryCode = $selectedCountry; + + break; + } + } + + return array( + 'countrylist' => $countries, + 'country_code' . $addressType => $countryCode, + 'country_dropdown' => JHTML::_( + 'select.genericlist', + $countries, + $countryListName, + array('class' => $class, 'stateId' => 'rs_state_' . $stateListId), + 'value', + 'text', + $selectedCountry, + 'rs_country_' . $countryListName + ) + ); + } + + /** + * Get all the countries supported by shop + * + * @return array Countries + */ + public static function countries() + { + if (!empty(self::$countries)) { + return self::$countries; + } + + $db = JFactory::getDbo(); + + // Load allowed countries from config + $countries = Redshop::getConfig()->get('COUNTRY_LIST'); + + if (!empty($countries)) { + // Covert them into an array + $countries = explode(',', $countries); + + if (!empty($countries)) { + // Quote them and prepare for query + $countries = self::quoteArray($countries); + + $query = $db->getQuery(true) + ->select( + array( + $db->qn('country_3_code', 'value'), + $db->qn('country_name', 'text'), + $db->qn('country_jtext'), + ) + ) + ->from($db->qn('#__redshop_country')) + ->where($db->qn('country_3_code') . ' IN (' . implode(',', $countries) . ')') + ->order($db->qn('country_name')); + + // Set the query and load the result. + $db->setQuery($query); + + self::$countries = RedshopHelperUtility::convertLanguageString($db->loadObjectList()); + + // Check for a database error. + if ($db->getErrorNum()) { + JError::raiseWarning(500, $db->getErrorMsg()); + + return null; + } + } + } + + return self::$countries; + } + + /** + * Method for quote array + * + * @param array $list List of item for quote. + * + * @return array + * + * @since 2.0.3 + */ + protected static function quoteArray($list = array()) + { + if (empty($list) || !is_array($list)) { + return array(); + } + + $db = JFactory::getDbo(); + + foreach ($list as $key => $item) { + $list[$key] = $db->quote($item); + } + + return $list; + } + + /** + * This function will get state list from country code and return HTML of state (both billing and shipping) + * + * @param array $post $post get from $_POST request + * @param string $stateListName State Code from billing or Shipping + * @param string $addressType Distinguish billing or shipping + * @param string $class Class of state of selected field + * @param string $fieldValue Field column for value + * + * @return array + */ + public static function getStateList( + $post = array(), + $stateListName = "state_code", + $addressType = "BT", + $class = "inputbox form-control", + $fieldValue = 'state_2_code' + ) { + $selectedCountryCode = Redshop::getConfig()->get('SHOP_COUNTRY'); + + if (isset($post['country_code'])) { + $selectedCountryCode = $post['country_code']; + } elseif (isset($post['country_code_ST'])) { + $selectedCountryCode = $post['country_code_ST']; + } + + $selectedStateCode = ""; + + if (isset($post['state_code'])) { + $selectedStateCode = $post['state_code']; + } elseif (isset($post['state_code_ST'])) { + $selectedStateCode = $post['state_code_ST']; + } + + $states = self::getStates($selectedCountryCode, $fieldValue); + + $totalStates = count($states); + + if ($totalStates > 1) { + $states = array_merge( + array(JHtml::_('select.option', '', JText::_("COM_REDSHOP_SELECT"))), + $states + ); + } + + return array( + 'statelist' => $states, + 'is_states' => $totalStates, + 'state_dropdown' => JHTML::_( + 'select.genericlist', + $states, + $stateListName, + array('class' => $class), + 'value', + 'text', + $selectedStateCode, + 'rs_state_' . $stateListName + ) + ); + } + + /** + * Get states based on country + * + * @param string $country Country Code + * @param string $fieldValue State field column for value + * + * @return array States information + */ + public static function getStates($country, $fieldValue = 'state_2_code') + { + $key = $country . '_' . $fieldValue; + + if (array_key_exists($key, self::$states)) { + return self::$states[$key]; + } + + $db = JFactory::getDbo(); + + $query = $db->getQuery(true) + ->select( + array( + $db->qn('s.' . $fieldValue, 'value'), + $db->qn('s.state_name', 'text') + ) + ) + ->from($db->qn('#__redshop_state', 's')) + ->leftJoin($db->qn('#__redshop_country', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('s.country_id')) + ->where($db->qn('c.country_3_code') . ' = ' . $db->quote($country)) + ->order($db->qn('s.state_name')); + + // Set the query and load the result. + $db->setQuery($query); + $states = $db->loadObjectList(); + + // Check for a database error. + if ($db->getErrorNum()) { + JError::raiseWarning(500, $db->getErrorMsg()); + + return null; + } + + // Store in states array + self::$states[$key] = $states; + + return self::$states[$key]; + } + + /** + * AJAX Task to get states list + * + * @param string $countryCode Country code. + * + * @return string JSON encoded string of states list. + */ + public static function getStatesAjax($countryCode) + { + $states = self::getStates($countryCode); + + if (!empty($states)) { + $states = array_merge( + array(JHtml::_('select.option', '', JText::_("COM_REDSHOP_SELECT"))), + $states + ); + } + + return json_encode($states); + } + + /** + * Method to get Country ID by country 3 code. + * + * @param int $country3code Country 3 code + * + * @return int + * + * @since 2.0.6 + */ + public static function getCountryId($country3code) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select($db->qn('id')) + ->from($db->qn('#__redshop_country')) + ->where($db->qn('country_3_code') . ' LIKE ' . $db->quote($country3code)); + + return $db->setQuery($query)->loadResult(); + } + + /** + * Method to get Country 2 code by Country 3 code. + * + * @param int $country3code Country 3 code + * + * @return string + * + * @since 2.0.6 + */ + public static function getCountryCode2($country3code) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select($db->qn('country_2_code')) + ->from($db->qn('#__redshop_country')) + ->where($db->qn('country_3_code') . ' LIKE ' . $db->quote($country3code)); + + return $db->setQuery($query)->loadResult(); + } + + /** + * Method to get State code 2 by State code 3. + * + * @param int $stateCode State 3 code + * + * @return string + * + * @since 2.0.6 + */ + public static function getStateCode2($stateCode) + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + + $query->select($db->qn('state_2_code')) + ->from($db->qn('#__redshop_state')) + ->where($db->qn('state_3_code') . ' LIKE ' . $db->quote($stateCode)); + + return $db->setQuery($query)->loadResult(); + } + + /** + * Method for get State Code + * + * @param int $id ID of state. + * @param string $stateCode State code 2 + * + * @return string + * + * @since 2.0.6 + */ + public static function getStateCode($id, $stateCode) + { + if (empty($stateCode)) { + return null; + } + + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select($db->qn(array('state_3_code', 'show_state'))) + ->from($db->qn('#__redshop_state')) + ->where($db->qn('state_2_code') . ' LIKE ' . $db->quote($stateCode)) + ->where($db->qn('id') . ' = ' . (int)$id); + + $result = $db->setQuery($query)->loadObject(); + + if ($result && $result->show_state == 3) { + return $result->state_3_code; + } + + return $stateCode; + } } diff --git a/libraries/redshop/html/redshopcalendar.php b/libraries/redshop/html/redshopcalendar.php index 78477bd4010..5403ca2d1f4 100644 --- a/libraries/redshop/html/redshopcalendar.php +++ b/libraries/redshop/html/redshopcalendar.php @@ -20,59 +20,61 @@ */ abstract class JHtmlRedshopcalendar { - /** - * Displays a calendar control field - * - * @param string $value The date value - * @param string $name The name of the text field - * @param string $id The id of the text field - * @param string $format The date format - * @param mixed $attribs Additional HTML attributes - * @param boolean $inline Inline or not - * @param string $tz Timezone of input value - * - * @return string HTML markup for a calendar field - * - * @since 1.5 - */ - public static function calendar($value, $name, $id, $format = '', $attribs = null, $inline = false, $tz = null) - { - $format = empty($format) ? Redshop::getConfig()->getString('DEFAULT_DATEFORMAT', 'Y-m-d') : $format; - $userTz = JFactory::getConfig()->get('offset'); + /** + * Displays a calendar control field + * + * @param string $value The date value + * @param string $name The name of the text field + * @param string $id The id of the text field + * @param string $format The date format + * @param mixed $attribs Additional HTML attributes + * @param boolean $inline Inline or not + * @param string $tz Timezone of input value + * + * @return string HTML markup for a calendar field + * + * @since 1.5 + */ + public static function calendar($value, $name, $id, $format = '', $attribs = null, $inline = false, $tz = null) + { + $format = empty($format) ? Redshop::getConfig()->getString('DEFAULT_DATEFORMAT', 'Y-m-d') : $format; + $userTz = JFactory::getConfig()->get('offset'); - if (is_array($attribs)) - { - $attribs['class'] = isset($attribs['class']) ? $attribs['class'] : 'input-medium'; - $attribs['class'] = trim($attribs['class'] . ' hasTooltip'); + if (is_array($attribs)) { + $attribs['class'] = isset($attribs['class']) ? $attribs['class'] : 'input-medium'; + $attribs['class'] = trim($attribs['class'] . ' hasTooltip'); - $attribs = ArrayHelper::toString($attribs); - } + $attribs = ArrayHelper::toString($attribs); + } - JHtml::_('bootstrap.tooltip'); + JHtml::_('bootstrap.tooltip'); - if (empty($tz)) - { - $tz = date_default_timezone_get(); - } + if (empty($tz)) { + $tz = date_default_timezone_get(); + } - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/moment.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/moment-timezone-with-data.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/bootstrap-datetimepicker.min.js', false, true, false, false); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/jquery.inputmask.min.js', false, true); - /** @scrutinizer ignore-deprecated */JHtml::stylesheet('com_redshop/bootstrap-datetimepicker.min.css', array(), true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/moment.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/moment-timezone-with-data.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/bootstrap-datetimepicker.min.js', false, true, false, false); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/jquery.inputmask.min.js', false, true); + /** @scrutinizer ignore-deprecated */ + JHtml::stylesheet('com_redshop/bootstrap-datetimepicker.min.css', array(), true); - $momentValue = false; + $momentValue = false; - if (!empty($value)) - { - $momentValue = DateTime::createFromFormat($format, $value, new DateTimeZone($tz)); - $momentValue = false !== $momentValue ? $momentValue->getTimestamp() : false; - } + if (!empty($value)) { + $momentValue = DateTime::createFromFormat($format, $value, new DateTimeZone($tz)); + $momentValue = false !== $momentValue ? $momentValue->getTimestamp() : false; + } - $defaultDate = $momentValue ? 'defaultDate: moment.unix(' . $momentValue . '),' : ''; + $defaultDate = $momentValue ? 'defaultDate: moment.unix(' . $momentValue . '),' : ''; - JFactory::getDocument()->addScriptDeclaration( - '(function($){ + JFactory::getDocument()->addScriptDeclaration( + '(function($){ $(document).ready(function(){ $("#' . $id . '_wrapper").datetimepicker({ timeZone: "' . $userTz . '", @@ -99,21 +101,20 @@ public static function calendar($value, $name, $id, $format = '', $attribs = nul }); }); })(jQuery);' - ); + ); - if (!$inline) - { - // Hide button using inline styles for readonly/disabled fields - return '
    ' - . '' - . '' - . '' . strtolower($format) . '' - . '
    '; - } + if (!$inline) { + // Hide button using inline styles for readonly/disabled fields + return '
    ' + . '' + . '' + . '' . strtolower($format) . '' + . '
    '; + } - // Hide button using inline styles for readonly/disabled fields - return '
    ' - . '' - . '
    '; - } + // Hide button using inline styles for readonly/disabled fields + return '
    ' + . '' + . '
    '; + } } diff --git a/libraries/redshop/html/redshopgrid.php b/libraries/redshop/html/redshopgrid.php index e3f6e715c1f..5a53d0f2dba 100644 --- a/libraries/redshop/html/redshopgrid.php +++ b/libraries/redshop/html/redshopgrid.php @@ -18,237 +18,262 @@ */ class JHtmlRedshopGrid extends JHtmlJGrid { - /** - * Method to check all checkboxes in a grid - * - * @param string $name The name of the form element - * @param string $tip The text shown as tooltip title instead of $tip - * @param string $action The action to perform on clicking the checkbox - * - * @return string - * - * @since 3.1.2 - */ - public static function checkall($name = 'checkall-toggle', $tip = 'JGLOBAL_CHECK_ALL', $action = 'Joomla.checkAll(this)') - { - if (version_compare(JVERSION, '3.0', '>=')) - { - JHtml::_('bootstrap.tooltip'); - - return ''; - } - else - { - return ''; - } - } - - /** - * Method for render text with slide if length is longer than count. - * - * @param string $data String data - * @param int $count Count of maximum length - * - * @return string - * - * @since 2.0.4 - */ - public static function slideText($data = '', $count = 50) - { - if (empty($data)) - { - return ''; - } - - if (strlen($data) <= $count) - { - return $data; - } - - JText::script('COM_REDSHOP_GRID_SLIDERTEXT_MORE'); - JText::script('COM_REDSHOP_GRID_SLIDERTEXT_LESS'); - - $teaser = JHtml::_('string.truncate', $data, $count, true, false); - - return "" . $teaser . " + /** + * Method to check all checkboxes in a grid + * + * @param string $name The name of the form element + * @param string $tip The text shown as tooltip title instead of $tip + * @param string $action The action to perform on clicking the checkbox + * + * @return string + * + * @since 3.1.2 + */ + public static function checkall( + $name = 'checkall-toggle', + $tip = 'JGLOBAL_CHECK_ALL', + $action = 'Joomla.checkAll(this)' + ) { + if (version_compare(JVERSION, '3.0', '>=')) { + JHtml::_('bootstrap.tooltip'); + + return ''; + } else { + return ''; + } + } + + /** + * Method for render text with slide if length is longer than count. + * + * @param string $data String data + * @param int $count Count of maximum length + * + * @return string + * + * @since 2.0.4 + */ + public static function slideText($data = '', $count = 50) + { + if (empty($data)) { + return ''; + } + + if (strlen($data) <= $count) { + return $data; + } + + JText::script('COM_REDSHOP_GRID_SLIDERTEXT_MORE'); + JText::script('COM_REDSHOP_GRID_SLIDERTEXT_LESS'); + + $teaser = JHtml::_('string.truncate', $data, $count, true, false); + + return "" . $teaser . " " . $data . " " . JText::_('COM_REDSHOP_GRID_SLIDERTEXT_MORE') . ""; - } - - /** - * Method for render HTML of inline edit field. - * - * @param string $name DOM name of field - * @param string $value Value of field - * @param string $display Value of field - * @param int $id DOM ID of field - * @param string $type Field type (text) - * - * @return string - * - * @since 2.0.6 - */ - public static function inline($name = '', $value = '', $display = '', $id = 0, $type = 'text') - { - if (!in_array($type, array('text', 'number', 'redshop.text'))) - { - return $value; - } - - JHtml::script('com_redshop/redshop.inline.min.js', false, true, false, false); - JText::script('COM_REDSHOP_SUCCESS'); - JText::script('COM_REDSHOP_DATA_UPDATE_SUCCESS'); - JText::script('COM_REDSHOP_FAIL'); - JText::script('COM_REDSHOP_DATA_UPDATE_FAIL'); - - return RedshopLayoutHelper::render( - 'inline.text', - array( - 'type' => $type, - 'name' => $name, - 'id' => $id, - 'value' => $value, - 'display' => $display - ), - null, - array('option' => 'com_redshop') - ); - } - - /** - * Returns a checked-out icon - * - * @param integer $i The row index. - * @param string $editorName The name of the editor. - * @param string $time The time that the object was checked out. - * @param string|array $prefix An optional task prefix or an array of options - * @param boolean $enabled True to enable the action. - * @param string $checkbox An optional prefix for checkboxes. - * @param string $formId An optional form id - * - * @return string The required HTML. - */ - public static function checkedOut($i, $editorName, $time, $prefix = '', $enabled = false, $checkbox = 'cb', $formId = 'adminForm') - { - if (is_array($prefix)) - { - $options = $prefix; - $enabled = array_key_exists('enabled', $options) ? $options['enabled'] : $enabled; - $checkbox = array_key_exists('checkbox', $options) ? $options['checkbox'] : $checkbox; - $prefix = array_key_exists('prefix', $options) ? $options['prefix'] : ''; - } - - $text = addslashes(htmlspecialchars($editorName, ENT_COMPAT, 'UTF-8')); - $date = addslashes(htmlspecialchars(JHtml::_('date', $time, JText::_('DATE_FORMAT_LC')), ENT_COMPAT, 'UTF-8')); - $time = addslashes(htmlspecialchars(JHtml::_('date', $time, 'H:i'), ENT_COMPAT, 'UTF-8')); - $active_title = JText::_('JLIB_HTML_CHECKIN') . '::' . $text . '
    ' . $date . '
    ' . $time; - $inactive_title = JText::_('JLIB_HTML_CHECKED_OUT') . '::' . $text . '
    ' . $date . '
    ' . $time; - - return self::action( - $i, 'checkin', $prefix, JText::_('JLIB_HTML_CHECKED_OUT'), $active_title, $inactive_title, true, 'lock', - 'lock', $enabled, false, $checkbox, $formId - ); - } - - /** - * Returns an action on a grid - * - * @param integer $i The row index - * @param string $task The task to fire - * @param string|array $prefix An optional task prefix or an array of options - * @param string $text An optional text to display - * @param string $active_title An optional active tooltip to display if $enable is true - * @param string $inactive_title An optional inactive tooltip to display if $enable is true - * @param boolean $tip An optional setting for tooltip - * @param string $active_class An optional active HTML class - * @param string $inactive_class An optional inactive HTML class - * @param boolean $enabled An optional setting for access control on the action. - * @param boolean $translate An optional setting for translation. - * @param string $checkbox An optional prefix for checkboxes. - * @param string $formId An optional form id - * @param string $buttonClass An optional button class - * - * @return string The Html code - */ - public static function action($i, $task, $prefix = '', $text = '', $active_title = '', $inactive_title = '', - $tip = false, $active_class = '', $inactive_class = '', - $enabled = true, $translate = true, $checkbox = 'cb', $formId = 'adminForm', $buttonClass = '') - { - if (is_array($prefix)) - { - $options = $prefix; - $active_title = array_key_exists('active_title', $options) ? $options['active_title'] : $active_title; - $inactive_title = array_key_exists('inactive_title', $options) ? $options['inactive_title'] : $inactive_title; - $tip = array_key_exists('tip', $options) ? $options['tip'] : $tip; - $active_class = array_key_exists('active_class', $options) ? $options['active_class'] : $active_class; - $inactive_class = array_key_exists('inactive_class', $options) ? $options['inactive_class'] : $inactive_class; - $enabled = array_key_exists('enabled', $options) ? $options['enabled'] : $enabled; - $translate = array_key_exists('translate', $options) ? $options['translate'] : $translate; - $checkbox = array_key_exists('checkbox', $options) ? $options['checkbox'] : $checkbox; - $formId = array_key_exists('formId', $options) ? $options['formId'] : $formId; - $buttonClass = array_key_exists('buttonClass', $options) ? $options['buttonClass'] : $buttonClass; - $prefix = array_key_exists('prefix', $options) ? $options['prefix'] : ''; - } - - if ($tip) - { - JHtml::_('redshopjquery.popover'); - } - - $iconClass = $active_class; - - if ($active_class === 'publish') - { - $iconClass = 'check-circle'; - } - elseif ($active_class === 'unpublish') - { - $iconClass = 'minus-circle'; - } - - if ($enabled) - { - $buttonClass = 'btn-' . str_replace(' ', '-', strtolower($task)); - - // Prepare the class. - if ($active_class === 'publish') - { - $buttonClass .= ' btn-success btn-state-item'; - } - - elseif ($active_class === 'unpublish') - { - $buttonClass .= ' btn-danger btn-state-item'; - } - - $buttonClass .= $tip ? ' hasPopover' : ''; - - $html[] = ''; - $html[] = ''; - $html[] = ''; - $html[] = ''; - } - else - { - $html[] = ''; - - if ($active_class == "protected") - { - $html[] = ''; - } - else - { - $html[] = ''; - } - - $html[] = ''; - } - - return implode($html); - } + } + + /** + * Method for render HTML of inline edit field. + * + * @param string $name DOM name of field + * @param string $value Value of field + * @param string $display Value of field + * @param int $id DOM ID of field + * @param string $type Field type (text) + * + * @return string + * + * @since 2.0.6 + */ + public static function inline($name = '', $value = '', $display = '', $id = 0, $type = 'text') + { + if (!in_array($type, array('text', 'number', 'redshop.text'))) { + return $value; + } + + JHtml::script('com_redshop/redshop.inline.min.js', false, true, false, false); + JText::script('COM_REDSHOP_SUCCESS'); + JText::script('COM_REDSHOP_DATA_UPDATE_SUCCESS'); + JText::script('COM_REDSHOP_FAIL'); + JText::script('COM_REDSHOP_DATA_UPDATE_FAIL'); + + return RedshopLayoutHelper::render( + 'inline.text', + array( + 'type' => $type, + 'name' => $name, + 'id' => $id, + 'value' => $value, + 'display' => $display + ), + null, + array('option' => 'com_redshop') + ); + } + + /** + * Returns a checked-out icon + * + * @param integer $i The row index. + * @param string $editorName The name of the editor. + * @param string $time The time that the object was checked out. + * @param string|array $prefix An optional task prefix or an array of options + * @param boolean $enabled True to enable the action. + * @param string $checkbox An optional prefix for checkboxes. + * @param string $formId An optional form id + * + * @return string The required HTML. + */ + public static function checkedOut( + $i, + $editorName, + $time, + $prefix = '', + $enabled = false, + $checkbox = 'cb', + $formId = 'adminForm' + ) { + if (is_array($prefix)) { + $options = $prefix; + $enabled = array_key_exists('enabled', $options) ? $options['enabled'] : $enabled; + $checkbox = array_key_exists('checkbox', $options) ? $options['checkbox'] : $checkbox; + $prefix = array_key_exists('prefix', $options) ? $options['prefix'] : ''; + } + + $text = addslashes(htmlspecialchars($editorName, ENT_COMPAT, 'UTF-8')); + $date = addslashes( + htmlspecialchars(JHtml::_('date', $time, JText::_('DATE_FORMAT_LC')), ENT_COMPAT, 'UTF-8') + ); + $time = addslashes(htmlspecialchars(JHtml::_('date', $time, 'H:i'), ENT_COMPAT, 'UTF-8')); + $active_title = JText::_('JLIB_HTML_CHECKIN') . '::' . $text . '
    ' . $date . '
    ' . $time; + $inactive_title = JText::_('JLIB_HTML_CHECKED_OUT') . '::' . $text . '
    ' . $date . '
    ' . $time; + + return self::action( + $i, + 'checkin', + $prefix, + JText::_('JLIB_HTML_CHECKED_OUT'), + $active_title, + $inactive_title, + true, + 'lock', + 'lock', + $enabled, + false, + $checkbox, + $formId + ); + } + + /** + * Returns an action on a grid + * + * @param integer $i The row index + * @param string $task The task to fire + * @param string|array $prefix An optional task prefix or an array of options + * @param string $text An optional text to display + * @param string $active_title An optional active tooltip to display if $enable is true + * @param string $inactive_title An optional inactive tooltip to display if $enable is true + * @param boolean $tip An optional setting for tooltip + * @param string $active_class An optional active HTML class + * @param string $inactive_class An optional inactive HTML class + * @param boolean $enabled An optional setting for access control on the action. + * @param boolean $translate An optional setting for translation. + * @param string $checkbox An optional prefix for checkboxes. + * @param string $formId An optional form id + * @param string $buttonClass An optional button class + * + * @return string The Html code + */ + public static function action( + $i, + $task, + $prefix = '', + $text = '', + $active_title = '', + $inactive_title = '', + $tip = false, + $active_class = '', + $inactive_class = '', + $enabled = true, + $translate = true, + $checkbox = 'cb', + $formId = 'adminForm', + $buttonClass = '' + ) { + if (is_array($prefix)) { + $options = $prefix; + $active_title = array_key_exists('active_title', $options) ? $options['active_title'] : $active_title; + $inactive_title = array_key_exists( + 'inactive_title', + $options + ) ? $options['inactive_title'] : $inactive_title; + $tip = array_key_exists('tip', $options) ? $options['tip'] : $tip; + $active_class = array_key_exists('active_class', $options) ? $options['active_class'] : $active_class; + $inactive_class = array_key_exists( + 'inactive_class', + $options + ) ? $options['inactive_class'] : $inactive_class; + $enabled = array_key_exists('enabled', $options) ? $options['enabled'] : $enabled; + $translate = array_key_exists('translate', $options) ? $options['translate'] : $translate; + $checkbox = array_key_exists('checkbox', $options) ? $options['checkbox'] : $checkbox; + $formId = array_key_exists('formId', $options) ? $options['formId'] : $formId; + $buttonClass = array_key_exists('buttonClass', $options) ? $options['buttonClass'] : $buttonClass; + $prefix = array_key_exists('prefix', $options) ? $options['prefix'] : ''; + } + + if ($tip) { + JHtml::_('redshopjquery.popover'); + } + + $iconClass = $active_class; + + if ($active_class === 'publish') { + $iconClass = 'check-circle'; + } elseif ($active_class === 'unpublish') { + $iconClass = 'minus-circle'; + } + + if ($enabled) { + $buttonClass = 'btn-' . str_replace(' ', '-', strtolower($task)); + + // Prepare the class. + if ($active_class === 'publish') { + $buttonClass .= ' btn-success btn-state-item'; + } elseif ($active_class === 'unpublish') { + $buttonClass .= ' btn-danger btn-state-item'; + } + + $buttonClass .= $tip ? ' hasPopover' : ''; + + $html[] = ''; + $html[] = ''; + $html[] = ''; + $html[] = ''; + } else { + $html[] = ''; + + if ($active_class == "protected") { + $html[] = ''; + } else { + $html[] = ''; + } + + $html[] = ''; + } + + return implode($html); + } } diff --git a/libraries/redshop/html/redshopjquery.php b/libraries/redshop/html/redshopjquery.php index 3e141554f0f..f073e13956c 100644 --- a/libraries/redshop/html/redshopjquery.php +++ b/libraries/redshop/html/redshopjquery.php @@ -18,173 +18,141 @@ */ abstract class JHtmlRedshopjquery { - /** - * Array containing information for loaded files - * - * @var array - */ - protected static $loaded = array(); - - /** - * Load the jQuery framework - * - * If debugging mode is on an uncompressed version of jQuery is included for easier debugging. - * - * @param boolean $noConflict True to load jQuery in noConflict mode [optional] - * @param mixed $debug Is debugging mode on? [optional] - * @param boolean $migrate True to enable the jQuery Migrate plugin - * - * @return void - */ - public static function framework($noConflict = true, $debug = null, $migrate = true) - { - // Only load once - if (!empty(static::$loaded[__METHOD__])) - { - return; - } - - if (version_compare(JVERSION, '3.0', '<')) - { - // If no debugging value is set, use the configuration setting - if ($debug === null) - { - $config = JFactory::getConfig(); - $debug = (boolean) $config->get('debug'); - } - - JHtml::script('com_redshop/jquery.min.js', false, true, false, false, $debug); - - // Check if we are loading in noConflict - if ($noConflict) - { - JHtml::_('script', 'com_redshop/jquery-noconflict.js', false, true, false, false, false); - } - - // Check if we are loading Migrate - if ($migrate) - { - JHtml::_('script', 'com_redshop/jquery-migrate.min.js', false, true, false, false, $debug); - } - } - else - { - JHtml::_('jquery.framework', $noConflict, $debug, $migrate); - } - - static::$loaded[__METHOD__] = true; - - return; - } - - /** - * Load the jQuery UI library - * - * @return void - * - * @since 1.5 - */ - public static function ui() - { - // Only load once - if (!empty(static::$loaded[__METHOD__])) - { - return; - } - - JHtml::stylesheet('com_redshop/jquery-ui/jquery-ui.min.css', array(), true); - self::framework(); - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/jquery-ui.min.js', false, true, false, false); - - if (version_compare(JVERSION, '3.0', '>=')) - { - // Check includes and remove core joomla jquery.ui script - JHtml::_('jquery.ui', array('core')); - $document = JFactory::getDocument(); - $headData = $document->getHeadData(); - - if (isset($headData['scripts'][JUri::root(true) . '/media/jui/js/jquery.ui.core.min.js'])) - { - unset($headData['scripts'][JUri::root(true) . '/media/jui/js/jquery.ui.core.min.js']); - } - - if (JFactory::getConfig()->get('debug')) - { - if (isset($headData['scripts'][JUri::root(true) . '/media/jui/js/jquery.ui.core.js'])) - { - unset($headData['scripts'][JUri::root(true) . '/media/jui/js/jquery.ui.core.js']); - } - } - - $document->setHeadData($headData); - } - - static::$loaded[__METHOD__] = true; - - return; - } - - /** - * Load the flexslider library. - * - * @param string $selector CSS Selector to initalise selects - * @param array $options Optional array with options - * - * @return void - */ - public static function flexslider($selector = '.flexslider', $options = null) - { - // Only load once - if (isset(static::$loaded[__METHOD__][$selector])) - { - return; - } - - self::framework(); - - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/flexslider.min.js', false, true); - JHtml::stylesheet('com_redshop/flexslider/flexslider.min.css', array(), true); - - $options = static::options2Jregistry($options); - - JFactory::getDocument()->addScriptDeclaration(" + /** + * Array containing information for loaded files + * + * @var array + */ + protected static $loaded = array(); + + /** + * Load the flexslider library. + * + * @param string $selector CSS Selector to initalise selects + * @param array $options Optional array with options + * + * @return void + */ + public static function flexslider($selector = '.flexslider', $options = null) + { + // Only load once + if (isset(static::$loaded[__METHOD__][$selector])) { + return; + } + + self::framework(); + + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/flexslider.min.js', false, true); + JHtml::stylesheet('com_redshop/flexslider/flexslider.min.css', array(), true); + + $options = static::options2Jregistry($options); + + JFactory::getDocument()->addScriptDeclaration( + " (function($){ $(document).ready(function () { $('" . $selector . "').flexslider(" . $options->toString() . "); }); })(jQuery); - "); - static::$loaded[__METHOD__][$selector] = true; - - return; - } - - /** - * Load bootstrap radio button style - * - * @param string $selector CSS Selector to initalise selects - * - * @return void - */ - public static function radioButton($selector = '.btn-group') - { - // Only load once - if (isset(static::$loaded[__METHOD__])) - { - return; - } - - static::$loaded[__METHOD__] = true; - - // Loads only for joomla 3 - if (version_compare(JVERSION, '3.0', '<')) - { - return; - } - - self::framework(); - - JFactory::getDocument()->addScriptDeclaration(" + " + ); + static::$loaded[__METHOD__][$selector] = true; + + return; + } + + /** + * Load the jQuery framework + * + * If debugging mode is on an uncompressed version of jQuery is included for easier debugging. + * + * @param boolean $noConflict True to load jQuery in noConflict mode [optional] + * @param mixed $debug Is debugging mode on? [optional] + * @param boolean $migrate True to enable the jQuery Migrate plugin + * + * @return void + */ + public static function framework($noConflict = true, $debug = null, $migrate = true) + { + // Only load once + if (!empty(static::$loaded[__METHOD__])) { + return; + } + + if (version_compare(JVERSION, '3.0', '<')) { + // If no debugging value is set, use the configuration setting + if ($debug === null) { + $config = JFactory::getConfig(); + $debug = (boolean)$config->get('debug'); + } + + JHtml::script('com_redshop/jquery.min.js', false, true, false, false, $debug); + + // Check if we are loading in noConflict + if ($noConflict) { + JHtml::_('script', 'com_redshop/jquery-noconflict.js', false, true, false, false, false); + } + + // Check if we are loading Migrate + if ($migrate) { + JHtml::_('script', 'com_redshop/jquery-migrate.min.js', false, true, false, false, $debug); + } + } else { + JHtml::_('jquery.framework', $noConflict, $debug, $migrate); + } + + static::$loaded[__METHOD__] = true; + + return; + } + + /** + * Function to receive & pre-process javascript options + * + * @param mixed $options Associative array/JRegistry object with options + * + * @return JRegistry Options converted to JRegistry object + */ + private static function options2Jregistry($options) + { + // Support options array + if (is_array($options)) { + $options = new JRegistry($options); + } + + if (!($options instanceof JRegistry)) { + $options = new JRegistry; + } + + return $options; + } + + /** + * Load bootstrap radio button style + * + * @param string $selector CSS Selector to initalise selects + * + * @return void + */ + public static function radioButton($selector = '.btn-group') + { + // Only load once + if (isset(static::$loaded[__METHOD__])) { + return; + } + + static::$loaded[__METHOD__] = true; + + // Loads only for joomla 3 + if (version_compare(JVERSION, '3.0', '<')) { + return; + } + + self::framework(); + + JFactory::getDocument()->addScriptDeclaration( + " (function($) { $(document).ready(function() @@ -220,52 +188,51 @@ public static function radioButton($selector = '.btn-group') }); }); })(jQuery); - "); - - return; - } - - /** - * Load the select2 library - * https://github.com/ivaynberg/select2 - * - * @param string $selector CSS Selector to initalise selects - * @param array $options Optional array with options - * @param bool $getInitTemplate Return init template or (false) set script in header - * - * @return void - */ - public static function select2($selector = '.select2', $options = null, $getInitTemplate = false) - { - // Only load once - if (isset(static::$loaded[__METHOD__][$selector])) - { - return; - } - - self::framework(); - - /** @scrutinizer ignore-deprecated */JHtml::script('com_redshop/select2.min.js', false, true); - JHtml::stylesheet('com_redshop/select2/select2.css', array(), true); - - if (version_compare(JVERSION, '3.0', '>=')) - { - JHtml::stylesheet('com_redshop/select2/select2-bootstrap.css', array(), true); - } - - $prefix = ''; - - if (isset($options['multiple']) && $options['multiple'] == 'true') - { - self::ui(); - $prefix = ".select2('container').find('ul.select2-choices').sortable({ + " + ); + + return; + } + + /** + * Load the select2 library + * https://github.com/ivaynberg/select2 + * + * @param string $selector CSS Selector to initalise selects + * @param array $options Optional array with options + * @param bool $getInitTemplate Return init template or (false) set script in header + * + * @return void + */ + public static function select2($selector = '.select2', $options = null, $getInitTemplate = false) + { + // Only load once + if (isset(static::$loaded[__METHOD__][$selector])) { + return; + } + + self::framework(); + + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/select2.min.js', false, true); + JHtml::stylesheet('com_redshop/select2/select2.css', array(), true); + + if (version_compare(JVERSION, '3.0', '>=')) { + JHtml::stylesheet('com_redshop/select2/select2-bootstrap.css', array(), true); + } + + $prefix = ''; + + if (isset($options['multiple']) && $options['multiple'] == 'true') { + self::ui(); + $prefix = ".select2('container').find('ul.select2-choices').sortable({ containment: 'parent', start: function() { $('" . $selector . "').select2('onSortStart'); }, update: function() { $('" . $selector . "').select2('onSortEnd'); } })"; - } + } - $initTemplate = " + $initTemplate = " (function($){ $(document).ready(function () { $('" . $selector . "').select2( @@ -281,166 +248,206 @@ public static function select2($selector = '.select2', $options = null, $getInit })(jQuery); "; - if ($getInitTemplate) - { - echo $initTemplate; - } - else - { - JFactory::getDocument()->addScriptDeclaration($initTemplate); - } - - static::$loaded[__METHOD__][$selector] = true; - - return; - } - - /** - * Function to receive & pre-process select2 events options - * - * @param mixed $options Associative array/JRegistry object with options - * - * @return string - */ - private static function formatSelect2Events($options) - { - $result = ''; - - if (isset($options['events']) && is_array($options['events'])) - { - foreach ($options['events'] as $key => $event) - { - $result .= ".on('" . $key . "', " . $event . ")"; - } - } - - return $result; - } - - /** - * Function to receive & pre-process select2 options - * - * @param mixed $options Associative array/JRegistry object with options - * - * @return string The options ready for the select2() function - */ - private static function formatSelect2Options($options) - { - $options = static::options2Jregistry($options); - - $options->def('width', 'resolve'); - $options->def('formatNoMatches', 'function () { return "' . JText::_("LIB_REDSHOP_SELECT2_NO_MATHES") . '"; }'); - $options->def('formatInputTooShort', 'function (input, min) { var n = min - input.length; return "' - . JText::_("LIB_REDSHOP_SELECT2_INPUT_TO_SHORT") . '" + (n == 1? "" : "' . JText::_("LIB_REDSHOP_SELECT2_PREFIX") . '"); }'); - $options->def('formatInputTooLong', 'function (input, max) { var n = input.length - max; return "' - . JText::_("LIB_REDSHOP_SELECT2_TO_LONG") . '" + (n == 1? "" : "' . JText::_("LIB_REDSHOP_SELECT2_PREFIX") . '"); }'); - $options->def('formatSelectionTooBig', 'function (limit) { return "' - . JText::_("LIB_REDSHOP_SELECT2_TO_BIG") . '" + (limit == 1 ? "" : "' . JText::_("LIB_REDSHOP_SELECT2_PREFIX") . '"); }'); - $options->def('formatLoadMore', 'function (pageNumber) { return "' . JText::_("LIB_REDSHOP_SELECT2_LOAD_MORE") . '"; }'); - $options->def('formatSearching', 'function () { return "' . JText::_("LIB_REDSHOP_SELECT2_SEARCHING") . '"; }'); - - $return = array(); - $functions = array('ajax', 'initSelection', 'formatNoMatches', 'formatInputTooShort', 'formatInputTooLong', - 'formatSelectionTooBig', 'formatLoadMore', 'formatSearching', 'escapeMarkup', 'multiple', 'allowClear'); - $exclude = array('events'); - - foreach ($options->toArray() as $key => $option) - { - if (in_array($key, $exclude)) - { - continue; - } - - if (!in_array($key, $functions)) - { - $option = '"' . $option . '"'; - } - - $return[] = $key . ':' . $option; - } - - return '{' . implode(', ', $return) . '}'; - } - - /** - * Function to receive & pre-process javascript options - * - * @param mixed $options Associative array/JRegistry object with options - * - * @return JRegistry Options converted to JRegistry object - */ - private static function options2Jregistry($options) - { - // Support options array - if (is_array($options)) - { - $options = new JRegistry($options); - } - - if (!($options instanceof JRegistry)) - { - $options = new JRegistry; - } - - return $options; - } - - /** - * Add javascript support for Bootstrap popovers - * - * Use element's Title as popover content - * - * @param string $selector Selector for the popover - * @param array $params An array of options for the popover. - * Options for the popover can be: - * animation boolean apply a css fade transition to the popover - * html boolean Insert HTML into the popover. If false, jQuery's text method will be used to insert - * content into the dom. - * placement string|function how to position the popover - top | bottom | left | right - * selector string If a selector is provided, popover objects will be delegated to the specified targets. - * trigger string how popover is triggered - hover | focus | manual - * title string|function default title value if `title` tag isn't present - * content string|function default content value if `data-content` attribute isn't present - * delay number|object delay showing and hiding the popover (ms) - does not apply to manual trigger type - * If a number is supplied, delay is applied to both hide/show - * Object structure is: delay: { show: 500, hide: 100 } - * container string|boolean Appends the popover to a specific element: { container: 'body' } - * - * @return void - */ - public static function popover($selector = '.hasPopover', $params = array()) - { - // Only load once - if (isset(static::$loaded[__METHOD__][$selector])) - { - return; - } - - // Include Bootstrap framework - static::framework(); - - $opt['animation'] = isset($params['animation']) ? $params['animation'] : null; - $opt['html'] = isset($params['html']) ? $params['html'] : true; - $opt['placement'] = isset($params['placement']) ? $params['placement'] : null; - $opt['selector'] = isset($params['selector']) ? $params['selector'] : null; - $opt['title'] = isset($params['title']) ? $params['title'] : null; - $opt['trigger'] = isset($params['trigger']) ? $params['trigger'] : 'hover focus'; - $opt['content'] = isset($params['content']) ? $params['content'] : null; - $opt['delay'] = isset($params['delay']) ? $params['delay'] : null; - $opt['container'] = isset($params['container']) ? $params['container'] : 'body'; - - $options = json_encode($opt); - - // Attach the popover to the document - JFactory::getDocument()->addScriptDeclaration( - "jQuery(document).ready(function() + if ($getInitTemplate) { + echo $initTemplate; + } else { + JFactory::getDocument()->addScriptDeclaration($initTemplate); + } + + static::$loaded[__METHOD__][$selector] = true; + + return; + } + + /** + * Load the jQuery UI library + * + * @return void + * + * @since 1.5 + */ + public static function ui() + { + // Only load once + if (!empty(static::$loaded[__METHOD__])) { + return; + } + + JHtml::stylesheet('com_redshop/jquery-ui/jquery-ui.min.css', array(), true); + self::framework(); + /** @scrutinizer ignore-deprecated */ + JHtml::script('com_redshop/jquery-ui.min.js', false, true, false, false); + + if (version_compare(JVERSION, '3.0', '>=')) { + // Check includes and remove core joomla jquery.ui script + JHtml::_('jquery.ui', array('core')); + $document = JFactory::getDocument(); + $headData = $document->getHeadData(); + + if (isset($headData['scripts'][JUri::root(true) . '/media/jui/js/jquery.ui.core.min.js'])) { + unset($headData['scripts'][JUri::root(true) . '/media/jui/js/jquery.ui.core.min.js']); + } + + if (JFactory::getConfig()->get('debug')) { + if (isset($headData['scripts'][JUri::root(true) . '/media/jui/js/jquery.ui.core.js'])) { + unset($headData['scripts'][JUri::root(true) . '/media/jui/js/jquery.ui.core.js']); + } + } + + $document->setHeadData($headData); + } + + static::$loaded[__METHOD__] = true; + + return; + } + + /** + * Function to receive & pre-process select2 options + * + * @param mixed $options Associative array/JRegistry object with options + * + * @return string The options ready for the select2() function + */ + private static function formatSelect2Options($options) + { + $options = static::options2Jregistry($options); + + $options->def('width', 'resolve'); + $options->def('formatNoMatches', 'function () { return "' . JText::_("LIB_REDSHOP_SELECT2_NO_MATHES") . '"; }'); + $options->def( + 'formatInputTooShort', + 'function (input, min) { var n = min - input.length; return "' + . JText::_("LIB_REDSHOP_SELECT2_INPUT_TO_SHORT") . '" + (n == 1? "" : "' . JText::_( + "LIB_REDSHOP_SELECT2_PREFIX" + ) . '"); }' + ); + $options->def( + 'formatInputTooLong', + 'function (input, max) { var n = input.length - max; return "' + . JText::_("LIB_REDSHOP_SELECT2_TO_LONG") . '" + (n == 1? "" : "' . JText::_( + "LIB_REDSHOP_SELECT2_PREFIX" + ) . '"); }' + ); + $options->def( + 'formatSelectionTooBig', + 'function (limit) { return "' + . JText::_("LIB_REDSHOP_SELECT2_TO_BIG") . '" + (limit == 1 ? "" : "' . JText::_( + "LIB_REDSHOP_SELECT2_PREFIX" + ) . '"); }' + ); + $options->def( + 'formatLoadMore', + 'function (pageNumber) { return "' . JText::_("LIB_REDSHOP_SELECT2_LOAD_MORE") . '"; }' + ); + $options->def('formatSearching', 'function () { return "' . JText::_("LIB_REDSHOP_SELECT2_SEARCHING") . '"; }'); + + $return = array(); + $functions = array( + 'ajax', + 'initSelection', + 'formatNoMatches', + 'formatInputTooShort', + 'formatInputTooLong', + 'formatSelectionTooBig', + 'formatLoadMore', + 'formatSearching', + 'escapeMarkup', + 'multiple', + 'allowClear' + ); + $exclude = array('events'); + + foreach ($options->toArray() as $key => $option) { + if (in_array($key, $exclude)) { + continue; + } + + if (!in_array($key, $functions)) { + $option = '"' . $option . '"'; + } + + $return[] = $key . ':' . $option; + } + + return '{' . implode(', ', $return) . '}'; + } + + /** + * Function to receive & pre-process select2 events options + * + * @param mixed $options Associative array/JRegistry object with options + * + * @return string + */ + private static function formatSelect2Events($options) + { + $result = ''; + + if (isset($options['events']) && is_array($options['events'])) { + foreach ($options['events'] as $key => $event) { + $result .= ".on('" . $key . "', " . $event . ")"; + } + } + + return $result; + } + + /** + * Add javascript support for Bootstrap popovers + * + * Use element's Title as popover content + * + * @param string $selector Selector for the popover + * @param array $params An array of options for the popover. + * Options for the popover can be: + * animation boolean apply a css fade transition to the popover + * html boolean Insert HTML into the popover. If false, jQuery's text method will be used to insert + * content into the dom. + * placement string|function how to position the popover - top | bottom | left | right + * selector string If a selector is provided, popover objects will be delegated to the specified targets. + * trigger string how popover is triggered - hover | focus | manual + * title string|function default title value if `title` tag isn't present + * content string|function default content value if `data-content` attribute isn't present + * delay number|object delay showing and hiding the popover (ms) - does not apply to manual trigger type + * If a number is supplied, delay is applied to both hide/show + * Object structure is: delay: { show: 500, hide: 100 } + * container string|boolean Appends the popover to a specific element: { container: 'body' } + * + * @return void + */ + public static function popover($selector = '.hasPopover', $params = array()) + { + // Only load once + if (isset(static::$loaded[__METHOD__][$selector])) { + return; + } + + // Include Bootstrap framework + static::framework(); + + $opt['animation'] = isset($params['animation']) ? $params['animation'] : null; + $opt['html'] = isset($params['html']) ? $params['html'] : true; + $opt['placement'] = isset($params['placement']) ? $params['placement'] : null; + $opt['selector'] = isset($params['selector']) ? $params['selector'] : null; + $opt['title'] = isset($params['title']) ? $params['title'] : null; + $opt['trigger'] = isset($params['trigger']) ? $params['trigger'] : 'hover focus'; + $opt['content'] = isset($params['content']) ? $params['content'] : null; + $opt['delay'] = isset($params['delay']) ? $params['delay'] : null; + $opt['container'] = isset($params['container']) ? $params['container'] : 'body'; + + $options = json_encode($opt); + + // Attach the popover to the document + JFactory::getDocument()->addScriptDeclaration( + "jQuery(document).ready(function() { jQuery('" . $selector . "').popover(" . $options . "); });" - ); + ); - static::$loaded[__METHOD__][$selector] = true; + static::$loaded[__METHOD__][$selector] = true; - return; - } + return; + } } diff --git a/libraries/redshop/html/redshopmedia.php b/libraries/redshop/html/redshopmedia.php index a97c77c13cc..943fdae6b6a 100644 --- a/libraries/redshop/html/redshopmedia.php +++ b/libraries/redshop/html/redshopmedia.php @@ -18,37 +18,45 @@ */ abstract class JHtmlRedshopMedia { - /** - * Show modal media - * - * If debugging mode is on an uncompressed version of jQuery is included for easier debugging. - * - * @param string $mediaSection Media Section. Ex: product - * @param string $sectionId Id of section - * @param string $sectionName Name of section - * @param int $count Number of media uploaded - * @param string $class Class of modal, default is 'modal' - * @param string $handler Default is iframe - * @param int $width Width of modal - * @param height $height Height of modal - * - * @return void - */ - public static function showButton($mediaSection, $sectionId, $sectionName, $count, $class = 'modal', $handler = 'iframe', $width = 1050, $height = 450) - { - JHTMLBehavior::modal(); + /** + * Show modal media + * + * If debugging mode is on an uncompressed version of jQuery is included for easier debugging. + * + * @param string $mediaSection Media Section. Ex: product + * @param string $sectionId Id of section + * @param string $sectionName Name of section + * @param int $count Number of media uploaded + * @param string $class Class of modal, default is 'modal' + * @param string $handler Default is iframe + * @param int $width Width of modal + * @param height $height Height of modal + * + * @return void + */ + public static function showButton( + $mediaSection, + $sectionId, + $sectionName, + $count, + $class = 'modal', + $handler = 'iframe', + $width = 1050, + $height = 450 + ) { + JHTMLBehavior::modal(); - $displayData = [ - 'mediaSection' => $mediaSection, - 'sectionId' => $sectionId, - 'sectionName' => $sectionName, - 'count' => $count, - 'class' => $class, - 'handler' => $handler, - 'width' => $width, - 'height' => $height, - ]; + $displayData = [ + 'mediaSection' => $mediaSection, + 'sectionId' => $sectionId, + 'sectionName' => $sectionName, + 'count' => $count, + 'class' => $class, + 'handler' => $handler, + 'width' => $width, + 'height' => $height, + ]; - return RedshopLayoutHelper::render('html.media.button', $displayData); - } + return RedshopLayoutHelper::render('html.media.button', $displayData); + } } diff --git a/libraries/redshop/html/redshopselect.php b/libraries/redshop/html/redshopselect.php index d8476cd5ced..d8486cf6c27 100644 --- a/libraries/redshop/html/redshopselect.php +++ b/libraries/redshop/html/redshopselect.php @@ -22,198 +22,235 @@ */ abstract class JHtmlRedshopSelect extends JHtmlSelect { - /** - * Default values for options. Organized by option group. - * - * @var array - * @since 1.5 - */ - static protected $optionDefaults = array( - 'option' => array('option.attr' => null, 'option.disable' => 'disable', 'option.id' => null, 'option.key' => 'value', - 'option.key.toHtml' => true, 'option.label' => null, 'option.label.toHtml' => true, 'option.text' => 'text', - 'option.text.toHtml' => true, 'option.class' => 'class', 'option.onclick' => 'onclick')); - - /** - * Generates a yes/no radio list. - * - * @param string $name The value of the HTML name attribute - * @param array $attribs Additional HTML attributes for the tag - * @param mixed $optKey The key that is selected - * @param string $optText The name of the object variable for the option value - * @param string $selected The name of the object variable for the option text - * @param boolean $idtag Value of the field id or null by default - * @param boolean $translate True if options will be translated - * - * @return string HTML for the select list - * - * @since 1.5 - */ - public static function radiolist($data, $name, $attribs = null, $optKey = 'value', $optText = 'text', $selected = null, $idtag = false, $translate = false, $classSuffix = ' btn-group redRadioGroup') - { - JHtml::_('redshopjquery.radiobutton'); - - return self::prepareButtonList( - 'radio', - $data, - $name, - $attribs, - $optKey, - $optText, - $selected, - $idtag, - $translate - ); - } - - /** - * Generates an HTML radio list. - * - * @param array $data An array of objects - * @param string $name The value of the HTML name attribute - * @param string $attribs Additional HTML attributes for the tag. - * @param bool $getInitTemplate Return init template or (false) set script in header - * - * @return string HTML for the select list. - * - * @since 1.5 - */ - public static function search($data, $name, $attribs = null, $getInitTemplate = false) - { - JHtml::$formatOptions['select2.ajaxOptions'] = array( - 'limit' => 10, - 'quietMillis' => 300, - 'typeField' => '', - 'url' => JURI::base() . 'index.php?option=com_redshop&task=search.search&format=json' - ); - - // Set default options - $options = array_merge(JHtml::$formatOptions, static::$optionDefaults['option'], array('format.depth' => 0, 'id' => false)); - - if (is_array($attribs)) - { - if (isset($attribs['select2.ajaxOptions']) && is_array($attribs['select2.ajaxOptions'])) - { - $options['select2.ajaxOptions'] = array_merge($options['select2.ajaxOptions'], $attribs['select2.ajaxOptions']); - unset($attribs['select2.ajaxOptions']); - } - - $options = array_merge($options, $attribs); - } - - $initSelection = null; - $value = array(); - - if (is_array($data) && count($data) > 0) - { - foreach ($data as $key => $val) - { - $object = new stdClass; - $object->id = $val->{$options['option.key']}; - $object->text = $val->{$options['option.text']}; - $initSelection[] = $object; - $value[] = $val->{$options['option.key']}; - } - } - elseif (is_object($data) && isset($data->{$options['option.key']}) && isset($data->{$options['option.text']})) - { - $initSelection = new stdClass; - $initSelection->id = $data->{$options['option.key']}; - $initSelection->text = $data->{$options['option.text']}; - $value[] = $data->{$options['option.key']}; - } - - $options['select2.options'] = array( - 'placeholder' => '', - 'minimumInputLength' => 2, - 'width' => 'resolve', - 'multiple' => 'false', - 'allowClear' => 'true', - 'ajax' => '{ // instead of writing the function to execute the request we use Select2\'s convenient helper + /** + * Default values for options. Organized by option group. + * + * @var array + * @since 1.5 + */ + static protected $optionDefaults = array( + 'option' => array( + 'option.attr' => null, + 'option.disable' => 'disable', + 'option.id' => null, + 'option.key' => 'value', + 'option.key.toHtml' => true, + 'option.label' => null, + 'option.label.toHtml' => true, + 'option.text' => 'text', + 'option.text.toHtml' => true, + 'option.class' => 'class', + 'option.onclick' => 'onclick' + ) + ); + + /** + * Generates a yes/no radio list. + * + * @param string $name The value of the HTML name attribute + * @param array $attribs Additional HTML attributes for the tag + * @param mixed $optKey The key that is selected + * @param string $optText The name of the object variable for the option value + * @param string $selected The name of the object variable for the option text + * @param boolean $idtag Value of the field id or null by default + * @param boolean $translate True if options will be translated + * + * @return string HTML for the select list + * + * @since 1.5 + */ + public static function radiolist( + $data, + $name, + $attribs = null, + $optKey = 'value', + $optText = 'text', + $selected = null, + $idtag = false, + $translate = false, + $classSuffix = ' btn-group redRadioGroup' + ) { + JHtml::_('redshopjquery.radiobutton'); + + return self::prepareButtonList( + 'radio', + $data, + $name, + $attribs, + $optKey, + $optText, + $selected, + $idtag, + $translate + ); + } + + /** + * Generates an HTML output for radio or checkbox list. + * + * @return string HTML for the select list + * + * @since 1.5 + */ + protected static function prepareButtonList() + { + list($type, $data, $name, $attribs, $optKey, $optText, $selected, $idtag, $translate) = func_get_args(); + + reset($data); + + $html = RedshopLayoutHelper::render( + 'html.list', + array( + 'type' => $type, + 'data' => $data, + 'name' => $name, + 'attribs' => $attribs, + 'optKey' => $optKey, + 'optText' => $optText, + 'selected' => $selected, + 'idtag' => $idtag, + 'translate' => $translate + ) + ); + + return $html; + } + + /** + * Generates an HTML radio list. + * + * @param array $data An array of objects + * @param string $name The value of the HTML name attribute + * @param string $attribs Additional HTML attributes for the tag. + * @param bool $getInitTemplate Return init template or (false) set script in header + * + * @return string HTML for the select list. + * + * @since 1.5 + */ + public static function search($data, $name, $attribs = null, $getInitTemplate = false) + { + JHtml::$formatOptions['select2.ajaxOptions'] = array( + 'limit' => 10, + 'quietMillis' => 300, + 'typeField' => '', + 'url' => JURI::base() . 'index.php?option=com_redshop&task=search.search&format=json' + ); + + // Set default options + $options = array_merge( + JHtml::$formatOptions, + static::$optionDefaults['option'], + array('format.depth' => 0, 'id' => false) + ); + + if (is_array($attribs)) { + if (isset($attribs['select2.ajaxOptions']) && is_array($attribs['select2.ajaxOptions'])) { + $options['select2.ajaxOptions'] = array_merge( + $options['select2.ajaxOptions'], + $attribs['select2.ajaxOptions'] + ); + unset($attribs['select2.ajaxOptions']); + } + + $options = array_merge($options, $attribs); + } + + $initSelection = null; + $value = array(); + + if (is_array($data) && count($data) > 0) { + foreach ($data as $key => $val) { + $object = new stdClass; + $object->id = $val->{$options['option.key']}; + $object->text = $val->{$options['option.text']}; + $initSelection[] = $object; + $value[] = $val->{$options['option.key']}; + } + } elseif (is_object( + $data + ) && isset($data->{$options['option.key']}) && isset($data->{$options['option.text']})) { + $initSelection = new stdClass; + $initSelection->id = $data->{$options['option.key']}; + $initSelection->text = $data->{$options['option.text']}; + $value[] = $data->{$options['option.key']}; + } + + $options['select2.options'] = array( + 'placeholder' => '', + 'minimumInputLength' => 2, + 'width' => 'resolve', + 'multiple' => 'false', + 'allowClear' => 'true', + 'ajax' => '{ // instead of writing the function to execute the request we use Select2\'s convenient helper url: "' . $options['select2.ajaxOptions']['url'] . '", dataType: "json", type: "post", @@ -235,125 +272,117 @@ public static function search($data, $name, $attribs = null, $getInitTemplate = return {results: data.result, more: more}; } }', - 'initSelection' => 'function(element, callback) { + 'initSelection' => 'function(element, callback) { callback(' . json_encode($initSelection) . '); }' - ); - - if (is_array($attribs)) - { - if (isset($attribs['select2.options']) && is_array($attribs['select2.options'])) - { - $options['select2.options'] = array_merge($options['select2.options'], $attribs['select2.options']); - } - } - - $id = $options['id'] !== false ? $options['id'] : $name; - $id = str_replace(array('[', ']'), '', $id); - - if ($getInitTemplate) - { - return JHtml::_('redshopjquery.select2', '#' . $id, $options['select2.options'], $getInitTemplate); - } - else - { - JHtml::_('redshopjquery.select2', '#' . $id, $options['select2.options']); - } - - $value = ArrayHelper::toInteger($value); - $value = implode(',', $value); - - if ($value == 0) - { - $value = ''; - } - - if (isset($options['list.attr']) && is_array($options['list.attr'])) - { - if (!isset($options['list.attr']['class']) || $options['list.attr']['class'] == '') - { - $options['list.attr']['class'] = 'searchSelect2'; - } - - $attribs = JArrayHelper::toString($options['list.attr']); - - if ($attribs != '') - { - $attribs = ' ' . $attribs; - } - } - else - { - $attribs = ' class="searchSelect2"'; - } - - return ''; - } - - /** - * Generates an HTML selection list. - * - * @param array $data An array of objects, arrays, or scalars. - * @param string $name The value of the HTML name attribute. - * @param mixed $attribs Additional HTML attributes for the '; + } + + /** + * Generates an HTML selection list. + * + * @param array $data An array of objects, arrays, or scalars. + * @param string $name The value of the HTML name attribute. + * @param mixed $attribs Additional HTML attributes for the '; - } + ); + + if (is_array($attribs)) { + if (isset($attribs['select2.options']) && is_array($attribs['select2.options'])) { + $options['select2.options'] = array_merge($options['select2.options'], $attribs['select2.options']); + } + } + + $id = $options['id'] !== false ? $options['id'] : $name; + $id = str_replace(array('[', ']'), '', $id); + + if ($getInitTemplate) { + return JHtml::_('redshopjquery.select2', '#' . $id, $options['select2.options'], $getInitTemplate); + } else { + JHtml::_('redshopjquery.select2', '#' . $id, $options['select2.options']); + } + + $value = ArrayHelper::toInteger($value); + $value = implode(',', $value); + + if ($value == 0) { + $value = ''; + } + + if (isset($options['list.attr']) && is_array($options['list.attr'])) { + if (!isset($options['list.attr']['class']) || $options['list.attr']['class'] == '') { + $options['list.attr']['class'] = 'searchSelect2'; + } + + $attribs = JArrayHelper::toString($options['list.attr']); + + if ($attribs != '') { + $attribs = ' ' . $attribs; + } + } else { + $attribs = ' class="searchSelect2"'; + } + + return ''; + } } diff --git a/libraries/redshop/html/redshopsortable.php b/libraries/redshop/html/redshopsortable.php index f886e3edcdc..d51bf056362 100644 --- a/libraries/redshop/html/redshopsortable.php +++ b/libraries/redshop/html/redshopsortable.php @@ -18,99 +18,102 @@ */ abstract class JHtmlRedshopSortable { - /** - * Array containing information for loaded files - * - * @var array - */ - protected static $loaded = array(); - - /** - * Extension name to use in the asset calls - * Basically the media/com_xxxxx folder to use - */ - const EXTENSION = 'redshop'; - - /** - * Load the main Searchtools libraries - * - * @return void - * - * @since 2.0.3 - */ - public static function main() - { - // Only load once - if (!empty(static::$loaded[__METHOD__])) - { - return; - } - - // Depends on jQuery UI - JHtml::_('redshopjquery.ui', array('core', 'sortable')); - - JHtml::script('com_redshop/sortablelist.min.js', false, true, false, false); - JHtml::stylesheet('com_redshop/sortablelist.min.css', false, true, false, false); - - static::$loaded[__METHOD__] = true; - - return; - } - - /** - * Method to load the Sortable script and make table sortable - * - * @param string $tableId DOM id of the table - * @param string $formId DOM id of the form - * @param string $sortDir Sort direction - * @param string $saveOrderingUrl Save ordering url, ajax-load after an item dropped - * @param boolean $proceedSaveOrderButton Set whether a save order button is displayed - * @param boolean $nestedList Set whether the list is a nested list - * - * @return void - */ - public static function sortable($tableId, $formId, $sortDir = 'asc', $saveOrderingUrl = '', $proceedSaveOrderButton = true, $nestedList = false) - { - // Only load once - if (isset(self::$loaded[__METHOD__])) - { - return; - } - - static::main(); - - // Attach sortable to document - JFactory::getDocument()->addScriptDeclaration(" + /** + * Extension name to use in the asset calls + * Basically the media/com_xxxxx folder to use + */ + const EXTENSION = 'redshop'; + /** + * Array containing information for loaded files + * + * @var array + */ + protected static $loaded = array(); + + /** + * Method to load the Sortable script and make table sortable + * + * @param string $tableId DOM id of the table + * @param string $formId DOM id of the form + * @param string $sortDir Sort direction + * @param string $saveOrderingUrl Save ordering url, ajax-load after an item dropped + * @param boolean $proceedSaveOrderButton Set whether a save order button is displayed + * @param boolean $nestedList Set whether the list is a nested list + * + * @return void + */ + public static function sortable( + $tableId, + $formId, + $sortDir = 'asc', + $saveOrderingUrl = '', + $proceedSaveOrderButton = true, + $nestedList = false + ) { + // Only load once + if (isset(self::$loaded[__METHOD__])) { + return; + } + + static::main(); + + // Attach sortable to document + JFactory::getDocument()->addScriptDeclaration( + " (function ($){ $(document).ready(function (){ var sortableList = new $.JSortableList('#" . $tableId . " tbody','" . $formId . "','" - . $sortDir . "' , '" . $saveOrderingUrl . "','','" . $nestedList . "'); + . $sortDir . "' , '" . $saveOrderingUrl . "','','" . $nestedList . "'); }); })(jQuery); " - ); - - if ($proceedSaveOrderButton) - { - self::_proceedSaveOrderButton(); - } - - // Set static array - self::$loaded[__METHOD__] = true; - - return; - } - - /** - * Method to inject script for enabled and disable Save order button - * when changing value of ordering input boxes - * - * @return void - */ - public static function _proceedSaveOrderButton() - { - JFactory::getDocument()->addScriptDeclaration( - "(function ($){ + ); + + if ($proceedSaveOrderButton) { + self::_proceedSaveOrderButton(); + } + + // Set static array + self::$loaded[__METHOD__] = true; + + return; + } + + /** + * Load the main Searchtools libraries + * + * @return void + * + * @since 2.0.3 + */ + public static function main() + { + // Only load once + if (!empty(static::$loaded[__METHOD__])) { + return; + } + + // Depends on jQuery UI + JHtml::_('redshopjquery.ui', array('core', 'sortable')); + + JHtml::script('com_redshop/sortablelist.min.js', false, true, false, false); + JHtml::stylesheet('com_redshop/sortablelist.min.css', false, true, false, false); + + static::$loaded[__METHOD__] = true; + + return; + } + + /** + * Method to inject script for enabled and disable Save order button + * when changing value of ordering input boxes + * + * @return void + */ + public static function _proceedSaveOrderButton() + { + JFactory::getDocument()->addScriptDeclaration( + "(function ($){ $(document).ready(function (){ var saveOrderButton = $('.saveorder'); saveOrderButton.css({'opacity':'0.2', 'cursor':'default'}).attr('onclick','return false;'); @@ -128,8 +131,8 @@ public static function _proceedSaveOrderButton() }); }); })(jQuery);" - ); + ); - return; - } + return; + } } diff --git a/libraries/redshop/install/install.php b/libraries/redshop/install/install.php index 7065d667a58..cc5d475f4bb 100644 --- a/libraries/redshop/install/install.php +++ b/libraries/redshop/install/install.php @@ -16,132 +16,131 @@ */ class RedshopInstall { - /** - * Install state key - * - * @var string - */ - const REDSHOP_INSTALL_STATE_NAME = 'redshop.install.tasks'; - - /** - * @var null|array - */ - public static $tasks = null; - - /** - * Get list of available tasks for clean install - * - * @return array|mixed - * - * @since 2.0.6 - * - * @throws Exception - */ - public static function getInstallTasks() - { - $tasks = array( - array( - 'text' => JText::_('COM_REDSHOP_INSTALL_STEP_SYNCHRONIZE_USERS'), - 'func' => 'RedshopInstall::synchronizeUser' - ), - array( - 'text' => JText::_('COM_REDSHOP_INSTALL_STEP_TEMPLATE_DATA'), - 'func' => 'RedshopInstall::templateData' - ), - array( - 'text' => JText::_('COM_REDSHOP_INSTALL_STEP_INTEGRATE_SH404SEF'), - 'func' => 'RedshopInstall::integrateSh404sef' - ), - array( - 'text' => JText::_('COM_REDSHOP_INSTALL_STEP_HANDLE_CONFIG'), - 'func' => 'RedshopInstall::handleConfig' - ) - ); - - JFactory::getApplication()->setUserState(self::REDSHOP_INSTALL_STATE_NAME, $tasks); - - return $tasks; - } - - /** - * Method for get remaining tasks - * - * @return mixed List of remaining tasks - * - * @since 2.0.6 - * - * @throws Exception - */ - public static function getRemainingTasks() - { - return JFactory::getApplication()->getUserState(self::REDSHOP_INSTALL_STATE_NAME, null); - } - - /** - * Method for synchronize Joomla User to redSHOP user - * - * @return int Number of synchronized user. - * - * @since 2.0.6 - * @throws Exception - */ - public static function synchronizeUser() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('u.*') - ->from($db->qn('#__users', 'u')) - ->leftJoin($db->qn('#__redshop_users_info', 'ru') . ' ON ' . $db->qn('ru.user_id') . ' = ' . $db->qn('u.id')) - ->where($db->qn('ru.user_id') . ' IS NULL'); - $joomlaUsers = $db->setQuery($query)->loadObjectList(); - - if (empty($joomlaUsers)) - { - return 0; - } - - foreach ($joomlaUsers as $joomlaUser) - { - $name = explode(" ", $joomlaUser->name); - - $post = array(); - $post['user_id'] = $joomlaUser->id; - $post['email'] = $joomlaUser->email; - $post['email1'] = $joomlaUser->email; - $post['firstname'] = $name[0]; - $post['lastname'] = (isset($name[1]) && $name[1]) ? $name[1] : ''; - $post['is_company'] = (Redshop::getConfig()->get('DEFAULT_CUSTOMER_REGISTER_TYPE') == 2) ? 1 : 0; - $post['password1'] = ''; - $post['billisship'] = 1; - - RedshopHelperUser::storeRedshopUser($post, $joomlaUser->id, 1); - } - - return count($joomlaUsers); - } - - /** - * Method for insert demo templates - * - * @return boolean - * - * @since 2.0.6 - */ - public static function templateData() - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true) - ->select('COUNT(id)') - ->from($db->qn('#__redshop_template')); - $result = $db->setQuery($query)->loadResult(); - - if ($result) - { - return true; - } - - // Start template demo content - $query = "INSERT IGNORE INTO `#__redshop_template` (`id`, `name`, `section`, `published`) VALUES + /** + * Install state key + * + * @var string + */ + const REDSHOP_INSTALL_STATE_NAME = 'redshop.install.tasks'; + + /** + * @var null|array + */ + public static $tasks = null; + + /** + * Get list of available tasks for clean install + * + * @return array|mixed + * + * @throws Exception + * @since 2.0.6 + * + */ + public static function getInstallTasks() + { + $tasks = array( + array( + 'text' => JText::_('COM_REDSHOP_INSTALL_STEP_SYNCHRONIZE_USERS'), + 'func' => 'RedshopInstall::synchronizeUser' + ), + array( + 'text' => JText::_('COM_REDSHOP_INSTALL_STEP_TEMPLATE_DATA'), + 'func' => 'RedshopInstall::templateData' + ), + array( + 'text' => JText::_('COM_REDSHOP_INSTALL_STEP_INTEGRATE_SH404SEF'), + 'func' => 'RedshopInstall::integrateSh404sef' + ), + array( + 'text' => JText::_('COM_REDSHOP_INSTALL_STEP_HANDLE_CONFIG'), + 'func' => 'RedshopInstall::handleConfig' + ) + ); + + JFactory::getApplication()->setUserState(self::REDSHOP_INSTALL_STATE_NAME, $tasks); + + return $tasks; + } + + /** + * Method for get remaining tasks + * + * @return mixed List of remaining tasks + * + * @throws Exception + * @since 2.0.6 + * + */ + public static function getRemainingTasks() + { + return JFactory::getApplication()->getUserState(self::REDSHOP_INSTALL_STATE_NAME, null); + } + + /** + * Method for synchronize Joomla User to redSHOP user + * + * @return int Number of synchronized user. + * + * @throws Exception + * @since 2.0.6 + */ + public static function synchronizeUser() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('u.*') + ->from($db->qn('#__users', 'u')) + ->leftJoin( + $db->qn('#__redshop_users_info', 'ru') . ' ON ' . $db->qn('ru.user_id') . ' = ' . $db->qn('u.id') + ) + ->where($db->qn('ru.user_id') . ' IS NULL'); + $joomlaUsers = $db->setQuery($query)->loadObjectList(); + + if (empty($joomlaUsers)) { + return 0; + } + + foreach ($joomlaUsers as $joomlaUser) { + $name = explode(" ", $joomlaUser->name); + + $post = array(); + $post['user_id'] = $joomlaUser->id; + $post['email'] = $joomlaUser->email; + $post['email1'] = $joomlaUser->email; + $post['firstname'] = $name[0]; + $post['lastname'] = (isset($name[1]) && $name[1]) ? $name[1] : ''; + $post['is_company'] = (Redshop::getConfig()->get('DEFAULT_CUSTOMER_REGISTER_TYPE') == 2) ? 1 : 0; + $post['password1'] = ''; + $post['billisship'] = 1; + + RedshopHelperUser::storeRedshopUser($post, $joomlaUser->id, 1); + } + + return count($joomlaUsers); + } + + /** + * Method for insert demo templates + * + * @return boolean + * + * @since 2.0.6 + */ + public static function templateData() + { + $db = JFactory::getDbo(); + $query = $db->getQuery(true) + ->select('COUNT(id)') + ->from($db->qn('#__redshop_template')); + $result = $db->setQuery($query)->loadResult(); + + if ($result) { + return true; + } + + // Start template demo content + $query = "INSERT IGNORE INTO `#__redshop_template` (`id`, `name`, `section`, `published`) VALUES (8, 'grid', 'category', 1), (5, 'list', 'category', 1), (26, 'product2', 'product',1), @@ -201,159 +200,155 @@ public static function templateData() (550, 'stock_note', 'stock_note', 1), (551, 'login', 'login', 1)"; - $db->setQuery($query)->execute(); - - $query = $db->getQuery(true) - ->select($db->qn('id')) - ->from($db->qn('#__redshop_template')) - ->order($db->qn('id')); - $templates = $db->setQuery($query)->loadColumn(); - - foreach ($templates as $templateId) - { - /** @var RedshopTableTemplate $table */ - $table = RedshopTable::getAdminInstance('Template', array('ignore_request' => true), 'com_redshop'); - - $table->load($templateId); - $table->templateDesc = RedshopHelperTemplate::getDefaultTemplateContent($table->section); - $table->store(); - } - - return true; - } - - /** - * Method for integrate with com_sh404sef extension if necessary. - * - * @return boolean - * - * @throws Exception - * - * @since 2.0.3 - */ - public static function integrateSh404sef() - { - if (!JComponentHelper::isInstalled('com_sh404sef')) - { - return true; - } - - // Install the sh404SEF router files - JLoader::import('joomla.filesystem.file'); - JLoader::import('joomla.filesystem.folder'); - - $sh404SEFAdmin = JPATH_SITE . '/administrator/components/com_sh404sef'; - $redShopSefFolder = JPATH_SITE . '/administrator/components/com_redshop/extras'; - - if (!JFile::copy($redShopSefFolder . '/sh404sef/language/com_redshop.php', $sh404SEFAdmin . '/language/plugins/com_redshop.php')) - { - throw new Exception(JText::_('COM_REDSHOP_FAILED_TO_COPY_SH404SEF_PLUGIN_LANGUAGE_FILE')); - } - - return true; - } - - /** - * Handle config - * - * @return void - * - * @since 2.0.6 - * - * @throws Exception - */ - public static function handleConfig() - { - // Only loading from legacy when version is older than 1.6 - if (version_compare(RedshopHelperJoomla::getManifestValue('version'), '1.6', '<')) - { - // Load configuration file from legacy file. - Redshop::getConfig()->loadLegacy(); - } - - // Try to load distinct if no config found. - Redshop::getConfig()->loadDist(); - } - - /** - * Method for get specific available version of installation. - * - * @param string $version Version specific. - * - * @return array - * - * @since 2.1.0 - */ - public static function getUpdateTasks($version = null) - { - if (null === $version) - { - return array(); - } - - $tasks = self::loadUpdateTasks(); - - if (empty($tasks) || !isset($tasks[$version])) - { - return array(); - } - - return $tasks[$version]; - } - - /** - * Method for get all available version of installation. - * - * @return array List of update tasks. - * - * @since 2.1.0 - */ - public static function loadUpdateTasks() - { - if (null !== self::$tasks) - { - return self::$tasks; - } - - $updatePath = JPATH_COMPONENT_ADMINISTRATOR . '/updates'; - - $files = JFolder::files($updatePath, '.php', false, true); - $versions = array(); - - foreach ($files as $file) - { - $version = new stdClass; - - $version->version = JFile::stripExt(basename($file)); - - require_once $file; - - $version->class = 'RedshopUpdate' . str_replace(array('.', '-'), '', $version->version); - $version->path = $file; - - /** @var RedshopInstallUpdate $updateClass */ - $updateClass = new $version->class; - $classTasks = $updateClass->getTasksList(); - $version->tasks = array(); - - if (empty($classTasks)) - { - continue; - } - - foreach ($classTasks as $classTask) - { - $version->tasks[] = array('text' => JText::_($classTask->name), 'func' => $version->class . '.' . $classTask->func); - } - - $versions[$version->version] = $version; - } - - uksort($versions, 'version_compare'); - $versions = array_reverse($versions); - - self::$tasks = $versions; - - return self::$tasks; - } + $db->setQuery($query)->execute(); + + $query = $db->getQuery(true) + ->select($db->qn('id')) + ->from($db->qn('#__redshop_template')) + ->order($db->qn('id')); + $templates = $db->setQuery($query)->loadColumn(); + + foreach ($templates as $templateId) { + /** @var RedshopTableTemplate $table */ + $table = RedshopTable::getAdminInstance('Template', array('ignore_request' => true), 'com_redshop'); + + $table->load($templateId); + $table->templateDesc = RedshopHelperTemplate::getDefaultTemplateContent($table->section); + $table->store(); + } + + return true; + } + + /** + * Method for integrate with com_sh404sef extension if necessary. + * + * @return boolean + * + * @throws Exception + * + * @since 2.0.3 + */ + public static function integrateSh404sef() + { + if (!JComponentHelper::isInstalled('com_sh404sef')) { + return true; + } + + // Install the sh404SEF router files + JLoader::import('joomla.filesystem.file'); + JLoader::import('joomla.filesystem.folder'); + + $sh404SEFAdmin = JPATH_SITE . '/administrator/components/com_sh404sef'; + $redShopSefFolder = JPATH_SITE . '/administrator/components/com_redshop/extras'; + + if (!JFile::copy( + $redShopSefFolder . '/sh404sef/language/com_redshop.php', + $sh404SEFAdmin . '/language/plugins/com_redshop.php' + )) { + throw new Exception(JText::_('COM_REDSHOP_FAILED_TO_COPY_SH404SEF_PLUGIN_LANGUAGE_FILE')); + } + + return true; + } + + /** + * Handle config + * + * @return void + * + * @throws Exception + * @since 2.0.6 + * + */ + public static function handleConfig() + { + // Only loading from legacy when version is older than 1.6 + if (version_compare(RedshopHelperJoomla::getManifestValue('version'), '1.6', '<')) { + // Load configuration file from legacy file. + Redshop::getConfig()->loadLegacy(); + } + + // Try to load distinct if no config found. + Redshop::getConfig()->loadDist(); + } + + /** + * Method for get specific available version of installation. + * + * @param string $version Version specific. + * + * @return array + * + * @since 2.1.0 + */ + public static function getUpdateTasks($version = null) + { + if (null === $version) { + return array(); + } + + $tasks = self::loadUpdateTasks(); + + if (empty($tasks) || !isset($tasks[$version])) { + return array(); + } + + return $tasks[$version]; + } + + /** + * Method for get all available version of installation. + * + * @return array List of update tasks. + * + * @since 2.1.0 + */ + public static function loadUpdateTasks() + { + if (null !== self::$tasks) { + return self::$tasks; + } + + $updatePath = JPATH_COMPONENT_ADMINISTRATOR . '/updates'; + + $files = JFolder::files($updatePath, '.php', false, true); + $versions = array(); + + foreach ($files as $file) { + $version = new stdClass; + + $version->version = JFile::stripExt(basename($file)); + + require_once $file; + + $version->class = 'RedshopUpdate' . str_replace(array('.', '-'), '', $version->version); + $version->path = $file; + + /** @var RedshopInstallUpdate $updateClass */ + $updateClass = new $version->class; + $classTasks = $updateClass->getTasksList(); + $version->tasks = array(); + + if (empty($classTasks)) { + continue; + } + + foreach ($classTasks as $classTask) { + $version->tasks[] = array( + 'text' => JText::_($classTask->name), + 'func' => $version->class . '.' . $classTask->func + ); + } + + $versions[$version->version] = $version; + } + + uksort($versions, 'version_compare'); + $versions = array_reverse($versions); + + self::$tasks = $versions; + + return self::$tasks; + } } diff --git a/libraries/redshop/install/update.php b/libraries/redshop/install/update.php index 2df862b399e..7eb60378eb2 100644 --- a/libraries/redshop/install/update.php +++ b/libraries/redshop/install/update.php @@ -18,40 +18,40 @@ */ class RedshopInstallUpdate extends AbstractUpdate { - /** - * Return list of old files for clean - * - * @return array - * - * @since 2.0.6 - */ - protected function getOldFiles() - { - return array(); - } + /** + * Method clean old files + * + * @return void + * + * @since 2.0.6 + */ + public function cleanOldFiles() + { + $this->deleteFolders($this->getOldFolders()); + $this->deleteFiles($this->getOldFiles()); + } - /** - * Return list of old folders for clean - * - * @return array - * - * @since 2.0.6 - */ - protected function getOldFolders() - { - return array(); - } + /** + * Return list of old folders for clean + * + * @return array + * + * @since 2.0.6 + */ + protected function getOldFolders() + { + return array(); + } - /** - * Method clean old files - * - * @return void - * - * @since 2.0.6 - */ - public function cleanOldFiles() - { - $this->deleteFolders($this->getOldFolders()); - $this->deleteFiles($this->getOldFiles()); - } + /** + * Return list of old files for clean + * + * @return array + * + * @since 2.0.6 + */ + protected function getOldFiles() + { + return array(); + } } diff --git a/libraries/redshop/language/en-GB/en-GB.lib_redshop.ini b/libraries/redshop/language/en-GB/en-GB.lib_redshop.ini index d50f7a8d008..7382855a89c 100644 --- a/libraries/redshop/language/en-GB/en-GB.lib_redshop.ini +++ b/libraries/redshop/language/en-GB/en-GB.lib_redshop.ini @@ -3,35 +3,35 @@ ; License http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE.php ; Note : All ini files need to be saved as UTF-8 -LIB_REDSHOP="redSHOP Library" -LIB_REDSHOP_DESCRIPTION="Library for redSHOP applications" -LIB_REDSHOP_SELECT2_NO_MATHES="No matches found" -LIB_REDSHOP_SELECT2_PREFIX="s" -LIB_REDSHOP_SELECT2_INPUT_TO_SHORT="Please enter "_QQ_" + n + "_QQ_" more character" -LIB_REDSHOP_SELECT2_TO_LONG="Please delete "_QQ_" + n + "_QQ_" character" -LIB_REDSHOP_SELECT2_TO_BIG="You can only select "_QQ_" + limit + "_QQ_" item" -LIB_REDSHOP_SELECT2_LOAD_MORE="Loading more results..." -LIB_REDSHOP_SELECT2_SEARCHING="Searching..." -LIB_REDSHOP_SELECT2_PLACEHOLDER="Enter name/surname or login" -LIB_REDSHOP_PDF_CREATOR="redSHOP" -LIB_REDSHOP_APPLICATION_ERROR_PDF_LOAD="Unable to load: %s. Please download and install latest library from http://redcomponent.com" +LIB_REDSHOP = "redSHOP Library" +LIB_REDSHOP_DESCRIPTION = "Library for redSHOP applications" +LIB_REDSHOP_SELECT2_NO_MATHES = "No matches found" +LIB_REDSHOP_SELECT2_PREFIX = "s" +LIB_REDSHOP_SELECT2_INPUT_TO_SHORT = "Please enter "_QQ_" + n + "_QQ_" more character" +LIB_REDSHOP_SELECT2_TO_LONG = "Please delete "_QQ_" + n + "_QQ_" character" +LIB_REDSHOP_SELECT2_TO_BIG = "You can only select "_QQ_" + limit + "_QQ_" item" +LIB_REDSHOP_SELECT2_LOAD_MORE = "Loading more results..." +LIB_REDSHOP_SELECT2_SEARCHING = "Searching..." +LIB_REDSHOP_SELECT2_PLACEHOLDER = "Enter name/surname or login" +LIB_REDSHOP_PDF_CREATOR = "redSHOP" +LIB_REDSHOP_APPLICATION_ERROR_PDF_LOAD = "Unable to load: %s. Please download and install latest library from http://redcomponent.com" -LIB_REDSHOP_GIFTCARD_CODE_LBL="Gift Card Code" -LIB_REDSHOP_GIFTCARD_VALUE_LBL="Gift Card Value" -LIB_REDSHOP_GIFTCARD_RECIVER_EMAIL_LBL="Gift Card Receiver Email" -LIB_REDSHOP_GIFTCARD_RECIVER_NAME_LBL="Gift Card Receiver Name" -LIB_REDSHOP_GIFTCARD_PRICE_LBL="Gift Card Price" -LIB_REDSHOP_SELECT_SHIP_METHOD="Please select shipping method" +LIB_REDSHOP_GIFTCARD_CODE_LBL = "Gift Card Code" +LIB_REDSHOP_GIFTCARD_VALUE_LBL = "Gift Card Value" +LIB_REDSHOP_GIFTCARD_RECIVER_EMAIL_LBL = "Gift Card Receiver Email" +LIB_REDSHOP_GIFTCARD_RECIVER_NAME_LBL = "Gift Card Receiver Name" +LIB_REDSHOP_GIFTCARD_PRICE_LBL = "Gift Card Price" +LIB_REDSHOP_SELECT_SHIP_METHOD = "Please select shipping method" -LIB_REDSHOP_FILE_IS_NOT_EXIST="File %s is not exist" -LIB_REDSHOP_LEGACY_CONFIG_FILE_IS_NOT_EXIST="Legacy config file is not exist" -LIB_REDSHOP_LEGACY_CONFIG_FILE_IS_NOT_VALID="Legacy file %s is found invalid." +LIB_REDSHOP_FILE_IS_NOT_EXIST = "File %s is not exist" +LIB_REDSHOP_LEGACY_CONFIG_FILE_IS_NOT_EXIST = "Legacy config file is not exist" +LIB_REDSHOP_LEGACY_CONFIG_FILE_IS_NOT_VALID = "Legacy file %s is found invalid." -LIB_REDSHOP_AJAX_ERROR_ACCESS_FORBIDDEN="AJAX Access forbidden." +LIB_REDSHOP_AJAX_ERROR_ACCESS_FORBIDDEN = "AJAX Access forbidden." -LIB_REDSHOP_PRODUCT_ID_NOT_VALID_INTEGER="Id %s is not valid integer in %s. Your id has %s datatype." -LIB_REDSHOP_PRODUCT_NOT_FOUND_ERROR="Product information not found in %s" +LIB_REDSHOP_PRODUCT_ID_NOT_VALID_INTEGER = "Id %s is not valid integer in %s. Your id has %s datatype." +LIB_REDSHOP_PRODUCT_NOT_FOUND_ERROR = "Product information not found in %s" -LIB_REDSHOP_FIELD_ERROR_CANNOT_LOAD_FIELD="Error! Can not load field: %s" +LIB_REDSHOP_FIELD_ERROR_CANNOT_LOAD_FIELD = "Error! Can not load field: %s" -LIB_REDSHOP_PACSOFT_ERROR_NO_RESPONSE="

    Connection to Pacsoft failed. Please make sure that you have the XMLPosting add-on.

    You can get this from the Pacsoft webshop.
    In the right-side menu, click Webshop => Choose the Unifaun webshop => Additional Functionality => ERPConnect - XMLPosting." +LIB_REDSHOP_PACSOFT_ERROR_NO_RESPONSE = "

    Connection to Pacsoft failed. Please make sure that you have the XMLPosting add-on.

    You can get this from the Pacsoft webshop.
    In the right-side menu, click Webshop => Choose the Unifaun webshop => Additional Functionality => ERPConnect - XMLPosting." diff --git a/libraries/redshop/language/en-GB/en-GB.lib_redshop.sys.ini b/libraries/redshop/language/en-GB/en-GB.lib_redshop.sys.ini index f1512f92fbc..4186e02d358 100644 --- a/libraries/redshop/language/en-GB/en-GB.lib_redshop.sys.ini +++ b/libraries/redshop/language/en-GB/en-GB.lib_redshop.sys.ini @@ -3,5 +3,5 @@ ; License http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE.php ; Note : All ini files need to be saved as UTF-8 -LIB_REDSHOP="redSHOP Library" -LIB_REDSHOP_DESCRIPTION="Library for redSHOP applications" \ No newline at end of file +LIB_REDSHOP = "redSHOP Library" +LIB_REDSHOP_DESCRIPTION = "Library for redSHOP applications" \ No newline at end of file diff --git a/libraries/redshop/language/en-GB/en-GB.lib_twig.ini b/libraries/redshop/language/en-GB/en-GB.lib_twig.ini index 2eaaf824a03..a496d171415 100644 --- a/libraries/redshop/language/en-GB/en-GB.lib_twig.ini +++ b/libraries/redshop/language/en-GB/en-GB.lib_twig.ini @@ -3,8 +3,8 @@ ; License http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE ; Note : All ini files need to be saved as UTF-8 -LIB_TWIG_EXTENSION_JUSER_ERROR_MISSING_ID="Missing user identifier when using juser() in twig template. Use juser (with no parenthesis) for active user." -LIB_TWIG_LBL_COMPONENT="Component" -LIB_TWIG_LBL_MODULE="Module" -LIB_TWIG_LBL_PLUGIN="Plugin" -LIB_TWIG_LBL_TEMPLATE="Template" +LIB_TWIG_EXTENSION_JUSER_ERROR_MISSING_ID = "Missing user identifier when using juser() in twig template. Use juser (with no parenthesis) for active user." +LIB_TWIG_LBL_COMPONENT = "Component" +LIB_TWIG_LBL_MODULE = "Module" +LIB_TWIG_LBL_PLUGIN = "Plugin" +LIB_TWIG_LBL_TEMPLATE = "Template" diff --git a/libraries/redshop/layout/base.php b/libraries/redshop/layout/base.php index 5bf61387fcb..96c3af3c1c1 100644 --- a/libraries/redshop/layout/base.php +++ b/libraries/redshop/layout/base.php @@ -21,127 +21,120 @@ */ class RedshopLayoutBase implements RedshopLayout { - /** - * Options object - * - * @var Registry - */ - protected $options = null; + /** + * Options object + * + * @var Registry + */ + protected $options = null; - /** - * Debug information messages - * - * @var array - */ - protected $debugMessages = array(); + /** + * Debug information messages + * + * @var array + */ + protected $debugMessages = array(); - /** - * Set the options - * - * @param mixed $options Array / JRegistry object with the options to load - * - * @return RedshopLayoutBase An instance of itself for chaining - */ - public function setOptions($options = null) - { - // Received JRegistry - if ($options instanceof Registry) - { - $this->options = $options; - } + /** + * Get the options + * + * @return Registry Object with the options + */ + public function getOptions() + { + // Always return a JRegistry instance + if (!($this->options instanceof Registry)) { + $this->resetOptions(); + } - // Received array - elseif (is_array($options)) - { - $this->options = new Registry($options); - } - else - { - $this->options = new Registry; - } + return $this->options; + } - return $this; - } + /** + * Set the options + * + * @param mixed $options Array / JRegistry object with the options to load + * + * @return RedshopLayoutBase An instance of itself for chaining + */ + public function setOptions($options = null) + { + // Received JRegistry + if ($options instanceof Registry) { + $this->options = $options; + } // Received array + elseif (is_array($options)) { + $this->options = new Registry($options); + } else { + $this->options = new Registry; + } - /** - * Get the options - * - * @return Registry Object with the options - */ - public function getOptions() - { - // Always return a JRegistry instance - if (!($this->options instanceof Registry)) - { - $this->resetOptions(); - } + return $this; + } - return $this->options; - } + /** + * Function to empty all the options + * + * @return RedshopLayoutBase Instance of $this to allow chaining. + */ + public function resetOptions() + { + return $this->setOptions(null); + } - /** - * Function to empty all the options - * - * @return RedshopLayoutBase Instance of $this to allow chaining. - */ - public function resetOptions() - { - return $this->setOptions(null); - } + /** + * Method to escape output. + * + * @param string $output The output to escape. + * + * @return string The escaped output. + */ + public function escape($output) + { + return htmlspecialchars($output, ENT_COMPAT, 'UTF-8'); + } - /** - * Method to escape output. - * - * @param string $output The output to escape. - * - * @return string The escaped output. - */ - public function escape($output) - { - return htmlspecialchars($output, ENT_COMPAT, 'UTF-8'); - } + /** + * Get the debug messages array + * + * @return array + */ + public function getDebugMessages() + { + return $this->debugMessages; + } - /** - * Get the debug messages array - * - * @return array - */ - public function getDebugMessages() - { - return $this->debugMessages; - } + /** + * Method to render the layout. + * + * @param object $displayData Object which properties are used inside the layout file to build displayed output + * + * @return string The necessary HTML to display the layout + */ + public function render($displayData) + { + return ''; + } - /** - * Method to render the layout. - * - * @param object $displayData Object which properties are used inside the layout file to build displayed output - * - * @return string The necessary HTML to display the layout - */ - public function render($displayData) - { - return ''; - } + /** + * Render the list of debug messages + * + * @return string Output text/HTML code + */ + public function renderDebugMessages() + { + return implode($this->debugMessages, "\n"); + } - /** - * Render the list of debug messages - * - * @return string Output text/HTML code - */ - public function renderDebugMessages() - { - return implode($this->debugMessages, "\n"); - } - - /** - * Add a debug message to the debug messages array - * - * @param string $message Message to save - * - * @return void - */ - public function addDebugMessage($message) - { - $this->debugMessages[] = $message; - } + /** + * Add a debug message to the debug messages array + * + * @param string $message Message to save + * + * @return void + */ + public function addDebugMessage($message) + { + $this->debugMessages[] = $message; + } } diff --git a/libraries/redshop/layout/file.php b/libraries/redshop/layout/file.php index ecf6efac6bc..c9f606fa936 100644 --- a/libraries/redshop/layout/file.php +++ b/libraries/redshop/layout/file.php @@ -20,411 +20,391 @@ */ class RedshopLayoutFile extends RedshopLayoutBase { - /** - * @var string Dot separated path to the layout file, relative to base path - */ - protected $layoutId = ''; - - /** - * @var string Base path to use when loading layout files - */ - protected $basePath = null; - - /** - * @var string Full path to actual layout files, after possible template override check - */ - protected $fullPath = null; - - /** - * Paths to search for layouts - * - * @var array - */ - protected $includePaths = array(); - - /** - * Method to instantiate the file-based layout. - * - * @param string $layoutId Dot separated path to the layout file, relative to base path - * @param string $basePath Base path to use when loading layout files - * @param mixed $options Optional custom options to load. JRegistry or array format [@since 3.2] - */ - public function __construct($layoutId, $basePath = null, $options = null) - { - // Initialise / Load options - $this->setOptions($options); - - // Main properties - $this->setLayout($layoutId); - $this->basePath = $basePath; - - // Init Environment - $this->setComponent($this->options->get('component', 'auto')); - $this->setClient($this->options->get('client', 'auto')); - } - - /** - * Method to render the layout. - * - * @param array $displayData List properties are used inside the layout file to build displayed output - * - * @return string The necessary HTML to display the layout - */ - public function render($displayData) - { - $layoutOutput = ''; - - // Check possible overrides, and build the full path to layout file - $path = $this->getPath(); - - if ($this->options->get('debug', false)) - { - echo "
    " . $this->renderDebugMessages() . "
    "; - } - - // If there exists such a layout file, include it and collect its output - if (!empty($path)) - { - ob_start(); - include $path; - $layoutOutput = ob_get_contents(); - ob_end_clean(); - } - - return $layoutOutput; - } - - /** - * Method to finds the full real file path, checking possible overrides - * - * @return string The full path to the layout file - */ - protected function getPath() - { - JLoader::import('joomla.filesystem.path'); - - if (is_null($this->fullPath) && !empty($this->layoutId)) - { - $this->addDebugMessage('Layout: ' . $this->layoutId); - - // Refresh paths - $this->refreshIncludePaths(); - - $this->addDebugMessage('Include Paths: ' . print_r($this->includePaths, true)); - - $suffixes = $this->options->get('suffixes', array()); - - // Search for suffixed versions. Example: tags.j31.php - if (!empty($suffixes)) - { - $this->addDebugMessage('Suffixes: ' . print_r($suffixes, true)); - - foreach ($suffixes as $suffix) - { - $rawPath = str_replace('.', '/', $this->layoutId) . '.' . $suffix . '.php'; - $this->addDebugMessage('Searching layout for: ' . $rawPath); - - if ($this->fullPath = JPath::find($this->includePaths, $rawPath)) - { - $this->addDebugMessage('Found layout: ' . $this->fullPath); - - return $this->fullPath; - } - } - } - - // Standard version - $rawPath = str_replace('.', '/', $this->layoutId) . '.php'; - $this->addDebugMessage('Searching layout for: ' . $rawPath); - - $this->fullPath = JPath::find($this->includePaths, $rawPath); - - if ($this->fullPath) - { - $this->addDebugMessage('Found layout: ' . $this->fullPath); - } - } - - return $this->fullPath; - } - - /** - * Add one path to include in layout search. Proxy of addIncludePaths() - * - * @param string $path The path to search for layouts - * - * @return void - */ - public function addIncludePath($path) - { - $this->addIncludePaths($path); - } - - /** - * Add one or more paths to include in layout search - * - * @param string $paths The path or array of paths to search for layouts - * - * @return void - */ - public function addIncludePaths($paths) - { - if (!empty($paths)) - { - if (is_array($paths)) - { - $this->includePaths = array_unique(array_merge($paths, $this->includePaths)); - } - else - { - array_unshift($this->includePaths, $paths); - } - } - } - - /** - * Remove one path from the layout search - * - * @param string $path The path to remove from the layout search - * - * @return void - */ - public function removeIncludePath($path) - { - $this->removeIncludePaths($path); - } - - /** - * Remove one or more paths to exclude in layout search - * - * @param string $paths The path or array of paths to remove for the layout search - * - * @return void - */ - public function removeIncludePaths($paths) - { - if (!empty($paths)) - { - $paths = (array) $paths; - - $this->includePaths = array_diff($this->includePaths, $paths); - } - } - - /** - * Validate that the active component is valid - * - * @param string $option URL Option of the component. Example: com_content - * - * @return boolean - */ - protected function validComponent($option = null) - { - // By default we will validate the active component - $component = ($option !== null) ? $option : $this->options->get('component', null); - - if (!empty($component)) - { - // Valid option format - if (substr_count($component, 'com_')) - { - // Latest check: component exists and is enabled - return JComponentHelper::isEnabled($component); - } - } - - return false; - } - - /** - * Method to change the component where search for layouts - * - * @param string $option URL Option of the component. Example: com_content - * - * @return void - */ - public function setComponent($option) - { - $component = null; - - switch ((string) $option) - { - case 'none': - $component = null; - break; - - case 'auto': - if (defined('JPATH_COMPONENT')) - { - $parts = explode('/', JPATH_COMPONENT); - $component = end($parts); - } - - break; - - default: - $component = $option; - break; - } - - // Extra checks - if (!$this->validComponent($component)) - { - $component = null; - } - - $this->options->set('component', $component); - - // Refresh include paths - $this->refreshIncludePaths(); - } - - /** - * Function to initialise the application client - * - * @param mixed $client Frontend: 'site' or 0 | Backend: 'admin' or 1 - * - * @return void - */ - public function setClient($client) - { - // Force string conversion to avoid unexpected states - switch ((string) $client) - { - case 'site': - case '0': - $client = 0; - break; - - case 'admin': - case '1': - $client = 1; - break; - - default: - $client = (int) JFactory::getApplication()->isAdmin(); - break; - } - - $this->options->set('client', $client); - - // Refresh include paths - $this->refreshIncludePaths(); - } - - /** - * Change the layout - * - * @param string $layoutId Layout to render - * - * @return void - */ - public function setLayout($layoutId) - { - $this->layoutId = $layoutId; - $this->fullPath = null; - } - - /** - * Refresh the list of include paths - * - * @return void - */ - protected function refreshIncludePaths() - { - // Reset includePaths - $this->includePaths = array(); - - // (0 - lower priority) Frontend base layouts - $this->addIncludePaths(JPATH_ROOT . '/layouts'); - - // (1) Library path - $this->addIncludePaths(JPATH_LIBRARIES . '/redshop/layouts'); - - // (2) Standard Joomla! layouts overriden - $this->addIncludePaths(JPATH_THEMES . '/' . JFactory::getApplication()->getTemplate() . '/html/layouts'); - - // Component layouts & overrides if exist - $component = $this->options->get('component', null); - - if (!empty($component)) - { - // (3) Component path - if ($this->options->get('client') == 0) - { - $this->addIncludePaths(JPATH_SITE . '/components/' . $component . '/layouts'); - } - else - { - $this->addIncludePaths(JPATH_ADMINISTRATOR . '/components/' . $component . '/layouts'); - } - - // (4) Component template overrides path - $this->addIncludePath(JPATH_THEMES . '/' . JFactory::getApplication()->getTemplate() . '/html/layouts/' . $component); - } - - // Plugins layouts & overrides if exist - $plugin = $this->options->get('plugin', null); - - if (!empty($plugin)) - { - // (3) Plugins path - $this->addIncludePaths(JPATH_PLUGINS . '/' . $plugin . '/layouts'); - - // (4) Plugins template overrides path - $this->addIncludePath(JPATH_THEMES . '/' . JFactory::getApplication()->getTemplate() . '/html/layouts/plugins/' . $plugin); - } - - // Modules layouts & overrides if exist - $module = $this->options->get('module', null); - - if (!empty($module)) - { - // (3) Modules path - $this->addIncludePaths(JPATH_SITE . '/modules/' . $module . '/layouts'); - - // (4) Modules template overrides path - $this->addIncludePath(JPATH_THEMES . '/' . JFactory::getApplication()->getTemplate() . '/html/layouts/modules/' . $module); - } - - // (5 - highest priority) Received a custom high priority path ? - if (!is_null($this->basePath)) - { - $this->addIncludePath(rtrim($this->basePath, DIRECTORY_SEPARATOR)); - } - } - - /** - * Change the debug mode - * - * @param boolean $debug Enable / Disable debug - * - * @return void - */ - public function setDebug($debug) - { - $this->options->set('debug', (boolean) $debug); - } - - /** - * Render a layout with the same include paths & options - * - * @param object $layoutId Object which properties are used inside the layout file to build displayed output - * @param mixed $displayData Data to be rendered - * - * @return string The necessary HTML to display the layout - */ - public function sublayout($layoutId, $displayData) - { - // Sublayouts are searched in a subfolder with the name of the current layout - if (!empty($this->layoutId)) - { - $layoutId = $this->layoutId . '.' . $layoutId; - } - - $sublayout = new static($layoutId, $this->basePath, $this->options); - $sublayout->includePaths = $this->includePaths; - - return $sublayout->render($displayData); - } + /** + * @var string Dot separated path to the layout file, relative to base path + */ + protected $layoutId = ''; + + /** + * @var string Base path to use when loading layout files + */ + protected $basePath = null; + + /** + * @var string Full path to actual layout files, after possible template override check + */ + protected $fullPath = null; + + /** + * Paths to search for layouts + * + * @var array + */ + protected $includePaths = array(); + + /** + * Method to instantiate the file-based layout. + * + * @param string $layoutId Dot separated path to the layout file, relative to base path + * @param string $basePath Base path to use when loading layout files + * @param mixed $options Optional custom options to load. JRegistry or array format [@since 3.2] + */ + public function __construct($layoutId, $basePath = null, $options = null) + { + // Initialise / Load options + $this->setOptions($options); + + // Main properties + $this->setLayout($layoutId); + $this->basePath = $basePath; + + // Init Environment + $this->setComponent($this->options->get('component', 'auto')); + $this->setClient($this->options->get('client', 'auto')); + } + + /** + * Change the layout + * + * @param string $layoutId Layout to render + * + * @return void + */ + public function setLayout($layoutId) + { + $this->layoutId = $layoutId; + $this->fullPath = null; + } + + /** + * Method to change the component where search for layouts + * + * @param string $option URL Option of the component. Example: com_content + * + * @return void + */ + public function setComponent($option) + { + $component = null; + + switch ((string)$option) { + case 'none': + $component = null; + break; + + case 'auto': + if (defined('JPATH_COMPONENT')) { + $parts = explode('/', JPATH_COMPONENT); + $component = end($parts); + } + + break; + + default: + $component = $option; + break; + } + + // Extra checks + if (!$this->validComponent($component)) { + $component = null; + } + + $this->options->set('component', $component); + + // Refresh include paths + $this->refreshIncludePaths(); + } + + /** + * Validate that the active component is valid + * + * @param string $option URL Option of the component. Example: com_content + * + * @return boolean + */ + protected function validComponent($option = null) + { + // By default we will validate the active component + $component = ($option !== null) ? $option : $this->options->get('component', null); + + if (!empty($component)) { + // Valid option format + if (substr_count($component, 'com_')) { + // Latest check: component exists and is enabled + return JComponentHelper::isEnabled($component); + } + } + + return false; + } + + /** + * Refresh the list of include paths + * + * @return void + */ + protected function refreshIncludePaths() + { + // Reset includePaths + $this->includePaths = array(); + + // (0 - lower priority) Frontend base layouts + $this->addIncludePaths(JPATH_ROOT . '/layouts'); + + // (1) Library path + $this->addIncludePaths(JPATH_LIBRARIES . '/redshop/layouts'); + + // (2) Standard Joomla! layouts overriden + $this->addIncludePaths(JPATH_THEMES . '/' . JFactory::getApplication()->getTemplate() . '/html/layouts'); + + // Component layouts & overrides if exist + $component = $this->options->get('component', null); + + if (!empty($component)) { + // (3) Component path + if ($this->options->get('client') == 0) { + $this->addIncludePaths(JPATH_SITE . '/components/' . $component . '/layouts'); + } else { + $this->addIncludePaths(JPATH_ADMINISTRATOR . '/components/' . $component . '/layouts'); + } + + // (4) Component template overrides path + $this->addIncludePath( + JPATH_THEMES . '/' . JFactory::getApplication()->getTemplate() . '/html/layouts/' . $component + ); + } + + // Plugins layouts & overrides if exist + $plugin = $this->options->get('plugin', null); + + if (!empty($plugin)) { + // (3) Plugins path + $this->addIncludePaths(JPATH_PLUGINS . '/' . $plugin . '/layouts'); + + // (4) Plugins template overrides path + $this->addIncludePath( + JPATH_THEMES . '/' . JFactory::getApplication()->getTemplate() . '/html/layouts/plugins/' . $plugin + ); + } + + // Modules layouts & overrides if exist + $module = $this->options->get('module', null); + + if (!empty($module)) { + // (3) Modules path + $this->addIncludePaths(JPATH_SITE . '/modules/' . $module . '/layouts'); + + // (4) Modules template overrides path + $this->addIncludePath( + JPATH_THEMES . '/' . JFactory::getApplication()->getTemplate() . '/html/layouts/modules/' . $module + ); + } + + // (5 - highest priority) Received a custom high priority path ? + if (!is_null($this->basePath)) { + $this->addIncludePath(rtrim($this->basePath, DIRECTORY_SEPARATOR)); + } + } + + /** + * Add one or more paths to include in layout search + * + * @param string $paths The path or array of paths to search for layouts + * + * @return void + */ + public function addIncludePaths($paths) + { + if (!empty($paths)) { + if (is_array($paths)) { + $this->includePaths = array_unique(array_merge($paths, $this->includePaths)); + } else { + array_unshift($this->includePaths, $paths); + } + } + } + + /** + * Add one path to include in layout search. Proxy of addIncludePaths() + * + * @param string $path The path to search for layouts + * + * @return void + */ + public function addIncludePath($path) + { + $this->addIncludePaths($path); + } + + /** + * Function to initialise the application client + * + * @param mixed $client Frontend: 'site' or 0 | Backend: 'admin' or 1 + * + * @return void + */ + public function setClient($client) + { + // Force string conversion to avoid unexpected states + switch ((string)$client) { + case 'site': + case '0': + $client = 0; + break; + + case 'admin': + case '1': + $client = 1; + break; + + default: + $client = (int)JFactory::getApplication()->isAdmin(); + break; + } + + $this->options->set('client', $client); + + // Refresh include paths + $this->refreshIncludePaths(); + } + + /** + * Remove one path from the layout search + * + * @param string $path The path to remove from the layout search + * + * @return void + */ + public function removeIncludePath($path) + { + $this->removeIncludePaths($path); + } + + /** + * Remove one or more paths to exclude in layout search + * + * @param string $paths The path or array of paths to remove for the layout search + * + * @return void + */ + public function removeIncludePaths($paths) + { + if (!empty($paths)) { + $paths = (array)$paths; + + $this->includePaths = array_diff($this->includePaths, $paths); + } + } + + /** + * Change the debug mode + * + * @param boolean $debug Enable / Disable debug + * + * @return void + */ + public function setDebug($debug) + { + $this->options->set('debug', (boolean)$debug); + } + + /** + * Render a layout with the same include paths & options + * + * @param object $layoutId Object which properties are used inside the layout file to build displayed output + * @param mixed $displayData Data to be rendered + * + * @return string The necessary HTML to display the layout + */ + public function sublayout($layoutId, $displayData) + { + // Sublayouts are searched in a subfolder with the name of the current layout + if (!empty($this->layoutId)) { + $layoutId = $this->layoutId . '.' . $layoutId; + } + + $sublayout = new static($layoutId, $this->basePath, $this->options); + $sublayout->includePaths = $this->includePaths; + + return $sublayout->render($displayData); + } + + /** + * Method to render the layout. + * + * @param array $displayData List properties are used inside the layout file to build displayed output + * + * @return string The necessary HTML to display the layout + */ + public function render($displayData) + { + $layoutOutput = ''; + + // Check possible overrides, and build the full path to layout file + $path = $this->getPath(); + + if ($this->options->get('debug', false)) { + echo "
    " . $this->renderDebugMessages() . "
    "; + } + + // If there exists such a layout file, include it and collect its output + if (!empty($path)) { + ob_start(); + include $path; + $layoutOutput = ob_get_contents(); + ob_end_clean(); + } + + return $layoutOutput; + } + + /** + * Method to finds the full real file path, checking possible overrides + * + * @return string The full path to the layout file + */ + protected function getPath() + { + JLoader::import('joomla.filesystem.path'); + + if (is_null($this->fullPath) && !empty($this->layoutId)) { + $this->addDebugMessage('Layout: ' . $this->layoutId); + + // Refresh paths + $this->refreshIncludePaths(); + + $this->addDebugMessage('Include Paths: ' . print_r($this->includePaths, true)); + + $suffixes = $this->options->get('suffixes', array()); + + // Search for suffixed versions. Example: tags.j31.php + if (!empty($suffixes)) { + $this->addDebugMessage('Suffixes: ' . print_r($suffixes, true)); + + foreach ($suffixes as $suffix) { + $rawPath = str_replace('.', '/', $this->layoutId) . '.' . $suffix . '.php'; + $this->addDebugMessage('Searching layout for: ' . $rawPath); + + if ($this->fullPath = JPath::find($this->includePaths, $rawPath)) { + $this->addDebugMessage('Found layout: ' . $this->fullPath); + + return $this->fullPath; + } + } + } + + // Standard version + $rawPath = str_replace('.', '/', $this->layoutId) . '.php'; + $this->addDebugMessage('Searching layout for: ' . $rawPath); + + $this->fullPath = JPath::find($this->includePaths, $rawPath); + + if ($this->fullPath) { + $this->addDebugMessage('Found layout: ' . $this->fullPath); + } + } + + return $this->fullPath; + } } diff --git a/libraries/redshop/layout/helper.php b/libraries/redshop/layout/helper.php index 26109ff9128..3105b784bc3 100644 --- a/libraries/redshop/layout/helper.php +++ b/libraries/redshop/layout/helper.php @@ -9,7 +9,6 @@ defined('JPATH_BASE') or die; -use Joomla\Registry\Registry; use Redshop\Twig; JLoader::import('redshop.library'); @@ -24,141 +23,139 @@ */ class RedshopLayoutHelper { - /** - * A default base path that will be used if none is provided when calling the render method. - * Note that JLayoutFile itself will defaults to JPATH_ROOT . '/layouts' if no basePath is supplied at all - * - * @var string - */ - public static $defaultBasePath = ''; - - /** - * @var array - */ - public static $layoutOption = array( - 'component' => 'com_redshop', - 'layoutType' => 'Twig', - 'layoutOf' => 'library' - ); - - /** - * Method to render the layout. - * - * @param string $layoutFile Dot separated path to the layout file, relative to base path - * @param array $displayData Object which properties are used inside the layout file to build displayed output - * @param string $basePath Base path to use when loading layout files - * @param mixed $options Optional custom options to load. JRegistry or array format - * - * @return string - */ - public static function render($layoutFile, - $displayData = null, - $basePath = '', - $options = array('component' => 'com_redshop')) - { - $basePath = empty($basePath) ? self::$defaultBasePath : $basePath; - - // Make sure we send null to JLayoutFile if no path set - $basePath = empty($basePath) ? null : $basePath; - $renderedLayout = ''; - - if ($displayData === null) - { - $displayData = array(); - } - - // Check for render Twig or PHP normally - if (!empty($options['layoutType']) && $options['layoutType'] === 'Twig') - { - // Shorter code for Scrutinizer check - $renderedLayout = self::renderTwig($layoutFile, $displayData, $basePath, $options); - } - else - { - $layout = new RedshopLayoutFile($layoutFile, $basePath, $options); - $renderedLayout = $layout->render($displayData); - } - - return $renderedLayout; - } - - /** - * Method to render the layout of Twig - * - * @param string $layoutFile Dot separated path to the layout file, relative to base path - * @param array $displayData Object which properties are used inside the layout file to build displayed output - * @param string $basePath Base path to use when loading layout files - * @param mixed $options Optional custom options to load. JRegistry or array format - * - * @return string - */ - public static function renderTwig($layoutFile, - $displayData = array(), - $basePath = '', - $options = array('component' => 'com_redshop')) - { - if (empty($options['layoutOf']) ) - { - return ''; - } - - $layoutOf = Joomla\String\StringHelper::strtolower($options['layoutOf']); - $layoutOf = Joomla\String\StringHelper::trim((string) $layoutOf); - - if ($layoutOf === '') - { - return ''; - } - - $prefix = 'redshop'; - - if (!empty($options['prefix'])) - { - $prefix = $options['prefix']; - } - - // Ensure not include strange thing - $layoutFile = str_replace('_:', '', $layoutFile); - - $renderPath = str_replace('.', '/', $basePath . $layoutFile); - $renderPath = '@' . /** @scrutinizer ignore-type */ $layoutOf . '/' . $prefix . '/' . $renderPath . '.html.twig'; - - return html_entity_decode(Twig::render($renderPath, $displayData)); - } - - /** - * Method to render the redshop tag layout. - * - * @param string $tagName Name tag - * @param string $template Template with current tag - * @param string $tagSection Section tag - * @param array $displayData Object which properties are used inside the layout file to build displayed output - * @param string $basePath Base path to use when loading layout files - * @param mixed $options Optional custom options to load. JRegistry or array format - * - * @return void - */ - public static function renderTag($tagName, &$template, $tagSection = '', $displayData = null, $basePath = '', $options = null) - { - if (strpos($template, $tagName) === false) - { - return; - } - - $filePath = array('tags'); - - if ($tagSection) - { - $filePath[] = $tagSection; - } - else - { - $filePath[] = 'common'; - } - - $filePath[] = str_replace(array('{', '}', ':', ' '), array('', '', '_', '_'), $tagName); - - $return = self::render(implode('.', $filePath), $displayData, $basePath, $options); - $template = str_replace($tagName, $return, $template); - } + /** + * A default base path that will be used if none is provided when calling the render method. + * Note that JLayoutFile itself will defaults to JPATH_ROOT . '/layouts' if no basePath is supplied at all + * + * @var string + */ + public static $defaultBasePath = ''; + + /** + * @var array + */ + public static $layoutOption = array( + 'component' => 'com_redshop', + 'layoutType' => 'Twig', + 'layoutOf' => 'library' + ); + + /** + * Method to render the redshop tag layout. + * + * @param string $tagName Name tag + * @param string $template Template with current tag + * @param string $tagSection Section tag + * @param array $displayData Object which properties are used inside the layout file to build displayed output + * @param string $basePath Base path to use when loading layout files + * @param mixed $options Optional custom options to load. JRegistry or array format + * + * @return void + */ + public static function renderTag( + $tagName, + &$template, + $tagSection = '', + $displayData = null, + $basePath = '', + $options = null + ) { + if (strpos($template, $tagName) === false) { + return; + } + + $filePath = array('tags'); + + if ($tagSection) { + $filePath[] = $tagSection; + } else { + $filePath[] = 'common'; + } + + $filePath[] = str_replace(array('{', '}', ':', ' '), array('', '', '_', '_'), $tagName); + + $return = self::render(implode('.', $filePath), $displayData, $basePath, $options); + $template = str_replace($tagName, $return, $template); + } + + /** + * Method to render the layout. + * + * @param string $layoutFile Dot separated path to the layout file, relative to base path + * @param array $displayData Object which properties are used inside the layout file to build displayed output + * @param string $basePath Base path to use when loading layout files + * @param mixed $options Optional custom options to load. JRegistry or array format + * + * @return string + */ + public static function render( + $layoutFile, + $displayData = null, + $basePath = '', + $options = array('component' => 'com_redshop') + ) { + $basePath = empty($basePath) ? self::$defaultBasePath : $basePath; + + // Make sure we send null to JLayoutFile if no path set + $basePath = empty($basePath) ? null : $basePath; + $renderedLayout = ''; + + if ($displayData === null) { + $displayData = array(); + } + + // Check for render Twig or PHP normally + if (!empty($options['layoutType']) && $options['layoutType'] === 'Twig') { + // Shorter code for Scrutinizer check + $renderedLayout = self::renderTwig($layoutFile, $displayData, $basePath, $options); + } else { + $layout = new RedshopLayoutFile($layoutFile, $basePath, $options); + $renderedLayout = $layout->render($displayData); + } + + return $renderedLayout; + } + + /** + * Method to render the layout of Twig + * + * @param string $layoutFile Dot separated path to the layout file, relative to base path + * @param array $displayData Object which properties are used inside the layout file to build displayed output + * @param string $basePath Base path to use when loading layout files + * @param mixed $options Optional custom options to load. JRegistry or array format + * + * @return string + */ + public static function renderTwig( + $layoutFile, + $displayData = array(), + $basePath = '', + $options = array('component' => 'com_redshop') + ) { + if (empty($options['layoutOf'])) { + return ''; + } + + $layoutOf = Joomla\String\StringHelper::strtolower($options['layoutOf']); + $layoutOf = Joomla\String\StringHelper::trim((string)$layoutOf); + + if ($layoutOf === '') { + return ''; + } + + $prefix = 'redshop'; + + if (!empty($options['prefix'])) { + $prefix = $options['prefix']; + } + + // Ensure not include strange thing + $layoutFile = str_replace('_:', '', $layoutFile); + + $renderPath = str_replace('.', '/', $basePath . $layoutFile); + $renderPath = '@' . /** @scrutinizer ignore-type */ + $layoutOf . '/' . $prefix . '/' . $renderPath . '.html.twig'; + + return html_entity_decode(Twig::render($renderPath, $displayData)); + } } diff --git a/libraries/redshop/layout/layout.php b/libraries/redshop/layout/layout.php index 1bd390535d5..94d24a23f8e 100644 --- a/libraries/redshop/layout/layout.php +++ b/libraries/redshop/layout/layout.php @@ -19,21 +19,21 @@ */ interface RedshopLayout { - /** - * Method to escape output. - * - * @param string $output The output to escape. - * - * @return string The escaped output. - */ - public function escape($output); + /** + * Method to escape output. + * + * @param string $output The output to escape. + * + * @return string The escaped output. + */ + public function escape($output); - /** - * Method to render the layout. - * - * @param object $displayData Object which properties are used inside the layout file to build displayed output - * - * @return string The rendered layout. - */ - public function render($displayData); + /** + * Method to render the layout. + * + * @param object $displayData Object which properties are used inside the layout file to build displayed output + * + * @return string The rendered layout. + */ + public function render($displayData); } diff --git a/libraries/redshop/layouts/examples.html.twig b/libraries/redshop/layouts/examples.html.twig index 2c0f4bedded..9ca86ccd6d6 100644 --- a/libraries/redshop/layouts/examples.html.twig +++ b/libraries/redshop/layouts/examples.html.twig @@ -18,76 +18,76 @@

    jlang.getName()

    -{{ dump(jlang.getName()) }} +{{ dump(jlang.getName()) }}

    jlang('es-ES').getName():

    -{{ dump(jlang('es-ES').getName()) }} +{{ dump(jlang('es-ES').getName()) }}

    jlayout('joomla.html.treeprefix', constant('JPATH_SITE') ~ '/media', {'debug' : true}):

    - {% set options = {'debug' : true} %} - {% set layout = jlayout('joomla.html.treeprefix', constant('JPATH_SITE') ~ '/media', options) %} + {% set options = {'debug' : true} %} + {% set layout = jlayout('joomla.html.treeprefix', constant('JPATH_SITE') ~ '/media', options) %} -

    LayoutId:

    - {{ dump(layout.getLayoutId()) }} -
    +

    LayoutId:

    + {{ dump(layout.getLayoutId()) }} +
    -

    IncludePaths:

    - {{ dump(layout.getIncludePaths()) }} -
    +

    IncludePaths:

    + {{ dump(layout.getIncludePaths()) }} +
    -

    Render:

    - {{ dump(layout.render({'level' : 10})) }} +

    Render:

    + {{ dump(layout.render({'level' : 10})) }}

    jposition('position-8')

    -{{ dump(jposition('position-8')) }} +{{ dump(jposition('position-8')) }}

    jprofiler('joomla-twig')

    - {% set profiler = jprofiler('joomla-twig') %} -

    mark:

    - {{ dump(profiler.mark('before something')) }} -

    mark 2:

    - {{ dump(profiler.mark('after something')) }} + {% set profiler = jprofiler('joomla-twig') %} +

    mark:

    + {{ dump(profiler.mark('before something')) }} +

    mark 2:

    + {{ dump(profiler.mark('after something')) }}

    jroute('index.php?option=com_content&view=category&id=27')

    -{{ dump(jroute('index.php?option=com_content&view=category&id=27')) }} +{{ dump(jroute('index.php?option=com_content&view=category&id=27')) }}

    jsession.getToken()

    -{{ dump(jsession.getToken()) }} +{{ dump(jsession.getToken()) }}

    jtext('JENABLED')

    -{{ dump(jtext('JENABLED')) }} +{{ dump(jtext('JENABLED')) }}

    jtext_sprintf('JNEXT_TITLE', 'My article title')

    -{{ dump(jtext_sprintf('JNEXT_TITLE', 'My article title')) }} +{{ dump(jtext_sprintf('JNEXT_TITLE', 'My article title')) }}

    juri

    -{{ dump(juri) }} +{{ dump(juri) }}

    juri('index.php?option=com_content&view=category')

    -{{ dump(juri('index.php?option=com_content&view=category')) }} +{{ dump(juri('index.php?option=com_content&view=category')) }}

    juser.get('guest')

    -{{ dump(juser.get('guest')) }} +{{ dump(juser.get('guest')) }}

    juser(668).email

    -{{ dump(juser(668).email) }} +{{ dump(juser(668).email) }}

    's:6:"foobar";'|unserialize

    -{{ dump('s:6:"foobar";'|unserialize) }} +{{ dump('s:6:"foobar";'|unserialize) }}
    diff --git a/libraries/redshop/layouts/extrafields/display/article.php b/libraries/redshop/layouts/extrafields/display/article.php index 4b0da0daaf2..b14b466f38c 100644 --- a/libraries/redshop/layouts/extrafields/display/article.php +++ b/libraries/redshop/layouts/extrafields/display/article.php @@ -12,19 +12,20 @@ /** * $displayData extract * - * @var array $displayData Layout data. - * @var array $data Extra field data + * @var array $displayData Layout data. + * @var array $data Extra field data */ extract($displayData); ?>
    - - id .':'. $article->alias . - '&catid=' . $article->catid - )?> -
    title ?>
    - + + id . ':' . $article->alias . + '&catid=' . $article->catid + ) ?> +
    title ?> +
    +
    \ No newline at end of file diff --git a/libraries/redshop/layouts/extrafields/display/country.php b/libraries/redshop/layouts/extrafields/display/country.php index 9ec3d372a41..c744d21c030 100644 --- a/libraries/redshop/layouts/extrafields/display/country.php +++ b/libraries/redshop/layouts/extrafields/display/country.php @@ -12,9 +12,9 @@ /** * $displayData extract * - * @var array $displayData Layout data. - * @var integer $data Extra field data + * @var array $displayData Layout data. + * @var integer $data Extra field data */ extract($displayData); -echo RedshopEntityCountry::getInstance((int) $data)->get('country_name'); +echo RedshopEntityCountry::getInstance((int)$data)->get('country_name'); diff --git a/libraries/redshop/layouts/extrafields/display/document.php b/libraries/redshop/layouts/extrafields/display/document.php index e20dfdd707d..ff4708b9abf 100644 --- a/libraries/redshop/layouts/extrafields/display/document.php +++ b/libraries/redshop/layouts/extrafields/display/document.php @@ -12,11 +12,11 @@ /** * $displayData extract * - * @var array $displayData Layout data - * @var object $data Data object - * @var object $field Field object - * @var string $link Document link - * @var string $title Document title + * @var array $displayData Layout data + * @var object $data Data object + * @var object $field Field object + * @var string $link Document link + * @var string $title Document title */ extract($displayData); ?> diff --git a/libraries/redshop/layouts/extrafields/display/image.php b/libraries/redshop/layouts/extrafields/display/image.php index 6756ce803fe..1aa1052c151 100644 --- a/libraries/redshop/layouts/extrafields/display/image.php +++ b/libraries/redshop/layouts/extrafields/display/image.php @@ -22,8 +22,9 @@ $imgLink = !empty($link[$value->value_id]) ? 'href="' . $link[$value->value_id] . '"' : ''; ?> > - <?php echo $value->field_value; ?> - + <?php echo $value->field_value; ?> +
    title; ?>
    diff --git a/libraries/redshop/layouts/extrafields/display/textarea.php b/libraries/redshop/layouts/extrafields/display/textarea.php index 7272d8e7686..f57ce95d6e1 100644 --- a/libraries/redshop/layouts/extrafields/display/textarea.php +++ b/libraries/redshop/layouts/extrafields/display/textarea.php @@ -12,8 +12,8 @@ /** * $displayData extract * - * @var array $displayData Layout data. - * @var string $data Extra field data + * @var array $displayData Layout data. + * @var string $data Extra field data */ extract($displayData); diff --git a/libraries/redshop/layouts/extrafields/field/checkbox.php b/libraries/redshop/layouts/extrafields/field/checkbox.php index e6411f483d5..3d6bed12e5e 100644 --- a/libraries/redshop/layouts/extrafields/field/checkbox.php +++ b/libraries/redshop/layouts/extrafields/field/checkbox.php @@ -24,25 +24,25 @@ ?> - + - $field) : ?> - field_value), $checkData)) || - in_array($field->field_value, $checkData)) ? ' checked="checked" ' : ''; ?> - - + $field) : ?> + field_value), $checkData)) || + in_array($field->field_value, $checkData)) ? ' checked="checked" ' : ''; ?> + + \ No newline at end of file diff --git a/libraries/redshop/layouts/extrafields/field/country.php b/libraries/redshop/layouts/extrafields/field/country.php index de1f59105cc..2c9b5493c15 100644 --- a/libraries/redshop/layouts/extrafields/field/country.php +++ b/libraries/redshop/layouts/extrafields/field/country.php @@ -12,32 +12,36 @@ /** * $displayData extract * - * @param object $rowData Extra field data + * @param object $rowData Extra field data * @param string $extraFieldLabel Extra field label - * @param string $required Extra field required - * @param string $requiredLabel Extra field required label - * @param string $errorMsg Extra field error message - * @param string $fieldCheck Extra field check - * @param string $checkData Extra field check data + * @param string $required Extra field required + * @param string $requiredLabel Extra field required label + * @param string $errorMsg Extra field error message + * @param string $fieldCheck Extra field check + * @param string $checkData Extra field check data */ extract($displayData); ?> - + - + diff --git a/libraries/redshop/layouts/extrafields/field/date_picker.php b/libraries/redshop/layouts/extrafields/field/date_picker.php index bbc68ff399d..383ae3c86b8 100644 --- a/libraries/redshop/layouts/extrafields/field/date_picker.php +++ b/libraries/redshop/layouts/extrafields/field/date_picker.php @@ -24,16 +24,16 @@ ?> - + - name, - $rowData->name, - null, - array('class' => 'form-control', 'size' => $rowData->size > 0 ? $rowData->size : 20, 'maxlength' => '15') - ); - ?> + name, + $rowData->name, + null, + array('class' => 'form-control', 'size' => $rowData->size > 0 ? $rowData->size : 20, 'maxlength' => '15') + ); + ?> diff --git a/libraries/redshop/layouts/extrafields/field/document.php b/libraries/redshop/layouts/extrafields/field/document.php index d32f6bec5ab..f5eeea6014c 100644 --- a/libraries/redshop/layouts/extrafields/field/document.php +++ b/libraries/redshop/layouts/extrafields/field/document.php @@ -30,13 +30,15 @@ $(document).ready(function () { $("a#add_name ?>").on('click', function (e) { e.preventDefault(); - var extra_field_name = 'name ?>'; - var html_acceptor = $('#html_' + extra_field_name); - var total_elm = html_acceptor.children('div').length + 1; + var extra_field_name = 'name ?>'; + var html_acceptor = $('#html_' + extra_field_name); + var total_elm = html_acceptor.children('div').length + 1; var extra_field_doc_html = '
    '; extra_field_doc_html += ''; extra_field_doc_html += ''; - extra_field_doc_html += ''; + extra_field_doc_html += ''; extra_field_doc_html += '
    '; html_acceptor.append(extra_field_doc_html); @@ -53,49 +55,50 @@ })(jQuery); - +   -
    +
    - - - $value) : ?> - + + + $value) : ?> +
    - - /> + + + />   - - - - + + + + - - - - + + + +
    - + + 'div_name . $idx; ?>', '', + 'data_id . ':document'; ?>');">     + id="name; ?>" class="class; ?>" + value=""/>
    - +
      + id="name; ?>" class="class; ?>" + value=""/>
    - - - - + + + +
    - - + +
    diff --git a/libraries/redshop/layouts/extrafields/field/editor.php b/libraries/redshop/layouts/extrafields/field/editor.php index 007be7ec9a4..05eca2edcdf 100644 --- a/libraries/redshop/layouts/extrafields/field/editor.php +++ b/libraries/redshop/layouts/extrafields/field/editor.php @@ -23,8 +23,8 @@ ?> - + - display($rowData->name, $textValue, '200', '50', '100', '20', false); ?> + display($rowData->name, $textValue, '200', '50', '100', '20', false); ?> diff --git a/libraries/redshop/layouts/extrafields/field/image.php b/libraries/redshop/layouts/extrafields/field/image.php index 1794d81597a..d2b0ea32898 100644 --- a/libraries/redshop/layouts/extrafields/field/image.php +++ b/libraries/redshop/layouts/extrafields/field/image.php @@ -12,51 +12,51 @@ /** * $displayData extract * - * @var object $rowData Extra field data - * @var string $extraFieldLabel Extra field label - * @var string $required Extra field required - * @var string $requiredLabel Extra field required label - * @var string $errorMsg Extra field error message - * @var array $fieldCheck Extra field check - * @var array $checkData Extra field check data - * @var string $value Extra field value - * @var string $sectionId Extra field section Id + * @var object $rowData Extra field data + * @var string $extraFieldLabel Extra field label + * @var string $required Extra field required + * @var string $requiredLabel Extra field required label + * @var string $errorMsg Extra field error message + * @var array $fieldCheck Extra field check + * @var array $checkData Extra field check data + * @var string $value Extra field value + * @var string $sectionId Extra field section Id */ extract($displayData); ?> - + - - - $field) : ?> - value_id, $checkData)): ?> - - - - - - - - -
    -
    - <?php echo $field->field_value; ?> - /> -
    -
    + + + $field) : ?> + value_id, $checkData)): ?> + + + + + + + + +
    +
    + <?php echo $field->field_value; ?> + /> +
    +
    diff --git a/libraries/redshop/layouts/extrafields/field/image_link.php b/libraries/redshop/layouts/extrafields/field/image_link.php index 35985968828..682f9362672 100644 --- a/libraries/redshop/layouts/extrafields/field/image_link.php +++ b/libraries/redshop/layouts/extrafields/field/image_link.php @@ -28,73 +28,73 @@ ?> - + - - $field) : ?> - - value_id, $checkData)): ?> - - - value_id]; ?> - value_id]; ?> - - - - - - - - - - - -
    -
    - <?php echo $field->field_value; ?> - > -
    -
    -
    - - - - - - - - - -
    - - - -
    - - - -
    -
    -
    + + $field) : ?> + + value_id, $checkData)): ?> + + + value_id]; ?> + value_id]; ?> + + + + + + + + + + + +
    +
    + <?php echo $field->field_value; ?> + > +
    +
    +
    + + + + + + + + + +
    + + + +
    + + + +
    +
    +
    diff --git a/libraries/redshop/layouts/extrafields/field/multiple.php b/libraries/redshop/layouts/extrafields/field/multiple.php index 67ce14fa8fc..c2b97975fce 100644 --- a/libraries/redshop/layouts/extrafields/field/multiple.php +++ b/libraries/redshop/layouts/extrafields/field/multiple.php @@ -12,46 +12,58 @@ /** * $displayData extract * - * @param object $rowData Extra field data + * @param object $rowData Extra field data * @param string $extraFieldLabel Extra field label - * @param string $required Extra field required - * @param string $requiredLabel Extra field required label - * @param string $errorMsg Extra field error message - * @param string $fieldCheck Extra field check - * @param string $checkData Extra field check data + * @param string $required Extra field required + * @param string $requiredLabel Extra field required label + * @param string $errorMsg Extra field error message + * @param string $fieldCheck Extra field check + * @param string $checkData Extra field check data */ extract($displayData); ?> - + - + diff --git a/libraries/redshop/layouts/extrafields/field/radio.php b/libraries/redshop/layouts/extrafields/field/radio.php index 6123f92b59b..58786eb519e 100644 --- a/libraries/redshop/layouts/extrafields/field/radio.php +++ b/libraries/redshop/layouts/extrafields/field/radio.php @@ -24,25 +24,25 @@ ?> - + - $field) : ?> - field_value), $checkData)) || - in_array($field->field_value, $checkData)) ? ' checked="checked" ' : ''; ?> - - + $field) : ?> + field_value), $checkData)) || + in_array($field->field_value, $checkData)) ? ' checked="checked" ' : ''; ?> + + diff --git a/libraries/redshop/layouts/extrafields/field/select.php b/libraries/redshop/layouts/extrafields/field/select.php index a3a5d2d1446..8c1526ce203 100644 --- a/libraries/redshop/layouts/extrafields/field/select.php +++ b/libraries/redshop/layouts/extrafields/field/select.php @@ -24,22 +24,23 @@ ?> - + - + diff --git a/libraries/redshop/layouts/extrafields/field/selected_condition.php b/libraries/redshop/layouts/extrafields/field/selected_condition.php index 1613c6607ad..a652304ab9f 100644 --- a/libraries/redshop/layouts/extrafields/field/selected_condition.php +++ b/libraries/redshop/layouts/extrafields/field/selected_condition.php @@ -24,88 +24,88 @@ extract($displayData); ?> - + - - - - - - - - -
    - - -      - - -
      -
    - - -
    - - - - - - - - - 0) : ?> - $slitDate) : ?> - - - - - - - - - - - - - - - -
    - -  
    -
    - " - > -
    -
    - -
    -
    - " - > -
    -
    -
    -
    - -
    + + + + + + + + +
    + + +      + + +
      +
    + + +
    + + + + + + + + + 0) : ?> + $slitDate) : ?> + + + + + + + + + + + + + + + +
    + +  
    +
    + " + > +
    +
    + +
    +
    + " + > +
    +
    +
    +
    + +
    diff --git a/libraries/redshop/layouts/extrafields/field/text.php b/libraries/redshop/layouts/extrafields/field/text.php index 88720f2d262..240d67daaa9 100644 --- a/libraries/redshop/layouts/extrafields/field/text.php +++ b/libraries/redshop/layouts/extrafields/field/text.php @@ -12,31 +12,31 @@ /** * $displayData extract * - * @var array $displayData Layout data - * @var object $rowData Extra field data - * @var string $extraFieldLabel Extra field label - * @var string $required Extra field required - * @var string $requiredLabel Extra field required label - * @var string $errorMsg Extra field error message - * @var string $textValue Extra field value + * @var array $displayData Layout data + * @var object $rowData Extra field data + * @var string $extraFieldLabel Extra field label + * @var string $required Extra field required + * @var string $requiredLabel Extra field required label + * @var string $errorMsg Extra field error message + * @var string $textValue Extra field value */ extract($displayData); ?> - + - - - - /> + + + + /> diff --git a/libraries/redshop/layouts/extrafields/field/textarea.php b/libraries/redshop/layouts/extrafields/field/textarea.php index 6348b287026..b3e7259d82e 100644 --- a/libraries/redshop/layouts/extrafields/field/textarea.php +++ b/libraries/redshop/layouts/extrafields/field/textarea.php @@ -23,16 +23,16 @@ ?> - + diff --git a/libraries/redshop/layouts/extrafields/userfield/checkbox.php b/libraries/redshop/layouts/extrafields/userfield/checkbox.php index 235df47e6c2..f789bfbddb4 100644 --- a/libraries/redshop/layouts/extrafields/userfield/checkbox.php +++ b/libraries/redshop/layouts/extrafields/userfield/checkbox.php @@ -12,30 +12,33 @@ /** * $displayData extract * - * @var array $displayData Layout data. - * @var object $rowData Extra field data - * @var string $required Extra field required - * @var string $uniqueId Extra field unique Id - * @var arra $fieldCheck Extra field check - * @var string $checkData Extra field check data + * @var array $displayData Layout data. + * @var object $rowData Extra field data + * @var string $required Extra field required + * @var string $uniqueId Extra field unique Id + * @var arra $fieldCheck Extra field check + * @var string $checkData Extra field check data */ extract($displayData); ?> $field) : ?> - field_value), $checkData)) ? ' checked="checked" ' : ''; ?> -
    - -
    + field_value), + $checkData + )) ? ' checked="checked" ' : ''; ?> +
    + +
    diff --git a/libraries/redshop/layouts/extrafields/userfield/date_picker.php b/libraries/redshop/layouts/extrafields/userfield/date_picker.php index 725255b925d..7a12713f043 100644 --- a/libraries/redshop/layouts/extrafields/userfield/date_picker.php +++ b/libraries/redshop/layouts/extrafields/userfield/date_picker.php @@ -12,30 +12,30 @@ /** * $displayData extract * - * @var array $displayData Layout data. - * @var object $rowData Extra field data - * @var string $required Extra field required - * @var string $uniqueId Extra field unique Id - * @var array $fieldCheck Extra field check + * @var array $displayData Layout data. + * @var object $rowData Extra field data + * @var string $required Extra field required + * @var string $uniqueId Extra field unique Id + * @var array $fieldCheck Extra field check */ extract($displayData); ?>
    - name . '_' . $field->value_id, - '%d-%m-%Y', - array( - 'class' => 'inputbox', - 'size' => $rowData->size, - 'maxlength' => $rowData->maxlength, - 'userfieldlbl' => $rowData->title, - 'required' => $required, - 'errormsg' => '' - ) - ); - ?> + name . '_' . $field->value_id, + '%d-%m-%Y', + array( + 'class' => 'inputbox', + 'size' => $rowData->size, + 'maxlength' => $rowData->maxlength, + 'userfieldlbl' => $rowData->title, + 'required' => $required, + 'errormsg' => '' + ) + ); + ?>
    diff --git a/libraries/redshop/layouts/extrafields/userfield/document.php b/libraries/redshop/layouts/extrafields/userfield/document.php index dd0a05db942..599770ef1a7 100644 --- a/libraries/redshop/layouts/extrafields/userfield/document.php +++ b/libraries/redshop/layouts/extrafields/userfield/document.php @@ -9,104 +9,110 @@ defined('_JEXEC') or die; JHtml::_('redshopjquery.framework'); -/** @scrutinizer ignore-deprecated */ JHtml::script('com_redshop/ajaxupload.min.js', false, true); +/** @scrutinizer ignore-deprecated */ +JHtml::script('com_redshop/ajaxupload.min.js', false, true); /** * $displayData extract * - * @var array $displayData Layout data. - * @var object $rowData Extra field data - * @var string $required Extra field required - * @var string $uniqueId Extra field unique Id - * @var array $fieldCheck Extra field check + * @var array $displayData Layout data. + * @var object $rowData Extra field data + * @var string $required Extra field required + * @var string $uniqueId Extra field unique Id + * @var array $fieldCheck Extra field check */ extract($displayData); $http_referer = JFactory::getApplication()->input->server->getString('HTTP_REFERER', ''); ?>
    - - /> -

    - -

      -

      + + /> +

      + +

        +

        + type="hidden" + name="extrafieldname[]" + id="name . '_' . $uniqueId; ?>" + userfieldlbl="title; ?>" + /> - + && (strpos($http_referer, 'view=order_detail') !== false + || strpos($http_referer, 'view=addorder_detail') !== false + || strpos($http_referer, 'view=quotation') !== false + || strpos($http_referer, 'view=quotation_detail') !== false + || strpos($http_referer, 'view=addquotation_detail') !== false) +): ?> + - + diff --git a/libraries/redshop/layouts/extrafields/userfield/image.php b/libraries/redshop/layouts/extrafields/userfield/image.php index e7441e82b45..02076389ddc 100644 --- a/libraries/redshop/layouts/extrafields/userfield/image.php +++ b/libraries/redshop/layouts/extrafields/userfield/image.php @@ -12,38 +12,38 @@ /** * $displayData extract * - * @var array $displayData Layout data. - * @var object $rowData Extra field data - * @var string $required Extra field required - * @var string $uniqueId Extra field unique Id - * @var array $fieldCheck Extra field check - * @var string $checkData Extra field check data + * @var array $displayData Layout data. + * @var object $rowData Extra field data + * @var string $required Extra field required + * @var string $uniqueId Extra field unique Id + * @var array $fieldCheck Extra field check + * @var string $checkData Extra field check data */ extract($displayData); ?> - - $field) : ?> - - - - - > + + $field) : ?> + + + + + >
        -
        - <?php echo $field->field_value; ?> - > -
        -
        +
        + <?php echo $field->field_value; ?> + > +
        +
        diff --git a/libraries/redshop/layouts/extrafields/userfield/multiple.php b/libraries/redshop/layouts/extrafields/userfield/multiple.php index 339a932f4db..b3ec77a4a17 100644 --- a/libraries/redshop/layouts/extrafields/userfield/multiple.php +++ b/libraries/redshop/layouts/extrafields/userfield/multiple.php @@ -12,29 +12,33 @@ /** * $displayData extract * - * @var array $displayData Layout data. - * @var object $rowData Extra field data - * @var string $required Extra field required - * @var string $uniqueId Extra field unique Id - * @var array $fieldCheck Extra field check - * @var string $checkData Extra field check data + * @var array $displayData Layout data. + * @var object $rowData Extra field data + * @var string $required Extra field required + * @var string $uniqueId Extra field unique Id + * @var array $fieldCheck Extra field check + * @var string $checkData Extra field check data */ extract($displayData); ?>
        - +
        diff --git a/libraries/redshop/layouts/extrafields/userfield/radio.php b/libraries/redshop/layouts/extrafields/userfield/radio.php index b89eabdc409..8d587c9af08 100644 --- a/libraries/redshop/layouts/extrafields/userfield/radio.php +++ b/libraries/redshop/layouts/extrafields/userfield/radio.php @@ -12,30 +12,33 @@ /** * $displayData extract * - * @var array $displayData Layout data. - * @var object $rowData Extra field data - * @var string $required Extra field required - * @var string $uniqueId Extra field unique Id - * @var array $fieldCheck Extra field check - * @var string $checkData Extra field check data + * @var array $displayData Layout data. + * @var object $rowData Extra field data + * @var string $required Extra field required + * @var string $uniqueId Extra field unique Id + * @var array $fieldCheck Extra field check + * @var string $checkData Extra field check data */ extract($displayData); ?> $field) : ?> - field_value), $checkData)) ? ' checked="checked" ' : ''; ?> -
        - -
        + field_value), + $checkData + )) ? ' checked="checked" ' : ''; ?> +
        + +
        diff --git a/libraries/redshop/layouts/extrafields/userfield/select.php b/libraries/redshop/layouts/extrafields/userfield/select.php index c2812a25fc0..391327c5bb6 100644 --- a/libraries/redshop/layouts/extrafields/userfield/select.php +++ b/libraries/redshop/layouts/extrafields/userfield/select.php @@ -12,30 +12,34 @@ /** * $displayData extract * - * @var array $displayData Layout data. - * @var object $rowData Extra field data - * @var string $required Extra field required - * @var string $uniqueId Extra field unique Id - * @var array $fieldCheck Extra field check - * @var string $checkData Extra field check data + * @var array $displayData Layout data. + * @var object $rowData Extra field data + * @var string $required Extra field required + * @var string $uniqueId Extra field unique Id + * @var array $fieldCheck Extra field check + * @var string $checkData Extra field check data */ extract($displayData); ?>
        - +
        diff --git a/libraries/redshop/layouts/extrafields/userfield/text.php b/libraries/redshop/layouts/extrafields/userfield/text.php index 46f4460d6f1..855ac46d7da 100644 --- a/libraries/redshop/layouts/extrafields/userfield/text.php +++ b/libraries/redshop/layouts/extrafields/userfield/text.php @@ -12,25 +12,25 @@ /** * $displayData extract * - * @var array $displayData Layout data. - * @var object $rowData Extra field data - * @var string $uniqueId Extra field unique Id - * @var string $required Extra field required + * @var array $displayData Layout data. + * @var object $rowData Extra field data + * @var string $uniqueId Extra field unique Id + * @var string $required Extra field required */ extract($displayData); ?>
        - - > + + >
        diff --git a/libraries/redshop/layouts/extrafields/userfield/textarea.php b/libraries/redshop/layouts/extrafields/userfield/textarea.php index f8e9f309c24..01dde423b18 100644 --- a/libraries/redshop/layouts/extrafields/userfield/textarea.php +++ b/libraries/redshop/layouts/extrafields/userfield/textarea.php @@ -12,24 +12,24 @@ /** * $displayData extract * - * @var array $displayData Layout data. - * @var object $rowData Extra field data - * @var string $uniqueId Extra field unique Id - * @var string $required Extra field required + * @var array $displayData Layout data. + * @var object $rowData Extra field data + * @var string $uniqueId Extra field unique Id + * @var string $required Extra field required */ extract($displayData); ?>
        diff --git a/libraries/redshop/layouts/field/date_range.php b/libraries/redshop/layouts/field/date_range.php index 8b9f232e838..95a8ef014f6 100644 --- a/libraries/redshop/layouts/field/date_range.php +++ b/libraries/redshop/layouts/field/date_range.php @@ -12,133 +12,157 @@ /** * Layout variables * ----------------- - * @var string $displayData Date format - * @var string $format Date format - * @var int $firstDay First day config. - * @var boolean $autoApply Auto-apply when select date. - * @var JFormFieldRdaterange $field Field object. - * @var string $value Field value. - * @var string $class Field class. - * @var boolean $showButton Show calendar button or not. - * @var string $onChange On change js function. - * @var string $phpFormat Date format in PHP. + * @var string $displayData Date format + * @var string $format Date format + * @var int $firstDay First day config. + * @var boolean $autoApply Auto-apply when select date. + * @var JFormFieldRdaterange $field Field object. + * @var string $value Field value. + * @var string $class Field class. + * @var boolean $showButton Show calendar button or not. + * @var string $onChange On change js function. + * @var string $phpFormat Date format in PHP. */ extract($displayData); -if (!empty($value)) -{ - $dateRange = explode('-', $value); - $startDate = (!empty($dateRange[0])) ? date($phpFormat, $dateRange[0]) : ''; - $endDate = (!empty($dateRange[1])) ? date($phpFormat, $dateRange[1]) : ''; +if (!empty($value)) { + $dateRange = explode('-', $value); + $startDate = (!empty($dateRange[0])) ? date($phpFormat, $dateRange[0]) : ''; + $endDate = (!empty($dateRange[1])) ? date($phpFormat, $dateRange[1]) : ''; } ?>
        -
        - - - - - -
        +
        + + + + + +
        diff --git a/libraries/redshop/layouts/field/radio.php b/libraries/redshop/layouts/field/radio.php index 9be7d7a5c74..60d58ddfd42 100644 --- a/libraries/redshop/layouts/field/radio.php +++ b/libraries/redshop/layouts/field/radio.php @@ -9,59 +9,60 @@ defined('_JEXEC') or die; -$data = (object) $displayData; +$data = (object)$displayData; $attributes = array(); $attributes['id'] = $data->id; -$attributes['class'] = $data->element['class'] ? (string) $data->element['class'] : null; -$attributes['size'] = $data->element['size'] ? (int) $data->element['size'] : null; +$attributes['class'] = $data->element['class'] ? (string)$data->element['class'] : null; +$attributes['size'] = $data->element['size'] ? (int)$data->element['size'] : null; $attributes['multiple'] = $data->multiple ? 'multiple' : null; $attributes['required'] = $data->required ? 'required' : null; $attributes['aria-required'] = $data->required ? 'true' : null; $attributes['autofocus'] = $data->autofocus ? ' autofocus' : null; -$attributes['onchange'] = $data->element['onchange'] ? (string) $data->element['onchange'] : null; +$attributes['onchange'] = $data->element['onchange'] ? (string)$data->element['onchange'] : null; -if ((string) $data->element['readonly'] == 'true' || (string) $data->element['disabled'] == 'true') -{ - $attributes['disabled'] = 'disabled'; +if ((string)$data->element['readonly'] == 'true' || (string)$data->element['disabled'] == 'true') { + $attributes['disabled'] = 'disabled'; } $renderedAttributes = RedshopHelperUtility::toAttributes($attributes); -$readOnly = ((string) $data->element['readonly'] == 'true'); +$readOnly = ((string)$data->element['readonly'] == 'true'); // If it's readonly the select will have no name $selectName = $readOnly ? '' : $data->name; ?>
        > - options) : ?> - options as $i => $option) : ?> - value == (string) $data->value) ? 'checked' : null; - $inputAttributes['class'] = !empty($option->class) ? $option->class : null; - $inputAttributes['class'] .= !empty($data->element['input-class']) ? (string) $data->element['input-class'] : null; - $inputAttributes['disabled'] = (!empty($option->disable) || ($readOnly && !$checked)) ? 'disabled' : null; - $inputAttributes['onclick'] = !empty($option->onclick) ? $option->onclick : null; - $inputAttributes['onchange'] = !empty($option->onchange) ? $option->onchange : null; - $inputAttributes['required'] = !empty($attributes['required']) ? 'required' : null; + options) : ?> + options as $i => $option) : ?> + value == (string)$data->value) ? 'checked' : null; + $inputAttributes['class'] = !empty($option->class) ? $option->class : null; + $inputAttributes['class'] .= !empty($data->element['input-class']) ? (string)$data->element['input-class'] : null; + $inputAttributes['disabled'] = (!empty($option->disable) || ($readOnly && !$checked)) ? 'disabled' : null; + $inputAttributes['onclick'] = !empty($option->onclick) ? $option->onclick : null; + $inputAttributes['onchange'] = !empty($option->onchange) ? $option->onchange : null; + $inputAttributes['required'] = !empty($attributes['required']) ? 'required' : null; - // Label attributes - $labelAttributes = array(); - $labelAttributes['class'] = !empty($data->element['label-class']) ? (string) $data->element['label-class'] : null; - ?> - - - + // Label attributes + $labelAttributes = array(); + $labelAttributes['class'] = !empty($data->element['label-class']) ? (string)$data->element['label-class'] : null; + ?> + + +
        diff --git a/libraries/redshop/layouts/field/rules/group.php b/libraries/redshop/layouts/field/rules/group.php index 46a79e3febd..0feafc39f5b 100644 --- a/libraries/redshop/layouts/field/rules/group.php +++ b/libraries/redshop/layouts/field/rules/group.php @@ -25,7 +25,7 @@ extract($displayData); ?> - value == 1) ? ' active' : ''; ?> + value == 1) ? ' active' : ''; ?>
        @@ -34,135 +34,162 @@ # - (text ?>) + (text ?>) - + - + - + - + - value, 'core.admin'); ?> + value, 'core.admin'); ?> - - $groupActions): ?> + + $groupActions): ?> - + -
        - +
        + - + - - name); ?> - - - value, $action->name, $assetId); - $assetRule = ($newItem === false) ? $assetRules->allow($action->name, $group->value) : null; - ?> + + name); ?> + + + value, $action->name, $assetId); + $assetRule = ($newItem === false) ? $assetRules->allow( + $action->name, + $group->value + ) : null; + ?> - - - - value, $action->name, $assetId); - $inheritedGroupParentAssetRule = !empty($parentAssetId) ? JAccess::checkGroup($group->value, $action->name, $parentAssetId) : null; - $inheritedParentGroupRule = !empty($group->parent_id) ? JAccess::checkGroup($group->parent_id, $action->name, $assetId) : null; + + + + value, + $action->name, + $assetId + ); + $inheritedGroupParentAssetRule = !empty($parentAssetId) ? JAccess::checkGroup( + $group->value, + $action->name, + $parentAssetId + ) : null; + $inheritedParentGroupRule = !empty($group->parent_id) ? JAccess::checkGroup( + $group->parent_id, + $action->name, + $assetId + ) : null; - if ($isSuperUserGroup) - { - $result['class'] = 'text-primary'; - $result['text'] = '' . JText::_('JLIB_RULES_ALLOWED_ADMIN'); - } - else - { - if ($inheritedGroupRule === null || $inheritedGroupRule === false) - { - $result['class'] = 'text-danger'; - $result['text'] = JText::_('JLIB_RULES_NOT_ALLOWED_INHERITED'); - } - else - { - $result['class'] = 'text-success'; - $result['text'] = JText::_('JLIB_RULES_ALLOWED_INHERITED'); - } + if ($isSuperUserGroup) { + $result['class'] = 'text-primary'; + $result['text'] = '' . JText::_( + 'JLIB_RULES_ALLOWED_ADMIN' + ); + } else { + if ($inheritedGroupRule === null || $inheritedGroupRule === false) { + $result['class'] = 'text-danger'; + $result['text'] = JText::_('JLIB_RULES_NOT_ALLOWED_INHERITED'); + } else { + $result['class'] = 'text-success'; + $result['text'] = JText::_('JLIB_RULES_ALLOWED_INHERITED'); + } - if ($assetRule === false) - { - $result['class'] = 'text-danger'; - $result['text'] = JText::_('JLIB_RULES_NOT_ALLOWED'); - } - elseif ($assetRule === true) - { - $result['class'] = 'text-success'; - $result['text'] = JText::_('JLIB_RULES_ALLOWED'); - } + if ($assetRule === false) { + $result['class'] = 'text-danger'; + $result['text'] = JText::_('JLIB_RULES_NOT_ALLOWED'); + } elseif ($assetRule === true) { + $result['class'] = 'text-success'; + $result['text'] = JText::_('JLIB_RULES_ALLOWED'); + } - if (empty($group->parent_id) && $isGlobalConfig === true && $assetRule === null) - { - $result['class'] = 'text-danger'; - $result['text'] = JText::_('JLIB_RULES_NOT_ALLOWED_DEFAULT'); - } - elseif ($inheritedGroupParentAssetRule === false || $inheritedParentGroupRule === false) - { - $result['class'] = 'text-muted'; - $result['text'] = '' . JText::_('JLIB_RULES_NOT_ALLOWED_LOCKED'); - } - } - ?> - + if (empty($group->parent_id) && $isGlobalConfig === true && $assetRule === null) { + $result['class'] = 'text-danger'; + $result['text'] = JText::_('JLIB_RULES_NOT_ALLOWED_DEFAULT'); + } elseif ($inheritedGroupParentAssetRule === false || $inheritedParentGroupRule === false) { + $result['class'] = 'text-muted'; + $result['text'] = '' . JText::_( + 'JLIB_RULES_NOT_ALLOWED_LOCKED' + ); + } + } + ?> + - + - + - - - + + +   - + - - + + @@ -170,45 +197,53 @@   - + - + - + - + - + - + - + - + diff --git a/libraries/redshop/layouts/field/rules/rules.php b/libraries/redshop/layouts/field/rules/rules.php index 68d05ddbfb8..1c1ab03c777 100644 --- a/libraries/redshop/layouts/field/rules/rules.php +++ b/libraries/redshop/layouts/field/rules/rules.php @@ -12,173 +12,187 @@ /** * Layout variables * ----------------- - * @var array $displayData List of available data. - * @var array $groups List of available user groups. - * @var array $actions List of available actions. - * @var JFormField $field Field object data. - * @var boolean $newItem Is that new item. - * @var JAccessRules $assetRules Access Rules - * @var integer $assetId Asset ID - * @var string $component Component + * @var array $displayData List of available data. + * @var array $groups List of available user groups. + * @var array $actions List of available actions. + * @var JFormField $field Field object data. + * @var boolean $newItem Is that new item. + * @var JAccessRules $assetRules Access Rules + * @var integer $assetId Asset ID + * @var string $component Component */ extract($displayData); ?> - value == 1) ? ' active' : ''; - ?> -
        - - - - - - - - - - - value, 'core.admin'); - ?> - - - - - - - - - -
        - - - - - -
        - - - - - - - - value, $action->name, $assetId); - $inheritedGroupParentAssetRule = !empty($parentAssetId) ? JAccess::checkGroup($group->value, $action->name, $parentAssetId) : null; - $inheritedParentGroupRule = !empty($group->parent_id) ? JAccess::checkGroup($group->parent_id, $action->name, $assetId) : null; - - // Current group is a Super User group, so calculated setting is "Allowed (Super User)". - if ($isSuperUserGroup) - { - $result['class'] = 'label label-success'; - $result['text'] = '' . JText::_('JLIB_RULES_ALLOWED_ADMIN'); - } - // Not super user. - else - { - // First get the real recursive calculated setting and add (Inherited) to it. - - // If recursive calculated setting is "Denied" or null. Calculated permission is "Not Allowed (Inherited)". - if ($inheritedGroupRule === null || $inheritedGroupRule === false) - { - $result['class'] = 'label label-important'; - $result['text'] = JText::_('JLIB_RULES_NOT_ALLOWED_INHERITED'); - } - // If recursive calculated setting is "Allowed". Calculated permission is "Allowed (Inherited)". - else - { - $result['class'] = 'label label-success'; - $result['text'] = JText::_('JLIB_RULES_ALLOWED_INHERITED'); - } - - // Second part: Overwrite the calculated permissions labels if there is an explicit permission in the current group. - - /** - * @to do: incorrect info - * If a component as a permission that doesn't exists in global config (ex: frontend editing in com_modules) by default - * we get "Not Allowed (Inherited)" when we should get "Not Allowed (Default)". - */ - - // If there is an explicit permission "Not Allowed". Calculated permission is "Not Allowed". - if ($assetRule === false) - { - $result['class'] = 'label label-important'; - $result['text'] = JText::_('JLIB_RULES_NOT_ALLOWED'); - } - // If there is an explicit permission is "Allowed". Calculated permission is "Allowed". - elseif ($assetRule === true) - { - $result['class'] = 'label label-success'; - $result['text'] = JText::_('JLIB_RULES_ALLOWED'); - } - - // Third part: Overwrite the calculated permissions labels for special cases. - - // Global configuration with "Not Set" permission. Calculated permission is "Not Allowed (Default)". - if (empty($group->parent_id) && $isGlobalConfig === true && $assetRule === null) - { - $result['class'] = 'label label-important'; - $result['text'] = JText::_('JLIB_RULES_NOT_ALLOWED_DEFAULT'); - } - - /** - * Component/Item with explicit "Denied" permission at parent Asset (Category, Component or Global config) configuration. - * Or some parent group has an explicit "Denied". - * Calculated permission is "Not Allowed (Locked)". - */ - elseif ($inheritedGroupParentAssetRule === false || $inheritedParentGroupRule === false) - { - $result['class'] = 'label label-important'; - $result['text'] = '' . JText::_('JLIB_RULES_NOT_ALLOWED_LOCKED'); - } - } - ?> - -
        -
        + value == 1) ? ' active' : ''; + ?> +
        + + + + + + + + + + + value, 'core.admin'); + ?> + + + + + + + + + +
        + + + + + +
        + + + + + + + + value, + $action->name, + $assetId + ); + $inheritedGroupParentAssetRule = !empty($parentAssetId) ? JAccess::checkGroup( + $group->value, + $action->name, + $parentAssetId + ) : null; + $inheritedParentGroupRule = !empty($group->parent_id) ? JAccess::checkGroup( + $group->parent_id, + $action->name, + $assetId + ) : null; + + // Current group is a Super User group, so calculated setting is "Allowed (Super User)". + if ($isSuperUserGroup) { + $result['class'] = 'label label-success'; + $result['text'] = '' . JText::_( + 'JLIB_RULES_ALLOWED_ADMIN' + ); + } // Not super user. + else { + // First get the real recursive calculated setting and add (Inherited) to it. + + // If recursive calculated setting is "Denied" or null. Calculated permission is "Not Allowed (Inherited)". + if ($inheritedGroupRule === null || $inheritedGroupRule === false) { + $result['class'] = 'label label-important'; + $result['text'] = JText::_('JLIB_RULES_NOT_ALLOWED_INHERITED'); + } // If recursive calculated setting is "Allowed". Calculated permission is "Allowed (Inherited)". + else { + $result['class'] = 'label label-success'; + $result['text'] = JText::_('JLIB_RULES_ALLOWED_INHERITED'); + } + + // Second part: Overwrite the calculated permissions labels if there is an explicit permission in the current group. + + /** + * @to do: incorrect info + * If a component as a permission that doesn't exists in global config (ex: frontend editing in com_modules) by default + * we get "Not Allowed (Inherited)" when we should get "Not Allowed (Default)". + */ + + // If there is an explicit permission "Not Allowed". Calculated permission is "Not Allowed". + if ($assetRule === false) { + $result['class'] = 'label label-important'; + $result['text'] = JText::_('JLIB_RULES_NOT_ALLOWED'); + } // If there is an explicit permission is "Allowed". Calculated permission is "Allowed". + elseif ($assetRule === true) { + $result['class'] = 'label label-success'; + $result['text'] = JText::_('JLIB_RULES_ALLOWED'); + } + + // Third part: Overwrite the calculated permissions labels for special cases. + + // Global configuration with "Not Set" permission. Calculated permission is "Not Allowed (Default)". + if (empty($group->parent_id) && $isGlobalConfig === true && $assetRule === null) { + $result['class'] = 'label label-important'; + $result['text'] = JText::_('JLIB_RULES_NOT_ALLOWED_DEFAULT'); + } /** + * Component/Item with explicit "Denied" permission at parent Asset (Category, Component or Global config) configuration. + * Or some parent group has an explicit "Denied". + * Calculated permission is "Not Allowed (Locked)". + */ + elseif ($inheritedGroupParentAssetRule === false || $inheritedParentGroupRule === false) { + $result['class'] = 'label label-important'; + $result['text'] = '' . JText::_( + 'JLIB_RULES_NOT_ALLOWED_LOCKED' + ); + } + } + ?> + +
        +
        diff --git a/libraries/redshop/layouts/field/rules/wrapper.php b/libraries/redshop/layouts/field/rules/wrapper.php index df61249afd4..24abf539c22 100644 --- a/libraries/redshop/layouts/field/rules/wrapper.php +++ b/libraries/redshop/layouts/field/rules/wrapper.php @@ -26,8 +26,11 @@ */ extract($displayData); -$layout = ($showGroup === true) ? 'field.rules.group' : 'field.rules.rules'; -$selectedTabPosition = JFactory::getApplication()->getUserState('com_redshop.access.selectedTabPosition', 'permission-1'); +$layout = ($showGroup === true) ? 'field.rules.group' : 'field.rules.rules'; +$selectedTabPosition = JFactory::getApplication()->getUserState( + 'com_redshop.access.selectedTabPosition', + 'permission-1' +); ?>

        @@ -35,51 +38,55 @@
        - $groups, - 'actions' => $actions, - 'field' => $field, - 'newItem' => $newItem, - 'assetRules' => $assetRules, - 'assetId' => $assetId, - 'isGlobalConfig' => $isGlobalConfig, - 'component' => $component - ) - ); - ?> + $groups, + 'actions' => $actions, + 'field' => $field, + 'newItem' => $newItem, + 'assetRules' => $assetRules, + 'assetId' => $assetId, + 'isGlobalConfig' => $isGlobalConfig, + 'component' => $component + ) + ); + ?>
        - +
        diff --git a/libraries/redshop/layouts/field_display/checkbox.php b/libraries/redshop/layouts/field_display/checkbox.php index 8757d126069..eacdb5eaa8d 100644 --- a/libraries/redshop/layouts/field_display/checkbox.php +++ b/libraries/redshop/layouts/field_display/checkbox.php @@ -18,15 +18,15 @@ extract($displayData); ?> - - - - - - -
        - -
        -
        - + + + + + + +
        + +
        +
        + diff --git a/libraries/redshop/layouts/field_display/country.php b/libraries/redshop/layouts/field_display/country.php index 8757d126069..eacdb5eaa8d 100644 --- a/libraries/redshop/layouts/field_display/country.php +++ b/libraries/redshop/layouts/field_display/country.php @@ -18,15 +18,15 @@ extract($displayData); ?> - - - - - - -
        - -
        -
        - + + + + + + +
        + +
        +
        + diff --git a/libraries/redshop/layouts/field_display/datepicker.php b/libraries/redshop/layouts/field_display/datepicker.php index 8757d126069..eacdb5eaa8d 100644 --- a/libraries/redshop/layouts/field_display/datepicker.php +++ b/libraries/redshop/layouts/field_display/datepicker.php @@ -18,15 +18,15 @@ extract($displayData); ?> - - - - - - -
        - -
        -
        - + + + + + + +
        + +
        +
        + diff --git a/libraries/redshop/layouts/field_display/multiple.php b/libraries/redshop/layouts/field_display/multiple.php index 70deecd4a86..78a42031f0d 100644 --- a/libraries/redshop/layouts/field_display/multiple.php +++ b/libraries/redshop/layouts/field_display/multiple.php @@ -18,15 +18,15 @@ extract($displayData); ?> - - - - - - -
        - -
        -
        - + + + + + + +
        + +
        +
        + diff --git a/libraries/redshop/layouts/field_display/radio.php b/libraries/redshop/layouts/field_display/radio.php index 8757d126069..eacdb5eaa8d 100644 --- a/libraries/redshop/layouts/field_display/radio.php +++ b/libraries/redshop/layouts/field_display/radio.php @@ -18,15 +18,15 @@ extract($displayData); ?> - - - - - - -
        - -
        -
        - + + + + + + +
        + +
        +
        + diff --git a/libraries/redshop/layouts/field_display/select.php b/libraries/redshop/layouts/field_display/select.php index 8757d126069..eacdb5eaa8d 100644 --- a/libraries/redshop/layouts/field_display/select.php +++ b/libraries/redshop/layouts/field_display/select.php @@ -18,15 +18,15 @@ extract($displayData); ?> - - - - - - -
        - -
        -
        - + + + + + + +
        + +
        +
        + diff --git a/libraries/redshop/layouts/field_display/text.php b/libraries/redshop/layouts/field_display/text.php index d6dce0f3eba..3dbdd43f0ce 100644 --- a/libraries/redshop/layouts/field_display/text.php +++ b/libraries/redshop/layouts/field_display/text.php @@ -19,15 +19,15 @@ extract($displayData); ?> - - - - - - -
        - -
        -
        - + + + + + + +
        + +
        +
        + diff --git a/libraries/redshop/layouts/field_display/textarea.php b/libraries/redshop/layouts/field_display/textarea.php index 8757d126069..eacdb5eaa8d 100644 --- a/libraries/redshop/layouts/field_display/textarea.php +++ b/libraries/redshop/layouts/field_display/textarea.php @@ -18,15 +18,15 @@ extract($displayData); ?> - - - - - - -
        - -
        -
        - + + + + + + +
        + +
        +
        + diff --git a/libraries/redshop/layouts/html/list.php b/libraries/redshop/layouts/html/list.php index d80c9414301..27a17acf28b 100644 --- a/libraries/redshop/layouts/html/list.php +++ b/libraries/redshop/layouts/html/list.php @@ -29,50 +29,45 @@ $cssClassSuffix = ' btn-group redRadioGroup'; -if (is_array($attribs)) -{ - $cssClassSuffix = (isset($attribs['cssClassSuffix'])) ? $attribs['cssClassSuffix'] : ' btn-group redRadioGroup'; +if (is_array($attribs)) { + $cssClassSuffix = (isset($attribs['cssClassSuffix'])) ? $attribs['cssClassSuffix'] : ' btn-group redRadioGroup'; - $attribs = ArrayHelper::toString($attribs); + $attribs = ArrayHelper::toString($attribs); } $idText = $idtag ? $idtag : $name; ?>
        - - $obj) : ?> - $optKey; - $title = $translate ? JText::_($obj->$optText) : $obj->$optText; - $id = (isset($obj->id) ? $obj->id : null); + + $obj) : ?> + $optKey; + $title = $translate ? JText::_($obj->$optText) : $obj->$optText; + $id = (isset($obj->id) ? $obj->id : null); - $extra = ''; - $id = $id ? $obj->id : $idText . '_' . $key; + $extra = ''; + $id = $id ? $obj->id : $idText . '_' . $key; - if (is_array($selected)) - { - foreach ($selected as $val) - { - $key2 = is_object($val) ? $val->$optKey : $val; + if (is_array($selected)) { + foreach ($selected as $val) { + $key2 = is_object($val) ? $val->$optKey : $val; - if ($key == $key2) - { - $extra .= ' selected="selected" '; - break; - } - } - } - else - { - $extra .= ((string) $key == (string) $selected ? ' checked="checked" ' : ''); - } - ?> - rel="noicheck"/> + if ($key == $key2) { + $extra .= ' selected="selected" '; + break; + } + } + } else { + $extra .= ((string)$key == (string)$selected ? ' checked="checked" ' : ''); + } + ?> + rel="noicheck"/> - - + +
        diff --git a/libraries/redshop/layouts/html/media/button.php b/libraries/redshop/layouts/html/media/button.php index add658cea4f..715d79d1749 100644 --- a/libraries/redshop/layouts/html/media/button.php +++ b/libraries/redshop/layouts/html/media/button.php @@ -11,9 +11,13 @@ extract($displayData); -$url = JRoute::_(JURI::base() . 'index.php?option=com_redshop&view=media§ion_id=' . $sectionId . '&showbuttons=1&media_section=' . $mediaSection . '§ion_name=' . $sectionName . '&tmpl=component'); +$url = JRoute::_( + JURI::base( + ) . 'index.php?option=com_redshop&view=media§ion_id=' . $sectionId . '&showbuttons=1&media_section=' . $mediaSection . '§ion_name=' . $sectionName . '&tmpl=component' +); -JFactory::getDocument()->addScriptDeclaration(' +JFactory::getDocument()->addScriptDeclaration( + ' (function($){ jQuery(document).ready(function(){ jQuery("#btnModal_' . $sectionId . '").on("click", function(){ @@ -24,15 +28,16 @@ }); }); })(jQuery); -'); +' +); ?> media () + src="media16.png" align="absmiddle" + alt="media"> () -
        +
        diff --git a/libraries/redshop/layouts/media/additional_media.php b/libraries/redshop/layouts/media/additional_media.php index 2ae9a8a2e76..c69e0123459 100644 --- a/libraries/redshop/layouts/media/additional_media.php +++ b/libraries/redshop/layouts/media/additional_media.php @@ -12,193 +12,208 @@ /** * Layout variables * ======================= - * @var array $displayData List of data. - * @var string $id ID - * @var string $type Type of section (Ex: product) - * @var string $sectionId Section ID (Ex: Product ID if $type is product) - * @var string $mediaSection Section media (Ex: product) - * @var array $file Files data as array - * @var array $gallery List of data + * @var array $displayData List of data. + * @var string $id ID + * @var string $type Type of section (Ex: product) + * @var string $sectionId Section ID (Ex: Product ID if $type is product) + * @var string $mediaSection Section media (Ex: product) + * @var array $file Files data as array + * @var array $gallery List of data */ extract($displayData); ?> -
        -
        - - - - - + + + + + +
        +
        + +
        +
        + + + + + diff --git a/libraries/redshop/layouts/product/rating_comments.php b/libraries/redshop/layouts/product/rating_comments.php index 954a7c4a8e5..d9911664592 100644 --- a/libraries/redshop/layouts/product/rating_comments.php +++ b/libraries/redshop/layouts/product/rating_comments.php @@ -12,10 +12,10 @@ /** * $displayData extract * - * @var array $displayData Display data - * @var integer $productId Product Id - * @var string $main_template Template rating - * @var integer $mainblock Main block + * @var array $displayData Display data + * @var integer $productId Product Id + * @var string $main_template Template rating + * @var integer $mainblock Main block */ extract($displayData); @@ -24,150 +24,152 @@ $reviews_template = ""; $product_template = ""; -if (strstr($main_template, "{product_loop_start}") && strstr($main_template, "{product_loop_end}")) -{ - $product_start = explode("{product_loop_start}", $main_template); - $product_end = explode("{product_loop_end}", $product_start [1]); - $product_template = $product_end [0]; - - if (strstr($main_template, "{product_loop_start}") && strstr($main_template, "{product_loop_end}")) - { - $review_start = explode("{review_loop_start}", $product_template); - $review_end = explode("{review_loop_end}", $review_start [1]); - $reviews_template = $review_end [0]; - } +if (strstr($main_template, "{product_loop_start}") && strstr($main_template, "{product_loop_end}")) { + $product_start = explode("{product_loop_start}", $main_template); + $product_end = explode("{product_loop_end}", $product_start [1]); + $product_template = $product_end [0]; + + if (strstr($main_template, "{product_loop_start}") && strstr($main_template, "{product_loop_end}")) { + $review_start = explode("{review_loop_start}", $product_template); + $review_end = explode("{review_loop_end}", $review_start [1]); + $reviews_template = $review_end [0]; + } } $allImage = array(); $product_data = ''; $reviews_all = ''; -if ($product_template != "" && $reviews_template != "" && count($reviews) > 0) -{ - $product_data .= str_replace("{product_title}", '', $product_template); - - $reviews_data1 = ""; - $reviews_data2 = ""; - $reviews_data = ""; - - for ($j = 0; $j < $mainblock && $j < count($reviews); $j++) - { - $fullname = $reviews[$j]->firstname . " " . $reviews[$j]->lastname; - $starimage = ''; - - if ($fullname != " ") - { - $displayname = $fullname; - } - else - { - $displayname = $reviews[$j]->username; - } - - $images1 = json_decode($reviews[$j]->images); - $imgHtml1 = '
          '; - - foreach ($images1 as $image1) - { - if (!empty($image1)) - { - $linkImage = REDSHOP_FRONT_IMAGES_ABSPATH . 'product_rating/' . $image1; - - $thumbImg1 = RedshopHelperMedia::getImagePath( - $image1, - '', - 'thumb', - 'product_rating', - Redshop::getConfig()->get('RATING_THUMB_IMAGE_WIDTH'), - Redshop::getConfig()->get('RATING_THUMB_IMAGE_HEIGHT'), - Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') - ); - - $allImage[] = $linkImage; - $imgHtml1 .= '
        • '; - } - } - - $imgHtml1 .= '
        '; - - $reviews_data1 = str_replace("{fullname}", $displayname, $reviews_template); - $reviews_data1 = str_replace("{email}", $reviews[$j]->email, $reviews_data1); - $reviews_data1 = str_replace("{company_name}", $reviews[$j]->company_name, $reviews_data1); - $reviews_data1 = str_replace("{title}", $reviews [$j]->title, $reviews_data1); - $reviews_data1 = str_replace("{comment}", nl2br($reviews [$j]->comment), $reviews_data1); - $reviews_data1 = str_replace("{stars}", $starimage, $reviews_data1); - $reviews_data1 = str_replace("{images}", $imgHtml1, $reviews_data1); - $reviews_data1 = str_replace("{reviewdate}", RedshopHelperDatetime::convertDateFormat($reviews [$j]->time), $reviews_data1); - $reviews_data .= $reviews_data1; - } - - if ($mainblock < count($reviews)) - { - $reviews_data .= ''; - } - - $reviews_data .= ''; - $reviews_all .= $reviews_data; +if ($product_template != "" && $reviews_template != "" && count($reviews) > 0) { + $product_data .= str_replace("{product_title}", '', $product_template); + + $reviews_data1 = ""; + $reviews_data2 = ""; + $reviews_data = ""; + + for ($j = 0; $j < $mainblock && $j < count($reviews); $j++) { + $fullname = $reviews[$j]->firstname . " " . $reviews[$j]->lastname; + $starimage = ''; + + if ($fullname != " ") { + $displayname = $fullname; + } else { + $displayname = $reviews[$j]->username; + } + + $images1 = json_decode($reviews[$j]->images); + $imgHtml1 = '
          '; + + foreach ($images1 as $image1) { + if (!empty($image1)) { + $linkImage = REDSHOP_FRONT_IMAGES_ABSPATH . 'product_rating/' . $image1; + + $thumbImg1 = RedshopHelperMedia::getImagePath( + $image1, + '', + 'thumb', + 'product_rating', + Redshop::getConfig()->get('RATING_THUMB_IMAGE_WIDTH'), + Redshop::getConfig()->get('RATING_THUMB_IMAGE_HEIGHT'), + Redshop::getConfig()->get('USE_IMAGE_SIZE_SWAPPING') + ); + + $allImage[] = $linkImage; + $imgHtml1 .= '
        • '; + } + } + + $imgHtml1 .= '
        '; + + $reviews_data1 = str_replace("{fullname}", $displayname, $reviews_template); + $reviews_data1 = str_replace("{email}", $reviews[$j]->email, $reviews_data1); + $reviews_data1 = str_replace("{company_name}", $reviews[$j]->company_name, $reviews_data1); + $reviews_data1 = str_replace("{title}", $reviews [$j]->title, $reviews_data1); + $reviews_data1 = str_replace("{comment}", nl2br($reviews [$j]->comment), $reviews_data1); + $reviews_data1 = str_replace("{stars}", $starimage, $reviews_data1); + $reviews_data1 = str_replace("{images}", $imgHtml1, $reviews_data1); + $reviews_data1 = str_replace( + "{reviewdate}", + RedshopHelperDatetime::convertDateFormat($reviews [$j]->time), + $reviews_data1 + ); + $reviews_data .= $reviews_data1; + } + + if ($mainblock < count($reviews)) { + $reviews_data .= ''; + } + + $reviews_data .= ''; + $reviews_all .= $reviews_data; } -if (strstr($main_template, "{show_all_images_rating}")) -{ - $allImageHtml = '
          '; +if (strstr($main_template, "{show_all_images_rating}")) { + $allImageHtml = '
            '; - foreach ($allImage as $itemImage) - { - $allImageHtml .= '
          • '; - } + foreach ($allImage as $itemImage) { + $allImageHtml .= '
          • '; + } - $allImageHtml .= '
          '; + $allImageHtml .= '
        '; - $main_template = str_replace('{show_all_images_rating}', $allImageHtml, $main_template); + $main_template = str_replace('{show_all_images_rating}', $allImageHtml, $main_template); } -if (strstr($main_template, "{rating_statistics}") && !empty($reviews)) -{ - $main_template = str_replace( - '{rating_statistics}', - RedshopLayoutHelper::render('product.rating_summary', array('productId' => $productId)), - $main_template); +if (strstr($main_template, "{rating_statistics}") && !empty($reviews)) { + $main_template = str_replace( + '{rating_statistics}', + RedshopLayoutHelper::render('product.rating_summary', array('productId' => $productId)), + $main_template + ); } $main_template = str_replace('{rating_statistics}', '', $main_template); -$product_data = str_replace("{review_loop_start}" . $reviews_template . "{review_loop_end}", $reviews_all, $product_data); -$main_template = str_replace("{product_loop_start}" . $product_template . "{product_loop_end}", $product_data, $main_template); +$product_data = str_replace( + "{review_loop_start}" . $reviews_template . "{review_loop_end}", + $reviews_all, + $product_data +); +$main_template = str_replace( + "{product_loop_start}" . $product_template . "{product_loop_end}", + $product_data, + $main_template +); echo $main_template; \ No newline at end of file diff --git a/libraries/redshop/layouts/product/rating_summary.php b/libraries/redshop/layouts/product/rating_summary.php index 545ccf43366..ed121662957 100644 --- a/libraries/redshop/layouts/product/rating_summary.php +++ b/libraries/redshop/layouts/product/rating_summary.php @@ -12,52 +12,53 @@ /** * $displayData extract * - * @var array $displayData Display data - * @var integer $productId Product Id + * @var array $displayData Display data + * @var integer $productId Product Id */ extract($displayData); -$statistics = RedshopHelperProduct::statisticsRatingProduct($productId); -$star = array(); -$totalRating = 0; -$avg = 0; +$statistics = RedshopHelperProduct::statisticsRatingProduct($productId); +$star = array(); +$totalRating = 0; +$avg = 0; -foreach ($statistics as $statistic) -{ - $star[$statistic->user_rating] = $statistic->percent; - $totalRating += $statistic->count; - $avg += $statistic->user_rating * $statistic->count; +foreach ($statistics as $statistic) { + $star[$statistic->user_rating] = $statistic->percent; + $totalRating += $statistic->count; + $avg += $statistic->user_rating * $statistic->count; } -$avg = (is_numeric(number_format($avg / $totalRating, 1))) ? number_format($avg / $totalRating, 1) : 0; +$avg = (is_numeric(number_format($avg / $totalRating, 1))) ? number_format($avg / $totalRating, 1) : 0; $totalPercent = ($avg * 100) / 5; ?>
        - - - - - -
        -
        /5
        -
        -
        nhận xét
        -
        -
          - 0; $i--) : ?> - -
        • -
          - -
          -
          -
          -
          -
          -
          -
          %
          -
        • - -
        -
        + + + + + +
        +
        /5
        +
        +
        nhận xét
        +
        +
          + 0; $i--) : ?> + +
        • +
          + +
          +
          +
          +
          +
          +
          +
          %
          +
        • + +
        +
        diff --git a/libraries/redshop/layouts/product/subproperty_scroller.php b/libraries/redshop/layouts/product/subproperty_scroller.php index 1dbe5d5f5a6..668fb3d8b16 100644 --- a/libraries/redshop/layouts/product/subproperty_scroller.php +++ b/libraries/redshop/layouts/product/subproperty_scroller.php @@ -12,78 +12,85 @@ /** * $displayData extract * - * @var array $displayData Display data - * @var object $subProperties Subproperty - * @var string $commonId Common ID - * @var string $productId Product ID - * @var string $propertyId Property ID - * @var string $subPropertyId Subproperty ID - * @var string $accessoryId Accessory ID - * @var string $relatedProductId Related product ID - * @var int $selectedSubProperty Subproperty is selected - * @var array $subPropertyArray Subproperty array - * @var float $width Image width - * @var float $height Image height + * @var array $displayData Display data + * @var object $subProperties Subproperty + * @var string $commonId Common ID + * @var string $productId Product ID + * @var string $propertyId Property ID + * @var string $subPropertyId Subproperty ID + * @var string $accessoryId Accessory ID + * @var string $relatedProductId Related product ID + * @var int $selectedSubProperty Subproperty is selected + * @var array $subPropertyArray Subproperty array + * @var float $width Image width + * @var float $height Image height */ extract($displayData); $atth = 50; $attw = 50; -if (Redshop::getConfig()->get('ATTRIBUTE_SCROLLER_THUMB_HEIGHT')) -{ - $atth = Redshop::getConfig()->get('ATTRIBUTE_SCROLLER_THUMB_HEIGHT'); +if (Redshop::getConfig()->get('ATTRIBUTE_SCROLLER_THUMB_HEIGHT')) { + $atth = Redshop::getConfig()->get('ATTRIBUTE_SCROLLER_THUMB_HEIGHT'); } -if (Redshop::getConfig()->get('ATTRIBUTE_SCROLLER_THUMB_WIDTH')) -{ - $attw = Redshop::getConfig()->get('ATTRIBUTE_SCROLLER_THUMB_WIDTH'); +if (Redshop::getConfig()->get('ATTRIBUTE_SCROLLER_THUMB_WIDTH')) { + $attw = Redshop::getConfig()->get('ATTRIBUTE_SCROLLER_THUMB_WIDTH'); } ?> - - + + - - - + + +
        - -
        + + -
        -
        - - -
        -
        -
        - -
        +
        +
        + + +
        +
        +
        + +
        diff --git a/libraries/redshop/layouts/shop/compare_product.php b/libraries/redshop/layouts/shop/compare_product.php index 7f95e2b1f24..e47ddf29f36 100644 --- a/libraries/redshop/layouts/shop/compare_product.php +++ b/libraries/redshop/layouts/shop/compare_product.php @@ -12,48 +12,52 @@ /** * Layout variables * ----------------- - * @var array $displayData Layout data + * @var array $displayData Layout data * @var array $compareProducts Compare products - * @var boolean $excludeData Exclude table compare? - * @var integer $itemId Menu item ID + * @var boolean $excludeData Exclude table compare? + * @var integer $itemId Menu item ID */ extract($displayData); -$idx = isset($compareProducts) ? (int) $compareProducts['idx'] : 0; +$idx = isset($compareProducts) ? (int)$compareProducts['idx'] : 0; ?> - - + + - +
        product_name ?> - ,)"> + ,)">
        - - =')): ?> + + =')): ?>
        - $msgs) : ?> + $msgs) : ?>
        - - + + × - - + + - +

        - +
        - +

        - +
        - +
        - +
        - +
        - $msgs) : ?> - + $msgs) : ?> + - +
        - +
          - +
        • - +
        - - + +
        - - + +
        diff --git a/libraries/redshop/layouts/tags/accessory/add_chkbox.html.twig b/libraries/redshop/layouts/tags/accessory/add_chkbox.html.twig index 5323e382007..2ebbd869500 100644 --- a/libraries/redshop/layouts/tags/accessory/add_chkbox.html.twig +++ b/libraries/redshop/layouts/tags/accessory/add_chkbox.html.twig @@ -6,5 +6,5 @@ accessorywithoutvatprice='{{ accessoryPriceWithoutVAT }}' id='accessory_id_{{ commonId }}' value='{{ accessoryId }}' - {{ accessoryChecked }} + {{ accessoryChecked }} /> \ No newline at end of file diff --git a/libraries/redshop/layouts/tags/accessory/image/lightbox.html.twig b/libraries/redshop/layouts/tags/accessory/image/lightbox.html.twig index 3f6dfe76a6b..099a896776e 100644 --- a/libraries/redshop/layouts/tags/accessory/image/lightbox.html.twig +++ b/libraries/redshop/layouts/tags/accessory/image/lightbox.html.twig @@ -3,7 +3,7 @@ title='' class="modal" rel="{handler: 'image', size: {}}"> - + - - + + diff --git a/libraries/redshop/layouts/tags/accessory/image/lightbox.php b/libraries/redshop/layouts/tags/accessory/image/lightbox.php index a69deab3608..3ab3efd49c1 100644 --- a/libraries/redshop/layouts/tags/accessory/image/lightbox.php +++ b/libraries/redshop/layouts/tags/accessory/image/lightbox.php @@ -12,20 +12,20 @@ /** * $displayData extract * - * @param object $thumbUrl Thumb url - * @param object $imageUrl Image url - * @param integer $accessoryImage Accessory image - * @param integer $accessoryId Accessory id - * @param integer $accessoryWidthThumb Accessory width thumb - * @param integer $accessoryHeightThumb Accessory height thumb - + * @param object $thumbUrl Thumb url + * @param object $imageUrl Image url + * @param integer $accessoryImage Accessory image + * @param integer $accessoryId Accessory id + * @param integer $accessoryWidthThumb Accessory width thumb + * @param integer $accessoryHeightThumb Accessory height thumb */ extract($displayData); ?> - - + + diff --git a/libraries/redshop/layouts/tags/accessory/image/no_lightbox.html.twig b/libraries/redshop/layouts/tags/accessory/image/no_lightbox.html.twig index 11a99d4e2cf..15f16826c8b 100644 --- a/libraries/redshop/layouts/tags/accessory/image/no_lightbox.html.twig +++ b/libraries/redshop/layouts/tags/accessory/image/no_lightbox.html.twig @@ -1,6 +1,5 @@ - - + diff --git a/libraries/redshop/layouts/tags/accessory/image/no_lightbox.php b/libraries/redshop/layouts/tags/accessory/image/no_lightbox.php index be4c237fe72..51234ab152b 100644 --- a/libraries/redshop/layouts/tags/accessory/image/no_lightbox.php +++ b/libraries/redshop/layouts/tags/accessory/image/no_lightbox.php @@ -12,18 +12,17 @@ /** * $displayData extract * - * @param string $accessoryProductLink Accessory product link - * @param string $thumbUrl Thumb url - * @param integer $accessoryId Accessory Id - * @param integer $accessoryWidthThumb Accessory width thumb - * @param integer $accessoryHeightThumb Accessory height thumb - + * @param string $accessoryProductLink Accessory product link + * @param string $thumbUrl Thumb url + * @param integer $accessoryId Accessory Id + * @param integer $accessoryWidthThumb Accessory width thumb + * @param integer $accessoryHeightThumb Accessory height thumb */ extract($displayData); ?> - + diff --git a/libraries/redshop/layouts/tags/accessory/index.html b/libraries/redshop/layouts/tags/accessory/index.html index fa6d84e8055..1cbdf58d903 100644 --- a/libraries/redshop/layouts/tags/accessory/index.html +++ b/libraries/redshop/layouts/tags/accessory/index.html @@ -1 +1,3 @@ - \ No newline at end of file + + + \ No newline at end of file diff --git a/libraries/redshop/layouts/tags/accessory/quantity.html.twig b/libraries/redshop/layouts/tags/accessory/quantity.html.twig index 89f9a7aab63..460c7639397 100644 --- a/libraries/redshop/layouts/tags/accessory/quantity.html.twig +++ b/libraries/redshop/layouts/tags/accessory/quantity.html.twig @@ -3,4 +3,4 @@ value='{{ accqua }}' maxlength='{{ 'DEFAULT_CONFIG' | redconfig }}' size='{{ 'DEFAULT_CONFIG' | redconfig }}' - onchange='validateInputNumber(this.id)' /> \ No newline at end of file + onchange='validateInputNumber(this.id)'/> \ No newline at end of file diff --git a/libraries/redshop/layouts/tags/account/logout_link.html.twig b/libraries/redshop/layouts/tags/account/logout_link.html.twig index 530926b620b..cf57318c0f7 100644 --- a/libraries/redshop/layouts/tags/account/logout_link.html.twig +++ b/libraries/redshop/layouts/tags/account/logout_link.html.twig @@ -1,2 +1,2 @@ - + {{ jtext('COM_REDSHOP_LOGOUT') }} \ No newline at end of file diff --git a/libraries/redshop/layouts/tags/addtocart/addtocartscroll.html.twig b/libraries/redshop/layouts/tags/addtocart/addtocartscroll.html.twig index 43386308698..aabeccd7899 100644 --- a/libraries/redshop/layouts/tags/addtocart/addtocartscroll.html.twig +++ b/libraries/redshop/layouts/tags/addtocart/addtocartscroll.html.twig @@ -1,16 +1,16 @@
        -
        - - - - - - + + + + + + + {{ jtext('COM_REDSHOP_ADD_TO_CART') }} - +
        \ No newline at end of file diff --git a/libraries/redshop/layouts/tags/addtocart/button.html.twig b/libraries/redshop/layouts/tags/addtocart/button.html.twig index d945ed3e43c..0f268aa6894 100644 --- a/libraries/redshop/layouts/tags/addtocart/button.html.twig +++ b/libraries/redshop/layouts/tags/addtocart/button.html.twig @@ -1,11 +1,11 @@ {% if 'AJAX_CART_BOX' | redconfig != 1 %}
        - +
        {% else %} - +
        - +
        {% endif %} \ No newline at end of file diff --git a/libraries/redshop/layouts/tags/addtocart/image.html.twig b/libraries/redshop/layouts/tags/addtocart/image.html.twig index c0418f28f33..52ac9b9127d 100644 --- a/libraries/redshop/layouts/tags/addtocart/image.html.twig +++ b/libraries/redshop/layouts/tags/addtocart/image.html.twig @@ -1,29 +1,33 @@ {% if 'AJAX_CART_BOX' | redconfig != 1 %} {% if fileExist %} -
        +
        {{ requestLabel }}
        {% else %} - - + + {{ requestLabel }} {% endif %} {% else %} {% if fileExist %} - + -
        +
        {{ requestLabel }}
        {% else %} - - + + {{ requestLabel }} diff --git a/libraries/redshop/layouts/tags/addtocart/image_aslink.html.twig b/libraries/redshop/layouts/tags/addtocart/image_aslink.html.twig index 75bf9b121fe..6074626494b 100644 --- a/libraries/redshop/layouts/tags/addtocart/image_aslink.html.twig +++ b/libraries/redshop/layouts/tags/addtocart/image_aslink.html.twig @@ -1,25 +1,29 @@ {% if 'AJAX_CART_BOX' | redconfig != 1 %} {% if fileExist %} - {{ requestLabel }} + {{ requestLabel }} {% else %} - - + + {{ requestLabel }} {% endif %} {% else %} {% if fileExist %} - + - {{ requestLabel }} + {{ requestLabel }} {% else %} - - + + {{ requestLabel }} diff --git a/libraries/redshop/layouts/tags/addtocart/link.html.twig b/libraries/redshop/layouts/tags/addtocart/link.html.twig index 0bce998e30f..a698822b1c4 100644 --- a/libraries/redshop/layouts/tags/addtocart/link.html.twig +++ b/libraries/redshop/layouts/tags/addtocart/link.html.twig @@ -1,10 +1,12 @@ {% if 'AJAX_CART_BOX' | redconfig != 1 %} - + {{ requestLabel }} {% else %} - - + + {{ requestLabel }} diff --git a/libraries/redshop/layouts/tags/addtocart/quantity.html.twig b/libraries/redshop/layouts/tags/addtocart/quantity.html.twig index ecab32b60e2..9d19c286f44 100644 --- a/libraries/redshop/layouts/tags/addtocart/quantity.html.twig +++ b/libraries/redshop/layouts/tags/addtocart/quantity.html.twig @@ -1,5 +1,6 @@ - \ No newline at end of file diff --git a/libraries/redshop/layouts/tags/addtocart/quantity_increase_decrease.html.twig b/libraries/redshop/layouts/tags/addtocart/quantity_increase_decrease.html.twig index fc8d00734db..49e8cd1292e 100644 --- a/libraries/redshop/layouts/tags/addtocart/quantity_increase_decrease.html.twig +++ b/libraries/redshop/layouts/tags/addtocart/quantity_increase_decrease.html.twig @@ -1,4 +1,6 @@ - - + + + onClick="quantity{{ productId }}.value = (quantity{{ productId }}.value); var qty1 = quantity{{ productId }}.value; if( !isNaN( qty1 ) && qty1 > 1 ) quantity{{ productId }}.value--;return false;"/> diff --git a/libraries/redshop/layouts/tags/addtocart/quantity_selectbox.html.twig b/libraries/redshop/layouts/tags/addtocart/quantity_selectbox.html.twig index bd07d9daa0b..e6df1ae03e8 100644 --- a/libraries/redshop/layouts/tags/addtocart/quantity_selectbox.html.twig +++ b/libraries/redshop/layouts/tags/addtocart/quantity_selectbox.html.twig @@ -1,8 +1,10 @@ - {% if 'DEFAULT_QUANTITY_SELECTBOX_VALUE' | redconfig != '' or {{ product | quantity_selectbox_value }} == '' or {{ product | quantity_selectbox_value }} != '' %} - {% for quantityBoxes in quantityBox %} {% if intVal{{ quantityBox }} and intVal{{ quantityBox }} != 0 %}