'https://www.amazon.com.au/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', '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', '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', 'CN' => 'https://www.amazon.cn/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 = 'http'; /** * product preview status * @var bool */ protected $_product_preview = false; /** * @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 = strip_tags($_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', 'do_shortcode'); } if ($this->_product_preview == true) { add_action('wp_footer', array($this, 'addProductPreview')); } 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->_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_amazon_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 */ public function isDebug() { return get_option('_asa_debug'); } /** * @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('AmazonSimpleAdmin', 'AmazonSimpleAdmin', '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 '

AmazonSimpleAdmin (ASA1) '. self::VERSION .'

'; $this->_displayPreDispatcher($this->task); echo $this->getTabMenu($this->task); #echo '
'; 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 $nav; } protected function _displayPreDispatcher ($task) { switch ($task) { case 'options': if (count($_POST) > 0 && isset($_POST['info_update'])) { $options = array( '_asa_product_preview', '_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_product_preview', $_asa_product_preview); 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 = strip_tags($_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'], 'asa1_manage_collection')) { $this->error['manage_collection'] = __('Invalid access', 'asa1'); } else { $delete_items = $_POST['delete_collection_item']; if (count($delete_items) > 0) { foreach ($delete_items as $item) { $this->collection->deleteAsin($item); } } } } if (isset($_POST['submit_import'])) { /** * Import collection */ if (!wp_verify_nonce($_POST['nonce'], 'asa1_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'], 'asa1_add_to_collection')) { $this->error['submit_new_asin'] = __('Invalid access', 'asa1'); } else { $asin = strip_tags($_POST['new_asin']); $collection_id = strip_tags($_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->Title, $this->collection->getLabel($collection_id) ); } } } } else if (isset($_POST['submit_manage_collection'])) { $collection_id = strip_tags($_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'])) { $item_id = strip_tags($_GET['update_timestamp']); $this->collection->updateItemTimestamp($item_id); $collection_id = strip_tags($_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'], 'asa1_manage_collection')) { $this->error['manage_collection'] = __('Invalid access', 'asa1'); } else { $collection_id = strip_tags($_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'], 'asa1_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'])) { $this->collection->initDB(); } echo $this->_getSubMenu($task); if ($this->db->get_var("SHOW TABLES LIKE '". $this->db->prefix ."asa_collection%'") === null) { $this->_displayCollectionsSetup(); } else { $this->_displayCollectionsPage($params); } 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 'cache': if (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 if (count($_POST) > 0) { 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'])) { if (!wp_verify_nonce($_POST['nonce'], 'asa_setup')) { $this->_displayError(__('Invalid access', 'asa1')); } else { $_asa_amazon_api_key = sanitize_text_field(strip_tags(trim($_POST['_asa_amazon_api_key']))); $_asa_amazon_api_secret_key = sanitize_text_field(base64_encode(strip_tags(trim($_POST['_asa_amazon_api_secret_key'])))); $_asa_amazon_tracking_id = sanitize_text_field(strip_tags(trim($_POST['_asa_amazon_tracking_id']))); $_asa_api_connection_type = sanitize_text_field(strip_tags(trim($_POST['_asa_api_connection_type']))); $_asa_api_connection_type = ifw_filter_scalar($_asa_api_connection_type, array('http', 'https'), 'http'); update_option('_asa_amazon_api_key', $_asa_amazon_api_key); update_option('_asa_amazon_api_secret_key', $_asa_amazon_api_secret_key); update_option('_asa_amazon_tracking_id', $_asa_amazon_tracking_id); update_option('_asa_api_connection_type', $_asa_api_connection_type); if (isset($_POST['_asa_amazon_country_code'])) { $_asa_amazon_country_code = strip_tags($_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); } $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"'; } if (isset($item->Title)) { $title = str_replace("'", "\'", $item->Title); } else { $title = __('Invalid item', 'asa1'); } $table .= ''; $table .= ''; if (isset($item->SmallImage)) { $thumbnail = $item->SmallImage->Url->getUri(); } else { $thumbnail = asa_plugins_url( 'img/no_image.gif', __FILE__ ); } if (!isset($item->Offers->Offers)) { $price = '---'; } else { $price = $item->Offers->Offers[0]->FormattedPrice; } $table .= ''; $table .= ''; $table .= ''; $table .= ''; $table .= ''; $table .= ''; $table .= ''; if (isset($item->SmallImage->Width)) { $thumb_max_width[] = $item->SmallImage->Width; } } 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 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 '
  • '. $template .'
  • '; } ?>
_displaySidebar(); ?>
request('GET'); if ($response->isSuccessful()) { echo $response->getBody(); } else { echo '

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'])) { $asin = esc_attr($_POST['asin']); if (isset($_POST['tpl'])) { $tpl = esc_attr($_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 $this->getItem($asin, $tpl); } elseif ($mode == 'ratings') { $item = $this->_getItem($asin); // get the customer rating object $customerReviews = $this->getCustomerReviews($item, true); if ($customerReviews->isSuccess()) { echo '

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

'; echo '

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

'; echo '

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

'; echo '

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

'; echo $customerReviews->imgTag; } else { echo '

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

'; echo '

Error message: ' . $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(); ?>

_loadOptions(); ?>


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



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

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


:

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

/>

/>


:

/>

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') . ': ' . $this->_debugger->getWriter()->getFilename(); ?> )
_debugger)) echo nl2br(htmlspecialchars($this->_debugger->read())); ?>

/>

/>


/>

/>

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="http://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="http://docs.getasa2.com/caching.html" target="_blank"'); ?>

task == 'usage'): ?>

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


  • Templates Demo Page.', 'asa1'), ' href="https://www.asa2-demo.de/templates/" target="_blank"'); ?>
  • ()
  • ()
  • ()
  • (...)
  • ()
  • (Accelerated Mobile Pages)

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 ); } $_asa_status = false; $this->_getAmazonUserData(); $connectionTestResult = $this->testConnection(); if ($connectionTestResult['success'] === true) { $_asa_status = true; } else { $_asa_error = $connectionTestResult['message']; } ?>

