/** * Returns the url for the account administration iframe. * If the passed account is null, then the url will point to the start page where a new account can be created. * * @param NostoAccountMetaDataIframeInterface $meta the iframe meta data. * @param NostoAccount|null $account the account to return the url for. * @param array $params additional parameters to add to the iframe url. * @return string the iframe url. * @throws NostoException if the url cannot be created. */ public function getUrl(NostoAccountMetaDataIframeInterface $meta, NostoAccountInterface $account = null, array $params = array()) { $defaultParameters = array('lang' => strtolower($meta->getLanguageIsoCode()), 'ps_version' => $meta->getVersionPlatform(), 'nt_version' => $meta->getVersionModule(), 'product_pu' => $meta->getPreviewUrlProduct(), 'category_pu' => $meta->getPreviewUrlCategory(), 'search_pu' => $meta->getPreviewUrlSearch(), 'cart_pu' => $meta->getPreviewUrlCart(), 'front_pu' => $meta->getPreviewUrlFront(), 'shop_lang' => strtolower($meta->getLanguageIsoCodeShop()), 'shop_name' => $meta->getShopName(), 'unique_id' => $meta->getUniqueId(), 'fname' => $meta->getFirstName(), 'lname' => $meta->getLastName(), 'email' => $meta->getEmail()); if ($account instanceof NostoAccountInterface) { $missingScopes = $account->getMissingTokens(); if (!empty($missingScopes)) { $defaultParameters['missing_scopes'] = implode(',', $missingScopes); } } $queryParams = http_build_query(array_merge($defaultParameters, $params)); if ($account !== null && $account->isConnectedToNosto()) { try { $url = $account->ssoLogin($meta) . '?' . $queryParams; } catch (NostoException $e) { // If the SSO fails, we show a "remove account" page to the user in order to // allow to remove Nosto and start over. // The only case when this should happen is when the api token for some // reason is invalid, which is the case when switching between environments. $url = NostoHttpRequest::buildUri($this->getBaseUrl() . self::IFRAME_URI_UNINSTALL . '?' . $queryParams, array('{platform}' => $meta->getPlatform())); } } else { $url = NostoHttpRequest::buildUri($this->getBaseUrl() . self::IFRAME_URI_INSTALL . '?' . $queryParams, array('{platform}' => $meta->getPlatform())); } return $url; }
/** * Returns the url for the account administration iframe. * If the passed account is null, then the url will point to the start page where a new account can be created. * * @param NostoAccountMetaSingleSignOnInterface $sso the SSO meta data. * @param NostoAccountMetaIframeInterface $iframe the iframe meta data. * @param NostoAccount|null $account the account to return the url for. * @param array $params additional parameters to add to the iframe url. * @return string the iframe url. * @throws NostoException if the url cannot be created. */ public function getUrl(NostoAccountMetaSingleSignOnInterface $sso, NostoAccountMetaIframeInterface $iframe, NostoAccount $account = null, array $params = array()) { $queryParams = http_build_query(array_merge(array('lang' => $iframe->getLanguage()->getCode(), 'ps_version' => $iframe->getVersionPlatform(), 'nt_version' => $iframe->getVersionModule(), 'product_pu' => $iframe->getPreviewUrlProduct(), 'category_pu' => $iframe->getPreviewUrlCategory(), 'search_pu' => $iframe->getPreviewUrlSearch(), 'cart_pu' => $iframe->getPreviewUrlCart(), 'front_pu' => $iframe->getPreviewUrlFront(), 'shop_lang' => $iframe->getShopLanguage()->getCode(), 'shop_name' => $iframe->getShopName(), 'unique_id' => $iframe->getUniqueId(), 'fname' => $sso->getFirstName(), 'lname' => $sso->getLastName(), 'email' => $sso->getEmail(), 'missing_scopes' => !is_null($account) && !$account->isConnectedToNosto() ? implode(',', $account->getMissingScopes()) : ''), $params)); if ($account !== null) { try { $service = new NostoServiceAccount(); $url = $service->sso($account, $sso); $url .= '?' . $queryParams; } catch (NostoException $e) { // If the SSO fails, we show a "remove account" page to the user in order to // allow to remove Nosto and start over. // The only case when this should happen is when the api token for some // reason is invalid, which is the case when switching between environments. $url = NostoHttpRequest::buildUri($this->getBaseUrl() . self::IFRAME_URI_UNINSTALL . '?' . $queryParams, array('{platform}' => $sso->getPlatform())); } } else { $url = NostoHttpRequest::buildUri($this->getBaseUrl() . self::IFRAME_URI_INSTALL . '?' . $queryParams, array('{platform}' => $sso->getPlatform())); } return $url; }
/** * @param Store $store * @return \NostoAccount */ public function build(Store $store) { $metaData = new \NostoAccount(); try { $metaData->setTitle(implode(' - ', [$store->getWebsite()->getName(), $store->getGroup()->getName(), $store->getName()])); $metaData->setName(substr(sha1(rand()), 0, 8)); $metaData->setFrontPageUrl(\NostoHttpRequest::replaceQueryParamInUrl('___store', $store->getCode(), $store->getBaseUrl(UrlInterface::URL_TYPE_WEB))); $metaData->setCurrency(new \NostoCurrencyCode($store->getBaseCurrencyCode())); $lang = substr($store->getConfig('general/locale/code'), 0, 2); $metaData->setLanguage(new \NostoLanguageCode($lang)); $lang = substr($this->_localeResolver->getLocale(), 0, 2); $metaData->setOwnerLanguage(new \NostoLanguageCode($lang)); $owner = $this->_accountOwnerMetaBuilder->build(); $metaData->setOwner($owner); $billing = $this->_accountBillingMetaBuilder->build($store); $metaData->setBilling($billing); } catch (\NostoException $e) { $this->_logger->error($e, ['exception' => $e]); } return $metaData; }
/** * Loads the meta data for the given store. * * @param Mage_Core_Model_Store $store the store view to load the data for. */ public function loadData(Mage_Core_Model_Store $store) { /* @var Nosto_Tagging_Helper_Data $helper */ $helper = Mage::helper('nosto_tagging'); $this->_title = $helper->cleanUpAccountTitle($store->getWebsite()->getName() . ' - ' . $store->getGroup()->getName() . ' - ' . $store->getName()); $this->_name = substr(sha1(rand()), 0, 8); if (!$helper->getUsePrettyProductUrls()) { $this->_frontPageUrl = NostoHttpRequest::replaceQueryParamInUrl('___store', $store->getCode(), $store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)); } else { $this->_frontPageUrl = $store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB); } $this->_currencyCode = $store->getBaseCurrencyCode(); $this->_languageCode = substr($store->getConfig('general/locale/code'), 0, 2); $this->_ownerLanguageCode = substr(Mage::app()->getLocale()->getLocaleCode(), 0, 2); /** @var Nosto_Tagging_Model_Meta_Account_Owner $owner */ $owner = Mage::getModel('nosto_tagging/meta_account_owner'); $owner->loadData(); $this->_owner = $owner; /** @var Nosto_Tagging_Model_Meta_Account_Billing $billing */ $billing = Mage::getModel('nosto_tagging/meta_account_billing'); $billing->loadData($store); $this->_billing = $billing; $this->_useCurrencyExchangeRates = !$helper->multiCurrencyDisabled($store); if (!$helper->multiCurrencyDisabled($store)) { $this->_defaultPriceVariationId = $store->getBaseCurrencyCode(); } else { $this->_defaultPriceVariationId = ""; } $storeLocale = $store->getConfig('general/locale/code'); $currencyCodes = $store->getAvailableCurrencyCodes(true); if (is_array($currencyCodes) && count($currencyCodes) > 0) { /** @var Nosto_Tagging_Helper_Currency $currencyHelper */ $currencyHelper = Mage::helper('nosto_tagging/currency'); foreach ($currencyCodes as $currencyCode) { $this->_currencies[$currencyCode] = $currencyHelper->getCurrencyObject($storeLocale, $currencyCode); } } }
/** * Gets the absolute preview URL to the current store view front page. * The preview url includes "nostodebug=true" parameter. * * @param Mage_Core_Model_Store $store the store to get the url for. * * @return string the url. */ public function getPreviewUrlFront(Mage_Core_Model_Store $store) { $url = Mage::getUrl('', array('_store' => $store->getId(), '_store_to_url' => true)); return NostoHttpRequest::replaceQueryParamInUrl('nostodebug', 'true', $url); }
/** * @inheritdoc */ public function ssoLogin(NostoAccountMetaDataIframeInterface $meta) { $token = $this->getApiToken('sso'); if ($token === null) { return false; } $request = new NostoHttpRequest(); $request->setUrl(NostoHttpRequest::$baseUrl . NostoHttpRequest::PATH_SSO_AUTH); $request->setReplaceParams(array('{platform}' => $meta->getPlatform(), '{email}' => $meta->getEmail())); $request->setContentType('application/x-www-form-urlencoded'); $request->setAuthBasic('', $token->getValue()); $response = $request->post(http_build_query(array('fname' => $meta->getFirstName(), 'lname' => $meta->getLastName()))); $result = $response->getJsonResult(); if ($response->getCode() !== 200) { Nosto::throwHttpException('Unable to login employee to Nosto with SSO token.', $request, $response); } if (empty($result->login_url)) { throw new NostoException('No "login_url" returned when logging in employee to Nosto'); } return $result->login_url; }
/** * Builds the custom-user agent by using the platform's name and version with the * plugin version * * @param string $platformName the name of the platform using the SDK * @param array $platformVersion the version of the platform using the SDK * @param array $pluginVersion the version of the plugin using the SDK */ public static function buildUserAgent($platformName, $platformVersion, $pluginVersion) { self::$userAgent = sprintf('Nosto %s / %s %s', $pluginVersion, $platformName, $platformVersion); }
/** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Nosto * @package Nosto_Tagging * @author Nosto Solutions Ltd <*****@*****.**> * @copyright Copyright (c) 2013-2016 Nosto Solutions Ltd (http://www.nosto.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** @noinspection PhpIncludeInspection */ require_once Mage::getBaseDir('lib') . '/nosto/php-sdk/src/config.inc.php'; $version = (string) Mage::getConfig()->getNode('modules/Nosto_Tagging/version'); NostoHttpRequest::buildUserAgent('Magento', Mage::getVersion(), $version);
/** * Authenticates the application with the given code to receive an access token. * * @param string $code code sent by the authorization server to exchange for an access token. * @return NostoOAuthToken * @throws NostoException */ public function authenticate($code) { if (empty($code)) { throw new NostoException('Invalid authentication token'); } $request = new NostoHttpRequest(); $request->setUrl(self::$baseUrl . self::PATH_TOKEN); $request->setReplaceParams(array('{cid}' => $this->clientId, '{sec}' => $this->clientSecret, '{uri}' => $this->redirectUrl, '{cod}' => $code)); $response = $request->get(); $result = $response->getJsonResult(true); if ($response->getCode() !== 200) { Nosto::throwHttpException('Failed to authenticate with code.', $request, $response); } if (empty($result['access_token'])) { throw new NostoException('No "access_token" returned after authenticating with code'); } if (empty($result['merchant_name'])) { throw new NostoException('No "merchant_name" returned after authenticating with code'); } return NostoOAuthToken::create($result); }
/** * Redirects the user to the module admin url if the current user is logged in as an admin in the back office. * If the url cannot be found, then show the 404 page. * * @param array $query_params */ protected function redirectToModuleAdmin(array $query_params) { $admin_url = Nosto::helper('nosto_tagging/config')->getAdminUrl(); if (!empty($admin_url)) { $admin_url = NostoHttpRequest::replaceQueryParamsInUrl($query_params, $admin_url); Tools::redirect($admin_url, ''); die; } $this->notFound(); }
/** * Removes given parameter from the url * * @param $url * @param $param * @return string */ public function removeQueryParamFromUrl($url, $param) { $modified_url = $url; $url_parts = NostoHttpRequest::parseUrl($url); if ($url_parts !== false && isset($url_parts['query'])) { $query_array = NostoHttpRequest::parseQueryString($url_parts['query']); if (isset($query_array[$param])) { unset($query_array[$param]); if (empty($query_array)) { unset($url_parts['query']); } else { $url_parts['query'] = http_build_query($query_array); } $modified_url = NostoHttpRequest::buildUrl($url_parts); } } return $modified_url; }
/** * Signs the user in to Nosto via SSO. * * Requires that the account has a valid sso token associated with it. * * @param NostoAccount $account the account to sign into. * @param NostoAccountMetaSingleSignOnInterface $meta the SSO meta-data. * @return string a secure login url. * * @throws NostoException on failure. */ public function sso(NostoAccount $account, NostoAccountMetaSingleSignOnInterface $meta) { $token = $account->getApiToken(NostoApiToken::API_SSO); if (is_null($token)) { throw new NostoException(sprintf('No `%s` API token found for account "%s".', NostoApiToken::API_SSO, $account->getName())); } $request = new NostoHttpRequest(); $request->setUrl(NostoHttpRequest::$baseUrl . NostoHttpRequest::PATH_SSO_AUTH); $request->setReplaceParams(array('{platform}' => $meta->getPlatform(), '{email}' => $meta->getEmail())); $request->setContentType('application/x-www-form-urlencoded'); $request->setAuthBasic('', $token->getValue()); $response = $request->post(http_build_query(array('fname' => $meta->getFirstName(), 'lname' => $meta->getLastName()))); if ($response->getCode() !== 200) { throw Nosto::createHttpException('Failed to sign into Nosto using Single Sign On.', $request, $response); } $result = $response->getJsonResult(); if (empty($result->login_url)) { throw new NostoException('No "login_url" returned when logging in employee to Nosto'); } return $result->login_url; }
/** * Tests the http request socket adapter. */ public function testHttpRequestSocketAdapter() { $request = new NostoHttpRequest(new NostoHttpRequestAdapterSocket(NostoHttpRequest::$userAgent)); $request->setUrl('http://localhost:3000'); $response = $request->get(); $this->assertEquals(404, $response->getCode()); $response = $request->post('test'); $this->assertEquals(404, $response->getCode()); }
/** * Loads the meta data for the given store. * * @param Mage_Core_Model_Store $store the store view to load the data for. */ public function loadData(Mage_Core_Model_Store $store) { $this->_title = $store->getWebsite()->getName() . ' - ' . $store->getGroup()->getName() . ' - ' . $store->getName(); $this->_name = substr(sha1(rand()), 0, 8); $this->_frontPageUrl = NostoHttpRequest::replaceQueryParamInUrl('___store', $store->getCode(), $store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)); $this->_currencyCode = $store->getBaseCurrencyCode(); $this->_languageCode = substr($store->getConfig('general/locale/code'), 0, 2); $this->_ownerLanguageCode = substr(Mage::app()->getLocale()->getLocaleCode(), 0, 2); /** @var Nosto_Tagging_Model_Meta_Account_Owner $owner */ $owner = Mage::getModel('nosto_tagging/meta_account_owner'); $owner->loadData($store); $this->_owner = $owner; /** @var Nosto_Tagging_Model_Meta_Account_Billing $billing */ $billing = Mage::getModel('nosto_tagging/meta_account_billing'); $billing->loadData($store); $this->_billing = $billing; }
/** * Adds the `nostodebug` parameter to a url. * * @param string $url the url. * @return string the updated url. */ public function addNostoDebugParamToUrl($url) { return \NostoHttpRequest::replaceQueryParamInUrl('nostodebug', 'true', $url); }
* * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Nosto Solutions Ltd <*****@*****.**> * @copyright 2016 Nosto Solutions Ltd * @license http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause * */ // This is global bootstrap for autoloading date_default_timezone_set('Europe/Helsinki'); // Pre-load all sdk classes. require_once dirname(__FILE__) . '/../src/config.inc.php'; // Configure API, Web Hooks, and OAuth client to use Mock server when testing. NostoApiRequest::$baseUrl = 'http://localhost:3000'; NostoOAuthClient::$baseUrl = 'http://localhost:3000'; NostoHttpRequest::$baseUrl = 'http://localhost:3000'; NostoHttpRequest::buildUserAgent('PHPUnit', '1.0.0', '1.0.0');
require_once dirname(__FILE__) . '/classes/Nosto.php'; require_once dirname(__FILE__) . '/classes/NostoAccount.php'; require_once dirname(__FILE__) . '/classes/NostoAccountMeta.php'; require_once dirname(__FILE__) . '/classes/NostoCipher.php'; require_once dirname(__FILE__) . '/classes/NostoDotEnv.php'; require_once dirname(__FILE__) . '/classes/NostoMessage.php'; require_once dirname(__FILE__) . '/classes/NostoOrderConfirmation.php'; require_once dirname(__FILE__) . '/classes/NostoProductReCrawl.php'; require_once dirname(__FILE__) . '/classes/NostoValidator.php'; require_once dirname(__FILE__) . '/classes/NostoExchangeRate.php'; require_once dirname(__FILE__) . '/classes/NostoCurrency.php'; require_once dirname(__FILE__) . '/classes/NostoCurrencyCode.php'; require_once dirname(__FILE__) . '/classes/NostoCurrencySymbol.php'; require_once dirname(__FILE__) . '/classes/NostoCurrencyFormat.php'; require_once dirname(__FILE__) . '/classes/NostoCurrencyInfo.php'; // Libs require_once dirname(__FILE__) . '/libs/phpseclib/crypt/NostoCryptBase.php'; require_once dirname(__FILE__) . '/libs/phpseclib/crypt/NostoCryptRijndael.php'; require_once dirname(__FILE__) . '/libs/phpseclib/crypt/NostoCryptAES.php'; require_once dirname(__FILE__) . '/libs/phpseclib/crypt/NostoCryptRandom.php'; // Parse .env if exists and assign configured environment variables. NostoDotEnv::getInstance()->init(dirname(__FILE__)); if (isset($_ENV['NOSTO_API_BASE_URL'])) { NostoApiRequest::$baseUrl = $_ENV['NOSTO_API_BASE_URL']; } if (isset($_ENV['NOSTO_OAUTH_BASE_URL'])) { NostoOAuthClient::$baseUrl = $_ENV['NOSTO_OAUTH_BASE_URL']; } if (isset($_ENV['NOSTO_WEB_HOOK_BASE_URL'])) { NostoHttpRequest::$baseUrl = $_ENV['NOSTO_WEB_HOOK_BASE_URL']; }
/** * Builds a page url for the language and shop. * * We created our own method due to the existing one in `LinkCore` behaving differently across PS versions. * * @param string $controller the controller name. * @param int|null $id_lang the language ID (falls back on current context if not set). * @param int|null $id_shop the shop ID (falls back on current context if not set). * @param array $params additional params to add to the url. * @return string the page url. */ public function getPageUrl($controller, $id_lang = null, $id_shop = null, array $params = array()) { if (is_null($id_lang)) { $id_lang = (int) Context::getContext()->language->id; } if (is_null($id_shop)) { $id_shop = (int) Context::getContext()->shop->id; } if (version_compare(_PS_VERSION_, '1.5.0.0') === -1 || version_compare(_PS_VERSION_, '1.5.5.0') >= 0) { /** @var LinkCore $link */ $link = new Link(); $url = $link->getPageLink($controller, true, $id_lang, null, false, $id_shop); } else { // For PS versions 1.5.0.0 - 1.5.4.1 we always hard-code the urls to be in non-friendly format and fetch // the shops base url ourselves. This is a workaround to all the bugs related to url building in these // PS versions. $query_params = array('controller' => Tools::strReplaceFirst('.php', '', $controller), 'id_lang' => $id_lang); $url = $this->getBaseUrl($id_shop) . 'index.php?' . http_build_query($query_params); } if ((int) Configuration::get('PS_REWRITING_SETTINGS') === 0) { $params['id_lang'] = $id_lang; } return NostoHttpRequest::replaceQueryParamsInUrl($params, $url); }