/**
  * {@inheritdoc}
  */
 public function getCoordinates($street = null, $postal = null, $city = null, $country = null, $fullAddress = null)
 {
     // Generate a new container.
     $objReturn = new Container();
     // Set the query string.
     $sQuery = $this->getQueryString($street, $postal, $city, $country, $fullAddress);
     $objReturn->setSearchParam($sQuery);
     $oRequest = null;
     $oRequest = new \Request();
     $oRequest->send(sprintf($this->strGoogleUrl, rawurlencode($sQuery)));
     $objReturn->setUri(sprintf($this->strGoogleUrl, rawurlencode($sQuery)));
     if ($oRequest->code == 200) {
         $aResponse = json_decode($oRequest->response, 1);
         if (!empty($aResponse['status']) && $aResponse['status'] == 'OK') {
             $objReturn->setLatitude($aResponse['results'][0]['geometry']['location']['lat']);
             $objReturn->setLongitude($aResponse['results'][0]['geometry']['location']['lng']);
         } elseif (!empty($aResponse['error_message'])) {
             $objReturn->setError(true);
             $objReturn->setErrorMsg($aResponse['error_message']);
         } else {
             $objReturn->setError(true);
             $objReturn->setErrorMsg($aResponse['Status']['error_message']);
         }
     } else {
         // Okay nothing work. So set all to Error.
         $objReturn->setError(true);
         $objReturn->setErrorMsg('Could not find coordinates for address "' . $sQuery . '"');
     }
     return $objReturn;
 }
Example #2
0
/**
 * packages.json & provider-xxx$xxx.json downloader
 */
function downloadProviders($config, $globals)
{
    $cachedir = $config->cachedir;
    $packagesCache = $cachedir . 'packages.json';
    $req = new Request($config->packagistUrl . '/packages.json');
    $req->setOption('encoding', 'gzip');
    $res = $req->send();
    if (200 === $res->getStatusCode()) {
        $packages = json_decode($res->getBody());
        foreach (explode(' ', 'notify notify-batch search') as $k) {
            if (0 === strpos($packages->{$k}, '/')) {
                $packages->{$k} = 'https://packagist.org' . $packages->{$k};
            }
        }
        file_put_contents($packagesCache . '.new', json_encode($packages));
    } else {
        //no changes';
        copy($packagesCache, $packagesCache . '.new');
        $packages = json_decode(file_get_contents($packagesCache));
    }
    if (empty($packages->{'provider-includes'})) {
        throw new \RuntimeException('packages.json schema changed?');
    }
    $providers = [];
    $numberOfProviders = count((array) $packages->{'provider-includes'});
    $progressBar = new ProgressBarManager(0, $numberOfProviders);
    $progressBar->setFormat('Downloading Providers: %current%/%max% [%bar%] %percent%%');
    foreach ($packages->{'provider-includes'} as $tpl => $version) {
        $fileurl = str_replace('%hash%', $version->sha256, $tpl);
        $cachename = $cachedir . $fileurl;
        $providers[] = $cachename;
        if (!file_exists($cachename)) {
            $req->setOption('url', $config->packagistUrl . '/' . $fileurl);
            $res = $req->send();
            if (200 === $res->getStatusCode()) {
                $oldcache = $cachedir . str_replace('%hash%', '*', $tpl);
                if ($glob = glob($oldcache)) {
                    foreach ($glob as $old) {
                        $globals->expiredManager->add($old, time());
                    }
                }
                if (!file_exists(dirname($cachename))) {
                    mkdir(dirname($cachename), 0777, true);
                }
                file_put_contents($cachename, $res->getBody());
                if ($config->generateGz) {
                    file_put_contents($cachename . '.gz', gzencode($res->getBody()));
                }
            } else {
                $globals->retry = true;
            }
        }
        $progressBar->advance();
    }
    return $providers;
}
Example #3
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();
 }
 /**
  * {@inheritdoc}
  */
 public function getCoordinates($street = null, $postal = null, $city = null, $country = null, $fullAddress = null)
 {
     // Generate a new container.
     $objReturn = new Container();
     // Set the query string.
     $sQuery = $this->getQueryString($street, $postal, $city, $country, $fullAddress);
     $objReturn->setSearchParam($sQuery);
     $oRequest = null;
     $oRequest = new \Request();
     $oRequest->send(sprintf($this->strUrl, rawurlencode($sQuery)));
     $aResponse = json_decode($oRequest->response);
     $objResponse = $aResponse[0];
     if ($oRequest->code == 200) {
         if (!empty($objResponse->place_id)) {
             $objReturn->setLatitude($objResponse->lat);
             $objReturn->setLongitude($objResponse->lon);
         } else {
             $objReturn->setError(true);
             $objReturn->setErrorMsg('No data from OpenStreetMap for ' . $sQuery);
         }
     } else {
         // Okay nothing work. So set all to Error.
         $objReturn->setError(true);
         $objReturn->setErrorMsg('No response from OpenStreetMap for address "' . $sQuery . '"');
     }
     return $objReturn;
 }
