method not being called a third time - php

I have a method that updated fields in a table. Its used to update three tables, invoices invoice_items and payments All three tables have the same field to be updated. When the below code runs, the multi_checked() method runs for the first two times, but not for the third time and It's not obvious to me as to why. Any Ideas?
Method Call:
elseif (isset($_POST[$mod . '-del']) && count($check) > 0) {
$state = multi_checked(
$check,
'UPDATE ' . $db['database'] . '.invoices SET deleted="Y"',
EVENT_DEL,
'Invoice [' . $c . '] deleted',
'Please select at least one item',
FALSE,
'SELECT id FROM ' . $db['database'] . '.invoices'
);
$state = multi_checked(
$check,
'UPDATE ' . $db['database'] . '.payments SET deleted="Y"',
EVENT_DEL,
'Payment [' . $c . '] deleted',
'Please select at least one item',
TRUE,
'SELECT id FROM ' . $db['database'] . '.payments',
null,
"id_invoice"
);
$state = multi_checked(
$check,
'UPDATE ' . $db['database'] . '.invoice_items SET deleted="Y"',
EVENT_DEL,
'Invoice Item [' . $c . '] deleted',
'Please select at least one item',
TRUE,
'SELECT id FROM ' . $db['database'] . '.invoice_items',
null,
"id_invoice"
);
} # Clear Export timestamps
the multi_checked method is described as follows:
function multi_checked(
$check,
$query,
$event_type,
$event_desc,
$none = 'Please select at least one item',
$redirect = TRUE,
$meta_query = NULL,
$success_msg = NULL,
$field = "id"
) {
global $db, $mod;
$batch_count = count($check);
$meta_data = NULL;
if ($batch_count == 0) {
add_msg($none);
return (0);
} else {
$changed = 0;
$ref = load_array('SELECT MAX(id) FROM ' . $db['database'] . '.eventlog'); # batch id
foreach ($check As $c) {
if ($meta_query != NULL) {
$meta_data = load_array($meta_query . ' WHERE id' . $field . '="' . $c . '"');
if ($meta_data != NULL) $meta_data = ' (' . $meta_data . ')';
}
$q = $query . ' WHERE ' . $field . '="' . $c . '"';
$z = $query . ' WHERE ' . $field . '="' . $c . '"';
$g = "asf";
if (run_query($query . ' WHERE ' . $field . '="' . $c . '"') == 0) {
eventlog($db['database'], $event_type, $mod, $c, uid(), '[Batch #' . $ref . '] ' . $event_desc . $meta_data, uname());
$changed++;
} else {
eventlog($db['database'], $event_type, $mod, $c, uid(), '[Batch #' . $ref . '] FAIL: ' . $event_desc . $meta_data, uname(), FALSE, FALSE);
}
}
# Check for errors
if ($changed != $batch_count) {
add_error($changed . ' of ' . $batch_count . ' items processed - you may need to check the system log for details');
} # Success!
else {
$message = ($changed . ' item' . ($changed > 1 ? 's' : NULL) . ' processed successfully');
if ($changed > 1) { # log batch summary
#mysql_query("FLUSH QUERY CACHE");
eventlog($db['database'], $event_type, $mod, 0, uid(), '[Batch #' . $ref . '] ' . $changed . ' records processed', uname());
}
# Redirect
if ($redirect) {
header('Location: ?m=' . $mod . '&changed=' . $changed . '&message=' . $success_msg);
exit;
} else {
add_msg($message);
}
}
return ($changed);
}
}

The second call to multi_check has $redirect parameter set to TRUE - so the function redirects, preventing the script to call the function the third time...

Related

Add specific attribute and values to input and label html tags in Woocommerce

