Example #1
0
 /**
  * Find the longitute and latitude from a location string
  * @param string $strAddress Optimal format: street (+number), postal, city [country]
  * @param string
  * @return array|bool  return an array with logitute, latitude and address or false if error or empty results
  * @example https://developers.google.com/maps/documentation/geocoding/?hl=de
  */
 public static function getLonLat($strAddress, $strCountry = null)
 {
     // Google Geocoding API v3
     $strQuery = 'https://maps.googleapis.com/maps/api/geocode/json?' . 'address=' . rawurlencode($strAddress) . '&sensor=false' . '&language=' . $GLOBALS['TL_LANGUAGE'];
     if ($strCountry) {
         $strQuery .= '&components=country:' . $strCountry;
     }
     $objRequest = new \Request();
     $objRequest->send($strQuery);
     if (!$objRequest->hasError()) {
         $objResponse = json_decode($objRequest->response);
         // check the possible return status
         switch ($objResponse->status) {
             case 'OK':
                 return array('address' => $objResponse->results[0]->formatted_address, 'longitude' => $objResponse->results[0]->geometry->location->lng, 'latitude' => $objResponse->results[0]->geometry->location->lat);
             case 'ZERO_RESULTS':
             case 'OVER_QUERY_LIMIT':
             case 'REQUEST_DENIED':
             case 'INVALID_REQUEST':
             default:
                 \System::log("Google Maps API return error '{$objResponse->status}' for '{$strAddress}'", __METHOD__, TL_ERROR);
                 return false;
         }
     }
     \System::log("Failed Request '{$strQuery}' with error '{$objRequest->error}'", __METHOD__, TL_ERROR);
     return false;
 }
Example #2
0
 /**
  * Run the Live Update
  * @param \BackendTemplate
  */
 protected function runLiveUpdate(\BackendTemplate $objTemplate)
 {
     $archive = 'system/tmp/' . \Input::get('token');
     // Download the archive
     if (!file_exists(TL_ROOT . '/' . $archive)) {
         $objRequest = new \Request();
         $objRequest->send(\Config::get('liveUpdateBase') . 'request.php?token=' . \Input::get('token'));
         if ($objRequest->hasError()) {
             $objTemplate->updateClass = 'tl_error';
             $objTemplate->updateMessage = $objRequest->response;
             return;
         }
         \File::putContent($archive, $objRequest->response);
     }
     $objArchive = new \ZipReader($archive);
     // Extract
     while ($objArchive->next()) {
         if ($objArchive->file_name != 'TOC.txt') {
             try {
                 \File::putContent($objArchive->file_name, $objArchive->unzip());
             } catch (\Exception $e) {
                 $objTemplate->updateClass = 'tl_error';
                 $objTemplate->updateMessage = 'Error updating ' . $objArchive->file_name . ': ' . $e->getMessage();
                 return;
             }
         }
     }
     // Delete the archive
     $this->import('Files');
     $this->Files->delete($archive);
     // Run once
     $this->handleRunOnce();
 }
Example #3
0
 /**
  * Find the longitute and latitude from a location string
  * @param string $strAddress Optimal format: street (+number), postal, city [country]
  * @param string
  * @return array|bool  return an array with logitute, latitude and address or false if error or empty results
  * @example https://developers.google.com/maps/documentation/geocoding/?hl=de
  */
 public static function getLonLat($strAddress, $strCountry = null)
 {
     // Google Geocoding API v3
     $strUrl = 'https://maps.googleapis.com/maps/api/geocode/json';
     $arrParams = array('address' => $strAddress, 'language' => $GLOBALS['TL_LANGUAGE']);
     if (\Config::get('anystores_apiKey')) {
         $arrParams['key'] = \Config::get('anystores_apiKey');
     }
     $strQuery = $strUrl . '?' . http_build_query($arrParams, '', '&');
     if ($strCountry) {
         $strQuery .= '&components=country:' . strtoupper($strCountry);
     }
     $objRequest = new \Request();
     $objRequest->send($strQuery);
     if (!$objRequest->hasError()) {
         $objResponse = json_decode($objRequest->response);
         // check the possible return status
         switch ($objResponse->status) {
             case 'OK':
                 return array('address' => $objResponse->results[0]->formatted_address, 'longitude' => $objResponse->results[0]->geometry->location->lng, 'latitude' => $objResponse->results[0]->geometry->location->lat);
             case 'ZERO_RESULTS':
             case 'OVER_QUERY_LIMIT':
             case 'REQUEST_DENIED':
             case 'INVALID_REQUEST':
             default:
                 \System::log("Google Maps API return error '{$objResponse->status}' for '{$strAddress}': {$objResponse->error_message}", __METHOD__, TL_ERROR);
                 return false;
         }
     }
     \System::log("Failed Request '{$strQuery}' with error '{$objRequest->error}'", __METHOD__, TL_ERROR);
     return false;
 }
Example #4
0
 /**
  * Find the longitute and latitude from a location string
  * @param type $strAddress
  * @param type $strCountry
  * @example http://wiki.openstreetmap.org/wiki/Nominatim#Examples
  */
 public static function getLonLat($strAddress, $strCountry = null)
 {
     $strQuery = 'https://nominatim.openstreetmap.org/search?' . 'q=' . rawurlencode($strAddress) . '&format=json' . '&accept-language=' . $GLOBALS['TL_LANGUAGE'] . '&limit=1';
     if ($strCountry) {
         $strQuery .= '&countrycodes=' . $strCountry;
     }
     $objRequest = new \Request();
     $objRequest->send($strQuery);
     // Return on error
     if ($objRequest->hasError()) {
         \System::log("Failed Request '{$strQuery}' with error '{$objRequest->error}'", __METHOD__, TL_ERROR);
         return false;
     }
     $arrResponse = json_decode($objRequest->response);
     // Return on empty response
     if (!count($arrResponse)) {
         \System::log("Empty Request for address '{$strAddress}': '{$strQuery}'", __METHOD__, TL_ERROR);
         return false;
     }
     // Display copyright and licence in backend
     if (TL_MODE == 'BE') {
         \Message::addInfo($arrResponse[0]->licence);
     }
     return array('licence' => $arrResponse[0]->licence, 'address' => $arrResponse[0]->display_name, 'latitude' => $arrResponse[0]->lat, 'longitude' => $arrResponse[0]->lon);
 }