Example #5
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 #6
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 #7
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 #8
0
 public function send()
 {
     Request::post('http://api.postmarkapp.com/email', $this->parseData());
     Request::set(CURLOPT_HTTPHEADER, $this->headers);
     $return = Request::send();
     return isset($return->data) ? $return->data : $return;
 }
 /**
  * @covers AbiosGaming\Request::send
  */
 public function testSend()
 {
     $this->getsData(200, '{"hello":"world"}');
     $request = new Request($this->api, 'ping');
     $data = $request->send();
     $this->assertEquals($this->requestHistory->getLastRequest()->getUrl(), 'https://api.abiosgaming.com/v1/pingjson');
     $this->assertObjectHasAttribute('hello', $data);
     $this->assertEquals('world', $data->hello);
 }
Example #10
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();
 }
 /**
  * Find coordinates for given adress
  * @param string Street
  * @param string Postal/ZIP Code
  * @param string Name of city
  * @param string 2-letter country code
  * @param string Adress string without specific format
  * @return array
  */
 public function getCoordinates($street = NULL, $postal = NULL, $city = NULL, $country = NULL, $fullAdress = NULL)
 {
     // find coordinates using google maps api
     $sQuery = sprintf("%s %s %s %s", $street, $postal, $city, $country);
     $sQuery = $fullAdress ? $fullAdress : $sQuery;
     $oRequest = NULL;
     $oRequest = new Request();
     $oRequest->send("http://maps.googleapis.com/maps/api/geocode/json?address=" . rawurlencode($sQuery) . "&sensor=false&language=de");
     $hasError = false;
     if ($oRequest->code == 200) {
         $aResponse = array();
         $aResponse = json_decode($oRequest->response, 1);
         if (!empty($aResponse['status']) && $aResponse['status'] == 'OK') {
             $coords = array();
             $coords['latitude'] = $aResponse['results'][0]['geometry']['location']['lat'];
             $coords['longitude'] = $aResponse['results'][0]['geometry']['location']['lng'];
             return $coords;
         } else {
             // try alternative api if google blocked us
             $oRequest->send("http://maps.google.com/maps/geo?q=" . rawurlencode($sQuery) . "&output=json&oe=utf8&sensor=false&hl=de");
             if ($oRequest->code == 200) {
                 $aResponse = array();
                 $aResponse = json_decode($oRequest->response, 1);
                 if (!empty($aResponse['Status']) && $aResponse['Status']['code'] == 200) {
                     $coords = array();
                     $coords['latitude'] = $aResponse['Placemark'][0]['Point']['coordinates'][1];
                     $coords['longitude'] = $aResponse['Placemark'][0]['Point']['coordinates'][0];
                     return $coords;
                 } else {
                     $hasError = true;
                 }
             } else {
                 $hasError = true;
             }
         }
     } else {
         $hasError = true;
     }
     if ($hasError) {
         $this->log('Could not find coordinates for adress "' . $sQuery . '"', 'StoreLocator getCoordinates()', TL_ERROR);
     }
     return false;
 }
 public function checkLink($linkliste_id, $linkliste_url = '')
 {
     if ($linkliste_url == '') {
         $objData = $this->Database->prepare("SELECT url FROM tl_link_data WHERE id = ?")->execute($linkliste_id);
         $linkliste_url = $objData->url;
     }
     if ($linkliste_url == '') {
         return false;
     }
     $linkliste_url = html_entity_decode($linkliste_url);
     // Anchor
     if (strstr($linkliste_url, 'link_url')) {
         $linkliste_url = '{{env::url}}/' . $linkliste_url;
         $linkliste_url = $this->replaceInsertTags($linkliste_url);
     }
     $objRequest = new Request();
     $objRequest->send($linkliste_url);
     if (false) {
         echo '<pre>';
         print_r($objRequest);
         echo '</pre>';
     }
     $this->Database->prepare("UPDATE tl_link_data SET be_error = 0, be_warning = 0, be_text = '' WHERE id = ?")->execute($linkliste_id);
     $error = '';
     if ($objRequest->code == 0) {
         $this->Database->prepare("UPDATE tl_link_data SET be_error = 1 WHERE id=?")->execute($linkliste_id);
         if (strstr($objRequest->error, 'Name or service not known')) {
             $error = 'Name or service not known';
         } else {
             $error = $objRequest->error;
         }
     } elseif ($objRequest->code >= 400) {
         $this->Database->prepare("UPDATE tl_link_data SET be_error = 1 WHERE id=?")->execute($linkliste_id);
         $error = $objRequest->error;
     } elseif ($objRequest->code >= 300) {
         $this->Database->prepare("UPDATE tl_link_data SET be_warning = 1 WHERE id=?")->execute($linkliste_id);
         if ($objRequest->code == 301) {
             $error = 'Moved Permanently';
         } else {
             $error = $objRequest->error;
         }
     }
     if ($error != '' || $objRequest->code > 0) {
         $this->Database->prepare("UPDATE tl_link_data SET be_text = ? WHERE id=?")->execute($objRequest->code . ' ' . $error, $linkliste_id);
         //$objRequest->response
     }
     /* duplicates */
     $objData = $this->Database->prepare("SELECT id,be_text FROM tl_link_data WHERE url LIKE ?")->execute('%%' . $linkliste_url . '%%');
     if ($objData->numRows > 1) {
         while ($objData->next()) {
             $this->Database->prepare("UPDATE tl_link_data SET be_warning = 1 , be_text = ? WHERE id=?")->execute('Duplicate entrys ', $objData->id);
         }
     }
 }