I'm trying to add style, depending on whether the checkbox is clicked. This code is missing "id" and "for" for input and label (line 11). Logical decision to add generation of numbers. How to do it correctly?
foreach ($choices as $choice) {
$attr = '';
$key_val = explode("|", $choice);
/* It has to be two items ( Value => Label ), otherwise don't proceed */
if (count($key_val) == 2) {
if (in_array(trim($key_val[0]), $defaults)) {
$attr = 'checked';
}
/* For admin field, we don't need <li></li> wrapper */
$html .= (($_ptype != "wccaf") ? '<li>' : '') . '<input type="checkbox" data-has_field_rules="'.$has_field_rules.'" data-is_pricing_rules="'.$_is_pricing_rules.'" class="' . $_ptype . '-field ' . $_class . '" name="' . esc_attr($_meta["name"] . $_index) . '[]" value="' . esc_attr(trim($key_val[0])) . '" ' . $attr . ' ' . $_ptype . '-type="checkbox" ' . $_ptype . '-pattern="mandatory" ' . $_ptype . '-mandatory="' . $_meta["required"] . '" ' . $_readonly . ' /><label class="wcff-option-wrapper-label">' . esc_attr(trim($key_val[1])) . '</label>' . (($_ptype != "wccaf") ? '</li>' : '');
}
}
Updated
Try the following (untested), that will add a for attribute + value to the <label> and an id attribute + value to the <input>:
foreach ($choices as $choice) {
$attr = '';
$key_val = explode("|", $choice);
/* It has to be two items ( Value => Label ), otherwise don't proceed */
if (count($key_val) == 2) {
if (in_array(trim($key_val[0]), $defaults)) {
$attr = 'checked';
}
$sprintf = sprintf( '<input type="checkbox" %s %s %s %s %s %s %s /><label %s class="wcff-option-wrapper-label">%s</label>',
'id="' . esc_attr($_meta["name"] . $_index) . '"',
'data-has_field_rules="'.$has_field_rules.'"',
'data-is_pricing_rules="'.$_is_pricing_rules.'"',
'class="' . $_ptype . '-field ' . $_class . '"',
'name="' . esc_attr($_meta["name"] . $_index) . '[]"',
'value="' . esc_attr(trim($key_val[0])) . '"',
$attr . ' ' . $_ptype . '-type="checkbox" ' . $_ptype . '-pattern="mandatory' . $_meta["required"] . '" ' . $_readonly,
'for="' . esc_attr($_meta["name"] . $_index) . '"',
esc_attr(trim($key_val[1]) ) );
$html .= $_ptype != "wccaf" ? '<li>'.$sprintf.'</li>' : $sprintf;
}
}
I have embedded the code in a sprintf() function to make it more readable, functional and easy to tune.

Magento 2 : Allow customer to edit custom options on Cart

