Payzone Hashdigest not matching - php

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!!

Related

Shortcode parameter not working in WordPress

I am trying to pass amount parameters in url from the shortcode. The from and to attributes are working fine but the amount attribute is not working. The output shows the value of 1.
using the shortcode like this:
[exchange_rate from="USD" to="EUR" amount="100"]
function exchange_rate_shortcode($atts) {
$atts = shortcode_atts(array(
'from' => 'AED',
'to' => 'NPR',
'amount' => '1',
), $atts);
$url = "https://api.fastforex.io/convert?from=" . $atts['from'] . "&to=" . $atts['to'] . "&amount=" . $atts['amount'] . "&api_key=xxxx-xxxxx-xxxx";
$result = file_get_contents($url);
$result = json_decode($result, true);
return number_format((float)$result['result']['rate'], 2, '.', '') . " " . $atts['to'];
}
add_shortcode('exchange_rate', 'exchange_rate_shortcode');
Perhaps you somehow wrote the word "amount" wrong and therefore an error occurs. To avoid confusion, use the build_query function.
Your code will look like this:htt
function exchange_rate_shortcode($atts)
{
$atts = shortcode_atts(array(
'from' => 'AED',
'to' => 'NPR',
'amount' => '1',
'api_key' => 'xxxx-xxxxx-xxxx',
), $atts);
// to make sure the correct value type is specified
$atts['amount'] = (float)$atts['amount'];
$url = "https://api.fastforex.io/convert?" . build_query($atts);
$result = file_get_contents($url);
if ( ! empty($result)) {
$result = json_decode($result, true);
return number_format((float)$result['result']['rate'], 2, '.', '') . " " . $atts['to'];
}
return '';
}
add_shortcode('exchange_rate', 'exchange_rate_shortcode');

Displaying success message after form is submitted

My form was working perfectly fine and displays the success message when the form is submitted. However, I just added a small piece of code and though the form submits, it doesn't display the success message anymore.
This is my code:
public function entrymarks()
{
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('exam_group_class_batch_exam_subject_id', 'Subject', 'required|trim|xss_clean');
if ($this->form_validation->run() == false) {
$data = array(
'exam_group_class_batch_exam_subject_id' => form_error('exam_group_class_batch_exam_subject_id'),
);
$array = array('status' => 0, 'error' => $data);
echo json_encode($array);
} else {
$exam_group_student_id = $this->input->post('exam_group_student_id');
$insert_array = array();
$update_array = array();
if (!empty($exam_group_student_id)) {
foreach ($exam_group_student_id as $exam_group_student_key => $exam_group_student_value) {
$attendance_post = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value);
if (isset($attendance_post)) {
$attendance = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value);
} else {
$attendance = "present";
}
$cal1 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value);
$cal2 = $this->input->post('exam_group_student_ca2_' . $exam_group_student_value);
$cal3 = $this->input->post('exam_group_student_ca3_' . $exam_group_student_value);
$cal4 = $this->input->post('exam_group_student_ca4_' . $exam_group_student_value);
$exam = $this->input->post('exam_group_student_exam_' . $exam_group_student_value);
$total = $cal1 + $cal2 + $cal3 + $cal4 + $exam;
if ($total > 0) { // This line may be the problem
$array = array(
'exam_group_class_batch_exam_subject_id' => $this->input->post('exam_group_class_batch_exam_subject_id'),
'exam_group_class_batch_exam_student_id' => $exam_group_student_value,
'attendence' => $attendance,
'get_ca1' => $cal1,
'get_ca2' => $cal2,
'get_ca3' => $cal3,
'get_ca4' => $cal4,
'get_exam' => $exam,
'get_tot_score' => $total,
'note' => $this->input->post('exam_group_student_note_' . $exam_group_student_value),
);
$insert_array[] = $array;
}
}
}
$this->examgroupstudent_model->add_result($insert_array);
$array = array('status' => '1', 'error' => '', 'message' => $this->lang->line('success_message'));
echo json_encode($array);
}
}
How do I get the success message to display again?

How can I integrate Stripe without using JS? I have a problem with creating a session to stripe?

