Overall tax in invoice consolibite quickbook sdk in php - php

I am using consolibyte Quickbook online version for php.
I am creating the invoice and it is working fine for me.
And I am include tax in line. but I have to remove that tax and want to add in overall tax.
Can someone please help me.
Everything is working fine I just want to add tax same as attached image.
Please help
Thanks in advance
My code for add the invoice :
public function addInvoice($invoiceArray,$chargeArray,$customerRef,$db_product,$invoice_id,$other_charges,$price_grid,$payment,$orderId,$quickbook_id,$display_order_id,$payment_terms_name,$payment_terms_day){
$IPP = new \QuickBooks_IPP($this->QBO_DSN);
// Get our OAuth credentials from the database
$creds = $this->IntuitAnywhere->load(Session::get('useremail'), Session::get('user_id'));
// Tell the framework to load some data from the OAuth store
$IPP->authMode(
\QuickBooks_IPP::AUTHMODE_OAUTH,
Session::get('useremail'),
$creds);
if ($this->is_sandbox) {
// Turn on sandbox mode/URLs
$IPP->sandbox(true);
}
// This is our current realm
$this->realm = $creds['qb_realm'];
// Load the OAuth information from the database
$this->context = $IPP->context();
$InvoiceService = new \QuickBooks_IPP_Service_Invoice();
if($quickbook_id > 0) {
$retr = $InvoiceService->delete($this->context, $this->realm, $quickbook_id);
}
$Invoice = new \QuickBooks_IPP_Object_Invoice();
$CustomField = new \QuickBooks_IPP_Object_CustomField();
$CustomField->setDefinitionId('2');
$CustomField->setName('Sales Rep');
$CustomField->setType('StringType');
$CustomField->setStringValue($invoiceArray[0]->sales_name);
$Invoice->addCustomField($CustomField);
$CustomField1 = new \QuickBooks_IPP_Object_CustomField();
$CustomField1->setDefinitionId('1');
$CustomField1->setName('Customer PO');
$CustomField1->setType('StringType');
$CustomField1->setStringValue($invoiceArray[0]->custom_po);
$Invoice->addCustomField($CustomField1);
$Invoice->setDocNumber('INV-' . $display_order_id);
$Invoice->setTxnDate(date('Y-m-d'));
if($payment_terms_name != '') {
if($payment_terms_day > 0) {
$due_day = $payment_terms_day;
} else {
$due_day = 0;
}
$TermService = new \QuickBooks_IPP_Service_Term();
$terms = $TermService->query($this->context, $this->realm, "SELECT * FROM Term WHERE Name = '".$payment_terms_name."' ");
$Term = new \QuickBooks_IPP_Object_Term();
$payment_terms_id = 0;
if(!empty($terms)){
$Term = $terms[0];
$payment_terms_id = $Term->getId();
$payment_terms_id = str_replace('{','',$payment_terms_id);
$payment_terms_id = str_replace('}','',$payment_terms_id);
$payment_terms_id = abs($payment_terms_id);
}
if($payment_terms_id > 0) {
$Invoice->setSalesTermRef($payment_terms_id);
} else {
$Term->setName($payment_terms_name);
$Term->setDueDays($due_day);
if ($resp = $TermService->add($this->context, $this->realm, $Term))
{
$payment_terms_id = $this->getId($resp);
$Invoice->setSalesTermRef($payment_terms_id);
}
}
if($due_day > 0) {
$setDate = date('Y-m-d', strtotime("+".$due_day. "days"));
$Invoice->setDueDate($setDate);
} else {
$Invoice->setDueDate(date('Y-m-d'));
}
}
foreach ($invoiceArray as $key => $value) {
$desc = array();
foreach ($value->sizeData as $sizeAll) {
$desc[] = $sizeAll->size.'('.$sizeAll->qnty.')';
}
$description = implode(', ' , $desc);
$product_name_desc_display = $value->product_name.' : '.$value->color_name.' : '.$description;
$Line = new \QuickBooks_IPP_Object_Line();
$Line->setDetailType('SalesItemLineDetail');
$Line->setAmount($value->total_line_charge * $value->total_qnty);
$Line->setDescription($product_name_desc_display);
$SalesItemLineDetail = new \QuickBooks_IPP_Object_SalesItemLineDetail();
if($value->vendor_id == 1) {
$SalesItemLineDetail->setItemRef($db_product[0]->ss);
} else {
$SalesItemLineDetail->setItemRef($db_product[0]->custom_product);
}
$SalesItemLineDetail->setUnitPrice($value->total_line_charge);
$SalesItemLineDetail->setQty($value->total_qnty);
$Line->addSalesItemLineDetail($SalesItemLineDetail);
$Invoice->addLine($Line);
$Invoice->setCustomerRef($customerRef);
}
if($chargeArray[0]->order_total != 0 && $chargeArray[0]->order_total != '') {
$Line = new \QuickBooks_IPP_Object_Line();
$Line->setDetailType('SalesItemLineDetail');
$Line->setAmount($chargeArray[0]->tax);
$Line->setDescription('Tax-'.$chargeArray[0]->tax_rate);
$SalesItemLineDetail = new \QuickBooks_IPP_Object_SalesItemLineDetail();
$SalesItemLineDetail->setItemRef($db_product[0]->tax_charge);
$SalesItemLineDetail->setUnitPrice($chargeArray[0]->tax);
$SalesItemLineDetail->setQty(1);
$Line->addSalesItemLineDetail($SalesItemLineDetail);
$Invoice->addLine($Line);
$Invoice->setCustomerRef($customerRef);
}
if($chargeArray[0]->discount != 0 && $chargeArray[0]->discount != '') {
$Line = new \QuickBooks_IPP_Object_Line();
$Line->setDetailType('SalesItemLineDetail');
$Line->setAmount(-$chargeArray[0]->discount);
$Line->setDescription('Discount');
$SalesItemLineDetail = new \QuickBooks_IPP_Object_SalesItemLineDetail();
$SalesItemLineDetail->setItemRef($db_product[0]->discount_charge);
$SalesItemLineDetail->setUnitPrice(-$chargeArray[0]->discount);
$SalesItemLineDetail->setQty(1);
$Line->addSalesItemLineDetail($SalesItemLineDetail);
$Invoice->addLine($Line);
$Invoice->setCustomerRef($customerRef);
}
if ($resp = $InvoiceService->add($this->context, $this->realm, $Invoice))
{
$qb_invoice_id = $this->getId($resp);
$this->common->UpdateTableRecords('invoice',array('id' => $invoice_id),array('qb_id' => $qb_invoice_id));
//if($quickbook_id > 0) {
$this->common->UpdateTableRecords('payment_history',array('order_id' => $orderId),array('qb_id' => $qb_invoice_id,'qb_flag' => 0));
// }
return 1;
}
else
{
return 0;
}
}
enter image description here