I am trying to add functionality to allow a customer to edit options.
I have created a Module Vendor/COptions.
This is loading custom options and select, however is not getting user selected options.
I would like to know how to received selected options and check if the option is selected.
At the moment this line in Select.php is not receiving anything, and the variable $checked is null.
$configValue = $this->getProduct()->getPreconfiguredValues()->getData('options/' . $_option->getId());
in Vendor/COptions\view\frontend\templates\cart\item\default.phtml :
<?php $selectedOptions = $block->getSelectedOptionList(); ?>
<?php //$_options = Mage::helper('core')->decorateArray($block>getOptions())
$_options = $block->getOptions() ?>
<?php if ($_options AND count($_options)):?>
<dl>
<?php foreach($_options as $_option): ?>
<?php echo $this->getOptionHtml($_option) ?>
<?php endforeach; ?>
</dl>
<?php endif; ?>
in Vendor\COptions\Helper\Rewrite\Product:
public function getCustomOptions(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface $item, $simple="")
{
$product = $item->getProduct();
$coptions = [];
$coptions = $product->getOptions();
$options = array();
if ($coptions) {
foreach ($coptions as $option) {
$itemOption = $item->getOptionByCode('option_' . $option->getId());
/** #var $group \Magento\Catalog\Model\Product\Option\Type\DefaultType */
$group = $option->groupFactory($option->getType())
->setOption($option)
->setConfigurationItem($item)
->setConfigurationItemOption($itemOption);
if ('file' == $option->getType()) {
$downloadParams = $item->getFileDownloadParams();
if ($downloadParams) {
$url = $downloadParams->getUrl();
if ($url) {
$group->setCustomOptionDownloadUrl($url);
}
$urlParams = $downloadParams->getUrlParams();
if ($urlParams) {
$group->setCustomOptionUrlParams($urlParams);
}
}
}
if($simple == "Y"){
array_push($options, $itemOption['value']);
}else{
$options[] = [
'label' => $option->getTitle(),
'value' => $group->getFormattedOptionValue($itemOption['value']),
'print_value' => $group->getFormattedOptionValue($itemOption['value']),
'option_id' => $option->getId(),
'option_type' => $option->getType(),
'custom_view' => $group->isCustomizedView(),
];
}
}
}
$addOptions = $item->getOptionByCode('additional_options');
if ($addOptions) {
$options = array_merge($options, $this->serializer->unserialize($addOptions->getValue()));
}
return $options;
}
in Vendor/COptions\Block\Rewrite\Catalog\Product\View\Options\Type\Select.php:
public function getValuesHtml()
{
$_option = $this->getOption();
$configValue = $this->getProduct()->getPreconfiguredValues()->getData('options/' . $_option->getId());
$store = $this->getProduct()->getStore();
$this->setSkipJsReloadPrice(1);
// Remove inline prototype onclick and onchange events
if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN ||
$_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE
) {
$require = $_option->getIsRequire() ? ' required' : '';
$extraParams = '';
$select = $this->getLayout()->createBlock(
\Magento\Framework\View\Element\Html\Select::class
)->setData(
[
'id' => 'select_' . $_option->getId(),
'class' => $require . ' product-custom-option admin__control-select'
]
);
if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN) {
$select->setName('options[' . $_option->getid() . ']')->addOption('', __('-- Please Select --'));
} else {
$select->setName('options[' . $_option->getid() . '][]');
$select->setClass('multiselect admin__control-multiselect' . $require . ' product-custom-option');
}
foreach ($_option->getValues() as $_value) {
$priceStr = $this->_formatPrice(
[
'is_percent' => $_value->getPriceType() == 'percent',
'pricing_value' => $_value->getPrice($_value->getPriceType() == 'percent'),
],
false
);
$select->addOption(
$_value->getOptionTypeId(),
$_value->getTitle() . ' ' . strip_tags($priceStr) . '',
['price' => $this->pricingHelper->currencyByStore($_value->getPrice(true), $store, false)]
);
}
if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE) {
$extraParams = ' multiple="multiple"';
}
if (!$this->getSkipJsReloadPrice()) {
$extraParams .= ' onchange="opConfig.reloadPrice()"';
}
$extraParams .= ' data-selector="' . $select->getName() . '"';
$select->setExtraParams($extraParams);
if ($configValue) {
$select->setValue($configValue);
}
return $select->getHtml();
}
if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_RADIO ||
$_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX
) {
$selectHtml = '<div class="options-list nested" id="options-' . $_option->getId() . '-list">';
$require = $_option->getIsRequire() ? ' required' : '';
$arraySign = '';
switch ($_option->getType()) {
case \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_RADIO:
$type = 'radio';
$class = 'radio admin__control-radio';
if (!$_option->getIsRequire()) {
$selectHtml .= '<div class="field choice admin__field admin__field-option">' .
'<input type="radio" id="options_' .
$_option->getId() .
'" class="' .
$class .
' product-custom-option" name="options[' .
$_option->getId() .
']"' .
' data-selector="options[' . $_option->getId() . ']"' .
($this->getSkipJsReloadPrice() ? '' : ' onclick="opConfig.reloadPrice()"') .
' value="" checked="checked" /><label class="label admin__field-label" for="options_' .
$_option->getId() .
'"><span>' .
__('None') . '</span></label></div>';
}
break;
case \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX:
$type = 'checkbox';
$class = 'checkbox admin__control-checkbox';
$arraySign = '[]';
break;
}
$count = 1;
foreach ($_option->getValues() as $_value) {
$count++;
$priceStr = $this->_formatPrice(
[
'is_percent' => $_value->getPriceType() == 'percent',
'pricing_value' => $_value->getPrice($_value->getPriceType() == 'percent'),
]
);
$htmlValue = $_value->getOptionTypeId();
if ($arraySign) {
$checked = is_array($configValue) && in_array($htmlValue, $configValue) ? 'checked' : '';
} else {
$checked = $configValue == $htmlValue ? 'checked' : '';
}
$dataSelector = 'options[' . $_option->getId() . ']';
if ($arraySign) {
$dataSelector .= '[' . $htmlValue . ']';
}
$selectHtml .= '<div class="field choice admin__field admin__field-option' .
$require .
'">' .
'<input type="' .
$type .
'" class="' .
$class .
' ' .
$require .
' product-custom-option"' .
($this->getSkipJsReloadPrice() ? '' : ' onclick="opConfig.reloadPrice()"') .
' name="options[' .
$_option->getId() .
']' .
$arraySign .
'" id="options_' .
$_option->getId() .
'_' .
$count .
'" value="' .
$htmlValue .
'" ' .
$checked .
' data-selector="' . $dataSelector . '"' .
' price="' .
$this->pricingHelper->currencyByStore($_value->getPrice(true), $store, false) .
'" />' .
'<label class="label admin__field-label" for="options_' .
$_option->getId() .
'_' .
$count .
'"><span>' .
$_value->getTitle() .
'</span> ' .
$priceStr .
'</label>';
$selectHtml .= '</div>';
}
$selectHtml .= '</div>';
return $selectHtml;
}
}

The /e modifier is deprecated, use preg_replace_callback instead of preg_replace()

