Error in print prdf. Undefined property $_localeResolver - magento2

I am facing the below issue in print sales pdf in magento2 after upgrading the magento version.
1 exception(s):
Exception #0 (Exception): Notice: Undefined property:
InvoicePdfimage\Model\Magento\Sales\Order\Pdf\Invoice::$_localeResolver
in /InvoicePdfimage/Model/Magento/Sales/Order/Pdf/Invoice.php

Vendor/module/etc/di.xml,
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Sales\Model\Order\Pdf\Invoice" type="Vendor\module\Model\Order\Pdf\InvoicePdf"/>
</config>
Now you can create Vendor\module\Model\Order\Pdf\InvoicePdf.php file & add the below code,
<?php
namespace Vendor\module\Model\Order\Pdf;
use \Magento\Sales\Model\Order\Pdf\Invoice;
class InvoicePdf extends Invoice
{
public function getPdf($invoices = []) {
$this->_beforeGetPdf();
$this->_initRenderer('invoice');
$pdf = new \Zend_Pdf();
$this->_setPdf($pdf);
$style = new \Zend_Pdf_Style();
$this->_setFontBold($style, 10);
foreach ($invoices as $invoice) {
if ($invoice->getStoreId()) {
$this->_localeResolver->emulate($invoice->getStoreId());
$this->_storeManager->setCurrentStore($invoice->getStoreId());
}
$page = $this->newPage();
$order = $invoice->getOrder();
$this->insertLogo($page, $invoice->getStore());
$this->insertAddress($page, $invoice->getStore());
$this->insertOrder(
$page,
$order,
$this->_scopeConfig->isSetFlag(
self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
$order->getStoreId()
)
);
$this->insertDocumentNumber($page, __('Invoice # ') . $invoice->getIncrementId());
$this->_drawHeader($page);
foreach ($invoice->getAllItems() as $item) {
if ($item->getOrderItem()->getParentItem()) {
continue;
}
$this->_drawItem($item, $page, $order);
$page = end($pdf->pages);
}
$this->insertTotals($page, $invoice);
if ($invoice->getStoreId()) {
$this->_localeResolver->revert();
}
$this->drawNotice($page);
}
$this->_afterGetPdf();
return $pdf;
}
protected function drawNotice(\Zend_Pdf_Page $page) {
$iFontSize = 10;
$iColumnWidth = 520;
$iWidthBorder = 260;
$iXCoordinateText = 30;
$sEncoding = 'UTF-8';
$this->draw -= 10;
try {
$oFont = $this->_setFontRegular($page, $iFontSize);
$iXCoordinateText = $this->getAlignCenter($sNotice, $iXCoordinateText, $iColumnWidth, $oFont, $iFontSize);
$page->setLineColor(new \Zend_Pdf_Color_Rgb(1, 0, 0));
$iXCoordinateBorder = $iXCoordinateText - 10;
$page->drawLine($iXCoordinateBorder, $this->draw, $iXCoordinateBorder + $iWidthBorder, $this->draw);
$this->draw -= 15;
$page->drawText($sNotice, $iXCoordinateText, $this->draw, $sEncoding);
$this->draw -= 10;
$page->drawLine($iXCoordinateBorder, $this->draw, $iXCoordinateBorder + $iWidthBorder, $this->draw);
$this->draw -= 10;
} catch (\Exception $exception) {
}
}
protected function _drawHeader(\Zend_Pdf_Page $page)
{
$this->_setFontRegular($page, 10);
$page->setFillColor(new \Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
$page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5));
$page->setLineWidth(0.5);
$page->drawRectangle(25, $this->y, 570, $this->y - 15);
$this->y -= 10;
$page->setFillColor(new \Zend_Pdf_Color_Rgb(0, 0, 0));
//columns headers
$lines[0][] = ['text' => __('Products'), 'feed' => 35];
$lines[0][] = ['text' => __('SKU'), 'feed' => 290, 'align' => 'right'];
// custom column
$lines[0][] = ['text' => __('Qty'), 'feed' => 435, 'align' => 'right'];
$lines[0][] = ['text' => __('Price'), 'feed' => 360, 'align' => 'right'];
$lineBlock = ['lines' => $lines, 'height' => 5];
$this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
$page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
$this->y -= 20;
}
}