Related

Laravel Complex API Code Optimization to avoid nested loops

Introduction
Hi, I hope everyone is doing great. I am a little advance to beginner level in Laravel and developing a system where I have to use Instagram API to get all the data against different hashtags.
These hashtags could be 1, or 2, or even more. Here is the code that I am sharing, this code is taking too much time to run because of the nested loops in it. Can anyone who is expert share his/her knowledge and give me suggestions on how to improve this piece of code?
The code
public function getHastagMediaByID($token)
{
$client = new \GuzzleHttp\Client();
$event_hashtag = $this->event->hashtag;
$hashtagArray = explode(',', $event_hashtag);
$hashtagIdArray = array();
// dd($hashtagArray);
$count = 0;
$decodedInstagramDataApiResponse = null;
if (isset($hashtagArray)) {
$userIGAccounts = Event_Social_Post::where('event_id', $this->event->id)->where('platform', 'instagram')->get();
if ($userIGAccounts != null) {
foreach ($userIGAccounts as $userinstaAcc) {
try {
$userInstaAccId = $userinstaAcc->page_id;
$instagramUserDataApi = $client->request('GET', "https://graph.facebook.com/v12.0/$userInstaAccId?fields=username%2Cprofile_picture_url&access_token=$token");
$getInstagramDataApiResponse = $instagramUserDataApi->getBody()->getContents();
$decodedInstagramDataApiResponse[] = json_decode($getInstagramDataApiResponse, true);
foreach ($hashtagArray as $key => $hashtagValue) {
if (isset($hashtagValue) && $hashtagValue != "") {
try {
$hashtagValue = ltrim($hashtagValue);
$InstagramHashtagIdApi = $client->request('GET', "https://graph.facebook.com/v11.0/ig_hashtag_search?user_id=$userInstaAccId&q=$hashtagValue&access_token=$token");
$getInstagramHashTagApiResponse = $InstagramHashtagIdApi->getBody()->getContents();
$decodedInstagramHashTag = json_decode($getInstagramHashTagApiResponse, true);
$InstagramHashtagID = $decodedInstagramHashTag['data'][0]['id'];
$hashtagPostSearchApi = $client->request('GET', "https://graph.facebook.com/v11.0/$InstagramHashtagID/recent_media?user_id=$userInstaAccId&fields=id%2Crecent_type%2Ccomments_count%2Clike_count%2Ccaption%2Cmedia_url%2Cpermalink%2Cchildren{media_url}%2Ctimestamp&access_token=$token");
$getHashtagPostSearchApiApiResponse = $hashtagPostSearchApi->getBody()->getContents();
$decodedHashtagPostSearchResponse = json_decode($getHashtagPostSearchApiApiResponse, true);
$hashtagIdArray[] = $decodedHashtagPostSearchResponse;
// var_dump($hashtagIdArray);
$count++;
} catch (ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
if (Auth::check()) {
Session::put('instagramException', 'true');
Session::put('instagramExceptionMessage', $responseBodyAsString);
}
continue;
}
}
}
} catch (ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
if (Auth::check()) {
Session::put('instagramException', 'true');
Session::put('instagramExceptionMessage', $responseBodyAsString);
}
continue;
}
}
if (count($hashtagIdArray) > 0) {
foreach ($hashtagIdArray as $key => $post) {
$userDataLoopIndex = 0;
if (count($post['data']) > 0) {
// dd($post['data']);
foreach ($post['data'] as $postDatum) {
if (isset($postDatum['children'])) {
foreach ($postDatum['children'] as $key => $childrenData) {
foreach ($childrenData as $childrenSingleton) {
// $childrenSingleton['media_url'];
$soc = new E_social_wall;
$soc->text = $postDatum['caption'] ?? ''; //->caption;
$soc->image = $childrenSingleton['media_url'] ?? ''; //->media_url;
$soc->platform = 'instagram';
if ($userDataLoopIndex < count($decodedInstagramDataApiResponse)) {
//dd($media['userData']);
if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
$soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
} else {
$soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
}
$soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
$userDataLoopIndex++;
} else if ($userDataLoopIndex >= count($decodedInstagramDataApiResponse)) {
$userDataLoopIndex = 0;
if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
$soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
} else {
$soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
}
$soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
$userDataLoopIndex++;
}
$soc->posted_at = date('Y-m-d h:i', strtotime($postDatum['timestamp']));
$soc->url = $childrenSingleton['media_url'] ?? ''; //->media_url;
$soc->event_id = $this->event->id;
$soc->is_hashtag = 1;
if ($soc->image != '' || $soc->url != '') {
$soc->save();
}
$count++;
}
}
} else {
$soc = new E_social_wall;
$soc->text = $postDatum['caption'] ?? ''; //->caption;
$soc->image = $postDatum['media_url'] ?? ''; //->media_url;
$soc->platform = 'instagram';
if ($userDataLoopIndex < count($decodedInstagramDataApiResponse)) {
//dd($media['userData']);
if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
$soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
} else {
$soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
}
$soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
$userDataLoopIndex++;
} else if ($userDataLoopIndex >= count($decodedInstagramDataApiResponse)) {
$userDataLoopIndex = 0;
if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
$soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
} else {
$soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
}
$soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
$userDataLoopIndex++;
}
$soc->posted_at = date('Y-m-d h:i', strtotime($postDatum['timestamp']));
$soc->url = $postDatum['media_url'] ?? ''; //->media_url;
$soc->event_id = $this->event->id;
$soc->is_hashtag = 1;
if ($soc->image != '' || $soc->url != '') {
$soc->save();
}
$count++;
}
}
}
}
}
return array('response' => $hashtagIdArray, 'userData' => $decodedInstagramDataApiResponse);
}
}
}
any suggestion or help would be great. Thank you all in advance.

