'https://www.amazon.ae/exec/obidos/ASIN/%s/%s', 'AU' => 'https://www.amazon.com.au/exec/obidos/ASIN/%s/%s', 'BE' => 'https://www.amazon.com.be/exec/obidos/ASIN/%s/%s', 'BR' => 'https://www.amazon.com.br/exec/obidos/ASIN/%s/%s', 'CA' => 'https://www.amazon.ca/exec/obidos/ASIN/%s/%s', 'DE' => 'https://www.amazon.de/exec/obidos/ASIN/%s/%s', 'EG' => 'https://www.amazon.eg/exec/obidos/ASIN/%s/%s', 'FR' => 'https://www.amazon.fr/exec/obidos/ASIN/%s/%s', 'JP' => 'https://www.amazon.jp/exec/obidos/ASIN/%s/%s', 'MX' => 'https://www.amazon.com.mx/exec/obidos/ASIN/%s/%s', 'NL' => 'https://www.amazon.nl/exec/obidos/ASIN/%s/%s', 'SA' => 'https://www.amazon.sa/exec/obidos/ASIN/%s/%s', 'SG' => 'https://www.amazon.sg/exec/obidos/ASIN/%s/%s', 'TR' => 'https://www.amazon.com.tr/exec/obidos/ASIN/%s/%s', 'UK' => 'https://www.amazon.co.uk/exec/obidos/ASIN/%s/%s', 'US' => 'https://www.amazon.com/exec/obidos/ASIN/%s/%s', 'IN' => 'https://www.amazon.in/exec/obidos/ASIN/%s/%s', 'IT' => 'https://www.amazon.it/exec/obidos/ASIN/%s/%s', 'ES' => 'https://www.amazon.es/exec/obidos/ASIN/%s/%s', 'SE' => 'https://www.amazon.se/exec/obidos/ASIN/%s/%s', 'PL' => 'https://www.amazon.pl/exec/obidos/ASIN/%s/%s', ); /** * @var string */ protected $amazon_shop_url; /** * template placeholder prefix */ protected $tpl_prefix = '{$'; /** * template placeholder postfix */ protected $tpl_postfix = '}'; /** * template dir */ protected $tpl_dir = 'tpl'; /** * AmazonSimpleAdmin bb tag regex */ protected $bb_regex = '#\[asa(.[^\]]*|)\]([\w-]+)\[/asa\]#Usi'; /** * AmazonSimpleAdmin bb tag regex */ protected $bb_regex_collection = '#\[asa_collection(.[^\]]*|)\]([\w-\s]+)\[/asa_collection\]#Usi'; /** * param separator regex */ protected $_regex_param_separator = '/(,)(?=(?:[^"]|"[^"]*")*$)/m'; /** * user's Amazon Access Key ID */ protected $_amazon_api_key; /** * user's Amazon Access Key ID * @var string */ protected $_amazon_api_secret_key = ''; /** * user's Amazon Tracking ID */ protected $amazon_tracking_id; /** * selected country code */ protected $_amazon_country_code = 'US'; /** * @var */ protected $_amazon_api_connection_type = 'https'; /** * @var bool */ protected $_asa_use_flat_box_default = false; /** * product preview status * @var bool */ protected $_parse_comments = false; /** * use AJAX * @var bool */ protected $_async_load = false; /** * use only amazon prices for placeholder $AmazonPrice * @var bool */ protected $_asa_use_amazon_price_only = false; /** * internal param delimiter * @var string */ protected $_internal_param_delimit = '[#asa_param_delim#]'; /** * * @var string */ protected $task; /** * wpdb object */ protected $db; /** * collection object */ protected $collection; protected $error = array(); protected $success = array(); /** * the amazon webservice object */ protected $amazon; /** * @var null|bool */ protected $_isCache; /** * the cache object * @var null|AsaZend_Cache_Core|AsaZend_Cache_Frontend_File */ protected $cache; /** * @var Asa_Debugger */ protected $_debugger; /** * @var debugger error message */ protected $_debugger_error; /** * @var AsaEmail */ protected $_email; protected $_tplCssBuffer = array(); /** * constructor */ public function __construct ($wpdb) { //$libdir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lib'; //set_include_path(get_include_path() . PATH_SEPARATOR . $libdir); require_once ASA_LIB_DIR . 'AsaZend/Uri/Http.php'; require_once ASA_LIB_DIR . 'AsaZend/Service/Amazon.php'; require_once ASA_LIB_DIR . 'AsaZend/Service/Amazon/Accessories.php'; require_once ASA_LIB_DIR . 'AsaZend/Service/Amazon/EditorialReview.php'; require_once ASA_LIB_DIR . 'AsaZend/Service/Amazon/Image.php'; require_once ASA_LIB_DIR . 'AsaZend/Service/Amazon/Item.php'; require_once ASA_LIB_DIR . 'AsaZend/Service/Amazon/ListmaniaList.php'; require_once ASA_LIB_DIR . 'AsaZend/Service/Amazon/Offer.php'; require_once ASA_LIB_DIR . 'AsaZend/Service/Amazon/OfferSet.php'; require_once ASA_LIB_DIR . 'AsaZend/Service/Amazon/Query.php'; require_once ASA_LIB_DIR . 'AsaZend/Service/Amazon/ResultSet.php'; require_once ASA_LIB_DIR . 'AsaZend/Service/Amazon/SimilarProduct.php'; require_once ASA_LIB_DIR . 'Asa/Util/Buffer.php'; require_once ASA_LIB_DIR . 'Asa/ItemBuffer.php'; require_once dirname(__FILE__) . '/AsaWidget.php'; register_activation_hook( 'amazonsimpleadmin/amazonsimpleadmin.php', array($this, 'onActivation') ); register_uninstall_hook( 'amazonsimpleadmin/amazonsimpleadmin.php', array('AmazonSimpleAdmin', 'onUninstall') ); if ($this->isDebug()) { $this->_initDebugger(); } if (isset($_GET['task'])) { $this->task = sanitize_text_field($_GET['task']); } $this->tpl_dir = dirname(__FILE__) . DIRECTORY_SEPARATOR . $this->tpl_dir . DIRECTORY_SEPARATOR; $this->db = $wpdb; $this->cache = $this->_initCache(); // init translation load_plugin_textdomain('asa1', false, 'amazonsimpleadmin/lang'); // Hook for adding admin menus add_action('admin_menu', array($this, 'createAdminMenu')); // register shortcode handlers add_shortcode( 'asa', array($this, 'handleShortcodeAsa')); add_shortcode( 'asa_collection', array($this, 'handleShortcodeAsaCollection')); // Hooks for adding shortcode support add_filter('the_excerpt', 'do_shortcode'); add_filter('the_excerpt_feed', 'do_shortcode'); add_filter('the_excerpt_rss', 'do_shortcode'); add_filter('the_content_feed', 'do_shortcode'); add_filter('the_content_rss', 'do_shortcode'); add_filter('widget_text', 'do_shortcode'); if (!get_option('_asa_hide_meta_link')) { add_action('wp_meta', array($this, 'addMetaLink')); } $this->_getAmazonUserData(); $this->_loadOptions(); if ($this->_parse_comments == true) { // Hook for adding content filter for user comments // Feature request from Sebastian Steinfort //add_filter('comment_text', array($this, 'parseContent'), 1); add_filter('comment_text', [$this, 'doCommentShortcode']); } add_filter('upgrader_pre_install', array($this, 'onPreInstall'), 10, 2); add_filter('upgrader_post_install', array($this, 'onPostInstall'), 10, 2); add_action('in_plugin_update_message-amazonsimpleadmin/amazonsimpleadmin.php', array($this, 'handleUpdateMessage')); add_filter('plugin_action_links_amazonsimpleadmin/amazonsimpleadmin.php', array($this, 'addPluginActionLinks')); $this->amazon = $this->connect(); if (get_option('_asa_error_email_notification')) { require_once dirname(__FILE__) . '/AsaEmail.php'; $this->_email = AsaEmail::getInstance(); } $this->_checkPaApiVersion(); $this->_beforeOutput($this->task); $this->_initCallback(); } public function onActivation() { $firstActivation = get_option('_asa_first_activation'); if (empty($firstActivation)) { // only on first activation update_option('_asa_cache_active', 1); update_option('_asa_cache_skip_on_admin', 1); update_option('_asa_first_activation', self::VERSION); } // on every activation require_once dirname(__FILE__) . '/AsaCapabilities.php'; $caps = new AsaCapabilities(); $caps->install(); } public static function onUninstall() { delete_option('_asa_first_activation'); delete_option('_asa_cache_active'); delete_option('_asa_cache_skip_on_admin'); delete_option('_asa_product_preview'); delete_option('_asa_use_flat_box_default'); delete_option('_asa_parse_comments'); delete_option('_asa_async_load'); delete_option('_asa_ajax_css_ani'); delete_option('_asa_hide_meta_link'); delete_option('_asa_use_short_amazon_links'); delete_option('_asa_use_amazon_price_only'); delete_option('_asa_debug'); delete_option('_asa_get_rating_alternative'); delete_option('_asa_custom_widget_class'); delete_option('_asa_replace_empty_main_price'); delete_option('_asa_disable_prefetch'); delete_option('_asa_error_handling'); delete_option('_asa_admin_error_frontend'); delete_option('_asa_use_error_tpl'); delete_option('_asa_error_email_notification'); delete_option('_asa_error_email_notification_bridge_page_id'); delete_option('_asa_cache_lifetime'); delete_option('_asa_cache_dir'); delete_option('_asa_cache_active'); delete_option('_asa_cache_disable_variable_lifetime'); delete_option('_asa_amazon_api_key'); delete_option('_asa_amazon_api_secret_key'); delete_option('_asa_amazon_tracking_id'); delete_option('_asa_api_connection_type'); delete_option('_asa_pa_api_version'); delete_option('_asa_amazon_country_code'); delete_option('_asa_creators_api_credential_id'); delete_option('_asa_creators_api_credential_secret'); delete_option('_asa_creators_api_enabled'); delete_option('_asa_creators_api_tracking_id'); delete_option('_asa_creators_api_version'); delete_option('_asa_creators_api_country_code'); delete_option('_asa_donated'); delete_option('_asa_newsletter'); require_once dirname(__FILE__) . '/AsaCapabilities.php'; $caps = new AsaCapabilities(); $caps->uninstall(); } /** * */ public function addPluginActionLinks($links) { $links[] = '' . __('Settings', 'asa1') . ''; return $links; } protected function _initCallback() { add_action('init', array($this, 'onWpInit')); } public function onWpInit() { if (!is_admin() && $this->_isAsync()) { // be sure to have jQuery if AJAX mode is active wp_enqueue_script('jquery'); } } /** * Called before installation / upgrade * */ public function onPreInstall() { try { $this->backupTemplates(); } catch (Exception $e) { } } /** * Called after installation / upgrade * */ public function onPostInstall() { try { $this->restoreTemplates(); } catch (Exception $e) { } } /** * Backups the template files * */ public function backupTemplates() { $dirIt = new DirectoryIterator($this->tpl_dir); $custom_tpl = array(); foreach ($dirIt as $fileinfo) { if ($fileinfo->isDir() || $fileinfo->isDot()) { continue; } $custom_tpl[] = $fileinfo->getFilename(); } if (count($custom_tpl) > 0) { $backup_destination = $this->_getBackupDestination(); mkdir($backup_destination); foreach($custom_tpl as $tpl_file) { $tpl_source_file = $this->tpl_dir . $tpl_file; $tpl_destination_file = $backup_destination . $tpl_file; $cp = copy($tpl_source_file, $tpl_destination_file); if ($cp == false) { $tpl_data = file_get_contents($tpl_source_file); $handle = fopen($tpl_destination_file, 'w'); fwrite($handle, $tpl_data); fclose($handle); } } } } /** * Restores the template files * */ public function restoreTemplates() { $backup_destination = $this->_getBackupDestination(); if (!is_dir($backup_destination)) { return false; } $dirIt = new DirectoryIterator($backup_destination); $custom_tpl = array(); foreach ($dirIt as $fileinfo) { if ($fileinfo->isDir() || $fileinfo->isDot()) { continue; } $custom_tpl[] = $fileinfo->getFilename(); } if (count($custom_tpl) > 0) { foreach($custom_tpl as $tpl_file) { $tpl_source_file = $backup_destination . $tpl_file; $tpl_destination_file = $this->tpl_dir . $tpl_file; $cp = copy($tpl_source_file, $tpl_destination_file); if ($cp == false) { $tpl_data = file_get_contents($tpl_source_file); $handle = fopen($tpl_destination_file, 'w'); fwrite($handle, $data); fclose($handle); } unlink($tpl_source_file); } } rmdir($backup_destination); } protected function _getBackupDestination() { $tmp = get_temp_dir() . 'amazonsimpleadmin_tpl_backup' . DIRECTORY_SEPARATOR; return $tmp; } /** * trys to connect to the amazon webservice * @return Asa_Service_Amazon|null */ protected function connect () { require_once ASA_LIB_DIR . 'Asa/Service/Amazon.php'; try { $amazon = Asa_Service_Amazon::factory( $this->_amazon_api_key, $this->_amazon_api_secret_key, $this->amazon_tracking_id, $this->_amazon_country_code, $this->_amazon_api_connection_type ); return $amazon; } catch (Exception $e) { if ($this->isDebug() && $this->_debugger != null) { $this->_debugger->write($e->getMessage()); } return null; } } /** * */ protected function _initCache () { if (!$this->isCache()) { return null; } try { require_once ASA_LIB_DIR . 'AsaZend/Cache.php'; $_asa_cache_dir = get_option('_asa_cache_dir'); $current_cache_dir = (!empty($_asa_cache_dir) ? $_asa_cache_dir : 'cache'); $frontendOptions = array( 'lifetime' => $this->getCacheLifetime(), 'automatic_serialization' => true ); $backendOptions = array( 'cache_dir' => dirname(__FILE__) . DIRECTORY_SEPARATOR . $current_cache_dir ); // getting a AsaZend_Cache_Core object $cache = AsaZend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions); return $cache; } catch (Exception $e) { return null; } } /** * Determines if cache is activated and cache dir is writable * @return bool */ public function isCache() { if ($this->_isCache === null) { $_asa_cache_dir = get_option('_asa_cache_dir'); $current_cache_dir = (!empty($_asa_cache_dir) ? $_asa_cache_dir : 'cache'); if (get_option('_asa_cache_active') && is_writable(dirname(__FILE__) . '/' . $current_cache_dir)) { $this->_isCache = true; } else { $this->_isCache = false; } } return $this->_isCache; } /** * @return AsaZend_Cache_Core|AsaZend_Cache_Frontend|AsaZend_Cache_Frontend_File|null */ public function getCache() { return $this->cache; } /** * @return int */ public function getCacheLifetime() { $_asa_cache_lifetime = get_option('_asa_cache_lifetime'); $lifetime = !empty($_asa_cache_lifetime) ? $_asa_cache_lifetime : self::CACHE_DEFAULT_LIFETIME; return (int)$lifetime; } /** * @return int */ public function getVariantCacheLifetime() { $lt = $this->getCacheLifetime(); $variantRange = floor($lt * 0.1); return $lt + rand(1, $variantRange); } /** * @return bool */ public function isVariantCacheLifetime() { $disableVariantLifetime = get_option('_asa_cache_disable_variable_lifetime'); return empty($disableVariantLifetime); } /** * @return bool * @deprecated */ public function isDebug() { return false; } /** * @return bool */ public function isErrorHandling() { return get_option('_asa_error_handling'); } public function getDebugger() { return $this->_debugger; } /** * @return void */ protected function _initDebugger() { require_once ASA_LIB_DIR . 'Asa/Debugger.php'; try { $this->_debugger = Asa_Debugger::factory(); } catch (Exception $e) { $this->_debugger_error = $e->getMessage(); } } /** * action function for above hook * */ public function createAdminMenu () { // Add a new submenu under Options: add_options_page('Affiliate Simple Assistent', 'Affiliate Simple Assistent (ASA1)', 'manage_options', 'amazonsimpleadmin/amazonsimpleadmin.php', array($this, 'createOptionsPage')); add_action('admin_head', array($this, 'getOptionsHead')); wp_enqueue_script( 'listman' ); } /** * creates the AmazonSimpleAdmin admin page * */ public function createOptionsPage () { echo '
'; echo '

Affiliate Simple Assistent (ASA1) '. self::VERSION .'

'; $this->_displayPreDispatcher($this->task); echo wp_kses_post($this->getTabMenu($this->task)); echo '
'; $this->_displayDispatcher($this->task); echo '
'; } /** * */ protected function getTabMenu ($task) { $navItemFormat = '%s'; $nav = '
'; return $nav; } /** * @param string $task * @return string */ protected function _getSubMenu ($task) { $_asa_donated = get_option('_asa_donated'); $nav = '
'; if (empty($task)) { ?>
isCache()) { $nav .= '

'. sprintf( __('It is highly recommended to activate the cache!', 'asa1'), $this->plugin_url .'&task=cache') .'

'; } if ($this->isDebug()) { $nav .= '

'. __('Debugging mode is active. Be sure to deactivate it when you do not need it anymore.', 'asa1') .'

'; } return wp_kses_post( $nav ); } protected function _displayPreDispatcher ($task) { switch ($task) { case 'options': if (count($_POST) > 0 && isset($_POST['info_update'])) { if (!wp_verify_nonce($_POST['nonce'], self::NONCE_SAVE_OPTIONS)) { $this->_displayError(__('Invalid access', 'asa1')); } else { $options = array( '_asa_use_flat_box_default', '_asa_parse_comments', '_asa_async_load', '_asa_ajax_css_ani', '_asa_hide_meta_link', '_asa_use_short_amazon_links', '_asa_use_amazon_price_only', '_asa_debug', '_asa_get_rating_alternative', '_asa_custom_widget_class', '_asa_replace_empty_main_price', '_asa_disable_prefetch', '_asa_error_handling', '_asa_admin_error_frontend', '_asa_use_error_tpl', '_asa_error_email_notification', '_asa_error_email_notification_bridge_page_id', ); foreach ($options as $opt) { $$opt = isset($_POST[$opt]) ? sanitize_text_field($_POST[$opt]) : null; } update_option('_asa_use_flat_box_default', $_asa_use_flat_box_default); update_option('_asa_parse_comments', $_asa_parse_comments); update_option('_asa_async_load', $_asa_async_load); update_option('_asa_ajax_css_ani', $_asa_ajax_css_ani); update_option('_asa_hide_meta_link', $_asa_hide_meta_link); update_option('_asa_use_short_amazon_links', $_asa_use_short_amazon_links); update_option('_asa_use_amazon_price_only', $_asa_use_amazon_price_only); update_option('_asa_debug', $_asa_debug); update_option('_asa_get_rating_alternative', $_asa_get_rating_alternative); update_option('_asa_custom_widget_class', $_asa_custom_widget_class); update_option('_asa_replace_empty_main_price', $_asa_replace_empty_main_price); update_option('_asa_disable_prefetch', $_asa_disable_prefetch); update_option('_asa_error_handling', $_asa_error_handling); update_option('_asa_admin_error_frontend', $_asa_admin_error_frontend); update_option('_asa_use_error_tpl', $_asa_use_error_tpl); update_option('_asa_error_email_notification', $_asa_error_email_notification); update_option('_asa_error_email_notification_bridge_page_id', $_asa_error_email_notification_bridge_page_id); if ($this->isErrorHandling()) { $this->getLogger()->initTable(); } $this->_displaySuccess(__('Settings saved.', 'asa1')); } } if ($this->isDebug()) { $this->_initDebugger(); if (!empty($_POST['_asa_debug_clear'])) { $this->_debugger->clear(); } } break; } } /** * @param $task */ protected function _beforeOutput($task) { switch ($task) { case 'collections': require_once(dirname(__FILE__) . '/AsaCollection.php'); $this->collection = new AsaCollection($this->db); if (isset($_POST['submit_export_collection'])) { $collection_id = sanitize_text_field($_POST['select_manage_collection']); $collection_label = $this->collection->getLabel($collection_id); if ($collection_label !== null) { $this->collection->export((int)$collection_id, $this->_amazon_country_code); } } elseif (isset($_POST['submit_export_all_collections'])) { $collections = $this->collection->getAll(); if (!empty($collections)) { $this->collection->export(array_keys($collections), $this->_amazon_country_code); } } break; } } /** * the actual options page content * */ protected function _displayDispatcher ($task) { if (empty($task) && !current_user_can('asa1_edit_setup') && !current_user_can('activate_plugins')) { if (current_user_can('asa1_edit_options')) { echo ''; } elseif (current_user_can('asa1_edit_collections')) { echo ''; } elseif (current_user_can('asa1_edit_cache')) { echo ''; } else { echo ''; } } $_asa_donated = get_option('_asa_donated'); if ($task == 'checkDonation' && empty($_asa_donated)) { $this->_checkDonated(); } $_asa_newsletter = get_option('_asa_newsletter'); if ($task == 'checkNewsletter' && empty($_asa_newsletter)) { $this->_checkNewsletter(); } switch ($task) { case 'collections': require_once(dirname(__FILE__) . '/AsaCollection.php'); $this->collection = new AsaCollection($this->db); $params = array(); if (isset($_POST['deleteit_collection_item'])) { /** * Delete collection item(s) */ if (!wp_verify_nonce($_POST['nonce'], self::NONCE_MANAGE_COLLECTION)) { $this->error['manage_collection'] = __('Invalid access', 'asa1'); } else { // there is no sanitize function for array inputs // please see the sanitize_text_field function inside the foreach loop $delete_items = isset( $_POST['delete_collection_item'] ) ? (array) $_POST['delete_collection_item'] : array(); if (count($delete_items) > 0) { foreach ($delete_items as $item) { $this->collection->deleteAsin( sanitize_text_field($item) ); } } } } if (isset($_POST['submit_import'])) { /** * Import collection */ if (!wp_verify_nonce($_POST['nonce'], self::NONCE_IMPORT_COLLECTION)) { $this->error['submit_new_asin'] = __('Invalid access', 'asa1'); } else { require_once(dirname(__FILE__) . '/AsaCollectionImport.php'); $file = $_FILES['importfile']['tmp_name']; $import = new AsaCollectionImport($file, $this->collection); $import->import(); if ($import->getError() != null) { $this->error['submit_import'] = $import->getError(); } else { $importedCollections = $import->getImportedCollections(); $this->success['submit_import'] = sprintf(__('Collections imported: %s'), implode(', ', $importedCollections)); } } } if (isset($_POST['submit_new_asin'])) { /** * Add item to collection */ if (!wp_verify_nonce($_POST['nonce'], self::NONCE_ADD_ITEM_TO_COLLECTION)) { $this->error['submit_new_asin'] = __('Invalid access', 'asa1'); } else { $asin = sanitize_text_field($_POST['new_asin']); $collection_id = sanitize_text_field($_POST['collection']); $item = $this->_getItem($asin); if ($item === null) { // invalid asin $this->error['submit_new_asin'] = __('invalid ASIN', 'asa1'); } else if ($this->collection->checkAsin($asin, $collection_id) !== null) { // asin already added to this collection $this->error['submit_new_asin'] = sprintf( __('ASIN already added to collection %s', 'asa1'), $this->collection->getLabel($collection_id) ); } else { if ($this->collection->addAsin($asin, $collection_id) === true) { $this->success['submit_new_asin'] = sprintf( __('%s added to collection %s', 'asa1'), $item->getTitle(), $this->collection->getLabel($collection_id) ); } } } } else if (isset($_POST['submit_manage_collection'])) { $collection_id = sanitize_text_field($_POST['select_manage_collection']); $params['collection_items'] = $this->collection->getItems($collection_id); $params['collection_id'] = $collection_id; } else if (isset($_GET['select_manage_collection']) && isset($_GET['update_timestamp'])) { if (!wp_verify_nonce($_GET['nonce'], self::NONCE_UPDATE_COLLECTION_ITEM)) { $this->error['manage_collection'] = __('Invalid access', 'asa1'); } else { $item_id = sanitize_text_field($_GET['update_timestamp']); $this->collection->updateItemTimestamp($item_id); $collection_id = sanitize_text_field($_GET['select_manage_collection']); $params['collection_items'] = $this->collection->getItems($collection_id); $params['collection_id'] = $collection_id; } } else if (isset($_POST['submit_delete_collection'])) { /** * Delete collection */ if (!wp_verify_nonce($_POST['nonce'], self::NONCE_MANAGE_COLLECTION)) { $this->error['manage_collection'] = __('Invalid access', 'asa1'); } else { $collection_id = sanitize_text_field($_POST['select_manage_collection']); $collection_label = $this->collection->getLabel($collection_id); if ($collection_label !== null) { $this->collection->delete($collection_id); } $this->success['manage_collection'] = sprintf( __('collection deleted: %s', 'asa1'), $collection_label ); } } else if (isset($_POST['submit_new_collection'])) { /** * Create new collection */ if (!wp_verify_nonce($_POST['nonce'], self::NONCE_CREATE_COLLECTION)) { $this->error['submit_new_collection'] = __('Invalid access', 'asa1'); } else { $collection_label = str_replace(' ', '_', trim($_POST['new_collection'])); $collection_label = preg_replace("/[^a-zA-Z0-9_]+/", "", $collection_label); if (empty($collection_label)) { $this->error['submit_new_collection'] = __('Invalid collection label', 'asa1'); } else { if ($this->collection->create($collection_label) == true) { $this->success['submit_new_collection'] = sprintf( __('New collection %s created'), $collection_label ); } else { $this->error['submit_new_collection'] = __('This collection already exists', 'asa1'); } } } } else if (isset($_POST['submit_collection_init']) && isset($_POST['activate_collections'])) { if (!wp_verify_nonce($_POST['nonce'], self::NONCE_ACTIVATE_COLLECTIONS)) { $this->error['activate_collection'] = __('Invalid access', 'asa1'); } else { $this->collection->initDB(); } } echo $this->_getSubMenu($task); if ($this->collection->isEnabled()) { $this->_displayCollectionsPage($params); } else { $this->_displayCollectionsSetup(); } break; case 'usage': echo $this->_getSubMenu($task); $this->_displayUsagePage(); break; case 'faq': echo $this->_getSubMenu($task); $this->_displayFaqPage(); break; case 'test': echo $this->_getSubMenu($task); $this->_displayTestPage(); break; case 'log': echo $this->_getSubMenu($task); $this->_displayLogPage(); break; case 'credits': echo $this->_getSubMenu($task); $this->_displayCreditsPage(); break; case 'templates': echo $this->_getSubMenu($task); $this->_displayTemplates(); break; case 'cache': if (count($_POST) > 0) { if (!wp_verify_nonce($_POST['nonce'], self::NONCE_SAVE_CACHE_OPTIONS)) { $this->_displayError(__('Invalid access', 'asa1')); } elseif (isset($_POST['clean_cache'])) { if (empty($this->cache)) { $this->error['submit_cache'] = __('Cache not activated!', 'asa1'); } else { $this->cache->clean(AsaZend_Cache::CLEANING_MODE_ALL); $this->success['submit_cache'] = __('Cache cleaned up!', 'asa1'); } } else { foreach (array( '_asa_cache_lifetime', '_asa_cache_dir', '_asa_cache_active', '_asa_cache_disable_variable_lifetime', '_asa_cache_skip_on_admin') as $opt) { $$opt = isset($_POST[$opt]) ? sanitize_text_field($_POST[$opt]) : null; } update_option('_asa_cache_lifetime', intval($_asa_cache_lifetime)); update_option('_asa_cache_dir', $_asa_cache_dir); update_option('_asa_cache_active', intval($_asa_cache_active)); update_option('_asa_cache_skip_on_admin', intval($_asa_cache_skip_on_admin)); update_option('_asa_cache_disable_variable_lifetime', intval($_asa_cache_disable_variable_lifetime)); $this->success['submit_cache'] = __('Cache options updated!', 'asa1'); } } echo $this->_getSubMenu($task); $this->_displayCachePage(); break; case 'options': echo $this->_getSubMenu($task); $this->_displayOptionsPage(); break; default: if (count($_POST) > 0 && isset($_POST['setup_update'])) { // Security: Check capability before processing POST data if (!current_user_can('asa1_edit_setup') && !current_user_can('activate_plugins')) { $this->_displayError(__('You do not have sufficient permissions to access this page.', 'asa1')); } elseif (!wp_verify_nonce($_POST['nonce'], self::NONCE_SAVE_SETUP)) { $this->_displayError(__('Invalid access', 'asa1')); } else { $_asa_amazon_api_key = sanitize_text_field($_POST['_asa_amazon_api_key']); $_asa_amazon_tracking_id = sanitize_text_field($_POST['_asa_amazon_tracking_id']); update_option('_asa_amazon_api_key', $_asa_amazon_api_key); update_option('_asa_amazon_tracking_id', $_asa_amazon_tracking_id); // Only update secret if a new value is provided (allows keeping existing secret) if (!empty($_POST['_asa_amazon_api_secret_key'])) { $_asa_amazon_api_secret_key = base64_encode(sanitize_text_field($_POST['_asa_amazon_api_secret_key'])); update_option('_asa_amazon_api_secret_key', $_asa_amazon_api_secret_key); } if (isset($_POST['_asa_amazon_country_code'])) { $_asa_amazon_country_code = sanitize_text_field($_POST['_asa_amazon_country_code']); if (!Asa_Service_Amazon::isSupportedCountryCode($_asa_amazon_country_code)) { $_asa_amazon_country_code = 'US'; } update_option('_asa_amazon_country_code', $_asa_amazon_country_code); } // Save Creators API Credentials require_once ASA_LIB_DIR . 'Asa/Service/CreatorsApi/Credentials.php'; $creatorsCredentials = Asa_Service_CreatorsApi_Credentials::getInstance(); // Only process if PHP version supports Creators API if (Asa_Service_CreatorsApi_Credentials::isPhpVersionSupported()) { // Enabled checkbox $creatorsApiEnabled = isset($_POST['_asa_creators_api_enabled']) && $_POST['_asa_creators_api_enabled'] === '1'; $creatorsCredentials->setEnabled($creatorsApiEnabled); // Credential ID if (isset($_POST['_asa_creators_api_credential_id'])) { $creatorsCredentials->setCredentialId($_POST['_asa_creators_api_credential_id']); } // Credential Secret (only update if not empty - allows keeping existing secret) if (!empty($_POST['_asa_creators_api_credential_secret'])) { $creatorsCredentials->setCredentialSecret($_POST['_asa_creators_api_credential_secret']); } // Tracking ID (optional override) if (isset($_POST['_asa_creators_api_tracking_id'])) { $creatorsCredentials->setTrackingId($_POST['_asa_creators_api_tracking_id']); } // Credential version (Cognito v2.x or LWA v3.x) if (isset($_POST['_asa_creators_api_version'])) { $creatorsCredentials->setVersion(sanitize_text_field($_POST['_asa_creators_api_version'])); } // Country code override (validated against supported Creators API marketplaces) if (isset($_POST['_asa_creators_api_country_code'])) { if (!class_exists('Asa_Service_CreatorsApi', false)) { require_once ASA_LIB_DIR . 'Asa/Service/CreatorsApi.php'; } $countryInput = strtoupper(sanitize_text_field($_POST['_asa_creators_api_country_code'])); if ($countryInput === '' || in_array($countryInput, Asa_Service_CreatorsApi::getSupportedLocales(), true)) { $creatorsCredentials->setCountryCode($countryInput); } } $creatorsCredentials->save(); // Reset singleton to reload credentials Asa_Service_CreatorsApi_Credentials::resetInstance(); } $this->_displaySuccess(__('Settings saved.', 'asa1')); } } echo $this->_getSubMenu($task); $this->_displaySetupPage(); } } /** * check if user wants to hide the donation notice */ protected function _checkDonated () { if ($_POST['asa_donated'] == '1') { update_option('_asa_donated', '1'); } } /** * check if user wants to hide the newsletter box */ protected function _checkNewsletter () { if ($_POST['asa_check_newsletter'] == '1') { update_option('_asa_newsletter', '1'); } } /** * collections asasetup screen * */ protected function _displayCollectionsSetup () { if (!current_user_can('asa1_edit_collections') && !current_user_can('activate_plugins')) { do_action( 'admin_page_access_denied' ); wp_die( __( 'You do not have sufficient permissions to access this page.' ), 403 ); } ?>

 

 

guide if you do not know how to use collections.', 'asa1'), 'https://www.wp-amazon-plugin.com/guide/'); ?>

error['submit_new_collection'])) { $this->_displayError($this->error['submit_new_collection']); } else if (isset($this->success['submit_new_collection'])) { $this->_displaySuccess($this->success['submit_new_collection']); } ?>