Since I have payments, through PayPal I try to integrate payments through Stripe. My system works on the following principle:
dashboard.php - here I have , in which Gateway is selected (paypal or stripe) and the corresponding amount that the client wants to add to his personal balance
```
<form action="/balance" method="post" id="form-balance" data-ajax="true">
stripe: <input type="radio" name="method" value="stripe" id="method_stripe">
paypal: <input type="radio" name="method" value="paypal" id="method_paypal">
</div>
<div class="form" style="width:330px">
<label class="required">Amount:</label>
<div class="input-group">
<input type="number" name="price" value="" min="1" autofocus required>
<button type="submit" class="btn btn-primary">continue</button>
</div>
</div>
</form>
```
balance.php - (ajax) this is the ajax part. In it I check and process the sent data: gateway, amount.
<?php
$stop = $res = [];
switch ( $subaction ) {
case 'balance':
$sum = ( isset($_REQUEST['amount']) && validate_price($_REQUEST['amount']) ) ? round($_REQUEST['amount'], 2) : 35;
$method = ( isset($_REQUEST['method']) && trim($_REQUEST['method']) != '' ) ? strip_tags( trim($_REQUEST['method']) ) : '';
if ( ! $sum ) {
$stop[] = $lng->data['Enter the amount to be filled'];
} elseif ( $sum < $config['minimal_transfer'] ) {
$stop[] = $lng->data['Minimum amount to power the deposit']." - <b>".$config['valuta']['EUR']."".$config['minimal_transfer'].".</b>";
}
if ( $stop ) {
$res['answer'] = 'stop';
$res['error'] = $stop;
} else {
$db->query( "INSERT INTO " . PREFIX_S . "_payment (`user_id`, `sum`, `temp`, `date`) VALUES ('" . USER_ID . "', '{$sum}', '1', '{$_DATE}')" );
$id = $db->insert_id();
$res['answer'] = 'ok';
switch ( $method ) {
// stripe
case 'stripe':
$params = [
'PAYMENT_AMOUNT' => $sum,
'PAYMENT_DESC_BASE64' => base64_encode($lng->data['Funding of an account'].' #' . SITE_ID),
'PAYMENT_NO' => $id
];
$location = "/site/payment_do/stripe_charget?" . http_build_query($params);
$res['eval'] = "window.location.href = '{$location}';";
break;
// paypal
case 'paypal':
$params = [
'PAYMENT_AMOUNT' => $sum,
'PAYMENT_DESC_BASE64' => base64_encode($lng->data['Funding of an account'].' #' . SITE_ID),
'PAYMENT_NO' => $id
];
$location = "/site/payment_do/paypal_charget?" . http_build_query($params);
$res['eval'] = "window.location.href = '{$location}';";
break;
default:
$params = [
'PAYMENT_AMOUNT' => $sum,
'PAYMENT_NO' => $id
];
$_SESSION['params'] = $params;
break;
}
}
break;
default: die( 'error' );
}
$content = json_encode($res);
header( "Content-type: application/json; charset=" . $config['charset'] );
echo $content;
payment.php - If everything is fine in balance.php (ajax) I send the data to the appropriate gateway for payment to payment.php. It sends to the appropriate official gateway (paypal.com or stripe.com) for payment
<?php
$_TIME = time();
$_DATE = date( "Y-m-d H:i:s", $_TIME );
require ENGINE_DIR . '/autoloader.php';
/*Array
(
[PAYMENT_AMOUNT] => 35
[PAYMENT_DESC_BASE64] => 0JfQsNGF0YDQsNC90LLQsNC90LUg0L3QsCDRgdC80LXRgtC60LAgIzI1
[PAYMENT_NO] => 2578
[PAYEE_PURSE] =>
[init] => site
[do] => payment_do
[action] => stripe_charget
[lang] => 7
)
*/
define('STRIPE_SUCCESS_URL', '/site/payment_do/success/');
define('STRIPE_CANCEL_URL', 'site/payment_do/cancel/');
$productName = "Funding an Account";
$productID = "DP12345";
$currency = "eur";
$params = ( isset($_REQUEST['params']) && is_array($_REQUEST['params']) ) ? $_REQUEST['params'] : [];
$productPrice = ( isset($_REQUEST['PAYMENT_AMOUNT']) && $_REQUEST['PAYMENT_AMOUNT'] > 10 ) ? $_REQUEST['PAYMENT_AMOUNT'] : 35;
$stripeAmount = round($productPrice*100, 2); // Convert product price to cent
$res = $stop = [];
ini_set("display_errors", "1"); error_reporting(E_ALL);
switch ( $action ) {
case 'stripe_charget':
// Include Stripe PHP library
require_once ENGINE_DIR . '/stripe-php/init.php';
// Set API key
\Stripe\Stripe::setApiKey($config['stripe']['stripe_api_key']);
$response = array(
'status' => 0,
'error' => array(
'message' => 'Invalid Request!'
)
);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$input = file_get_contents('php://input');
$request = json_decode($input);
//print_r($request);
//die;
}
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode($response);
exit;
}
if(!empty($request->checkoutSession)){
// Create new Checkout Session for the order
try {
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'price_data' => [
'product_data' => [
'name' => $productName,
'metadata' => [
'pro_id' => $productID
]
],
'unit_amount' => $stripeAmount,
'currency' => $currency,
],
'quantity' => 1,
'description' => $productName,
]],
'mode' => 'payment',
'success_url' => STRIPE_SUCCESS_URL.'?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => STRIPE_CANCEL_URL,
]);
}catch(Exception $e) {
$api_error = $e->getMessage();
}
if(empty($api_error) && $session){
$response = array(
'status' => 1,
'message' => 'Checkout Session created successfully!',
'sessionId' => $session['id']
);
}else{
$response = array(
'status' => 0,
'error' => array(
'message' => 'Checkout Session creation failed! '.$api_error
)
);
}
}
unset($_SESSION['params']);
// Return response
echo json_encode($response);
break;
case 'paypal':
$id = ( isset($_REQUEST['params']['account']) && (int)$_REQUEST['params']['account'] > 0 ) ? (int)$_REQUEST['params']['account'] : 0;
break;
default:
die( 'error action' );
}
When I use stripe js, I get the following error because I can't send the data to balance.php and from there to payment.php
{"status":0,"error":{"message":"Invalid Request!"}}
If I do the code as described here: https://stripe.com/docs/checkout/integration-builder, it works but this way I stop working for payments via PayPal - I want to have two working payment systems in this case, i don't have to use js on stripe.