Example #5
0
 /**
  * エラー項目を判断し、HTMLのstyleプロパティを返却する
  * Smartyからコールされるfunctionのため、$paramsには、連想配列形式で
  * $params['name']にチェックする項目名をセットする
  * ※setErrorMesseageの第二引数と、HTMLのnameを一致させること
  * @param array $params Smartyパラメータ
  * @param Smarty &$o_smarty Smartyオブジェクト
  */
 public function checkErrorElement($params, &$o_smarty)
 {
     $retVal = '';
     /* エラー項目の背景色を設定する */
     if ($this->request->hasError($params['name'])) {
         $retVal = sprintf('style="%s"', S4_ERROR_COLUMN_COLOR);
     }
     return $retVal;
 }
Example #6
0
 /**
  * Process PayPal Instant Payment Notifications (IPN)
  * @param   IsotopeProductCollection
  */
 public function processPostsale(IsotopeProductCollection $objOrder)
 {
     $objRequest = new \Request();
     $objRequest->send('https://www.' . ($this->debug ? 'sandbox.' : '') . 'paypal.com/cgi-bin/webscr?cmd=_notify-validate', file_get_contents("php://input"), 'post');
     if ($objRequest->hasError()) {
         \System::log('Request Error: ' . $objRequest->error, __METHOD__, TL_ERROR);
         exit;
     } elseif ($objRequest->response == 'VERIFIED' && (\Input::post('receiver_email', true) == $this->paypal_account || $this->debug)) {
         // Validate payment data (see #2221)
         if ($objOrder->currency != \Input::post('mc_currency') || $objOrder->getTotal() != \Input::post('mc_gross')) {
             \System::log('IPN manipulation in payment from "' . \Input::post('payer_email') . '" !', __METHOD__, TL_ERROR);
             return;
         }
         if (!$objOrder->checkout()) {
             \System::log('IPN checkout for Order ID "' . \Input::post('invoice') . '" failed', __METHOD__, TL_ERROR);
             return;
         }
         // Store request data in order for future references
         $arrPayment = deserialize($objOrder->payment_data, true);
         $arrPayment['POSTSALE'][] = $_POST;
         $objOrder->payment_data = $arrPayment;
         $objOrder->save();
         // @see https://www.paypalobjects.com/webstatic/en_US/developer/docs/pdf/ipnguide.pdf
         switch (\Input::post('payment_status')) {
             case 'Completed':
                 $objOrder->date_paid = time();
                 $objOrder->updateOrderStatus($this->new_order_status);
                 break;
             case 'Canceled_Reversal':
             case 'Denied':
             case 'Expired':
             case 'Failed':
             case 'Voided':
                 // PayPal will also send this notification if the order has not been placed.
                 // What do we do here?
                 //                    $objOrder->date_paid = '';
                 //                    $objOrder->updateOrderStatus(Isotope::getConfig()->orderstatus_error);
                 break;
             case 'In-Progress':
             case 'Partially_Refunded':
             case 'Pending':
             case 'Processed':
             case 'Refunded':
             case 'Reversed':
                 break;
         }
         $objOrder->payment_data = $arrPayment;
         $objOrder->save();
         \System::log('PayPal IPN: data accepted', __METHOD__, TL_GENERAL);
     } else {
         \System::log('PayPal IPN: data rejected (' . $objRequest->response . ')', __METHOD__, TL_ERROR);
     }
     // 200 OK
     $objResponse = new Response();
     $objResponse->send();
 }
Example #7
0
 /**
  * @param string $address
  * @param $lang
  * @param bool $blnServer
  * @return array|mixed
  */
 public function getGeoCords($address = '', $lang, $blnServer = false)
 {
     // default return value
     $return = array('lat' => '0', 'lng' => '0');
     // check if parameters are set
     if (!$lang) {
         $lang = 'de';
     }
     if (!$address) {
         return $return;
     }
     // set id
     $keyID = md5(urlencode($address));
     // get lat and lng from cache
     $cacheReturn = $this->geoCordsCache[$keyID];
     if (!is_null($cacheReturn) && is_array($cacheReturn)) {
         return $cacheReturn;
     }
     // check if api key exist
     $apiKey = '';
     $strServerID = \Config::get('googleServerKey') ? \Config::get('googleServerKey') : '';
     $strBrowserID = \Config::get('googleApiKey') ? \Config::get('googleApiKey') : '';
     $strGoogleID = !$blnServer ? $strBrowserID : $strServerID;
     if ($strGoogleID) {
         $apiKey = '&key=' . $strGoogleID . '';
     }
     // create google map api
     $api = 'https://maps.googleapis.com/maps/api/geocode/json?address=%s%s&language=%s&region=%s';
     $strURL = sprintf($api, urlencode($address), $apiKey, urlencode($lang), strlen($lang));
     // send request to google maps api
     $request = new \Request();
     $request->send($strURL);
     // check if request is valid
     if ($request->hasError()) {
         return $return;
     }
     $response = $request->response ? json_decode($request->response, true) : array();
     if (!is_array($response)) {
         return $return;
     }
     if (empty($response)) {
         return $return;
     }
     // set lng and lat
     if ($response['results'][0]['geometry']) {
         $geometry = $response['results'][0]['geometry'];
         $return['lat'] = $geometry['location'] ? $geometry['location']['lat'] : '';
         $return['lng'] = $geometry['location'] ? $geometry['location']['lng'] : '';
     }
     // save cache
     $this->geoCordsCache[$keyID] = $return;
     // return  geoCoding
     return $return;
 }