()

error['submit_import'])) { $this->_displayError($this->error['submit_import']); } else if (isset($this->success['submit_import'])) { $this->_displaySuccess($this->success['submit_import']); } ?>


error['submit_new_asin'])) { $this->_displayError($this->error['submit_new_asin']); } else if (isset($this->success['submit_new_asin'])) { $this->_displaySuccess($this->success['submit_new_asin']); } ?>
collection->getSelectField('collection', $collection_id) ); ?>

_displaySidebar(); ?>

error['manage_collection'])) { $this->_displayError($this->error['manage_collection']); } else if (isset($this->success['manage_collection'])) { $this->_displaySuccess($this->success['manage_collection']); } ?>
collection->getSelectField('select_manage_collection', $manage_collection_id) ); ?>

:

plugin_url .'&task=collections" method="post">'; $table .= ''; $table .= '

'; $table .= ''; $table .= ''; $table .= ''; $table .= ''; $table .= ''; $table .= ''; $table .= ''; $table .= ''; $table .= ''; $table .= ''; $thumb_max_width = array(); for ($i=0;$i_getItem((string)$row->collection_item_asin); if ($item === null) { continue; } if ($i%2==0) { $tr_class =''; } else { $tr_class = ' class="alternate"'; } $title = $item->getTitle(); if (!empty($title)) { $title = str_replace("'", "\'", $title); } else { $title = __('Invalid item', 'asa1'); } $table .= ''; $table .= ''; $smallImageUrl = $item->getSmallImageURL(); if (!empty($smallImageUrl)) { $thumbnail = $smallImageUrl; } else { $thumbnail = asa_plugins_url( 'img/no_image.gif', __FILE__ ); } $mainPriceFormatted = $item->getOffersMainPriceFormattedPrice(); if (empty($mainPriceFormatted)) { $price = '---'; } else { $price = $mainPriceFormatted; } $DetailPageURL = $item->getDetailPageURL(); $table .= ''; $table .= ''; $table .= ''; $table .= ''; $table .= ''; $table .= ''; $table .= ''; $smallImageWidth = $item->getSmallImageWidth(); if (!empty($smallImageWidth)) { $thumb_max_width[] = $smallImageWidth; } } rsort($thumb_max_width); $table .= '
ASIN'. __('Price', 'asa1') .''. __('Title', 'asa1') .''. __('Timestamp', 'asa1') . '
'. $row->collection_item_asin .''. $price .''. $title .''. date(str_replace(' \<\b\r \/\>', ',', __('Y-m-d \<\b\r \/\> g:i:s a')), $row->timestamp) .''. __('latest', 'asa1') .'
'; $search = array( '/\[thumb_width\]/', ); $replace = array( isset($thumb_max_width[0]) ? $thumb_max_width[0] : '', ); echo esc_html_asa( preg_replace($search, $replace, $table) ); echo '
'; } else if (isset($collection_id)) { echo '

