/** * Load XML response from Correios * * @param string $number Tracking Code * * @throws Zend_Http_Client_Adapter_Exception * * @link http://www.correios.com.br/para-voce/correios-de-a-a-z/pdf/rastreamento-de-objetos/ * Manual_SROXML_28fev14.pdf * * @return SimpleXMLElement */ public function request($number) { $client = new Zend_Http_Client($this->getConfigData("url_sro_correios")); $client->setParameterPost('Usuario', $this->getConfigData('sro_username')); $client->setParameterPost('Senha', $this->getConfigData('sro_password')); $client->setParameterPost('Tipo', $this->getConfigData('sro_type')); $client->setParameterPost('Resultado', $this->getConfigData('sro_result')); $client->setParameterPost('Objetos', $number); try { $response = $client->request(Zend_Http_Client::POST)->getBody(); if (empty($response)) { throw new Zend_Http_Client_Adapter_Exception("Empty response"); } libxml_use_internal_errors(true); $this->_xml = simplexml_load_string($response); if (!$this->_xml || !isset($this->_xml->objeto)) { throw new Zend_Http_Client_Adapter_Exception("Invalid XML"); } } catch (Zend_Http_Exception $e) { Mage::log("{$e->getMessage()}"); Mage::log("TRACKING: {$number}"); Mage::log("RESPONSE: {$response}"); return false; } return $this; }
/** * Attempts to uninstall Pear * * @param $moduleName */ protected function processPearUninstall($moduleName) { Mage::log("facebook foo"); $command = 'uninstall'; $params[] = 'community'; $params[] = $moduleName; Mage_Connect_Command_Install::registerCommands(); // needed for init $pear = new Mage_Connect_Command_Install(); // we need a config obj /* @var $config Hackathon_MageTrashApp_Model_PearWrapper */ $config = Mage::getModel('magetrashapp/pearWrapper'); $bla = $config->getConfig(); /*$config = new Mage_Connect_Config(); $ftp=$config->__get('remote_config'); if(!empty($ftp)){ $packager = new Mage_Connect_Packager(); list($cache, $config, $ftpObj) = $packager->getRemoteConf($ftp); $config; } $config->magento_root = dirname(dirname(__FILE__)).DS.'..';DS.'..'; */ $pear->setConfigObject($bla); $result = $pear->doUninstall($command, array(), $params); $bla = 'dfdf'; }
/** * @return ICC_Ecodes_Model_Downloadable */ public function remainingSerialsReport() { /** added for log tracking by anil 28 jul **/ $currDate = date("Y-m-d H:i:s", Mage::getModel('core/date')->timestamp(time())); $fileName = date("Y-m-d", Mage::getModel('core/date')->timestamp(time())); Mage::log("Controller Name : Ecode/Downloadable , Action Name : remainingSerialsReport , Start Time : {$currDate}", null, $fileName); /** end **/ $threshold = Mage::getStoreConfig(self::XML_PATH_REPORT_THRESHOLD); $errors = array(); if (!is_numeric($threshold) || $threshold < 0) { $error = "Threshold was not a positive integer."; $errors[] = $error; Mage::log("Error while attempting to run " . __METHOD__ . ". " . $error); } else { $notifications = $this->getCollection()->prepareForRemainingReport($threshold); if ($notifications->count()) { try { $this->sendNotificationEmail($notifications); } catch (Exception $e) { Mage::logException($e); } } } /** added for log tracking by anil 28 jul start **/ $currDate = date("Y-m-d H:i:s", Mage::getModel('core/date')->timestamp(time())); Mage::log("Controller Name : Ecode/Downloadable , Action Name : remainingSerialsReport , End Time : {$currDate}", null, $fileName); /** end **/ return $this; }
/** * Fixes CGI only one Status header allowed bug * * @link http://bugs.php.net/bug.php?id=36705 * * @return Mage_Core_Controller_Response_Http */ public function sendHeaders() { if (!$this->canSendHeaders()) { Mage::log('HEADERS ALREADY SENT: ' . mageDebugBacktrace(true, true, true)); return $this; } if (substr(php_sapi_name(), 0, 3) == 'cgi') { $statusSent = false; foreach ($this->_headersRaw as $i => $header) { if (stripos($header, 'status:') === 0) { if ($statusSent) { unset($this->_headersRaw[$i]); } else { $statusSent = true; } } } foreach ($this->_headers as $i => $header) { if (strcasecmp($header['name'], 'status') === 0) { if ($statusSent) { unset($this->_headers[$i]); } else { $statusSent = true; } } } } return parent::sendHeaders(); }
public function cron() { if ($files = Mage::helper('cachewarm')->getMaps()) { Mage::helper('cachewarm')->unsMaps(); foreach ($files as $file) { if (file_exists($file)) { $xml = simplexml_load_file($file); foreach ($xml as $sectionName => $sectionData) { if ($sectionName == "url") { try { Mage::log($sectionData->loc, null, 'cachewarm.log', true); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, (string) $sectionData->loc); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_exec($ch); curl_close($ch); } catch (Exception $e) { Mage::logException($e); Mage::log('error: ' . $e->getMessage(), null, 'cachewarm.log', true); } } } } } } }
public function process(array $csvData, $cid, $imageDir) { $cnt = count($csvData); $importDir = Mage::getBaseDir() . DS . 'media' . DS . 'marketplace' . DS . $cid . DS . $imageDir . DS; if ($cnt > 1) { for ($i = 1; $i < $cnt; $i++) { try { $sku = $csvData[$i][0]; $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku); $fileName = trim($csvData[$i][11]); $filePath = $importDir . $fileName; if (file_exists($filePath) && $fileName != '') { $types = array('image', 'small_image', 'thumbnail'); foreach ($types as $type) { $product->addImageToMediaGallery($filePath, array($type), false); } $mediaGallery = $product->getMediaGallery(); if (isset($mediaGallery['images'])) { foreach ($mediaGallery['images'] as $key => $image) { Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->getId()), array($types[$key] => $image['file']), 0); } } $product->save(); unlink($filePath); } else { $message = 'Image does not exist for sku ' . $sku; Mage::log($message, null, 'sellerimages_debug.log', true); } } catch (Exception $e) { Mage::logException($e); } } } return true; }
public function sync_specific_payment($payment_method) { $response = array(); $helper = Mage::helper('magerpsync/connection'); if ($payment_method) { $context = $helper->getOdooContext(); $client = $helper->getClientConnect(); $userId = Mage::getSingleton('adminhtml/session')->getUserId(); $payment_array = $arrayVal = array('name' => new xmlrpcval($payment_method, "string"), 'type' => new xmlrpcval('cash', "string")); $msg = new xmlrpcmsg('execute'); $msg->addParam(new xmlrpcval($helper::$odoo_db, "string")); $msg->addParam(new xmlrpcval($userId, "int")); $msg->addParam(new xmlrpcval($helper::$odoo_pwd, "string")); $msg->addParam(new xmlrpcval("bridge.backbone", "string")); $msg->addParam(new xmlrpcval("create_payment_method", "string")); $msg->addParam(new xmlrpcval($payment_array, "struct")); $msg->addParam(new xmlrpcval($context, "struct")); $resp = $client->send($msg); if ($resp->faultCode()) { $error = "Payment " . $payment_method . " >>" . $resp->faultString(); $response['odoo_id'] = 0; $response['error'] = $error; Mage::log($error, null, 'odoo_connector.log'); } else { $odoo_id = $resp->value()->me["int"]; if ($odoo_id > 0) { $mapping_data = array('mage_payment_id' => $payment_method, 'erp_payment_id' => $odoo_id, 'created_by' => $helper::$mage_user); $this->createMapping($mapping_data); $response['odoo_id'] = $odoo_id; } } } return $response; }
public function log($message, $level, $data = null) { if (!is_null($data)) { $message .= ' ' . json_encode($data); } Mage::log($message, $level, 'solr.log'); }
public function export($schedule) { try { if (!Mage::helper('xtento_orderexport')->getModuleEnabled() || !Mage::helper('xtento_orderexport')->isModuleProperlyInstalled()) { return; } if (!$schedule) { return; } $jobCode = $schedule->getJobCode(); preg_match('/xtento_orderexport_profile_(\\d+)/', $jobCode, $jobMatch); if (!isset($jobMatch[1])) { Mage::throwException(Mage::helper('xtento_orderexport/export')->__('No profile ID found in job_code.')); } $profileId = $jobMatch[1]; $profile = Mage::getModel('xtento_orderexport/profile')->load($profileId); if (!$profile->getId()) { Mage::throwException(Mage::helper('xtento_orderexport/export')->__('Profile ID %d does not seem to exist anymore.', $profileId)); } if (!$profile->getEnabled()) { return; // Profile not enabled } if (!$profile->getCronjobEnabled()) { return; // Cronjob not enabled } $exportModel = Mage::getModel('xtento_orderexport/export', array('profile' => $profile)); $filters = $this->addProfileFilters($profile); $exportModel->cronExport($filters); } catch (Exception $e) { Mage::log('Cronjob exception for job_code ' . $jobCode . ': ' . $e->getMessage(), null, 'xtento_orderexport_cron.log', true); return; } }
/** * Disable package access when order is refunded * * @param Varien_Event_Observer $observer */ public function salesOrderCreditmemoSaveCommitAfter(Varien_Event_Observer $observer) { $event = $observer->getEvent(); /** @var Mage_Sales_Model_Order_Creditmemo $creditmemo */ $creditmemo = $event->getCreditmemo(); /** @var Mage_Sales_Model_Order $order */ $order = $creditmemo->getOrder(); $customerId = $order->getCustomerId(); $productIds = []; foreach ($creditmemo->getItemsCollection() as $item) { $productIds[] = $item->getProductId(); } $packageIds = Mage::getResourceModel('genmato_composerrepo/packages_collection')->addFielToFilter('product_id', array('in' => $productIds))->getAllIds(); $collection = Mage::getResourceModel('genmato_composerrepo/customer_packages_collection')->addFieldToFilter('status', array('eq' => 1))->addFieldToFilter('customer_id', array('eq' => $customerId))->addFieldToFilter('order_id', array('eq' => $order->getId()))->addFieldToFilter('package_id', array('in' => $packageIds)); foreach ($collection as $item) { $item->setStatus(0); } try { $collection->save(); } catch (Exception $ex) { Mage::log($ex->getMessage()); } $cleanTags = []; $cleanTags[] = Genmato_ComposerRepo_Model_Customer_Auth::CACHE_TAG . $customerId; Mage::app()->getCache()->clean('matchingTag', $cleanTags); }
public function log($m) { $storeId = Mage::app()->getStore()->getId(); if (Mage::getStoreConfig(Ebizmarts_Mandrill_Model_System_Config::ENABLE_LOG, $storeId)) { Mage::log($m, Zend_Log::INFO, 'Mandrill.log'); } }
/** * Gets the similar items of the product * @return Array of Mage_Catalog_Model_Product */ public function getSimilarItems() { if (empty($this->_collection)) { $return = array(); Mage::log("getting similar items"); //if(!parent::isCacheEnabled() || $this->loadFromCache("similaritems")==null){ $recs = $this->getSimilar(); if (!empty($json_items)) { $count = 0; foreach ($recs as $rec) { if ($count >= parent::getNumberItems()) { break; } if (!empty($rec['item']['permalink'])) { $itemid = $rec['item']['permalink']; $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $itemid); if (!empty($product)) { $return[] = $product; $count++; } } } } //} //else{ //$return = $this->loadFromCache("similaritems"); //age::log("loaded from cache"); //} $this->_collection = $return; return $return; } return $this->_collection; }
public function log($data, $level = Zend_Log::DEBUG, $filename = 'api.log') { if ($this->getDebugEnabled()) { $filename = 'connector_' . $filename; Mage::log($data, $level, $filename, $force = true); } }
/** * send a js error to the backend */ public function sendAction() { $request = $this->getRequest(); $errorMessage = 'MESSAGE|' . $request->getParam('message') . "\n"; $errorMessage = 'URL|' . $request->getParam('url'); Mage::log($errorMessage, ZEND_LOG::ERR); }
/** * Add to Debug Log * @param string $message * @param string $order_id */ public function addToDebug($message = '', $order_id = '') { if (!empty($order_id)) { $message .= ' OrderId: ' . $order_id; } Mage::log($message, null, 'payment_payexbankdebit.log'); }
/** * Logs to file * * @param mixed $message * * @return Steverobbins_Slack_Helper_Data */ public function log($message) { if (Mage::getSingleton('slack/config_settings')->isDebug()) { Mage::log($message, null, 'slack.log'); } return $this; }
/** * Send data to specific mtgox api url * * @staticvar null $ch * * @param string $path mtgox api path * @param string $key mtgox key * @param string $secret mtgox secret key * @param array $req date to be sent * * @return array * @throws Exception */ public function mtgoxQuery($path, $key, $secret, array $req = array()) { $mt = explode(' ', microtime()); $req['nonce'] = $mt[1] . substr($mt[0], 2, 6); $postData = http_build_query($req, '', '&'); $headers = array('Rest-Key: ' . $key, 'Rest-Sign: ' . base64_encode(hash_hmac('sha512', $postData, base64_decode($secret), TRUE))); static $ch = NULL; if (is_null($ch)) { $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MtGox PHP client; ' . php_uname('s') . '; PHP/' . phpversion() . ')'); } curl_setopt($ch, CURLOPT_URL, 'https://mtgox.com/api/' . $path); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $res = curl_exec($ch); if ($res === FALSE) { $msg = 'Could not get reply: ' . curl_error($ch); Mage::log($msg, Zend_Log::ERR); Mage::getSingleton('core/session')->addError($msg); } $dec = json_decode($res, TRUE); if (!$dec) { $msg = 'Invalid data received, please make sure connection is working and requested API exists'; Mage::log($msg, Zend_Log::ERR); Mage::getSingleton('core/session')->addError($msg); } return $dec; }
public function checkUpdate() { $feeds = $this->getAllFeeds(); if (!is_array($feeds)) { Mage::log('Ikonoshirt_CustomAdminNotifications: No feeds found.'); return $this; } if ($this->getFrequency() + $this->getLastUpdate() > time()) { return $this; } /* @var $inbox Mage_AdminNotification_Model_Inbox */ $inbox = Mage::getModel('adminnotification/inbox'); foreach ($feeds as $feed) { // IMPORTANT // in getFeedData $this->getFeedUrl() is called, // which returns $this->_feedUrl // to not overwrite this method, I set this attribute. $this->_feedUrl = $feed; $feedData = array(); $feedXml = $this->getFeedData($feed); if ($feedXml && $feedXml->channel && $feedXml->channel->item) { foreach ($feedXml->channel->item as $item) { $feedData[] = array('severity' => (int) isset($item->severity) ? $item->severity : Mage_AdminNotification_Model_Inbox::SEVERITY_NOTICE, 'date_added' => $this->getDate((string) $item->pubDate), 'title' => (string) $item->title, 'description' => (string) $item->description, 'url' => $item->link ? (string) $item->link : null); } if ($feedData) { $inbox->parse(array_reverse($feedData)); } } $this->setLastUpdate($feed); } return $this; }
public function prepareLineItems(Mage_Core_Model_Abstract $salesEntity, $discountTotalAsItem = true, $shippingTotalAsItem = false) { $items = array(); foreach ($salesEntity->getAllItems() as $item) { if (!$item->getParentItem()) { $items[] = new Varien_Object($this->_prepareLineItemFields($salesEntity, $item)); } } $discountAmount = 0; // this amount always includes the shipping discount $shippingDescription = ''; if ($salesEntity instanceof Mage_Sales_Model_Order) { $discountAmount = abs(1 * $salesEntity->getBaseDiscountAmount() + Mage::getSingleton('checkout/session')->getDiscount()); $shippingDescription = $salesEntity->getShippingDescription(); $totals = array('subtotal' => $salesEntity->getBaseSubtotal() - $discountAmount, 'tax' => $salesEntity->getBaseTaxAmount(), 'shipping' => $salesEntity->getBaseShippingAmount()); } else { $address = $salesEntity->getIsVirtual() ? $salesEntity->getBillingAddress() : $salesEntity->getShippingAddress(); $discountAmount = abs(1 * $address->getBaseDiscountAmount() + Mage::getSingleton('checkout/session')->getDiscount()); $shippingDescription = $address->getShippingDescription(); $totals = array('subtotal' => $salesEntity->getBaseSubtotal() - $discountAmount, 'tax' => $address->getBaseTaxAmount(), 'shipping' => $address->getBaseShippingAmount(), 'discount' => $discountAmount); } // discount total as line item (negative) if ($discountTotalAsItem && $discountAmount) { $items[] = new Varien_Object(array('name' => Mage::helper('paypal')->__('Discount'), 'qty' => 1, 'amount' => -1.0 * $discountAmount)); } Mage::log($discountAmount . "|" . Mage::getSingleton('checkout/session')->getDiscount()); // shipping total as line item if ($shippingTotalAsItem && !$salesEntity->getIsVirtual() && (double) $totals['shipping']) { $items[] = new Varien_Object(array('id' => Mage::helper('paypal')->__('Shipping'), 'name' => $shippingDescription, 'qty' => 1, 'amount' => (double) $totals['shipping'])); } return array($items, $totals, $discountAmount, $totals['shipping']); }
/** * Used by the Zendesk single sign on functionality to authenticate users. * Only works for admin panel users, not for customers. */ public function authenticateAction() { if (!Mage::getStoreConfig('zendesk/sso/enabled')) { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__('Single sign-on disabled.')); $this->_redirect(Mage::getSingleton('admin/session')->getUser()->getStartupPageUrl()); } $domain = Mage::getStoreConfig('zendesk/general/domain'); $token = Mage::getStoreConfig('zendesk/sso/token'); if (!Zend_Validate::is($domain, 'NotEmpty')) { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__('Zendesk domain not set. Please add this to the settings page.')); $this->_redirect(Mage::getSingleton('admin/session')->getUser()->getStartupPageUrl()); } if (!Zend_Validate::is($token, 'NotEmpty')) { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__('Zendesk SSO token not set. Please add this to the settings page.')); $this->_redirect(Mage::getSingleton('admin/session')->getUser()->getStartupPageUrl()); } $now = time(); $jti = md5($now . rand()); $user = Mage::getSingleton('admin/session')->getUser(); $name = $user->getName(); $email = $user->getEmail(); $externalId = $user->getId(); $payload = array("iat" => $now, "jti" => $jti, "name" => $name, "email" => $email, "external_id" => $externalId); Mage::log('Admin JWT: ' . var_export($payload, true), null, 'zendesk.log'); $jwt = JWT::encode($payload, $token); $url = "http://" . $domain . "/access/jwt?jwt=" . $jwt; Mage::log('Admin URL: ' . $url, null, 'zendesk.log'); $this->_redirectUrl($url); }
/** * @title "Execution Time Test" * @description "Execution Time Test" * @new_line */ public function testExecutionTimeAction() { ini_set('display_errors', 1); $seconds = (int) $this->getRequest()->getParam('seconds', null); $logDir = Mage::getBaseDir('var') . DS . 'log' . DS; $fileName = 'm2epro_execution_time.log'; $isLogFileExists = is_file($logDir . $fileName); if ($seconds) { $isLogFileExists && unlink($logDir . $fileName); $i = 0; while ($i < $seconds) { sleep(1); ++$i % 10 == 0 && Mage::log("{$i} seconds passed", null, $fileName, 1); } echo "<div>{$seconds} seconds passed successfully!</div><br/>"; } if ($isLogFileExists) { $contentsRows = explode("\n", file_get_contents($logDir . $fileName)); if (count($contentsRows) >= 2) { $lastRecord = trim($contentsRows[count($contentsRows) - 2], "\r\n"); echo "<button onclick=\"alert('{$lastRecord}')\">show prev. log</button>"; } } $url = Mage::helper('adminhtml')->getUrl('*/*/*'); return print <<<HTML <form action="{$url}" method="get"> <input type="text" name="seconds" class="input-text" value="180" style="text-align: right; width: 100px" /> <button type="submit">Test</button> </form> HTML; }
public function savelistAction() { if (!Mage::helper('customer')->isLoggedIn()) { $this->_redirect('/'); } $params = $this->getRequest()->getParams(); $lists = Mage::helper('ebizmarts_autoresponder')->getLists(); $email = Mage::helper('customer')->getCustomer()->getEmail(); $storeId = Mage::app()->getStore()->getStoreId(); foreach ($lists as $key => $list) { $collection = Mage::getModel('ebizmarts_autoresponder/unsubscribe')->getCollection(); $collection->addFieldToFilter('main_table.email', array('eq' => $email))->addFieldToFilter('main_table.list', array('eq' => $key))->addFieldToFilter('main_table.store_id', array('eq' => $storeId)); if (array_key_exists($key, $params) && $collection->getSize() > 0) { //try to remove $collection->getFirstItem()->delete(); } else { if (!array_key_exists($key, $params) && $collection->getSize() == 0) { $unsubscribe = Mage::getModel('ebizmarts_autoresponder/unsubscribe'); $unsubscribe->setEmail($email)->setList($key)->setStoreId($storeId); Mage::log($unsubscribe); $unsubscribe->save(); } } } Mage::getSingleton('core/session')->addSuccess($this->__('Lists updated')); $this->_redirect('ebizautoresponder/autoresponder'); }
public function hookToFrontendControllerActionPredispatch($observer = null) { if (!Mage::helper('activecodeline_actionlogger')->_canLogFrontendActions()) { return; } $log = Mage::getModel('activecodeline_actionlogger/frontend'); $log->setActionName(Mage::app()->getRequest()->getActionName()); $log->setControllerName(Mage::app()->getRequest()->getControllerName()); if (Mage::helper('activecodeline_actionlogger')->_canLogRequestParams()) { if ($params = Mage::app()->getRequest()->getParams()) { $log->setParams(Mage::helper('core')->encrypt(serialize($params))); } } $log->setClientIp(Mage::app()->getRequest()->getClientIp()); $log->setControllerModule(Mage::app()->getRequest()->getControllerModule()); if ($customer = Mage::getSingleton('customer/session')->getCustomer()) { $log->setCustomerId($customer->getId()); } else { $log->setCustomerId(0); } try { $log->save(); } catch (Exception $e) { Mage::log('file: ' . __FILE__ . ', line: ' . __LINE__, 'msg: ' . $e->getMessage()); } }
public function perform($storeId = 1, $apply = false) { $this->_storeId = $storeId; $this->_apply = $apply; $this->_existingUmask = 0777; //umask(); $appEmulation = Mage::getSingleton('core/app_emulation'); $initial = $appEmulation->startEnvironmentEmulation($this->_storeId, Mage_Core_Model_App_Area::AREA_FRONTEND, true); $this->_skinDefaultDir = Mage::getDesign()->getSkinBaseDir(); $this->_recommendations['settings']['store_id'] = $storeId; $this->_recommendations['settings']['package_name'] = Mage::getDesign()->getPackageName(); $this->_recommendations['settings']['theme'] = Mage::getDesign()->getTheme('layout'); $this->_localXmlFilename = Mage::getBaseDir('design') . DS . 'frontend' . DS . Mage::getDesign()->getPackageName() . DS . Mage::getDesign()->getTheme('layout') . DS . 'layout' . DS . 'local.xml'; $layout = Mage::app()->getLayout(); $update = $layout->getUpdate(); //reset needed since otherwise only packages related to adminhtml are loaded $update->resetPackageLayout(); $xml = $update->getFileLayoutUpdatesXml('frontend', 'base', 'default'); Mage::app()->removeCache($update->getCacheId()); $update->resetHandles(); $update->resetUpdates(); $this->loadDefault(); foreach ($xml->children() as $handle => $node) { Mage::log($handle); try { $this->processHandle($handle); } catch (Exception $e) { $this->_recommendations['skipped'][$handle] = true; } } $appEmulation->stopEnvironmentEmulation($initial); $this->convertRecommendationsToLocalXml(); //umask($this->_existingUmask); return $this->_recommendations; }
/** * Create Backup * * @return Mage_Log_Model_Cron */ public function scheduledBackup() { if (!Mage::getStoreConfigFlag(self::XML_PATH_BACKUP_ENABLED)) { return $this; } if (Mage::getStoreConfigFlag(self::XML_PATH_BACKUP_MAINTENANCE_MODE)) { Mage::helper('backup')->turnOnMaintenanceMode(); } $type = Mage::getStoreConfig(self::XML_PATH_BACKUP_TYPE); $this->_errors = array(); try { $backupManager = Mage_Backup::getBackupInstance($type)->setBackupExtension(Mage::helper('backup')->getExtensionByType($type))->setTime(time())->setBackupsDir(Mage::helper('backup')->getBackupsDir()); Mage::register('backup_manager', $backupManager); if ($type != Mage_Backup_Helper_Data::TYPE_DB) { $backupManager->setRootDir(Mage::getBaseDir())->addIgnorePaths(Mage::helper('backup')->getBackupIgnorePaths()); } $backupManager->create(); Mage::log(Mage::helper('backup')->getCreateSuccessMessageByType($type)); } catch (Exception $e) { $this->_errors[] = $e->getMessage(); $this->_errors[] = $e->getTrace(); Mage::log($e->getMessage(), Zend_Log::ERR); Mage::logException($e); } if (Mage::getStoreConfigFlag(self::XML_PATH_BACKUP_MAINTENANCE_MODE)) { Mage::helper('backup')->turnOffMaintenanceMode(); } return $this; }
public function ipnPostSubmit() { // Give PAP access to the data so it can handle any needed commissions try { $papModel = Mage::getModel('pap/pap'); $postData = $this->getIpnFormData(); $customdata = explode('~~~a469ccb0-767c-4fed-96de-99427e1783aa~~~', $postData['custom']); $saleData = isset($customdata[0]) ? $customdata[0] : null; $cookieValue = isset($customdata[1]) ? $customdata[1] : null; // Convert the JSON data into a usable array $saleData = json_decode($saleData); $saleData = $this->ForceArray($saleData); $sReq = ''; foreach ($this->getIpnFormData() as $k => $v) { $sReq .= '&' . $k . '=' . urlencode(stripslashes($v)); } //append ipn commdn $sReq .= "&cmd=_notify-validate"; $sReq = substr($sReq, 1); $http = new Varien_Http_Adapter_Curl(); $http->write(Zend_Http_Client::POST, $this->getPaypalUrl(), '1.1', array(), $sReq); $response = $http->read(); $response = preg_split('/^\\r?$/m', $response, 2); $response = trim($response[1]); if ($response == 'VERIFIED') { $papModel->registerSaleDetails($saleData, isset($cookieValue) ? $cookieValue : null); } } catch (Exception $e) { Mage::log('Caught exception while trying to log PayPal sale: ' . $e->getMessage() . "\n"); } // let the base class go on to do whatever processing it was going to do parent::ipnPostSubmit(); }
/** * create or update an TYPO3 Frontend User * * @param Varien_Event_Observer $observer */ public function customerSaveAfterEvent($observer) { if (!Mage::getSingleton('Flagbit_Typo3connect/Core')->isEnabled()) { return; } // no TYPO3 db data given -> nothing to do if (!Mage::getStoreConfig('typo3connect/typo3_db/host') || !Mage::getStoreConfig('typo3connect/typo3_db/username') || !Mage::getStoreConfig('typo3connect/typo3_db/password') || !Mage::getStoreConfig('typo3connect/typo3_db/dbname')) { return; } $customer = $observer->getCustomer(); // assign the fields $fields = array('username' => $customer->getData('email'), 'name' => $customer->getData('lastname'), 'firstname' => $customer->getData('firstname'), 'email' => $customer->getData('email'), 'password' => $customer->getData('password'), 'usergroup' => Mage::helper('Flagbit_Typo3connect')->getConfigData('fe_user_group_uid'), 'pid' => Mage::helper('Flagbit_Typo3connect')->getConfigData('fe_user_pid'), 'tx_fbmagento_id' => $customer->getId()); try { // get fe_users Model $feUsers = Mage::getSingleton('Flagbit_Typo3connect/typo3_frontend_user'); $customer->load($customer->getId()); if ($customer->getTypo3Uid()) { $feUsers->setId($customer->getTypo3Uid()); } foreach ($fields as $key => $value) { $feUsers->setData($key, $value); } $feUsers->save(); $customer->setData('typo3_uid', $feUsers->getData('uid')); $customer->getResource()->saveAttribute($customer, 'typo3_uid'); } catch (Exception $e) { Mage::log($e->getMessage()); } }
/** * Perform result pre-processing * * @param array $arguments */ protected function _preProcessResult($result) { $result = parent::_preProcessResult($result); /** * catch interface errors * * Excerpt of interface documentation: * A value of zero means, the request was processed without error. * A value greater than zero indicates that an error occurred. * The detailed mapping and explanation of returned status codes is * contained in the list. * * @var stdClass $status Interface status response */ if (Mage::getStoreConfig('intraship/general/logging_enabled')) { $logfile = Mage::getModel('intraship/config')->getLogfile(); Mage::log('REQUEST: ' . $this->getLastRequest(), null, $logfile); Mage::log('RESPONSE: ' . $this->getLastResponse(), null, $logfile); } $status = isset($result->status) ? $result->status : $result->Status; if (0 < (int) $status->StatusCode) { throw new Dhl_Intraship_Model_Soap_Client_Response_Exception($this->getErrorMessage($result), $status->StatusCode); } return $result; }
/** * license the app * */ public static function license($activationKey, $productToken) { $url = 'https://ls.amazonaws.com/'; $client = new Varien_Http_Client($url); $client->setMethod(Zend_Http_Client::GET); $client->setParameterGet("Action", "ActivateDesktopProduct"); $client->setParameterGet("ActivationKey", $activationKey); $client->setParameterGet("ProductToken", $productToken); $response = $client->request(); if ($response->isSuccessful()) { $body = $response->getRawBody(); $xml = new SimpleXMLElement($body); $result = array(); $result["access"] = $xml->ActivateDesktopProductResult->AWSAccessKeyId; $result["secret"] = $xml->ActivateDesktopProductResult->SecretAccessKey; $result["usertoken"] = $xml->ActivateDesktopProductResult->UserToken; // uncomment to debug raw submission response //Mage::log("result=" . print_r($result,true)); return $result; } else { Mage::log("Activation failed to URL: " . $url . ", HTTP response code was not 200"); Mage::log("Raw response: " . print_r($response, true)); return false; } }
public function run() { $queueCollection = Mage::getModel('predictions/queue')->getCollection()->addFieldToFilter('cookie_processed', array('eq' => '0')); $recommendFor = array(); foreach ($queueCollection as $task) { $recommendFor[] = $task->getCookieId(); if ($task->getCustomerId()) { $recommendFor[] = $task->getCustomerId(); } try { $this->_processTask($task); } catch (Exception $e) { Mage::log($e->getMessage()); } } // [todo] loop through $recommendFor and create recommendations in the db $predictionEngine = $this->getPredictionEngine(); foreach ($recommendFor as $uid) { try { $recommendations = $predictionEngine->getRecommendations($uid); // [todo] - Refactor this asap, terrible code hacked together to make it work foreach ($recommendations as $key => $value) { $rec = Mage::getModel('predictions/recommendation'); $rec->setCookieId($uid); $rec->setProductId($value); $rec->save(); } } catch (Exception $e) { Mage::logException($e); } } }