Merging times in php - merge

I'm trying to find the best way to merges times ... working on a schedule where users have 2 things :
Availabilities and Assigned Hours for X days.
The structure is the same for both and it look like this :
For a specific date let say (2012-10-07) the availability :
[2012-10-07]
[0][start_time] => 08:30
[end_time] => 13:30
[1][start_time] => 16:30
[end_time] => 23:30
Now for that specific day , he might be assigned and the result of my query look like :
[2012-10-07][0][start_time] => 08:30
[end_time] => 09:30
[1][start_time] => 10:30
[end_time] => 11:30
[2][start_time] => 17:00
[end_time] => 18:30
The results of the merge should look like :
[2012-10-07] [0][start_time]=> 08:30
[start_time]=> 09:30
[assigned]=> true
[1][start_time]=> 09:30
[start_time]=> 10:30
[assigned]=> false
[2][start_time]=> 10:30
[start_time]=> 11:30
[assigned]=> true
[3][start_time]=> 11:30
[start_time]=> 13:30
[assigned]=> false
[4][start_time]=> 16:30
[start_time]=> 17:00
[assigned]=> false
[5][start_time]=> 16:30
[start_time]=> 17:00
[assigned]=> false
[6][start_time]=> 17:00
[start_time]=> 18:30
[assigned]=> true
[7][start_time]=> 18:30
[start_time]=> 23:30
[assigned]=> false
Now when joining both on the calendar the availabilities are in green(false) and assigned in red (assigned = true) .
What i did was loop on availabilities , convert the start/end time to UNIX timestamps and then loop on each assigned time and converted to UNIX timestamps .
Then testing all cases if the time is inside the availability or if its outside , add a temp array and loop while no changes are made to the final array .
(Because each time i generate a new time i have to loop again on the assigned hours)
it works but i dont like the way I'm doing it ... is there a better way ?
UPDATE :
For those who want to see the full working code here it is :
function removeSessionsFromSchedule($schedule,$remove){
$modified = false;
if(is_array($schedule) && count($schedule) > 0 && is_array($remove) && count($remove) > 1) {
if($modified) {
break;
}
$pos = 0;
$countdispo = count($dispo);
foreach($schedule as $s => $dispo) {
$pos = 0;
$countdispo = count($dispo);
foreach($dispo as $d) {
$abs = $remove[$s];
$counter = 0;
// dispo debut/end
$dis_s = strtotime($d['heure_debut']);
$dis_e = strtotime($d['heure_fin']);
if(is_array($abs) && count($abs) > 0) {
foreach($abs as $a) {
// absence start/end
$abs_s = strtotime($a['heure_debut']);
$abs_e = strtotime($a['heure_fin']);
// (2) [a_s]---[ds - de]---[a_e]
if($abs_s <= $dis_s && $abs_e >= $dis_e) {
// delete availabilities
unset($schedule[$s][$pos]);
$modified = false;
}
// (7)[as == ds] && [ae < de]
else if($abs_s == $dis_s && $abs_e < $dis_e) {
unset($schedule[$s][$pos]);
$schedule[$s][$pos] = $d;
$schedule[$s][$pos]['heure_debut'] = date("H:i",$abs_e);
$schedule[$s][$pos]['heure_fin'] = date("H:i",$dis_e);
$modified = true;
break;
}
// (6) [ds -de] --- [as ae] return dispo as is
else if($abs_s >= $dis_e){
unset($schedule[$s][$pos]);
$schedule[$s][$pos] =$d;
$modified = false;
}
// (5)[as ae] [ds -de] --- return dispo as is
else if($abs_e <= $dis_s){
unset($schedule[$s][$pos]);
$schedule[$s][$pos]= $d;
$modified = false;
}
// (1)[ds] --- [as] --- [ae] --- [de] (duplicate dis with new times)
else if($abs_s > $dis_s && $abs_e <= $dis_e) {
// new times as : // s1 = ds-as && s2 = ae-de
unset($schedule[$s][$pos]);
$schedule[$s][$pos] =$d;
$schedule[$s][$pos+1] =$d;
$schedule[$s][$pos]['heure_debut'] = date("H:i",$dis_s);
$schedule[$s][$pos]['heure_fin'] = date("H:i",$abs_s);
$schedule[$s][$pos + 1]['heure_debut'] = date("H:i",$abs_e);
$schedule[$s][$pos + 1]['heure_fin'] = date("H:i",$dis_e);
//$pos++;
$modified = true;
break;
}
// (3)[as] -- [ds] --- [ae] -- [de]
else if($abs_s < $dis_s && $abs_e < $dis_e) {
unset($schedule[$s][$pos]);
$schedule[$s][$pos] =$d;
$schedule[$s][$pos]['heure_debut'] = date("H:i",$abs_e);
$schedule[$s][$pos]['heure_fin'] = date("H:i",$dis_e);
$modified = true;
break;
}
// (4) [ds]---[as]--- [de]--- [ae]
else if($abs_s > $dis_s && $abs_s < $dis_e && $abs_e > $dis_e) {
unset($schedule[$s][$pos]);
$schedule[$s][$pos] =$d;
$schedule[$s][$pos]['heure_debut'] = date("H:i",$dis_s);
$schedule[$s][$pos]['heure_fin'] = date("H:i",$abs_s);
$modified = true;
break;
}
else {$modified = false ;}
}
} else {$modified =false;}
$pos++;
}
}
}
else {$modified = false;}
if($modified) {
$schedule = removeSessionsFromSchedule($schedule,$remove);
}
return $schedule;
}
The Function that will merge the times :
function mergeSessionFromSchedule($schedule ,$seances) {
$sessions = removeSessionsFromSchedule($schedule,$seances);
$mergedSessions = array_merge_recursive($sessions , $seances);
foreach($mergedSessions as $s => $val) {
$sortedSessions[$s] = subval_sort_by_time($val,'heure_debut');
}
return $sortedSessions ;
}
Helpers :
function subval_sort_by_time($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtotime($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}

Here is my solution:
<?php
class SessionHandler {
private $keys = array();
private $times = array();
private $slots = array();
private $merged = array();
function __construct($available, $assigned) {
$this->times = array(
'available' => $available,
'assigned' => $assigned
);
$this->slots = array(
'available' => array(),
'assigned' => array(),
'excluded' => array()
);
$this->getKeys($this->times['available']);
$this->loadSessions($this->keys[0], $this->keys[1]);
}
private function getKeys($arr) {
if (count($arr)) {
$this->keys = array_keys($arr[0]);
} else {
throw new Exception('Invalid array format');
}
}
private function loadSessions($start, $end) {
foreach ($this->times as $type => $periods) {
foreach ($periods as $hours) {
$this->slots[$type][] = $hours[$start].'-'.$hours[$end];
$this->merged[] = strtotime($hours[$start]);
$this->merged[] = strtotime($hours[$end]);
}
}
$this->merged = array_unique($this->merged);
sort($this->merged);
$hours = $this->times['available'];
for ($i = 0; $i < count($hours) - 1; $i++) {
$this->slots['excluded'][] = $hours[$i][$end].'-'.$hours[$i + 1][$start];
}
}
public function mergeSessions() {
$result = array();
for ($i = 0; $i < count($this->merged) - 1; $i++) {
$start_hour = date('H:i', $this->merged[$i]);
$end_hour = date('H:i', $this->merged[$i + 1]);
$slot = $start_hour . '-' . $end_hour;
if (!in_array($slot, $this->slots['excluded'])) {
$assigned = in_array($slot, $this->slots['assigned']);
$result[] = array(
$this->keys[0] => $start_hour,
$this->keys[1] => $end_hour,
'assigned' => $assigned ? "true" : "false"
);
}
}
return($result);
}
}
$availability = array(
'2012-10-07' => array(
array('start_time' => '08:30', 'end_time' => '13:30'),
array('start_time' => '16:30', 'end_time' => '23:30')
)
);
$assignments = array(
'2012-10-07' => array(
array('start_time' => '08:30', 'end_time' => '09:30'),
array('start_time' => '10:30', 'end_time' => '11:30'),
array('start_time' => '17:00', 'end_time' => '18:30')
)
);
$sessions = array();
foreach ($availability as $day => $available) {
$assigned = isset($assignments[$day]) ? $assignments[$day] : array();
$SH = new SessionHandler($available, $assigned);
$sessions[$day] = $SH->mergeSessions();
}
?>
<!DOCTYPE html>
<html>
<body>
<pre><?php print_r($sessions) ?></pre>
</body>
</html>

Related

Error in print prdf. Undefined property $_localeResolver

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

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

Where can I change the calendar start date to Sunday from Monday

I am trying to make this calendar start on Sunday instead of Monday. I've looked through all the help files I can Google on this topic & cannot find any that have any lines of code that I can reference. Am I missing some? Or can some one point me to the point I need to change in order to make it start on Sunday instead of Monday?
<?php
/**
* Copyright (C) 2006-2014 Center Stage Software
* 1191 Luxton Street, Seaside, California 93955
* All Rights Reserved
*/
// ensure that this file is called up by another file
defined('_VALID_ACCESS') or die('Direct access of this file is prohibited.');
/**
* renderEventCalendar - Creates a calendar display of events for one month.
*
* #global (Array) $cstage
*/
function renderEventCalendar() {
global $cstage, $path;
// Result variable.
$calendar = '';
// Calculate first and last day of the month.
$firstDayTimestamp = strtotime($_SESSION[SYS_USER]['search']['Month'].'-01 07:00:00');
list($year,$month) = explode("-",$_SESSION[SYS_USER]['search']['Month']);
if( $month == 12 ) {
$month = 00;
$year += 1;
}
$lastDayTimestamp = strtotime("$year-".($month+1).'-01 08:00:00') - 86400; // minus 24 hours and add 1-day-light-savings-hour
// TODO: Remove the following calendar debugging code.
// print "<h1>first=$firstDayTimestamp; last=$lastDayTimestamp</h1>";
// Build query to retrieve entries for that month.
$aryEvents = array();
$extraSqlFields = '';
$extraSqlJoins = '';
$extraSqlConditions = '';
if( !empty($_SESSION[SYS_USER]['domain']) ) {
$extraSqlJoins .= 'LEFT JOIN "domainlist" AS "domain2" ON "domain2"."master_id" = "master"."master_id" ';
$extraSqlConditions .= sprintf('AND "domain2"."domain"=\'%s\' '
,$_SESSION[SYS_USER]['domain']
);
}
if( !empty($_SESSION[SYS_USER]['search']['Theatre']) ) {
$extraSqlConditions .= sprintf('AND "master"."theatre"=\'%s\' '
,$_SESSION[SYS_USER]['search']['Theatre']
);
}
if( !empty($_SESSION[SYS_USER]['search']['Location']) ) {
$extraSqlConditions .= sprintf('AND "master"."location"=\'%s\' '
,$_SESSION[SYS_USER]['search']['Location']
);
}
if( !empty($_SESSION[SYS_USER]['search']['EventType']) ) {
$extraSqlConditions .= sprintf('AND "master"."event_types_id"=\'%s\' '
,$_SESSION[SYS_USER]['search']['EventType']
);
}
if( !empty($_SESSION[SYS_USER]['search']['Month']) ) {
$extraSqlConditions .= sprintf('AND "shows"."show_date" >= \'%s\' AND "shows"."show_date" <= \'%s\' '
,date('Y-m-d',$firstDayTimestamp)
,date('Y-m-d',$lastDayTimestamp)
);
}
if( $cstage['rttEnable'] ) {
$extraSqlFields .= ', "rtt"."label" AS "rtt_label"';
$extraSqlJoins .= 'LEFT JOIN "rtt" ON "master"."rtt_id" = "rtt"."rtt_id" ';
} else {
$extraSqlConditions .= 'AND "master"."rtt_id"=0 ';
}
if( $cstage['enableEventPriceListTest'] ) {
$aryGroups = array($cstage['tixDomain']);
if( !empty($_SESSION[SYS_USER]['info']) && count($_SESSION[SYS_USER]['info']['groupDomains']) > 0 ) {
$aryGroups = array_merge($aryGroups, $_SESSION[SYS_USER]['info']['groupDomains']);
}
$extraSqlFields .= ', GROUP_CONCAT(DISTINCT "prices"."prices_id" SEPARATOR \';\') AS "priceidlist"';
$extraSqlFields .= ', GROUP_CONCAT(DISTINCT CONCAT("price_category"."label",\' \', "prices"."printed_as") SEPARATOR \', \') AS "pricelist"';
$extraSqlJoins .= ' INNER JOIN "price_category" ON "price_category"."master_id" = "master"."master_id" OR "price_category"."master_id"=0 INNER JOIN "prices" ON "price_category"."price_category_id" = "prices"."price_category_id" INNER JOIN "price_category_domain" ON "price_category_domain"."price_category_id" = "price_category"."price_category_id"';
$extraSqlConditions .= sprintf('AND ("price_category"."master_id"="shows"."master_id" OR "price_category"."master_id"=0) AND ("prices"."shows_id"="shows"."shows_id" OR "prices"."shows_id"=0) AND "prices"."onsale"<=CONCAT("shows"."show_date", \' 00:00:00\') AND ("prices"."offsale">=CONCAT("shows"."show_date", \' 23:59:59\') OR "prices"."offsale" IS NULL) AND "price_category_domain"."domain" IN (\'%s\') '
,implode('\',\'', $aryGroups)
);
}
$now = date('Y-m-d H:i:s');
$query = sprintf('SELECT "master".*, "shows"."show_date", "shows"."show_time", "shows"."onsale" AS "min_onsale"%s FROM "shows" INNER JOIN "master" ON "master"."master_id" = "shows"."master_id" INNER JOIN "domainlist" ON "domainlist"."master_id" = "master"."master_id" %s WHERE "shows"."offsale" >= \'%s\' AND ("shows"."wt_offsale"=\'\' OR "shows"."wt_offsale"=0) AND "domainlist"."domain"=\'%s\' %s GROUP BY "shows"."shows_id"'
,$extraSqlFields
,$extraSqlJoins
,$now
,$cstage['tixDomain']
,$extraSqlConditions
);
$keyEventCalendar = 'eventCalendar_'.$cstage['dbDatabase'].sha1($query);
if( !empty($cstage['cache']) ) {
// Is the record cached to save on slow database connections?
$calendar = $cstage['cache']->load($keyEventCalendar);
}
if( !$calendar ) {
$result = $cstage['pdo']->query( $query );
while( $show = $result->fetch( PDO::FETCH_ASSOC ) ) {
$show['domainlist'] = $cstage['tixDomain'].';'.$_SESSION[SYS_USER]['domain'];
$show['comingSoon'] = false;
if( $now < $show['min_onsale'] ) {
$show['comingSoon'] = true;
}
if( $show['rtt_id'] > 0 ) {
$show['master_id'] = trim($show['rtt_label']).trim($show[]);
if( !$cstage['rttEnable'] ) {
$show = array();
}
}
$path->inc_once('_includes/libf_okEvent.php');
if( okEvent($show) ) {
// Save data into array for usage later
$extraSort = $cstage['useEventSortOrder'] === true ? sprintf('%05d',$show['sortorder']) : '';
$aryEvents[$show['show_date']][date('H:i',strtotime($show['show_time'])).$extraSort.$show['showname'].$show['master_id']] = $show;
}
}
// Start rendering calendar.
$calendar = "\r\n".'<table class="EventCalendar ui-widget-content ui-corner-all"><thead '._HEAD.'><tr><th colspan="7">'.lang('Calendar of events for').' '.date('Y F',strtotime($_SESSION[SYS_USER]['search']['Month'].'-02')).'</th></tr>'
. "\r\n".'<tr><th>'.lang('Sunday').'</th><th>'.lang('Monday').'</th><th>'.lang('Tuesday').'</th><th>'.lang('Wednesday').'</th><th>'.lang('Thursday').'</th><th>'.lang('Friday').'</th><th>'.lang('Saturday').'</th></tr></thead>'
. '<tbody>';
$dayOfWeekPadding = date('w',$firstDayTimestamp);
if( $dayOfWeekPadding == 0 ) {
$dayOfWeekPadding = 6;
} else {
$dayOfWeekPadding -= 0;
}
if( $dayOfWeekPadding > 0 ) {
$calendar .= "\r\n<tr>";
}
for($day=7; $day < $dayOfWeekPadding; $day++) {
$calendar .= "\r\n<td class='EventCalendar_EmptyDate'> </td>";
}
$timeStamp = $firstDayTimestamp;
while( $timeStamp <= $lastDayTimestamp ) {
if( date('w',$timeStamp) == 0 ) {
$calendar .= "\r\n<tr>";
}
$dateKey = date('Y-m-d',$timeStamp);
$calendar .= "\r\n".'<td class="EventCalendar_Date" id="date'.$dateKey.'" onmouseover="tbl_colorchange(\'date'.$dateKey.'\', \'highlight\');" onmouseout="tbl_colorchange(\'date'.$dateKey.'\', \'normal\');"><span>'.date('d',$timeStamp).'</span>';
if( !empty($aryEvents[$dateKey]) ) {
ksort($aryEvents[$dateKey]);
$count = 0;
foreach( $aryEvents[$dateKey] as $key=>$show ) {
$cssClass = $count++ % 2 ? _ODD : _EVEN;
$rttUrl = ( $show['rtt_id'] > 0 ) ? '&rtt='.$show['rtt_id'] : '';
$strPriceList = (empty($show['pricelist']) ? '' : ' title="'.lang('Prices available').': '.$show['pricelist'].'"');
$calendar .= "\r\n<div {$cssClass}{$strPriceList}><a href='event-details.php?e={$show['master_id']}&date={$dateKey}{$rttUrl}'>{$show['']} # {$show['show_time']}</a></div>";
}
}
$calendar .= '</td>';
if( date('w',$timeStamp) == 0 ) {
$calendar .= "\r\n</tr>";
}
$timeStamp += 86400; // Get the next day (in seconds).
}
$dayOfWeekPadding = date('w',$timeStamp);
if( $dayOfWeekPadding == 0 ) {
$dayOfWeekPadding = 6;
} else if( $dayOfWeekPadding == 0 ) {
$dayOfWeekPadding = 0; // do not have an empty week of padding
} else {
$dayOfWeekPadding = 6 - $dayOfWeekPadding;
}
for($day=0; $day < $dayOfWeekPadding; $day++) {
$calendar .= "\r\n<td class='EventCalendar_EmptyDate'> </td>";
}
if( $dayOfWeekPadding > 0 ) {
$calendar .= "\r\n</tr>";
}
$calendar .= "\r\n</tbody></table>";
if( !empty($cstage['cache']) ) {
$cstage['cache']->save($calendar, $keyEventCalendar);
}
}
return $calendar;
}

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.