Related

Woocommerce Custom Place Order API not working cart empty

public function RetriveCart($request){
global $woocommerce;
$woocommerce->frontend_includes();
$user_id = $request['user_id'];
wp_set_current_user( $user_id );
add_action('woocommerce_cart_calculate_fees', array($this,'woo_cart_fee_update'));
$woocommerce->session = new WC_Session_Handler();
$woocommerce->session->init();
$woocommerce->customer = new WC_Customer( get_current_user_id(), true );
$woocommerce->cart = new WC_Cart();
$items = $woocommerce->cart->get_cart();
if(empty($items)){
$response['status'] = 0;
$response['message'] = __("Cart is empty", self::domainText);
$response['data'] = new stdClass();
return new WP_REST_Response($response, 200);
}
foreach($items as $item => $values) {
$_product = wc_get_product( $values['product_id']);
$cart[] = array('key'=>$item,
'product_id'=>$values['product_id'],
'title'=>$_product->get_title(),
'quantity'=>$values['quantity'],
'price'=>$_product->get_price(),
'subtotal'=> strval(($_product->get_price()+$addons_price) * $values['quantity']),
'currency_symbol'=>get_woocommerce_currency_symbol(),
);
}
WC()->cart->calculate_totals();
$shipping = $woocommerce->cart->fee_total;
$cart_summary = array('sub_total'=>$woocommerce->cart->subtotal,
'shipping_amount'=>$shipping,
'order_type'=>$order_type,
'is_deliverable'=>$is_deliverable,
'discount_amount'=>$woocommerce->cart->get_cart_discount_total(),
'tax_amount'=>$woocommerce->cart->tax_total,
'total_amount'=>$woocommerce->cart->total,
'currency_symbol'=>get_woocommerce_currency_symbol(),
);
$output['cart_summary'] = $cart_summary;
$output['items'] = $cart;
$response['status'] = 1;
$response['message'] = __("Cart Items found", self::domainText);
$response['data'] = $output;
return new WP_REST_Response($response, 200);
}
public function newOrder($request){
global $wpdb,$woocommerce;
$woocommerce->frontend_includes();
$orderRequest = $request['order'];
$user_id = $orderRequest['user_id'];
wp_set_current_user( $user_id );
$woocommerce->session = new WC_Session_Handler();
$woocommerce->session->init();
$woocommerce->customer = new WC_Customer( get_current_user_id(), true );
$woocommerce->cart = new WC_Cart();
if ($woocommerce->cart->get_cart_contents_count() == 0) {
$response['status'] = 0;
$response['message'] = __('Cart is empty', self::domainText);
$response['data'] = new stdClass();
return new WP_REST_Response($response, 200);
}
$cart = $woocommerce->cart->get_cart();
$order = wc_create_order(array('customer_id' => get_current_user_id()));
$order_id = $order->id;
foreach($cart as $item => $values) {
$product = wc_get_product($values['product_id']);
$quantity = (int)$values['quantity'];
if(wc_prices_include_tax()){
$product_price = wc_get_price_including_tax($product);
}else{
$product_price = wc_get_price_excluding_tax($product);
}
$variationsArray = array();
$order->add_product($product, $quantity, $variationsArray);
}
$order->set_address( $orderRequest['billing_address'], 'billing' );
$order->set_address( $orderRequest['shipping_address'], 'shipping' );
$order->set_payment_method($orderRequest['payment_method']['id']);
$get_fees = $woocommerce->cart->get_fees();
foreach($get_fees as $fee_data){
$item_fee = new WC_Order_Item_Fee();
$item_fee->set_name($fee_data->name);
$item_fee->set_amount($fee_data->amount);
$item_fee->set_tax_class( '' );
$item_fee->set_tax_status( 'none' );
$item_fee->set_total($fee_data->total);
$item_fee->save();
$order->add_item($item_fee);
}
if(!empty($coupon)){
$order->apply_coupon($coupon[0]);
}
$order->update_status('created');
$order->calculate_totals();
$woocommerce->cart->empty_cart();
$customer_id = $order->get_user_id();
$response['status'] = 1;
$response['message'] = __("Order $order_id is successfully placed", self::domainText);
$response['order_id'] = $order_id;
return new WP_REST_Response($response, 200);
}
In RetriveCart() all datas are there when I try place order. Its give me an empty cart and fees not added.