' . __('Nothing found. Add some products.', 'asa1') .'

'; } ?>

Usage Guide on the plugin\'s homepage to learn how to use it.', 'asa1'), 'https://www.wp-amazon-plugin.com/usage/' ); ?>

Step by Step Guide if you are new to this plugin.', 'asa1'), 'https://www.wp-amazon-plugin.com/guide/'); ?>


  • [asa tpl="flat_box_vertical"]ASIN[/asa]
  • [asa_collection tpl="flat_box_vertical"]collection_name[/asa]

: Keeping your custom templates update safe

    getAllTemplates(); foreach ($templates as $template) { echo '
  • '. sanitize_text_field( $template ) .'
  • '; } ?>
_displaySidebar(); ?>
request('GET'); if ($response->isSuccessful()) { echo wp_kses_post( $response->getBody() ); } else { echo wp_kses_post( '

Could not load FAQ from '. $faqUrl . '

' ); } } /** * the actual options page content * */ protected function _displayTestPage () { $templates = $this->getAllTemplates(); $mode = 'tpl'; if (count($_POST) > 0 && isset($_POST['asin']) && !empty($_POST['asin'])) { if (!wp_verify_nonce($_POST['nonce'], self::NONCE_SUBMIT_TEST)) { $this->_displayError(__('Invalid access', 'asa1')); } else { $asin = sanitize_text_field($_POST['asin']); if (isset($_POST['tpl'])) { $tpl = sanitize_text_field($_POST['tpl']); } else { $tpl = 'demo'; } if (isset($_POST['mode'])) { switch ($_POST['mode']) { case 'ratings': $mode = 'ratings'; break; default: $mode = 'tpl'; } } if (isset($_POST['block-log'])) { $blockLog = true; } } } ?>

:    
isErrorHandling()): ?>
_displaySidebar(); ?>
getLogger()->setBlock(true); } echo '

' . __('Result', 'asa1') . ':

'; if ($mode == 'tpl') { if (!isset($tpl) || empty($tpl)) { $tpl = 'demo'; } echo esc_html_asa( $this->getItem($asin, $tpl) ); } elseif ($mode == 'ratings') { $item = $this->_getItem($asin); if (!($item instanceof Asa_Service_Amazon_Item)) { echo '

' . __('Customer ratings could not be retrieved.', 'asa1') . '

'; echo '

' . esc_html__('The Amazon item could not be loaded. Check the Log tab for the underlying API error (invalid credentials, network failure, or unknown ASIN).', 'asa1') . '

'; return; } // get the customer rating object $customerReviews = $this->getCustomerReviews($item, true); if ($customerReviews->isSuccess()) { echo '

' . __('Successfully retrieved customer ratings.', 'asa1') . '

'; echo '

' . __('Total reviews:', 'asa1') . ' ' . esc_html( $customerReviews->totalReviews ) . '

'; echo '

' . __('Average rating:', 'asa1') . ' ' . esc_html( $customerReviews->averageRating ) . '

'; echo '

' . __('Image source:', 'asa1') . ' ' . esc_html( $customerReviews->imgSrc ) . '

'; echo esc_html_asa( $customerReviews->imgTag ); } else { echo '

' . __('Customer ratings could not be retrieved.', 'asa1') . '

'; echo '

Error message: ' . esc_html( $customerReviews->getErrorMessage() ) . '

'; echo '
';
                }
            }

        } elseif (count($_POST) > 0) {
            _e('Invalid ASIN', 'asa1');
        }
    }

    protected function _displayLogPage()
    {
        require_once dirname(__FILE__) . '/AsaLogListTable.php';

        if (isset($_POST['action']) && $_POST['action'] == 'clear') {
            $this->getLogger()->clear();
            echo '

'. __('All log entries have been deleted.') .'

'; } $listTable = new AsaLogListTable(); $listTable->setLogger($this->getLogger()); $listTable->prepare_items(); ?>

display(); ?>

getAllTemplatesWithPaths(); ?>

0): ?>

[asa tpl=""]ASIN[/asa]

[asa_collection tpl=""]collection_name[/asa_collection]

  • keeping your custom templates update safe.', 'asa1'), 'https://www.wp-amazon-plugin.com/2015/13280/keeping-your-custom-templates-update-safe/'); ?>

_displaySidebar(); ?>
_loadOptions(); ?>

support how to interpret the debugging information.', 'asa1'), 'https://www.wp-amazon-plugin.com/contact/' ); ?>isDebug()): ?> _debugger_error != null): ?> _debugger_error ); ?>_debugger instanceof Asa_Debugger && $this->_debugger->getWriter() instanceof Asa_Debugger_Writer_File) echo __('from', 'asa1') . ': ' . esc_html( $this->_debugger->getWriter()->getFilename() ); ?>plugin_url ); ?>_debugger)) echo nl2br(esc_html($this->_debugger->read())); ?>

_async_load == true) ? 'checked="checked"' : '') ?> />