I recenlythave tried to convert the preg_replace() line to preg_replace_callback, but with no success. I did try the methods on Stackoverflow, but they seem to be different.
Hope I could get some help with it.
function ame_process_bbcode(&$parser, &$param1, $param2 = '')
{
if (class_exists('vB_BbCodeParser_Wysiwyg') AND is_a($parser, 'vB_BbCodeParser_Wysiwyg'))
{
return $text;
}
else
{
global $vbulletin;
($hook = vBulletinHook::fetch_hook('automediaembed_parse_bbcode_start')) ? eval($hook) : false;
$ameinfo = fetch_full_ameinfo();
$text = preg_replace($ameinfo['find'], $ameinfo['replace'], ($param2 ? $param2 : $param1), 1);
($hook = vBulletinHook::fetch_hook('automediaembed_parse_bbcode_end')) ? eval($hook) : false;
return $text;
}
}
Updates: Thanks to #Barmar, I know now that the issue is related to the fetch_full_ameinfo function.. I will add function below. Maybe it will help others in the long run. I will also include the fix whenever I am done. Thanks to #Barmar for the help.
function &fetch_full_ameinfo($findonly = false, $refresh = false)
{
global $db, $vbulletin, $vbphrase, $stylevar;
static $ameinfo = array();
static $inied, $lastfind;
if ($refresh)
{
$inied = false;
}
if ($lastfind && !$findonly)
{
$inied = false;
$ameinfo = array();
}
if (!$inied)
{
if (!$refresh AND $vbulletin->options['automediaembed_cache'])
{
$path = $vbulletin->options['automediaembed_cache_path'];
if (file_exists($path . "findonly.php"));
{
if ($findonly)
{
include($path . "findonly.php");
}
else
{
include($path . "ameinfo.php");
}
$inied = true;
$lastfind = $findonly;
return $ameinfo;
}
}
if ($vbulletin->options['automediaembed_resolve'])
{
$embed = ",IF(extraction=1 AND embedregexp!= '', embedregexp, '') as embedregexp, IF(extraction=1 AND validation!= '', validation, '') as validation";
$embedwhere = " AND ((extraction = 0 AND embedregexp = '') OR (extraction = 1)) ";
}
else
{
$embedwhere = " AND embedregexp = ''";
}
$sql = "SELECT findcode" . (!$findonly ? ", replacecode,title,container,ameid" : ",extraction$embed") . " FROM " . TABLE_PREFIX . "automediaembed WHERE status=1 $embedwhere
ORDER BY displayorder, title ASC";
$results = $db->query_read_slave($sql);
while ($result = $db->fetch_array($results))
{
if ($result['findcode'])
{
if (!$findonly)
{
$ameinfo['find'][] = "~($result[findcode])~ie";
$ameinfo['replace'][] = 'ame_match_bbcode($param1, $param2, \'' . $result['ameid'] . '\', \'' . ame_slasher($result['title']) . '\', ' . $result['container'] . ', \'' . ame_slasher($result['replacecode']) . '\', \'\\1\', \'\\2\', \'\\3\', \'\\4\', \'\\5\', \'\\6\')';
}
else
{
$ameinfo['find'][] = "~(\[url\]$result[findcode]\[/url\])~ie";
$ameinfo['find'][] = "~(\[url=\"?$result[findcode]\"?\](.*?)\[/url\])~ie";
$ameinfo['replace'][] = 'ame_match("\1", "", ' . intval($result['extraction']) .', "' . ($result['embedregexp'] ? "~" . ame_slasher($result['embedregexp']) . "~sim" : "") . '", "' . ($result['validation'] ? "~" . ame_slasher($result['validation']) . "~sim" : "") . '",$ameinfo)';
$ameinfo['replace'][] = 'ame_match("\1", "\2", ' . intval($result['extraction']) .', "' . ($result['embedregexp'] ? "~" . ame_slasher($result['embedregexp']) . "~sim" : "") . '", "' . ($result['validation'] ? "~" . ame_slasher($result['validation']) . "~sim" : "") . '", $ameinfo)';
}
}
}
$inied = true;
}
$lastfind = $findonly;
return $ameinfo;
}
You can't put the replacement function in fetch_full_ameinfo(), because it needs to refer to the $param1 and $param2 variables, which are local to this function.
This means it needs to use eval() in the current function (this is essentially what preg_replace() does internally when it processes the /e flag).
You need to change the replacement string that fetch_full_ameinfo() creates so that it uses a variable instead of \1, \2, etc. to refer to the capture groups, because the callback function receives the captured matches as an array. So replace the block beginning with if (!$findonly) with this:
if (!$findonly)
{
$ameinfo['find'][] = "~($result[findcode])~i";
$ameinfo['replace'][] = 'ame_match_bbcode($param1, $param2, \'' . $result['ameid'] . '\', \'' . ame_slasher($result['title']) . '\', ' . $result['container'] . ', \'' . ame_slasher($result['replacecode']) . '\', \'$match[1]\', \'$match[2]\', \'$match[3]\', \'$match[4]\', \'$match[5]\', \'$match[6]\')';
}
else
{
$ameinfo['find'][] = "~(\[url\]$result[findcode]\[/url\])~i";
$ameinfo['find'][] = "~(\[url=\"?$result[findcode]\"?\](.*?)\[/url\])~i";
$ameinfo['replace'][] = 'ame_match("$match[1]", "", ' . intval($result['extraction']) .', "' . ($result['embedregexp'] ? "~" . ame_slasher($result['embedregexp']) . "~sim" : "") . '", "' . ($result['validation'] ? "~" . ame_slasher($result['validation']) . "~sim" : "") . '",$ameinfo)';
$ameinfo['replace'][] = 'ame_match("$match[1]", "$match[2]", ' . intval($result['extraction']) .', "' . ($result['embedregexp'] ? "~" . ame_slasher($result['embedregexp']) . "~sim" : "") . '", "' . ($result['validation'] ? "~" . ame_slasher($result['validation']) . "~sim" : "") . '", $ameinfo)';
}
Then change your code to:
$text = preg_replace_callback($ameinfo['find'], function($match) use (&$param1, &$param2, &$ameinfo) {
return eval($ameinfo['replace']);
}, ($param2 ? $param2 : $param1), 1);