Example #8
0
 /**
  * Check for new \Contao versions
  */
 public function checkForUpdates()
 {
     if (!is_numeric(BUILD)) {
         return;
     }
     $objRequest = new \Request();
     $objRequest->send(\Config::get('liveUpdateBase') . (LONG_TERM_SUPPORT ? 'lts-version.txt' : 'version.txt'));
     if (!$objRequest->hasError()) {
         \Config::set('latestVersion', $objRequest->response);
         \Config::persist('latestVersion', $objRequest->response);
     }
     // Add a log entry
     $this->log('Checked for Contao updates', __METHOD__, TL_CRON);
 }
Example #9
0
 /**
  * Check for new \Contao versions
  */
 public function checkForUpdates()
 {
     if (!is_numeric(BUILD)) {
         return;
     }
     $objRequest = new \Request();
     $objRequest->send($GLOBALS['TL_CONFIG']['liveUpdateBase'] . (LONG_TERM_SUPPORT ? 'lts-version.txt' : 'version.txt'));
     if (!$objRequest->hasError()) {
         $this->Config->update("\$GLOBALS['TL_CONFIG']['latestVersion']", $objRequest->response);
         $GLOBALS['TL_CONFIG']['latestVersion'] = $objRequest->response;
     }
     // Add a log entry
     $this->log('Checked for Contao updates', 'Automator checkForUpdates()', TL_CRON);
 }
Example #10
0
 /**
  * Find coordinates using the google maps geocode service
  *
  * @param string $strStreet
  * @param string $strPostal
  * @param string $strCity
  * @param string $strCountry
  *
  * @return WGS84|null
  */
 public static function findAddressOnGoogleMaps($strStreet, $strPostal, $strCity, $strCountry)
 {
     $strAddress = sprintf('%s, %s %s %s', $strStreet, $strPostal, $strCity, $strCountry);
     $strAddress = urlencode($strAddress);
     // Get the coordinates
     $objRequest = new \Request();
     $objRequest->send('http://maps.googleapis.com/maps/api/geocode/json?address=' . $strAddress . '&sensor=false');
     // Request failed
     if ($objRequest->hasError()) {
         \System::log('Could not get coordinates for: ' . $strAddress . ' (' . $objRequest->response . ')', __METHOD__, TL_ERROR);
         return null;
     }
     $objResponse = json_decode($objRequest->response);
     return new static($objResponse->results[0]->geometry->location->lat, $objResponse->results[0]->geometry->location->lng);
 }
Example #11
0
 /**
  * Process PayPal Instant Payment Notifications (IPN)
  *
  * @param IsotopeProductCollection|Order $objOrder
  */
 public function processPostsale(IsotopeProductCollection $objOrder)
 {
     if (\Input::post('payment_status') != 'Completed') {
         \System::log('PayPal IPN: payment status "' . \Input::post('payment_status') . '" not implemented', __METHOD__, TL_GENERAL);
         return;
     }
     $objRequest = new \Request();
     $objRequest->send('https://www.' . ($this->debug ? 'sandbox.' : '') . 'paypal.com/cgi-bin/webscr?cmd=_notify-validate', file_get_contents("php://input"), 'post');
     if ($objRequest->hasError()) {
         \System::log('PayPal IPN: Request Error (' . $objRequest->error . ')', __METHOD__, TL_ERROR);
         $response = new Response('', 500);
         $response->send();
     }
     if ($objRequest->response != 'VERIFIED') {
         \System::log('PayPal IPN: data rejected (' . $objRequest->response . ')', __METHOD__, TL_ERROR);
         return;
     }
     if (\Input::post('receiver_email', true) != $this->paypal_account && !$this->debug) {
         \System::log('PayPal IPN: Account email does not match (got ' . \Input::post('receiver_email', true) . ', expected ' . $this->paypal_account . ')', __METHOD__, TL_ERROR);
         return;
     }
     // Validate payment data (see #2221)
     if ($objOrder->currency != \Input::post('mc_currency') || $objOrder->getTotal() != \Input::post('mc_gross')) {
         \System::log('PayPal IPN: manipulation in payment from "' . \Input::post('payer_email') . '" !', __METHOD__, TL_ERROR);
         return;
     }
     if (!$objOrder->checkout()) {
         \System::log('PayPal IPN: checkout for Order ID "' . \Input::post('invoice') . '" failed', __METHOD__, TL_ERROR);
         return;
     }
     // Store request data in order for future references
     $arrPayment = deserialize($objOrder->payment_data, true);
     $arrPayment['POSTSALE'][] = $_POST;
     $objOrder->payment_data = $arrPayment;
     $objOrder->date_paid = time();
     $objOrder->updateOrderStatus($this->new_order_status);
     $objOrder->save();
     \System::log('PayPal IPN: data accepted', __METHOD__, TL_GENERAL);
 }