Example #13
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 #14
0
 public static function send($data)
 {
     // Get the config information
     $pm = Config::get('email.postmark');
     $key = $pm['apiKey'];
     //  Set headers to send to Postmark
     $headers = array('Accept: application/json', 'Content-Type: application/json', 'X-Postmark-Server-Token: ' . $key);
     Request::post('http://api.postmarkapp.com/email', json_encode($data));
     Request::set(CURLOPT_HTTPHEADER, $headers);
     $return = Request::send();
     return $return;
 }
Example #15
0
/**
 * Submits an HTTP POST to a reCAPTCHA server
 * @param string $host
 * @param string $path
 * @param array $data
 * @param int port
 * @return array response
 */
function _recaptcha_http_post($host, $path, $data, $port = 80)
{
    $req = _recaptcha_qsencode($data);
    $request = new Request($host, $path, $port, true, true, 10);
    $request->setData($data);
    $request->setUserAgent('reCAPTCHA/PHP');
    $request->skiplog(true);
    if (!($response = $request->send())) {
        trigger_error("Unable to reach reCAPCHA server.");
    }
    $response = explode("\r\n\r\n", $response, 2);
    return $response;
}
Example #16
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 #17
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 #18
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 #19
0
 public static function run($config)
 {
     // detect request method and url
     $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
     $path = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
     if (isset($config['domain_url_start_path'])) {
         $path = $config['domain_url_start_path'];
     }
     // parse the proxy url, and grab the directory
     $proxyPath = parse_url($config['proxy_url'], PHP_URL_PATH);
     // replace the proxy directory from the $path
     $path = preg_replace('/^' . preg_quote($proxyPath, '/') . '/', '', $path);
     // make request
     $req = new Request($method, $config['domain_url']);
     $res = $req->send($path);
     // setup response
     // give same http status
     self::setHttpStatus($res->getStatusCode());
     // content-type
     self::setHttpContentType($res->getHeader('content-type'));
     $content = (string) $res->getBody();
     // Hijack all ajax requests
     if (stristr($res->getHeader('content-type'), 'html')) {
         // Idea from: http://verboselogging.com/2010/02/20/hijack-ajax-requests-like-a-terrorist
         $script_include = "\n            <script>\n            (function(open) {\n                // set our start path\n            \tvar ourSuperHackyProxyPath = '" . str_replace('\'', '', $config['proxy_url']) . "/';\n                // hijack the XMLHttpRequest open method\n                XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {\n                    // force internal links to use our proxy\n                    if ( ! url.match(/^https?:\\/\\//)) {\n                        url = ourSuperHackyProxyPath + url.replace(/^\\//, '');\n                    }\n                    open.call(this, method, url, async, user, pass);\n                };\n            })(XMLHttpRequest.prototype.open);\n            </script>";
         $content = str_replace('<head>', '<head>' . $script_include, $content);
     }
     // Handle additional HTML content
     if (isset($config['append_html_content']) && stristr($res->getHeader('content-type'), 'html')) {
         $content .= $config['append_html_content'];
     }
     // run replacements over content
     $res = new Response($content);
     $res->setProxyPath($config['proxy_url']);
     $res->replaceDomainLinks($config['domain_url'] . '/');
     $res->replaceInternalHtmlLinks();
     if (stristr($path, '.css')) {
         $res->replaceInternalCssLinks();
     }
     $content = $res->getHtml();
     // and finaly return the output
     return $content;
 }
 /**
  *
  * @param type $strConfig
  * @param GeolocationContainer $objGeolocation
  * @return boolean|\GeolocationContainer 
  */
 public function getLocation($strConfig, GeolocationContainer $objGeolocation)
 {
     $objRequest = new Request();
     $objRequest->send(vsprintf($strConfig, array($objGeolocation->getLat(), $objGeolocation->getLon())));
     if ($objRequest->code != 200) {
         $this->log("Error by location service: " . vsprintf("Request error code %s - %s ", array($objRequest->code, $objRequest->error)), __CLASS__ . " | " . __FUNCTION__, __FUNCTION__);
         return false;
     }
     $arrJson = json_decode($objRequest->response, true);
     if (!is_array($arrJson)) {
         $this->log("Response is not a array.", __CLASS__ . " | " . __FUNCTION__, __FUNCTION__);
         return false;
     }
     $arrCountries = $this->getCountries();
     $strCountryShort = $arrJson['address']['country_code'];
     $strCounty = $arrCountries[$arrJson['address']['country_code']];
     $objGeolocation->setCountryShort($strCountryShort);
     $objGeolocation->setCountry($strCounty);
     return $objGeolocation;
 }
 /**
  * Returns the layer structure for the map.
  *
  * @param int $id
  */
 protected function getRoutingResponse($intProfileId = 0, $strParams)
 {
     $strRoutingUrl = "http://router.project-osrm.org/viaroute";
     if ($intProfileId > 0) {
         $objMapsProfile = \C4gMapProfilesModel::findBy('id', $intProfileId);
         if ($objMapsProfile !== null) {
             if ($objMapsProfile->router_viaroute_url) {
                 $strRoutingUrl = $objMapsProfile->router_viaroute_url;
             }
         }
     }
     $REQUEST = new \Request();
     if ($_SERVER['HTTP_REFERER']) {
         $REQUEST->setHeader('Referer', $_SERVER['HTTP_REFERER']);
     }
     if ($_SERVER['HTTP_USER_AGENT']) {
         $REQUEST->setHeader('User-Agent', $_SERVER['HTTP_USER_AGENT']);
     }
     $REQUEST->send($strRoutingUrl . '?' . $strParams);
     return $REQUEST->response;
 }