_asa_use_flat_box_default == true) ? 'checked="checked"' : '') ?> />

_parse_comments == true) ? 'checked="checked"' : '') ?> />


:

/>

/>


:

/>

/>


/>

/>

error_admin.htm will be used.', 'asa1'); ?>

/>

error.htm will be used. ', 'asa1'); ?>

/>


documentation about how to setup this feature. Error handling must be activated.', 'asa1'), 'https://www.wp-amazon-plugin.com/email-notification-feature/'); ?>

_displaySidebar(); ?>

Get ASA2!

task != 'collections'): ?>

empty ratings stars?', 'asa1'); ?>
advanced ratings mode.', 'asa1'), ' href="https://docs.getasa2.com/ratings.html#advanced-ratings-mode" target="_blank"'); ?>

task == 'collections'): ?>

task == 'options' || $this->task == 'test'): ?>

teaser video on YouTube.', 'asa1'); ?>

task == 'cache'): ?>

ASA2\'s caching strategy in the manual.', 'asa1'), ' href="https://docs.getasa2.com/caching.html" target="_blank"'); ?>

task == 'usage'): ?>

backwards compatible.', 'asa1'); ?> Migration Wizard for templates and collections.', 'asa1'), ' href="https://docs.getasa2.com/migration_wizard.html" target="_blank"'); ?>