Example #12
0
 /**
  * Send a PayComplete request to the Saferpay terminal
  *
  * @param string $strId
  * @param string $strToken
  * @param bool   $blnCancel
  *
  * @return bool
  */
 protected function sendPayComplete($strId, $strToken, $blnCancel = false)
 {
     $params = array('ID' => $strId, 'ACCOUNTID' => $this->saferpay_accountid, 'ACTION' => $blnCancel ? 'Cancel' : 'Settlement', 'TOKEN' => $strToken);
     // This is only for the sandbox mode where a password is required
     if (substr($this->saferpay_accountid, 0, 6) == '99867-') {
         $params['spPassword'] = '******';
     }
     $objRequest = new \Request();
     $objRequest->setHeader('Content-Type', 'application/x-www-form-urlencoded');
     $objRequest->send(static::payCompleteURI, http_build_query($params, null, '&'), 'POST');
     // Stop if capture was not successful
     if ($objRequest->hasError() || strtoupper(substr($objRequest->response, 0, 3)) != 'OK:') {
         \System::log(sprintf('Saferpay PayComplete failed. See log files for further details.'), __METHOD__, TL_ERROR);
         log_message(sprintf('Saferpay PayComplete failed. Message was: "%s".', $objRequest->response), 'isotope_saferpay.log');
         return false;
     }
     return true;
 }
 /**
  * Install the files of an extension.
  * @param string $aName Name of the extension to install/update.
  * @param int $aVersion The extension version to install/update to.
  * @param string $aKey License key for commercial or private extensions.
  */
 private function installExtension($aName, $aVersion, $aKey)
 {
     $text =& $GLOBALS['TL_LANG']['tl_repository'];
     $rep =& $this->Template->rep;
     $db =& $this->Database;
     $this->import('Files');
     $err = false;
     try {
         // get package info from repository
         $options = array('name' => $aName, 'version' => $aVersion, 'mode' => 'install');
         if ($aKey != '') {
             $options['key'] = $aKey;
         }
         $pkg = $this->getPackage($options);
         // create tmp name and copy package
         $zipname = 'system/tmp/' . $pkg->path;
         $this->Files->delete($zipname);
         // fetch package - using Request class
         // HOOK: proxy module
         if ($GLOBALS['TL_CONFIG']['useProxy']) {
             $req = new ProxyRequest();
         } else {
             $req = new Request();
         }
         $req->send($pkg->url);
         if ($req->hasError()) {
             throw new Exception($req->error);
         }
         $dstfile = new File($zipname);
         if (!$dstfile->write($req->response)) {
             throw new Exception(sprintf($text['fileerrwrite'], $zipname));
         }
         $dstfile->close();
         $req = null;
         // release mem
         try {
             // initialize counters
             $sum_inst = $sum_updt = 0;
             // open zip archive
             $zip = new ZipReader($zipname);
             try {
                 // get pid of installation record
                 $q = $db->prepare("select `id` from `tl_repository_installs` where `extension`=?")->execute($aName);
                 if (!$q->next()) {
                     throw new Exception($text['extinstrecntf']);
                 }
                 $instId = $q->id;
                 // process files in TL_ROOT and TL_FILES
                 while ($zip->next()) {
                     $filerel = '';
                     if (mb_substr($zip->file_name, 0, 8) == 'TL_ROOT/') {
                         $filerel = mb_substr($zip->file_name, 8);
                     } else {
                         if (mb_substr($zip->file_name, 0, 9) == 'TL_FILES/') {
                             $filerel = $this->tl_files . mb_substr($zip->file_name, 9);
                         }
                     }
                     // if
                     if ($filerel != '') {
                         $fileabs = $this->tl_root . $filerel;
                         if (file_exists($fileabs)) {
                             $sum_updt++;
                         } else {
                             $sum_inst++;
                         }
                         // save new directories by this file
                         $dir = dirname($filerel);
                         $enddirs = array('', '.', '/');
                         while (!in_array($dir, $enddirs) && !file_exists($this->tl_root . $dir)) {
                             $q = $db->prepare("update `tl_repository_instfiles` set `tstamp`=?" . " where `pid`=? and `filetype`='D' and `filename`=?")->executeUncached(array(time(), $instId, $dir));
                             if ($q->affectedRows == 0) {
                                 $db->prepare("insert into `tl_repository_instfiles` %s")->set(array('pid' => $instId, 'tstamp' => time(), 'filename' => $dir, 'filetype' => 'D'))->executeUncached();
                             }
                             $dir = dirname($dir);
                         }
                         // while
                         // save new or changed file
                         $f = new File($filerel);
                         if (!$f->write($zip->unzip())) {
                             throw new Exception(sprintf($text['fileerrwrite'], $filerel));
                         }
                         $f->close();
                         // add new file record
                         $db->prepare("insert into `tl_repository_instfiles` %s")->set(array('pid' => $instId, 'tstamp' => time(), 'filename' => $filerel, 'filetype' => 'F'))->executeUncached();
                     }
                     // if
                 }
                 // for
                 $zip = null;
                 // destruct = close
             } catch (Exception $exc) {
                 $zip = null;
                 throw $exc;
             }
             // catch
             // log counter and success message
             if ($sum_inst > 0) {
                 $rep->log .= '<div>' . sprintf($text['filesinstalled'], $sum_inst) . "</div>\n";
             }
             if ($sum_updt > 0) {
                 $rep->log .= '<div>' . sprintf($text['filesupdated'], $sum_updt) . "</div>\n";
             }
             $rep->log .= '<div class="color_green">' . $text['actionsuccess'] . "</div>\n";
             // cleanup
             $this->Files->delete($zipname);
         } catch (Exception $exc) {
             $this->Files->delete($zipname);
             throw $exc;
         }
         // catch
         $this->log('Extension "' . $aName . '" version "' . Repository::formatVersion($aVersion) . '" has been installed', 'RepositoryManager::installExtension()', TL_REPOSITORY);
     } catch (Exception $exc) {
         $rep->log .= "<div class=\"color_red\">\n" . str_replace("\n", "<br/>\n", $exc->getMessage()) . "<br/>\n" . $exc->getFile() . '[' . $exc->getLine() . ']' . "</div>\n";
         error_log(sprintf('Extension Manager: %s in %s on line %s', $exc->getMessage(), $exc->getFile(), $exc->getLine()));
         $err = true;
     }
     // catch
     return $err;
 }