Finicity API Issue

We are using the finicity API to get statements and transaction. We have followed below steps, but we are getting "aggregationStatusCode:185" while fetching the customer accounts [ https://api.finicity.com/aggregation/v1/customers/['customer_id']/accounts ].
To get the custommer account I am using https://api.finicity.com/aggregation/v1/customers/['customer_id']/accounts.
Then we are fetching statements for account using "https://api.finicity.com/aggregation/v1/customers/['customer_id']/accounts/['account_id']/statement?index=1; this loops for 6 times. We need 6 months statement for each account.
Then, we are fetching transaction for account using "https://api.finicity.com/aggregation/v1/customers/['customer_id']/accounts/['account_id']/transactions?fromDate=".$from."&toDate=".strtotime(date('Y-m-d'))."&limit=".$transactionLimit."&includePending=true";
We are facing the below two issues.
1. Getting timeout error, when selecting more than 2 accounts.
2. Getting "aggregationStatusCode:185" for some live accounts.
Below are the code for reference.
function get_statements(){
$FinicityAppToken=$_POST['FinicityAppToken'];
$customerId=$_POST['customerId'];
$leadId=$_POST['leadId'];
$finicityConnectUrl=$_POST['finicityConnectUrl'];
$NoOFStatements = 6;
$transactionLimit = 100;
$transactionsMonth = 1;
$url="https://api.finicity.com/aggregation/v1/customers/".$customerId."/accounts";
$response=callAPI('POST', $url,false,$FinicityAppToken);
$response = json_decode($response);
$allstatements=array();
if($response){
if(isset($response->accounts)){
$accounts = array();
$array = array();
foreach($response->accounts as $account){
if ($account->aggregationStatusCode == 0 && $account->aggregationSuccessDate != '' && $account->aggregationAttemptDate != '') {
for($i=1;$i<=$NoOFStatements;$i++) {
$url="https://api.finicity.com/aggregation/v1/customers/".$customerId."/accounts/".$account->id."/statement?index=".$i;
$stateresponse=callAPI('GET', $url,false,$FinicityAppToken);
$temp = array();
$temp['accountId'] = $account->id;
$temp['statement'] = base64_encode($stateresponse);
$statements[]=$temp;
}
$act = array();
$month = date('m') - $transactionsMonth;
$from = strtotime(date('Y').'-'.$month.'-1');
$url="https://api.finicity.com/aggregation/v1/customers/".$customerId."/accounts/".$account->id."/transactions?fromDate=".$from."&toDate=".strtotime(date('Y-m-d'))."&limit=".$transactionLimit."&includePending=true";
$data['url'] = $url;
$transactions = json_decode(callAPI('GET', $url,false,$FinicityAppToken));
$act['account']['accountNumber'] = $account->number;
unset($account->number);
$act['account']['currencySymbol'] = $account->currency;
unset($account->currency);
if(empty((array) $account->detail)) {
$account->detail = (object) transactionsDetailsEmpty();
}
$act['account'] = json_decode(json_encode($account), true);
if(isset($transactions->transactions)) {
$act['transactions'] = $transactions->transactions;
} else {
$act['transactions'] = array();
}
// echo "step";
$accounts[] = $act;
} else {
$data['success'] = 1;
$data['response']=$response ;
$data['finicityConnectUrl'] = $finicityConnectUrl;
$data['leadId'] = $leadId;
$data['FinicityAppToken'] = $FinicityAppToken;
$data['customerId'] = $customerId;
echo json_encode($data);
die();
}
$j++;
}
$array['accounts'] = $accounts;
$array['leadId'] = $leadId;
$data['accounts'] = $array;
$url="https://api.finicity.com/aggregation/v1/customers/".$customerId;
$response=callAPI('DELETE', $url,false,$FinicityAppToken);
}
}
}

php script create csv export file, based on product values

I currently have the following script, that change the producttitle of a product with a specific ID.
Now I want to re-write the script, so that it does not update the attributes but generates a .csv file of the entire catalog with two columns.
Product_SKU
$productnamingseo value
How can I achieve this?
Current working php script for 1 product, it adds successfully all product SKU's but not the referral $productnamingseo, only of the first product:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require('../app/Mage.php');
Mage::app();
$product = Mage::getModel('catalog/product')->load(409728);
Mage::register('current_product', $product);
$seotitle = Mage::helper('seo')->getCurrentSeo();
$productnamestring = Mage::getSingleton('seo/object_product')->getTitle();
$findseo = array('/\h+inch (?:(i[357])-\w+|\h+\w+)?/', '/(\w+)#\w+/', '/(^| )(.{4,}) (.*)\2/', '/\s*-\s*$/');
$replaceseo = array('" $1', '$1', '$1$2 $3', '');
$productnamingseo = preg_replace($findseo, $replaceseo, $productnamestring);
$product->setName($productnamingseo);
$product->getResource()->saveAttribute($product, 'name');
EDIT already tried this, that works for only 1 product. All other products got that $productnamingseo value of product 1, instead of their own unique value.
This create a .csv file with the following output. Only the first line is correct. All other lines got the wrong $productnamingseo of the first product.
"ACER_EY.JE001.002","Acer C120 LED - EY.JE001.002"
"ALLIEDTELESIS_AT-2701FXA/SC-001","Acer C120 LED - EY.JE001.002"
"APC_0M-0213-005","Acer C120 LED - EY.JE001.002"
Script:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
ini_set('memory_limit', '4G');
require('app/Mage.php');
Mage::app();
$file_path = "var/import/productname.csv";
$mage_csv = new Varien_File_Csv();
$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->setPageSize(1)->setCurPage(1);
foreach ($products as $product) {
$prod = Mage::register('current_product', $product);
$seotitle = Mage::helper('seo')->getCurrentSeo();
$productnamestring = Mage::getSingleton('seo/object_product')->getTitle();
$findseo = array('/\h+inch (?:(i[357])-\w+|\h+\w+)?/', '/(\w+)#\w+/', '/(^| )(.{4,}) (.*)\2/', '/\s*-\s*$/');
$replaceseo = array('" $1', '$1', '$1$2 $3', '');
$productnamingseo = preg_replace($findseo, $replaceseo, $productnamestring);
echo $productnamingseo;
$data = array();
$data['sku'] = $product->getSku();
$data['name'] = $productnamingseo;
$products_row[] = $data;
Mage::unregister('current_product')
}
$mage_csv->saveData($file_path, $products_row);
echo 'Done!';
SEO helper Mirasvit_Seo_Model_Object_Product:
public function _construct()
{
parent::_construct();
$this->_product = Mage::registry('current_product');
if (!$this->_product) {
$this->_product = Mage::registry('product');
}
if (!$this->_product) {
return;
}
$this->_parseObjects['product'] = $this->_product;
$this->setAdditionalVariable('product', 'url', $this->_product->getProductUrl());
$this->setAdditionalVariable('product', 'final_price', $this->_product->getFinalPrice());
$this->setAdditionalVariable('product', 'final_price_minimal', Mage::helper('seo')->getCurrentProductFinalPrice($this->_product));
$this->setAdditionalVariable('product', 'final_price_range', Mage::helper('seo')->getCurrentProductFinalPriceRange($this->_product));
$this->setAdditionalVariable('product', 'stock_qty', Mage::helper('seo')->getCurrentProductStockQty($this->_product));
$categoryId = $this->_product->getSeoCategory();
$this->_category = Mage::registry('current_category');
if ($this->_category && !$categoryId) {
$this->_parseObjects['category'] = $this->_category;
} elseif ($this->_product) {
if (!$categoryId) {
$categoryIds = $this->_product->getCategoryIds();
if (count($categoryIds) > 0) {
//we need this for multi websites configuration
$categoryRootId = Mage::app()->getStore()->getRootCategoryId();
$category = Mage::getModel('catalog/category')->getCollection()
->addFieldToFilter('path', array('like' => "%/{$categoryRootId}/%"));
//don't delete (for some stores need main_table)
$stringSelect = $category->getSelect()->__toString();
$entityIdFilter = (strpos($stringSelect, 'main_table') !== false)
? 'main_table.entity_id' : 'entity_id';
$category = $category->addFieldToFilter($entityIdFilter, $categoryIds)
->setOrder('level', 'desc')
->setOrder($entityIdFilter, 'desc')
->getFirstItem()
;
$categoryId = $category->getId();
}
}
//load category with flat data attributes
$category = Mage::getModel('catalog/category')->load($categoryId);
$this->_category = $category;
$this->_parseObjects['category'] = $category;
if (!Mage::registry('seo_current_category')) {// to be sure that register will not be done twice
Mage::register('seo_current_category', $category);
};
}
$this->_parseObjects['store'] = Mage::getModel('seo/object_store');
$this->init();
}
getCurrentSeo() code:
public function getCurrentSeo()
{
if (Mage::app()->getStore()->getCode() == 'admin') {
return new Varien_Object();
}
$isCategory = Mage::registry('current_category') || Mage::registry('category');
$isProduct = Mage::registry('current_product') || Mage::registry('product');
$isFilter = false;
if ($isCategory) {
$filters = Mage::getSingleton('catalog/layer')->getState()->getFilters();
$isFilter = count($filters) > 0;
}
if ($isProduct) {
$seo = Mage::getSingleton('seo/object_product');
} elseif ($isCategory && $isFilter) {
$seo = Mage::getSingleton('seo/object_filter');
} elseif ($isCategory) {
$seo = Mage::getSingleton('seo/object_category');
} else {
$seo = new Varien_Object();
}
if ($seoTempalate = $this->checkTempalateRule($isProduct, $isCategory, $isFilter)) {
foreach ($seoTempalate->getData() as $k=>$v) {
if ($v) {
$seo->setData($k, $v);
}
}
}
if ($seoRewrite = $this->checkRewrite()) {
foreach ($seoRewrite->getData() as $k=>$v) {
if ($v) {
$seo->setData($k, $v);
}
}
}
$storeId = Mage::app()->getStore()->getStoreId();
$page = Mage::app()->getFrontController()->getRequest()->getParam('p');
if (!$page) {
$page = 1;
}
if ($isCategory && !$isProduct) {
if ($this->_titlePage) {
switch ($this->_config->getMetaTitlePageNumber($storeId)) {
case Mirasvit_Seo_Model_Config::META_TITLE_PAGE_NUMBER_BEGIN:
if ($page > 1) {
$seo->setMetaTitle(Mage::helper('seo')->__("Page %s | %s", $page, $seo->getMetaTitle()));
$this->_titlePage = false;
}
break;
case Mirasvit_Seo_Model_Config::META_TITLE_PAGE_NUMBER_END:
if ($page > 1) {
$seo->setMetaTitle(Mage::helper('seo')->__("%s | Page %s", $seo->getMetaTitle(), $page));
$this->_titlePage = false;
}
break;
case Mirasvit_Seo_Model_Config::META_TITLE_PAGE_NUMBER_BEGIN_FIRST_PAGE:
$seo->setMetaTitle(Mage::helper('seo')->__("Page %s | %s", $page, $seo->getMetaTitle()));
$this->_titlePage = false;
break;
case Mirasvit_Seo_Model_Config::META_TITLE_PAGE_NUMBER_END_FIRST_PAGE:
$seo->setMetaTitle(Mage::helper('seo')->__("%s | Page %s", $seo->getMetaTitle(), $page));
$this->_titlePage = false;
break;
}
}
if ($this->_descriptionPage) {
switch ($this->_config->getMetaDescriptionPageNumber($storeId)) {
case Mirasvit_Seo_Model_Config::META_DESCRIPTION_PAGE_NUMBER_BEGIN:
if ($page > 1) {
$seo->setMetaDescription(Mage::helper('seo')->__("Page %s | %s", $page, $seo->getMetaDescription()));
$this->_descriptionPage = false;
}
break;
case Mirasvit_Seo_Model_Config::META_DESCRIPTION_PAGE_NUMBER_END:
if ($page > 1) {
$seo->setMetaDescription(Mage::helper('seo')->__("%s | Page %s", $seo->getMetaDescription(), $page));
$this->_descriptionPage = false;
}
break;
case Mirasvit_Seo_Model_Config::META_DESCRIPTION_PAGE_NUMBER_BEGIN_FIRST_PAGE:
$seo->setMetaDescription(Mage::helper('seo')->__("Page %s | %s", $page, $seo->getMetaDescription()));
$this->_descriptionPage = false;
break;
case Mirasvit_Seo_Model_Config::META_DESCRIPTION_PAGE_NUMBER_END_FIRST_PAGE:
$seo->setMetaDescription(Mage::helper('seo')->__("%s | Page %s", $seo->getMetaDescription(), $page));
$this->_descriptionPage = false;
break;
}
}
if ($page > 1) {
$seo->setDescription(''); //set an empty description for page with number > 1 (to not have a duplicate content)
}
}
if ($metaTitleMaxLength = $this->_config->getMetaTitleMaxLength($storeId)) {
$metaTitleMaxLength = (int)$metaTitleMaxLength;
if ($metaTitleMaxLength < Mirasvit_Seo_Model_Config::META_TITLE_INCORRECT_LENGTH) {
$metaTitleMaxLength = Mirasvit_Seo_Model_Config::META_TITLE_MAX_LENGTH; //recommended length
}
$seo->setMetaTitle($this->_getTruncatedString($seo->getMetaTitle(), $metaTitleMaxLength, $page));
}
if ($metaDescriptionMaxLength = $this->_config->getMetaDescriptionMaxLength($storeId)) {
$metaDescriptionMaxLength = (int)$metaDescriptionMaxLength;
if ($metaDescriptionMaxLength < Mirasvit_Seo_Model_Config::META_DESCRIPTION_INCORRECT_LENGTH) {
$metaDescriptionMaxLength = Mirasvit_Seo_Model_Config::META_DESCRIPTION_MAX_LENGTH; //recommended length
}
$seo->setMetaDescription($this->_getTruncatedString($seo->getMetaDescription(), $metaDescriptionMaxLength, $page));
}
return $seo;
}

What is wrong with this php string

I am new to php, trying to get a RSS Reader to display a message when there is nothing to display.
I asked for some help yesterday and was kindly assisted, and it made sense, but for some reason it is not storing it.
Hoping someone could tell me what is wrong with the following php.
<?php
require_once("rsslib.php");
$url = "http://www.bom.gov.au/fwo/IDZ00063.warnings_land_qld.xml";
$rss123 = RSS_Display($url, 3, false, true);
if (count($rss123) < 1)
{
// nothing shown, do whatever you want
echo 'There are no current warnings';
echo '<style type="text/css">
#flashing_wrapper {
display: none;
}
</style>';
}
else
{
// something to display
echo $rss123;
}
?>
My problem is, it doesnt seem to be storing a value in $rss123.
It can be viewed at the following address - http://goo.gl/12XQSe
Thanks in advanced,
Pete
----- EDIT ------
As requested in a comment, RSS_Display is from the rsslib.php file, which is as follows
<?php
/*
RSS Extractor and Displayer
(c) 2007-2010 Scriptol.com - Licence Mozilla 1.1.
rsslib.php
Requirements:
- PHP 5.
- A RSS feed.
Using the library:
Insert this code into the page that displays the RSS feed:
<?php
require_once("rsslib.php");
echo RSS_Display("http://www.xul.fr/rss.xml", 15);
? >
*/
$RSS_Content = array();
function RSS_Tags($item, $type)
{
$y = array();
$tnl = $item->getElementsByTagName("title");
$tnl = $tnl->item(0);
$title = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("link");
$tnl = $tnl->item(0);
$link = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("pubDate");
$tnl = $tnl->item(0);
$date = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("description");
$tnl = $tnl->item(0);
$description = $tnl->firstChild->textContent;
$y["title"] = $title;
$y["link"] = $link;
$y["date"] = $date;
$y["description"] = $description;
$y["type"] = $type;
return $y;
}
function RSS_Channel($channel)
{
global $RSS_Content;
$items = $channel->getElementsByTagName("item");
// Processing channel
$y = RSS_Tags($channel, 0); // get description of channel, type 0
array_push($RSS_Content, $y);
// Processing articles
foreach($items as $item)
{
$y = RSS_Tags($item, 1); // get description of article, type 1
array_push($RSS_Content, $y);
}
}
function RSS_Retrieve($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
RSS_Channel($channel);
}
}
function RSS_RetrieveLinks($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
$items = $channel->getElementsByTagName("item");
foreach($items as $item)
{
$y = RSS_Tags($item, 1); // get description of article, type 1
array_push($RSS_Content, $y);
}
}
}
function RSS_Links($url, $size = 15)
{
global $RSS_Content;
$page = "<ul>";
RSS_RetrieveLinks($url);
if($size > 0)
$recents = array_slice($RSS_Content, 0, $size + 1);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0) continue;
$title = $article["title"];
$link = $article["link"];
$page .= "<li>$title</li>\n";
}
$page .="</ul>\n";
return $page;
}
function RSS_Display($url, $size = 18, $site = 0, $withdate = 0)
{
global $RSS_Content;
$opened = false;
$page = "";
$site = (intval($site) == 0) ? 1 : 0;
RSS_Retrieve($url);
if($size > 0)
$recents = array_slice($RSS_Content, $site, $size + 1 - $site);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0)
{
if($opened == true)
{
$page .="</ul>\n";
$opened = false;
}
$page .="<b>";
}
else
{
if($opened == false)
{
$page .= "<ul>\n";
$opened = true;
}
}
$title = $article["title"];
$link = $article["link"];
$page .= "<li>$title";
if($withdate)
{
$date = $article["date"];
$page .=' <span class="rssdate">'.$date.'</span>';
}
$description = $article["description"];
if($description != false)
{
$page .= "<br><span class='rssdesc'>$description</span>";
}
$page .= "</li>\n";
if($type==0)
{
$page .="</b><br />";
}
}
if($opened == true)
{
$page .="</ul>\n";
}
return $page."\n";
}
?>
There seems to be something wrong with the xml file you are using. I tried the with a another xml by replacing the url with the mentioned value. $url = "http://www.scriptol.com/rss.xml";
Oddly enough it seems to be working now with the old xml as well.