Laravel - paypal keep maximum 30 second exceed

Paypal in laravel keep returning maximum 30 seconds timeout, sometime it can proceed smoothly but when cart product increase, it will keep return this error, and sometime the error is when create payment, sometime is execute payment, extremely not stable, how can i solve this? i have tried extend the timeout setting to 300, but it still return me a timeout error.
here is my create payment code:
$item_array = [];
$shipping = $request->shipping;
$tax = $request->tax;
$tax_amount = 0;
$subtotal = $total = 0;
$currency = "MYR";
$payer = new Payer();
$payer->setPaymentMethod("paypal");
$credential = new OAuthTokenCredential(env('PAYPAL_SANDBOX_CLIENT_ID'), env('PAYPAL_SANDBOX_SECRET'));
$apiContext = new ApiContext($credential, null);
$order = Order::findOrFail($id);
// change order product status
foreach ($order->orderProduct as $order_product_key => $order_product) {
// get variant
$variant_title_array = array();
if (count($order_product->variantValue) > 0) {
foreach ($order_product->variantValue->variantOption as $variant_option) {
array_push($variant_title_array, $variant_option->name);
}
}
$variant= "";
if (count($variant_title_array) > 0) {
$variant = " ( ".implode(', ', $variant_title_array)." )";
}
// calculate product price and promotion price
$product_price = $compare_price = "";
$product_promotion = get_cart_product_promotion ($order_product, $order);
$product_price = get_product_price_in_cart ($order_product);
// if promotion exits
if (count($product_promotion) != 0) {
$compare_price = get_product_price_in_cart ($order_product);
$product_price = calculate_product_price_after_promotion ($compare_price, $product_promotion);
}
$item = new Item();
$item->setName($order_product->product->title . $variant)
->setCurrency($currency)
->setQuantity($order_product->quantity)
->setSku(get_product_sku_in_cart ($order_product)) // Similar to `item_number` in Classic API
->setPrice((float) str_replace('RM ','', $product_price));
$item_array[$order_product_key] = $item;
$subtotal += (float) str_replace('RM ','', $product_price) * $order_product->quantity;
}
// calculate tax
$tax_amount = ($subtotal * $tax) / 100;
$itemList = new ItemList();
$itemList->setItems($item_array);
$shipping_address = new ShippingAddress();
$shipping_address->setCity('City')
->setCountryCode('AR')
->setPostalCode('200')
->setLine1('Adress Line1')
->setState('State')
->setRecipientName('Recipient Name');
$details = new Details();
$details->setShipping($shipping)
->setTax($tax_amount)
->setSubtotal($subtotal);
$total = $subtotal + $shipping + $tax_amount;
$amount = new Amount();
$amount->setCurrency($currency)
->setTotal($total)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
$baseUrl = url('/');
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true")
->setCancelUrl("$baseUrl/ExecutePayment.php?success=false");
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
$request = clone $payment;
try {
$payment->create($apiContext);
} catch (PayPalConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData(); // Prints the detailed error message
die($ex);
} catch (Exception $ex) {
die($ex);
}
$approvalUrl = $payment->getApprovalLink();
$response = array(
'paymentID' => $payment->id
);
return json_encode($response);
here is my execute payment code:
$shipping = $request->shipping;
$tax = $request->tax;
$tax_amount = 0;
$subtotal = $total = 0;
$currency = "MYR";
$credential = new OAuthTokenCredential(env('PAYPAL_SANDBOX_CLIENT_ID'), env('PAYPAL_SANDBOX_SECRET'));
$apiContext = new ApiContext($credential, null);
$paymentId = $request->paymentID;
$payment = Payment::get($paymentId, $apiContext);
$transaction = new Transaction();
$amount = new Amount();
$details = new Details();
$order = Order::findOrFail($id);
// store order address
$order_address = OrderAddress::firstOrCreate(
[
'order_id' => $order->id
],
[
'name' => $request->shipping_name ,
'phone' => $request->shipping_phone ,
'address1' => $request->shipping_address1 ,
'address2' => $request->shipping_address2 ,
'postcode' => $request->shipping_postcode ,
'state' => $request->shipping_state ,
'country' => $request->shipping_country ,
'city' => $request->shipping_city ,
'order_id' => $order->id
]
);
// update address if exist
$order_address->update([
'name' => $request->shipping_name ,
'phone' => $request->shipping_phone ,
'address1' => $request->shipping_address1 ,
'address2' => $request->shipping_address2 ,
'postcode' => $request->shipping_postcode ,
'state' => $request->shipping_state ,
'country' => $request->shipping_country ,
'order_id' => $order->id
]);
// change order product status
foreach ($order->orderProduct as $order_product) {
// calculate product price and promotion price
$product_price = $compare_price = "";
$product_promotion = get_cart_product_promotion ($order_product, $order);
$product_price = get_product_price_in_cart ($order_product);
// if promotion exits
if (count($product_promotion) != 0) {
$compare_price = get_product_price_in_cart ($order_product);
$product_price = calculate_product_price_after_promotion ($compare_price, $product_promotion);
}
$product_price = (float) str_replace("RM ","",$product_price);
// add promotion to order product if promotion exist
if ($compare_price != "") {
$order_product->order_promotion_id = $order->orderPromotion->promotion_id;
}
$order_product->price = $product_price;
$order_product->status = 2;
$subtotal += $product_price * $order_product->quantity;
$order_product->save();
}
// calculate tax
$tax_amount = ($subtotal * $tax) / 100;
// change cart detail
$current_date_time = Carbon::now();
$order->update([
'subtotal' => $subtotal,
'status' => 2,
'submited_on' => $current_date_time,
'payment_method' => "paypal"
]);
// update shipping fees
if ($shipping > 0) {
$order->shipping_fees = $shipping;
}
// update tax
if ($tax > 0) {
$order->tax = ($subtotal * $tax) / 100;
}
$order->save();
// paypal settings
$total = $subtotal + $shipping + $tax_amount;
$details->setShipping($shipping)
->setTax($tax_amount)
->setSubtotal($subtotal);
$amount->setCurrency($currency);
$amount->setTotal($total);
$amount->setDetails($details);
$transaction->setAmount($amount);
// Add the above transaction object inside our Execution object.
$execution->addTransaction($transaction);
try {
$result = $payment->execute($execution, $apiContext);
try {
$payment = Payment::get($paymentId, $apiContext);
} catch (Exception $ex) {
exit(1);
}
} catch (Exception $ex) {
exit(1);
}
echo "success";