Example #22
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 #23
0
 public function delete($file)
 {
     $encodedEntryURI = $this->policy->encodedEntryURI($file);
     $url = 'http://rs.qiniu.com/delete/' . $encodedEntryURI;
     $access_token = $this->policy->genAccessToken($url);
     $HttpReuqst = new Request($url, 'POST');
     $HttpReuqst->setHeader('Authorization', 'QBox ' . $access_token);
     $response = $HttpReuqst->send();
     $code = $response->getStatus();
     if ($code == 599) {
         //给七牛发邮件
         $body = print_r($response->getRequestHeader(), true) . $response->getBody();
         $mail = new Mailer();
         $mail->setSubject("服务端操作失败");
         $mail->setBody($body);
         $mail->setTo("*****@*****.**");
         $mail->send();
     } elseif ($code != 200) {
         return false;
     }
     return true;
 }
 /**
  * 
  * @param String $strConfig
  * @param GeolocationContainer $objGeolocation
  * @return boolean|GeolocationContainer 
  */
 public function getLocation($strConfig, GeolocationContainer $objGeolocation)
 {
     $objRequest = new Request();
     $objRequest->send(vsprintf($strConfig, array($objGeolocation->getIP())));
     if ($objRequest->code != 200) {
         $this->log("Error by location service: " . vsprintf("Request error code %s - %s ", array($objRequest->code, $objRequest->error)), __CLASS__ . " | " . __FUNCTION__, TL_ERROR);
         return false;
     }
     $arrResponse = deserialize($objRequest->response);
     if (!is_array($arrResponse)) {
         return false;
     }
     $arrCountryShort = strtolower($arrResponse['geoplugin_countryCode']);
     $arrCountries = $this->getCountries();
     if (!key_exists($arrCountryShort, $arrCountries)) {
         return false;
     }
     $objGeolocation->setCountryShort($arrCountryShort);
     $objGeolocation->setCountry($arrCountries[$arrCountryShort]);
     $objGeolocation->setLat($arrResponse['geoplugin_latitude']);
     $objGeolocation->setLon($arrResponse['geoplugin_longitude']);
     return $objGeolocation;
 }