Why isn't my sorting algorithm working?

I'm developing a system for a client that creates a csv of packing labels which is sent to a printer. The client has six different items. Customers order products in bulk from my client. Two items (product A and product B) share the same packing line. In order to make packing more efficient my client wants to alternate between packing product A and packing product B first.
For example, if John, Sally, and James all ordered both products, the system needs to write John's orders to the csv starting with product A, Sally's orders starting with product B, and James' orders starting with product A again.
I've pasted my non-working code below, but this is really screwing with my head and I'm having a really tough time with it.
foreach($orders as $order) {
$name = null;
$phone = null;
$account = DAO_ContactPerson::get($order->account_id);
$delivery = false;
if($account->is_agency) {
$name = $order->getAttribute('name');
$phone = $order->getAttribute('phone');
} else {
$name = sprintf("%s %s",
$account->getPrimaryAddress()->first_name,
$account->getPrimaryAddress()->last_name
);
$phone = $account->phone;
}
$name = trim($name);
$phone = trim($phone);
$items = $order->getItems();
if($order->getAttribute('delivery')) {
$type = 'deliveries';
$destination = 'Delivery';
$address = sprintf("%s %s %s",
$order->getAttribute('delivery_address.line1'),
$order->getAttribute('delivery_address.line2'),
$order->getAttribute('delivery_address.postal')
);
} else {
$type = 'pickups';
$agency = DAO_ContactPerson::getAgency($order->getAttribute('pickup'));
$destination = $agency->name;
// Override account id so orders are grouped by agency
$order->account_id = $agency->id;
$address = null;
}
// var_dump($order->id);
// Init account array
if(!isset($rows[$type][$order->account_id]))
$rows[$type][$order->account_id] = array('combined' => array(), 'separate' => array());
foreach($items as $item) {
$packing = 'separated';
if($item->product_id == 3 || $item->product_id == 4)
$packing = 'combined';
if(!isset($rows[$type][$order->account_id][$packing][$item->product_id]))
$rows[$type][$order->account_id][$packing][$item->product_id] = array();
$i = 0;
while($i < $item->quantity) {
$rows[$type][$order->account_id][$packing][$item->product_id][] = array(
'number' => $order->id,
'destination' => $destination,
'size' => $item->product_id,
'name' => $name,
'address' => $address,
'phone' => $phone
);
$i++;
}
}
// if($order->id == 176) {
// var_dump($rows[$type][$order->account_id][$packing]);
// }
}
$this->weight = 1;
$pickups = count($rows['pickups']);
for($i = 0; $i < $pickups; $i++) {
$account =& $rows['pickups'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$deliveries = count($rows['deliveries']);
for($i = 0; $i < $deliveries; $i++) {
$account =& $rows['deliveries'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$rows['output'] = $rows['pickups'];
array_push($rows['output'], $rows['deliveries']);
$output = '';
foreach($rows['output'] as $account_id => $boxes) {
if(!empty($boxes['output'])) {
foreach($boxes['output'] as $labels) {
if(!empty($labels)) {
foreach($labels as $label) {
$output .= implode(',', $label) . "<br>";
}
}
}
}
}
The _compareBoxes method looks like this:
private function _compareBoxes($a, $b) {
if($a['size'] == $b['size']) {
return 0;
}
if($this->weight == 1) {
// Medium first, then Large
return ($a['size'] < $b['size']) ? -1 : 1;
}
if($this->weight == -1) {
// Large first, then Medium
return ($a['size'] > $b['size']) ? -1 : 1;
}
}

Categories