How to get new uploaded file name in controller?

1.Can anyone suggest me how to get new uploaded file name in controller action? I'm using validation rule like..
'validators' => [
[
'name' => '\User\Validator\ImageValidator',
'options' => [
'minSize' => '1',
'maxSize' => '1024',
'newFileName' => time() . 'newFileName2',
'uploadPath' => getcwd() . '/public/uploads/platform/'
],
],
],
and it's working properly but I have no idea to how to get file name or error in controller action.
How to overwrite the minSize and maxSize error message? My validator file code is:
namespace User\Validator;
use Zend\Validator\File\Extension;
use Zend\File\Transfer\Adapter\Http;
use Zend\Validator\File\FilesSize;
use Zend\Filter\File\Rename;
use Zend\Validator\File\MimeType;
use Zend\Validator\AbstractValidator;
class ImageValidator extends AbstractValidator
{
const FILE_EXTENSION_ERROR = 'invalidFileExtention';
const FILE_NAME_ERROR = 'invalidFileName';
const FILE_INVALID = 'invalidFile';
const FALSE_EXTENSION = 'fileExtensionFalse';
const NOT_FOUND = 'fileExtensionNotFound';
const TOO_BIG = 'fileFilesSizeTooBig';
const TOO_SMALL = 'fileFilesSizeTooSmall';
const NOT_READABLE = 'fileFilesSizeNotReadable';
public $minSize = 64; //KB
public $maxSize = 1024; //KB
public $overwrite = true;
public $newFileName = null;
public $uploadPath = './data/';
public $extensions = array('jpg', 'png', 'gif', 'jpeg');
public $mimeTypes = array(
'image/gif',
'image/jpg',
'image/png',
);
protected $messageTemplates = array(
self::FILE_EXTENSION_ERROR => "File extension is not correct",
self::FILE_NAME_ERROR => "File name is not correct",
self::FILE_INVALID => "File is not valid",
self::FALSE_EXTENSION => "File has an incorrect extension",
self::NOT_FOUND => "File is not readable or does not exist",
self::TOO_BIG => "// want to overwrite these message",
self::TOO_SMALL => "// want to overwrite these message",
self::NOT_READABLE => "One or more files can not be read",
);
protected $fileAdapter;
protected $validators;
protected $filters;
public function __construct($options)
{
$this->fileAdapter = new Http();
parent::__construct($options);
}
public function isValid($fileInput)
{
$options = $this->getOptions();
$extensions = $this->extensions;
$minSize = $this->minSize;
$maxSize = $this->maxSize;
$newFileName = $this->newFileName;
$uploadPath = $this->uploadPath;
$overwrite = $this->overwrite;
if (array_key_exists('extensions', $options)) {
$extensions = $options['extensions'];
}
if (array_key_exists('minSize', $options)) {
$minSize = $options['minSize'];
}
if (array_key_exists('maxSize', $options)) {
$maxSize = $options['maxSize'];
}
if (array_key_exists('newFileName', $options)) {
$newFileName = $options['newFileName'];
}
if (array_key_exists('uploadPath', $options)) {
$uploadPath = $options['uploadPath'];
}
if (array_key_exists('overwrite', $options)) {
$overwrite = $options['overwrite'];
}
$fileName = $fileInput['name'];
$fileSizeOptions = null;
if ($minSize) {
$fileSizeOptions['min'] = $minSize*1024 ;
}
if ($maxSize) {
$fileSizeOptions['max'] = $maxSize*1024 ;
}
if ($fileSizeOptions) {
$this->validators[] = new FilesSize($fileSizeOptions);
}
$this->validators[] = new Extension(array('extension' => $extensions));
if (! preg_match('/^[a-z0-9-_]+[a-z0-9-_\.]+$/i', $fileName)) {
$this->error(self::FILE_NAME_ERROR);
return false;
}
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
if (! in_array($extension, $extensions)) {
$this->error(self::FILE_EXTENSION_ERROR);
return false;
}
if ($newFileName) {
$destination = $newFileName.".$extension";
if (! preg_match('/^[a-z0-9-_]+[a-z0-9-_\.]+$/i', $destination)) {
$this->error(self::FILE_NAME_ERROR);
return false;
}
} else {
$destination = $fileName;
}
$renameOptions['target'] = $uploadPath.$destination;
$renameOptions['overwrite'] = $overwrite;
$this->filters[] = new Rename($renameOptions);
$this->fileAdapter->setFilters($this->filters);
$this->fileAdapter->setValidators($this->validators);
if ($this->fileAdapter->isValid()) {
$this->fileAdapter->receive();
return true;
} else {
$messages = $this->fileAdapter->getMessages();
if ($messages) {
$this->setMessages($messages);
foreach ($messages as $key => $value) {
$this->error($key);
}
} else {
$this->error(self::FILE_INVALID);
}
return false;
}
}
}
I'm new to Zend framework so unable to understand how this validator code is working.
Thank you