Example #25
0
 protected function sendRequest($url, $content)
 {
     $request = new Request();
     $request->setMethod('POST')->setContent($content);
     return $request->send($url);
 }
Example #26
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 #27
0
 /**
  * processPayment function.
  *
  * @access public
  * @return void
  */
 public function processPayment()
 {
     $this->import('Isotope');
     $objOrder = $this->Database->prepare("SELECT * FROM tl_iso_orders WHERE cart_id=?")->limit(1)->execute($this->Isotope->Cart->id);
     $arrPaymentData = deserialize($objOrder->payment_data);
     $arrBillingSubdivision = explode('-', $this->Isotope->Cart->billingAddress['subdivision']);
     $arrShippingSubdivision = explode('-', $this->Isotope->Cart->shippingAddress['subdivision']);
     //$strExp = str_replace('/','',$_SESSION['CHECKOUT_DATA']['payment'][$this->id]['cc_exp']);
     switch ($_SESSION['CHECKOUT_DATA']['payment'][$this->id]['cc_type']) {
         case 'mc':
             $strCardType = 'MasterCard';
             break;
         case 'visa':
             $strCardType = 'Visa';
             break;
         case 'amex':
             $strCardType = 'Amex';
             break;
         case 'discover':
             $strCardType = 'Discover';
             break;
         case 'jcb':
             $strCardType = 'Jcb';
             break;
         case 'diners':
             $strCardType = 'Diners';
             break;
         case 'maestro':
             $strCardType = 'Maestro';
     }
     $arrData = array('USER' => $this->payflowpro_user, 'VENDOR' => $this->payflowpro_vendor, 'PARTNER' => $this->payflowpro_partner, 'PWD' => $this->payflowpro_password, 'TENDER' => 'C', 'TRXTYPE' => 'S', 'ACCT' => $_SESSION['CHECKOUT_DATA']['payment'][$this->id]['cc_num'], 'EXPDATE' => $_SESSION['CHECKOUT_DATA']['payment'][$this->id]['cc_exp_month'] . $_SESSION['CHECKOUT_DATA']['payment'][$this->id]['cc_exp_year'], 'NAME' => $strCardType, 'AMT' => round($this->Isotope->Cart->grandTotal, 2), 'CURRENCY' => $this->Isotope->Config->currency, 'COMMENT1' => '', 'FIRSTNAME' => $this->Isotope->Cart->billingAddress['firstname'], 'LASTNAME' => $this->Isotope->Cart->billingAddress['lastname'], 'STREET' => $this->Isotope->Cart->billingAddress['street_1'] . "\n" . $this->Isotope->Cart->billingAddress['street_2'] . "\n" . $this->Isotope->Cart->billingAddress['street_3'], 'CITY' => $this->Isotope->Cart->billingAddress['city'], 'STATE' => $arrBillingSubdivision[1], 'ZIP' => $this->Isotope->Cart->billingAddress['postal'], 'COUNTRY' => strtoupper($this->Isotope->Cart->billingAddress['country']), 'NOTIFYURL' => $this->Environment->base . 'system/modules/isotope/postsale.php?mod=pay&id=' . $this->id);
     if ($this->requireCCV) {
         $arrData['CVV2'] = $_SESSION['CHECKOUT_DATA']['payment'][$this->id]['cc_ccv'];
     }
     if ($this->Isotope->Config->country == 'UK') {
         if ($this->Isotope->Cart->billingAddress['country'] == 'UK' && ($_SESSION['CHECKOUT_DATA']['payment'][$this->id]['cc_type'] == 'maestro' || $_SESSION['CHECKOUT_DATA']['payment'][$this->id]['cc_type'] == 'solo')) {
             $arrData['STARTDATE'] = $_SESSION['CHECKOUT_DATA']['payment'][$this->id]['cc_start_date'];
             $arrData['ISSUENUMBER'] = $_SESSION['CHECKOUT_DATA']['payment'][$this->id]['cc_issue_number'];
         }
     }
     $arrData['CLIENTIP'] = $this->Environment->ip;
     $arrData['VERBOSITY'] = 'MEDIUM';
     //$arrFinal = array_map(array($this,'urlEncodeVars'), $arrData);
     foreach ($arrData as $k => $v) {
         $arrNVP[] .= $k . '[' . strlen($v) . ']=' . $v;
     }
     $tempstr = $_SESSION['CHECKOUT_DATA']['payment'][$this->id]['cc_num'] . $this->Isotope->Cart->grandTotal . date('YmdGis') . "1";
     $request_id = md5($tempstr);
     $objRequest = new Request();
     $arrHeaders = array('Content-Type' => 'text/namevalue', 'X-VPS-Request-ID' => $request_id, 'X-VPS-Timeout' => '45', 'X-VPS-VIT-Client-Type' => 'PHP/cURL', 'X-VPS-VIT-Client-Version' => '0.01', 'X-VPS-VIT-Client-Architecture' => 'x86', 'X-VPS-VIT-Integration-Product' => 'Isotope E-commerce', 'X-VPS-VIT-Integration-Version' => '0.01');
     foreach ($arrHeaders as $k => $v) {
         $objRequest->setHeader($k, $v);
     }
     $objRequest->send('https://' . ($this->debug ? 'pilot-' : '') . 'payflowpro.verisign.com/transaction', implode('&', $arrNVP), 'post');
     $pfpro = explode('&', $objRequest->response);
     foreach ($pfpro as $row) {
         $arrPair = explode('=', $row);
         $arrResponse[$arrPair[0]] = $arrPair[1];
     }
     if (isset($arrResponse['RESULT']) && $arrResponse['RESULT'] == 0) {
         return true;
     } else {
         $_SESSION['CHECKOUT_DATA']['payment'][$this->id]['error'] = $arrResponse['RESPMSG'];
         $this->redirect($this->addToUrl('step=payment'));
     }
 }