task == null): ?> task != 'collections') : ?>


_amazon_api_key) && !empty($this->_amazon_api_secret_key)) { try { $this->amazon = $this->connect(); if ($this->amazon != null) { $this->amazon->testConnection(); $success = true; } else { $message = __('Connection to Amazon Webservice failed. Please check the mandatory data.', 'asa1'); } } catch (Exception $e) { $message = $e->getMessage(); } } return array('success' => $success, 'message' => $message); } /** * Retrieves connections status * * @return bool */ public function getConnectionStatus() { $result = $this->testConnection(); return $result['success'] === true; } /** * Loads setup panel * */ protected function _displaySetupPage () { if (!current_user_can('asa1_edit_setup') && !current_user_can('activate_plugins')) { do_action( 'admin_page_access_denied' ); wp_die( __( 'You do not have sufficient permissions to access this page.' ), 403 ); } if (!empty($_GET['setup_reset']) && wp_verify_nonce($_GET['nonce'], 'asa-setup-reset')) { Asa_Service_Amazon::resetCredentials(); header('Location: ' . admin_url('options-general.php?page=amazonsimpleadmin/amazonsimpleadmin.php')); } $_asa_status = false; $this->_getAmazonUserData(); $connectionTestResult = $this->testConnection(); if ($connectionTestResult['success'] === true) { $_asa_status = true; } else { $_asa_error = $connectionTestResult['message']; } ?>

Amazon has announced the deprecation of the Product Advertising API (PA API). The API is expected to stop working on or around May 15, 2026.', 'asa1'); ?>

Amazon Creators API as soon as possible. ASA1 already supports both Cognito (v2.x) and LWA (v3.x) credentials — configure them in the Amazon Creators API section below.', 'asa1'); ?>

' . __('Amazon Creators API onboarding', 'asa1') . '' ); ?>

'; echo '

'. __('PHP Version', 'asa1') .': '; echo sprintf( __('You are using PHP version %s. WordPress recommends PHP %s or higher for optimal performance, security, and compatibility.', 'asa1'), $current_php, $recommended_php ); echo ' '; echo sprintf( __('Please contact your hosting provider to upgrade to PHP %s or higher.', 'asa1'), $recommended_php ); echo ' '; echo __('While ASA1 currently works with older PHP versions, support for outdated versions will be discontinued in future releases.', 'asa1'); echo ' '; echo sprintf( __('Learn more about WordPress requirements.', 'asa1'), 'https://wordpress.org/about/requirements/' ); echo '

'; } ?>

'. __('Error', 'asa1') .': '. esc_html($_asa_error) . '

'; } ?>
: — %s to see how ASA works.', 'asa1'), ' href="options-general.php?page=amazonsimpleadmin%2Famazonsimpleadmin.php&task=usage"', __('Usage', 'asa1')); ?>



_amazon_api_secret_key)): ?>

✓


(: US)

:

:

—

/>

/>

hasCredentialSecret()): ?>
✓

/>

getVersion(); $localeFallback = Asa_Service_CreatorsApi_Credentials::getDefaultVersionForLocale($this->_amazon_country_code); ?>

getCountryCode(); $supportedLocales = Asa_Service_CreatorsApi::getSupportedLocales(); sort($supportedLocales); ?>

  • PA API Fallback: If PA API credentials are configured and Creators API fails or is disabled, ASA1 automatically falls back to PA API.', 'asa1'); ?>
  • Credential Version: v2.x credentials use Cognito, v3.x credentials (issued from February 2026) use Login with Amazon. Both are accepted by ASA1; choose the one Amazon issued for your account.', 'asa1'); ?>
  • Get Credentials: Find the PartnerNet URL for your country in our %1$s, then check out the %2$s to learn how to register.', 'asa1'), '' . __('documentation', 'asa1') . '', '' . __('Amazon Creators API Documentation', 'asa1') . '' ); ?>



:

_displaySidebar(); ?>

error['submit_cache'])) { $this->_displayError($this->error['submit_cache']); } else if (isset($this->success['submit_cache'])) { $this->_displaySuccess($this->success['submit_cache']); } ?>

/>
/>
/>