Add custom text around a barcode with Zend_Pdf (Zend Framework 1.12)

I want to add a custom text around a barcode inside a PDF-document using Zend_Pdf and Zend_Barcode. Right now it is only showing the barcode but I want to add my custom text too above it.
So now I am getting this:
but I want this:
Here is my code:
$pdf = new Zend_Pdf();
$hidden =$_POST['hidden'];
$quantityfrom =$_POST['quantity_from'];
$quantityto =$_POST['quantity_to'];
//Here is code for update the Quantity
$product_id = $_POST['product_id'];
$table = new Account_Model_DbTable_Products();
$query = $table->updateQuantity($product_id,$quantityto);
Zend_Barcode::setBarcodeFont(dirname(ROOT_PATH) . '/inventory/library/Zend/Barcode/Object/fonts/open-sans/OpenSans-Semibold.ttf');
$numberOfPages = ceil(($quantityto-$quantityfrom)/15);
$equipmentCount = $quantityto-$quantityfrom+1;
for($i = 1; $i <= $numberOfPages; $i++)
{
$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
$width = $page->getWidth(); // A4 : 595
$height = $page->getHeight(); // A4 : 842
$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA), 20);
$pdf->pages[] = $page;
}
$index = 0;
for($j=1 ; $j<=$numberOfPages;$j++){
if($equipmentCount > 10)
{
$barcodesOnThisPage = 10;
$equipmentCount = $equipmentCount - 10;
}
else
{
$barcodesOnThisPage = $equipmentCount;
}
echo $barcodesOnThisPage."</br>";
$k = 1;
for($i=1;$i<=$barcodesOnThisPage;$i++){
$num_padded = sprintf("%04d", $quantityfrom);
$barcodeOptions = array(
'text' => $hidden.$num_padded,
'barHeight' =>100,
);
$rendererOptions = array(
'topOffset' => 80*$k,
'horizontalPosition' =>'left'
);
$pdfWithBarcode = Zend_Barcode::factory('code39', 'pdf',
$barcodeOptions, $rendererOptions)->setResource($pdf,$index)->draw();
$pdfWithBarcode->save('testBarcode.pdf');
$k++;
$quantityfrom++;
}
$index++;
}
$this->_redirect('/testBarcode.pdf');
}