Example #28
0
    exit;
}
// If there was a login for this one, get the info
$info = $result->fetch();
// Set some timezones and headers
date_default_timezone_set('Europe/Stockholm');
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename=' . 'cal.ics');
// Create the request, send it and parse it
$request = new Request();
$request->loginGetUrl = 'https://fogis.svenskfotboll.se/Fogisdomarklient/Login/Login.aspx';
$request->loginPostUrl = 'https://fogis.svenskfotboll.se/Fogisdomarklient/Login/Login.aspx';
$request->finalGetUrl = 'https://fogis.svenskfotboll.se/Fogisdomarklient/Uppdrag/UppdragUppdragLista.aspx';
$request->username = $info['username'];
$request->password = openssl_decrypt($info['password'], $method, $key);
$request->send();
$request->parseResult();
// Create the output!
?>
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Fogis Domare//Jonas Dahl//SV
URL:http://jdahl.se/domarkalender
NAME:Fogis Domare
X-WR-CALNAME:Fogis Domare
DESCRIPTION:Matcher för Jonas Dahl
X-WR-CALDESC:Matcher för Jonas Dahl
TIMEZONE-ID:Europe/Stockholm
X-WR-TIMEZONE:Europe/Stockholm
REFRESH-INTERVAL;VALUE=DURATION:PT12H
X-PUBLISHED-TTL:PT12H
Example #29
0
 /**
  * Create sitemap
  *
  * @return bool
  */
 public function sitemap()
 {
     // Generate a Sitemap Protocol v0.9 compliant sitemap (http://sitemaps.org)
     $this->_sitemap_xml = new XML();
     $this->_sitemap_xml->startElement('urlset', array('xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9'));
     // Generate Standard records
     $store_url = CC_SSL ? $GLOBALS['config']->get('config', 'ssl_url') : $GLOBALS['config']->get('config', 'standard_url');
     $this->_sitemap_link(array('url' => $store_url . '/index.php'));
     # Sale Items
     if ($GLOBALS['config']->get('config', 'catalogue_sale_mode') !== '0') {
         $this->_sitemap_link(array('url' => $store_url . '/index.php?_a=saleitems'));
     }
     # Gift Certificates
     if ($GLOBALS['config']->get('gift_certs', 'status') == '1') {
         $this->_sitemap_link(array('url' => $store_url . '/index.php?_a=certificates'));
     }
     $queryArray = array('category' => $GLOBALS['db']->select('CubeCart_category', array('cat_id'), array('status' => '1')), 'product' => $GLOBALS['db']->select('CubeCart_inventory', array('product_id', 'updated'), array('status' => '1')), 'document' => $GLOBALS['db']->select('CubeCart_documents', array('doc_id'), array('doc_parent_id' => '0', 'doc_status' => 1)));
     foreach ($queryArray as $type => $results) {
         if ($results) {
             foreach ($results as $record) {
                 switch ($type) {
                     case 'category':
                         $id = $record['cat_id'];
                         $key = 'cat_id';
                         break;
                     case 'product':
                         $id = $record['product_id'];
                         $key = 'product_id';
                         break;
                     case 'document':
                         $id = $record['doc_id'];
                         $key = 'doc_id';
                         break;
                 }
                 $this->_sitemap_link(array('key' => $key, 'id' => $id), !isset($record['updated']) ? (int) $record['updated'] : time(), $type);
             }
         }
     }
     $sitemap = $this->_sitemap_xml->getDocument(true);
     if (function_exists('gzencode')) {
         // Compress the file if GZip is enabled
         $filename = CC_ROOT_DIR . '/sitemap.xml.gz';
         $mapdata = gzencode($sitemap, 9, FORCE_GZIP);
     } else {
         $filename = CC_ROOT_DIR . '/sitemap.xml';
         $mapdata = $sitemap;
     }
     if ($GLOBALS['config']->get('config', 'offline') == '0') {
         if (file_put_contents($filename, $mapdata)) {
             // Ping Google
             $request = new Request('www.google.com', '/webmasters/sitemaps/ping');
             $request->setMethod('get');
             $request->setData(array('sitemap' => $store_url . '/' . basename($filename)));
             $request->send();
             return true;
         }
     }
     return false;
 }
Example #30
0
 public function completePurchase(PurchaseDetails $p, $token, $payerId)
 {
     $req = new Request($this->cfg);
     return new PaymentResult($req->send('DoExpressCheckoutPayment', array('TOKEN' => $token, 'PAYERID' => $payerId, 'MAXAMT' => self::fmt($p->getTotalPrice()), 'PAYMENTREQUEST_0_NOTIFYURL' => $p->getNotifyUrl(), 'PAYMENTREQUEST_0_AMT' => self::fmt($p->getTotalPrice()), 'PAYMENTREQUEST_0_CURRENCYCODE' => $p->getCurrency(), 'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale')));
 }