'. __('Error', 'asa1') .': '. $_asa_error; echo '
'. __('Get help at', 'asa1') .' https://www.wp-amazon-plugin.com/faq/#setup_errors

'; echo '

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

'; } ?>

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



(: US)



:

_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') .': '. $error .'

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

'. __('Success', 'asa1') .': '. $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; } /** * 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')) { $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 $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 $item = $this->_getItem($asin); if ($item instanceof AsaZend_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; } } $lowestOfferPrice = null; // get the customer rating object $customerReviews = $this->getCustomerReviews($item); if (isset($item->Offers->LowestUsedPrice) && isset($item->Offers->LowestNewPrice)) { $lowestOfferPrice = ($item->Offers->LowestUsedPrice < $item->Offers->LowestNewPrice) ? $item->Offers->LowestUsedPrice : $item->Offers->LowestNewPrice; $lowestOfferCurrency = ($item->Offers->LowestUsedPrice < $item->Offers->LowestNewPrice) ? $item->Offers->LowestUsedPriceCurrency : $item->Offers->LowestNewPriceCurrency; $lowestOfferFormattedPrice = ($item->Offers->LowestUsedPrice < $item->Offers->LowestNewPrice) ? $item->Offers->LowestUsedPriceFormattedPrice : $item->Offers->LowestNewPriceFormattedPrice; } else if (isset($item->Offers->LowestNewPrice)) { $lowestOfferPrice = $item->Offers->LowestNewPrice; $lowestOfferCurrency = $item->Offers->LowestNewPriceCurrency; $lowestOfferFormattedPrice = $item->Offers->LowestNewPriceFormattedPrice; } else if (isset($item->Offers->LowestUsedPrice)) { $lowestOfferPrice = $item->Offers->LowestUsedPrice; $lowestOfferCurrency = $item->Offers->LowestUsedPriceCurrency; $lowestOfferFormattedPrice = $item->Offers->LowestUsedPriceFormattedPrice; } $lowestOfferPrice = $this->_formatPrice($lowestOfferPrice); $lowestNewPrice = isset($item->Offers->LowestNewPrice) ? $this->_formatPrice($item->Offers->LowestNewPrice) : ''; $lowestNewOfferFormattedPrice = isset($item->Offers->LowestNewPriceFormattedPrice) ? $item->Offers->LowestNewPriceFormattedPrice : ''; $lowestUsedPrice = isset($item->Offers->LowestUsedPrice) ? $this->_formatPrice($item->Offers->LowestUsedPrice) : ''; $lowestUsedOfferFormattedPrice = isset($item->Offers->LowestUsedPriceFormattedPrice) ? $item->Offers->LowestUsedPriceFormattedPrice : ''; $amazonPrice = $this->getAmazonPrice($item); $amazonPriceFormatted = $this->getAmazonPrice($item, true); if (isset($item->Offers->Offers[0]->Price) && !empty($item->Offers->Offers[0]->Price)) { if (isset($item->Offers->SalePriceAmount)) { // set main price to sale price $offerMainPriceAmount = $this->_formatPrice((string)$item->Offers->SalePriceAmount); $offerMainPriceCurrencyCode = $item->Offers->SalePriceCurrencyCode; $offerMainPriceFormatted = $item->Offers->SalePriceFormatted; } else { $offerMainPriceAmount = $this->_formatPrice((string)$item->Offers->Offers[0]->Price); $offerMainPriceCurrencyCode = (string)$item->Offers->Offers[0]->CurrencyCode; $offerMainPriceFormatted = (string)$item->Offers->Offers[0]->FormattedPrice; } } else { // empty main price $emptyMainPriceText = get_option('_asa_replace_empty_main_price'); $offerMainPriceCurrencyCode = ''; if (!empty($emptyMainPriceText)) { $offerMainPriceFormatted = $emptyMainPriceText; $offerMainPriceAmount = $emptyMainPriceText; } else { $offerMainPriceFormatted = '--'; $offerMainPriceAmount = '--'; } } $listPriceFormatted = $item->ListPriceFormatted; $totalOffers = 0; foreach (array($item->Offers->TotalNew, $item->Offers->TotalUsed, $item->Offers->TotalCollectible, $item->Offers->TotalRefurbished) as $totalValue) { $totalOffers += $totalValue; } $platform = $item->Platform; if (is_array($platform)) { $platform = implode(', ', $platform); } $percentageSaved = $item->PercentageSaved; $no_img_url = asa_plugins_url( 'img/no_image.gif', __FILE__ ); $placeholderStack = array( 'ASIN' => $item->ASIN, 'SmallImageUrl' => ($item->SmallImage != null) ? $item->SmallImage->Url->getUri() : $no_img_url, 'SmallImageWidth' => ($item->SmallImage != null) ? $item->SmallImage->Width : 60, 'SmallImageHeight' => ($item->SmallImage != null) ? $item->SmallImage->Height : 60, 'MediumImageUrl' => ($item->MediumImage != null) ? $item->MediumImage->Url->getUri() : $no_img_url, 'MediumImageWidth' => ($item->MediumImage != null) ? $item->MediumImage->Width : 60, 'MediumImageHeight' => ($item->MediumImage != null) ? $item->MediumImage->Height : 60, 'LargeImageUrl' => ($item->LargeImage != null) ? $item->LargeImage->Url->getUri() : $no_img_url, 'LargeImageWidth' => ($item->LargeImage != null) ? $item->LargeImage->Width : 60, 'LargeImageHeight' => ($item->LargeImage != null) ? $item->LargeImage->Height : 60, 'Label' => $item->Label, 'Manufacturer' => $item->Manufacturer, 'Publisher' => $item->Publisher, 'Studio' => $item->Studio, 'Title' => $item->Title, 'AmazonUrl' => $this->getItemUrl($item), 'TotalOffers' => empty($totalOffers) ? '0' : $totalOffers, 'LowestOfferPrice' => empty($lowestOfferPrice) ? '---' : $lowestOfferPrice, 'LowestOfferPrice' => isset($lowestOfferCurrency) ? $lowestOfferCurrency : '', 'LowestOfferFormattedPrice' => isset($lowestOfferFormattedPrice) ? str_replace('$', '\$', $lowestOfferFormattedPrice) : '', 'LowestNewPrice' => empty($lowestNewPrice) ? '---' : $lowestNewPrice, 'LowestNewOfferFormattedPrice' => str_replace('$', '\$', $lowestNewOfferFormattedPrice), 'LowestUsedPrice' => empty($lowestUsedPrice) ? '---' : $lowestUsedPrice, 'LowestUsedOfferFormattedPrice' => str_replace('$', '\$', $lowestUsedOfferFormattedPrice), 'AmazonPrice' => empty($amazonPrice) ? '---' : str_replace('$', '\$', $amazonPrice), 'AmazonPriceFormatted' => empty($amazonPriceFormatted) ? '---' : str_replace('$', '\$', $amazonPriceFormatted), 'ListPriceFormatted' => empty($listPriceFormatted) ? '---' : str_replace('$', '\$', $listPriceFormatted), 'AmazonCurrency' => isset($item->Offers->Offers[0]->CurrencyCode) ? $item->Offers->Offers[0]->CurrencyCode : '', 'AmazonAvailability' => isset($item->Offers->Offers[0]->Availability) ? $item->Offers->Offers[0]->Availability : '', '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' => $this->_handleItemUrl($item->DetailPageURL), 'Platform' => $platform, 'ISBN' => $item->ISBN, 'EAN' => $item->EAN, 'NumberOfPages' => $item->NumberOfPages, 'ReleaseDate' => $this->getLocalizedDate($item->ReleaseDate), 'Binding' => $item->Binding, 'Author' => is_array($item->Author) ? implode(', ', $item->Author) : $item->Author, 'Creator' => is_array($item->Creator) ? implode(', ', $item->Creator) : $item->Creator, 'Edition' => $item->Edition, '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__ ), 'Director' => is_array($item->Director) ? implode(', ', $item->Director) : $item->Director, 'Actors' => is_array($item->Actor) ? implode(', ', $item->Actor) : $item->Actor, 'RunningTime' => $item->RunningTime, 'Format' => is_array($item->Format) ? implode(', ', $item->Format) : $item->Format, 'CustomRating' => !empty($parse_params['custom_rating']) ? '' : '', 'ProductDescription' => isset($item->EditorialReviews[0]) ? $item->EditorialReviews[0]->Content : '', 'AmazonDescription' => !empty($item->EditorialReviews[1]) ? $item->EditorialReviews[1]->Content : '', 'Artist' => is_array($item->Artist) ? implode(', ', $item->Artist) : $item->Artist, 'Comment' => !empty($parse_params['comment']) ? $parse_params['comment'] : '', 'PercentageSaved' => !empty($percentageSaved) ? $percentageSaved : 0, 'Prime' => !empty($item->Offers->Offers[0]->IsEligibleForSuperSaverShipping) ? 'AmazonPrime' : '', 'PrimePic' => !empty($item->Offers->Offers[0]->IsEligibleForSuperSaverShipping) ? '' : '', 'ProductReviewsURL' => $this->getAmazonShopUrl() . 'product-reviews/' . $item->ASIN . '/&tag=' . $this->getTrackingId(), 'TrackingId' => $this->getTrackingId(), 'AmazonShopURL' => $this->getAmazonShopUrl(), 'SalePriceAmount' => isset($item->Offers->SalePriceAmount) ? $this->_formatPrice($item->Offers->SalePriceAmount) : '', 'SalePriceCurrencyCode' => isset($item->Offers->SalePriceCurrencyCode) ? $item->Offers->SalePriceCurrencyCode : '', 'SalePriceFormatted' => isset($item->Offers->SalePriceFormatted) ? $item->Offers->SalePriceFormatted : '', 'Class' => !empty($parse_params['class']) ? $parse_params['class'] : '', 'OffersMainPriceAmount' => $offerMainPriceAmount, 'OffersMainPriceCurrencyCode' => $offerMainPriceCurrencyCode, 'OffersMainPriceFormattedPrice' => $offerMainPriceFormatted, 'AlignCss' => $alignCss // align ); $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 $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 $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 $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 $output; } else { return ''; } } /** * get item information from amazon webservice or cache * * @param string ASIN * @return object AsaZend_Service_Amazon_Item object */ 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 $item = $this->cache->load($asin); if ($item === false || !($item instanceof AsaZend_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_product_preview = get_option('_asa_product_preview'); if (empty($_asa_product_preview)) { $this->_product_preview = false; } else { $this->_product_preview = true; } $_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 AmazonSimpleAdmin
  • '; } /** * enabled amazon product preview layers */ public function addProductPreview () { $js = ''; $js .= ''; $search = array( '/\[domain\]/', '/\[tag\]/', '/\[o_id\]/', ); switch ($this->_amazon_country_code) { case 'DE': $replace = array( 'de', (!empty($this->amazon_tracking_id) ? $this->amazon_tracking_id : ''), '3' ); $js = preg_replace($search, $replace, $js); break; case 'UK': $replace = array( 'co.uk', (!empty($this->amazon_tracking_id) ? $this->amazon_tracking_id : ''), '2' ); $js = preg_replace($search, $replace, $js); break; case 'US': case false: $replace = array( 'com', (!empty($this->amazon_tracking_id) ? $this->amazon_tracking_id : ''), '1' ); $js = preg_replace($search, $replace, $js); break; default: $js = ''; } echo $js . "\n"; } /** * @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 $item * @param bool $formatted * @return mixed|null */ public function getAmazonPrice($item, $formatted=false) { $result = null; 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 $item * @param bool $uncached * @return AsaCustomerReviews|null */ public function getCustomerReviews($item, $uncached = false) { require_once(dirname(__FILE__) . '/AsaCustomerReviews.php'); $iframeUrl = ($item->CustomerReviewsIFrameURL != null) ? $item->CustomerReviewsIFrameURL : ''; if ($uncached) { $cache = null; } else { $cache = $this->cache; } $reviews = new AsaCustomerReviews($item->ASIN, $iframeUrl, $cache); if (get_option('_asa_get_rating_alternative')) { $reviews->setFindMethod(AsaCustomerReviews::FIND_METHOD_DOM); } $reviews->load(); return $reviews; } /** * @param $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->ASIN, $this->amazon_tracking_id); } else { $url = $item->DetailPageURL; } 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; } } 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';