Webmaster Tool Api Crawl Optimize

By using webmaster tool API to parse data from google. The speed of downloading is very slow, Is there any way to optimize, Or use another method. It can take more than hour depending on the data.
Regards.
const HOST = "https://www.google.com";
const SERVICEURI = "/webmasters/tools/";
public function __construct()
{
$this->_auth = $this->_loggedIn = $this->_domain = false;
$this->_data = array();
}
public function getArray($domain)
{
if ($this->_validateDomain($domain)) {
if ($this->_prepareData()) {
return $this->_data;
} else {
throw new Exception('Error receiving crawl issues for ' . $domain);
}
} else {
throw new Exception('The given domain is not connected to your Webmastertools account!');
exit;
}
}
public function getCsv($domain, $localPath = false)
{
if ($this->_validateDomain($domain)) {
if ($this->_prepareData()) {
if (!$localPath) {
$this->_HttpHeaderCSV();
$this->_outputCSV();
} else {
$this->_outputCSV($localPath);
}
} else {
throw new Exception('Error receiving crawl issues for ' . $domain);
}
} else {
throw new Exception('The given domain is not connected to your Webmastertools account!');
exit;
}
}
public function getSites()
{
if ($this->_loggedIn) {
$feed = $this->_getData('feeds/sites/');
if ($feed) {
$doc = new DOMDocument();
$doc->loadXML($feed);
$sites = array();
foreach ($doc->getElementsByTagName('entry') as $node) {
array_push($sites, $node->getElementsByTagName('title')->item(0)->nodeValue);
}
return (0 < sizeof($sites)) ? $sites : false;
} else {
return false;
}
} else {
return false;
}
}
public function login($mail, $pass)
{
$postRequest = array(
'accountType' => 'HOSTED_OR_GOOGLE',
'Email' => $mail,
'Passwd' => $pass,
'service' => "sitemaps",
'source' => "Google-WMTdownloadscript-0.11-php"
);
// Before PHP version 5.2.0 and when the first char of $pass is an # symbol,
// send data in CURLOPT_POSTFIELDS as urlencoded string.
if ('#' === (string) $pass[0] || version_compare(PHP_VERSION, '5.2.0') < 0) {
$postRequest = http_build_query($postRequest);
}
$ch = curl_init(self::HOST . '/accounts/ClientLogin');
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $postRequest,
));
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if (200 != $info['http_code']) {
throw new Exception('Login failed!');
exit;
} else {
#preg_match('/Auth=(.*)/', $output, $match);
if (isset($match[1])) {
$this->_auth = $match[1];
$this->_loggedIn = true;
return true;
} else {
throw new Exception('Login failed!');
exit;
}
}
}
private function _prepareData()
{
if ($this->_loggedIn) {
$currentIndex = 1;
$maxResults = 100;
$encUri = urlencode($this->_domain);
/*
* Get the total result count / result page count
*/
$feed = $this->_getData("feeds/{$encUri}/crawlissues?start-index=1&max-results=1");
if (!$feed) {
return false;
}
$doc = new DOMDocument();
$doc->loadXML($feed);
$totalResults = (int) $doc->getElementsByTagNameNS('http://a9.com/-/spec/opensearch/1.1/', 'totalResults')->item(0)->nodeValue;
$resultPages = (0 != $totalResults) ? ceil($totalResults / $maxResults) : false;
unset($feed, $doc);
if (!$resultPages) {
return false;
}
/*
* Paginate over issue feeds
*/
else {
// Csv data headline
$this->_data = Array(
Array(
'Issue Id',
'Crawl type',
'Issue type',
'Detail',
'URL',
'Date detected',
'Last detected'
)
);
while ($currentIndex <= $resultPages) {
$startIndex = ($maxResults * ($currentIndex - 1)) + 1;
$feed = $this->_getData("feeds/{$encUri}/crawlissues?start-index={$startIndex}&max-results={$maxResults}");
$doc = new DOMDocument();
$doc->loadXML($feed);
foreach ($doc->getElementsByTagName('entry') as $node) {
$issueId = str_replace(self::HOST . self::SERVICEURI . "feeds/{$encUri}/crawlissues/", '', $node->getElementsByTagName('id')->item(0)->nodeValue);
$crawlType = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'crawl-type')->item(0)->nodeValue;
$issueType = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'issue-type')->item(0)->nodeValue;
$detail = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'detail')->item(0)->nodeValue;
$url = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'url')->item(0)->nodeValue;
$dateDetected = date('d/m/Y', strtotime($node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'date-detected')->item(0)->nodeValue));
$updated = date('d/m/Y', strtotime($node->getElementsByTagName('updated')->item(0)->nodeValue));
// add issue data to results array
array_push($this->_data, Array(
$issueId,
$crawlType,
$issueType,
$detail,
$url,
$dateDetected,
$updated
));
}
unset($feed, $doc);
$currentIndex++;
}
return true;
}
} else {
return false;
}
}
private function _getData($url)
{
if ($this->_loggedIn) {
$header = array(
'Authorization: GoogleLogin auth=' . $this->_auth,
'GData-Version: 2'
);
$ch = curl_init(self::HOST . self::SERVICEURI . $url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_ENCODING => 1,
CURLOPT_HTTPHEADER => $header
));
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return (200 != $info['http_code']) ? false : $result;
} else {
return false;
}
}
private function _HttpHeaderCSV()
{
header('Content-type: text/csv; charset=utf-8');
header('Content-disposition: attachment; filename=gwt-crawlerrors-' . $this->_getFilename());
header('Pragma: no-cache');
header('Expires: 0');
}
private function _outputCSV($localPath = false)
{
$outstream = !$localPath ? 'php://output' : $localPath . DIRECTORY_SEPARATOR . $this->_getFilename();
$outstream = fopen($outstream, "w");
if (!function_exists('__outputCSV')) {
function __outputCSV(&$vals, $key, $filehandler)
{
fputcsv($filehandler, $vals); // add parameters if you want
}
}
array_walk($this->_data, "__outputCSV", $outstream);
fclose($outstream);
}
private function _getFilename()
{
return 'gwt-crawlerrors-' . parse_url($this->_domain, PHP_URL_HOST) . '-' . date('Ymd-His') . '.csv';
}
private function _validateDomain($domain)
{
if (!filter_var($domain, FILTER_VALIDATE_URL)) {
return false;
}
$sites = $this->getSites();
if (!$sites) {
return false;
}
foreach ($sites as $url) {
if (parse_url($domain, PHP_URL_HOST) == parse_url($url, PHP_URL_HOST)) {
$this->_domain = $domain;
return true;
}
}
return false;
}
The url from Google is in error Google has added a false extension look carefully and you will see it.
Google Crap!
Your site is probably fine.