&text=] --> inserts link to amazon item
[amazon cat= ' . __('Use this section to set up the global Display Options that change how links are displayed and their behaviour, to enable advance options like \' ' . __('Within this section you can also set up the Amazon Product Data Cache, select Enable to install the cache, Disable to remove it, and Flush to empty any cached data.','amazon-link') . ' ' . __('The status of the ip2nation database is displayed at the bottom of this section, with options to Install the database if it is not already installed or a new version is available on the ip2nation website.','amazon-link') . ' ' . __('Use this section to set up the global default Amazon Affiliate Tags, as well as create named Channels that can be used on the Amazon Affiliate Site to track the performance of different sections of your site. You can also set Affiliate tags in the WordPress User\'s Profile page, these will automatically be used on any post authored by that user','amazon-link') . ' ' . __('Use this section to edit, create and delete Templates used to create the Amazon Links on your site, the content is standard HTML with special ' . __('This section lists all the default templates included with the plugin, use it to re-install or your update your active templates.','amazon-link') . ' '. __('For more information:', 'amazon-link'). ' ' . __('Plugin Home Page','amazon-link') . ' ' . __('Plugin FAQ','amazon-link') . ' ' . __('Channels Help','amazon-link') . ' ' . __('Template Help','amazon-link') . 'live data\', the Product search tool or \'Wishlist\' facility you must also configure your AWS keys in the Amazon Associate Information sub section.','amazon-link') . '% delimited keywords that are replaced by appropriate product information, see the \'Template Help\' section for a list of all valid keywords.','amazon-link') . ' ' . $data['name'],
'Hint' => sprintf(__('Enter your affiliate tag for %1$s.', 'amazon-link'), $data['name'] ));
$option_list ['title']['Description'] .= ''. $data['name']. ', ';
}
return $option_list;
}
function getOptions() {
if (!isset($this->Opts)) {
$this->Opts = get_option($this->optionName, array());
if (!isset($this->Opts['version']) || ($this->Opts['version'] < $this->option_version))
{
$this->upgrade_settings($this->Opts);
$this->Opts = get_option($this->optionName, array());
}
}
return $this->Opts;
}
function saveOptions($Opts) {
$optionList = $this->get_option_list();
if (!is_array($Opts)) {
return;
}
// Ensure hidden items are not stored in the database
foreach ( $optionList as $optName => $optDetails ) {
if ($optDetails['Type'] == 'hidden') unset($Opts[$optName]);
}
update_option($this->optionName, $Opts);
$this->Opts = $Opts;
}
function deleteOptions() {
delete_option($this->optionName);
}
function getTemplates() {
if (!isset($this->Templates)) {
$this->Templates = get_option($this->templatesName, array());
}
return $this->Templates;
}
function saveTemplates($Templates) {
if (!is_array($Templates)) {
return;
}
ksort($Templates);
update_option($this->templatesName, $Templates);
$this->Templates = $Templates;
}
function get_channels($override = False, $user_channels = False) {
if (!$override || !isset($this->channels)) {
$channels = get_option($this->channels_name, array());
if ($user_channels) {
$users = get_users();
foreach ($users as $user => $data) {
$user_options = $this->get_user_options($data->ID);
if (is_array($user_options)) {
$channels['al_user_' . $data->ID] = $user_options;
$channels['al_user_' . $data->ID]['user_channel'] = 1;
}
}
}
if (!$override) return $channels;
$country_data = $this->get_country_data();
$this->channels = array();
foreach ( $channels as $channel_id => $channel_data) {
$this->channels[$channel_id] = $channel_data;
$this->channels[$channel_id]['ID'] = $channel_id;
foreach ( $country_data as $cc => $data) {
if ($channel_data['tag_'. $cc] == '') {
$this->channels[$channel_id]['tag_'. $cc] = ($channels['default']['tag_' .$cc] != '') ?
$channels['default']['tag_' .$cc] : $data['default_tag'];
}
}
}
}
return $this->channels;
}
function save_channels($channels) {
if (!is_array($channels)) {
return;
}
$defaults = $channels['default'];
unset($channels['default']);
ksort($channels);
$channels = array('default' => $defaults) + $channels;
update_option($this->channels_name, $channels);
$this->channels = $channels;
}
/*
* Parse the arguments passed in.
*/
function parseArgs($arguments) {
$optionList = $this->get_option_list();
$args = array();
parse_str(html_entity_decode($arguments), $args);
$Opts = $this->getOptions();
unset($this->Settings);
/*
* Check for each setting, local overides saved option, otherwise fallback to default.
*/
foreach ($optionList as $key => $details) {
if (isset($args[$key])) {
if (is_array($args[$key])) {
$this->Settings[$key] = array_map("trim", $args[$key]);
} else {
$this->Settings[$key] = trim(stripslashes($args[$key]),"\x22\x27"); // Local setting
}
} else if (isset($Opts[$key])) {
$this->Settings[$key] = $Opts[$key]; // Global setting
if (isset($details['OverrideBlank']) && ($Opts[$key] == '')) {
$this->Settings[$key] = $details['OverrideBlank']; // Use default if Global Setting is blank
}
} else if (isset ($details['Default'])) {
$this->Settings[$key] = $details['Default']; // Use default
} else if (isset ($details['OverrideBlank'])) {
$this->Settings[$key] = $details['OverrideBlank']; // Use default
}
}
if (!is_array($this->Settings['asin'])) $this->Settings['asin'] = isset($this->Settings['asin']) ? explode (',', $this->Settings['asin']) : array();
}
/*
* Normally Settings are populated from parsing user arguments, however some
* external calls do not cause argument parsing (e.g. amazon_query). So this
* ensures we have the defaults.
*/
function getSettings() {
if (!isset($this->Settings)) {
$this->Settings = $this->getOptions();
}
$optionList = $this->get_option_list();
foreach ($optionList as $key => $details) {
if ((!isset($this->Settings[$key]) || ($this->Settings[$key] == '')) && isset($details['OverrideBlank'])) {
$this->Settings[$key] = $details['OverrideBlank']; // Use default
}
}
return $this->Settings;
}
function get_user_options($ID) {
$options = get_the_author_meta( $this->user_options, $ID );
return $options;
}
function save_user_options($ID, $options ) {
update_usermeta( $ID, $this->user_options, $options );
}
function valid_keys() {
$Settings = $this->getSettings();
if ( (strlen($Settings['pub_key']) > 10) && (strlen($Settings['priv_key']) > 10))
return True;
return False;
}
function validate_keys($Settings = NULL) {
if (Settings === NULL) $Settings = $this->getSettings();
$result['Valid'] = 0;
$result['Message'] = 'AWS query failed to get a response - try again later.';
$request = array('Operation' => 'ItemLookup',
'ResponseGroup' => 'ItemAttributes',
'IdType' => 'ASIN', 'ItemId' => 'B000H2X2EW');
$pxml = $this->doQuery($request, $Settings);
if (isset($pxml['Items'])) {
$result['Valid'] = 1;
} else if (isset($pxml['Error'])) {
$result['Valid'] = 0;
$result['Message'] = $pxml['Error']['Message'];
}
return $result;
}
/*****************************************************************************************/
function cache_install() {
global $wpdb;
$settings = $this->getOptions();
if ($settings['cache_enabled']) return False;
$cache_table = $wpdb->prefix . $this->cache_table;
$sql = "CREATE TABLE $cache_table (
asin varchar(10) NOT NULL,
cc varchar(5) NOT NULL,
updated datetime NOT NULL,
xml longtext NOT NULL,
PRIMARY KEY (asin, cc)
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
$settings['cache_enabled'] = 1;
$this->saveOptions($settings);
return True;
}
function cache_remove() {
global $wpdb;
$settings = $this->getOptions();
if (!$settings['cache_enabled']) return False;
$settings['cache_enabled'] = 0;
$this->saveOptions($settings);
$cache_table = $wpdb->prefix . $this->cache_table;
$sql = "DROP TABLE $cache_table;";
$wpdb->query($sql);
return True;
}
function cache_empty() {
global $wpdb;
$settings = $this->getOptions();
if (!$settings['cache_enabled']) return False;
$cache_table = $wpdb->prefix . $this->cache_table;
$sql = "TRUNCATE TABLE $cache_table;";
$wpdb->query($sql);
return True;
}
function cache_flush() {
global $wpdb;
$settings = $this->getOptions();
$cache_table = $wpdb->prefix . $this->cache_table;
$sql = "DELETE FROM $cache_table WHERE updated < DATE_SUB(NOW(),INTERVAL " . $settings['cache_age']. " HOUR);";
$wpdb->query($sql);
}
/*****************************************************************************************/
/// Affiliate Tracking ID Channels
/*****************************************************************************************/
/*
* Check the channels in order until we get a match
*
* Filter rules:
* cat = [category slug|category id]
* parent_cat = [category slug| category id]
* author = [author name|author id]
* tag = [tag name|tag id]
* type = [page|post|other = widget|template, etc]
* parent = [page/post id]
* random = 1-99
* empty filter = always use.
*/
function get_channel($settings = NULL) {
// Need $GLOBALS & Channels
if ($settings === NULL)
$settings = $this->getSettings();
$channels = $this->get_channels(True, True);
if (isset($settings['in_post']) && $settings['in_post']) {
$post = $GLOBALS['post'];
} else {
$post = '';
}
// If manually set always respect.
if (isset($settings['chan']) && isset($channels[strtolower($settings['chan'])]))
{
return $channels[strtolower($settings['chan'])];
}
// If post or page, check $this->channel_ids[ID] to see if already processed
// For each channel (excluding default)
// For each filter check for match
// Switch on rule type [cat|parent_cat|author|tag|type]
// cat
// if !isset($cats) grab array(cat_id => cat_slug)
// check cat in array or array_keys
// parent_cat = recursive list of all category parents
// if !isset($cats) grab array(cat_id => cat_slug)
// if !isset($parent_cats) grab array(cat_id => cat_slug)
// check cat in either cats/parent_cats array or array_keys
// author
// if !isset($author) grab array(author_id => author_name)
// check author in array or array_keys
// tag
// if !isset($tags) grab array(tag_id => tag_name)
// check tag in array or array_keys
// type
// if !isset($type) post_type / other
// check type == type
// If any rule fails drop to next channel
// If all rules pass use this channel, save in $this->channel_ids[ID]
// If no specific channel detected then check for author specific IDs via get_the_author_meta
if (isset($post->post_author) && isset($channels['al_user_'.$post->post_author])) {
return $channels['al_user_'.$post->post_author];
}
// No match found return default channel.
return $channels['default'];
}
/*****************************************************************************************/
/// Localise Link Facility
/*****************************************************************************************/
function get_country($settings = NULL) {
if ($settings === NULL)
$settings = $this->getSettings();
// Pretty arbitrary mapping of domains to Amazon sites, default to 'com' - the 'international' site.
$country_map = array('uk' => array('uk', 'ie', 'gi', 'gl', 'nl', 'vg', 'cy', 'gb', 'dk'),
'fr' => array('fr', 'be', 'bj', 'bf', 'bi', 'cm', 'cf', 'td', 'km', 'cg', 'dj', 'ga', 'gp',
'gf', 'gr', 'pf', 'tf', 'ht', 'ci', 'lu', 'mg', 'ml', 'mq', 'yt', 'mc', 'nc',
'ne', 're', 'sn', 'sc', 'tg', 'vu', 'wf'),
'de' => array('de', 'at', 'ch', 'no', 'dn', 'li', 'sk'),
'es' => array('es'),
'it' => array('it'),
'cn' => array('cn'),
'ca' => array('ca', 'pm'),
'jp' => array('jp')
);
$country = False;
if ($settings['localise'])
{
if (!isset($this->local_country)) {
$cc = $this->ip2n->get_cc();
if ($cc === NULL) return $settings['default_cc'];
$country = 'us';
foreach ($country_map as $key => $countries) {
if (in_array($cc, $countries)) {
$country = $key;
continue;
}
}
$this->local_country = $country;
}
return $this->local_country;
}
return $settings['default_cc'];
}
function widget_filter($content) {
return $this->content_filter($content, TRUE, FALSE);
}
/*****************************************************************************************/
/// Searches through the_content for our 'Tag' and replaces it with the lists or links
/*
* Performs 2 functions:
* 1. Process the content and replace the shortcode with amazon links and wishlists
* 2. Search through the content and record any Amazon ASIN numbers ready to generate a wishlist.
*/
/*****************************************************************************************/
function content_filter($content, $doLinks=TRUE, $in_post=TRUE) {
$new_content='';
$reg_ex = '\[amazon +((?:[^\[\]]*(?:\[[a-z]*\]){0,1})*)\]';
$split_content = preg_split('/'.$reg_ex.'/', $content, NULL, PREG_SPLIT_DELIM_CAPTURE );
if ($doLinks) {
$index = 0;
while ($index <= count($split_content)) {
// Non-matching content - just add to output
if (isset($split_content[$index])) $new_content .= $split_content[$index];
$index++;
$output='';
// Matching content - parse arguments
if (isset($split_content[$index])) {
$this->parseArgs($split_content[$index]);
if (isset($this->Settings['cat'])) {
$this->Settings['in_post'] = $in_post;
if ($this->Settings['debug']) {
$output .= '';
}
$output .= $this->showRecommendations($this->Settings['cat'], $this->Settings['last']);
} else {
// Generate Amazon Link
if (isset($this->Settings['asin'][0])) {
$this->tags = array_merge($this->Settings['asin'], $this->tags);
}else{
$this->tags = array_merge(array($this->Settings['asin']), $this->tags);
}
$this->Settings['in_post'] = $in_post;
if ($this->Settings['debug']) {
$output .= '';
}
$output .= $this->make_links($this->Settings['asin'], $this->Settings['text']);
}
$new_content .= $output;
}
$index++;
}
} else {
$index = 1;
while ($index <= count($split_content)) {
$this->parseArgs($split_content[$index]);
if (isset($this->Settings['asin'][0])){
$this->tags = array_merge($this->Settings['asin'], $this->tags);
}else{
$this->tags = array_merge(array($this->Settings['asin']), $this->tags);
}
$index += 2;
}
}
return $new_content;
}
/*****************************************************************************************/
/// Display Content, Widgets and Pages
/*****************************************************************************************/
// Top level function to display options
function show_options_page() {
global $screen_layout_columns;
?>
%' . strtoupper($keyword) . '%
'; } echo $text; } /*****************************************************************************************/ // Page/Post Edit Screen Widget function insertForm($post) { include('include/insertForm.php'); } /*****************************************************************************************/ /// Helper Functions /*****************************************************************************************/ function aws_signed_request($region, $params, $public_key, $private_key) { return include('include/awsRequest.php'); } /*****************************************************************************************/ /// Do Amazon Link Constructs /*****************************************************************************************/ function showRecommendations ($categories='1', $last='30') { return include('include/showRecommendations.php'); } function get_local_info($settings = NULL) { if ($settings === NULL) $settings = $this->getSettings(); $channel = $this->get_channel($settings); $top_cc = $this->get_country($settings); $country_data = $this->get_country_data(); $info = array( 'flag' => $country_data[$top_cc]['flag'], 'cc' => $top_cc, 'rcm' => $country_data[$top_cc]['rcm'], 'mplace_id' => $country_data[$top_cc]['m_id'], 'mplace' => $country_data[$top_cc]['market'], 'tld' => $country_data[$top_cc]['tld'], 'tag' => $channel['tag_' . $top_cc], 'channel' => $channel['ID']); return $info; } function getURL($term, $tld, $tag) { $type = substr($term,0,1); $arg = substr($term,2); if ($type == 'A') $text='http://www.amazon.' . $tld . '/gp/product/'. $arg. '?ie=UTF8&linkCode=as2&camp=1634&creative=6738&tag=' . $tag .'&creativeASIN='. $arg; else if ($type == 'S') { $text='http://www.amazon.' . $tld . '/mn/search/?_encoding=UTF8&linkCode=ur2&camp=1634&creative=19450&tag=' . $tag. '&field-keywords=' . $arg; } else { $text='http://www.amazon.' . $tld . '/review/'. $arg. '?_encoding=UTF8&linkCode=ur2&camp=1634&creative=19450&tag=' . $tag. '&field-keywords=' . $arg; } return $text; } function itemLookup($asin, $settings = NULL ) { global $wpdb; $cache_table = $wpdb->prefix . $this->cache_table; if ($settings === NULL) $settings = $this->getSettings(); if (TIMING) $time_start = microtime(true); $result = NULL; if ($settings['cache_enabled']) { // Check if asin is already in the cache $li = $this->get_local_info($settings); $cc = $li['cc']; $sql = "SELECT xml FROM $cache_table WHERE asin LIKE '$asin' AND cc LIKE '$cc' AND updated >= DATE_SUB(NOW(),INTERVAL " . $settings['cache_age']. " HOUR)"; $result = $wpdb->get_row($sql, ARRAY_A); if ($result !== NULL) { $items = unserialize($result['xml']); $items[0]['cached'] = 1; } } if (TIMING) {$time_taken = microtime(true)-$time_start;echo "";} if ($result === NULL) { if (TIMING) $time_start = microtime(true); // Create query to retrieve the an item $request = array('Operation' => 'ItemLookup', 'ResponseGroup' => 'Offers,ItemAttributes,Small,Reviews,Images,SalesRank', 'ItemId' => $asin, 'IdType' => 'ASIN'); $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 $items = array(array('ASIN' => $asin, 'found' => 0, 'error' => (isset($pxml['Error']['Message'])? $pxml['Error']['Message'] : 'No Items Found') )); return $items; } 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']); if ($settings['cache_enabled']) { $sql = "DELETE FROM $cache_table WHERE asin LIKE '$asin' AND cc LIKE '$cc'"; $wpdb->query($sql); $data = array( 'asin' => $asin, 'cc' => $cc, 'xml' => serialize($items), updated => current_time('mysql')); $wpdb->insert($cache_table, $data); if (TIMING) {$time_taken = microtime(true)-$time_start;echo "";} } } else { // Returned several results $items =$pxml['Items']['Item']; } } } for ($index=0; $index < count($items); $index++ ) { $items[$index]['found'] = 1; } return $items; } 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 = '', $type = 'product') { if ($settings === NULL) $settings = $this->getSettings(); if ($local_info === NULL) $local_info = $this->get_local_info($settings); if (!isset($settings['home_cc'])) $settings['home_cc'] = $settings['default_cc']; if ($settings['multi_cc']) { // Need to check all locales... $sep = '{'; $term =''; $countries = $this->get_country_data(); foreach ($countries as $country => $country_data) { if (isset($asin[$country])) { $term .= $sep. $country .' : \'A-'. $asin[$country].'\''; } else if ($settings['search_link']) { $term .= $sep. $country .' : \'S-'. $search .'\''; } else { $term .= $sep. $country .' : \'A-'. $asin[$settings['home_cc']].'\''; } $sep = ','; } } $term .= '}'; if ($type == 'review') { $type = 'R-'; } else if ($type == 'product') { $type = 'A-'; } if (isset($asin[$local_info['cc']])) { // User Specified ASIN always use $url_term = $type . $asin[$local_info['cc']]; } else if ($settings['search_link']) { $url_term = 'S-'. ($search); } else { $url_term = $type . $asin[$settings['home_cc']]; } /* * Generate a localised/multinational link, wrapped around '$object' */ $TARGET = $settings['new_window'] ? 'target="_blank"' : ''; $URL = $this->getURL($url_term, $local_info['tld'], $local_info['tag']); if ($settings['multi_cc']) { $this->create_popup(); $text =''; $text .= $object. ''; $this->multi_id++; } else { $text='' . $object . ''; } return $text; } 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') { $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[] = array_merge( array('asins' => $list), $Settings); } elseif ($Settings['template_type'] == 'No ASIN') { $details[] = array_merge(array('found' => 1), $Settings); } elseif (!isset($asins[0])) { $details[] = array_merge($Settings, array( 'asin' => $asins, 'live' => 1)); } else { foreach ($asins as $asin) { if (count($asins) > 1) { $details[] = array_merge($Settings, array( 'asin' => $asin, 'live' => 1)); } else { $details[] = array_merge($Settings, array( 'asin' => $asin)); } } } 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 = '