Example #14
0
	/**
	 * Run the live update
	 * @param BackendTemplate
	 */
	protected function runLiveUpdate(BackendTemplate $objTemplate)
	{
		$archive = 'system/tmp/' . $this->Input->get('token');

		// Download the archive
		if (!file_exists(TL_ROOT . '/' . $archive))
		{
			$objRequest = new Request();
			$objRequest->send($GLOBALS['TL_CONFIG']['liveUpdateBase'] . 'request.php?token=' . $this->Input->get('token'));

			if ($objRequest->hasError())
			{
				$objTemplate->updateClass = 'tl_error';
				$objTemplate->updateMessage = $objRequest->response;
				return;
			}

			$objFile = new File($archive);
			$objFile->write($objRequest->response);
			$objFile->close();
		}

		// Create a minimalistic HTML5 document
		echo '<!DOCTYPE html>'
			.'<head>'
			  .'<meta charset="utf-8">'
			  .'<title>Contao Live Update</title>'
			  .'<style>'
			    .'body { background:#f5f5f5 url("../system/themes/default/images/hbg.jpg") left top repeat-x; font-family:Verdana,sans-serif; font-size:11px; color:#444; padding:1em; }'
			    .'div { max-width:680px; margin:0 auto; border:1px solid #bbb; background:#fff; }'
			    .'h1 { font-size:12px; color:#fff; margin:1px; padding:2px 6px 4px; background:#b3b6b3 url("../system/themes/default/images/headline.gif") left top repeat-x; }'
			    .'h2 { font-size:14px; color:#8ab858; margin:18px 15px; padding:6px 42px 8px; background:url("../system/themes/default/images/current.gif") left center no-repeat; }'
			    .'ol { border:1px solid #ccc; max-height:430px; margin:0 15px 18px; overflow:auto; padding:3px 18px 3px 48px; background:#fcfcfc; }'
			    .'li { margin-bottom:3px; }'
			    .'p { margin:0 12px; padding:0; overflow:hidden; }'
			    .'.button { font-family:"Trebuchet MS",Verdana,sans-serif; font-size:12px; display:block; float:right; margin:0 3px 18px; border-radius:3px; background:#808080; text-decoration:none; color:#fff; padding:4px 18px; box-shadow:0 1px 3px #bbb; text-shadow:1px 1px 0 #666; }'
			    .'.button:hover,.button:focus { box-shadow:0 0 6px #8ab858; }'
			    .'.button:active { background:#8ab858; }'
			  .'</style>'
			.'<body>'
			.'<div>';

		$objArchive = new ZipReader($archive);

		// Table of contents
		if ($this->Input->get('toc'))
		{
			$arrFiles = $objArchive->getFileList();
			array_shift($arrFiles);

			echo '<hgroup>'
				  .'<h1>Contao Live Update</h1>'
				  .'<h2>' . $GLOBALS['TL_LANG']['tl_maintenance']['toc'] . '</h2>'
				.'</hgroup>'
				.'<ol>'
				  .'<li>' . implode('</li><li>', $arrFiles) . '</li>'
				.'</ol>'
				.'<p>'
				  .'<a href="' . ampersand(str_replace('toc=1', 'toc=', $this->Environment->base . $this->Environment->request)) . '" class="button">' . $GLOBALS['TL_LANG']['MSC']['continue'] . '</a>'
				  .'<a href="' . $this->Environment->base . 'contao/main.php?do=maintenance" class="button">' . $GLOBALS['TL_LANG']['MSC']['cancelBT'] . '</a>'
				  .'</p>'
				.'</div>';

			exit;
		}

		// Backup
		if ($this->Input->get('bup'))
		{
			echo '<hgroup>'
				  .'<h1>Contao Live Update</h1>'
				  .'<h2>' . $GLOBALS['TL_LANG']['tl_maintenance']['backup'] . '</h2>'
				.'</hgroup>'
				.'<ol>';

			$arrFiles = $objArchive->getFileList();
			$objBackup = new ZipWriter('LU' . date('YmdHi') . '.zip');

			foreach ($arrFiles as $strFile)
			{
				if ($strFile == 'TOC.txt' || $strFile == 'system/runonce.php')
				{
					continue;
				}

				try
				{
					$objBackup->addFile($strFile);
					echo '<li>Backed up ' . $strFile . '</li>';
				}
				catch (Exception $e)
				{
					echo '<li>' . $e->getMessage() . ' (skipped)</li>';
				}
			}

			$objBackup->close();

			echo '</ol>'
				.'<p>'
				  .'<a href="' . ampersand(str_replace('bup=1', 'bup=', $this->Environment->base . $this->Environment->request)) . '" id="continue" class="button">' . $GLOBALS['TL_LANG']['MSC']['continue'] . '</a>'
				  .'<a href="' . $this->Environment->base . 'contao/main.php?do=maintenance" id="back" class="button">' . $GLOBALS['TL_LANG']['MSC']['cancelBT'] . '</a>'
				  .'</p>'
				.'</div>';

			exit;
 		}

 		echo '<hgroup>'
			  .'<h1>Contao Live Update</h1>'
			  .'<h2>' . $GLOBALS['TL_LANG']['tl_maintenance']['update'] . '</h2>'
			.'</hgroup>'
			.'<ol>';

		// Update
		while ($objArchive->next())
		{
			if ($objArchive->file_name == 'TOC.txt')
			{
				continue;
			}

			try
			{
				$objFile = new File($objArchive->file_name);
				$objFile->write($objArchive->unzip());
				$objFile->close();

				echo '<li>Updated ' . $objArchive->file_name . '</li>';
			}
			catch (Exception $e)
			{
				echo '<li><span style="color:#c55">Error updating ' . $objArchive->file_name . ': ' . $e->getMessage() . '</span></li>';
			}
		}

		// Delete the archive
		$this->import('Files');
		$this->Files->delete($archive);

		// Add a log entry
		$this->log('Live update from version ' . VERSION . '.' . BUILD . ' to version ' . $GLOBALS['TL_CONFIG']['latestVersion'] . ' completed', 'LiveUpdate run()', TL_GENERAL);

		echo '</ol>'
			.'<p>'
			  .'<a href="' . $this->Environment->base . 'contao/main.php?do=maintenance&amp;act=runonce" id="continue" class="button">' . $GLOBALS['TL_LANG']['MSC']['continue'] . '</a>'
			.'</p>'
			.'</div>';

		exit;
	}