(writable!', 'asa1'); ?>)
'. __('writable', 'asa1') . ''; } else { echo ''. __('not writable', 'asa1') . ''; } ?>

_displaySidebar(); ?>

'. __('Error', 'asa1') .': '. esc_html( $error ) .'

'; } /** * */ protected function _displaySuccess ($success) { echo '

'. __('Success', 'asa1') .': '. esc_html( $success ) .'

'; } /** * parses post content * * @param string $content post content * @return string parsed content * @deprecated */ public function parseContent ($content) { return $content; } /** * Retrieves default template name */ public function getDefaultTplName() { if ($this->_asa_use_flat_box_default == true) { $tpl_file_name = 'flat_box_horizontal'; } else { $tpl_file_name = 'default'; } return $tpl_file_name; } /** * Retrieves all existing template files */ public function getAllTemplates() { $availableTemplates = array(); foreach($this->getTplLocations() as $loc) { if (!is_dir($loc)) { continue; } $dirIt = new DirectoryIterator($loc); foreach ($dirIt as $fileinfo) { $filename = $fileinfo->getFilename(); if ($fileinfo->isDir() || $fileinfo->isDot()) { continue; } $filePathinfo = pathinfo($filename); if (!in_array($filePathinfo['extension'], $this->getTplExtensions())) { continue; } array_push($availableTemplates, $filePathinfo['filename']); } } $availableTemplates = array_unique($availableTemplates); sort($availableTemplates); return $availableTemplates; } public function getAllTemplatesWithPaths() { $availableTemplates = array(); foreach($this->getTplLocations() as $loc) { if (!is_dir($loc)) { continue; } $dirIt = new DirectoryIterator($loc); foreach ($dirIt as $fileinfo) { $filename = $fileinfo->getFilename(); if ($fileinfo->isDir() || $fileinfo->isDot()) { continue; } $filePathinfo = pathinfo($filename); if (!in_array($filePathinfo['extension'], $this->getTplExtensions())) { continue; } $templateName = $filePathinfo['filename']; // Exclude demo and error templates from display $excludedTemplates = array('demo', 'error', 'error_admin'); if (in_array($templateName, $excludedTemplates)) { continue; } if (!isset($availableTemplates[$templateName])) { $availableTemplates[$templateName] = array( 'name' => $templateName, 'path' => $loc . $filename, 'location' => $loc, 'is_builtin' => (strpos($loc, 'built-in') !== false) ); } } } ksort($availableTemplates); return $availableTemplates; } /** * Retrieves template file to use * @param $tpl_file * @param bool $default * @return bool|string */ public function getTpl($tpl_file, $default = false, $skipCss = false) { if (!empty($tpl_file)) { if (!Asa_Util_Buffer::exists($tpl_file, 'tpl_source')) { foreach ($this->getTplLocations() as $loc) { if (!is_dir($loc)) { continue; } foreach ($this->getTplExtensions() as $ext) { $tplPath = $loc . $tpl_file . '.' . $ext; if (file_exists($tplPath)) { if (!Asa_Util_Buffer::exists($tpl_file, 'tpl_css')) { if (strpos($tpl_file, 'flat_box_horizontal') !== false) { $tplCssPath = $loc . 'flat_box_horizontal.css'; } elseif (strpos($tpl_file, 'flat_box_vertical') !== false) { $tplCssPath = $loc . 'flat_box_vertical.css'; } else { $tplCssPath = $loc . $tpl_file . '.css'; } $tplCss = $this->_getTplCss($tplCssPath); if (!empty($tplCss)) { Asa_Util_Buffer::set($tpl_file, $tplCss, 'tpl_css'); } } $tpl = ''; $tpl .= asa_compress_html(trim(file_get_contents($tplPath))); } } if (isset($tpl)) { Asa_Util_Buffer::set($tpl_file, $tpl, 'tpl_source'); break; } } } } if (Asa_Util_Buffer::exists($tpl_file, 'tpl_source')) { // template found $tpl = ''; if (!$skipCss && Asa_Util_Buffer::exists($tpl_file, 'tpl_css') && !Asa_Util_Buffer::exists($tpl_file, 'tpl_css_added')) { $tpl .= $this->getCssStyleTag(Asa_Util_Buffer::get($tpl_file, 'tpl_css')); Asa_Util_Buffer::set($tpl_file, true, 'tpl_css_added'); } $tpl .= Asa_Util_Buffer::get($tpl_file, 'tpl_source'); } else { if ($default === true) { // get default template $tpl = $this->getTpl($this->getDefaultTplName(), false, $skipCss); } elseif (is_string($default)) { // take provided string $tpl = $default; } else { $tpl = false; } } return wp_kses_asa( $tpl ); } /** * @param $tplCssPath * @return mixed|string */ protected function _getTplCss($tplCssPath) { if (!array_key_exists($tplCssPath, $this->_tplCssBuffer) && file_exists($tplCssPath)) { $this->_tplCssBuffer[$tplCssPath] = asa_compress_css(trim(file_get_contents($tplCssPath))); return $this->_tplCssBuffer[$tplCssPath]; } return ''; } /** * @param $css * @return string */ public function getCssStyleTag($css) { return sprintf('', $css); } /** * @return mixed|void */ public function getTplLocations() { $tplLocations = array( get_stylesheet_directory() . DIRECTORY_SEPARATOR . 'asa' . DIRECTORY_SEPARATOR, dirname(__FILE__) . DIRECTORY_SEPARATOR . 'tpl' . DIRECTORY_SEPARATOR, dirname(__FILE__) . DIRECTORY_SEPARATOR . 'tpl' . DIRECTORY_SEPARATOR . 'built-in' . DIRECTORY_SEPARATOR ); return apply_filters('asa_tpl_locations', $tplLocations); } /** * @return mixed|void */ public function getTplExtensions() { $tplExtensions = array('htm', 'html'); return apply_filters('asa_tpl_extensions', $tplExtensions); } /** * parses the chosen template * * @param $asin * @param $tpl * @param null $parse_params * @param null $tpl_file * @internal param \amazon $string asin * @internal param \the $string template contents * * @return string the parsed template */ public function parseTpl ($asin, $tpl, $parse_params=null, $tpl_file=null) { if (($this->_isAsync() && !defined('ASA_ASYNC_REQUEST') && !isset($parse_params['no_ajax'])) || (!$this->_isAsync() && isset($parse_params['force_ajax']))) { // on AJAX request return $this->_getAsyncContent($asin, $tpl_file, $parse_params); } // get the item data /** * @var Asa_Service_Amazon_Item $item */ $item = $this->_getItem($asin); if ($item instanceof Asa_Service_Amazon_Item) { //$search = $this->_getTplPlaceholders($this->tpl_placeholder, true); $alignCss = 'float:left;'; if (isset($parse_params['align'])) { switch ($parse_params['align']) { case 'center': $alignCss = 'float:none;display:block;margin:0 auto 10px;'; break; case 'right': $alignCss = 'float:right;margin-left:15px;margin-right:0;'; break; } } // get the customer rating object $customerReviews = $this->getCustomerReviews($item); $lowestOfferPrice = null; $LowestUsedPrice = $item->getOffersLowestUsedPriceAmount(); $LowestNewPrice = $item->getOffersLowestNewPriceAmount(); if (!empty($LowestUsedPrice) && !empty($LowestNewPrice)) { $lowestOfferPrice = ($LowestUsedPrice < $LowestNewPrice) ? $LowestUsedPrice : $LowestNewPrice; $lowestOfferCurrency = ($LowestUsedPrice < $LowestNewPrice) ? $item->getOffersLowestUsedPriceCurrencyCode() : $item->getOffersLowestNewPriceCurrencyCode(); $lowestOfferFormattedPrice = ($LowestUsedPrice < $LowestNewPrice) ? $item->getOffersLowestUsedPriceFormattedPrice() : $item->getOffersLowestNewPriceFormattedPrice(); } else if (isset($LowestNewPrice)) { $lowestOfferPrice = $LowestNewPrice; $lowestOfferCurrency = $item->getOffersLowestNewPriceCurrencyCode(); $lowestOfferFormattedPrice = $item->getOffersLowestNewPriceFormattedPrice(); } else if (!empty($LowestUsedPrice)) { $lowestOfferPrice = $LowestUsedPrice; $lowestOfferCurrency = $item->getOffersLowestUsedPriceCurrencyCode(); $lowestOfferFormattedPrice = $item->getOffersLowestUsedPriceFormattedPrice(); } $lowestOfferPrice = $this->_formatPrice($lowestOfferPrice); $offerMainPriceAmount = $item->getOffersMainPriceAmount(); if (!empty($offerMainPriceAmount)) { $salePriceAmount = $item->getOffersSalePriceAmount(); if (!empty($salePriceAmount)) { // set main price to sale price $offerMainPriceAmount = $this->_formatPrice((string)$salePriceAmount); $offerMainPriceCurrencyCode = $item->getOffersSalePriceCurrencyCode(); $offerMainPriceFormatted = $item->getOffersSalePriceFormattedPrice(); } else { $offerMainPriceAmount = $this->_formatPrice((string)$offerMainPriceAmount); $offerMainPriceCurrencyCode = $item->getOffersMainPriceCurrencyCode(); $offerMainPriceFormatted = $item->getOffersMainPriceFormattedPrice(); } } else { // empty main price $emptyMainPriceText = get_option('_asa_replace_empty_main_price'); $offerMainPriceCurrencyCode = ''; if (!empty($emptyMainPriceText)) { $offerMainPriceFormatted = $emptyMainPriceText; $offerMainPriceAmount = $emptyMainPriceText; } else { $offerMainPriceFormatted = '--'; $offerMainPriceAmount = '--'; } } $totalOffers = 0; foreach (array($item->getOffersTotalNew(), $item->getOffersTotalUsed(), $item->getOffersTotalCollectible(), $item->getOffersTotalRefurbished()) as $totalValue) { $totalOffers += $totalValue; } $amazonPrice = $this->getAmazonPrice($item); $amazonPriceFormatted = $this->getAmazonPrice($item, true); $no_img_url = asa_plugins_url( 'img/no_image.gif', __FILE__ ); $features = $item->getFeatures(); if (is_array($features)) { $features = sprintf('', implode('
  • ', $features)); } $languages = $item->getLanguages(); if (is_array($languages)) { $langOutput = []; foreach ($languages as $lang) { $langOutputTmp = ''; if (!empty($lang['Name'])) { $langOutputTmp .= $lang['Name']; } if (!empty($lang['Type'])) { $langOutputTmp .= ' (' . esc_html($lang['Type']) . ')'; } array_push($langOutput, $langOutputTmp); } $languages = sprintf('', implode('
  • ', $langOutput)); } $placeholderStack = array( 'Features' => $features, 'ASIN' => $item->getAsin(), 'SmallImageUrl' => ($item->getSmallImageURL() != null) ? $item->getSmallImageURL() : $no_img_url, 'SmallImageWidth' => ($item->getSmallImageWidth() != null) ? $item->getSmallImageWidth() : 60, 'SmallImageHeight' => ($item->getSmallImageHeight() != null) ? $item->getSmallImageHeight() : 60, 'MediumImageUrl' => ($item->getMediumImageURL() != null) ? $item->getMediumImageURL() : $no_img_url, 'MediumImageWidth' => ($item->getMediumImageWidth() != null) ? $item->getMediumImageWidth() : 60, 'MediumImageHeight' => ($item->getMediumImageHeight() != null) ? $item->getMediumImageHeight() : 60, 'LargeImageUrl' => ($item->getLargeImageURL() != null) ? $item->getLargeImageURL() : $no_img_url, 'LargeImageWidth' => ($item->getLargeImageWidth() != null) ? $item->getLargeImageWidth() : 60, 'LargeImageHeight' => ($item->getLargeImageHeight() != null) ? $item->getLargeImageHeight() : 60, 'Label' => $item->getBrand(), 'Manufacturer' => $item->getManufacturer(), 'Studio' => $item->getManufacturer(), 'Title' => $item->getTitle(), 'AmazonUrl' => $item->getDetailPageURL(), 'AmazonLogoSmallUrl' => asa_plugins_url( 'img/amazon_' . (empty($this->_amazon_country_code) ? 'US' : $this->_amazon_country_code) .'_small.gif', __FILE__ ), 'AmazonLogoLargeUrl' => asa_plugins_url( 'img/amazon_' . (empty($this->_amazon_country_code) ? 'US' : $this->_amazon_country_code) .'.gif', __FILE__ ), 'DetailPageURL' => $item->getDetailPageURL(), 'ISBN' => $item->getISBN(), 'EAN' => $item->getEAN(), 'NumberOfPages' => $item->getPagesCount(), 'ReleaseDate' => $this->getLocalizedDate($item->getReleaseDate()), 'Binding' => $item->getBinding(), 'Author' => is_array($item->getAuthor()) ? implode(', ', $item->getAuthor()) : $item->getAuthor(), 'Creator' => $item->getCreator(), 'Edition' => $item->getEdition(), 'Director' => $item->getDirector(), 'Actors' => is_array($item->getActor()) ? implode(', ', $item->getActor()) : $item->getActor(), 'Format' => $item->getFormat(), 'CustomRating' => !empty($parse_params['custom_rating']) ? '' : '', 'ProductDescription' => $item->getEditorialReviews(), 'AmazonDescription' => $item->getEditorialReviews(), 'EditorialReview' => $item->getEditorialReviews(), 'Artist' => $item->getArtist(), 'Comment' => !empty($parse_params['comment']) ? $parse_params['comment'] : '', 'TrackingId' => $this->getTrackingId(), 'AmazonShopURL' => $this->getAmazonShopUrl(), 'Prime' => $item->getOfferIsPrime() ? 'AmazonPrime' : '', 'PrimePic' => $item->getOfferIsPrime() ? '' : '', 'Class' => !empty($parse_params['class']) ? $parse_params['class'] : '', 'AlignCss' => $alignCss, 'ProductReviewsURL' => $this->getAmazonShopUrl() . 'product-reviews/' . $item->getAsin() . '/&tag=' . $this->getTrackingId(), 'ProductGroup' => $item->getProductGroup(), 'Language' => $languages, 'AverageRating' => $customerReviews->averageRating, 'TotalReviews' => ($customerReviews->totalReviews != null) ? $customerReviews->totalReviews : 0, 'RatingStars' => ($customerReviews->imgTag != null) ? $customerReviews->imgTag : '', 'RatingStarsSrc' => ($customerReviews->imgSrc != null) ? $customerReviews->imgSrc : asa_plugins_url( 'img/stars-0.gif', __FILE__ ), 'LowestNewPrice' => empty($item->getOffersLowestNewPriceAmount()) ? '---' : $this->_formatPrice($item->getOffersLowestNewPriceAmount()), 'LowestNewOfferFormattedPrice' => str_replace('$', '\$', $item->getOffersLowestNewPriceFormattedPrice()), 'LowestUsedPrice' => empty($item->getOffersLowestUsedPriceAmount()) ? '---' : $this->_formatPrice($item->getOffersLowestUsedPriceAmount()), 'LowestUsedOfferFormattedPrice' => str_replace('$', '\$', $item->getOffersLowestUsedPriceFormattedPrice()), 'ListPriceFormatted' => empty($item->getOffersListPriceFormattedPrice()) ? '---' : str_replace('$', '\$', $item->getOffersListPriceFormattedPrice()), 'SalePriceAmount' => !empty($item->getOffersSalePriceAmount()) ? $item->getOffersSalePriceAmount() : '', 'SalePriceCurrencyCode' => $item->getOffersSalePriceCurrencyCode(), 'SalePriceFormatted' => $item->getOffersSalePriceFormattedPrice(), 'PercentageSaved' => $item->getOfferPercentageSaved(), 'AmazonPrice' => empty($amazonPrice) ? '---' : str_replace('$', '\$', $this->_formatPrice($amazonPrice)), 'AmazonPriceFormatted' => empty($amazonPriceFormatted) ? '---' : str_replace('$', '\$', $amazonPriceFormatted), 'OffersMainPriceAmount' => $offerMainPriceAmount, 'OffersMainPriceCurrencyCode' => $offerMainPriceCurrencyCode, 'OffersMainPriceFormattedPrice' => $offerMainPriceFormatted, 'LowestOfferPrice' => empty($lowestOfferPrice) ? '---' : $lowestOfferPrice, 'LowestOfferCurrency' => isset($lowestOfferCurrency) ? $lowestOfferCurrency : '', 'LowestOfferFormattedPrice' => isset($lowestOfferFormattedPrice) ? str_replace('$', '\$', $lowestOfferFormattedPrice) : '', 'Publisher' => '', // deprecated with PA API 5.0 'Platform' => '', // deprecated with PA API 5.0 'RunningTime' => '', // deprecated with PA API 5.0 'TotalOffers' => empty($totalOffers) ? '0' : $totalOffers, 'AmazonCurrency' => $item->getOffersMainPriceCurrencyCode(), 'AmazonAvailability' => $item->getOfferAvailabilityMessage(), 'text1' => isset($parse_params['text1']) ? $parse_params['text1'] : '', 'text2' => isset($parse_params['text2']) ? $parse_params['text2'] : '', ); $search = $this->_getTplPlaceholders(array_keys($placeholderStack), true); $replace = array_values($placeholderStack); $result = preg_replace($search, $replace, $tpl); // check for unresolved preg_match_all('/\{\$([a-z0-9\-\>]*)\}/i', $result, $matches); $unresolved = $matches[1]; if (count($unresolved) > 0) { $unresolved_names = $matches[1]; $unresolved_placeholders = $matches[0]; $unresolved_search = array(); $unresolved_replace = array(); for ($i=0; $i{$unresolved_names[$i]}; } else { $value = ''; } if (strstr($value, '$')) { $value = str_replace('$', '\$', $value); } $unresolved_search[] = $this->TplPlaceholderToRegex($unresolved_placeholders[$i]); $unresolved_replace[] = $value; } if (count($unresolved_search) > 0) { $result = preg_replace($unresolved_search, $unresolved_replace, $result); } } return do_shortcode($result); } elseif ($this->isErrorHandling() && $item instanceof Asa_Service_Amazon_Error && get_option('_asa_admin_error_frontend') && is_super_admin()) { // show admin error $errors = $item->getErrors(); $error = array_shift($errors); // load error_admin.htm $search = $this->_getTplPlaceholders(array('Error', 'Message', 'ASIN'), true); $replace = array($error['Code'], $error['Message'], $error['ASIN']); $output = preg_replace($search, $replace, $this->getTpl('error_admin')); echo esc_html_asa( $output ); } elseif ($item instanceof Asa_Service_Amazon_Error && get_option('_asa_use_error_tpl')) { $errors = $item->getErrors(); $error = array_shift($errors); // load error.htm $search = $this->_getTplPlaceholders(array('Error', 'Message', 'ASIN'), true); $replace = array($error['Code'], $error['Message'], $error['ASIN']); $output = preg_replace($search, $replace, $this->getTpl('error')); echo esc_html_asa( $output ); } elseif ($item === null && $this->isErrorHandling()) { // general error $message = __('Error while loading product data.', 'asa1'); $search = $this->_getTplPlaceholders(array('Error', 'Message', 'ASIN'), true); $replace = array('General error', $message, $asin); if (get_option('_asa_admin_error_frontend') && is_super_admin()) { $output = preg_replace($search, $replace, $this->getTpl('error_admin')); } else { $output = preg_replace($search, $replace, $this->getTpl('error')); } echo esc_html_asa( $output ); } else { return ''; } } /** * get item information from amazon webservice or cache * * @param string ASIN * @return Asa_Service_Amazon_Item */ protected function _getItem ($asin) { try { if (Asa_ItemBuffer::hasItem($asin)) { // check for prefetched or cached item $item = Asa_ItemBuffer::getItem($asin); } else { if ($this->cache == null || $this->_useCache() === false) { // if cache could not be initialized $item = $this->getItemLookup($asin); } else { // try to load item from cache if (asa_is_pa_api_5()) { require_once __DIR__ . '/lib/Asa/Service/Amazon/Item/PaApi5.php'; } $item = $this->cache->load($asin); if ($item === false || !($item instanceof Asa_Service_Amazon_Item)) { // item could not be loaded from cache or is not an item object //asa_debug('could not load from cache: ' . $asin); $item = $this->getItemLookup($asin); if (!($item instanceof Asa_Service_Amazon_Error)) { // put asin in cache if it is not an error response if ($this->isVariantCacheLifetime()) { $this->cache->save($item, $asin, array(), $this->getVariantCacheLifetime()); } else { $this->cache->save($item, $asin); } } } else { // asin could be loaded from cache // debug //asa_debug('loaded from cache: ' . $asin); //asa_debug($item); } } } return $item; } catch (Exception $e) { if ($this->isErrorHandling()) { $message = "Error while trying to load item data: %s\n\nASIN: %s"; $error = array(); $error['Message'] = sprintf($message, $e->getMessage(), $asin); $error['ASIN'] = $asin; $error['Code'] = 'General error'; $this->getLogger()->logError($error); } return null; } } /** * Public alias for self::_getItem($asin) * * @param $asin * @return object */ public function getItemObject($asin) { return $this->_getItem($asin); } /** * get item information from amazon webservice * * @param string ASIN * @return object AsaZend_Service_Amazon_Item object * @throws Asa_Exception */ public function getItemLookup ($asin) { if (Asa_ItemBuffer::hasItem($asin)) { return Asa_ItemBuffer::getItem($asin); } if ($this->amazon instanceof Asa_Service_Amazon_Interface) { $result = $this->amazon->itemLookup($asin, array( 'ResponseGroup' => 'ItemAttributes,Images,Offers,OfferListings,Reviews,EditorialReview,Tracks')); if ($result instanceof Asa_Service_Amazon_Error) { // handle errors if ($this->isErrorHandling()) { $this->getLogger()->logError($result); } } return $result; } else { throw new Asa_Exception('Could not connect to the API.'); } } /** * gets options from database options table */ protected function _getAmazonUserData () { $this->_amazon_api_key = get_option('_asa_amazon_api_key'); $this->_amazon_api_secret_key = base64_decode(get_option('_asa_amazon_api_secret_key')); $this->amazon_tracking_id = get_option('_asa_amazon_tracking_id'); $this->_amazon_api_connection_type = ifw_filter_scalar(get_option('_asa_api_connection_type'), array('http', 'https'), 'http'); $amazon_country_code = get_option('_asa_amazon_country_code'); if (!empty($amazon_country_code)) { $this->_amazon_country_code = $amazon_country_code; } } /** * Loads options */ protected function _loadOptions() { $_asa_use_flat_box_default = get_option('_asa_use_flat_box_default'); if (empty($_asa_use_flat_box_default)) { $this->_asa_use_flat_box_default = false; } else { $this->_asa_use_flat_box_default = true; } $_asa_parse_comments = get_option('_asa_parse_comments'); if (empty($_asa_parse_comments)) { $this->_parse_comments = false; } else { $this->_parse_comments = true; } $_asa_async_load = get_option('_asa_async_load'); if (empty($_asa_async_load)) { $this->_async_load = false; } else { $this->_async_load = true; } $_asa_use_amazon_price_only = get_option('_asa_use_amazon_price_only'); if (empty($_asa_use_amazon_price_only)) { $this->_asa_use_amazon_price_only = false; } else { $this->_asa_use_amazon_price_only = true; } } /** * generates right placeholder format and returns them as array * optionally prepared for use as regex * * @param bool true for regex prepared * @return array */ protected function _getTplPlaceholders ($placeholders, $regex=false) { $result = array(); foreach ($placeholders as $ph) { $result[] = $this->tpl_prefix . $ph . $this->tpl_postfix; } if ($regex == true) { return array_map(array($this, 'TplPlaceholderToRegex'), $result); } return $result; } /** * excapes placeholder for regex usage * * @param string placehoder * @return string escaped placeholder */ public function TplPlaceholderToRegex ($ph) { $search = array( '{', '}', '$', '-', '>' ); $replace = array( '\{', '\}', '\$', '\-', '\>' ); $ph = str_replace($search, $replace, $ph); return '/'. $ph .'/'; } /** * formats the price value from amazon webservice * * @param string price * @return mixed price (float, int for JP) */ protected function _formatPrice ($price) { if ($price === null || empty($price)) { return $price; } if ($this->_amazon_country_code != 'JP') { $price = (float) substr_replace($price, '.', (strlen($price)-2), -2); } else { $price = intval($price); } $dec_point = '.'; $thousands_sep = ','; if ($this->_amazon_country_code == 'DE' || $this->_amazon_country_code == 'FR') { // taken the amazon websites as example $dec_point = ','; $thousands_sep = '.'; } if ($this->_amazon_country_code != 'JP') { $price = number_format($price, 2, $dec_point, $thousands_sep); } else { $price = number_format($price, 0, $dec_point, $thousands_sep); } return $price; } /** * includes the css file for admin page */ public function getOptionsHead () { echo ''; } /** * Adds the meta link */ public function addMetaLink() { echo '
  • Powered by Affiliate Simple Assistent
  • '; } /** * @param $label * @param bool $type * @param bool $tpl * @return string */ public function getCollection ($label, $type=false, $tpl=false) { $collection_html = ''; $sql = ' SELECT a.collection_item_asin as asin FROM `'. $this->db->prefix . self::DB_COLL_ITEM .'` a INNER JOIN `'. $this->db->prefix . self::DB_COLL .'` b USING(collection_id) WHERE b.collection_label = "'. esc_sql($label) .'" ORDER by a.collection_item_timestamp DESC '; $result = $this->db->get_results($sql); if (count($result) == 0) { return $collection_html; } if ($tpl == false) { $tpl = 'collection_sidebar_default'; } if ($type == false) { $type = 'all'; } $tpl_src = $this->getTpl($tpl); switch ($type) { case 'latest': $collection_html .= $this->parseTpl($result[0]->asin, $tpl_src, null, $tpl); break; case 'all': default: foreach ($result as $row) { $collection_html .= $this->parseTpl($row->asin, $tpl_src, null, $tpl); } } return $collection_html; } /** * @param $asin * @param null $tpl * @param array $options * @return string */ public function getItem ($asin, $tpl = null, $options = array()) { $item_html = ''; if (empty($tpl)) { $tpl = 'sidebar_item'; } $tpl_src = $this->getTpl($tpl); $item_html .= $this->parseTpl(trim($asin), $tpl_src, $options, $tpl); return $item_html; } /** * @return bool */ protected function _isAsync() { return $this->_async_load === true; } /** * @param $asin * @param $tpl * @param $parse_params * @param $match * @return string */ protected function _getAsyncContent($asin, $tpl, $parse_params) { $containerID = 'asa-' . md5(uniqid(mt_rand())); if ($this->getLogger()->isBlock()) { $parse_params['asa-block-errorlog'] = true; } if (isset($parse_params['force_ajax'])) { unset($parse_params['force_ajax']); } $params = str_replace("'", "\'", json_encode($parse_params)); $nonce = wp_create_nonce('amazonsimpleadmin'); $ajax_url = admin_url( 'admin-ajax.php' ); if (empty($tpl)) { $tpl = $this->getDefaultTplName(); } $output = ''; $loadingAniHtml = ''; $loadingAniStyle = get_option('_asa_ajax_css_ani'); if (!empty($loadingAniStyle)) { require_once ASA_LIB_DIR . '/Asa/CssLoading.php'; $loadingAniHtml = Asa_CssLoading::getInstance()->getHtml($loadingAniStyle); $loadingAniCss = Asa_CssLoading::getInstance()->getCss($loadingAniStyle); if (!empty($loadingAniCss)) { $output .= $this->getCssStyleTag($loadingAniCss); } } $output .= '
    '. $loadingAniHtml .'
    '; $output .= ""; return $output; } /** * @param Asa_Service_Amazon_Item $item * @param bool $formatted * @return mixed|null */ public function getAmazonPrice($item, $formatted=false) { $result = null; if ($item instanceof Asa_Service_Amazon_Item) { $salePriceAmount = $item->getOffersSalePriceAmount(); $mainPriceAmount = $item->getOffersMainPriceAmount(); $lowestNewPriceAmount = $item->getOffersLowestNewPriceAmount(); $lowestUsedPriceAmount = $item->getOffersLowestUsedPriceAmount(); if (!empty($salePriceAmount)) { if ($formatted) { $result = $item->getOffersSalePriceFormattedPrice(); } else { $result = $salePriceAmount; } } elseif (!empty($mainPriceAmount)) { if ($formatted) { $result = $item->getOffersMainPriceFormattedPrice(); } else { $result = $mainPriceAmount; } } elseif (!empty($lowestNewPriceAmount)) { if ($formatted) { $result = $item->getOffersLowestNewPriceFormattedPrice(); } else { $result = $lowestNewPriceAmount; } } elseif (!empty($lowestUsedPriceAmount)) { if ($formatted) { $result = $item->getOffersLowestUsedPriceFormattedPrice(); } else { $result = $lowestUsedPriceAmount; } } // if (isset($item->Offers->SalePriceAmount) && $item->Offers->SalePriceAmount != null) { // if ($formatted === false) { // $result = $this->_formatPrice($item->Offers->SalePriceAmount); // } else { // $result = $item->Offers->SalePriceFormatted; // } // } elseif (isset($item->Offers->Offers[0]->Price) && $item->Offers->Offers[0]->Price != null) { // if ($formatted === false) { // $result = $this->_formatPrice($item->Offers->Offers[0]->Price); // } else { // $result = $item->Offers->Offers[0]->FormattedPrice; // } // } elseif (isset($item->Offers->LowestNewPrice) && !empty($item->Offers->LowestNewPrice)) { // if ($formatted === false) { // $result = $this->_formatPrice($item->Offers->LowestNewPrice); // } else { // $result = $item->Offers->LowestNewPriceFormattedPrice; // } // } elseif (isset($item->Offers->LowestUsedPrice) && !empty($item->Offers->LowestUsedPrice)) { // if ($formatted === false) { // $result = $this->_formatPrice($item->Offers->LowestUsedPrice); // } else { // $result = $item->Offers->LowestUsedPriceFormattedPrice; // } // } } return $result; } /** * Retrieve the customer reviews object * * @param Asa_Service_Amazon_Item $item * @param bool $uncached * @return AsaCustomerReviews|null */ public function getCustomerReviews($item, $uncached = false) { require_once(dirname(__FILE__) . '/AsaCustomerReviews.php'); $iframeUrl = isset($item->CustomerReviewsIFrameURL) ? $item->CustomerReviewsIFrameURL : ''; if ($uncached) { $cache = null; } else { $cache = $this->cache; } $reviews = new AsaCustomerReviews($item->getAsin(), $iframeUrl, $cache); if (get_option('_asa_get_rating_alternative')) { $reviews->setFindMethod(AsaCustomerReviews::FIND_METHOD_DOM); } $reviews->load(); return $reviews; } /** * @param Asa_Service_Amazon_Item $item * @return string */ public function getItemUrl($item) { if (get_option('_asa_use_short_amazon_links')) { $url = sprintf($this->amazon_url[$this->_amazon_country_code], $item->getAsin(), $this->amazon_tracking_id); } else { $url = $item->getDetailPageURL(); } return $this->_handleItemUrl($url); } /** * @param $url * @return string */ protected function _handleItemUrl($url) { $url = urldecode($url); $url = strtr($url, array( '%' => '%25' )); return $url; } /** * @param $date * @return bool|string */ public function getLocalizedDate($date) { if (!empty($date)) { $dt = new DateTime($date); $format = get_option('date_format'); $date = date($format, $dt->format('U')); } return $date; } /** * @return string */ public function getCountryCode() { return $this->_amazon_country_code; } /** * @return mixed */ public function getAmazonShopUrl() { if ($this->amazon_shop_url == null) { $url = $this->amazon_url[$this->getCountryCode()]; $this->amazon_shop_url = current(explode('exec', $url)); } return $this->amazon_shop_url; } /** * @return mixed */ public function getTrackingId() { return $this->amazon_tracking_id; } /** * @return bool */ protected function _useCache() { if ((int)get_option('_asa_cache_skip_on_admin') === 1 && current_user_can('install_plugins')) { return false; } return true; } /** * @return AsaLogger */ public function getLogger() { require_once dirname(__FILE__) . '/AsaLogger.php'; return AsaLogger::getInstance($this->db); } /** * @param $plugin_data * @param $meta_data */ public function handleUpdateMessage($plugin_data = null, $meta_data = null) { printf('
    %s %s.
    ', __('Remember to backup your custom template files before updating!', 'asa1'), __('Read more', 'asa1') ); } /** * @param $options * @param string $content * @param string $code * @return string */ public function handleShortcodeAsa($options, $content = '', $code = '') { $output = ''; $asin = $content; if (!empty($asin)) { $options = array_map('asa_sanitize_shortcode_option_value', asa_var_to_array($options)); if (isset($options['comment'])) { $options['comment'] = html_entity_decode($options['comment']); } if (isset($options['class'])) { $options['class'] = html_entity_decode($options['class']); } $tplName = asa_get_tpl_name_from_options($options); $tplSrc = $this->getTpl($tplName, true); $output = $this->parseTpl($asin, $tplSrc, $options, $tplName); } return $output; } /** * @param $options * @param string $content * @param string $code * @return string */ public function handleShortcodeAsaCollection($options, $content = '', $code = '') { $output = ''; require_once(dirname(__FILE__) . '/AsaCollection.php'); $this->collection = new AsaCollection($this->db); $collection_id = $this->collection->getId(trim($content)); $coll_items = $this->collection->getItems($collection_id); if (count($coll_items) == 0) { // not items found, return empty output return $output; } $options = array_map('asa_sanitize_shortcode_option_value', asa_var_to_array($options)); $tplName = asa_get_tpl_name_from_options($options); // random if (isset($options['type'])) { if ($options['type'] == 'random') { shuffle($coll_items); } elseif ($options['type'] == 'latest') { $coll_items = array_slice($coll_items, 0, 1); } } // limit results if (isset($options['limit']) && is_numeric($options['limit'])) { $limit = (int)$options['limit']; } elseif (isset($options['items']) && is_numeric($options['items'])) { $limit = (int)$options['items']; } if (isset($limit) && $limit > 0) { $coll_items = array_slice($coll_items, 0, $limit); } $tplSrc = $this->getTpl($tplName, true, true); if (Asa_Util_Buffer::exists($tplName, 'tpl_css')) { $output .= $this->getCssStyleTag(Asa_Util_Buffer::get($tplName, 'tpl_css')); } elseif (Asa_Util_Buffer::exists($this->getDefaultTplName(), 'tpl_css')) { $output .= $this->getCssStyleTag(Asa_Util_Buffer::get($this->getDefaultTplName(), 'tpl_css')); } $coll_items_counter = 1; foreach ($coll_items as $row) { $output .= $this->parseTpl($row->collection_item_asin, $tplSrc, $options, $tplName); $coll_items_counter++; if (isset($coll_items_limit) && $coll_items_counter > $coll_items_limit) { break; } } return $output; } protected function _checkPaApiVersion() { if (isset($_GET['page']) && strpos($_GET['page'], 'amazonsimpleadmin') === 0 && !asa_is_pa_api_5()) { add_action('admin_notices', [$this, 'showPaApi5Notice']); } } public function showPaApi5Notice() { $class = 'notice notice-error'; $message = sprintf('%s! %s ', __('Action required', 'asa1'), __('AmazonSimpleAdmin is not yet set up for PA API 5.0. This is mandatory from March 9, 2020!', 'asa1')) . ' ' . sprintf('%s', 'https://www.wp-amazon-plugin.com/2019/15403/important-upcoming-asa2-update-amazon-pa-api-version-4-will-no-longer-be-supported-from-november-2019/', __('More info', 'asa1')) . '
    ' . sprintf(__('If the requirements are met, you can switch to PA API version 5.0 in the Setup.', 'asa1'), ' href="'. admin_url('options-general.php?page=amazonsimpleadmin%2Famazonsimpleadmin.php') .'"'); printf('

    %2$s

    ', $class, $message); } public function doCommentShortcode($content) { // Escape [ and ] inside HTML tags so the shortcode regex below cannot match a // shortcode delimiter that starts inside an attribute value (e.g. title="[asa ...]") // and closes outside the element. Without this, a crafted comment can make the // regex splice shortcode output into the middle of an open HTML attribute, letting // the browser reinterpret trailing comment text as new tag attributes (mutation XSS). $content = preg_replace_callback( '/<[^>]+>/s', function ($m) { return str_replace(['[', ']'], ['[', ']'], $m[0]); }, $content ); $pattern = '/\[asa(?:\s+[^]]*)?\](.*?)\[\/asa\]/s'; $result = preg_replace_callback( $pattern, function ($match) { return do_shortcode('[asa' . (isset($match[1]) ? ']' . $match[1] . '[/asa]' : ']')); }, $content ); // Defense in depth: strip any tags/attributes (including event handlers) that // could still slip through, regardless of how they were constructed above. return wp_kses_post($result); } } global $wpdb; $asa = new AmazonSimpleAdmin($wpdb); include_once ASA_INCLUDE_DIR . 'asa_pointers.php'; include_once ASA_INCLUDE_DIR . 'asa_php_functions.php'; include_once ASA_INCLUDE_DIR . 'asa_ajax_callback.php'; include_once ASA_INCLUDE_DIR . 'asa_actions.php';