public function updateSetting($sender, $param) { $result = $errors = array(); try { $result = $products = array(); $systemSetting = SystemSettings::getByType(SystemSettings::TYPE_SYSTEM_BUILD_PRODUCTS_ID); foreach ($param->CallbackParameter as $type => $ids) { $result[$type] = array(); $products[$type] = array(); foreach ($ids as $index => $id) { $id = intval(trim($id)); if (($product = Product::get($id)) instanceof Product) { $result[$type][] = $id; $products[$type][] = $product->getJson(); } } } Dao::beginTransaction(); $systemSetting->setValue(json_encode($result))->save(); Dao::commitTransaction(); } catch (Exception $ex) { // Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($products, $errors); }
/** * Output the debug message * * @param string $msg * */ private static function _debug($msg = "", $newLine = self::NEW_LINE, $prefix = "", UDate $start = null) { $now = UDate::now(SystemSettings::getSettings(SystemSettings::TYPE_SYSTEM_TIMEZONE)); if (self::$_debug === true) { echo $prefix . '[' . $now . ']: ' . $msg . ($start instanceof UDate ? '[ Took ' . ($now->getUnixTimeStamp() - $start->getUnixTimeStamp()) . ' second(s)]' : '') . $newLine; } return $now; }
function disableProduct($sku) { $sku = trim($sku); $params = array(); $params['status'] = '2'; // '2' means Disable in magento $script = CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->updateProductInfo($sku, $params); echo 'product with sku "' . $sku . '" disabled in magento' . "\n"; }
public static function sendEmail($from, $to, $subject, $body, array $attachmentAssetIds = array()) { $settings = json_decode(SystemSettings::getSettings(SystemSettings::TYPE_EMAIL_SENDING_SERVER), true); //Create a new PHPMailer instance $mail = new PHPMailer(); //Tell PHPMailer to use SMTP $mail->isSMTP(); $mail->isHTML(true); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = isset($settings['SMTPDebug']) ? $settings['SMTPDebug'] : 2; //Ask for HTML-friendly debug output $mail->Debugoutput = isset($settings['debugOutput']) ? $settings['debugOutput'] : 'html'; //Set the hostname of the mail server $mail->Host = isset($settings['host']) ? $settings['host'] : ""; //Set the SMTP port number - likely to be 25, 465 or 587 $mail->Port = isset($settings['port']) ? $settings['port'] : 25; //Whether to use SMTP authentication $mail->SMTPAuth = isset($settings['SMTPAuth']) ? $settings['SMTPAuth'] : true; //Username to use for SMTP authentication $mail->Username = isset($settings['username']) ? $settings['username'] : ""; //Password to use for SMTP authentication $mail->Password = isset($settings['password']) ? $settings['password'] : ""; //Set who the message is to be sent from $mail->setFrom($from); //Set an alternative reply-to address //$mail->addReplyTo('*****@*****.**', 'First Last'); //Set who the message is to be sent to $mail->addAddress($to); //Set the subject line $mail->Subject = $subject; //Read an HTML message body from an external file, convert referenced images to embedded, //convert HTML into a basic plain-text alternative body //$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); //Replace the plain text body with one created manually //$mail->AltBody = 'This is a plain-text message body'; //html body $mail->Body = $body; if (count($attachmentAssetIds) > 0) { foreach (Asset::getAllByCriteria('assetId in (' . implode(', ', array_fill(0, count($attachmentAssetIds), '?')) . ')', $attachmentAssetIds) as $asset) { //Attach an image file $mail->addAttachment($asset->getPath(), $asset->getFilename()); } } //send the message, check for errors if (!$mail->send()) { throw new CoreException('SENDING EMAIL ERROR: ' . $mail->ErrorInfo); } return true; }
public function syncProductAndProductCategory() { $cronStartDateTime = UDate::now(); $criteria = array("(sku != '' OR (mageId != '' AND mageId != 0))"); $param = array(); if (($lastUpdateDateTime = trim(SystemSettings::getSettings(SystemSettings::TYPE_PRODUCT_LAST_UPDATED))) !== '') { $criteria[] = "updated >= ?"; $param[] = $lastUpdateDateTime; } $counter = Product::countByCriteria(implode(" and ", $criteria), $param); if ($counter > 0) { $this->_mySoapClient = $this->_connect(); $this->syncAllProductCategory(); $productArray = Product::findByCriteria(implode(" and ", $criteria), $param); foreach ($productArray as $product) { $linkedCategories = array(); $product_categoryArray = Product_Category::getCategories($product); if (is_array($product_categoryArray) && count($product_categoryArray) > 0) { $linkedCategories = array_map(create_function('$a', 'return $a->getCategory()->getMageId();'), $product_categoryArray); } /// if no category is found, set the default to 1 /// if (count($linkedCategories) <= 0) { $linkedCategories = array(1); } $productData = $this->_generateProductData($product, $linkedCategories); if (($productMageId = trim($product->getMageId())) === '' || $productMageId === '0') { $attributeSets = $this->_mySoapClient->catalogProductAttributeSetList($session); $attributeSet = current($attributeSets); $productType = 'simple'; $newMageId = $this->_mySoapClient->catalogProductCreate($this->_session, $productType, $attributeSet->set_id, trim($product->getSku()), $productData); if (is_numeric($newMageId)) { $product->setMageId($newMageId)->save(); } else { $this->_handle_failed_product($product, $cronStartDateTime); } } else { // update product on magento $updated = $this->_mySoapClient->catalogProductUpdate($this->_session, $productMageId, $productData); if ($updated === false) { $this->_handle_failed_product($product, $cronStartDateTime, "update"); } } } } SystemSettings::addSettings(SystemSettings::TYPE_PRODUCT_LAST_UPDATED, $cronStartDateTime); //Debug::inspect($products); die(); }
/** * Getting the root path of the asset files * * @return Ambigous <string, multitype:> */ public static function getRootPath() { return SystemSettings::getSettings(SystemSettings::TYPE_ASSET_ROOT_DIR); }
/** * Getting the view preferences * * @return multitype: */ private function _getViewPreference() { $now = new UDate('now', SystemSettings::getSettings(SystemSettings::TYPE_SYSTEM_TIMEZONE)); return array('ord_item.eta.from' => $now->format('Y-m-d 00:00:00'), 'ord_item.eta.to' => $now->format('Y-m-d 23:59:59')); }
function main() { $Register =& Register::getInstance(); $smarty =& $Register->get(VAR_SMARTY); /*@var $smarty Smarty*/ // shopping cart //iframe cookie security workaround if (isset($_GET['check_cookie'])) { if ($_GET['check_cookie'] != session_id()) { $productID = (int) $_GET['productID']; $product_data = GetProduct($productID); $product_slug = $product_data && isset($product_data['slug']) ? $product_data['slug'] : ''; $url = "?ukey=product_widget&productID={$productID}&product_slug={$product_slug}&check_cookie&"; $widgets = false; $Register->set('widgets', $widgets); $_SERVER['REQUEST_URI'] = preg_replace('/(^|&)widgets=1/', '', $_SERVER['REQUEST_URI']); RedirectSQ($url); } else { renderURL('check_cookie&productID', '', true); } } if (isset($_GET["make_more_exact_cart_content"])) { $smarty->assign("make_more_exact_cart_content", 1); } if (isset($_GET["remove"]) && $_GET["remove"] > 0) { //remove from cart product with productID == $remove $cartEntry = new ShoppingCart(); $cartEntry->loadCurrentCart(); $cartEntry->setItemQuantity($_GET['remove'], 0); $cartEntry->saveCurrentCart(); if ($cartEntry->isEmpty()) { //remove coupon from empty cart ClassManager::includeClass('discount_coupon'); discount_coupon::remove(); } RedirectSQ('remove='); } $cart_view = $this->_detect_cart_view(); if (isset($_POST["update"]) || isset($_POST["recalculate"])) { //update shopping cart content if ($_POST['discount_coupon_code'] != '') { $this->_check_and_apply_coupon($_POST['discount_coupon_code']); } $cartEntry = new ShoppingCart(); $cartEntry->loadCurrentCart(); $upd_data = scanArrayKeysForID($_POST, 'count'); foreach ($upd_data as $_itemID => $_data) { $cartEntry->setItemQuantity($_itemID, intval($_data['count'])); } $cartEntry->saveCurrentCart(); if ($cartEntry->isEmpty()) { //remove coupon from empty cart ClassManager::includeClass('discount_coupon'); discount_coupon::remove(); } if (cartCheckMinOrderAmount() && cartCheckMinTotalOrderAmount()) { switch ($cart_view) { case CARTVIEW_FRAME: if (isset($_POST['checkout']) && $Register->get('store_mode') == 'facebook') { $store_mode = false; $Register->set('store_mode', $store_mode); $jsgoto = '?ukey=checkout&view=noframe'; RedirectSQ($jsgoto ? 'jsgoto=' . base64_encode(set_query($jsgoto)) : ''); } RedirectSQ(isset($_POST['checkout']) ? '?ukey=checkout' : (isset($_POST['ppe_checkout_x']) ? 'ppexpresscheckout2=1' : (isset($_POST['google_checkout_x']) ? 'googlecheckout2=1' : ''))); break; case CARTVIEW_WIDGET: case CARTVIEW_FADE: $jsgoto = isset($_POST['checkout']) ? '?ukey=checkout&view=noframe' : (isset($_POST['ppe_checkout_x']) ? 'ppexpresscheckout2=1&view=frame' : (isset($_POST['google_checkout_x']) ? 'googlecheckout2=1&view=frame' : '')); RedirectSQ($jsgoto ? 'jsgoto=' . base64_encode(set_query($jsgoto)) : ''); break; } } elseif (isset($_POST['checkout']) || isset($_POST['google_checkout_x']) || isset($_POST['ppe_checkout_x'])) { $smarty->assign('cart_error_show', '1'); } } if (isset($_GET["clear_cart"])) { //completely clear shopping cart $cartEntry = new ShoppingCart(); $cartEntry->loadCurrentCart(); $cartEntry->cleanCurrentCart('erase'); //remove coupon from empty cart ClassManager::includeClass('discount_coupon'); discount_coupon::remove(); RedirectSQ('clear_cart='); } if (isset($_POST['checkout'])) { if (SystemSettings::is_hosted() && file_exists(WBS_DIR . '/kernel/classes/class.metric.php')) { include_once WBS_DIR . '/kernel/classes/class.metric.php'; $DB_KEY = SystemSettings::get('DB_KEY'); $U_ID = sc_getSessionData('U_ID'); $metric = metric::getInstance(); $metric->addAction($DB_KEY, $U_ID, 'SC', 'CHECKOUT', isset($_GET['widgets']) ? 'WIDGET' : 'STOREFRONT', ''); } } $resCart = cartGetCartContent(); $resDiscount = dscGetCartDiscounts($resCart["total_price"], isset($_SESSION["log"]) ? $_SESSION["log"] : ""); $currencyEntry = Currency::getSelectedCurrencyInstance(); $cart_discount_show = $resDiscount['other_discounts']['cu'] > 0 ? $currencyEntry->getView($resDiscount['other_discounts']['cu']) : ''; $coupon_discount_show = $resDiscount['coupon_discount']['cu'] > 0 ? $currencyEntry->getView($resDiscount['coupon_discount']['cu']) : ''; $smarty->assign("cart_content", xHtmlSpecialChars($resCart["cart_content"], null, 'name')); $smarty->assign("cart_amount", $resCart["total_price"] - $resDiscount["discount_standart_unit"]); $smarty->assign('cart_min', show_price(CONF_MINIMAL_ORDER_AMOUNT)); $smarty->assign("cart_total", $currencyEntry->getView($resDiscount['total']['cu'])); $smarty->assign('cart_discount', $cart_discount_show); $smarty->assign('discount_percent', round($resDiscount['discount_percent'], 1)); $smarty->assign('coupon_discount', $coupon_discount_show); $smarty->assign("current_coupon", discount_coupon::getCurrentCoupon()); if (isset($_SESSION['log'])) { $smarty->assign('shippingAddressID', regGetDefaultAddressIDByLogin($_SESSION['log'])); } if (isset($_GET['min_order'])) { $smarty->assign('minOrder', 'error'); } if (isset($_GET['jsgoto'])) { $smarty->assign('jsgoto', base64_decode($_GET['jsgoto'])); } $smarty->assign('main_content_template', 'shopping_cart.html'); $smarty->assign('main_body_style', 'style="' . (CONF_SHOPPING_CART_VIEW == 2 || $cart_view == CARTVIEW_FRAME ? '' : 'background:#FFFFFF;') . 'min-width:auto;width:auto;_width:auto;"'); }
/** Force env or read it * @param string $env Environment name * @return void */ public static function set_env($env = null) { if (is_null($env)) { if (file_exists($ef = BASE_DIR . self::DIR_CONF_DIST . '/env')) { self::$env = trim(\System\File::read($ef)); } } else { self::$env = $env; } if (!defined("YACMS_ENV")) { define("YACMS_ENV", self::$env); } }
/** * @return PHPExcel */ private function _getExcel($data) { $phpexcel = new PHPExcel(); $activeSheet = $phpexcel->setActiveSheetIndex(0); $columnNo = 0; $rowNo = 1; // excel start at 1 NOT 0 // header row $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'SKU'); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Product Name'); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Last Week'); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Last Fortnight'); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Last 1 Month'); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Last 3 Month'); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Last 6 Month'); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Last 12 Month'); $rowNo++; foreach ($data as $productId => $rowNoData) { $columnNo = 0; // excel start at 1 NOT 0 $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['proSku']); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['proName']); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['7days']); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['14days']); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['1month']); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['3month']); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['6month']); $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['12month']); $rowNo++; } // Set document properties $now = UDate::now(); $objWriter = new PHPExcel_Writer_Excel2007($phpexcel); $filePath = '/tmp/' . md5($now); $objWriter->save($filePath); $fileName = 'RunRate_' . str_replace(':', '_', str_replace('-', '_', str_replace(' ', '_', $now->setTimeZone(SystemSettings::getSettings(SystemSettings::TYPE_SYSTEM_TIMEZONE))))) . '.xlsx'; $asset = Asset::registerAsset($fileName, file_get_contents($filePath), Asset::TYPE_TMP); return $asset; }
function cartUpdateAddCounter($productID) { db_phquery("UPDATE ?#PRODUCTS_TABLE SET add2cart_counter=(add2cart_counter+1) WHERE productID=?", $productID); //TODO: add_metric_code /* include_once('class.metric.php'); $metric = metric::getInstance(); $metric->addAction($DB_KEY, $currentUser, 'SC', _ACTION_, _CLIENT_, _DATA_); _ACTION_ - DOWNLOAD/UPLOAD/ADDCONTACT/etc... _CLIENT_ - FLASH/JAVA/etc.. (default WA) _DATA_ - данные поясняющие действие. */ if (SystemSettings::is_hosted() && file_exists(WBS_DIR . '/kernel/classes/class.metric.php')) { include_once WBS_DIR . '/kernel/classes/class.metric.php'; $DB_KEY = strtoupper(SystemSettings::get('DB_KEY')); $U_ID = sc_getSessionData('U_ID'); $metric = metric::getInstance(); $metric->addAction($DB_KEY, $U_ID, 'SC', 'ADD2CART', isset($_GET['widgets']) ? 'WIDGET' : 'STOREFRONT', ''); } }
private function updateMagentoPrice($price) { $product = Product::getBySku($this->sku); if (!$product instanceof Product) { throw new Exception('Invalid Product passed in. "' . $product . '" given.'); } $connector = CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY)); if ($this->debug) { echo 'Connecting to Magento for Product ' . $product->getSku() . '(id=' . $product->getId() . ')' . "\n"; } $result = $connector->updateProductPrice($product->getSku(), $price); if ($result !== true && $this->debug === true) { echo print_r($result, true); } if ($result === true && $this->debug === true) { echo 'Magento Price Successfully updated to $' . $price . "\n"; } return $this; }
public static function admin_executables() { if (!$GLOBALS['user']->hasCos(UserCos::ROOT)) { $msg = 'Not authorized!'; SystemEvent::raise(SystemEvent::INFO, $msg, __METHOD__); echo json_encode(array('success' => false, 'error' => $msg)); exit; } $settings = new SystemSettings(); foreach ($_POST['executablesForm'] as $key => $value) { $settingsValue = $value['value']; if ($value['type'] == 'checkbox') { $settingsValue = $value['value'] ? '1' : '0'; } $settings->setSetting($key, $settingsValue); } $GLOBALS['settings'] = $settings; SystemEvent::raise(SystemEvent::DEBUG, "Executables settings changed. {$GLOBALS['user']->getUsername()}.", __METHOD__); echo json_encode(array('success' => true, 'error' => 'Executables settings saved.')); exit; }
public function Create($OPTIONS = null) { if (!$OPTIONS) { $OPTIONS = SystemSettings::get(); } $soapClient = GETISoapClientFactory::Create($OPTIONS); return new ECheckProcessor($OPTIONS, $soapClient); }
/** * * @param unknown $sender * @param unknown $params * @throws Exception */ public function addPayment($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); if (!isset($param->CallbackParameter->againstEntity) || !isset($param->CallbackParameter->againstEntity->entity) || !isset($param->CallbackParameter->againstEntity->entityId) || ($entityName = trim($param->CallbackParameter->againstEntity->entity)) === '' || !($entity = $entityName::get(trim($param->CallbackParameter->againstEntity->entityId))) instanceof $entityName) { throw new Exception('System Error: invalid Order or CreditNote provided. Can NOT get any payments at all.'); } if (!$entity instanceof Order && !$entity instanceof CreditNote) { throw new Exception('System Error: you can ONLY add payments for a Order or a CreditNote'); } if (!isset($param->CallbackParameter->payment) || !isset($param->CallbackParameter->payment->paidAmount) || ($paidAmount = StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->payment->paidAmount))) === '' || !is_numeric($paidAmount)) { throw new Exception('System Error: invalid Paid Amount passed in!'); } if (!isset($param->CallbackParameter->payment->payment_method_id) || ($paymentMethodId = trim($param->CallbackParameter->payment->payment_method_id)) === '' || !($paymentMethod = PaymentMethod::get($paymentMethodId)) instanceof PaymentMethod) { throw new Exception('System Error: invalid Payment Method passed in!'); } $notifyCust = isset($param->CallbackParameter->payment->notifyCust) && intval($param->CallbackParameter->payment->notifyCust) === 1 ? true : false; $extraComment = ''; if (!isset($param->CallbackParameter->payment->extraComments) || ($extraComment = trim($param->CallbackParameter->payment->extraComments)) === '') { throw new Exception('Some comments for this payment is required.'); } //save the payment $newPayment = null; $entity = $entity->addPayment($paymentMethod, $paidAmount, $extraComment, new UDate(), $newPayment); $results['item'] = $newPayment->getJson(); //notify the customer if ($entity instanceof Order && $notifyCust === true && $entity->getIsFromB2B() === true) { $notificationMsg = trim(OrderNotificationTemplateControl::getMessage('paid', $entity)); if ($notificationMsg !== '') { B2BConnector::getConnector(B2BConnector::CONNECTOR_TYPE_ORDER, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->changeOrderStatus($entity, OrderStatus::get(OrderStatus::ID_PICKED)->getMageStatus(), $notificationMsg, true); $comments = 'An email notification contains payment checked info has been sent to customer for: ' . $entity->getStatus()->getName(); Comments::addComments($entity, $comments, Comments::TYPE_SYSTEM); } } Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
<?php require_once dirname(__FILE__) . '/../main/bootstrap.php'; try { $soapClient = null; echo "Begin" . __CLASS__ . " Melb Time: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n <pre>"; Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); Dao::beginTransaction(); SystemSettings::addSettings('system_build_product_ids', json_encode(array()), 'the product id json for system builds'); Dao::commitTransaction(); } catch (Exception $e) { echo "Error:"; if ($soapClient instanceof SoapClient) { echo "Response:<textarea>" . $soapClient->__getLastResponse() . "</textarea>"; } echo $e->getMessage() . "\n" . $e->getTraceAsString() . "\n"; Dao::rollbackTransaction(); throw $e; }
/** * import all products * * @return CatelogConnector */ public function importProducts() { if (!($systemSetting = SystemSettings::getByType(SystemSettings::TYPE_LAST_NEW_PRODUCT_PULL)) instanceof SystemSettings) { throw new Exception('cannot get LAST_NEW_PRODUCT_PULL in system setting'); } $fromDate = $systemSetting->getValue(); $products = $this->getProductList($fromDate); if (count($products) === 0) { echo 'nothing from magento. exitting' . "\n"; return $this; } try { $transStarted = false; try { Dao::beginTransaction(); } catch (Exception $e) { $transStarted = true; } foreach ($products as $pro) { $mageId = trim($pro->product_id); $sku = trim($pro->sku); $pro = $this->getProductInfo($sku, $this->getInfoAttributes()); $created_at = trim($pro->created_at); $updated_at = trim($pro->updated_at); $product_id = trim($pro->product_id); if (is_null($pro) || !isset($pro->additional_attributes)) { continue; } // handle extra long sku from magento, exceeding mysql sku length limit DaoMap::loadMap('Product'); $skuSizeLimit = DaoMap::$map['product']['sku']['size']; if (strlen($sku) > $skuSizeLimit) { echo 'Product ' . $sku . '(id=' . $product->getId() . ', magento Product Creation Time=' . trim($pro->created_at) . ') magento sku length exceed system sku length limit of' . $skuSizeLimit . ', skipped' . "\n"; continue; } $additionAttrs = $this->_getAttributeFromAdditionAttr($pro->additional_attributes); $name = trim($additionAttrs['name']); $short_description = trim($additionAttrs['short_description']); $description = trim($additionAttrs['description']); $weight = trim($additionAttrs['weight']); $statusId = trim($additionAttrs['status']); $price = trim($additionAttrs['price']); $specialPrice = isset($additionAttrs['special_price']) ? trim($additionAttrs['special_price']) : ''; $specialPrice_From = isset($additionAttrs['special_from_date']) ? trim($additionAttrs['special_from_date']) : null; $specialPrice_To = isset($additionAttrs['special_to_date']) ? trim($additionAttrs['special_to_date']) : null; if (!($product = Product::getBySku($sku)) instanceof Product) { $product = Product::create($sku, $name); Log::logging(0, get_class($this), 'Found New Product from Magento with sku="' . trim($sku) . '" and name="' . $name . '", created_at="' . $created_at, self::LOG_TYPE, '', __FUNCTION__); echo 'Found New Product from Magento with sku="' . trim($sku) . '" and name="' . $name . '", created_at="' . $created_at . ', updated_at' . $updated_at . "\n"; } elseif (Product::getBySku($sku) instanceof Product) { $product = Product::getBySku($sku); echo 'Found Existing Product from Magento with sku="' . trim($sku) . '" and name="' . $name . '", created_at="' . $created_at . ', updated_at' . $updated_at . '"' . "\n"; echo "\t" . 'Name: "' . $name . '"' . "\n"; echo "\t" . 'MageId: "' . $mageId . '"' . "\n"; echo "\t" . 'Short Description: "' . $short_description . '"' . "\n"; echo "\t" . 'Full Description: "' . $description . '"' . "\n"; echo "\t" . 'Status: "' . ProductStatus::get($statusId) . '"' . "\n"; echo "\t" . 'Manufacturer: id=' . $this->getManufacturerName(trim($additionAttrs['manufacturer']))->getId() . ', name="' . $this->getManufacturerName(trim($additionAttrs['manufacturer']))->getName() . '"' . "\n"; echo "\t" . 'Price: "' . $price . '"' . "\n"; echo "\t" . 'Weight: "' . $weight . '"' . "\n"; } $asset = ($assetId = trim($product->getFullDescAssetId())) === '' || !($asset = Asset::getAsset($assetId)) instanceof Asset ? Asset::registerAsset('full_desc_' . $sku, $description, Asset::TYPE_PRODUCT_DEC) : $asset; $product->setName($name)->setMageId($mageId)->setShortDescription($short_description)->setFullDescAssetId(trim($asset->getAssetId()))->setIsFromB2B(true)->setStatus(ProductStatus::get($statusId))->setSellOnWeb(true)->setManufacturer($this->getManufacturerName(trim($additionAttrs['manufacturer'])))->save()->clearAllPrice()->addPrice(ProductPriceType::get(ProductPriceType::ID_RRP), $price)->addInfo(ProductInfoType::ID_WEIGHT, $weight); if ($specialPrice !== '') { $product->addPrice(ProductPriceType::get(ProductPriceType::ID_CASUAL_SPECIAL), $specialPrice, $specialPrice_From, $specialPrice_To); } if (isset($additionAttrs['supplier']) && ($supplierName = trim($additionAttrs['supplier'])) !== '') { $product->addSupplier(Supplier::create($supplierName, $supplierName, true)); } if (isset($pro->categories) && count($pro->categories) > 0) { $product->clearAllCategory(); foreach ($pro->category_ids as $cateMageId) { if (!($category = ProductCategory::getByMageId($cateMageId)) instanceof ProductCategory) { continue; } $product->addCategory($category); } } } $systemSetting->setValue($updated_at)->save(); if ($transStarted === false) { Dao::commitTransaction(); } } catch (Exception $ex) { if ($transStarted === false) { Dao::rollbackTransaction(); } throw $ex; } return $this; }
/** * A product is shipped * * @param unknown $qty * @param string $comments * @param BaseEntityAbstract $entity * * @return Product */ public function shipped($qty, $comments = '', BaseEntityAbstract $entity = null) { $order = $entity instanceof Order ? $entity : ($entity instanceof OrderItem ? $entity->getOrder() : null); $newQty = ($originStockOnOrder = $this->getStockOnOrder()) - $qty; if ($newQty < 0 && intval($qty) > 0 && intval(SystemSettings::getSettings(SystemSettings::TYPE_ALLOW_NEGTIVE_STOCK)) !== 1) { throw new Exception('Product (SKU:' . $this->getSKU() . ') can NOT be pick, as there is not enough stock.'); } return $this->setStockOnOrder($newQty)->snapshotQty($entity instanceof BaseEntityAbstract ? $entity : $this, ProductQtyLog::TYPE_STOCK_MOVE_INTERNAL, 'Stock shipped. ' . ($order instanceof Order ? '[' . $order->getOrderNo() . ']' : ''))->save()->addLog('StockOnOrder(' . $originStockOnOrder . ' => ' . $this->getStockOnOrder() . ')', Log::TYPE_SYSTEM, 'STOCK_QTY_CHG', __CLASS__ . '::' . __FUNCTION__); }
require CINTIENT_SMARTY_INCLUDE; session_start(); // session_start *has* to come after the custom autoloading SystemEvent::setSeverityLevel(CINTIENT_LOG_SEVERITY); // // Global stuff // // Get to the part of the URL that matters $currentUrl = 'http://' . $_SERVER['HTTP_HOST'] . strtok($_SERVER['REQUEST_URI'], '?'); $GLOBALS['uri'] = substr($currentUrl, strlen(CINTIENT_BASE_URL)); if (substr($GLOBALS['uri'], -1) != '/') { $GLOBALS['uri'] .= '/'; } SystemEvent::raise(SystemEvent::DEBUG, "Handling request. [URI={$GLOBALS['uri']}" . (empty($_SERVER['QUERY_STRING']) ? '' : '?' . html_entity_decode($_SERVER['QUERY_STRING'])) . "]", "WebHandler"); $GLOBALS['section'] = null; $GLOBALS['settings'] = SystemSettings::load(); // Pull up system settings $GLOBALS['smarty'] = null; $GLOBALS['subSection'] = null; $GLOBALS['templateFile'] = null; $GLOBALS['templateMethod'] = null; $GLOBALS['user'] = isset($_SESSION['userId']) ? User::getById($_SESSION['userId']) : null; $GLOBALS['project'] = (!empty($_SESSION['projectId']) || !empty($_GET['pid'])) && !empty($GLOBALS['user']) ? Project::getById($GLOBALS['user'], !empty($_GET['pid']) ? $_GET['pid'] : $_SESSION['projectId']) : null; $_SESSION['projectId'] = $GLOBALS['project'] instanceof Project ? $GLOBALS['project']->getId() : null; // // Smarty // $GLOBALS['smarty'] = new Smarty(); $GLOBALS['smarty']->setAllowPhpTag(true); $GLOBALS['smarty']->setCacheLifetime(0); $GLOBALS['smarty']->setDebugging(SMARTY_DEBUG);
$ok = false; $msg = "Could not setup SystemSettings object."; SystemEvent::raise(CINTIENT_LOG_SEVERITY_ERROR, $msg, "Installer"); sendResponse($ok, $msg); } // // Everything ok!!! // if (!Database::endTransaction()) { Database::rollbackTransaction(); $ok = false; $msg = "Problems commiting all changes to the database."; SystemEvent::raise(CINTIENT_LOG_SEVERITY_ERROR, $msg, "Installer"); sendResponse($ok, $msg); } $settings = SystemSettings::load(); $settings->setSetting(SystemSettings::VERSION, CINTIENT_INSTALLER_VERSION); if (!$upgrade) { // // Root user account // $user = new User(); $user->setEmail($get['email']); $user->setNotificationEmails($get['email'] . ','); $user->setName('Administrative Account'); $user->setUsername('root'); $user->setCos(2); $user->init(); $user->setPassword($get['password']); } // Just to make sure everything's neat and tidy, especially after
<?php ini_set('memory_limit', '1024M'); require_once dirname(__FILE__) . '/../../bootstrap.php'; Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); echo "Begin downloadProductInfo from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n"; $newOnly = true; $debug = true; $script = CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY)); $script->downloadProductInfo($newOnly, $debug); echo "Done downloadProductInfo from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n";
function importNewProduct() { $debug = true; $newOnly = true; $script = CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->processDownloadedProductInfo($newOnly, $debug); }
public static function install() { SystemEvent::raise(SystemEvent::INFO, "Creating systemsettings table...", __METHOD__); $tableName = 'systemsettings'; $sql = <<<EOT DROP TABLE IF EXISTS {$tableName}NEW; CREATE TABLE IF NOT EXISTS {$tableName}NEW( key VARCHAR(255) PRIMARY KEY, value TEXT NOT NULL DEFAULT '' ); EOT; if (!Database::setupTable($tableName, $sql)) { SystemEvent::raise(SystemEvent::ERROR, "Problems setting up {$tableName} table.", __METHOD__); return false; } $self = new SystemSettings(); $self->_save(true); // This allows us to save the default system settings values at install time. SystemEvent::raise(SystemEvent::INFO, "{$tableName} table created.", __METHOD__); return true; }
/** * The row with default value * * @param UDate $lastUpdatedInDB * @param Product $product * @param string $preFix * @param bool $debug * * @return multitype:string number */ private static function _getRowWithDefaultValues(UDate $lastUpdatedInDB, Product $product = null, $preFix = '', $debug = false) { $attributeSetDefault = 'Default'; $attributeSetName = $attributeSetDefault; $enabled = true; $sku = $statusId = $productName = $rrpPrice = $weight = $shortDescription = $fullDecription = $supplierName = $supplierCode = $manufacturerName = $asNewFrom = $asNewTo = $specialPrice = $specialPriceFromDate = $specialPriceToDate = ''; $categoryIds = array(2); //default category if ($product instanceof Product) { $sku = trim($product->getSku()); $productName = trim($product->getName()); $shortDescription = trim($product->getShortDescription()); $asNewFrom = $product->getAsNewFromDate() instanceof UDate ? $product->getAsNewFromDate()->format('Y-m-d H:i:sP') : ''; $asNewTo = $product->getAsNewToDate() instanceof UDate ? $product->getAsNewToDate()->format('Y-m-d H:i:sP') : ''; $weight = trim($product->getWeight()); if ($product->getAttributeSet() instanceof ProductAttributeSet) { $attributeSetName = $product->getAttributeSet()->getName(); self::_log('-- attributeSetName ', __CLASS__ . '::' . __FUNCTION__ . " attributeSetName={$attributeSetName}", $preFix); } //RRP if (($rrp = $product->getRRP()) instanceof ProductPrice) { $rrpPrice = StringUtilsAbstract::getValueFromCurrency($rrp->getPrice()); } //special price if (($specialPriceObj = $product->getNearestSpecialPrice()) instanceof ProductPrice) { $specialPrice = StringUtilsAbstract::getValueFromCurrency($specialPriceObj->getPrice()); $specialPriceFromDate = $specialPriceObj->getStart()->format('Y-m-d H:i:sP'); $specialPriceToDate = $specialPriceObj->getEnd()->format('Y-m-d H:i:sP'); if ($specialPrice == 0) { $specialPrice = ''; $specialPriceFromDate = '1990-10-10'; $specialPriceToDate = '2009-10-10'; } } else { // delete the special price //$specialPrice = StringUtilsAbstract::getValueFromCurrency('99999999'); //$specialPrice = '9999999'; $specialPrice = ''; $specialPriceFromDate = '1990-10-10'; $specialPriceToDate = '2009-10-10'; } // if it is the daily promotion time then overwrite the special price with the daily special price $isDailyPromotionTime = intval(SystemSettings::getSettings(SystemSettings::TYP_ISDAILYPROMOTIONTIME)); if ($isDailyPromotionTime === 1) { // get daily promotion price if (($specialPriceObj = $product->getDailySpecialPrice()) instanceof ProductPrice) { $dailySpecialPrice = StringUtilsAbstract::getValueFromCurrency($specialPriceObj->getPrice()); if ($dailySpecialPrice != 0) { $specialPrice = $dailySpecialPrice; $specialPriceFromDate = $specialPriceObj->getStart()->format('Y-m-d H:i:sP'); $specialPriceToDate = $specialPriceObj->getEnd()->format('Y-m-d H:i:sP'); } } } // if it is the daily promotion time then overwrite the special price with the daily special price $isWeekendPromotionTime = intval(SystemSettings::getSettings(SystemSettings::TYP_ISWEEKENDPROMOTIONTIME)); if ($isWeekendPromotionTime === 1) { // get weekend promotion price if (($specialPriceObj = $product->getWeekendSpecialPrice()) instanceof ProductPrice) { $weekendSpecialPrice = StringUtilsAbstract::getValueFromCurrency($specialPriceObj->getPrice()); if ($weekendSpecialPrice != 0) { $specialPrice = $weekendSpecialPrice; $specialPriceFromDate = $specialPriceObj->getStart()->format('Y-m-d H:i:sP'); $specialPriceToDate = $specialPriceObj->getEnd()->format('Y-m-d H:i:sP'); } } } //full description if (($asset = Asset::getAsset($product->getFullDescAssetId())) instanceof Asset) { //$fullDecription = '"' . $asset->read() . '"'; $fullDecription = $asset->read(); } //supplier if (count($supplierCodes = SupplierCode::getAllByCriteria('productId = ?', array($product->getId()), true, 1, 1)) > 0) { $supplierName = ($supplier = $supplierCodes[0]->getSupplier()) instanceof Supplier ? $supplier->getName() : ''; $supplierCode = trim($supplierCodes[0]->getCode()); } //Manufacturer if ($product->getManufacturer() instanceof Manufacturer) { $manufacturerName = trim($product->getManufacturer()->getName()); } //disable or enabled if (intval($product->getActive()) === 0 || intval($product->getSellOnWeb()) === 0) { $enabled = false; } else { if ($product->getStatus() instanceof ProductStatus && intval($product->getStatus()->getId()) === ProductStatus::ID_DISABLED) { $enabled = false; } } //categories if (count($categories = Product_Category::getAllByCriteria('productId = ?', array($product->getId()))) > 0) { foreach ($categories as $category) { if (!$category->getCategory() instanceof ProductCategory || ($mageCateId = trim($category->getCategory()->getMageId())) === '') { continue; } if (trim($attributeSetName) === $attributeSetDefault && ($productAttributeSet = $category->getCategory()->getProductAttributeSet()) instanceof ProductAttributeSet) { $attributeSetName = trim($productAttributeSet->getName()); } $categoryIds[] = $mageCateId; } } //ProductStatus if ($product->getStatus() instanceof ProductStatus) { $statusId = $product->getStatus()->getName(); } } $categoryIds = array_unique($categoryIds); return array("store" => 'default', "websites" => 'base', "attribute_set" => $attributeSetName, "type" => 'simple', "category_ids" => implode(',', $categoryIds), "sku" => $sku, "name" => $productName, "price" => $rrpPrice, "special_from_date" => $specialPriceFromDate, "special_to_date" => $specialPriceToDate, "special_price" => $specialPrice, "news_from_date" => $asNewFrom, "news_to_date" => $asNewTo, "status" => intval($enabled) === 1 ? 1 : 2, "visibility" => 4, "tax_class_id" => 2, "description" => $fullDecription, "short_description" => $shortDescription, "supplier" => $supplierName, "man_code" => '', "sup_code" => $supplierCode, "meta_title" => '', "meta_description" => '', "manufacturer" => $manufacturerName, "url_key" => '', "url_path" => '', "custom_design" => '', "page_layout" => '', "country_of_manufacture" => '', "msrp_enabled" => '', "msrp_display_actual_price_type" => '', "meta_keyword" => '', "custom_layout_update" => '', "custom_design_from" => '', "custom_design_to" => '', "weight" => $weight, "msrp" => 'Use config', "gift_wrapping_price" => '', "qty" => 99, "min_qty" => 99, "use_config_min_qty" => 99, "is_qty_decimal" => '', "backorders" => '', "use_config_backorders" => '', "min_sale_qty" => '', "use_config_min_sale_qty" => '', "max_sale_qty" => '', "use_config_max_sale_qty" => '', "all_ln_stock" => $statusId, "is_in_stock" => 1, "low_stock_date" => '', "notify_stock_qty" => '', "use_config_notify_stock_qty" => '', "manage_stock" => '', "use_config_manage_stock" => '', "stock_status_changed_auto" => '', "use_config_qty_increments" => '', "qty_increments" => '', "use_config_enable_qty_inc" => '', "enable_qty_increments" => '', "is_decimal_divided" => '', "stock_status_changed_automatically" => '', "use_config_enable_qty_increments" => '', "image" => '', "small_image" => '', "thumbnail" => '', "media_gallery" => '', "is_recurring" => '', "media_gallery_reset" => 0); }
/** * updating the shipping details * * @param unknown $sender * @param unknown $param */ public function updateShippingDetails($sender, $params) { $result = $error = $shippingInfoArray = array(); try { Dao::beginTransaction(); if (!isset($params->CallbackParameter->order) || !($order = Order::getByOrderNo($params->CallbackParameter->order->orderNo)) instanceof Order) { throw new Exception('System Error: invalid order passed in!'); } if (!$order->getStatus() instanceof OrderStatus || trim($order->getStatus()->getId()) !== trim(OrderStatus::ID_PICKED)) { throw new Exception('System Error: Order [' . $order->getOrderNo() . '] Is Not is PICKED status. Current status is [' . ($order->getStatus() instanceof OrderStatus ? $order->getStatus()->getName() : 'NULL') . ']'); } if (intval($order->getPassPaymentCheck()) !== 1) { throw new Exception('Error: there is no payment or payments has been cancelled!'); } if (!isset($params->CallbackParameter->shippingInfo)) { throw new Exception('System Error: invalid Shipping Info Details passed in!'); } $shippingInfo = $params->CallbackParameter->shippingInfo; if (!($courier = Courier::get($shippingInfo->courierId)) instanceof Courier) { throw new Exception('Invalid Courier Id [' . $shippingInfo->courierId . '] provided'); } if (intval($order->getPassPaymentCheck()) !== 1) { throw new Exception('This ' . $order->getType() . ' has NOT pass payment check yet, please let the accounting department know before further actions!'); } $notifyCust = isset($shippingInfo->notifyCust) && intval($shippingInfo->notifyCust) === 1 ? true : false; //$companyName = $shippingInfo->companyName; $contactName = $shippingInfo->contactName; $contactNo = $shippingInfo->contactNo; $shippingAddress = Address::create(trim($shippingInfo->street), trim($shippingInfo->city), trim($shippingInfo->region), trim($shippingInfo->country), trim($shippingInfo->postCode), trim($contactName), trim($contactNo)); $shipment = Shippment::create($shippingAddress, $courier, trim($shippingInfo->conNoteNo), new UDate(), $order, $contactName, trim($contactNo), trim($shippingInfo->noOfCartons), '0', StringUtilsAbstract::getValueFromCurrency(trim($shippingInfo->actualShippingCost)), isset($shippingInfo->deliveryInstructions) ? trim($shippingInfo->deliveryInstructions) : ''); $order->setStatus(OrderStatus::get(OrderStatus::ID_SHIPPED))->save(); $result['shipment'] = $shipment->getJson(); //add shipment information if ($notifyCust === true && $order->getIsFromB2B() === true) { $templateName = trim($shipment->getCourier()->getId()) === trim(Courier::ID_LOCAL_PICKUP) ? 'local_pickup' : $order->getStatus()->getName(); $notificationMsg = trim(OrderNotificationTemplateControl::getMessage($templateName, $order)); if ($notificationMsg !== '') { B2BConnector::getConnector(B2BConnector::CONNECTOR_TYPE_SHIP, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->shipOrder($order, $shipment, array(), $notificationMsg, false, false); //push the status of the order to SHIPPed $emailToCustomer = trim($shipment->getCourier()->getId()) !== trim(Courier::ID_LOCAL_PICKUP); B2BConnector::getConnector(B2BConnector::CONNECTOR_TYPE_ORDER, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->changeOrderStatus($order, $order->getStatus()->getMageStatus(), $notificationMsg, $emailToCustomer); if ($emailToCustomer === true) { $order->addComment('An email notification contains shippment information has been sent to customer for: ' . $order->getStatus()->getName(), Comments::TYPE_SYSTEM); } } } Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $error[] = $ex->getMessage(); } $params->ResponseData = StringUtilsAbstract::getJson($result, $error); }
function onPageComplete($page = false) { global $debug_total_time; global $debug_total_sql_query; global $debug_sql_query_stack; $debug_total_string = ''; if (isset($debug_total_time) && $debug_total_time) { $time = microtime(true) - $debug_total_time; $debug_total_memory = function_exists('memory_get_peak_usage') ? memory_get_peak_usage() : 0; $debug_total_string .= sprintf('<div style="z-index:9999;position:fixed;right:50px;top:5px;height:23px;padding:0px;padding-bottom:2px;font-weight:bolder;color:green;background-color:#000033;opacity:0.8;border:1px dotted grey;"><span style="padding-left:10px;color:%s;">%0.3f s</span>' . "\t", $time > 0.5 ? $time > 1 ? 'red' : 'yellow' : 'green', $time); if ($debug_total_memory) { $debug_total_memory /= 1048576; $debug_total_string .= sprintf('<span style="padding-left:10px;color:%s;"> %0.3f MB</span>' . "\t", $debug_total_memory > 8 ? $debug_total_memory > 16 ? 'red' : 'yellow' : 'green', $debug_total_memory); } if (extension_loaded('eAccelerator')) { $eaccelerator_info = eaccelerator_info(); if ($eaccelerator_info['cache']) { $debug_total_string .= sprintf('<span style="padding-left:10px;color:%s;"> eAccelerator %s [%0.2fMB(%d%%)/%d scripts]</span>' . "\t" . "\n", 'cyan', $eaccelerator_info['version'], $eaccelerator_info['memoryAllocated'] / 1048576, 100 * $eaccelerator_info['memoryAllocated'] / $eaccelerator_info['memorySize'], $eaccelerator_info['cachedScripts']); } } elseif (extension_loaded('xCache')) { if (isset($_GET['xcache'])) { $pcnt = xcache_count(XC_TYPE_PHP); $total = array('size' => 0, 'avail' => 0, 'cached' => 0, 'slots' => 0); $fields = array('size', 'avail', 'cached', 'slots'); for ($i = 0; $i < $pcnt; $i++) { $data = xcache_info(XC_TYPE_PHP, $i); foreach ($fields as $field) { $total[$field] += $data[$field]; } } $total['used'] = $total['size'] - $total['avail']; $version = phpversion('xcache'); $debug_total_string .= sprintf('<span style="padding-left:10px;color:%s;"> xCache %s [%0.2fMB(%d%%)/%d scripts]</span>' . "\t" . "\n", 'cyan', $version, $total['used'] / 1048576, 100 * $total['used'] / $total['size'], $total['cached']); } else { $version = phpversion('xcache'); $debug_total_string .= sprintf('<span style="padding-left:10px;color:%s;"> xCache %s</span>' . "\t" . "\n", 'cyan', $version); } } $debug_total_string .= sprintf('<span style="padding-left:10px;color:%s;"> %d SQL query</span>' . "\t" . "\n", $debug_total_sql_query > 50 ? $debug_total_sql_query > 100 ? 'red' : 'yellow' : 'green', $debug_total_sql_query); $debug_total_string .= sprintf('<span style="padding-left:10px;"> %d File(s)</span>' . "\t" . "\n", count(get_included_files())); $page_size = ob_get_length(); $debug_total_string .= sprintf('<span style="padding-left:10px;"> %0.3f KB page size</span>' . "\t", ($page_size ? $page_size : strlen($page)) / 1024); //$debug_total_string .= sprintf('<span style="padding-left:10px;"> %s mode</span>',false?'DEV':'PRODUCTION'); $debug_total_string .= '<img style="padding:0;padding-left:10px;margin:0;cursor:pointer;" src="' . URL_IMAGES_COMMON . '/close.gif" title="close" alt="close" onclick="this.parentNode.style.display=\'none\';"></div>'; $firebug_enabled = false; if (class_exists('FirePHP')) { $firebug_enabled = strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'firephp') === false ? false : true; $firebug = FirePHP::getInstance(true); $firebug_enabled = $firebug->detectClientExtension(); $firebug->setEnabled($firebug_enabled); $firebug->info(strip_tags($debug_total_string), basename(__FILE__)); if ($debug_sql_query_stack && (isset($_COOKIE['debug']) && $_COOKIE['debug'] == 'sql')) { $total = 0.0; foreach ($debug_sql_query_stack as $stack_item) { $total += $stack_item['time']; } $debug_sql_query_stack[] = array('#' => 'TOTAL', 'time' => sprintf('%0.2f', $total), 'query' => ''); $firebug->table('SQL', $debug_sql_query_stack); } } if (!SystemSettings::is_hosted() && (isset($_COOKIE['debug']) && $_COOKIE['debug'] == 'log') && ($fp = @fopen(DIR_TEMP . '/access.' . date("Y.m.d") . '.log', "a"))) { @fwrite($fp, date("Y-m-d H:i:s") . "\t" . $_REQUEST['REQUEST_URI'] . $_REQUEST['QUERY_STRING'] . "\t" . preg_replace('/\\s+/', ' ', strip_tags($debug_total_string)) . "\n"); if ($debug_sql_query_stack) { foreach ($debug_sql_query_stack as $query) { @fwrite($fp, "\t" . implode("\t", $query) . "\n\n"); } @fwrite($fp, "\n\n==========================================\n"); } @fclose($fp); } } session_write_close(); if ($page) { if (!$firebug_enabled) { print preg_replace('@</body>\\s*</html>\\s*$@', '', $page); print $debug_total_string . ' </body> </html>'; } else { print $page; return $debug_total_string; } } }
<?php require_once dirname(__FILE__) . '/../../bootstrap.php'; echo "Begin importProductCategories from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n"; Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->importProductCategories(); echo "Done importProductCategories from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n";
public static function install() { session_destroy(); // // Create necessary dirs // if (!file_exists(CINTIENT_WORK_DIR) && !mkdir(CINTIENT_WORK_DIR, DEFAULT_DIR_MASK, true)) { SystemEvent::raise(SystemEvent::ERROR, "Could not create working dir. Check your permissions.", __METHOD__); echo "Error"; // TODO: treat this properly exit; } if (!file_exists(CINTIENT_PROJECTS_DIR) && !mkdir(CINTIENT_PROJECTS_DIR, DEFAULT_DIR_MASK, true)) { SystemEvent::raise(SystemEvent::ERROR, "Could not create projects dir. Check your permissions.", __METHOD__); echo "Error"; // TODO: treat this properly exit; } if (!file_exists(CINTIENT_ASSETS_DIR) && !mkdir(CINTIENT_ASSETS_DIR, DEFAULT_DIR_MASK, true)) { SystemEvent::raise(SystemEvent::ERROR, "Could not create assets dir. Check your permissions.", __METHOD__); echo "Error"; // TODO: treat this properly exit; } if (!file_exists(CINTIENT_AVATARS_DIR) && !mkdir(CINTIENT_AVATARS_DIR, DEFAULT_DIR_MASK, true)) { SystemEvent::raise(SystemEvent::ERROR, "Could not create avatars dir. Check your permissions.", __METHOD__); echo "Error"; // TODO: treat this properly exit; } // // Setup all objects // if (!User::install()) { SystemEvent::raise(SystemEvent::ERROR, "Could not setup User object.", __METHOD__); echo "Error"; // TODO: treat this properly exit; } if (!Project::install()) { SystemEvent::raise(SystemEvent::ERROR, "Could not setup Project object.", __METHOD__); echo "Error"; // TODO: treat this properly exit; } if (!SystemSettings::install()) { SystemEvent::raise(SystemEvent::ERROR, "Could not setup SystemSettings object.", __METHOD__); echo "Error"; // TODO: treat this properly exit; } // // Test user setup // $user = new User(); $user->setEmail('*****@*****.**'); $user->setNotificationEmails('pedro.matamouros@gmail.com,'); $user->setName('Pedro Mata-Mouros'); $user->setUsername('matamouros'); $user->setCos(UserCos::ROOT); $user->init(); $user->setPassword('pedro'); header('Location: ' . UrlManager::getForDashboard()); exit; }
/** * Import Orders * * @param string $lastUpdatedTime The datatime string * * @return B2BConnector */ public function importOrders($lastUpdatedTime = '') { $totalItems = 0; $this->_log(0, get_class($this), 'starting ...', self::LOG_TYPE, 'start', __FUNCTION__); if (($lastUpdatedTime = trim($lastUpdatedTime)) === '') { $this->_log(0, get_class($this), 'Getting the last updated time', self::LOG_TYPE, '$lastUpdatedTime is blank', __FUNCTION__); // $lastImportTime = new UDate(SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_LAST_IMPORT_TIME), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_TIMEZONE)); $lastUpdatedTime = trim(SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_LAST_IMPORT_TIME)); } //getting the lastest order since last updated time $orders = $this->getlastestOrders($lastUpdatedTime); $this->_log(0, get_class($this), 'Found ' . count($orders) . ' order(s) since "' . $lastUpdatedTime . '".', self::LOG_TYPE, '', __FUNCTION__); if (is_array($orders) && count($orders) > 0) { $transStarted = false; try { try { Dao::beginTransaction(); } catch (Exception $e) { $transStarted = true; } foreach ($orders as $index => $order) { $this->_log(0, get_class($this), 'Found order from Magento with orderNo = ' . trim($order->increment_id) . '.', self::LOG_TYPE, '', __FUNCTION__); $order = $this->getOrderInfo(trim($order->increment_id)); if (!is_object($order)) { $this->_log(0, get_class($this), 'Found no object from $order, next element!', self::LOG_TYPE, '$index = ' . $index, __FUNCTION__); continue; } if (($status = trim($order->state)) === '') { $this->_log(0, get_class($this), 'Found no state Elment from $order, next element!', self::LOG_TYPE, '$index = ' . $index, __FUNCTION__); continue; } //saving the order $orderDate = new UDate(trim($order->created_at), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_TIMEZONE)); $orderDate->setTimeZone('UTC'); // $totalPaid = (!isset($order->total_paid) ? 0 : trim($order->total_paid)); $shippingAddr = $billingAddr = null; if (($o = Order::getByOrderNo(trim($order->increment_id))) instanceof Order) { //skip, if order exsits $this->_log(0, get_class($this), 'Found order from DB, ID = ' . $o->getId(), self::LOG_TYPE, '$index = ' . $index, __FUNCTION__); continue; // $shippingAddr = $o->getShippingAddr(); // $billingAddr = $o->getBillingAddr(); } $o = new Order(); $this->_log(0, get_class($this), 'Found no order from DB, create new', self::LOG_TYPE, '$index = ' . $index, __FUNCTION__); $customer = Customer::create(isset($order->billing_address) && isset($order->billing_address->company) && trim($order->billing_address->company) !== '' ? trim($order->billing_address->company) : (isset($order->customer_firstname) ? trim($order->customer_firstname) . ' ' . trim($order->customer_lastname) : ''), '', trim($order->customer_email), $this->_createAddr($order->billing_address, $billingAddr), true, '', $this->_createAddr($order->shipping_address, $shippingAddr), isset($order->customer_id) ? trim($order->customer_id) : 0); $o->setOrderNo(trim($order->increment_id))->setOrderDate(trim($orderDate))->setTotalAmount(trim($order->grand_total))->setStatus(strtolower($status) === 'canceled' ? OrderStatus::get(OrderStatus::ID_CANCELLED) : OrderStatus::get(OrderStatus::ID_NEW))->setIsFromB2B(true)->setShippingAddr($customer->getShippingAddress())->setBillingAddr($customer->getBillingAddress())->setCustomer($customer)->save(); $this->_log(0, get_class($this), 'Saved the order, ID = ' . $o->getId(), self::LOG_TYPE, '$index = ' . $index, __FUNCTION__); $totalShippingCost = StringUtilsAbstract::getValueFromCurrency(trim($order->shipping_amount)) * 1.1; //create order info $this->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_CUS_NAME), trim($customer->getName()))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_CUS_EMAIL), trim($customer->getEmail()))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_QTY_ORDERED), intval(trim($order->total_qty_ordered)))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_MAGE_ORDER_STATUS), trim($order->status))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_MAGE_ORDER_STATE), trim($order->state))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_MAGE_ORDER_TOTAL_AMOUNT), trim($order->grand_total))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_MAGE_ORDER_SHIPPING_METHOD), trim($order->shipping_description))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_MAGE_ORDER_SHIPPING_COST), $totalShippingCost)->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_MAGE_ORDER_PAYMENT_METHOD), !isset($order->payment) ? '' : (!isset($order->payment->method) ? '' : trim($order->payment->method))); $this->_log(0, get_class($this), 'Updated order info', self::LOG_TYPE, '$index = ' . $index, __FUNCTION__); //saving the order item $totalItemCost = 0; foreach ($order->items as $item) { $this->_createItem($o, $item); $totalItemCost = $totalItemCost * 1 + StringUtilsAbstract::getValueFromCurrency($item->row_total) * 1.1; } if (($possibleSurchargeAmount = $o->getTotalAmount() - $totalShippingCost - $totalItemCost) > 0 && ($product = Product::getBySku('surcharge')) instanceof Product) { OrderItem::create($o, $product, $possibleSurchargeAmount, 1, $possibleSurchargeAmount); } //record the last imported time for this import process SystemSettings::addSettings(SystemSettings::TYPE_B2B_SOAP_LAST_IMPORT_TIME, trim($order->created_at)); $this->_log(0, get_class($this), 'Updating the last updated time :' . trim($order->created_at), self::LOG_TYPE, '', __FUNCTION__); $totalItems++; } if ($transStarted === false) { Dao::commitTransaction(); } } catch (Exception $e) { if ($transStarted === false) { Dao::rollbackTransaction(); } throw $e; } } $this->_log(0, get_class($this), $lastUpdatedTime . " => " . SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_LAST_IMPORT_TIME) . ' => ' . $totalItems, self::LOG_TYPE, '', __FUNCTION__); return $this; }
function importOrder() { $script = B2BConnector::getConnector(B2BConnector::CONNECTOR_TYPE_ORDER, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->importOrders(); echo implode($script->getLogs()); }