Example #15
0
 /**
  * Update the store configs with latest currency conversion data
  * @return void
  */
 public function convertCurrencies()
 {
     $this->import('Database');
     $objConfigs = $this->Database->execute("SELECT * FROM tl_iso_config WHERE currencyAutomator='1'");
     while ($objConfigs->next()) {
         switch ($objConfigs->currencyProvider) {
             case 'ecb.int':
                 $fltCourse = $objConfigs->currency == 'EUR' ? 1 : 0;
                 $fltCourseOrigin = $objConfigs->currencyOrigin == 'EUR' ? 1 : 0;
                 $objRequest = new Request();
                 $objRequest->send('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
                 if ($objRequest->hasError()) {
                     $this->log('Error retrieving data from European Central Bank (ecb.int): ' . $objRequest->error . ' (Code ' . $objRequest->code . ')', __METHOD__, TL_ERROR);
                     return;
                 }
                 $objXml = new SimpleXMLElement($objRequest->response);
                 foreach ($objXml->Cube->Cube->Cube as $currency) {
                     if (!$fltCourse && strtolower($currency['currency']) == strtolower($objConfigs->currency)) {
                         $fltCourse = (double) $currency['rate'];
                     }
                     if (!$fltCourseOrigin && strtolower($currency['currency']) == strtolower($objConfigs->currencyOrigin)) {
                         $fltCourseOrigin = (double) $currency['rate'];
                     }
                 }
                 // Log if one of the currencies is not available
                 if (!$fltCourse || !$fltCourseOrigin) {
                     $this->log('Could not find currency to convert in European Central Bank (ecb.int).', __METHOD__, TL_ERROR);
                     return;
                 }
                 $fltFactor = $fltCourse / $fltCourseOrigin;
                 $this->Database->prepare("UPDATE tl_iso_config SET priceCalculateFactor=? WHERE id=?")->execute($fltFactor, $objConfigs->id);
                 break;
             case 'admin.ch':
                 $fltCourse = $objConfigs->currency == 'CHF' ? 1 : 0;
                 $fltCourseOrigin = $objConfigs->currencyOrigin == 'CHF' ? 1 : 0;
                 $objRequest = new Request();
                 $objRequest->send('http://www.afd.admin.ch/publicdb/newdb/mwst_kurse/wechselkurse.php');
                 if ($objRequest->hasError()) {
                     $this->log('Error retrieving data from Swiss Federal Department of Finance (admin.ch): ' . $objRequest->error . ' (Code ' . $objRequest->code . ')', __METHOD__, TL_ERROR);
                     return;
                 }
                 $objXml = new SimpleXMLElement($objRequest->response);
                 foreach ($objXml->devise as $currency) {
                     if (!$fltCourse && $currency['code'] == strtolower($objConfigs->currency)) {
                         $fltCourse = (double) $currency->kurs;
                     }
                     if (!$fltCourseOrigin && $currency['code'] == strtolower($objConfigs->currencyOrigin)) {
                         $fltCourseOrigin = (double) $currency->kurs;
                     }
                 }
                 // Log if one of the currencies is not available
                 if (!$fltCourse || !$fltCourseOrigin) {
                     $this->log('Could not find currency to convert in Swiss Federal Department of Finance (admin.ch).', __METHOD__, TL_ERROR);
                     return;
                 }
                 $fltFactor = $fltCourse / $fltCourseOrigin;
                 $this->Database->prepare("UPDATE tl_iso_config SET priceCalculateFactor=? WHERE id=?")->execute($fltFactor, $objConfigs->id);
                 break;
             default:
                 // HOOK for other currency providers
                 // function myCurrencyConverter($strProvider, $strSourceCurrency, $strTargetCurrency, $arrConfig)
                 if (isset($GLOBALS['ISO_HOOKS']['convertCurrency']) && is_array($GLOBALS['ISO_HOOKS']['convertCurrency'])) {
                     foreach ($GLOBALS['ISO_HOOKS']['convertCurrency'] as $callback) {
                         $this->import($callback[0]);
                         $this->{$callback}[0]->{$callback}[1]($objConfigs->currencyProvider, $objConfigs->currencyOrigin, $objConfigs->currency, $objConfigs - row());
                     }
                 }
         }
     }
 }
 /**
  * Send Postmark request message
  * @param   Message
  * @param   array
  * @param   string
  * @return  bool
  */
 public function send(Message $objMessage, array $arrTokens, $strLanguage = '')
 {
     if ($this->objModel->postmark_key == '') {
         \System::log(sprintf('Please provide the Postmark API key for message ID "%s"', $objMessage->id), __METHOD__, TL_ERROR);
         return false;
     }
     /**
      * @var $objDraft \NotificationCenter\MessageDraft\PostmarkMessageDraft
      */
     $objDraft = $this->createDraft($objMessage, $arrTokens, $strLanguage);
     // return false if no language found for BC
     if ($objDraft === null) {
         return false;
     }
     $strFrom = $objDraft->getSenderEmail();
     // Generate friendly name from address if possible
     if ($strSenderName = $objDraft->getSenderName()) {
         // Don't do this if the sender name contains the email address
         if ($strFrom !== $strSenderName) {
             $strFrom = $strSenderName . ' <' . $strFrom . '>';
         }
     }
     // Recipients
     $arrTo = $objDraft->getRecipientEmails();
     $arrCc = $objDraft->getCcRecipientEmails();
     $arrBcc = $objDraft->getBccRecipientEmails();
     if (count(array_merge($arrTo, $arrCc, $arrBcc)) >= 20) {
         \System::log(sprintf('The Postmark gateway does not support sending to more than 20 recipients (CC and BCC included) for message ID "%s".', $objMessage->id), __METHOD__, TL_ERROR);
         return false;
     }
     // Set basic data
     $arrData = array('From' => $strFrom, 'To' => implode(',', $arrTo), 'Subject' => $objDraft->getSubject(), 'HtmlBody' => $objDraft->getHtmlBody(), 'TextBody' => $objDraft->getTextBody(), 'TrackOpens' => $objDraft->getTrackOpen());
     // Set CC recipients
     if (!empty($arrCc)) {
         $arrData['Cc'] = implode(',', $arrCc);
     }
     // Set BCC recipients
     if (!empty($arrBcc)) {
         $arrData['Bcc'] = implode(',', $arrBcc);
     }
     // Set reply-to address
     if ($strReplyTo = $objDraft->getReplyToEmail()) {
         $arrData['ReplyTo'] = $strReplyTo;
     }
     // Set the Postmark tag
     if ($strTag = $objDraft->getTag()) {
         $arrData['Tag'] = $strTag;
     }
     $strData = json_encode($arrData);
     $objRequest = new \Request();
     $objRequest->setHeader('Content-Type', 'application/json');
     $objRequest->setHeader('X-Postmark-Server-Token', $this->objModel->postmark_test ? 'POSTMARK_API_TEST' : $this->objModel->postmark_key);
     $objRequest->send(($this->objModel->postmark_ssl ? 'https://' : 'http://') . 'api.postmarkapp.com/email', $strData, 'POST');
     // Postmark uses HTTP status code 10 for wrong API keys. The contao request class cannot handle this and thus returns 0.
     $code = $objRequest->code;
     if ($code == 0) {
         $code = 10;
     }
     if ($objRequest->hasError()) {
         \System::log(sprintf('Error sending the Postmark request for message ID "%s". HTTP Response status code: %s. JSON data sent: %s', $objMessage->id, $code, $strData), __METHOD__, TL_ERROR);
         return false;
     } else {
         $strWouldHave = $this->objModel->postmark_test ? ' would have (test mode)' : '';
         \System::log(sprintf('The Postmark API accepted the request and%s sent %s emails. HTTP Response status code: %s. JSON data sent: %s', $strWouldHave, count($arrTo), $code, $strData), __METHOD__, TL_GENERAL);
     }
     return true;
 }
Example #17
0
 /**
  * Update the store configs with latest currency conversion data
  * @param   int Config id (optional, if none given, all will be taken)
  */
 public function convertCurrencies($intId = 0)
 {
     $arrColumns = array(Config::getTable() . '.currencyAutomator=?');
     $arrValues = array('1');
     if ($intId > 0) {
         $arrColumns[] = Config::getTable() . '.id=?';
         $arrValues[] = $intId;
     }
     $objConfigs = Config::findBy($arrColumns, $arrValues);
     if (null === $objConfigs) {
         return;
     }
     while ($objConfigs->next()) {
         switch ($objConfigs->currencyProvider) {
             case 'ecb.int':
                 $fltCourse = $objConfigs->currency == 'EUR' ? 1 : 0;
                 $fltCourseOrigin = $objConfigs->currencyOrigin == 'EUR' ? 1 : 0;
                 $objRequest = new \Request();
                 $objRequest->send('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
                 if ($objRequest->hasError()) {
                     \System::log('Error retrieving data from European Central Bank (ecb.int): ' . $objRequest->error . ' (Code ' . $objRequest->code . ')', __METHOD__, TL_ERROR);
                     return;
                 }
                 $objXml = new \SimpleXMLElement($objRequest->response);
                 foreach ($objXml->Cube->Cube->Cube as $currency) {
                     if (!$fltCourse && strtolower($currency['currency']) == strtolower($objConfigs->currency)) {
                         $fltCourse = (double) $currency['rate'];
                     }
                     if (!$fltCourseOrigin && strtolower($currency['currency']) == strtolower($objConfigs->currencyOrigin)) {
                         $fltCourseOrigin = (double) $currency['rate'];
                     }
                 }
                 // Log if one of the currencies is not available
                 if (!$fltCourse || !$fltCourseOrigin) {
                     \System::log('Could not find currency to convert in European Central Bank (ecb.int).', __METHOD__, TL_ERROR);
                     return;
                 }
                 $objConfigs->priceCalculateFactor = $fltCourse / $fltCourseOrigin;
                 $objConfigs->save();
                 break;
             case 'admin.ch':
                 $fltCourse = $objConfigs->currency == 'CHF' ? 1 : 0;
                 $fltCourseOrigin = $objConfigs->currencyOrigin == 'CHF' ? 1 : 0;
                 $objRequest = new \Request();
                 $objRequest->send('http://www.afd.admin.ch/publicdb/newdb/mwst_kurse/wechselkurse.php');
                 if ($objRequest->hasError()) {
                     \System::log('Error retrieving data from Swiss Federal Department of Finance (admin.ch): ' . $objRequest->error . ' (Code ' . $objRequest->code . ')', __METHOD__, TL_ERROR);
                     return;
                 }
                 $objXml = new \SimpleXMLElement($objRequest->response);
                 foreach ($objXml->devise as $currency) {
                     if (!$fltCourse && $currency['code'] == strtolower($objConfigs->currency)) {
                         $fltCourse = (double) $currency->kurs;
                     }
                     if (!$fltCourseOrigin && $currency['code'] == strtolower($objConfigs->currencyOrigin)) {
                         $fltCourseOrigin = (double) $currency->kurs;
                     }
                 }
                 // Log if one of the currencies is not available
                 if (!$fltCourse || !$fltCourseOrigin) {
                     \System::log('Could not find currency to convert in Swiss Federal Department of Finance (admin.ch).', __METHOD__, TL_ERROR);
                     return;
                 }
                 $objConfigs->priceCalculateFactor = $fltCourse / $fltCourseOrigin;
                 $objConfigs->save();
                 break;
             default:
                 // !HOOK: other currency providers
                 if (isset($GLOBALS['ISO_HOOKS']['convertCurrency']) && is_array($GLOBALS['ISO_HOOKS']['convertCurrency'])) {
                     foreach ($GLOBALS['ISO_HOOKS']['convertCurrency'] as $callback) {
                         $objCallback = \System::importStatic($callback[0]);
                         $objCallback->{$callback}[1]($objConfigs->current());
                     }
                 }
         }
     }
 }
 /**
  * Fetch the album images and save them into the folder
  */
 public function fetchImages()
 {
     $folder = $this->getAlbumFolder();
     if ($folder === null) {
         return;
     }
     $photos = $this->getPhotos();
     if (empty($photos)) {
         return;
     }
     foreach ($photos as $photo) {
         $request = new \Request();
         $request->send($photo['source']);
         if ($request->hasError()) {
             continue;
         }
         $source = parse_url($photo['source']);
         $file = new \File($folder->path . '/' . basename($source['path']));
         $file->write($request->response);
         $file->close();
     }
     $this->updateMetaFile($photos);
 }
Example #19
0
 /**
  * Process PayPal Instant Payment Notifications (IPN)
  *
  * @access public
  * @return void
  */
 public function processPostSale()
 {
     $arrData = array();
     foreach ($_POST as $k => $v) {
         $arrData[] = $k . '=' . urlencode($v);
     }
     $objRequest = new Request();
     $objRequest->send('https://www.' . ($this->debug ? 'sandbox.' : '') . 'paypal.com/cgi-bin/webscr?cmd=_notify-validate', implode('&', $arrData), 'post');
     if ($objRequest->hasError()) {
         $this->log('Request Error: ' . $objRequest->error, __METHOD__, TL_ERROR);
         exit;
     } elseif ($objRequest->response == 'VERIFIED' && ($this->Input->post('receiver_email', true) == $this->paypal_account || $this->debug)) {
         $objOrder = new IsotopeOrder();
         if (!$objOrder->findBy('id', $this->Input->post('invoice'))) {
             $this->log('Order ID "' . $this->Input->post('invoice') . '" not found', __METHOD__, TL_ERROR);
             return;
         }
         // Validate payment data (see #2221)
         if ($objOrder->currency != $this->Input->post('mc_currency') || $objOrder->grandTotal != $this->Input->post('mc_gross')) {
             $this->log('IPN manipulation in payment from "' . $this->Input->post('payer_email') . '" !', __METHOD__, TL_ERROR);
             return;
         }
         if (!$objOrder->checkout()) {
             $this->log('IPN checkout for Order ID "' . $this->Input->post('invoice') . '" failed', __METHOD__, TL_ERROR);
             return;
         }
         // Load / initialize data
         $arrPayment = deserialize($objOrder->payment_data, true);
         // Store request data in order for future references
         $arrPayment['POSTSALE'][] = $_POST;
         $arrData = $objOrder->getData();
         $arrData['old_payment_status'] = $arrPayment['status'];
         $arrPayment['status'] = $this->Input->post('payment_status');
         $arrData['new_payment_status'] = $arrPayment['status'];
         // array('pending','processing','complete','on_hold', 'cancelled'),
         switch ($arrPayment['status']) {
             case 'Completed':
                 $objOrder->date_paid = time();
                 break;
             case 'Canceled_Reversal':
             case 'Denied':
             case 'Expired':
             case 'Failed':
             case 'Voided':
                 $objOrder->date_paid = '';
                 if ($objOrder->status == 'complete') {
                     $objOrder->status = 'on_hold';
                 }
                 break;
             case 'In-Progress':
             case 'Partially_Refunded':
             case 'Pending':
             case 'Processed':
             case 'Refunded':
             case 'Reversed':
                 break;
         }
         $objOrder->payment_data = $arrPayment;
         $objOrder->save();
         $this->log('PayPal IPN: data accepted', __METHOD__, TL_GENERAL);
     } else {
         $this->log('PayPal IPN: data rejected (' . $objRequest->response . ')', __METHOD__, TL_ERROR);
     }
     header('HTTP/1.1 200 OK');
     exit;
 }