Related
I have a PHP tree structure (array max depth: 5):
$arr = array(
'31' => array(
'Amsterdam' => array(),
'Rotterdam' => array(),
'Den Haag' => array(),
'Utrecht' => array(),
'Eindhoven' => array(),
'Tilburg' => array(),
'Almere' => array(
'036' => array(
'BU00340212' => array(
'name' => 'Muziekwijk Noord',
'residents' => array(
'Henk',
'Dirk',
'Jaap',
),
),
'BU00340213' => array(
'name' => 'Muziekwijk Zuid',
'residents' => array(
'Wim',
'Pim',
'Jim',
'Tim',
),
),
)
),
'Groningen' => array(),
'Breda' => array(),
'Nijmegen' => array(),
)
);
I would like to have this output:
Almere(netnummer: 036)(cbscode: BU00340212): Henk
Almere(netnummer: 036)(cbscode: BU00340212): Dirk
Almere(netnummer: 036)(cbscode: BU00340212): Jaap
Almere(netnummer: 036)(cbscode: BU00340213): Wim
Almere(netnummer: 036)(cbscode: BU00340213): Pim
Almere(netnummer: 036)(cbscode: BU00340213): Jim
Almere(netnummer: 036)(cbscode: BU00340213): Tim
So I did some coding by myself. The code below produces the output that I want.
foreach($arr as $unitKey => $citySet){
foreach($citySet as $cityName => $cityData){
if($cityName === 'Almere'){
$almere = $citySet[$cityName];
foreach($almere as $netnummer => $netData){
foreach($netData as $cbsCode => $data){
foreach($data['residents'] as $residents){
echo $cityName . '(netnummer: '. $netnummer .')(cbscode: '. $cbsCode .'): ' . $residents . '<br>';
}
}
}
}
}
}
The code displayed above makes use of 5 foreaches, and I'm doubting if that's a good idea. So I tried to reduce a couple foreaches like this:
$arrB = $arr['31']['Almere']['036'];
foreach($arrB as $k => $netData){
foreach($netData as $field => $fieldData){
if($field === 'residents') {
foreach($fieldData as $resident){
echo 'Almere(netnummer: 036)(cbscode: '. $k .'): ' . $resident . '<br>';
}
}
}
}
The code displayed above makes use of 3 foreaches. That is because it doesn't traverse the full tree.
I want to traverse the full tree with 1 foreach, and produce the output I was aiming for. So I was thinking about RecursiveArray in combination with RecursiveIteratorIterator, but I can't get the cbscode if I use this approach. See for yourself:
$recursiveArrayIterator = new RecursiveArrayIterator($arr);
$recursiveIteratorIterator = new RecursiveIteratorIterator($recursiveArrayIterator);
foreach($recursiveIteratorIterator as $k => $v){
if($k !== 'name'){
echo 'Almere(netnummer: 036)(cbscode: ???): ' . $v . '<br>';
}
}
Q1: is this possible to traverse the tree structure with one foreach with the shown output?
Q2:if it is possible, can you show the code? if not, is it possible to reduce the amount of used foreaches to 2?
-- Edit --
Q (rephrased): What is most readable way to fully traverse an 5 level deep array?
You can short this down to:
$arrB = $arr['31']['Almere']['036'];
foreach($arrB as $code => $val) {
if (isset($val["residents"])) {
$prefix = 'Almere(netnummer: 036)(cbscode: '. $code .'): ';
echo $prefix . implode('<br>' . $prefix, $val["residents"]) . '<br>';
}
}
Live example: 3v4l
I invested some time in this problem, and came with a functional programming approach:
function recursive($data, $countryCode = null, $countryData = null, $city = null, $cityData = null, $netNummer = null, $netData = null, $cbscode = null, $cbsData = null, $residents = null){
if($residents){
$resident = array_shift($residents);
echo $city . '(netnummer: ' . $netNummer . ')(cbscode: ' . $cbscode .'): ' . $resident . '<br>';
if($residents){
recursive($data, $countryCode, $countryData, $city, $cityData, $netNummer, $netData, $cbscode, $cbsData, $residents);
}
return null;
}
if($cbscode && $cbsData){
$residents = $cbsData['residents'];
recursive($data, $countryCode, $countryData, $city, $cityData, $netNummer, $netData, $cbscode, $cbsData, $residents);
}
if($countryCode && $countryData && $netData){
$cbscode = key($netData);
$cbsData = array_shift($netData);
recursive($data, $countryCode, $countryData, $city, $cityData, $netNummer, $netData, $cbscode, $cbsData);
}
if($countryCode && $countryData && $city && $cityData){
$netNummer = key($cityData);
$netData = array_shift($cityData);
recursive($data, $countryCode, $countryData, $city, $cityData, $netNummer, $netData);
}
if($countryCode && $countryData){
$city = key($countryData);
$cityData = array_shift($countryData);
recursive($data, $countryCode, $countryData, $city, $cityData);
}
if($data){
$countryCode = key($data);
$countryData = array_shift($data);
if($countryData){
recursive($data, $countryCode, $countryData);
}
}
return null;
}
recursive($arr);
Online source: https://3v4l.org/rsf5o
I'm trying to integrate payzone payment in wordpress and getting some error. I've done some code to take remaining payment after the order is processed via woocommerce..The site takes certain amount via woocommerce payzone plugin and final amount via custom payzone hosted form..The error im getting is below:
"This transaction cannot be processed. The submitted data was rejected for a SECURITY reason: HashDigest does not match."
The merchant detials are correct and working fine with woocommerce but custom integration is giving me errors..I tried but couldnt trackt the error yet! Below is my code to create the hashdigest
public static function calculate_hash_digest($string, $pre_shared_key, $hash_method) {
switch($hash_method) {
case "MD5":
$hash_digest = md5($string);
break;
case "SHA1":
$hash_digest = sha1($string);
break;
case "HMACMD5":
$hash_digest = hash_hmac("md5", $string, $pre_shared_key);
break;
case "HMACSHA1":
$hash_digest = hash_hmac("sha1", $string, $pre_shared_key);
break;
}
return $hash_digest;
}
public static function get_country_code($country_code) {
$code = 826;
switch ($country_code ) {
case 'GB':
$code = 826;
break;
case 'US':
$code = 840;
break;
case 'AU':
$code = 36;
break;
case 'CA':
$code = 124;
break;
default;
$code = 826;
break;
}
return $code;
}
public static function payzone_settings($key) {
$settings = get_option('woocommerce_payzone_settings');
if($key) {
if(array_key_exists($key, $settings)) {
return $settings[$key];
}
}
else {
return $settings;
}
}
public static function generate_string_to_hash(
$merchant_id,
$merchant_password,
$amount,
$country_code,
$order_id,
$transaction_type,
$transaction_date_time,
$callback_url,
$order_description,
$customer_name,
$billing_address_1,
$billing_address_2,
$billing_address_3,
$billing_address_4,
$billing_city,
$billing_state,
$billing_postcode,
$billing_country,
$CV2_mandatory,
$address1_mandatory,
$city_mandatory,
$postcode_mandatory,
$state_mandatory,
$country_mandatory,
$result_delivery_method,
$server_result_url,
$payment_form_displays_result,
$pre_shared_key,
$hash_method,
$billing_email,
$billing_phone
)
{
$return_string = "";
switch($hash_method) {
case "MD5":
$include_pre_shared_key_in_string = true;
break;
case "SHA1":
$include_pre_shared_key_in_string = true;
break;
case "HMACMD5":
$include_pre_shared_key_in_string = false;
break;
case "HMACSHA1":
$include_pre_shared_key_in_string = false;
break;
}
if($include_pre_shared_key_in_string) {
$return_string = "PreSharedKey=" . $pre_shared_key . "&";
}
$return_string .=
"MerchantID=" .
$merchant_id .
"&Password=" .
$merchant_password.
"&Amount=" .
$amount .
"&CurrencyCode=" .
$country_code .
"&EchoAVSCheckResult=true" .
"&EchoCV2CheckResult=true" .
"&EchoThreeDSecureAuthenticationCheckResult=true" .
"&EchoCardType=true" .
"&OrderID=" .
$order_id .
"&TransactionType=" .
$transaction_type .
"&TransactionDateTime=" .
$transaction_date_time .
"&CallbackURL=" .
$callback_url .
"&OrderDescription=" .
$order_description .
"&CustomerName=" .
$customer_name .
"&Address1=" .
$billing_address_1 .
"&Address2=" .
$billing_address_2 .
"&Address3=" .
$billing_address_3.
"&Address4=" .
$billing_address_4.
"&City=" .
$billing_city .
"&State=" .
$billing_state .
"&PostCode=" .
$billing_postcode .
"&CountryCode=" .
$billing_country .
"&EmailAddress=" .
$billing_email .
"&PhoneNumber=" .
$billing_phone .
"&CV2Mandatory=" .
$CV2_mandatory .
"&Address1Mandatory=" .
$address1_mandatory .
"&CityMandatory=" .
$city_mandatory .
"&PostCodeMandatory=" .
$postcode_mandatory .
"&StateMandatory=" .
$state_mandatory .
"&CountryMandatory=" .
$country_mandatory .
"&ResultDeliveryMethod=
".$result_delivery_method."
&ServerResultURL=" .
$server_result_url .
"&PaymentFormDisplaysResult=" .
$payment_form_displays_result.
"&ServerResultURLCookieVariables=" .
"&ServerResultURLFormVariables=" .
"&ServerResultURLQueryStringVariables=";
return $return_string;
}
public static function get_hosted_payment_form_args(
$callback_url,
$server_result_url,
$order_id,
$amount = 0
) {
$order = new WC_Order( $order_id );
$transaction_date_time = date('Y-m-d H:i:s P');
$currency = get_option('woocommerce_currency');
$country_code = self::get_country_code($currency);
$settings = self::payzone_settings();
$mode = $settings['test_mode'];
$merchant_id = $mode == 'yes' ? $settings['test_mid'] : $settings['live_mid'];
$merchant_password = $mode == 'yes' ? $settings['test_password'] : $settings['live_password'];
$pre_shared_key = $settings['pre_shared_key'];
$hash_method = $settings['hash_method'];
$transaction_type = $settings['transaction_type'];
$string_to_hash =
self::generate_string_to_hash(
$merchant_id,
$merchant_password,
$amount,
$country_code ,
$order->get_id(),
$transaction_type,
$transaction_date_time,
$callback_url,
'Rental Remaining Payment for Order '.$order->get_id(),
$order->billing_first_name.' '.$order->billing_last_name,
$order->billing_address_1,
$order->billing_address_2,
'',
'',
$order->billing_city,
$order->billing_state,
$order->billing_postcode,
$country_code,
"true",
"false",
"false",
"false",
"false",
"false",
'POST',
$server_result_url,
'false',
$pre_shared_key ,
$hash_method,
$order->billing_email,
$order->billing_phone
);
return array(
'HashDigest' => self::calculate_hash_digest($string_to_hash , $pre_shared_key, $hash_method),
'MerchantID' => $merchant_id,
'Amount' => (string) $amount,
'CurrencyCode' => (string) $country_code ,
'EchoAVSCheckResult' => "true",
'EchoCV2CheckResult' => "true",
'EchoThreeDSecureAuthenticationCheckResult' => "true",
'EchoCardType' => "true",
'OrderID' => (string) $order->get_id(),
'TransactionType' => $transaction_type,
'TransactionDateTime' => $transaction_date_time,
'CallbackURL' => $callback_url,
'OrderDescription' => 'Rental Remaining Payment for Order '.$order->get_id(),
'CustomerName' => $order->billing_first_name.' '.$order->billing_last_name,
'Address1' => $order->billing_address_1,
'Address2' => $order->billing_address_2,
'Address3' => "",
'Address4' => "",
'City' => $order->billing_city,
'State' => $order->billing_state,
'Postcode' => $order->billing_postcode,
'CountryCode' => (string) $country_code,
'EmailAddress' => $order->billing_email,
'PhoneNumber' => $order->billing_phone,
'CV2Mandatory' => "true",
'Address1Mandatory' => "false",
'CityMandatory' => "false",
'PostCodeMandatory' => "false",
'StateMandatory' => "false",
'CountryMandatory' => "false",
'ResultDeliveryMethod' => 'POST',
'ServerResultURL' => $server_result_url,
'PaymentFormDisplaysResult' => 'false',
'ServerResultURLCookieVariables' => "",
'ServerResultURLFormVariables' => "",
'ServerResultURLQueryStringVariables' => ""
);
}
Any help is really appreciated!!
I have problem with upload field. Error page image
Actualy when I add upload field to form script gives an error.
The server gives an error for this line: $filenamefields[$group]['sub']
foreach ($fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$min_req = true;
if (isset($fieldlist['sub'])) {
$this->customrule_addrec(
$fieldlist['sub'],
$required, $title,
$type,
$gprefix.'[' . $group . '][sub]',
$filenamefields[$group]['sub'],
$filetypefields[$group]['sub'],
$filetmpnamefields[$group]['sub'],
$fileerrorfields[$group]['sub'],
$filesizefields[$group]['sub']);
and this line: $this->files['size']['fields']);
$min_req = $this->customrule_addrec($fields, $required, $title, $type, '',
$this->files['name']['fields'],
$this->files['type']['fields'],
$this->files['tmp_name']['fields'],
$this->files['error']['fields'],
$this->files['size']['fields']);
if (!$min_req)
$this->addError($attribute, 'Select a group');
file codes :
<?php
class Orders extends CActiveRecord
{
public $fields;
public $files;
public $file;
public $remove;
public function tableName()
{
return 'orders';
}
public function rules()
{
return array(
array(
'name, start_date, ordertype, user',
'required'
),
array(
'status, ordertype, user',
'numerical',
'integerOnly' => true
),
array(
'name',
'length',
'max' => 200
),
array(
'finish_date, desc',
'safe'
),
array(
'id, name, start_date, finish_date, status, ordertype, user, desc',
'safe',
'on' => 'search'
),
array(
'fields,files',
'safe'
),
array(
'fields',
'customrule_add',
'on' => 'add'
),
array(
'fields',
'customrule_edit',
'on' => 'edit'
),
array(
'file, remove',
'safe',
'on' => 'answer'
)
);
}
public function customrule_add($attribute, $params)
{
$fieldtypes = Orderfield::model()->findAll('ordergroup in (select id from ' . Ordergroup::model()->tableName() . ' where orderform = \'' . $this->ordertype . '\')');
$required = CHtml::listData($fieldtypes, 'id', 'required');
$title = CHtml::listData($fieldtypes, 'id', 'name');
$type = CHtml::listData($fieldtypes, 'id', 'type');
$fields = $this->$attribute;
$min_req = $this->customrule_addrec($fields, $required, $title, $type, '',
$this->files['name']['fields'],
$this->files['type']['fields'],
$this->files['tmp_name']['fields'],
$this->files['error']['fields'],
$this->files['size']['fields']);
if (!$min_req)
$this->addError($attribute, 'Select a group');
}
private function customrule_addrec($fields, $required, $title, $type, $gprefix, $filenamefields, $filetypefields, $filetmpnamefields, $fileerrorfields, $filesizefields)
{
$min_req = false;
foreach ($fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$min_req = true;
if (isset($fieldlist['sub'])) {
$this->customrule_addrec(
$fieldlist['sub'],
$required, $title,
$type,
$gprefix.'[' . $group . '][sub]',
$filenamefields[$group]['sub'],
$filetypefields[$group]['sub'],
$filetmpnamefields[$group]['sub'],
$fileerrorfields[$group]['sub'],
$filesizefields[$group]['sub']);
foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
if (isset($sfieldlist['active']) && $sfieldlist['active']) {
foreach ($sfieldlist as $key => $value) {
if (($key != 'active') && ($key != 'sub') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'Value ' . $title[$key] . ' Can not be empty');
} else if (!isset($this->files['name']['fields'][$group]['sub'][$sgroup][$key]) || !$this->files['name']['fields'][$group]['sub'][$sgroup][$key]) {
$this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'File ' . $title[$key] . ' Must send');
}
}
}
}
}
}
foreach ($fieldlist as $key => $value) {
if (($key != 'active') && ($key != 'sub') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields' . $gprefix . '[' . $group . '][' . $key . ']', 'Value ' . $title[$key] . ' Can not be empty');
} else if (!isset($filenamefields[$group][$key]) || !$filenamefields[$group][$key]) {
$this->addError('fields' . $gprefix . '[' . $group . '][' . $key . ']', 'File ' . $title[$key] . ' Must send');
}
}
}
}
}
return $min_req;
}
public function customrule_edit($attribute, $params)
{
$fieldtypes = Orderfield::model()->findAll('ordergroup in (select id from ' . Ordergroup::model()->tableName() . ' where orderform = \'' . $this->ordertype . '\')');
$required = CHtml::listData($fieldtypes, 'id', 'required');
$title = CHtml::listData($fieldtypes, 'id', 'name');
$type = CHtml::listData($fieldtypes, 'id', 'type');
$groups = CHtml::listData(Ordergroup::model()->findAll(array(
'select' => 'id,name,orderform',
'condition' => 'orderform = \'' . $this->ordertype . '\''
)), 'id', 'name');
$fields = $this->$attribute;
$min_req = false;
foreach ($fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$min_req = true;
if (isset($fieldlist['sub'])) {
foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
if (isset($sfieldlist['active']) && $sfieldlist['active']) {
foreach ($sfieldlist as $key => $value) {
if (($key != 'active') && ($key != 'sub') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'value ' . $title[$key] . ' Can not be empty');
}
}
}
}
}
}
foreach ($fieldlist as $key => $value) {
if (($key != 'active') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields[' . $group . '][' . $key . ']', 'value ' . $title[$key] . 'Can not be empty');
}
}
}
}
}
if (!$min_req)
$this->addError($attribute, 'Choose a group');
}
public function add()
{
$name = $this->name;
$exists = Orders::model()->exists('`name` = \'' . $name . '\'');
if ($exists) {
$count = Orders::model()->count('`name` regexp \'^' . $name . ' - [0-9]+$\'');
$this->name = $name . ' - ' . ($count + 2);
}
$status = $this->save();
$status = $this->addsub(
$this->fields,
$status,
$this->files['name']['fields'],
$this->files['type']['fields'],
$this->files['tmp_name']['fields'],
$this->files['error']['fields'],
$this->files['size']['fields']
);
if (!$status) {
Ordervalues::model()->deleteAllByAttributes(array(
'order' => $this->id
));
GroupOfOrder::model()->deleteAllByAttributes(array(
'order' => $this->id
));
$this->delete();
return false;
}
return true;
}
private function addsub($thisfields, $status, $filenamefields, $filetypefields, $filetmpnamefields, $fileerrorfields, $filesizefields)
{
foreach ($thisfields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active'] && $status) {
$gofo = new GroupOfOrder('insert');
$gofo->group = $group;
$gofo->order = $this->id;
$gofo->save();
if (isset($fieldlist['sub'])) {
$status = $this->addsub(
$fieldlist['sub'],
$status,
$filenamefields[$group]['sub'],
$filetypefields[$group]['sub'],
$filetmpnamefields[$group]['sub'],
$fileerrorfields[$group]['sub'],
$filesizefields[$group]['sub']
);
if(!$status)
return false;
}
foreach ($fieldlist as $key => $value) {
if ($key != 'active' && $key != 'sub' && $status) {
$ftype = Orderfield::model()->findByPk($key);
if (!$ftype) {
$this->addError('fields', 'Field type error');
Ordervalues::model()->deleteAllByAttributes(array(
'order' => $this->id
));
GroupOfOrder::model()->deleteAllByAttributes(array(
'order' => $this->id
));
$this->delete();
return false;
}
if (!empty($value)) {
$field = new Ordervalues('insert');
$field->field = $key;
$field->order = $this->id;
$field->value = $value;
$status = ($status && $field->save());
} elseif (isset($filenamefields[$group][$key]) && !empty($filenamefields[$group][$key])) {
$file = new CUploadedFile($filenamefields[$group][$key], $filetmpnamefields[$group][$key], $filetypefields[$group][$key], $filesizefields[$group][$key], $fileerrorfields[$group][$key]);
if ($ftype->file_type) {
$all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
$allowed = false;
foreach ($all as $ex) {
if ($ex == $file->extensionName) {
$allowed = true;
break;
}
}
if (!$allowed) {
$this->addError('files', 'This format' . $file->extensionName . 'is not true');
Ordervalues::model()->deleteAllByAttributes(array(
'order' => $this->id
));
GroupOfOrder::model()->deleteAllByAttributes(array(
'order' => $this->id
));
$this->delete();
return false;
}
}
$ffield = new Ordervalues('insert');
$ffield->field = $key;
$ffield->order = $this->id;
$ffield->value = $file->name;
$ffield->file_size = $file->size;
$status = ($status && $ffield->save());
$status = ($status && $file->saveAs('files/' . $ffield->id));
}
}
}
}
}
return true;
}
public function edit()
{
$status = true;
foreach ($this->fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$gofo = GroupOfOrder::model()->findByAttributes(array(
'order' => $this->id,
'group' => $group
));
if (!$gofo) {
$gofo = new GroupOfOrder('insert');
$gofo->group = $group;
$gofo->order = $this->id;
$gofo->save();
}
if (isset($fieldlist['sub'])) {
foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
if (isset($sfieldlist['active']) && $sfieldlist['active']) {
$sgofo = GroupOfOrder::model()->findByAttributes(array(
'order' => $this->id,
'group' => $sgroup
));
if (!$sgofo) {
$sgofo = new GroupOfOrder('insert');
$sgofo->group = $sgroup;
$sgofo->order = $this->id;
$sgofo->save();
}
foreach ($sfieldlist as $key => $value) {
if ($key != 'active' && $key != 'sub' && $status) {
$ftype = Orderfield::model()->findByPk($key);
if (!$ftype) {
$this->addError('fields', 'Field type error');
return false;
}
if (!empty($value)) {
$field = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$field) {
$field = new Ordervalues('insert');
$field->field = $key;
$field->order = $this->id;
}
$field->value = $value;
$status = ($status && $field->save());
} elseif (isset($this->files['name']['fields'][$group]['sub'][$sgroup][$key]) && !empty($this->files['name']['fields'][$group]['sub'][$sgroup][$key])) {
$file = new CUploadedFile($this->files['name']['fields'][$group]['sub'][$sgroup][$key], $this->files['tmp_name']['fields'][$group]['sub'][$sgroup][$key], $this->files['type']['fields'][$group]['sub'][$sgroup][$key], $this->files['size']['fields'][$group]['sub'][$sgroup][$key], $this->files['error']['fields'][$group]['sub'][$sgroup][$key]);
if ($ftype->file_type) {
$all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
$allowed = false;
foreach ($all as $ex) {
if ($ex == $file->extensionName) {
$allowed = true;
break;
}
}
if (!$allowed) {
$this->addError('files', 'This format ' . $file->extensionName . ' is not true');
return false;
}
}
$ffield = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$ffield) {
$ffield = new Ordervalues('insert');
$ffield->field = $key;
$ffield->order = $this->id;
}
$ffield->value = $file->name;
$ffield->file_size = $file->size;
$status = ($status && $ffield->save());
$status = ($status && $file->saveAs('files/' . $ffield->id));
}
}
}
}
}
}
foreach ($fieldlist as $key => $value) {
if ($key != 'active' && $key != 'sub' && $status) {
$ftype = Orderfield::model()->findByPk($key);
if (!$ftype) {
$this->addError('fields', 'Field error');
return false;
}
if (!empty($value)) {
$field = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$field) {
$field = new Ordervalues('insert');
$field->field = $key;
$field->order = $this->id;
}
$field->value = $value;
$status = ($status && $field->save());
} elseif (isset($this->files['name']['fields'][$group][$key]) && !empty($this->files['name']['fields'][$group][$key])) {
$file = new CUploadedFile($this->files['name']['fields'][$group][$key], $this->files['tmp_name']['fields'][$group][$key], $this->files['type']['fields'][$group][$key], $this->files['size']['fields'][$group][$key], $this->files['error']['fields'][$group][$key]);
if ($ftype->file_type) {
$all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
$allowed = false;
foreach ($all as $ex) {
if ($ex == $file->extensionName) {
$allowed = true;
break;
}
}
if (!$allowed) {
$this->addError('files', 'This format ' . $file->extensionName . ' is not true');
return false;
}
}
$ffield = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$ffield) {
$ffield = new Ordervalues('insert');
$ffield->field = $key;
$ffield->order = $this->id;
}
$ffield->value = $file->name;
$ffield->file_size = $file->size;
$status = ($status && $ffield->save());
$status = ($status && $file->saveAs('files/' . $ffield->id));
}
}
}
} else {
$gofo = GroupOfOrder::model()->findByAttributes(array(
'order' => $this->id,
'group' => $group
));
if ($gofo) {
$gofo->delete();
$ovs = Ordervalues::model()->findAll('order = ' . $this->id . ' AND field in (select id from ' . Orderfield::model()->tableName() . ' where ordergroup=' . $group . ')');
foreach ($ovs as $ov) {
if ($ov->field0->type == 2)
unlink(Yii::app()->getBasePath() . '/../files/' . $ov->id);
$ov->delete();
}
}
}
}
$status = ($status && $this->save());
return $status;
}
public function answer()
{
if ($this->remove) {
foreach ($this->remove as $id => $f) {
if ($f) {
$filemodel = Orderfiles::model()->findByAttributes(array(
'id' => $id,
'order_id' => $this->id
));
if ($filemodel) {
$filemodel->delete();
$path = Yii::app()->basePath . '/../files/answers/' . $id;
if (file_exists($path))
unlink($path);
}
}
}
}
$file = CUploadedFile::getInstance($this, 'file');
if ($file) {
$fm = new Orderfiles('insert');
$fm->name = $file->name;
$fm->size = $file->size;
$fm->order_id = $this->id;
if ($fm->save() && $this->save())
return $file->saveAs('files/answers/' . $fm->id);
return false;
}
return $this->save();
}
public function fill_in_fields()
{
$this->fields = array();
foreach ($this->ordervalues as $field) {
$f = $field->field0;
if (!isset($this->fields[$f->ordergroup]['active']))
$this->fields[$f->ordergroup]['active'] = true;
$this->fields[$f->ordergroup][$f->id] = $field->value;
}
}
public function getPrice()
{
return Yii::app()->db->createCommand('select sum(price) from ' . Ordergroup::model()->tableName() . ' where id in (select `group` from ' . GroupOfOrder::model()->tableName() . ' where `order` = ' . $this->id . ')')->queryScalar();
}
public function deleteTree()
{
$ovsff = Ordervalues::model()->findAll('`order` = ' . $this->id . ' AND field in (select id from ' . Orderfield::model()->tableName() . ' where type = 2)');
if ($ovsff) {
foreach ($ovsff as $value) {
$path = Yii::app()->getBasePath() . '/../files/' . $value->id;
if (file_exists($path))
unlink($path);
}
}
Ordervalues::model()->deleteAll('`order` = ' . $this->id);
GroupOfOrder::model()->deleteAll('`order` = ' . $this->id);
$status = true;
$ovsff = Orderfiles::model()->findAll('`order_id` = ' . $this->id); // files of answered orders
if ($ovsff) {
foreach ($ovsff as $value) {
$path = Yii::app()->getBasePath() . '/../files/answers/' . $value->id;
if (file_exists($path))
unlink($path);
$status = $status && $value->delete();
}
}
$trans = $this->trackCode;
$status = $this->delete();
$trans->delete();
return $status;
}
public function relations()
{
return array(
'orderfiles' => array(
self::HAS_MANY,
'Orderfiles',
'order_id'
),
'ordertype0' => array(
self::BELONGS_TO,
'Orderform',
'ordertype'
),
'trackCode' => array(
self::BELONGS_TO,
'Transaction',
'track_code'
),
'user0' => array(
self::BELONGS_TO,
'Users',
'user'
),
'ordervalues' => array(
self::HAS_MANY,
'Ordervalues',
'order'
),
'tickets' => array(
self::HAS_MANY,
'Ticket',
'order_id'
)
);
}
public function attributeLabels()
{
return array(
'id' => 'Code',
'name' => 'Name',
'start_date' => 'Date',
'finish_date' => 'End Date',
'status' => 'status',
'ordertype' => 'Type',
'user' => 'User',
'track_code' => 'Pay code',
'desc' => 'Description',
'file' => 'File'
);
}
public function getStatus()
{
$status = array(
0 => 'Waiting for pay',
1 => 'In progress',
2 => 'Completed',
3 => 'Draft'
);
return $status[$this->status];
}
public function getButton()
{
$status = array(
0 => 'Waiting for pay',
1 => 'In progress',
2 => 'Completed',
4 => 'Draft'
);
if ($this->status == 0) {
return CHtml::button('Pay', array(
'onclick' => 'window.location.href=\'' . Yii::app()->createUrl('financial/invoice', array(
'id' => $this->track_code
)) . '\''
));
}
return CHtml::button('Details', array(
'onclick' => 'window.location.href=\'' . Yii::app()->createUrl('service/order', array(
'id' => $this->id
)) . '\''
));
}
public function search()
{
$criteria = new CDbCriteria();
$criteria->compare('id', $this->id);
$criteria->compare('name', $this->name, true);
$criteria->compare('start_date', $this->start_date, true);
$criteria->compare('finish_date', $this->finish_date, true);
$criteria->compare('status', $this->status);
$criteria->compare('ordertype', $this->ordertype);
$criteria->compare('user', $this->user);
$criteria->compare('track_code', $this->track_code);
$criteria->compare('desc', $this->desc, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria
));
}
public static function model($className = __CLASS__)
{
return parent::model($className);
}
}
I'm only using a small part of this function actually but I wanted to post it all to provide the big picture. There is a part of the query in this function that finds recent attachments a user has posted to the forums. The block is on the user profile. IT works but the problem is ... it's VERY slow!! Core attachments locks up for 30+ seconds and makes my site unusable.
Any one who could help it would be much appreciated.
private function getAttImages($limit, $forumIds = 0, $fidsReverse = false, $topicIds = 0, $membersIds = 0, $order = 'attach_date', $sort = 'desc', $group = null)
{
$fids = '';
if ($forumIds)
{
$r = '';
if ($fidsReverse)
{
$r = ' NOT ';
}
if (is_array($forumIds))
{
$forumIds = implode(',', $forumIds);
}
$fids = ' AND forums_topics.forum_id ' . $r . ' IN (' . $forumIds . ')';
}
$tids = '';
if ($topicIds)
{
$tids = ' AND forums_topics.tid IN (' . $topicIds . ')';
}
$mids = '';
if ($membersIds)
{
$mids = ' AND core_attachments.attach_member_id IN (' . $membersIds . ')';
}
$whereT = array();
$joinsT = array();
$findInPosts = ' AND ' . \IPS\Db::i()->findInSet('queued', array('0'));
$joinsT[] = array(
'select' => 'forums_posts.*',
'from' => 'forums_posts',
'where' => array("forums_posts.pid=core_attachments_map.id2" . $findInPosts),
);
$findInTopics = ' AND ' . \IPS\Db::i()->findInSet('approved', array('1'));
$joinsT[] = array(
'select' => 'forums_topics.*',
'from' => 'forums_topics',
'where' => array("forums_topics.tid=forums_posts.topic_id" . $findInTopics . $fids . $tids),
);
$select = 'core_attachments.attach_id AS custom_data, core_attachments.*';
if ($group)
{
$select = 'core_attachments.attach_id AS custom_data, COUNT(attach_is_image) as cnt_images, SUM(attach_hits) as summ_attach_hits, core_attachments.*';
}
$joinsT[] = array(
'select' => $select,
'from' => 'core_attachments',
'where' => array('core_attachments.attach_is_image=1 AND core_attachments.attach_is_archived=0 AND core_attachments.attach_id=core_attachments_map.attachment_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_members.member_id, core_members.member_group_id, core_members.mgroup_others, core_members.name, core_members.members_seo_name',
'from' => 'core_members',
'where' => array('core_attachments.attach_member_id=core_members.member_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_permission_index.perm_id',
'from' => 'core_permission_index',
'where' => array("core_permission_index.app='forums' AND core_permission_index.perm_type='forum' AND core_permission_index.perm_type_id=forums_topics.forum_id"),
);
$groupT = $group;
$whereT[] = array(
"core_attachments_map.location_key='forums_Forums' AND " .
\IPS\Db::i()->findInSet('perm_view', array_merge(array(\IPS\Member::loggedIn()->member_group_id), array_filter(explode(',', \IPS\Member::loggedIn()->mgroup_others)))) . " OR perm_view='*'" .
$fids . $tids . $mids
);
$table = new \IPS\Helpers\Table\Db(
'core_attachments_map',
\IPS\Http\Url::internal('app=core&module=system&controller=nbattachpictures', 'front', 'nbattachpictures'),
$whereT,
$groupT
);
$table->joins = $joinsT;
$table->limit = $limit;
$table->sortBy = $order;
$table->sortDirection = $sort;
$table->rowsTemplate = array(\IPS\Theme::i()->getTemplate('plugins', 'core', 'global'), 'nbAttachmentsBlocksRows');
$table->parsers = array(
'custom_data' => function( $val, $row )
{
return array(
'topic_data' => \IPS\Http\Url::internal("app=forums&module=forums&controller=topic&id={$row['tid']}", 'front', 'forums_topic', array($row['title_seo'])),
'summ_attach_hits' => $row['summ_attach_hits'],
'jewel' => $this->attachJewel($row['summ_attach_hits']),
);
},
);
return $table;
}
I have an array like this, which has the product selected data.
$option_data[] = array(
'product_option_id' => $product_option_id,
'product_option_value_id' => $option_value,
'name1' => $option_value['name'],
'option_id' => $option_query->row['option_id'],
'option_value_id' => $option_value_query->row['option_value_id'],
'name' => $option_query->row['name'],
'option_value' => $option_value_query->row['name'],
'type' => $option_query->row['type'],
'quantity' => $option_value_query->row['quantity'],
'subtract' => $option_value_query->row['subtract'],
'price' => $option_value_query->row['price'],
'sdate' => $option_value_query->row['sdate'],
'edate' => $option_value_query->row['edate'],
'price_prefix' => $option_value_query->row['price_prefix'],
'points' => $option_value_query->row['points'],
'points_prefix' => $option_value_query->row['points_prefix'],
'weight' => $option_value_query->row['weight'],
'weight_prefix' => $option_value_query->row['weight_prefix']
);
And I need the values for price, So I have assigned price value like this
$pricelist = $option_value_query->row['price'];
Actually it has two values , now I want to add those two values. I am not getting how to separate it and add those values.
EDITED ****
My function is like this
public function getProducts12() {
if ($this->data) {
foreach ($this->session->data['cart'] as $key => $quantity) {
$product = explode(':', $key);
$product_id = $product[0];
$stock = true;
//echo $product_id;
// Options
if (isset($product[1])) {
$options = unserialize(base64_decode($product[1]));
} else {
$options = array();
}
$product_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) WHERE p.product_id = '" . (int)$product_id . "' AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND p.date_available <= NOW() AND p.status = '1'");
if ($product_query->num_rows) {
$option_price = 0;
$option_points = 0;
$option_weight = 0;
foreach ($options as $option)
{
$array123[] = $option;
$var123 = $array123[0];
}
$option_data = array();
foreach ($options as $product_option_id => $option_value) {
$option_query = $this->db->query("SELECT po.product_option_id, po.option_id, od.name, o.type FROM " . DB_PREFIX . "product_option po LEFT JOIN `" . DB_PREFIX . "option` o ON (po.option_id = o.option_id) LEFT JOIN " . DB_PREFIX . "option_description od ON (o.option_id = od.option_id) WHERE po.product_option_id = '" . (int)$product_option_id . "' AND po.product_id = '" . (int)$product_id . "' AND od.language_id = '" . (int)$this->config->get('config_language_id') . "'");
if ($option_query->num_rows) {
if ($option_query->row['type'] == 'radio' ){
$option_value_query = $this->db->query("SELECT pov.option_value_id, ovd.name, pov.price, pov.sdate, pov.edate, pov.price_prefix, pov.points, pov.points_prefix, pov.weight, pov.weight_prefix FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE pov.product_option_value_id = '" . (int)$option_value . "' AND pov.product_option_id = '" . (int)$product_option_id . "' AND ovd.language_id = '" . (int)$this->config->get('config_language_id') . "'");
if ($option_value_query->num_rows) {
if ($option_value_query->row['price_prefix'] == '+') {
$option_price += $option_value_query->row['price'];
} elseif ($option_value_query->row['price_prefix'] == '-') {
$option_price -= $option_value_query->row['price'];
}
if ($option_value_query->row['points_prefix'] == '+') {
$option_points += $option_value_query->row['points'];
} elseif ($option_value_query->row['points_prefix'] == '-') {
$option_points -= $option_value_query->row['points'];
}
if ($option_value_query->row['weight_prefix'] == '+') {
$option_weight += $option_value_query->row['weight'];
} elseif ($option_value_query->row['weight_prefix'] == '-') {
$option_weight -= $option_value_query->row['weight'];
}
$option_data[] = array(
'product_option_id' => $product_option_id,
'product_option_value_id' => $option_value,
'name1' => $option_value['name'],
'option_id' => $option_query->row['option_id'],
'option_value_id' => $option_value_query->row['option_value_id'],
'name' => $option_query->row['name'],
'option_value' => $option_value_query->row['name'],
'type' => $option_query->row['type'],
'quantity' => $option_value_query->row['quantity'],
'subtract' => $option_value_query->row['subtract'],
'price' => $option_value_query->row['price'],
'sdate' => $option_value_query->row['sdate'],
'edate' => $option_value_query->row['edate'],
'price_prefix' => $option_value_query->row['price_prefix'],
'points' => $option_value_query->row['points'],
'points_prefix' => $option_value_query->row['points_prefix'],
'weight' => $option_value_query->row['weight'],
'weight_prefix' => $option_value_query->row['weight_prefix']
);
}
//var_dump ($option_value_query->row['price']);
$pricelist = $option_value_query->row['price'];
//$_SESSION['m'] = $pricelist[0];
}
}
}
var_dump($pricelist);
}
}
}
//echo ($option_price);
return $this->data;
//echo $this->data;
}
}