&text=] --> inserts link to amazon item
[amazon cat=&last=] --> inserts table of random items
Layout:
amazon_container - Encloses whole wishlist.
amazon_prod - Encloses each list item.
amazon_img_container - Encloses the item thumbnail (link+img)
amazon_pic - Class of the item thumbnail IMG element
amazon_text_container - Encloses the item description (Title paragraphs+link + Details paragraphs)
amazon_details - Encloses the item details part of the description
amazon_price - Spans the item's formatted price.
*/
/*******************************************************************************************************
To serve a page containing amazon links the plugin performs the following:
* Queue the Amazon javascript and styles
* Search through the content and widget text for Amazon links, for each one:
* Parse arguments (get_options_list(>cached), get_country_data (>cached), get_options(>cached))
* Make Links:
* get_templates (>cached)
* for each ASIN:
* (if live) perform itemLookup
* parse results:
* Get local Info:
* get channel
* get country [ip2n lookup >cached]
* get country data
* return country specific data
* For each ASIN:
* Check for local images
* Make links * 5:
* get URL (get local info)
* get local info
* Fill in template
* If 'multinational' link found when doing the above then:
* Return all channels and user channels(>cached), create the javascript for the multinational popup.
*******************************************************************************************************/
define (TIMING, False);
require_once('include/displayForm.php');
//require_once('include/translate.php');
if (!class_exists('AmazonWishlist_ip2nation'))
include_once ( 'include/ip2nation.php');
if (!class_exists('AmazonLinkSearch'))
include_once ( 'include/amazonSearch.php');
if (!class_exists('AmazonWishlist_For_WordPress')) {
class AmazonWishlist_For_WordPress {
/*****************************************************************************************/
/// Settings:
/*****************************************************************************************/
// String to insert into Posts to indicate where to insert the amazon items
var $cache_table = 'amazon_link_cache';
var $refs_table = 'amazon_link_refs';
var $option_version= 6;
var $plugin_version= '3.0.4';
var $optionName = 'AmazonLinkOptions';
var $user_options = 'amazonlinkoptions';
var $templatesName = 'AmazonLinkTemplates';
var $channels_name = 'AmazonLinkChannels';
var $menu_slug = 'amazon-link-settings';
var $plugin_home = 'http://www.houseindorset.co.uk/plugins/amazon-link/';
var $multi_id = 0;
var $scripts_done = False;
var $tags = array();
/*****************************************************************************************/
// Constructor for the Plugin
function AmazonWishlist_For_WordPress() {
$this->__construct();
}
function __construct() {
$this->URLRoot = plugins_url("", __FILE__);
$this->icon = plugins_url('images/amazon-icon.png', __FILE__);
$this->filename = __FILE__;
$this->base_name = plugin_basename( __FILE__ );
$this->plugin_dir = dirname( $this->base_name );
$this->extras_dir = WP_PLUGIN_DIR . '/'. $this->plugin_dir. '/extras/';
$this->ip2n = new AmazonWishlist_ip2nation;
// Frontend & Backend Related
register_activation_hook(__FILE__, array($this, 'install')); // To perform options installation
register_uninstall_hook(__FILE__, array($this, 'uninstall')); // To perform options removal
add_action('init', array($this, 'init')); // Load i18n and initialise translatable vars
add_filter('the_content', array($this, 'content_filter'),15); // Process the content
add_filter('widget_text', array($this, 'widget_filter'), 16); // Filter widget text (after the content?)
// Backend only
add_action('admin_menu', array($this, 'admin_menu')); // Add options page and page/post edit hooks
}
/*****************************************************************************************/
// Functions for the above hooks
// On activation of plugin - used to create default settings
function install() {
$opts = $this->getOptions();
$this->saveOptions($opts);
}
// On removal of plugin - used to delete all related database entries
function uninstall() {
$opts = $this->getOptions();
if ($opts['full_uninstall']) {
$this->cache_remove();
$this->ip2nation->uninstall();
$this->delete_options();
}
}
// On wordpress initialisation - load text domain and register styles & scripts
function init() {
/* load localisation */
load_plugin_textdomain('amazon-link', $this->plugin_dir . '/i18n', $this->plugin_dir . '/i18n');
// Initialise dependent classes
$this->form = new AmazonWishlist_Options;
$this->form->init($this); // Need to register form styles
$this->search = new AmazonLinkSearch;
$this->search->init($this); // Need to register scripts & ajax callbacks
$this->ip2n->init($this); // ip2nation needed on Frontend
// Register our styles and scripts
$script = plugins_url("amazon.js", __FILE__);
$edit_script = plugins_url("postedit.js", __FILE__);
$admin_script = plugins_url("include/amazon-admin.js", __FILE__);
$multi_script = plugins_url("include/amazon-multi.js", __FILE__);
// Allow the user to override our default styles.
if (file_exists(dirname (__FILE__).'/user_styles.css')) {
$stylesheet = plugins_url("user_styles.css", __FILE__);
} else {
$stylesheet = plugins_url("Amazon.css", __FILE__);
}
wp_register_style ('amazon-link-style', $stylesheet, false, $this->plugin_version);
wp_register_script('amazon-link-script', $script, false, $this->plugin_version);
wp_register_script('amazon-link-multi-script', $multi_script, false, $this->plugin_version);
wp_register_script('amazon-link-edit-script', $edit_script, array('jquery', 'amazon-link-search'), $this->plugin_version);
wp_register_script('amazon-link-admin-script', $admin_script, false, $this->plugin_version);
// Add base stylesheet
add_action('wp_enqueue_scripts', array($this, 'amazon_styles'));
// Add default url generator - low priority
add_filter('amazon_link_url', array($this, 'get_url'), 20, 6);
add_filter('amazon_link_format_list', array($this, 'format_list'), 10, 2);
// Call any user hooks - passing the current plugin Settings and the Amazon Link Instance.
do_action('amazon_link_init', $this->getSettings(), $this);
}
// If in admin section then register options page and required styles & metaboxes
function admin_menu() {
$submenus = $this->get_menus();
// Add plugin options page, with load hook to bring in meta boxes and scripts and styles
$this->menu = add_menu_page(__('Amazon Link Options', 'amazon-link'), __('Amazon Link', 'amazon-link'), 'manage_options', $this->menu_slug, NULL, $this->icon, 81.375);
foreach ($submenus as $slug => $menu) {
$ID= add_submenu_page($this->menu_slug, $menu['Title'], $menu['Label'], $menu['Capability'], $slug, array($this, 'show_settings_page'));
$this->pages[$ID] = $menu;
add_action('load-'.$ID, array(&$this, 'load_settings_page'));
add_action( 'admin_print_styles-' . $ID, array($this,'amazon_admin_styles') );
add_action( 'admin_print_scripts-' . $ID, array($this,'amazon_admin_scripts') );
if (isset($menu['Scripts'])) {
foreach ($menu['Scripts'] as $script)
add_action( 'admin_print_scripts-' . $ID, $script );
}
if (isset($menu['Styles'])) {
add_action( 'admin_print_styles-' . $ID, $menu['Styles'] );
}
}
// Add support for Post edit metabox, this requires our styles and post edit AJAX scripts.
$post_types = get_post_types();
foreach ( $post_types as $post_type ) {
add_meta_box('amazonLinkID', 'Add Amazon Link', array($this,'insertForm'), $post_type, 'normal');
}
add_action( "admin_print_scripts-post.php", array($this,'edit_scripts') );
add_action( "admin_print_scripts-post-new.php", array($this,'edit_scripts') );
add_action( "admin_print_styles-post-new.php", array($this,'amazon_admin_styles') );
add_action( "admin_print_styles-post.php", array($this,'amazon_admin_styles') );
add_filter('plugin_row_meta', array($this, 'register_plugin_links'),10,2); // Add extra links to plugins page
add_action('show_user_profile', array($this, 'show_user_options') ); // Display User Options
add_action('edit_user_profile', array($this, 'show_user_options') ); // Display User Options
add_action('personal_options_update', array($this, 'update_user_options')); // Update User Options
add_action('edit_user_profile_update', array($this, 'update_user_options'));// Update User Options
}
// Hooks required to bring up options page with meta boxes:
function load_settings_page() {
$screen = get_current_screen();
if (!isset($this->pages[$screen->id])) return;
$page = $this->pages[$screen->id];
$slug = $page['Slug'];
add_filter('screen_layout_columns', array(&$this, 'admin_columns'), 10, 2);
wp_enqueue_script('common');
wp_enqueue_script('wp-lists');
wp_enqueue_script('postbox');
if (isset($page['Metaboxes'])) {
foreach($page['Metaboxes'] as $id => $data) {
add_meta_box( $id, $data['Title'], $data['Callback'], $screen->id, $data['Context'], $data['Priority'], $this);
}
}
add_meta_box( 'alInfo', __( 'About', 'amazon-link' ), array (&$this, 'show_info' ), $screen->id, 'side', 'core' );
// Add Contextual Help
if (isset($page['Help'])) {
$tabs = include( $page['Help']);
foreach ($tabs as $tab) $screen->add_help_tab( $tab );
}
$screen->set_help_sidebar('
';
}
echo $text;
}
/*****************************************************************************************/
// Page/Post Edit Screen Widget
function insertForm($post, $args) {
include('include/insertForm.php');
}
/*****************************************************************************************/
/// Helper Functions
/*****************************************************************************************/
function aws_signed_request($region, $params, $public_key, $private_key)
{
return include('include/awsRequest.php');
}
function remove_parents ($array) {
if (is_array($array)) {
return $this->remove_parents($array[0]);
} else {
return $array;
}
}
function format_list ( $array, $key_info = array()) {
/* Only process if it is an array, if it isn't then it probably has already been filtered. */
if (!is_array($array)) return $array;
$class = isset($key_info['Class']) ? $key_info['Class'] : 'al_'. $key_info['Keyword'];
$ul = '
';
foreach ($array as $item) {
$ul .= '
'. $item . '
';
}
$ul .= '
';
return $ul;
}
/*
* Utility function to create some html based on an associative array.
*/
function merge_items($items, $elements, $preserve_duplicates = False) {
if (!isset($items[0])) {
$items = array('0' => $items);
}
$unique_items = array();
$primary = key($elements);
$result = '';
foreach ($items as $item) {
if (isset($item[$primary]) && ($preserve_duplicates || !in_array($item[$primary], $unique_items))) {
$unique_items[] = $item[$primary];
foreach($elements as $element => $info) {
$result .= $info['Pre'] . $item[$element] . $info['Post'];
}
}
}
return $result;
}
/*****************************************************************************************/
/// Do Amazon Link Constructs
/*****************************************************************************************/
function showRecommendations ($categories='1', $last='30') {
return include('include/showRecommendations.php');
}
function grab($data, $keys, $default) {
foreach ($keys as $location) {
$result = $data;
foreach ($location as $key) if (isset($result[$key])) {$result = $result[$key];} else {$result=NULL;break;}
if (isset($result)) return $result;
}
if ($keys = '') return $data; // If no keys then return the whole item
return $default;
}
function cached_query($request, $settings = NULL) {
if ($settings === NULL)
$settings = $this->getSettings();
/* If not a request then must be a standard ASIN Lookup */
if (!is_array($request))
$asin = $request;
if (TIMING) $time_start = microtime(true);
$data = NULL;
if (!is_array($request)) {
$li = $this->get_local_info($settings);
$cc = $li['cc'];
$data[0] = $this->cache_lookup_item($asin, $cc);
if (TIMING) {$time_taken = microtime(true)-$time_start;echo "";}
if ($data[0] !== NULL) {
$data[0]['cached'] = 1;
return $data;
}
}
if (TIMING) $time_start = microtime(true);
// Create query to retrieve the an item
if (!is_array($request)) {
$request = array();
$request['Operation'] = 'ItemLookup';
$request['ItemId'] = $asin;
$request['IdType'] = 'ASIN';
$request['ResponseGroup'] = $this->get_response_groups();
} else {
$request['ResponseGroup'] = $this->get_response_groups();
}
$pxml = $this->doQuery($request, $settings);
if (TIMING) {$time_taken = microtime(true)-$time_start;echo "";}
if (($pxml === False) || !isset($pxml['Items']['Item'])) {
// Failed to return any results
$data = array(array('ASIN' => $asin, 'found' => 0 ));
$data['Error'] = (isset($pxml['Error']['Message'])? $pxml['Error']['Message'] :
(isset($pxml['Items']['Request']['Errors']['Error']['Message']) ?
$pxml['Items']['Request']['Errors']['Error']['Message'] : 'No Items Found'));
return $data;
} else {
if (array_key_exists('ASIN', $pxml['Items']['Item'])) {
// Returned a single result (not in an array)
if (TIMING) $time_start = microtime(true);
$items = array($pxml['Items']['Item']);
} else {
// Returned several results
$items =$pxml['Items']['Item'];
}
$keywords = $this->get_keywords();
/* Extract useful information from the xml */
$data= array();
for ($index=0; $index < count($items); $index++ ) {
$result = $items[$index];
foreach ($keywords as $keyword => $key_info) {
if (isset($key_info['Live'])) {
$key_data = $this->grab($result, $key_info['Position'], $key_info['Default']);
$key_info['Keyword'] = $keyword;
if (isset($key_info['Filter'])) $key_data = apply_filters($key_info['Filter'], $key_data, $key_info, $this);
$data[$index][$keyword] = $key_data;
}
}
$data[$index]['asins'] = 0;
$data[$index]['artist'] = $this->remove_parents($data[$index]['artist']);
$data[$index]['type'] = 'Amazon';
$data[$index]['found'] = 1;
/* Save each item to the cache if it is enabled */
$this->cache_update_item($data[$index]['asin'], $cc, $data[$index]);
if (TIMING) {$time_taken = microtime(true)-$time_start;echo "";}
}
}
return $data;
}
function doQuery($request, $Settings = NULL)
{
if ($Settings === NULL)
$Settings = $this->getSettings();
else
$this->Settings = $Settings;
$li = $this->get_local_info($Settings);
$tld = $li['tld'];
if (!isset($request['AssociateTag'])) $request['AssociateTag'] = $li['tag'];
return $this->aws_signed_request($tld, $request, $Settings['pub_key'], $Settings['priv_key']);
}
function make_link($asin, $object, $settings = NULL, $local_info = NULL, $search = NULL, $type = 'product', $close = True)
{
if ($settings === NULL)
$settings = $this->getSettings();
if ($local_info === NULL)
$local_info = $this->get_local_info($settings);
if ($search === NULL)
$search = array('','');
if (!isset($settings['home_cc'])) $settings['home_cc'] = $settings['default_cc'];
/*
* Generate a localised/multinational link, wrapped around '$object'
*/
$TARGET = $settings['new_window'] ? 'target="_blank"' : '';
$url = apply_filters('amazon_link_url', '', $type, $asin, $search[0], $local_info, $settings, $this);
$text='' . $object . ($close ?'' : '');
if ($settings['multi_cc']) {
$multi_data = array('settings' => $settings, 'type' => $type, 'asin' => $asin, 'search' => $search[1], 'cc' => $local_info['cc'], 'channel' => $local_info['channel'] );
$text = $this->create_popup($multi_data, $text);
}
return $text;
}
function get_url($url, $type, $asin, $search, $local_info, $settings) {
// URL already created just drop out.
if ($url != '') return $url;
if (!empty($asin[$local_info['cc']])) {
// User Specified ASIN always use
$asin = $asin[$local_info['cc']];
} else if ($settings['search_link'] && ($type == 'product') && !empty($asin[$settings['home_cc']]) ) {
$type = 'search';
} else if (!empty($asin[$settings['home_cc']])) {
$asin = $asin[$settings['home_cc']];
} else if (!empty($settings['url'])) {
$url = isset($settings['url'][$local_info['cc']]) ? $settings['url'][$local_info['cc']] : $settings['url'][$settings['home_cc']];
return $url;
}
if ($type == 'product') {
$text='http://www.amazon.' . $local_info['tld'] . '/gp/product/'. $asin. '?ie=UTF8&linkCode=as2&camp=1634&creative=6738&tag=' . $local_info['tag'] .'&creativeASIN='. $asin;
} else if ($type == 'search') {
$text='http://www.amazon.' . $local_info['tld'] . '/mn/search/?_encoding=UTF8&linkCode=ur2&camp=1634&creative=19450&tag=' . $local_info['tag'] . '&field-keywords=' . $search;
} else {
$text='http://www.amazon.' . $local_info['tld'] . '/review/'. $asin. '?_encoding=UTF8&linkCode=ur2&camp=1634&creative=19450&tag=' . $local_info['tag'];
}
return $text;
}
function create_popup ($data, $text){
if (!$this->scripts_done) {
$this->scripts_done = True;
add_action('wp_print_footer_scripts', array($this, 'footer_scripts'));
}
// Need to check all locales...
$sep = '';
$term ='{';
$countries = $this->get_country_data();
$home_cc = $data['settings']['home_cc'];
foreach ($countries as $country => $country_data) {
if ($data['type'] == 'search' ) {
$term .= $sep. $country .' : \'S-'. ($data['search']) .'\'';
} else {
if ($data['type'] == 'review') {
$type = 'R-';
} else if ($data['type'] == 'product') {
$type = 'A-';
}
if (!empty($data['asin'][$country])) {
$term .= $sep. $country .' : \''. $type. $data['asin'][$country].'\'';
} else if ($data['settings']['search_link'] && !empty($data['asin'][$home_cc])) {
$term .= $sep. $country .' : \'S-'. ($data['search']) .'\'';
} else if (empty($data['asin'][$home_cc]) && !empty($data['settings']['url'][$country])){
$term .= $sep. $country .' : \''. 'U-'. $data['settings']['url'][$country].'\'';
} else {
$term .= $sep. $country .' : \'X-\'';
}
}
$sep = ',';
}
$term .= '}';
$script = 'onMouseOut="al_link_out()" onMouseOver="al_gen_multi('. $this->multi_id . ', ' . $term. ', \''. $data['cc']. '\', \''. $data['channel'] .'\');" ';
$script = str_replace ('multi_id++;
return $script;
}
function make_links($asins, $link_text, $Settings = NULL)
{
global $post;
if ($Settings === NULL)
$Settings = $this->getSettings();
$local_info = $this->get_local_info($Settings);
$output = '';
/*
* If a template is specified and exists then populate it
*/
if (isset($Settings['template'])) {
$template = strtolower($Settings['template']);
$Templates = $this->getTemplates();
if (isset($Templates[$template])) {
$Settings['template_content'] = $Templates[$template]['Content'];
$Settings['template_type'] = $Templates[$template]['Type'];
}
}
if (isset($Settings['template_content'])) {
$details = array();
unset($Settings['asin']);
if ($Settings['template_type'] == 'Multi') {
/* Multi-product template collapse array back to a list, respecting country specific selection */
$sep = ''; $list='';
foreach ($asins as $i => $asin) {
$list .= $sep .(is_array($asin) ? (isset($asin[$local_info['cc']]) ? $asin[$local_info['cc']] : $asin[$Settings['default_cc']]) : $asin);
$sep=',';
}
$details[0] = $Settings;
$details[0]['asins'][$local_info['cc']] = $list;
} elseif ($Settings['template_type'] == 'No ASIN') {
/* No asin provided so don't try and parse it */
$details[0] = $Settings;
$details[0]['found'] = 1;
} else {
/* Usual case where user provides asin=X or asin=X,Y,Z */
for ($index=0; $index < count($asins); $index++ ) {
if (count($asins) > 1) {
$details[$index] = $Settings;
$details[$index]['asin'] = $asins[$index];
$details[$index]['live'] = 1;
} else {
$details[$index] = $Settings;
$details[$index]['asin'] = $asins[$index];
}
}
}
if (!empty($details))
{
foreach ($details as $item) {
$output .= $this->search->parse_template($item);
}
}
return $output;
}
foreach ($asins as $asin) {
/*
* This code required to maintain backward compatibility
*/
$object = stripslashes($link_text);
// Do we need to display or link to an image ?
if (!empty($Settings['image']) || !empty($Settings['thumb'])) {
$media_ids = $this->search->find_attachments($asin);
if (!is_wp_error($media_ids)) {
$media_id = $media_ids[0]->ID;
}
if (!empty($Settings['thumb'])) {
if (isset($media_id)) {
$thumb = wp_get_attachment_thumb_url($media_id);
} elseif (strlen($Settings['thumb']) > 4) {
$thumb = $Settings['thumb'];
}
}
if (!empty($Settings['image'])) {
if (isset($media_id)) {
$image = wp_get_attachment_url($media_id);
} elseif (strlen($Settings['image']) > 4) {
$image = $Settings['image'];
}
}
}
// If both thumb and image are specified then just insert the image
if (isset($thumb) && isset($image)) {
$object = '';
return $object;
}
if (isset($image))
$object = '';
if (isset($thumb))
$object = '';
if ($Settings['search_link']) {
$Settings['template_content'] = $Settings['search_text'];
$search = $this->search->parse_template($Settings);
$search = array( '0' => $search, '1' => urlencode($search));
} else {
$search = NULL;
}
$output .= $this->make_link($asin, $object, $Settings, $local_info, $search);
}
return $output;
}
/////////////////////////////////////////////////////////////////////
} // End Class
$awlfw = new AmazonWishlist_For_WordPress();
} // End if exists
function amazon_get_link($args)
{
global $awlfw;
$awlfw->parseArgs($args); // Get the default settings
$li = $awlfw->get_local_info();
foreach ($awlfw->Settings['asin'] as $asin) {
return $awlfw->get_url('product', $asin, '', $li, $awlfw->$Settings); // Return a URL
}
}
function amazon_scripts()
{
global $awlfw;
$this->footer_scripts();
}
function amazon_query($request)
{
global $awlfw;
return $awlfw->doQuery($request); // Return response
}
function amazon_shortcode($args)
{
global $awlfw;
$awlfw->parseArgs($args); // Get the default settings
$awlfw->Settings['in_post'] = False;
if (isset($awlfw->Settings['cat']))
return $awlfw->showRecommendations($awlfw->Settings['cat'], $awlfw->Settings['last']);
else
return $awlfw->make_links($awlfw->Settings['asin'], $awlfw->Settings['text'], $awlfw->Settings);
}
function amazon_recommends($categories='1', $last='30')
{
global $awlfw;
return $awlfw->showRecommendations ($categories, $last);
}
function amazon_make_links($args)
{
global $awlfw;
$awlfw->parseArgs($args); // Get the default settings
$awlfw->Settings['in_post'] = False;
return $awlfw->make_links($awlfw->Settings['asin'], $awlfw->Settings['text'], $awlfw->Settings); // Return html
}
?>