less < operator not recognize if I set like string PHP

I have strange problem with PHP. When I set the string like '<' and if I make new string with few strings then when is go to '<' is stop to working and go to next row of the script
$a = new SomeObject();
$a->where('id', 13332, "<");
public function where($column, $param, $operator = '=') {
echo strlen($operator);
if (isset($column) && strlen($operator) > 0) {
echo $operator;
if ($operator === '>') {
$this->_where = ' WHERE ' . $column . '>?';
} else if ($operator == '<') {
$this->_where = ' WHERE ' . $column . '<?';
} else if ($operator === '=') {
$this->_where = ' WHERE ' . $column . '=?';
} else {
$this->_where = ' WHERE ' . $column . $operator . '?';
}
$this->_where = ' WHERE ' . $column . chr(0x3c) . '?';
echo '<br/>' . $this->_where . '<br/>';
} else {
throw new \Exception('We need to have $column variable like string and $param like Param!', 500);
}
echo '<br/>c';
}
And the result is:
1< WHERE id c
And my question is why less < is cannot get like string. The > and = operators is OK. But the < just is not recognize. What I'm doing wrong?
Remove one line and it will work (test one below yourself):-
<?php
error_reporting(E_ALL); //check all type of errors
ini_set('display_errors',1); // display those if any happen
$a = new SomeObject();
$a->where('id', 13332, "<");
public function where($column, $param, $operator = '=') {
echo strlen($operator);
if (isset($column) && strlen($operator) > 0) {
echo $operator;
if ($operator === '>') {
$this->_where = ' WHERE ' . $column . '> ?'; // added space
} else if ($operator == '<') {
$this->_where = ' WHERE ' . $column . '< ?'; // added space
} else if ($operator === '=') {
$this->_where = ' WHERE ' . $column . '= ?'; // added space
} else {
$this->_where = ' WHERE ' . $column . $operator . '?';
}
//$this->_where = ' WHERE ' . $column . chr(0x3c) . '?'; remove this line
echo '<br/>' . $this->_where . '<br/>';
} else {
throw new \Exception('We need to have $column variable like string and $param like Param!', 500);
}
echo '<br/>c';
}
Note:-
Reason for not working:-
You have to add spaces too to make it correct(commented by #RiggsFolly) (For browser showing sake)
You are just over-writing your conditions. (commented and example by #JonStirling :- https://3v4l.org/vCO5Z) (for working purpose)
In this line:
$this->_where = ' WHERE ' . $column . chr(0x3e) . '?';
you overwrite your all previous changes so no wonder you can not see right result
Please try with this function and let me know will it gives you desired output
public function where($column, $param, $operator = '=') {
echo strlen($operator);
if (isset($column) && strlen($operator) > 0) {
echo $operator;
if ($operator === '>') {
$this->_where = ' WHERE ' . $column . '> ?';
} else if ($operator == '<') {
$this->_where = ' WHERE ' . $column . '< ?';
} else if ($operator === '=') {
$this->_where = ' WHERE ' . $column . '= ?';
} else {
$this->_where = ' WHERE ' . $column . $operator . ' ?';
}
if($this->_where != '')
{
$this->_where .= ' and ' . $column . chr(0x3e) . ' ?';
}
else
{
$this->_where = ' WHERE ' . $column . chr(0x3e) . ' ?';
}
echo '<br/>' . $this->_where . '<br/>';
} else {
throw new \Exception('We need to have $column variable like string and $param like Param!', 500);
}
echo '<br/>c';
}

OSCommerce price schedule inconsistent behaviour

Working on a problem with an "old" shop in OSCommerce. It's a multistore configuration which is tweaked by the previous owner. I have 2 similar products with a price schedule or quantity price break feature.
The problem is 1 of the 2 products is not reacting consistent when added to cart or showing the product page.
1st product: has a price schedule of >5, >10, >20 and >30, with prices from high to low.
2nd product: has the same schedule but is somehow shown the other way around: >30, >20, >10 and >5 with prices from low to high.
The weird thing is that the option sort_order does not exist in the price schedule table so the way that the quantity order is shown is random, but always from high to low or low to high.
The first product shows the correct price in the shopping cart, the second product always shows the highest price at any quantity, where the shopping cart should adjust the price according to the price schedule data.
Done so far without any luck:
Checked the price schedule configuration in backend
Checked product configuration in backend and rechecked in Database
Checked all related database tables
After discovering that the only difference between the products are: product name, product image and product_id, gave the product an product_id close to the working one. Also changed all the related database entry's
Make a copy of the correctly working product and add a price schedule as well.
Here is the code of the class which generates the price_schedule:
<?php
/*
$Id: price_schedule.php,v 1.0 2004/08/23 22:50:52 rmh Exp $
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2003 osCommerce
Released under the GNU General Public License
*/
/*
price_schedule.php - module to support customer classes with quantity pricing
Originally Created 2003, Beezle Software based on some code mods by WasaLab Oy (Thanks!)
Modified by Ryan Hobbs (hobbzilla)
*/
class PriceFormatter {
var $hiPrice;
var $lowPrice;
var $quantity;
var $hasQuantityPrice;
var $hasSpecialPrice;
var $qtyPriceBreaks;
function PriceFormatter($prices=NULL) {
$this->productsID = -1;
$this->hasQuantityPrice=false;
$this->hasSpecialPrice=false;
$this->hiPrice=-1;
$this->lowPrice=-1;
$this->thePrice = -1;
$this->specialPrice = -1;
$this->qtyBlocks = 1;
$this->qtyPriceBreaks = 0;
if($prices) {
$this->parse($prices);
}
}
function encode() {
$str = $this->productsID . ":"
. (($this->hasQuantityPrice == true) ? "1" : "0") . ":"
. (($this->hasSpecialPrice == true) ? "1" : "0") . ":"
. $this->quantity[1] . ":"
. $this->quantity[2] . ":"
. $this->quantity[3] . ":"
. $this->quantity[4] . ":"
. $this->price[1] . ":"
. $this->price[2] . ":"
. $this->price[3] . ":"
. $this->price[4] . ":"
. $this->thePrice . ":"
. $this->specialPrice . ":"
. $this->qtyBlocks . ":"
. $this->taxClass;
return $str;
}
function decode($str) {
list($this->productsID,
$this->hasQuantityPrice,
$this->hasSpecialPrice,
$this->quantity[1],
$this->quantity[2],
$this->quantity[3],
$this->quantity[4],
$this->price[1],
$this->price[2],
$this->price[3],
$this->price[4],
$this->thePrice,
$this->specialPrice,
$this->qtyBlocks,
$this->taxClass) = explode(":", $str);
$this->hasQuantityPrice = (($this->hasQuantityPrice == 1) ? true : false);
$this->hasSpecialPrice = (($this->hasSpecialPrice == 1) ? true : false);
}
function parse($prices) {
global $customer_group_id, $customer_group_type, $customer_group_discount;
if (!tep_not_null($customer_group_id)) {
$customer_group_id = VISITOR_PRICING_GROUP;
$check_group_query = tep_db_query("select customers_groups_type, customers_groups_discount from " . TABLE_CUSTOMERS_GROUPS . " where customers_groups_id = '" . (int)$customer_group_id . "'");
$check_group = tep_db_fetch_array($check_group_query);
$customer_group_type = $check_group['customers_groups_type'];
$customer_group_discount = $check_group['customers_groups_discount'];
}
$this->productsID = $prices['products_id'];
$this->hasQuantityPrice=false;
$this->hasSpecialPrice=false;
// if ($customer_group_type != '1') {
// $price_schedule_query = tep_db_query("select products_groups_price, products_groups_price_qty FROM " . TABLE_PRODUCTS_PRICE_SCHEDULES . " WHERE products_id = '" . $prices['products_id'] . "' and customers_groups_id = '" . (int)$customer_group_id . "' and stores_id = '" . STORES_ID . "'");
$price_schedule_query = tep_db_query("select products_groups_price, products_groups_price_qty FROM " . TABLE_PRODUCTS_PRICE_SCHEDULES . " WHERE products_id = '" . $prices['products_id'] . "' and stores_id = '" . STORES_ID . "'");
$this->qtyPriceBreaks = tep_db_num_rows($price_schedule_query);
$this->thePrice = $prices['products_price'];
$this->specialPrice = $prices['specials_new_products_price'];
// } else {
// $this->qtyPriceBreaks = 0;
// $this->thePrice = $prices['products_price'] * (100 - $customer_group_discount)/100;
// $this->specialPrice = $prices['specials_new_products_price'];
// if ($this->thePrice < $this->specialPrice) $this->specialPrice = "";
// }
$this->hiPrice = $this->thePrice;
$this->lowPrice = $this->thePrice;
$this->hasSpecialPrice = tep_not_null($this->specialPrice);
$this->qtyBlocks = $prices['products_qty_blocks'];
$this->taxClass=$prices['products_tax_class_id'];
$n = 0;
if ($this->qtyPriceBreaks > 0 ) {
while ($price_schedule = tep_db_fetch_array($price_schedule_query)) {
$this->price[$n]=$price_schedule['products_groups_price'];
$this->quantity[$n]=$price_schedule['products_groups_price_qty'];
if ($this->quantity[$n] == '1') {
$this->thePrice = $this->price[$n];
$this->hiPrice = $this->thePrice;
$this->lowPrice = $this->thePrice;
} else {
$this->hasQuantityPrice = true;
}
$n += 1;
}
}
for($i=0; $i<$this->qtyPriceBreaks; $i++) {
if ($this->hasSpecialPrice == true) {
$this->hiPrice = $this->specialPrice;
if ($this->price[$i] > $this->specialPrice) {
$this->price[$i] = $this->specialPrice;
}
}
if ($this->hasQuantityPrice == true) {
if ($this->price[$i] > $this->hiPrice) {
$this->hiPrice = $this->price[$i];
}
if ($this->price[$i] < $this->lowPrice) {
$this->lowPrice = $this->price[$i];
}
}
}
}
function loadProduct($product_id, $language_id=1)
{
$sql="select pd.products_name, p.products_model, p.products_image, p.products_leadtime, p.products_id, p.manufacturers_id, p.products_price, p.products_weight, p.products_unit, p.products_qty_blocks, p.products_tax_class_id, p.distributors_id, IF(s.status = '1' AND s.stores_id = '" . STORES_ID . "', s.specials_new_products_price, NULL) as specials_new_products_price, IF(s.status = '1' AND s.stores_id = '" . STORES_ID . "', s.specials_new_products_price, p.products_price) as final_price from " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c, ((" . TABLE_PRODUCTS . " p left join " . TABLE_MANUFACTURERS . " m on p.manufacturers_id = m.manufacturers_id, " . TABLE_PRODUCTS_DESCRIPTION . " pd) left join " . TABLE_SPECIALS . " s on p.products_id = s.products_id and s.stores_id = '" . STORES_ID . "') INNER JOIN " . TABLE_PRODUCTS_TO_STORES . " p2s ON p.products_id = p2s.products_id where p2s.stores_id = '" . STORES_ID . "' AND p.products_status = '1' and p.products_id = '" . (int)$product_id . "' and pd.products_id = '" . (int)$product_id . "' and pd.language_id = '". (int)$language_id ."'";
$product_info_query = tep_db_query($sql);
$product_info = tep_db_fetch_array($product_info_query);
$this->parse($product_info);
return $product_info;
}
function computePrice($qty) {
$qty = $this->adjustQty($qty);
$price = $this->thePrice;
if ($this->hasSpecialPrice == true) {
$price = $this->specialPrice;
}
if ($this->hasQuantityPrice == true) {
for ($i=0; $i<$this->qtyPriceBreaks; $i++) {
if (($this->quantity[$i] > 0) && ($qty >= $this->quantity[$i])) {
$price = $this->price[$i];
}
}
}
return $price;
}
// Force QTY_BLOCKS granularity
function adjustQty($qty) {
$qb = $this->getQtyBlocks();
if ($qty < 1) {
$qty = 0;
return $qty;
}
if ($qb >= 1) {
if ($qty < $qb) {
$qty = $qb;
}
if (($qty % $qb) != 0) {
$qty += ($qb - ($qty % $qb));
}
}
return $qty;
}
function getQtyBlocks() {
return $this->qtyBlocks;
}
function getPrice() {
return $this->thePrice;
}
function getLowPrice() {
return $this->lowPrice;
}
function getHiPrice() {
return $this->hiPrice;
}
function hasSpecialPrice() {
return $this->hasSpecialPrice;
}
function hasQuantityPrice() {
return $this->hasQuantityPrice;
}
function getPriceString($style='productPriceInBox') {
global $currencies, $customer_id;
// If you want to change the format of the price/quantity table
// displayed on the product information page, here is where you do it.
if (($this->hasSpecialPrice == true) && ($this->hasQuantityPrice == false)) {
$lc_text = ' <s>' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</s> <span class="productSpecialPrice">' . $currencies->display_price($this->specialPrice, tep_get_tax_rate($this->taxClass)) . '</span>';
}
if($this->hasQuantityPrice == true) {
$lc_text = '<table align="top" border="0" cellspacing="0" cellpadding="0"><tr><td align="center" colspan="2"><b>' . ($this->hasSpecialPrice == true ? '<s>' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</s> <span class="productSpecialPrice">' . $currencies->display_price($this->specialPrice, tep_get_tax_rate($this->taxClass)) . '</span> ' : 'vanaf ' . $currencies->display_price($this->lowPrice, tep_get_tax_rate($this->taxClass)) ) . '</b></td></tr>';
for($i=0; $i<=$this->qtyPriceBreaks; $i++) {
if(($this->quantity[$i] > 0) && ($this->price[$i] > $this->specialPrice)) {
$lc_text .= '<tr><td class='.$style.' align="right">> ' . $this->quantity[$i] . ' </td><td class='.$style.'>' . $currencies->display_price($this->price[$i], tep_get_tax_rate($this->taxClass)) . '</td></tr>';
}
}
$lc_text .= '</table>';
} else {
if ($this->hasSpecialPrice == true) {
$lc_text = ' <s>' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</s> <span class="productSpecialPrice">' . $currencies->display_price($this->specialPrice, tep_get_tax_rate($this->taxClass)) . '</span>';
} else {
$lc_text = ' ' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '';
}
}
// if (VISITOR_PRICING_GROUP < '0' && !tep_session_is_registered('customer_id')) {
// return '';
// } else {
return $lc_text;
// }
}
function getPriceStringShort() {
global $currencies, $customer_id;
if (($this->hasSpecialPrice == true) && ($this->hasQuantityPrice == false)) {
$lc_text = '<div class="priceold">' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</div><div class="pricenew">' . $currencies->display_price($this->specialPrice, tep_get_tax_rate($this->taxClass)) . '</div>';
} elseif ($this->hasQuantityPrice == true) {
$lc_text = '<div class="vanaf">vanaf</div><div class="price">' . $currencies->display_price($this->lowPrice, tep_get_tax_rate($this->taxClass)) . ' </div>';
} else {
$lc_text = '<div class="price">' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</div>';
}
// if (VISITOR_PRICING_GROUP < '0' && !tep_session_is_registered('customer_id')) {
// return TEXT_LOGIN_TO_SEE_PRICES;
// } else {
return $lc_text;
// }
}
}
?>
I'm not experienced enough to decipher the class and find strange things, if you need more info, do not hesitate to ask.
Any help would be apreciated.
As I understand your question, you would like the product prices to be ordered consistently. I'm aware of the addons you mention but I'm not very familiar with them. That being said you can try to change this line...
$price_schedule_query = tep_db_query("select products_groups_price, products_groups_price_qty FROM " . TABLE_PRODUCTS_PRICE_SCHEDULES . " WHERE products_id = '" . $prices['products_id'] . "' and stores_id = '" . STORES_ID . "'");
to
$price_schedule_query = tep_db_query("select products_groups_price, products_groups_price_qty FROM " . TABLE_PRODUCTS_PRICE_SCHEDULES . " WHERE products_id = '" . $prices['products_id'] . "' and stores_id = '" . STORES_ID . "'" . " ORDER BY products_groups_price ASC");
As I said, I'm not familiar with exactly how the addons you mentioned work but I'd start by adding ordering to the mysql query. This approach has worked for me on numerous occasions with various addons.

Categories