PHP Payment Gateway Transaction Errors

I keep getting get the following 2 errors which I do not know how to fix
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'invalid keys: lineItems[ in C:\wamp64\www\pay\braintree\lib\Braintree\Util.php on line 351
And
InvalidArgumentException: invalid keys: lineItems[ in C:\wamp64\www\pay\braintree\lib\Braintree\Util.php on line 351
This is line 351 throw new InvalidArgumentException('invalid keys: ' . $sortedList); from the code below.
public static function verifyKeys($signature, $attributes)
{
$validKeys = self::_flattenArray($signature);
$userKeys = self::_flattenUserKeys($attributes);
$invalidKeys = array_diff($userKeys, $validKeys);
$invalidKeys = self::_removeWildcardKeys($validKeys, $invalidKeys);
if(!empty($invalidKeys)) {
asort($invalidKeys);
$sortedList = join(', ', $invalidKeys);
throw new InvalidArgumentException('invalid keys: ' . $sortedList);
}
}
Here is the first of my two functions that seem to cause the errors
function payment_data($gateway, $order_id){
try{
$account_number = account_number();
$total_amount = total_amount();
$credit_cards = $gateway->customer()->find($account_number);
$members_first_name = $credit_cards->firstName;
$members_last_name = $credit_cards->lastName;
$members_email = $credit_cards->email;
if(!empty($credit_cards)){
foreach($credit_cards->creditCards as $c){
if($c->default === true){
$first_name = $c->billingAddress->firstName;
$last_name = $c->billingAddress->lastName;
$street_address = $c->billingAddress->streetAddress;
$extended_address = $c->billingAddress->extendedAddress;
$city = $c->billingAddress->locality;
$region = $c->billingAddress->region;
$postal_code = $c->billingAddress->postalCode;
$country_name = $c->billingAddress->countryName;
$card_token = $c->token;
$customer_id = $c->customerId;
if(empty($extended_address)){
$extended_address = null;
}
if(empty($region)){
$region = null;
}
$result = $gateway->transaction()->sale([
'amount' => $total_amount,
'orderId' => $order_id,
'customerId' => $customer_id,
'customer' => [
'firstName' => $members_first_name,
'lastName' => $members_last_name,
'email' => $members_email
],
'billing' => [
'firstName' => $first_name,
'lastName' => $last_name,
'streetAddress' => $street_address ,
'extendedAddress' => $extended_address,
'countryName' => $country_name,
'locality' => $city,
'region' => $region,
'postalCode' => $postal_code
],
'shipping' => [
'firstName' => $first_name,
'lastName' => $last_name,
'streetAddress' => $street_address ,
'extendedAddress' => $extended_address,
'countryName' => $country_name,
'locality' => $city,
'region' => $region,
'postalCode' => $postal_code
],
'lineItems' => [
products($order_id)
],
'options' => [
'submitForSettlement' => true
]
]);
}
}
}
} catch (Braintree_Exception_NotFound $e) {
return false;
}
}
Here is my second function
function products($order_id){
if(products('Now') !== false){
$total = count(products('Now'));
$x = 1;
$line_items = '';
foreach(products('Now') as $product){
$title = $product['title'];
$quantity = $product['quantity'];
$sales_tax = $product['sales_tax'];
$regular_price = $product['regular_price'];
$total_sales_tax = $product['total_sales_tax'];
$total_amount = $product['total_amount'];
$savings_price = $product['savings_price'];
$product_id = $product['product_id'];
$line_items .= "[";
$line_items .= "'name' => '" . $title . "',";
$line_items .= "'description' => 'Product',";
$line_items .= "'quantity' => '" . $quantity . "',";
$line_items .= "'unitTaxAmount' => '" . $sales_tax . "',";
$line_items .= "'unitAmount' => '" . $regular_price . "',";
$line_items .= "'taxAmount' => '" . $total_sales_tax . "',";
$line_items .= "'totalAmount' => '" . $total_amount . "',";
$line_items .= "'discountAmount' => '" . $savings_price . "',";
$line_items .= "'productCode' => '" . $product_id . "',";
$line_items .= "'kind' => 'debit',";
$line_items .= "'url' => 'http://localhost/product.php?id=" . $product_id . "'";
if($x !== $total){
$line_items .= "],";
} else {
$line_items .= "]";
}
$x++;
}
return $line_items;
}
}
I'm guessing you need something more like this, I've used Braintree a bit and I've never passed it a big string of data like that.
function products($order_id){
if(products('Now') !== false){
$total = count(products('Now'));
$line_items = Array();
foreach(products('Now') as $product){
$title = $product['title'];
$quantity = $product['quantity'];
$sales_tax = $product['sales_tax'];
$regular_price = $product['regular_price'];
$total_sales_tax = $product['total_sales_tax'];
$total_amount = $product['total_amount'];
$savings_price = $product['savings_price'];
$product_id = $product['product_id'];
$line_item = Array();
$line_item['name'] = $title;
$line_item['description'] = 'Product';
$line_item['quantity'] = $quantity;
$line_item['unitTaxAmount'] = $sales_tax;
$line_item['unitAmount'] = $regular_price;
$line_item['taxAmount'] = $total_sales_tax;
$line_item['totalAmount'] = $total_amount;
$line_item['discountAmount'] = $savings_price;
$line_item['productCode'] = $product_id;
$line_item['kind'] = 'debit';
$line_item['url'] = 'http://localhost/product.php?id=' . $product_id;
$line_items[] = $line_item;
}
return $line_items;
}
}

IPB php function works but is slow. SQL needs to be faster

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;
}

Categories