<?php
/*
Plugin Name:    Amazilon - Amazon PartnerNet
Description:    Integration des Amazon PartnerNet (APN) per Shortcodes
Version:        1.8.8
Author:         Amazilon.com
Author URI:     https://amazilon.com/
*/

if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly

$__amazilonApiCalls = 0;
$__amazilonVersion  = '1.8.8';

$__amazilonNoXchange     = false;
$__amazilonNoAutoVariant = false;

$__amazilonCurrentShortcode = '';
$__amazilonSearchindexes    = array(
	'de' => array(
		'All'                => array( 'title' => 'Alle Kategorien', 'id' => - 1 ),
		'UnboxVideo'         => array( 'title' => 'Amazon Instant Video', 'id' => 3010076031 ),
		'Pantry'             => array( 'title' => 'Amazon Pantry', 'id' => - 1 ),
		'MobileApps'         => array( 'title' => 'Apps & Spiele', 'id' => 1661650031 ),
		'Automotive'         => array( 'title' => 'Auto & Motorrad', 'id' => 78193031 ),
		'Baby'               => array( 'title' => 'Baby', 'id' => 357577011 ),
		'Tools'              => array( 'title' => 'Baumarkt', 'id' => 80085031 ),
		'Beauty'             => array( 'title' => 'Beauty', 'id' => 64257031 ),
		'Apparel'            => array( 'title' => 'Bekleidung', 'id' => 78689031 ),
		'Lighting'           => array( 'title' => 'Beleuchtung', 'id' => 213084031 ),
		'Books'              => array( 'title' => 'Bücher', 'id' => 541686 ),
		'OfficeProducts'     => array( 'title' => 'Bürobedarf & Schreibwaren', 'id' => 192417031 ),
		'PCHardware'         => array( 'title' => 'Computer & Zubehör', 'id' => 569604 ),
		'DVD'                => array( 'title' => 'DVD & Blu-Ray', 'id' => 547664 ),
		'HealthPersonalCare' => array( 'title' => 'Drogerie & Körperpflege', 'id' => 64257031 ),
		'Appliances'         => array( 'title' => 'Elektro-Großgeräte', 'id' => 931573031 ),
		'Electronics'        => array( 'title' => 'Elektronik & Foto', 'id' => 569604 ),
		'ForeignBooks'       => array( 'title' => 'Fremdsprachige Bücher', 'id' => 54071011 ),
		'VideoGames'         => array( 'title' => 'Games', 'id' => 541708 ),
		'HomeGarden'         => array( 'title' => 'Garten', 'id' => 10925241 ),
		'GiftCards'          => array( 'title' => 'Geschenkgutscheine', 'id' => 1571257031 ),
		'PetSupplies'        => array( 'title' => 'Haustier', 'id' => 427727031 ),
		'Photo'              => array( 'title' => 'Kamera & Foto', 'id' => 571860 ),
		'KindleStore'        => array( 'title' => 'Kindle-Shop', 'id' => 530485031 ),
		'Classical'          => array( 'title' => 'Klassik', 'id' => 542676 ),
		'Luggage'            => array( 'title' => 'Koffer, Rücksäcke & Taschen', 'id' => 2454119031 ),
		'Kitchen'            => array( 'title' => 'Küche & Haushalt', 'id' => 3169011 ),
		'Grocery'            => array( 'title' => 'Lebensmittel & Getränke', 'id' => 344162031 ),
		'Music'              => array( 'title' => 'Musik-CDs & Vinyl', 'id' => 542676 ),
		'MP3Downloads'       => array( 'title' => 'Musik-Downloads', 'id' => 180529031 ),
		'MusicalInstruments' => array( 'title' => 'Musikinstrumente & DJ-Equipment', 'id' => 340850031 ),
		'Jewelry'            => array( 'title' => 'Schmuck', 'id' => 327473011 ),
		'Shoes'              => array( 'title' => 'Schuhe & Handtaschen', 'id' => 362995011 ),
		'Software'           => array( 'title' => 'Software', 'id' => 542064 ),
		'Toys'               => array( 'title' => 'Spielzeug', 'id' => 12950661 ),
		'SportingGoods'      => array( 'title' => 'Sport & Freizeit', 'id' => 16435121 ),
		'Industrial'         => array( 'title' => 'Technik & Wissenschaft', 'id' => 5866099031 ),
		'Watches'            => array( 'title' => 'Uhren', 'id' => 193708031 ),
		'Magazines'          => array( 'title' => 'Zeitschriften', 'id' => 1161660 )
	)
);

require_once dirname( __FILE__ ) . '/libs/aws.php';
function amazilonInit() {
	global $__amazilonVersion;
	load_plugin_textdomain( 'amazilon', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
	$config = get_option( 'bowsxWpApn' );
	if ( amazilonCheck() ) {
		add_shortcode( 'apn', 'amazilonShortCode' );
		add_shortcode( 'apnx', 'amazilonShortCodeX' );
		add_shortcode( 'amazilon', 'amazilonShortCodeAmazilon' );
		add_shortcode( 'amazilon-search', 'amazilonShortCodeAmazilonSearch' );
		add_filter( 'comment_text', 'amazilonFilterCommentText', 10, 2 );
	}
	add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'amazilonAddActionLink' );
	add_filter( 'pre_set_site_transient_update_plugins', 'amazilonInjectUpdate' );
	add_filter( 'plugins_api', 'amazilonGetInfo', 10, 3 );
	add_action( 'wp_ajax_amazilonClearCache', 'amazilonClearCache_callback' );
	add_action( 'wp_ajax_amazilonCT', 'amazilonCT_callback' );
	add_action( 'wp_ajax_nopriv_amazilonCT', 'amazilonCT_callback' );
	add_action( 'wp_ajax_amazilonShorten', 'amazilonShorten_callback' );
	add_action( 'wp_ajax_amazilonPreview', 'amazilonPreview_callback' );
	add_action( 'wp_ajax_amazilonSearch', 'amazilonSearch_callback' );
	add_action( 'wp_ajax_amazilonSimilar', 'amazilonSimilar_callback' );
	add_action( 'wp_ajax_amazilonSearchCategories', 'amazilonSearchCategories_callback' );
	add_action( 'wp_ajax_amazilonBestsellers', 'amazilonBestsellers_callback' );
	add_action( 'wp_ajax_amazilonBestsellersPreview', 'amazilonBestsellersPreview_callback' );

	$aDeps  = array( 'dashicons' );
	$oTheme = wp_get_theme();
	if ( ! is_admin() && ( $oTheme->name == 'twentyseventeen' || $oTheme->Template == 'twentyseventeen' ) ) {
		array_push( $aDeps, 'twentyseventeen-style' );
	}

	wp_enqueue_style( 'amazilon', plugins_url( 'gfx/style.css', __FILE__ ), $aDeps, $__amazilonVersion );
	wp_enqueue_style( 'jquery-ui', plugins_url( 'gfx/jquery-ui.min.css', __FILE__ ), array(), '1.12.0' );
	wp_enqueue_script( 'jquery-ui-tooltip' );
	wp_enqueue_script( 'amazilon-lib', plugins_url( 'gfx/lib.js', __FILE__ ), array(), $__amazilonVersion );
	wp_localize_script( 'amazilon-lib', 'amazilonObj', array(
		'ajax_url' => admin_url( 'admin-ajax.php' ),
		'te'       => ( isset( $config['sTrackerEnabled'] ) ? (int) $config['sTrackerEnabled'] : 0 )
	) );

	if ( $config !== false && isset( $config['search']['bActive'] ) && $config['search']['bActive'] == '1' ) {
		add_filter( 'get_search_form', 'amazilonSearchPrepare' );
		add_action( 'wp_footer', 'amazilonSearchFill', 100 );

		if ( isset( $config['search']['bForce'] ) && $config['search']['bForce'] == '1' ) {
			add_action( 'loop_end', 'amazilonSearchPrepareContent' );
		}
	}
}

add_filter( 'pre_update_option_bowsxWpApn', 'AmazilonOnUpdateOption', 10, 2 );
function AmazilonOnUpdateOption( $newVal, $oldVal ) {
	if ( current_user_can( 'amazilon_manage_rights' ) ) {
		$aCaps  = array(
			'amazilon_manage_rights',
			'amazilon_change_options',
			'amazilon_use_generators',
			'amazilon_use_shortcodes_comments',
			'amazilon_modify_dynamic_widget'
		);
		$aRoles = get_editable_roles();
		foreach ( $aRoles as $sRole => $aRoledata ) {
			# Never ever touch the admins!
			if ( $sRole == 'administrator' ) {
				continue;
			}
			$oRole = get_role( $sRole );
			for ( $iCap = 0; $iCap < count( $aCaps ); $iCap ++ ) {
				if ( isset( $_POST['amazilonCap'][ $sRole ][ $aCaps[ $iCap ] ] ) && $_POST['amazilonCap'][ $sRole ][ $aCaps[ $iCap ] ] == 'true' ) {
					if ( ! $oRole->has_cap( $aCaps[ $iCap ] ) ) {
						$oRole->add_cap( $aCaps[ $iCap ] );
					}
				} elseif ( $oRole->has_cap( $aCaps[ $iCap ] ) ) {
					$oRole->remove_cap( $aCaps[ $iCap ] );
				}
			}
		}
	}

	return $newVal;
}

function amazilonFilterCommentText( $sText, $oComment ) {
	if ( (int) $oComment->user_id < 1 || ! user_can( (int) $oComment->user_id, 'amazilon_use_shortcodes_comments' ) ) {
		return $sText;
	}

	return do_shortcode( $sText );
}

function amazilonWidgets() {
	register_widget( 'amazilonWidget' );
}

function amazilonAdminInit() {
	global $__amazilonVersion;
	$config = get_option( 'bowsxWpApn' );
	$aDeps  = array( 'dashicons' );

	wp_enqueue_style( 'amazilon', plugins_url( 'gfx/style.css', __FILE__ ), $aDeps, $__amazilonVersion );
	wp_enqueue_style( 'jquery-ui', plugins_url( 'gfx/jquery-ui.min.css', __FILE__ ), array(), '1.12.0' );
	wp_enqueue_script( 'jquery-ui-tooltip' );
	wp_enqueue_script( 'jquery-ui-datepicker' );
	wp_enqueue_script( 'amazilon-lib', plugins_url( 'gfx/lib.js', __FILE__ ), array(), $__amazilonVersion );
	wp_localize_script( 'amazilon-lib', 'amazilonObj', array(
		'ajax_url' => admin_url( 'admin-ajax.php' ),
		'te'       => ( isset( $config['sTrackerEnabled'] ) ? (int) $config['sTrackerEnabled'] : 0 )
	) );
	wp_enqueue_script( 'amazilon-lib-admin', plugins_url( 'gfx/lib.admin.php', __FILE__ ), array(), $__amazilonVersion,
		true );
	wp_enqueue_script( 'amazilon-js-cookie', plugins_url( 'gfx/js.cookie.min.js', __FILE__ ), array( 'amazilon-lib' ),
		'2.1.3' );

	if ( current_user_can( 'amazilon_modify_dynamic_widget' ) ) {
		new amazilonMetaBox();
	}
	$sVersion = get_option( 'amazilonVersion' );
	if ( $sVersion === false ) {
		amazilonActivate();
	} elseif ( version_compare( $sVersion, $__amazilonVersion ) < 0 ) {
		amazilonActivate();
	}
}

function amazilonInstall() {
	if ( ( $config = get_option( 'bowsxWpApn' ) ) === false || ! isset( $config['dontDelete'] ) || $config['dontDelete'] != '1' ) {
		add_option( 'bowsxWpApn', array(
			'publicKey'         => '',
			'privateKey'        => '',
			'associateTag'      => '',
			'useSSL'            => '0',
			'useNofollow'       => '0',
			'useCurrencySymbol' => '0',
			'bForce'            => '0',
			'urlFormat'         => '0',
			'iCaching'          => '86400',
			'licenseKey'        => '',
			'dontDelete'        => '0',
			'sHinweistext'      => '',
			'sAdnotice'         => __( 'Advertisement', 'amazilon' ),
			'bRetrieveStars'    => '0'
		), '', 'yes' );
	}
}

function amazilonActivate() {
	global $__amazilonVersion;
	if ( ! wp_next_scheduled( 'bowsx_wp_apn_cleanup' ) ) {
		wp_schedule_event( time(), 'daily', 'bowsx_wp_apn_cleanup' );
	}
	if ( ! wp_next_scheduled( 'bowsx_wp_apn_daily' ) ) {
		wp_schedule_event( time(), 'daily', 'bowsx_wp_apn_daily' );
	}

	global $wpdb;
	$charset_collate = $wpdb->get_charset_collate();
	$sql             = 'CREATE TABLE ' . $wpdb->prefix . 'wpapn_errors (
        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
        `c32` INT UNSIGNED NOT NULL,
        `asin` CHAR(10) NOT NULL,
        `titel` MEDIUMTEXT NOT NULL,
		`msg` TINYTEXT NOT NULL,
		`url` TEXT NOT NULL,
		`shortcode` VARCHAR(50) NOT NULL,
        `tstamp` TIMESTAMP NOT NULL,
        PRIMARY KEY (`id`)
    ) ' . $charset_collate . ';
    CREATE TABLE ' . $wpdb->prefix . 'amazilon_clicktracker (
        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
        `c32` INT UNSIGNED NOT NULL,
        `asin` CHAR(10) NOT NULL,
        `title` TEXT NOT NULL,
        `sc` VARCHAR(250) NOT NULL,
        `tag` VARCHAR(50) NOT NULL,
		`referer` TEXT NOT NULL,
        `tstamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP(),
        PRIMARY KEY (`id`)
    ) ' . $charset_collate . ';
    CREATE TABLE ' . $wpdb->prefix . 'amazilon_xchange (
        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
        `asin` CHAR(10) NOT NULL,
        `title` TEXT NOT NULL,
        `asinNew` CHAR(10) NOT NULL,
        `titleNew` TEXT NOT NULL,
        `tstamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP(),
        PRIMARY KEY (`id`),
        INDEX `asin` (`asin` ASC)
    ) ' . $charset_collate . ';
    CREATE TABLE ' . $wpdb->prefix . 'amazilon_scodes (
        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
        `c32` INT UNSIGNED NOT NULL,
        `name` TINYTEXT NOT NULL,
        `code` TEXT NOT NULL,
        `coded` TEXT NOT NULL,
        PRIMARY KEY (`id`)
    ) ' . $charset_collate . ';';

	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql );
	$sOldVersion = get_option( 'amazilonVersion' );
	if ( $sOldVersion === false || version_compare( $sOldVersion, '1.7.0', '<' ) ) {
		$aRoles = get_editable_roles();
		foreach ( $aRoles as $sRole => $aRoledata ) {
			$oRole = get_role( $sRole );
			if ( $oRole->has_cap( 'manage_options' ) ) {
				$oRole->add_cap( 'amazilon_change_options' );
				$oRole->add_cap( 'amazilon_use_statistics' );
				$oRole->add_cap( 'amazilon_use_generators' );
				$oRole->add_cap( 'amazilon_use_shortcodes_comments' );
				$oRole->add_cap( 'amazilon_modify_dynamic_widget' );
			} elseif ( $oRole->has_cap( 'edit_posts' ) ) {
				$oRole->remove_cap( 'amazilon_change_options' );
				$oRole->add_cap( 'amazilon_use_statistics' );
				$oRole->add_cap( 'amazilon_use_generators' );
				$oRole->add_cap( 'amazilon_use_shortcodes_comments' );
				$oRole->add_cap( 'amazilon_modify_dynamic_widget' );
			}
			if ( $sRole == 'administrator' ) {
				$oRole->add_cap( 'amazilon_manage_rights' );
			}
		}
		amazilonClearCache();
	}

	if ( $sOldVersion !== false ) {
		update_option( 'amazilonVersion', $__amazilonVersion );
	} else {
		add_option( 'amazilonVersion', $__amazilonVersion, '', false );
	}
}

function amazilonDeactivate() {
	amazilonClearCache();
	wp_clear_scheduled_hook( 'bowsx_wp_apn_cleanup' );
	wp_clear_scheduled_hook( 'bowsx_wp_apn_daily' );
}

function amazilonUninstall() {
	global $wpdb;
	if ( ( $config = get_option( 'bowsxWpApn' ) ) === false || ! isset( $config['dontDelete'] ) || $config['dontDelete'] != '1' ) {
		delete_option( 'bowsxWpApn' );
		$wpdb->query( 'DROP TABLE ' . $wpdb->prefix . 'wpapn_errors' );
	}
}

function amazilonAdminMenu() {
	global $__amazilonVersion;
	$hook = add_menu_page( __( 'Amazilon', 'amazilon' ), __( 'Amazilon', 'amazilon' ), 'amazilon_change_options',
		'amazilon-options', 'amazilonOptionsPage', plugins_url( 'gfx/amazilon-icon.png', __FILE__ ) );
	add_action( 'load-' . $hook, 'amazilonOnUpdateSettings' );
	add_submenu_page( 'amazilon-options', __( 'Settings', 'amazilon' ), __( 'Settings', 'amazilon' ),
		'amazilon_change_options', 'amazilon-options' );
	if ( current_user_can( 'amazilon_use_generators' ) ) {
		add_submenu_page( 'amazilon-options', __( 'Generators', 'amazilon' ), __( 'Generators', 'amazilon' ),
			'amazilon_use_generators', 'amazilon-generators', 'amazilonGeneratorsPage' );
		add_submenu_page( 'amazilon-options', __( 'ASIN Replacements', 'amazilon' ),
			__( 'ASIN Replacements', 'amazilon' ), 'amazilon_use_generators', 'amazilon-xchange',
			'amazilonXchangePage' );
	}
	if ( current_user_can( 'amazilon_use_statistics' ) ) {
		add_submenu_page( 'amazilon-options', __( 'Statistics', 'amazilon' ), __( 'Statistics', 'amazilon' ),
			'amazilon_use_statistics', 'amazilon-statistics', 'amazilonStatisticsPage' );
	}
	$aRights = array(
		'amazilon_manage_rights',
		'amazilon_change_options',
		'amazilon_use_generators',
		'amazilon_use_shortcodes_comments',
		'amazilon_use_statistics'
	);
	for ( $i = 0; $i < count( $aRights ); $i ++ ) {
		if ( current_user_can( $aRights[ $i ] ) ) {
			add_submenu_page( 'amazilon-options', __( 'Help', 'amazilon' ), __( 'Help', 'amazilon' ), $aRights[ $i ],
				'amazilon-help', 'amazilonHelpPage' );
			$i = count( $aRights );
		}
	}

	if ( current_user_can( 'amazilon_use_generators' ) ) {
		add_action( 'admin_bar_menu', 'amazilonAdminBar' );
	}

	if ( current_user_can( 'amazilon_change_options' ) ) {
		add_settings_section(
			'amazilon-options',
			__( 'Settings', 'amazilon' ),
			'amazilonRenderHeader',
			'amazilon-options'
		);
		add_settings_field(
			'licenseKey',
			__( 'Amazilon Lizenz', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'licenseKey'
			)
		);
		add_settings_field(
			'publicKey',
			__( 'Public-Key / Access Key ID', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'publicKey'
			)
		);
		add_settings_field(
			'privateKey',
			__( 'Private-Key / Secret Access Key', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'privateKey'
			)
		);
		add_settings_field(
			'associateTag',
			__( 'Associate-Tag', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'associateTag'
			)
		);
		add_settings_field(
			'iCaching',
			__( 'Cache duration', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'iCaching'
			)
		);
		add_settings_field(
			'useNofollow',
			__( 'use rel="nofollow" for links', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'useNofollow'
			)
		);
		add_settings_field(
			'useCurrencySymbol',
			__( 'Show currencies symbol', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'useCurrencySymbol'
			)
		);
		add_settings_field(
			'urlFormat',
			__( 'Format of links', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'urlFormat'
			)
		);
		add_settings_field(
			'bReportAsin',
			__( 'E-Mail notifications if ASIN ist not deliverable', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'bReportAsin'
			)
		);
		add_settings_field(
			'bStatisticsAutoclear',
			__( 'Automatically clear errors for each ASIN', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'bStatisticsAutoclear'
			)
		);
		add_settings_field(
			'sEventTracker',
			__( 'Clickevent tracken', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'sEventTracker'
			)
		);
		add_settings_field(
			'sEventTrackerInfo',
			__( 'Clickevent Info', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'sEventTrackerInfo'
			)
		);
		add_settings_field(
			'sTrackerEnabled',
			__( 'internal Click-Statistics', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'sTrackerEnabled'
			)
		);
		add_settings_field(
			'sHinweistext',
			__( 'Affiliate Note', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'sHinweistext'
			)
		);
		add_settings_field(
			'sAdnotice',
			__( 'Advertisement info', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'sAdnotice'
			)
		);
		add_settings_field(
			'stdImage',
			__( '"no image" Image', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'stdImage'
			)
		);
		add_settings_field(
			'stdImageMedium',
			__( '"no image" Image (medium)', 'amazilon' ) . ':',
			false,
			'amazilon-options',
			'hidden',
			array(
				'field' => 'stdImageMedium'
			)
		);
		add_settings_field(
			'stdImageLarge',
			__( '"no image" Image (large)', 'amazilon' ) . ':',
			false,
			'amazilon-options',
			'hidden',
			array(
				'field' => 'stdImageLarge'
			)
		);
		add_settings_field(
			'bRetrieveStars',
			__( 'Store product reviews', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'bRetrieveStars'
			)
		);
		add_settings_field(
			'dontDelete',
			__( 'Save settings ', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-options',
			array(
				'field' => 'dontDelete'
			)
		);


		add_settings_section(
			'amazilon-searchoptions',
			__( 'Search completion', 'amazilon' ),
			'amazilonRenderHeader',
			'amazilon-options'
		);
		add_settings_field(
			'bActive',
			__( 'Fill Search Results', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-searchoptions',
			array(
				'field' => 'bActive'
			)
		);
		add_settings_field(
			'bForce',
			__( 'Force Results', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-searchoptions',
			array(
				'field' => 'bForce'
			)
		);
		add_settings_field(
			'bInfobox',
			__( 'Display the infobox', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-searchoptions',
			array(
				'field' => 'bInfobox'
			)
		);
		add_settings_field(
			'bStars',
			__( 'Show Reviews', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-searchoptions',
			array(
				'field' => 'bStars'
			)
		);
		add_settings_field(
			'iProducts',
			__( 'Numer of products', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-searchoptions',
			array(
				'field' => 'iProducts'
			)
		);
		add_settings_field(
			'sPosition',
			__( 'Position of products', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-searchoptions',
			array(
				'field' => 'sPosition'
			)
		);
		add_settings_field(
			'sIndex',
			__( 'Area', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-searchoptions',
			array(
				'field' => 'sIndex'
			)
		);
		add_settings_field(
			'sTitle',
			__( 'Heading', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-searchoptions',
			array(
				'field' => 'sTitle'
			)
		);
		add_settings_field(
			'sSearchButtontext',
			__( 'Button label', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-searchoptions',
			array(
				'field' => 'sSearchButtontext'
			)
		);
		add_settings_field(
			'sSearchTag',
			__( 'Associate-Tag', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-searchoptions',
			array(
				'field' => 'sSearchTag'
			)
		);
		add_settings_field(
			'sSearchTemplate',
			__( 'Template', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-searchoptions',
			array(
				'field' => 'sSearchTemplate'
			)
		);

		add_settings_section(
			'amazilon-expertoptions',
			__( 'Expert Settings', 'amazilon' ),
			'amazilonRenderHeader',
			'amazilon-options'
		);
		add_settings_field(
			'sJquerySelectorSearch',
			__( 'jQuery Search Selector', 'amazilon' ) . ':',
			'amazilonRenderField',
			'amazilon-options',
			'amazilon-expertoptions',
			array(
				'field' => 'sJquerySelectorSearch'
			)
		);
		register_setting( 'amazilon-options', 'bowsxWpApn' );
	}
	if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array(
			'amazilon-options',
			'amazilon-generators',
			'amazilon-help',
			'amazilon-statistics',
			'amazilon-xchange'
		) ) ) {
		wp_enqueue_style( 'amazilon-admin', plugins_url( 'gfx/style-admin.css', __FILE__ ), array( 'dashicons' ),
			$__amazilonVersion );
	}
	wp_enqueue_style( 'amazilon-admin', plugins_url( 'gfx/style-admin-general.css', __FILE__ ), array( 'dashicons' ),
		$__amazilonVersion );
}

function amazilonXchangePage() {
	require plugin_dir_path( __FILE__ ) . '/inc/xchange.php';

	return;
}

function amazilonGeneratorsPage() {
	wp_enqueue_script( 'clipboardjs', plugins_url( 'gfx/js/clipboard.min.js', __FILE__ ), array( 'amazilon-lib-admin' ),
		'1.8.0' );
	if ( isset( $_GET['mini'] ) && $_GET['mini'] == 'true' ) {
		echo '<style media="all">#adminmenumain,#wpadminbar,#wpfooter,.amazilon-nav,.update-nag{display:none}#wpcontent{margin:0}#wpbody-content{padding-bottom: 1em;}html.wp-toolbar{padding:0;}.auto-fold #wpcontent,.auto-fold #wpfooter{margin:0;}</style>';
	}
	require plugin_dir_path( __FILE__ ) . '/inc/generators.php';

	return;
}

function amazilonHelpPage() {
	require plugin_dir_path( __FILE__ ) . '/inc/help.php';

	return;
}

function amazilonStatisticsDownload() {
	require_once dirname( __FILE__ ) . '/inc/amazilonListTableClicks.inc.php';
	$sHost     = parse_url( get_home_url(), PHP_URL_HOST );
	$sFilename = 'Amazilon-Export-' . $sHost . '.csv';

	$amazilonListTableClicks = new amazilonListTableClicks();
	$amazilonListTableClicks->prepare_items();
	header( 'Content-type: text/csv; charset=UTF-8' );
	header( 'Content-Disposition: attachment; filename="' . $sFilename . '"' );
	header( 'Expires: 0' );
	header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
	$fp = fopen( 'php://output', 'w' );
	fputs( $fp, chr( 0xEF ) . chr( 0xBB ) . chr( 0xBF ) );
	$aCols    = array(
		'clicks'  => __( 'Clicks', 'amazilon' ),
		'asin'    => __( 'ASIN', 'amazilon' ),
		'sc'      => __( 'Shortcode', 'amazilon' ),
		'tag'     => __( 'Associate-Tag', 'amazilon' ),
		'referer' => __( 'URL', 'amazilon' ),
		'title'   => __( 'Product', 'amazilon' )
	);
	$aColkeys = array_keys( $aCols );
	fputcsv( $fp, array_values( $aCols ), ';' );
	for ( $iRow = 0; $iRow < count( $amazilonListTableClicks->items ); $iRow ++ ) {
		$aRow = &$amazilonListTableClicks->items[ $iRow ];
		$aOut = array();
		for ( $iCol = 0; $iCol < count( $aColkeys ); $iCol ++ ) {
			$aOut[] = $aRow[ $aColkeys[ $iCol ] ];
		}
		fputcsv( $fp, $aOut, ';' );
	}
	fclose( $fp );
	die();
}

function wporg_current_screen_example( $oScreen ) {
	if ( $oScreen->base == 'amazilon_page_amazilon-statistics' && isset( $_REQUEST['amazilon-clicks-download'] ) ) {
		amazilonStatisticsDownload();
	}
}

add_action( 'current_screen', 'wporg_current_screen_example' );

function amazilonStatisticsPage() {
	if ( isset( $_GET['page'] ) ) {
		switch ( $_GET['page'] ) {
			case 'amazilon-statistics':
				require plugin_dir_path( __FILE__ ) . '/inc/statistics.php';
				break;
		}
	}

	return;
}

function amazilonOptionsPage() {
	global $__amazilonVersion;
	wp_enqueue_style( 'amazilon', plugins_url( 'gfx/style.css', __FILE__ ), array( 'dashicons' ), $__amazilonVersion );
	wp_enqueue_script( 'jquery' );
	wp_enqueue_media();

	echo '<script type="text/javascript">
    jQuery(document).ready(function($){
        $(\'#stdImage-upload-btn\').click(function(e) {
            e.preventDefault();
            var image = wp.media({ title: \'' . __( 'Upload Image', 'amazilon' ) . '\', multiple: false })
            .open()
            .on(\'select\', function(e){
                var oImg = image.state().get(\'selection\').first();
                var sImgUrl = oImg.toJSON().url;
                $(\'#bowsxWpApn-stdImage\').val(sImgUrl).trigger(\'change\');
            });
        });
        jQuery(\'#bowsxWpApn-stdImage\').change(function() {
            if ( this.value != \'\' )
            {
                jQuery(\'#img-stdImage\').attr(\'src\', this.value);
            } else {
                jQuery(\'#img-stdImage\').attr(\'src\', \'' . esc_attr( plugins_url( 'gfx/no-pic-75.png', __FILE__ ) ) . '\');
            }
        });
        jQuery(\'#stdImage-x-btn\').click(function() {
            jQuery(\'#bowsxWpApn-stdImage\').val(\'\').trigger(\'change\');
        });

        $(\'#stdImageMedium-upload-btn\').click(function(e) {
            e.preventDefault();
            var image = wp.media({ title: \'' . __( 'Upload Image', 'amazilon' ) . '\', multiple: false })
            .open()
            .on(\'select\', function(e){
                var oImg = image.state().get(\'selection\').first();
                var sImgUrl = oImg.toJSON().url;
                $(\'#bowsxWpApn-stdImageMedium\').val(sImgUrl).trigger(\'change\');
            });
        });
        jQuery(\'#bowsxWpApn-stdImageMedium\').change(function() {
            if ( this.value != \'\' )
            {
                jQuery(\'#img-stdImageMedium\').attr(\'src\', this.value);
            } else {
                jQuery(\'#img-stdImageMedium\').attr(\'src\', \'' . esc_attr( plugins_url( 'gfx/no-pic-160.png',
			__FILE__ ) ) . '\');
            }
        });
        jQuery(\'#stdImageMedium-x-btn\').click(function() {
            jQuery(\'#bowsxWpApn-stdImageMedium\').val(\'\').trigger(\'change\');
        });

        $(\'#stdImageLarge-upload-btn\').click(function(e) {
            e.preventDefault();
            var image = wp.media({ title: \'' . __( 'Upload Image', 'amazilon' ) . '\', multiple: false })
            .open()
            .on(\'select\', function(e){
                var oImg = image.state().get(\'selection\').first();
                var sImgUrl = oImg.toJSON().url;
                $(\'#bowsxWpApn-stdImageLarge\').val(sImgUrl).trigger(\'change\');
            });
        });
        jQuery(\'#bowsxWpApn-stdImageLarge\').change(function() {
            if ( this.value != \'\' )
            {
                jQuery(\'#img-stdImageLarge\').attr(\'src\', this.value);
            } else {
                jQuery(\'#img-stdImageLarge\').attr(\'src\', \'' . esc_attr( plugins_url( 'gfx/no-pic-500.png',
			__FILE__ ) ) . '\');
            }
        });
        jQuery(\'#stdImageLarge-x-btn\').click(function() {
            jQuery(\'#bowsxWpApn-stdImageLarge\').val(\'\').trigger(\'change\');
        });
    });
    </script>';

	require dirname( __FILE__ ) . '/inc/options.php';
}

function amazilonRenderHeader( $args ) {
	if ( $args['id'] != 'amazilon-options' ) {
		return;
	}
}

function amazilonRenderField( $args ) {
	$config = get_option( 'bowsxWpApn' );
	if ( ! isset( $config[ $args['field'] ] ) ) {
		switch ( $args['field'] ) {
			default:
				$config[ $args['field'] ] = '';
		}
	}

	switch ( $args['field'] ) {
		case 'licenseKey':
			echo '<input type="text" style="width: 30em;" name="bowsxWpApn[licenseKey]" id="bowsxWpApn[licenseKey]" value="' . esc_attr( trim( $config['licenseKey'] ) ) . '" />';
			break;
		case 'publicKey':
			echo '<input type="text" style="width: 30em;" name="bowsxWpApn[publicKey]" id="bowsxWpApn[publicKey]" value="' . esc_attr( trim( $config['publicKey'] ) ) . '" /><br /><small>' . __( 'Register for "Product Advertising API"/ insight into data',
					'amazilon' ) . ': <a href="' . __( 'https://partnernet.amazon.de/gp/advertising/api/registration/welcome.html',
					'amazilon' ) . '" target="_blank">' . __( 'https://partnernet.amazon.de/gp/advertising/api/registration/welcome.html',
					'amazilon' ) . '</a></small>';
			break;
		case 'privateKey':
			echo '<input type="password" style="width: 30em;" name="bowsxWpApn[privateKey]" id="bowsxWpApn[privateKey]" value="' . esc_attr( $config['privateKey'] ) . '" /><br /><small>' . __( 'Register for "Product Advertising API"/ insight into data',
					'amazilon' ) . ': <a href="' . __( 'https://partnernet.amazon.de/gp/advertising/api/registration/welcome.html',
					'amazilon' ) . '" target="_blank">' . __( 'https://partnernet.amazon.de/gp/advertising/api/registration/welcome.html',
					'amazilon' ) . '</a></small>';
			break;
		case 'associateTag':
			echo '<input type="text" style="width: 10em;" placeholder="example-21" name="bowsxWpApn[associateTag]" id="bowsxWpApn[associateTag]" value="' . esc_attr( $config['associateTag'] ) . '" /><br /><small>' . __( 'This is the standard tag and is absolutely necessary for the API retrieval.',
					'amazilon' ) . '</small>';
			break;
		case 'useCurrencySymbol':
			echo '<input type="checkbox" name="bowsxWpApn[useCurrencySymbol]" id="bowsxWpApn[useCurrencySymbol]" value="1" ';
			checked( $config['useCurrencySymbol'], 1 );
			echo ' /> <small>' . __( 'If this is activ the "EUR" will be replaced with &euro; next to the article price',
					'amazilon' ) . '</small>';
			break;
		case 'useNofollow':
			echo '<input type="checkbox" name="bowsxWpApn[useNofollow]" id="bowsxWpApn[useNofollow]" value="1" ';
			checked( $config['useNofollow'], 1 );
			echo ' />';
			break;
		case 'bInfobox':
			echo '<input type="checkbox" name="bowsxWpApn[search][bInfobox]" id="bowsxWpApn[search][bInfobox]" value="1" ';
			checked( @$config['search']['bInfobox'], 1 );
			echo ' />';
			break;
		case 'bStars':
			echo '<input type="checkbox" name="bowsxWpApn[search][bStars]" id="bowsxWpApn[search][bStars]" value="1" ';
			checked( @$config['search']['bStars'], 1 );
			echo ' /> <small>' . sprintf( __( 'Only used if <b>%s</b> is activated!', 'amazilon' ),
					__( 'Store product reviews', 'amazilon' ) ) . '</small>';
			break;
		case 'bActive':
			echo '<input type="checkbox" name="bowsxWpApn[search][bActive]" id="bowsxWpApn[search][bActive]" value="1" ';
			checked( @$config['search']['bActive'], 1 );
			echo ' /> <small>' . __( 'Fill empty Search Results with Amazon Products', 'amazilon' ) . '</small>';
			break;
		case 'bForce':
			echo '<input type="checkbox" name="bowsxWpApn[search][bForce]" id="bowsxWpApn[search][bForce]" value="1" ';
			checked( @$config['search']['bForce'], 1 );
			echo ' /> <small>' . __( 'Show Search Results for Amazon Products even if Blog Results are found.',
					'amazilon' ) . '</small>';
			break;
		case 'urlFormat':
			echo '<select name="bowsxWpApn[urlFormat]" id="bowsxWpApn[urlFormat]">';
			echo '<option value="0"';
			selected( $config['urlFormat'], 0 );
			echo '>' . __( 'API-standard (really long URL)', 'amazilon' ) . '</option>';
			echo '<option value="1"';
			selected( $config['urlFormat'], 1 );
			echo '>' . __( 'https://www.amazon.de/exec/obidos/ASIN/B07PHPXHQS/example-21', 'amazilon' ) . '</option>';
			echo '<option value="2"';
			selected( $config['urlFormat'], 2 );
			echo '>' . __( 'https://www.amazon.de/dp/B07PHPXHQS/?tag=example-21', 'amazilon' ) . '</option>';
			echo '</select>';
			echo '<br /><small>' . __( 'The API of Amazon has an access limit, which depens on the generated volume of sales through the API links. <br />When incorporating many Amazon products "API stadard" should be used, because an increase of the access limit is only through sales over API standard links achievable.',
					'amazilon' ) . '</small>';
			break;
		case 'iCaching':
			echo '<select name="bowsxWpApn[iCaching]" id="bowsxWpApn[iCaching]">';
			echo '<option value="86400"';
			selected( $config['iCaching'], 86400 );
			echo '>' . sprintf( _n( '%d hour', '%d hours', 24, 'amazilon' ), 24 ) . '</option>';
			echo '<option value="57600"';
			selected( $config['iCaching'], 57600 );
			echo '>' . sprintf( _n( '%d hour', '%d hours', 16, 'amazilon' ), 16 ) . '</option>';
			echo '<option value="28800"';
			selected( $config['iCaching'], 28800 );
			echo '>' . sprintf( _n( '%d hour', '%d hours', 8, 'amazilon' ), 8 ) . '</option>';
			echo '<option value="14400"';
			selected( $config['iCaching'], 14400 );
			echo '>' . sprintf( _n( '%d hour', '%d hours', 4, 'amazilon' ), 4 ) . '</option>';
			echo '<option value="7200"';
			selected( $config['iCaching'], 7200 );
			echo '>' . sprintf( _n( '%d hour', '%d hours', 2, 'amazilon' ), 2 ) . '</option>';
			echo '<option value="3600"';
			selected( $config['iCaching'], 3600 );
			echo '>' . sprintf( _n( '%d hour', '%d hours', 1, 'amazilon' ), 1 ) . '</option>';
			echo '</select>';
			echo '<br /><small>' . __( 'The API of Amazon has an access limit, which depens on the generated volume of sales through the API links. A higher caching time reduces the inquiry volume. We reccomend a value of 16 or 24 hours.',
					'amazilon' ) . '</small>';
			break;
		case 'iProducts':
			echo '<select name="bowsxWpApn[search][iProducts]" id="bowsxWpApn[search][iProducts]">';
			if ( ! isset( $config['search']['iProducts'] ) ) {
				$config['search']['iProducts'] = 3;
			}
			for ( $i = 1; $i <= 10; $i ++ ) {
				echo '<option value="' . $i . '"';
				selected( $config['search']['iProducts'], $i );
				echo '>' . sprintf( _n( '%d product', '%d products', $i, 'amazilon' ), $i ) . '</option>';
			}
			echo '</select>';
			break;
		case 'sIndex':
			echo '<select name="bowsxWpApn[search][sIndex]" id="bowsxWpApn[search][sIndex]">';
			if ( ! isset( $config['search']['sIndex'] ) ) {
				$config['search']['sIndex'] = 'All';
			}
			$sIndexes = amazilonGetSearchindexes( 'de' );
			foreach ( $sIndexes as $sIndex => $aEntry ) {
				echo '<option value="' . esc_attr( $sIndex ) . '"';
				selected( $config['search']['sIndex'], $sIndex );
				echo '>' . esc_attr( $aEntry['title'] ) . '</option>';
			}
			echo '</select>';
			break;
		case 'sTitle':
			echo '<input type="text" style="width: 30em;" name="bowsxWpApn[search][sTitle]" id="bowsxWpApn[search][sTitle]" value="' . esc_attr( $config['search']['sTitle'] ) . '" placeholder="' . __( 'e.g.: %term% on Amazon',
					'amazilon' ) . '" /><br /><small>' . __( 'Shown above product listing. Use %term% as placeholder for current search query.',
					'amazilon' ) . '</small>';
			break;
		case 'sSearchButtontext':
			echo '<input type="text" style="width: 30em;" name="bowsxWpApn[search][sSearchButtontext]" id="bowsxWpApn[search][sSearchButtontext]" value="' . esc_attr( $config['search']['sSearchButtontext'] ) . '" placeholder="' . __( 'e.g.: Buy now on Amazon',
					'amazilon' ) . '" />';
			break;
		case 'sSearchTag':
			echo '<input type="text" style="width: 10em;" name="bowsxWpApn[search][sTag]" id="bowsxWpApn[search][sTag]" value="' . esc_attr( $config['search']['sTag'] ) . '" placeholder="example-21" /><br /><small>' . __( 'This is the tag to be used for search results page only. Leave empty if you want to use the standard tag.',
					'amazilon' ) . '</small>';
			break;
		case 'sSearchTemplate':
			if ( ! isset( $config['search']['sSearchTemplate'] ) ) {
				$config['search']['sSearchTemplate'] = 'tpl-2';
			}
			echo '<select name="bowsxWpApn[search][sSearchTemplate]" id="bowsxWpApn[search][sSearchTemplate]">';
			for ( $i = 1; $i < 8; $i ++ ) {
				echo '<option value="tpl-' . $i . '"';
				selected( $config['search']['sSearchTemplate'], 'tpl-' . $i );
				echo '>' . sprintf( __( 'Layout %s', 'amazilon' ), $i );
				if ( in_array( $i, array( 2, 5, 6, 7 ) ) ) {
					echo '*';
				}
				echo '</option>';
			}
			echo '<option value="vergleich"' . selected( $config['search']['sSearchTemplate'],
					'vergleich' ) . '>' . __( 'Comparison box',
					'amazilon' ) . '*</option><option value="vergleich2"' . selected( $config['search']['sSearchTemplate'],
					'vergleich2' ) . '>' . __( 'Comparison table',
					'amazilon' ) . '*</option></select><br /><small>' . __( 'Layouts with a star (*) expand to full width.',
					'amazilon' ) . '</small>';
			break;
		case 'sPosition':
			echo '<select name="bowsxWpApn[search][sPosition]" id="bowsxWpApn[search][sPosition]">';
			echo '<option value="before"';
			selected( $config['search']['sPosition'], 'before' );
			echo '>' . __( 'before searchbox', 'amazilon' ) . '</option>';
			echo '<option value="after"';
			selected( $config['search']['sPosition'], 'after' );
			echo '>' . __( 'after searchbox', 'amazilon' ) . '</option>';
			echo '</select>';
			break;
		case 'sEventTracker':
			echo '<select name="bowsxWpApn[sEventTracker]" id="bowsxWpApn[sEventTracker]">';
			echo '<option value="none"';
			selected( $config['sEventTracker'], 'none' );
			echo '>- ' . __( 'do not track', 'amazilon' ) . ' -</option>';
			echo '<option value="gajs"';
			selected( $config['sEventTracker'], 'gajs' );
			echo '>' . __( 'Google Analytics (ga.js)', 'amazilon' ) . '</option>';
			echo '<option value="analyticsjs"';
			selected( $config['sEventTracker'], 'analyticsjs' );
			echo '>' . __( 'Universal Analytics (analytics.js)', 'amazilon' ) . '</option>';
			echo '</select>';
			break;
		case 'sEventTrackerInfo':
			echo '<select name="bowsxWpApn[sEventTrackerInfo]" id="bowsxWpApn[sEventTrackerInfo]">';
			echo '<option value="asin"';
			selected( $config['sEventTrackerInfo'], 'asin' );
			echo '>' . __( 'ASIN', 'amazilon' ) . '</option>';
			echo '<option value="productname"';
			selected( $config['sEventTrackerInfo'], 'productname' );
			echo '>' . __( 'Product Name', 'amazilon' ) . '</option>';
			echo '</select>';
			break;
		case 'sTrackerEnabled':
			echo '<input type="checkbox" name="bowsxWpApn[sTrackerEnabled]" id="bowsxWpApn[sTrackerEnabled]" value="1" ';
			checked( $config['sTrackerEnabled'], 1 );
			echo ' />';
			break;
		case 'dontDelete':
			echo '<input type="checkbox" name="bowsxWpApn[dontDelete]" id="bowsxWpApn[dontDelete]" value="1" ';
			checked( $config['dontDelete'], 1 );
			echo ' /> <small>' . __( 'If this option is activated, all plugin settings will be saved when deactivating or deinstalling the plugin.',
					'amazilon' ) . '</small>';
			break;
		case 'bReportAsin':
			echo '<input type="checkbox" name="bowsxWpApn[bReportAsin]" id="bowsxWpApn[bReportAsin]" value="1" ';
			checked( $config['bReportAsin'], 1 );
			echo ' /> <small>' . __( 'If this option is activated, a daily overview with not deliverable ASINs will be sent to the admin via email. ',
					'amazilon' ) . '</small>';
			break;
		case 'bStatisticsAutoclear':
			echo '<input type="checkbox" name="bowsxWpApn[bStatisticsAutoclear]" id="bowsxWpApn[bStatisticsAutoclear]" value="1" ';
			checked( $config['bStatisticsAutoclear'], 1 );
			echo ' /> <small>' . __( 'If this option is activated, errors for ASINs will be cleared automatically when the ASINs information are renewed. ',
					'amazilon' ) . '</small>';
			break;
		case 'bRetrieveStars':
			echo '<input type="checkbox" name="bowsxWpApn[bRetrieveStars]" id="bowsxWpApn[bRetrieveStars]" value="1" ';
			checked( $config['bRetrieveStars'], 1 );
			echo ' /><br /><small style="color:#D00;">' . __( 'Warning: Reading and (temporary) saving of the product rating doesn\'t match the reqular API terms of use!<br /> Using this function will happen at one\'s own responsibility. ',
					'amazilon' ) . '</small>';
			break;
		case 'sHinweistext':
			echo '<input type="text" style="width: 40em;" name="bowsxWpApn[sHinweistext]" id="bowsxWpApn[sHinweistext]" value="' . esc_attr( $config['sHinweistext'] ) . '" placeholder="' . esc_attr( __( 'These information are advertising referrals to amazon.',
					'amazilon' ) ) . '" />';
			break;
		case 'stdImage':
			_e( 'If the API contains no image, you can set your own image as fallback.', 'amazilon' );
			echo '<br />';
			echo '<div style="display:inline-block; vertical-align: bottom; padding: 1em;">';
			echo '<img src="' . esc_attr( ( isset( $config['stdImage'] ) && ! empty( $config['stdImage'] ) ) ? $config['stdImage'] : plugins_url( 'gfx/no-pic-75.png',
					__FILE__ ) ) . '" style="max-width: 75px; max-height: 75px;" id="img-stdImage" /><br />';
			echo '<input type="hidden" name="bowsxWpApn[stdImage]" id="bowsxWpApn-stdImage" value="' . esc_attr( $config['stdImage'] ) . '" />';
			echo '<input type="button" name="upload-btn" id="stdImage-upload-btn" class="button-secondary" value="' . __( 'Select' ) . '" />';
			echo '<input type="button" name="x-btn" id="stdImage-x-btn" class="button-secondary" value="X" />';
			echo '<br /><small>' . __( 'Optimal size 75x75 pixels', 'amazilon' ) . '</small>';
			echo '</div>';

			echo '<div style="display:inline-block; vertical-align: bottom; padding: 1em;">';
			echo '<img src="' . esc_attr( ( isset( $config['stdImageMedium'] ) && ! empty( $config['stdImageMedium'] ) ) ? $config['stdImageMedium'] : plugins_url( 'gfx/no-pic-160.png',
					__FILE__ ) ) . '" style="max-width: 160px; max-height: 160px;" id="img-stdImageMedium" /><br />';
			echo '<input type="hidden" name="bowsxWpApn[stdImageMedium]" id="bowsxWpApn-stdImageMedium" value="' . esc_attr( $config['stdImageMedium'] ) . '" />';
			echo '<input type="button" name="upload-btn" id="stdImageMedium-upload-btn" class="button-secondary" value="' . __( 'Select' ) . '" />';
			echo '<input type="button" name="x-btn" id="stdImageMedium-x-btn" class="button-secondary" value="X" />';
			echo '<br /><small>' . __( 'Optimal size 160x160 pixels', 'amazilon' ) . '</small>';
			echo '</div>';

			echo '<div style="display:inline-block; vertical-align: bottom; padding: 1em;">';
			echo '<img src="' . esc_attr( ( isset( $config['stdImageLarge'] ) && ! empty( $config['stdImageLarge'] ) ) ? $config['stdImageLarge'] : plugins_url( 'gfx/no-pic-160.png',
					__FILE__ ) ) . '" style="max-width: 250px; max-height: 250px;" id="img-stdImageLarge" /><br />';
			echo '<input type="hidden" name="bowsxWpApn[stdImageLarge]" id="bowsxWpApn-stdImageLarge" value="' . esc_attr( $config['stdImageLarge'] ) . '" />';
			echo '<input type="button" name="upload-btn" id="stdImageLarge-upload-btn" class="button-secondary" value="' . __( 'Select' ) . '" />';
			echo '<input type="button" name="x-btn" id="stdImageLarge-x-btn" class="button-secondary" value="X" />';
			echo '<br /><small>' . __( 'Optimal size 500x500 pixels',
					'amazilon' ) . ' | ' . __( 'Example above scaled to max. 250x250 pixels!',
					'amazilon' ) . '</small>';
			echo '</div>';
			break;
		case 'sAdnotice':
			echo '<input type="text" style="width: 40em;" name="bowsxWpApn[sAdnotice]" id="bowsxWpApn[sAdnotice]" value="' . esc_attr( $config['sAdnotice'] ) . '" placeholder="' . esc_attr( __( 'empty for none otherwise for example: Advertisement',
					'amazilon' ) ) . '" /><br /><small>' . __( 'Info shown to identify integrations as advertisement. Leave empty to hide.',
					'amazilon' ) . '</small>';
			break;
		case 'sJquerySelectorSearch':
			echo '<input type="text" style="width: 40em;" name="bowsxWpApn[search][sJquerySelector]" id="bowsxWpApn[search][sJquerySelector]" value="' . esc_attr( $config['search']['sJquerySelector'] ) . '" placeholder="' . esc_attr( __( 'e.g.: #content .inner',
					'amazilon' ) ) . '" /><br /><small>' . sprintf( __( 'jQuery selector to find content-element containing search results and search input field. Used for automatic search completion. See <a href="%s" target="_blank">jQuery API Documentation</a> for usage instructions.',
					'amazilon' ), 'https://api.jquery.com/category/selectors/' ) . '</small>';
			break;
	}
}

add_action( 'init', 'amazilonInit' );
add_action( 'admin_init', 'amazilonAdminInit' );
add_action( 'admin_menu', 'amazilonAdminMenu' );
add_action( 'bowsx_wp_apn_cleanup', 'amazilonCleanup' );
add_action( 'bowsx_wp_apn_daily', 'amazilonDaily' );
add_action( 'admin_notices', 'amazilonAdminNotices' );
add_action( 'widgets_init', 'amazilonWidgets' );
register_activation_hook( __FILE__, 'amazilonInstall' );
register_uninstall_hook( __FILE__, 'amazilonUninstall' );
register_deactivation_hook( __FILE__, 'amazilonDeactivate' );
register_activation_hook( __FILE__, 'amazilonActivate' );

function amazilonShortCodeAmazilon( $atts, $content ) {
	global $wpdb;
	$args = shortcode_atts(
		array(
			'id' => 0
		),
		$atts
	);

	if ( (int) $args['id'] < 1 ) {
		return '';
	}
	$oRow = $wpdb->get_row( $wpdb->prepare( 'SELECT code FROM ' . $wpdb->prefix . 'amazilon_scodes WHERE id=%d',
		$args['id'] ) );
	if ( is_null( $oRow ) ) {
		return '';
	}

	return do_shortcode( $oRow->code );
}

function amazilonShortCodeAmazilonSearch( $atts, $content ) {
	global $wpdb;
	$args = shortcode_atts(
		array(
			'keyword' => '',
			'entries' => 3
		),
		$atts
	);

	if ( (int) $args['entries'] < 1 || (int) $args['entries'] > 10 ) {
		$args['entries'] = 3;
	}

	if ( empty( $args['keyword'] ) ) {
		return '';
	}

	$sReturn = '';
	$sParams = '';
	foreach ( $atts as $sKey => $sVal ) {
		if ( in_array( $sKey, array( 'asin' ) ) ) {
			continue;
		}
		$sParams .= ' ' . $sKey . '="' . esc_attr( $sVal ) . '"';
	}

	$aItems = amazilonItemSearch( $args['keyword'], 'All', $args['entries'] );
	for ( $iItem = 0; $iItem < count( $aItems ) && $iItem < $args['entries']; $iItem ++ ) {
		$sReturn .= do_shortcode( '[apn asin="' . $aItems[ $iItem ]['asin'] . '"' . $sParams . ']' );
	}

	return $sReturn;
}

function amazilonShortCode( $atts, $content ) {
	global $__amazilonCurrentShortcode, $__amazilonNoAutoVariant;
	$config = get_option( 'bowsxWpApn' );
	if ( ( $config = get_option( 'bowsxWpApn' ) ) === false || empty( $config['publicKey'] ) || empty( $config['privateKey'] ) || empty( $config['associateTag'] ) ) {
		return '';
	}
	$args = shortcode_atts(
		array(
			'asin'       => '',
			'typ'        => '',
			'true'       => false,
			'false'      => false,
			'tag'        => trim( $config['associateTag'] ),
			'rel'        => false,
			'template'   => '',
			'max'        => 0,
			'node'       => '',
			'_master'    => '',
			'novariants' => 0,
		),
		$atts
	);
	if ( (int) $args['novariants'] == 1 ) {
		$__amazilonNoAutoVariant = true;
	} else {
		$__amazilonNoAutoVariant = false;
	}
	$args['asin'] = trim( $args['asin'] );
	$args['tag']  = trim( $args['tag'] );
	if ( empty( $args['_master'] ) ) {
		$args['_master'] = $args['typ'];
	} else {
		$args['_master'] .= '|' . $args['typ'];
	}


	/**
	 * Associate-Tag Filter für ShortCodes.
	 *
	 * Filter vor Verarbeitung eines ShortCodes.
	 *
	 * @param string $args ['tag'] Associate-Tag
	 * @param string $args ['typ'] aufgerufener Shortcode-Typ
	 * @param string $args ['asin'] Übergebene ASIN
	 *
	 * @since 1.7.0.3
	 *
	 */
	$args['tag'] = apply_filters( 'amazilon_sc_tag', $args['tag'], $args['typ'], $args['asin'] );

	$aNoASIN = array( 'infobox', 'bestseller', 'bestsellers' );

	if ( empty( $args['typ'] ) || ( empty( $args['asin'] ) && ! in_array( $args['typ'], $aNoASIN ) ) ) {
		return '';
	}
	$__amazilonCurrentShortcode = $args['typ'];
	$aItem                      = false;
	if ( strlen( $args['asin'] ) == 10 && substr_count( $args['asin'], ',' ) < 1 ) {
		$aItem = amazilonGetItem( substr( $args['asin'], 0, 10 ) );
	} elseif ( strlen( $args['asin'] ) > 10 ) {
		$aItem = array();
		preg_match_all( '=([0-9a-z]+)(!?)(,|$)=Usi', $args['asin'], $aMatches );
		for ( $i = 0; $i < count( $aMatches[0] ); $i ++ ) {
			if ( ! empty( $aMatches[1][ $i ] ) && strlen( $aMatches[1][ $i ] ) == 10 ) {
				if ( ( $aItemTmp = amazilonGetItem( $aMatches[1][ $i ] ) ) !== false ) {
					$aItem[] = array( 'item' => $aItemTmp, 'special' => $aMatches[2][ $i ] );
				}
			}
		}
	}

	if ( ! in_array( $args['typ'], $aNoASIN ) && $aItem === false ) {
		if ( $args['false'] !== false ) {
			return $args['false'];
		}

		return __( 'N/A', 'amazilon' );
	}

	switch ( $args['typ'] ) {
		case 'feature':
			if ( ! isset( $atts['tpl-num'] ) || (int) $atts['tpl-num'] > 5 || (int) $atts['tpl-num'] < 1 ) {
				$atts['tpl-num'] = 1;
			}
			if ( ! isset ( $aItem['aFeatures'][ $atts['tpl-num'] - 1 ] ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return __( 'N/A', 'amazilon' );
			}
			if ( (int) $args['max'] > 0 ) {
				$aItem['aFeatures'][ $atts['tpl-num'] - 1 ] = amazilonStrShorter( $aItem['aFeatures'][ $atts['tpl-num'] - 1 ],
					(int) $args['max'] );
			}

			return $aItem['aFeatures'][ $atts['tpl-num'] - 1 ];
			break;
		case 'features':
			if ( ! isset( $atts['tpl-count'] ) || (int) $atts['tpl-count'] > 5 || (int) $atts['tpl-count'] < 1 ) {
				$atts['tpl-count'] = 5;
			}
			$sReturn = '';
			if ( ! isset( $aItem['aFeatures'] ) || count( $aItem['aFeatures'] ) == 0 ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return '';
			}
			$sReturn = '<ul class="amazilon-features">';
			for ( $i = 1; $i <= $atts['tpl-count'] && $i <= count( $aItem['aFeatures'] ); $i ++ ) {
				$sReturn .= '<li class="amazilon-feature amazilon-feature' . $i . '">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="feature" tpl-num="' . $i . '" max="' . esc_attr( $args['max'] ) . '"]</li>';
			}
			$sReturn .= '</ul>';

			return do_shortcode( $sReturn );
			break;
		case 'titel':
			if ( isset( $atts['tpl-pname'] ) && ! empty( $atts['tpl-pname'] ) ) {
				$aItem['title'] = trim( $atts['tpl-pname'] );
			}
			if ( ! isset( $aItem['title'] ) || empty( $aItem['title'] ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return __( 'N/A', 'amazilon' );
			}
			if ( (int) $args['max'] > 0 ) {
				$aItem['title'] = amazilonStrShorter( $aItem['title'], (int) $args['max'] );
			}

			return $aItem['title'];
			break;
		case 'preis':
			if ( ! isset( $aItem['preis']['preis'] ) || $aItem['preis']['preis'] === false ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return __( 'N/A', 'amazilon' );
			}

			return number_format_i18n( $aItem['preis']['preis'] / 100,
					2 ) . ' ' . amazilonMakeCurrency( $aItem['preis']['waehrung'] );
			break;
		case 'rabatt':
			if ( ! isset( $aItem['preis']['discount'] ) || $aItem['preis']['discount'] === false || ! isset( $aItem['preis']['preis'] ) || $aItem['preis']['preis'] === false ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return '';
			}
			if ( $args['template'] == '%' ) {
				return number_format_i18n( ( function_exists( 'bcdiv' ) ? bcdiv( bcmul( $aItem['preis']['discount'],
						100, 8 ), $aItem['streichpreis']['preis'],
						8 ) : $aItem['preis']['discount'] * 100 / $aItem['streichpreis']['preis'] ) ) . ' %';
			}

			return number_format_i18n( $aItem['preis']['discount'] / 100,
					2 ) . ' ' . amazilonMakeCurrency( $aItem['preis']['waehrung'] );
			break;
		case 'bewertung':
			if ( ! isset( $config['bRetrieveStars'] ) || (int) $config['bRetrieveStars'] != 1 || ! isset( $aItem['fReviewsStars'] ) || bccomp( $aItem['fReviewsStars'],
					'5.0', 1 ) > 0 || bccomp( '0.0', $aItem['fReviewsStars'], 1 ) >= 0 ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return '';
			}
			if ( $args['template'] == 'text' ) {
				return sprintf( __( '%s of 5 Stars', 'amazilon' ), number_format_i18n( $aItem['fReviewsStars'], 1 ) );
			}

			return '<img src="' . plugins_url( 'gfx/sterne-' . sprintf( '%.1F',
						bcdiv( sprintf( '%.0F', bcmul( $aItem['fReviewsStars'], '2.0', 1 ) ), '2.0', 1 ) ) . '.png',
					__FILE__ ) . '" alt="' . esc_attr( sprintf( __( '%s of 5 Stars', 'amazilon' ),
					number_format_i18n( $aItem['fReviewsStars'],
						1 ) ) ) . '" title="' . esc_attr( sprintf( __( '%s of 5 Stars', 'amazilon' ),
					number_format_i18n( $aItem['fReviewsStars'], 1 ) ) ) . '" />';
			break;
		case 'anzahlbewertungen':
			if ( ! isset( $config['bRetrieveStars'] ) || (int) $config['bRetrieveStars'] != 1 || ! isset( $aItem['iReviewsCount'] ) || $aItem['iReviewsCount'] < 1 ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return 'N/A';
			}
			$iRating = number_format_i18n( $aItem['iReviewsCount'], 0 );

			return isset( $atts['tpl-format'] ) ? sprintf( $atts['tpl-format'], $iRating ) : $iRating;
			break;
		case 'vergleich':
			if ( ! is_array( $aItem ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return '';
			}
			$sReturn = '<div class="amazilon-compare">';
			if ( ! isset( $aItem[0] ) ) {
				$aItem = array( array( 'item' => $aItem, 'special' => '' ) );
			}
			for ( $i = 0; $i < count( $aItem ); $i ++ ) {
				$aCurrentItem = $aItem[ $i ]['item'];
				if ( empty( $aCurrentItem['asin'] ) || strlen( $aCurrentItem['asin'] ) != 10 ) {
					continue;
				}
				$sCurrent = '
						<div class="amazilon-col amazilon-col-' . $i . ( $aItem[ $i ]['special'] == '!' ? ' amazilon-highlight' : '' ) . '" style="width: calc(100% / ' . count( $aItem ) . ' - 2px);">
							' . ( isset( $atts['tpl-label'] ) && ! empty( $atts['tpl-label'] ) ? '<div class="label">' . esc_html( $atts['tpl-label'] ) . '</div>' : '' ) . '
							' . ( isset( $atts['tpl-infobox'] ) && ( $atts['tpl-infobox'] == '1' || $atts['tpl-infobox'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" typ="infobox"]' : '' ) . '
							<div class="titleamz">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : 60 ) . '" false="' . __( 'N/A',
						'amazilon' ) . '"]</div>
							<div class="picamz">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="link" true="$BILDMEDIUM" false=false tag="' . esc_attr( $args['tag'] ) . '"]</div>
							<div class="priceamz">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="preis" false="-"]</div>
							<div class="old_priceamz"><del style="color:#F00;">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="streichpreis" false=""]</del>&nbsp;</div>
							<div class="rabattamz">' . ( isset( $aCurrentItem['preis']['discount'] ) && $aCurrentItem['preis']['discount'] > 0 ? 'Rabatt: [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="rabatt" false="' . __( '0,00 $',
							'amazilon' ) . '"]' : '' ) . '&nbsp;</div>
							<div class="starsamz">' . ( isset( $atts['tpl-stars'] ) && ( (int) $atts['tpl-stars'] == 1 || $atts['tpl-stars'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="bewertung"]' : '' ) . '</div>
							<div class="primeamz">[apnx _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="prime" false="-"]<a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $aCurrentItem['asin'] ) . '\' typ=\'url\' tag=\'' . esc_attr( $args['tag'] ) . '\']' ) . '" target="_blank" rel="nofollow"';
				if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
					$sCurrent .= ' data-amazilont="' . esc_attr( $aCurrentItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $aCurrentItem['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
				}
				$sCurrent .= '><img src="' . plugins_url( 'gfx/ampr.png', __FILE__ ) . '" alt=""></a>[/apnx]</div>
							<div class="buttonamz">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="button" template="' . ( ( isset( $atts['tpl-buttontpl'] ) && $atts['tpl-buttontpl'] != '' ) ? (int) $atts['tpl-buttontpl'] : '1' ) . '" false="" true="' . ( ( isset( $atts['tpl-buttontext'] ) && ! empty( $atts['tpl-buttontext'] ) ) ? esc_attr( $atts['tpl-buttontext'] ) : __( 'On Amazon',
						'amazilon' ) ) . '" tag="' . esc_attr( $args['tag'] ) . '"]</div>
							<div class="dateamz">' . __( 'State of data',
						'amazilon' ) . ': [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="state" false="' . __( 'unknown',
						'amazilon' ) . '"]</div>
						</div>';
				$sReturn  .= do_shortcode( $sCurrent );
			}
			$sReturn .= '</div>';

			return $sReturn;
		case 'vergleich2':
			if ( ! isset( $aItem[0] ) ) {
				$aItem = array( array( 'item' => $aItem, 'special' => '' ) );
			}
			if ( ! isset( $atts['tpl-fmax'] ) || (int) $atts['tpl-fmax'] < 1 || (int) $atts['tpl-fmax'] > 500 ) {
				$atts['tpl-fmax'] = 500;
			}
			if ( ! isset( $atts['tpl-features'] ) || (int) $atts['tpl-features'] < 1 || (int) $atts['tpl-features'] > 5 ) {
				$atts['tpl-features'] = 0;
			}

			$sReturn = '<div class="amazilon-table-wrapper"><table class="amazilon-table"><tr class="amazilon-row amazilon-header">';
			if ( ! isset( $atts['tpl-hidelegend'] ) || empty( $atts['tpl-hidelegend'] ) ) {
				$sReturn .= '<th class="amazilon-cell amazilon-header-text">&nbsp;</th>';
				for ( $i = 0; $i < count( $aItem ); $i ++ ) {
					$aCurrentItem = $aItem[ $i ]['item'];
					if ( empty( $aCurrentItem['asin'] ) || strlen( $aCurrentItem['asin'] ) != 10 ) {
						continue;
					}
					$sReturn .= '<th class="amazilon-cell amazilon-header">' . ( ! isset( $atts['tpl-headerlegend'] ) ? __( 'Product',
							'amazilon' ) : esc_html( $atts['tpl-headerlegend'] ) ) . '</th>';
				}
			}
			$sReturn .= '</tr>';

			$sReturn .= '<tr class="amazilon-row">';
			if ( ! isset( $atts['tpl-hidelegend'] ) || empty( $atts['tpl-hidelegend'] ) ) {
				$sReturn .= '<td class="amazilon-cell amazilon-image-text">' . ( ! isset( $atts['tpl-imagelegend'] ) ? '&nbsp;' : esc_html( $atts['tpl-imagelegend'] ) ) . '</td>';
			}
			for ( $i = 0; $i < count( $aItem ); $i ++ ) {
				$aCurrentItem = $aItem[ $i ]['item'];
				if ( empty( $aCurrentItem['asin'] ) || strlen( $aCurrentItem['asin'] ) != 10 ) {
					continue;
				}
				$sReturn .= '<td class="amazilon-cell amazilon-image">';
				$sReturn .= '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="link" true="$BILDMEDIUM" tag="' . esc_attr( $args['tag'] ) . '"]';
				if ( isset( $atts['tpl-hidelegend'] ) && ! empty( $atts['tpl-hidelegend'] ) && isset( $atts['tpl-infobox'] ) && ( $atts['tpl-infobox'] == 'true' || $atts['tpl-infobox'] == '1' ) ) {
					$sReturn .= '[apn _master="' . esc_attr( $args['_master'] ) . '" typ="infobox" tag="' . esc_attr( $args['tag'] ) . '"]';
				}
				$sReturn .= '</td>';
			}
			$sReturn .= '</tr>';

			$sReturn .= '<tr class="amazilon-row">';
			if ( ! isset( $atts['tpl-hidelegend'] ) || empty( $atts['tpl-hidelegend'] ) ) {
				$sReturn .= '<td class="amazilon-cell amazilon-product-text">' . ( ! isset( $atts['tpl-productlegend'] ) ? '&nbsp;' : esc_html( $atts['tpl-productlegend'] ) ) . '</td>';
			}
			for ( $i = 0; $i < count( $aItem ); $i ++ ) {
				$aCurrentItem = $aItem[ $i ]['item'];
				if ( empty( $aCurrentItem['asin'] ) || strlen( $aCurrentItem['asin'] ) != 10 ) {
					continue;
				}
				$sReturn .= '<td class="amazilon-cell amazilon-product"><div><a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $aCurrentItem['asin'] ) . '\' typ=\'url\' tag=\'' . esc_attr( $args['tag'] ) . '\']' ) . '" target="_blank" rel="nofollow" title="' . do_shortcode( '[apn _master="' . esc_attr( $args['_master'] ) . '" asin=\'' . esc_attr( $aCurrentItem['asin'] ) . '\' typ=\'titel\' tag=\'' . esc_attr( $args['tag'] ) . '\']' ) . '"';
				if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
					$sReturn .= ' data-amazilont="' . esc_attr( $aCurrentItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $aCurrentItem['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
				}
				$sReturn .= '>[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : '' ) . '" tag="' . esc_attr( $args['tag'] ) . '"]</a></div></td>';
			}
			$sReturn .= '</tr>';

			for ( $iFeature = 1; $iFeature <= $atts['tpl-features']; $iFeature ++ ) {
				$sReturn .= '<tr class="amazilon-row">';
				if ( ! isset( $atts['tpl-hidelegend'] ) || empty( $atts['tpl-hidelegend'] ) ) {
					$sReturn .= '<td class="amazilon-cell amazilon-features-text">' . ( ! isset( $atts['tpl-productlegend'] ) ? '&nbsp;' : esc_html( $atts['tpl-productlegend'] ) ) . '</td>';
				}
				for ( $i = 0; $i < count( $aItem ); $i ++ ) {
					$aCurrentItem = $aItem[ $i ]['item'];
					if ( empty( $aCurrentItem['asin'] ) || strlen( $aCurrentItem['asin'] ) != 10 ) {
						continue;
					}
					$sReturn .= '<td class="amazilon-cell amazilon-features" style="font-size: small;">';
					$sReturn .= '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="feature" max="' . $atts['tpl-fmax'] . '" tpl-num="' . $iFeature . '" false="" tag="' . esc_attr( $args['tag'] ) . '"]';
					$sReturn .= '</td>';
				}
				$sReturn .= '</tr>';
			}

			$sReturn .= '<tr class="amazilon-row">';
			if ( ! isset( $atts['tpl-hidelegend'] ) || empty( $atts['tpl-hidelegend'] ) ) {
				$sReturn .= '<td class="amazilon-cell amazilon-price-text">' . ( ! isset( $atts['tpl-pricelegend'] ) ? __( 'Price',
						'amazilon' ) : esc_html( $atts['tpl-pricelegend'] ) ) . '</td>';
			}
			for ( $i = 0; $i < count( $aItem ); $i ++ ) {
				$aCurrentItem = $aItem[ $i ]['item'];
				if ( empty( $aCurrentItem['asin'] ) || strlen( $aCurrentItem['asin'] ) != 10 ) {
					continue;
				}
				$sReturn .= '<td class="amazilon-cell amazilon-price"><span class="amazilon-price">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="preis" tag="' . esc_attr( $args['tag'] ) . '"]</span> [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="streichpreis" tpl-format="statt <span class=\'amazilon-price-old\'>%s</span>" tag="' . esc_attr( $args['tag'] ) . '"]</td>';
			}
			$sReturn .= '</tr>';

			if ( ! isset( $atts['tpl-savings'] ) || $atts['tpl-savings'] != 'false' ) {
				$sReturn .= '<tr class="amazilon-row">';
				if ( ! isset( $atts['tpl-hidelegend'] ) || empty( $atts['tpl-hidelegend'] ) ) {
					$sReturn .= '<td class="amazilon-cell amazilon-savings-text">' . ( ! isset( $atts['tpl-savingslegend'] ) ? __( 'You save',
							'amazilon' ) : esc_html( $atts['tpl-savingslegend'] ) ) . '</td>';
				}
				for ( $i = 0; $i < count( $aItem ); $i ++ ) {
					$aCurrentItem = $aItem[ $i ]['item'];
					if ( empty( $aCurrentItem['asin'] ) || strlen( $aCurrentItem['asin'] ) != 10 ) {
						continue;
					}
					$sReturn .= '<td class="amazilon-cell amazilon-savings">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="rabatt" tag="' . esc_attr( $args['tag'] ) . '"]</td>';
				}
				$sReturn .= '</tr>';
			}

			if ( isset( $atts['tpl-stars'] ) && ( $atts['tpl-stars'] == '1' || $atts['tpl-stars'] == 'true' ) ) {
				$sReturn .= '<tr class="amazilon-row">';
				if ( ! isset( $atts['tpl-hidelegend'] ) || empty( $atts['tpl-hidelegend'] ) ) {
					$sReturn .= '<td class="amazilon-cell amazilon-ratings-text">' . ( ! isset( $atts['tpl-ratingslegend'] ) ? __( 'Customers Rating',
							'amazilon' ) : esc_html( $atts['tpl-ratingslegend'] ) ) . '</td>';
				}
				for ( $i = 0; $i < count( $aItem ); $i ++ ) {
					$aCurrentItem = $aItem[ $i ]['item'];
					if ( empty( $aCurrentItem['asin'] ) || strlen( $aCurrentItem['asin'] ) != 10 ) {
						continue;
					}
					$sReturn .= '<td class="amazilon-cell amazilon-ratings">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="bewertung" tag="' . esc_attr( $args['tag'] ) . '"]</td>';
				}
				$sReturn .= '</tr>';
			}

			if ( ! isset( $atts['tpl-prime'] ) || $atts['tpl-prime'] != 'false' ) {
				$sReturn .= '<tr class="amazilon-row">';
				if ( ! isset( $atts['tpl-hidelegend'] ) || empty( $atts['tpl-hidelegend'] ) ) {
					$sReturn .= '<td class="amazilon-cell amazilon-prime-text">' . ( ! isset( $atts['tpl-primelegend'] ) ? __( 'Shipping',
							'amazilon' ) : esc_html( $atts['tpl-primelegend'] ) ) . '</td>';
				}
				for ( $i = 0; $i < count( $aItem ); $i ++ ) {
					$aCurrentItem = $aItem[ $i ]['item'];
					if ( empty( $aCurrentItem['asin'] ) || strlen( $aCurrentItem['asin'] ) != 10 ) {
						continue;
					}
					$sReturn .= '<td class="amazilon-cell amazilon-prime">[apnx _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="prime" false="" tag="' . esc_attr( $args['tag'] ) . '"]<img src="' . plugins_url( 'gfx/ampr.png',
							__FILE__ ) . '" alt="Amazon Prime">[/apnx]</td>';
				}
				$sReturn .= '</tr>';
			}

			$sReturn .= '<tr class="amazilon-row">';
			if ( ! isset( $atts['tpl-hidelegend'] ) || empty( $atts['tpl-hidelegend'] ) ) {
				$sReturn .= '<td class="amazilon-cell amazilon-button-text">' . ( ! isset( $atts['tpl-buttonlegend'] ) ? __( 'Trader',
						'amazilon' ) : esc_html( $atts['tpl-buttonlegend'] ) ) . '</td>';
			}
			for ( $i = 0; $i < count( $aItem ); $i ++ ) {
				$aCurrentItem = $aItem[ $i ]['item'];
				if ( empty( $aCurrentItem['asin'] ) || strlen( $aCurrentItem['asin'] ) != 10 ) {
					continue;
				}
				$sReturn .= '<td class="amazilon-cell amazilon-button">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="button" template="' . ( ( isset( $atts['tpl-buttontpl'] ) && $atts['tpl-buttontpl'] != '' ) ? (int) $atts['tpl-buttontpl'] : '3' ) . '" true="' . ( ( isset( $atts['tpl-buttontext'] ) && ! empty( $atts['tpl-buttontext'] ) ) ? esc_attr( $atts['tpl-buttontext'] ) : 'Amazon' ) . '" false="" tag="' . esc_attr( $args['tag'] ) . '"]</td>';
			}
			$sReturn .= '</tr>';

			$sReturn .= '      <tr class="amazilon-row">';
			if ( ! isset( $atts['tpl-hidelegend'] ) || empty( $atts['tpl-hidelegend'] ) ) {
				$sReturn .= '<td class="amazilon-cell amazilon-state-text">' . ( ! isset( $atts['tpl-statelegend'] ) ? __( 'State',
						'amazilon' ) : esc_html( $atts['tpl-statelegend'] ) ) . ( isset( $atts['tpl-infobox'] ) && ( $atts['tpl-infobox'] == 'true' || $atts['tpl-infobox'] == '1' ) ? ' [apn _master="' . esc_attr( $args['_master'] ) . '" typ="infobox" tag="' . esc_attr( $args['tag'] ) . '"]' : '' ) . '</td>';
			}
			for ( $i = 0; $i < count( $aItem ); $i ++ ) {
				$aCurrentItem = $aItem[ $i ]['item'];
				if ( empty( $aCurrentItem['asin'] ) || strlen( $aCurrentItem['asin'] ) != 10 ) {
					continue;
				}
				$sReturn .= '<td class="amazilon-cell amazilon-state">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aCurrentItem['asin'] ) . '" typ="state" tag="' . esc_attr( $args['tag'] ) . '"]';
				if ( $i == count( $aItem ) - 1 && isset( $config['sAdnotice'] ) && ! empty( $config['sAdnotice'] ) ) {
					$sReturn .= '<span class="amazilon-adnotice">' . esc_html( $config['sAdnotice'] ) . '</span>';
				}
				$sReturn .= '</td>';
			}
			$sReturn .= '</tr>';

			$sReturn .= '</table></div>';
			$sReturn = do_shortcode( $sReturn );

			return $sReturn;
		case 'streichpreis':
			if ( ! isset( $aItem['streichpreis']['preis'] ) || (int) $aItem['streichpreis']['preis'] <= (int) $aItem['preis']['preis'] || ! isset( $aItem['preis']['preis'] ) || $aItem['preis']['preis'] === false ) {
				if ( ! $args['false'] ) {
					return $args['false'];
				}

				return __( 'N/A', 'amazilon' );
			}
			$sPrice = number_format_i18n( $aItem['streichpreis']['preis'] / 100,
					2 ) . ' ' . amazilonMakeCurrency( $aItem['streichpreis']['waehrung'] );

			return isset( $atts['tpl-format'] ) ? sprintf( $atts['tpl-format'], $sPrice ) : $sPrice;
			break;
		case 'bild':
		case 'image':
			if ( ! isset( $atts['tpl-num'] ) || (int) $atts['tpl-num'] > 7 || (int) $atts['tpl-num'] < 1 ) {
				$atts['tpl-num'] = 0;
			}
			if ( ! isset( $aItem['images'][ (int) $atts['tpl-num'] ]['small'] ) || empty( $aItem['images'][ $atts['tpl-num'] ]['small'] ) ) {
				amazilonLogAdd( $args['asin'], $aItem['title'], __( 'No small image available', 'amazilon' ) );
				if ( $args['false'] !== false && $args['false'] != 'false' ) {
					return $args['false'];
				}
				$aItem['images'][ $atts['tpl-num'] ]['small'] = ( isset( $config['stdImage'] ) && ! empty( $config['stdImage'] ) ) ? $config['stdImage'] : plugins_url( 'gfx/no-pic-75.png',
					__FILE__ );
			}

			return '<img src="' . amazilonMakeSsl( $aItem['images'][ $atts['tpl-num'] ]['small'] ) . '" style="max-width: 75px; max-height: 75px;" alt="' . esc_attr( do_shortcode( '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . $args['asin'] . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : '' ) . '"' . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']' ) ) . '" title="' . esc_attr( do_shortcode( '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . $args['asin'] . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : '' ) . '"' . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']' ) ) . '" />';
			break;
		case 'bildMedium':
		case 'imageMedium':
			if ( ! isset( $atts['tpl-num'] ) || (int) $atts['tpl-num'] > 7 || (int) $atts['tpl-num'] < 1 ) {
				$atts['tpl-num'] = 0;
			}
			if ( ! isset( $aItem['images'][ $atts['tpl-num'] ]['medium'] ) || empty( $aItem['images'][ $atts['tpl-num'] ]['medium'] ) ) {
				amazilonLogAdd( $args['asin'], $aItem['title'], __( 'No medium image available', 'amazilon' ) );
				if ( $args['false'] !== false && $args['false'] != 'false' ) {
					return $args['false'];
				}
				$aItem['images'][ $atts['tpl-num'] ]['medium'] = ( isset( $config['stdImageMedium'] ) && ! empty( $config['stdImageMedium'] ) ) ? $config['stdImageMedium'] : plugins_url( 'gfx/no-pic-160.png',
					__FILE__ );
			}

			return '<img src="' . amazilonMakeSsl( $aItem['images'][ $atts['tpl-num'] ]['medium'] ) . '" style="max-width: 160px; max-height: 160px;" alt="' . esc_attr( do_shortcode( '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . $args['asin'] . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : '' ) . '"' . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']' ) ) . '" title="' . esc_attr( do_shortcode( '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . $args['asin'] . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : '' ) . '"' . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']' ) ) . '" />';
			break;
		case 'bildLarge':
		case 'imageLarge':
			if ( ! isset( $atts['tpl-num'] ) || (int) $atts['tpl-num'] > 7 || (int) $atts['tpl-num'] < 1 ) {
				$atts['tpl-num'] = 0;
			}
			if ( ! isset( $aItem['images'][ $atts['tpl-num'] ]['large'] ) || empty( $aItem['images'][ $atts['tpl-num'] ]['large'] ) ) {
				amazilonLogAdd( $args['asin'], $aItem['title'], __( 'No large image available', 'amazilon' ) );
				if ( $args['false'] !== false && $args['false'] != 'false' ) {
					return $args['false'];
				}
				$aItem['images'][ $atts['tpl-num'] ]['large'] = ( isset( $config['stdImageLarge'] ) && ! empty( $config['stdImageLarge'] ) ) ? $config['stdImageLarge'] : plugins_url( 'gfx/no-pic-500.png',
					__FILE__ );
			}

			return '<img src="' . amazilonMakeSsl( $aItem['images'][ $atts['tpl-num'] ]['large'] ) . '" style="max-width: 500px; max-height: 500px;" alt="' . esc_attr( do_shortcode( '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . $args['asin'] . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : '' ) . '"' . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']' ) ) . '" title="' . esc_attr( do_shortcode( '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . $args['asin'] . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : '' ) . '"' . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']' ) ) . '" />';
			break;
		case 'prime':
			if ( ! isset( $aItem['isPrime'] ) || empty( $aItem['isPrime'] ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return __( 'No', 'amazilon' );
			}
			if ( (int) $aItem['isPrime'] == 1 ) {
				if ( $args['true'] !== false ) {
					return $args['true'];
				}

				return __( 'Yes', 'amazilon' );
			}
			if ( $args['false'] !== false ) {
				return $args['false'];
			}

			return __( 'No', 'amazilon' );
			break;
		case 'link':
			if ( ! isset( $aItem['sLink'] ) || empty( $aItem['sLink'] ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return '';
			}
			if ( ! empty( $args['true'] ) ) {
				if ( $args['true'] == '$BILD' ) {
					$args['true'] = amazilonShortCode( array(
						'asin'      => $args['asin'],
						'typ'       => 'bild',
						'tpl-pname' => ( isset( $atts['tpl-pname'] ) ? $atts['tpl-pname'] : '' ),
						'tpl-num'   => ( isset( $atts['tpl-num'] ) ? $atts['tpl-num'] : '' ),
						'false'     => $args['false']
					), $content );
				} elseif ( $args['true'] == '$BILDMEDIUM' ) {
					$args['true'] = amazilonShortCode( array(
						'asin'      => $args['asin'],
						'typ'       => 'bildMedium',
						'tpl-pname' => ( isset( $atts['tpl-pname'] ) ? $atts['tpl-pname'] : '' ),
						'tpl-num'   => ( isset( $atts['tpl-num'] ) ? $atts['tpl-num'] : '' ),
						'false'     => $args['false']
					), $content );
				} elseif ( $args['true'] == '$BILDLARGE' ) {
					$args['true'] = amazilonShortCode( array(
						'asin'      => $args['asin'],
						'typ'       => 'bildLarge',
						'tpl-pname' => ( isset( $atts['tpl-pname'] ) ? $atts['tpl-pname'] : '' ),
						'tpl-num'   => ( isset( $atts['tpl-num'] ) ? $atts['tpl-num'] : '' ),
						'false'     => $args['false']
					), $content );
				} elseif ( $args['true'] == '$PREIS' ) {
					$args['true'] = amazilonShortCode( array(
						'asin'  => $args['asin'],
						'typ'   => 'preis',
						'false' => $args['false']
					), $content );
				} elseif ( $args['true'] == '$TITEL' ) {
					$args['true'] = amazilonShortCode( array(
						'asin'      => $args['asin'],
						'typ'       => 'titel',
						'tpl-pname' => ( isset( $atts['tpl-pname'] ) ? $atts['tpl-pname'] : '' ),
						'false'     => $args['false']
					), $content );
				}
			}
			$sOnClick = '';
			if ( isset( $config['sEventTracker'] ) && ! empty( $config['sEventTracker'] ) ) {
				$sEventInfo = ( isset( $config['sEventTrackerInfo'] ) && $config['sEventTrackerInfo'] == 'productname' ) ? $aItem['title'] : $args['asin'];
				switch ( $config['sEventTracker'] ) {
					case 'gajs':
						$sOnClick = 'amazilonTrack(\'gajs\', \'clickout\', \'' . esc_attr( $sEventInfo ) . '\');';
						break;
					case 'analyticsjs':
						$sOnClick = 'amazilonTrack(\'analyticsjs\', \'clickout\', \'' . esc_attr( $sEventInfo ) . '\');';
						break;
				}
			}
			$sCurrent = '<a href="' . esc_url( empty( $args['tag'] ) ? amazilonMakeUrl( $aItem['sLink'],
					$aItem['asin'] ) : str_replace( $config['associateTag'], urlencode( $args['tag'] ),
					amazilonMakeUrl( $aItem['sLink'],
						$aItem['asin'] ) ) ) . '" target="_blank"' . amazilonNofollow( $args['rel'] ) . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );
			if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
				$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
			}
			$sCurrent .= '>' . ( ! empty( $args['true'] ) ? $args['true'] : __( 'click here to find on Amazon',
					'amazilon' ) ) . '</a>';

			return $sCurrent;
			break;
		case 'url':
			if ( ! isset( $aItem['sLink'] ) || empty( $aItem['sLink'] ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return '#';
			}

			return esc_url( ( empty( $args['tag'] ) ? amazilonMakeUrl( $aItem['sLink'],
				$aItem['asin'] ) : str_replace( $config['associateTag'], urlencode( $args['tag'] ),
				amazilonMakeUrl( $aItem['sLink'], $aItem['asin'] ) ) ) );
			break;
		case 'stand':
		case 'state':
			if ( ! isset( $aItem['state'] ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return __( 'unknown', 'amazilon' );
			}

			return date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ),
				strtotime( $aItem['state'] ) );
			break;
		case 'button':
			if ( isset( $atts['tpl-pname'] ) && ! empty( $atts['tpl-pname'] ) ) {
				$aItem['title'] = $atts['tpl-pname'];
			}
			if ( ! isset( $aItem['sLink'] ) || empty( $aItem['sLink'] ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return '';
			}
			if ( (int) $args['max'] > 0 ) {
				$aItem['title'] = amazilonStrShorter( $aItem['title'], (int) $args['max'] );
			}
			if ( isset( $atts['tpl-buttontext'] ) && ! empty( $atts['tpl-buttontext'] ) ) {
				$args['true'] = $atts['tpl-buttontext'];
			}
			if ( empty( $args['template'] ) ) {
				$args['template'] = '0';
			}
			$args['_master'] .= ' (' . (int) $args['template'] . ')';
			$sOnClick        = '';
			if ( isset( $config['sEventTracker'] ) && ! empty( $config['sEventTracker'] ) ) {
				$sEventInfo = ( isset( $config['sEventTrackerInfo'] ) && $config['sEventTrackerInfo'] == 'productname' ) ? $aItem['title'] : $args['asin'];
				switch ( $config['sEventTracker'] ) {
					case 'gajs':
						$sOnClick = 'amazilonTrack(\'gajs\', \'clickout\', \'' . esc_attr( $sEventInfo ) . '\');';
						break;
					case 'analyticsjs':
						$sOnClick = 'amazilonTrack(\'analyticsjs\', \'clickout\', \'' . esc_attr( $sEventInfo ) . '\');';
						break;
				}
			}
			$sCurrent = '<a href="' . esc_url( empty( $args['tag'] ) ? amazilonMakeUrl( $aItem['sLink'],
					$aItem['asin'] ) : str_replace( $config['associateTag'], urlencode( $args['tag'] ),
					amazilonMakeUrl( $aItem['sLink'],
						$aItem['asin'] ) ) ) . '" class="amazilon-button-' . $args['template'] . '" target="_blank"' . amazilonNofollow( $args['rel'] ) . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );
			if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
				$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
			}
			$sCurrent .= '>' . ( ! empty( $args['true'] ) ? $args['true'] : esc_html( $aItem['title'] ) ) . '</a>';

			return $sCurrent;
			break;
		case 'infobox':
			return '<img src="' . plugins_url( 'gfx/information.png',
					__FILE__ ) . '" title="' . ( ! empty( $config['sHinweistext'] ) ? esc_attr( $config['sHinweistext'] ) : __( 'These information are advertising referrals to amazon.',
					'amazilon' ) ) . '" class="amazilon-tooltip infoamz">';
			break;
		case 'bestseller':
		case 'bestsellers':
			amazilonLogAdd( 'B00BN3YZM2', 'Bestsellers-Shortccode',
				__( 'Amazon Web Service currently does not provide bestsellers.', 'amazilon' ) );

			return '';
			$sReturn = '';
			if ( ! isset( $args['node'] ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return '';
			}
			if ( ! isset( $args['template'] ) ) {
				$args['template'] = 'vergleich';
			}
			if ( ! isset( $args['max'] ) || (int) $args['max'] < 1 || (int) $args['max'] > 10 ) {
				$args['max'] = 10;
			}
			$pxml = amazilonBrowseNodeLookup( (int) $args['node'] );
			if ( $pxml === false ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return '';
			}
			$aAsins = array();
			if ( isset( $pxml->BrowseNodes->BrowseNode->TopItemSet->TopItem ) && count( $pxml->BrowseNodes->BrowseNode->TopItemSet->TopItem ) > 0 ) {
				for ( $iItem = 0; isset( $pxml->BrowseNodes->BrowseNode->TopItemSet->TopItem[ $iItem ] ) && $iItem < (int) $args['max']; $iItem ++ ) {
					array_push( $aAsins, $pxml->BrowseNodes->BrowseNode->TopItemSet->TopItem[ $iItem ]->ASIN );
				}

				if ( count( $aAsins ) > 0 ) {
					if ( $args['template'] == 'vergleich' || $args['template'] == 'vergleich2' ) {
						$sAsins  = implode( ',', $aAsins );
						$sReturn .= do_shortcode( '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $sAsins ) . '" typ="' . esc_attr( $args['template'] ) . '" tpl-buttontext="' . ( ( isset( $atts['tpl-buttontext'] ) && ! empty( $atts['tpl-buttontext'] ) ) ? esc_attr( $atts['tpl-buttontext'] ) : '' ) . '" tpl-buttontpl="' . ( ( isset( $atts['tpl-buttontpl'] ) && $atts['tpl-buttontpl'] != '' ) ? (int) $atts['tpl-buttontpl'] : '' ) . '" false="' . esc_attr( $args['false'] ) . '"' . ( isset( $atts['tpl-infobox'] ) ? ' tpl-infobox="' . esc_attr( $atts['tpl-infobox'] ) . '"' : '' ) . ( ( isset( $atts['tpl-hidelegend'] ) && $args['template'] == 'vergleich2' ) ? ' tpl-hidelegend="' . esc_attr( $atts['tpl-hidelegend'] ) . '"' : '' ) . ( ( isset( $atts['tpl-headerlegend'] ) && $args['template'] == 'vergleich2' ) ? ' tpl-headerlegend="' . esc_attr( $atts['tpl-headerlegend'] ) . '"' : '' ) . ( ( isset( $atts['tpl-imagelegend'] ) && $args['template'] == 'vergleich2' ) ? ' tpl-imagelegend="' . esc_attr( $atts['tpl-imagelegend'] ) . '"' : '' ) . ( ( isset( $atts['tpl-productlegend'] ) && $args['template'] == 'vergleich2' ) ? ' tpl-productlegend="' . esc_attr( $atts['tpl-productlegend'] ) . '"' : '' ) . ( ( isset( $atts['tpl-pricelegend'] ) && $args['template'] == 'vergleich2' ) ? ' tpl-pricelegend="' . esc_attr( $atts['tpl-pricelegend'] ) . '"' : '' ) . ( ( isset( $atts['tpl-savingslegend'] ) && $args['template'] == 'vergleich2' ) ? ' tpl-savingslegend="' . esc_attr( $atts['tpl-savingslegend'] ) . '"' : '' ) . ( ( isset( $atts['tpl-ratingslegend'] ) && $args['template'] == 'vergleich2' ) ? ' tpl-ratingslegend="' . esc_attr( $atts['tpl-ratingslegend'] ) . '"' : '' ) . ( ( isset( $atts['tpl-primelegend'] ) && $args['template'] == 'vergleich2' ) ? ' tpl-primelegend="' . esc_attr( $atts['tpl-primelegend'] ) . '"' : '' ) . ( ( isset( $atts['tpl-buttonlegend'] ) && $args['template'] == 'vergleich2' ) ? ' tpl-buttonlegend="' . esc_attr( $atts['tpl-buttonlegend'] ) . '"' : '' ) . ( ( isset( $atts['tpl-statelegend'] ) && $args['template'] == 'vergleich2' ) ? ' tpl-statelegend="' . esc_attr( $atts['tpl-statelegend'] ) . '"' : '' ) . ( isset( $atts['tpl-label'] ) ? ' tpl-label="' . esc_attr( $atts['tpl-label'] ) . '"' : '' ) . ( isset( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-stars'] ) ? ' tpl-stars="' . esc_attr( $atts['tpl-stars'] ) . '"' : '' ) . ( isset( $atts['tpl-savings'] ) ? ' tpl-savings="' . esc_attr( $atts['tpl-savings'] ) . '"' : '' ) . ( isset( $atts['tpl-prime'] ) ? ' tpl-prime="' . esc_attr( $atts['tpl-prime'] ) . '"' : '' ) . ']' );
					} else {
						for ( $iItem = 0; $iItem < count( $aAsins ); $iItem ++ ) {
							$sReturn .= do_shortcode( '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $aAsins[ $iItem ] ) . '" typ="template" tpl-buttontext="' . ( ( isset( $atts['tpl-buttontext'] ) && ! empty( $atts['tpl-buttontext'] ) ) ? esc_attr( $atts['tpl-buttontext'] ) : '' ) . '" tpl-buttontpl="' . ( ( isset( $atts['tpl-buttontpl'] ) && $atts['tpl-buttontpl'] != '' ) ? (int) $atts['tpl-buttontpl'] : '' ) . '" template="' . esc_attr( $args['template'] ) . '" false="' . esc_attr( $args['false'] ) . '"' . ( isset( $atts['tpl-infobox'] ) ? ' tpl-infobox="' . esc_attr( $atts['tpl-infobox'] ) . '"' : '' ) . ( isset( $atts['tpl-stars'] ) ? ' tpl-stars="' . esc_attr( $atts['tpl-stars'] ) . '"' : '' ) . ( isset( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-label'] ) ? ' tpl-label="' . esc_attr( $atts['tpl-label'] ) . '"' : '' ) . ']' );
						}
					}

					return $sReturn;
				}
			}

			if ( $args['false'] !== false ) {
				return $args['false'];
			}

			return '';
			break;
		case 'template':
			if ( isset( $atts['tpl-pname'] ) && ! empty( $atts['tpl-pname'] ) ) {
				$aItem['title'] = $atts['tpl-pname'];
			}
			if ( ! isset( $aItem['sLink'] ) || empty( $aItem['sLink'] ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return '';
			}
			if ( ! isset( $atts['tpl-fmax'] ) || (int) $atts['tpl-fmax'] < 1 || (int) $atts['tpl-fmax'] > 500 ) {
				$atts['tpl-fmax'] = 500;
			}
			if ( ! isset( $atts['tpl-features'] ) || (int) $atts['tpl-features'] < 1 || (int) $atts['tpl-features'] > 5 ) {
				$atts['tpl-features'] = 0;
			}

			$sOnClick = '';
			if ( isset( $config['sEventTracker'] ) && ! empty( $config['sEventTracker'] ) ) {
				$sEventInfo = ( isset( $config['sEventTrackerInfo'] ) && $config['sEventTrackerInfo'] == 'productname' ) ? $aItem['title'] : $args['asin'];
				switch ( $config['sEventTracker'] ) {
					case 'gajs':
						$sOnClick = 'amazilonTrack(\'gajs\', \'clickout\', \'' . esc_attr( $sEventInfo ) . '\');';
						break;
					case 'analyticsjs':
						$sOnClick = 'amazilonTrack(\'analyticsjs\', \'clickout\', \'' . esc_attr( $sEventInfo ) . '\');';
						break;
				}
			}
			$args['_master'] .= ' (' . $args['template'] . ')';
			switch ( $args['template'] ) {
				case 'tpl-2':
				case 'tpl-2s':
					$sCurrent = '<div class="amazilon-tpl-2' . ( $args['template'] == 'tpl-2s' ? ' amazilon-shadow' : '' ) . ' amazilon-asin-' . esc_attr( $args['asin'] ) . '">
                            <div class="links">
                                    ' . ( isset( $atts['tpl-infobox'] ) && ( $atts['tpl-infobox'] == '1' || $atts['tpl-infobox'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" typ="infobox"]' : '' ) . '
                                    <div class="pic">
                                        [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="link" true="$BILDMEDIUM"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']
                                    </div>
                            </div>
                            <div class="rechts">
                                    <div class="info">
                                        <div class="title"><a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $args['asin'] ) . '\' typ=\'url\'' . ( ! empty( $args['tag'] ) ? ' tag=\'' . esc_attr( $args['tag'] ) . '\'' : '' ) . ']' ) . '" target="_blank" rel="nofollow"' . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );
					if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
						$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
					}
					$sCurrent .= '>[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : 75 ) . '"' . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']</a></div>';

					if ( (int) $atts['tpl-features'] > 0 ) {
						$sCurrent .= '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="features" tpl-count="' . (int) $atts['tpl-features'] . '" max="' . $atts['tpl-fmax'] . '"]';
					}

					$sCurrent .= '<div class="price">
                                             ' . ( isset( $atts['tpl-label'] ) && ! empty( $atts['tpl-label'] ) ? '<div class="label">' . esc_html( $atts['tpl-label'] ) . '</div>' : '' ) . '
                                             <span class="price-now">[apnx _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="prime" false=""]<img class="prime" src="' . plugins_url( 'gfx/ampr.png',
							__FILE__ ) . '" alt="' . __( 'Amazon Prime',
							'amazilon' ) . '">[/apnx][apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="preis"]</span> <span class="old-price">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="streichpreis" false=""]</span>
                                        </div>
										' . ( isset( $atts['tpl-stars'] ) && ( $atts['tpl-stars'] == '1' || $atts['tpl-stars'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="bewertung"]' : '' ) . '
                                        <div class="date">' . __( 'State',
							'amazilon' ) . ': [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="state"] ' . __( 'time',
							'amazilon' ) . '</div>
                                        [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="button" template="' . ( ( isset( $atts['tpl-buttontpl'] ) && $atts['tpl-buttontpl'] != '' ) ? (int) $atts['tpl-buttontpl'] : '1' ) . '" true="' . ( ( isset( $atts['tpl-buttontext'] ) && ! empty( $atts['tpl-buttontext'] ) ) ? esc_attr( $atts['tpl-buttontext'] ) : __( 'Buy now on Amazon',
							'amazilon' ) ) . '"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']
                                    </div>
                            </div>';
					if ( isset( $config['sAdnotice'] ) && ! empty( $config['sAdnotice'] ) ) {
						$sCurrent .= '<div class="amazilon-adnotice">' . esc_html( $config['sAdnotice'] ) . '</div>';
					}
					$sCurrent .= '
                        </div>';

					return do_shortcode( $sCurrent );
					break;
				case 'tpl-3':
				case 'tpl-3s':
					$sCurrent = '<div class="amazilon-tpl-3' . ( $args['template'] == 'tpl-3s' ? ' amazilon-shadow' : '' ) . ' amazilon-asin-' . esc_attr( $args['asin'] ) . '">
                                    ' . ( isset( $atts['tpl-label'] ) && ! empty( $atts['tpl-label'] ) ? '<div class="label">' . esc_html( $atts['tpl-label'] ) . '</div>' : '' ) . '
                                    ' . ( isset( $atts['tpl-infobox'] ) && ( $atts['tpl-infobox'] == '1' || $atts['tpl-infobox'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" typ="infobox"]' : '' ) . '
                                    <div class="pic">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="link" true="$BILDMEDIUM"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . '] </div>
                                    <div class="title"><a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $args['asin'] ) . '\' typ=\'url\'' . ( ! empty( $args['tag'] ) ? ' tag=\'' . esc_attr( $args['tag'] ) . '\'' : '' ) . ']' ) . '" target="_blank" rel="nofollow"' . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );

					if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
						$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
					}
					$sCurrent .= '>[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : 75 ) . '"' . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']</a></div>
                                    <div class="price">                                        <span class="price-now">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="preis"]</span> <span class="old-price">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="streichpreis" false=""]</span>
                                    </div>
									' . ( isset( $atts['tpl-stars'] ) && ( $atts['tpl-stars'] == '1' || $atts['tpl-stars'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="bewertung"]' : '' ) . '
                                    <div class="date">' . __( 'State',
							'amazilon' ) . ': [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="state"] ' . __( 'time',
							'amazilon' ) . '</div>
                                    <div class="prime">[apnx _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="prime" false=""]<a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $args['asin'] ) . '\' typ=\'url\'' . ( ! empty( $args['tag'] ) ? ' tag=\'' . esc_attr( $args['tag'] ) . '\'' : '' ) . ']' ) . '" target="_blank" rel="nofollow"' . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );
					if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
						$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] . '|prime' ) . '"';
					}
					$sCurrent .= '><img src="' . plugins_url( 'gfx/ampr.png',
							__FILE__ ) . '" alt="' . __( 'Amazon Prime', 'amazilon' ) . '"></a>[/apnx]</div>
                                    <div>[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="button" true="' . ( ( isset( $atts['tpl-buttontext'] ) && ! empty( $atts['tpl-buttontext'] ) ) ? esc_attr( $atts['tpl-buttontext'] ) : __( 'Buy now on Amazon',
							'amazilon' ) ) . '" template="' . ( ( isset( $atts['tpl-buttontpl'] ) && $atts['tpl-buttontpl'] != '' ) ? (int) $atts['tpl-buttontpl'] : '' ) . '"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']</div>';
					if ( isset( $config['sAdnotice'] ) && ! empty( $config['sAdnotice'] ) ) {
						$sCurrent .= '<div class="amazilon-adnotice">' . esc_html( $config['sAdnotice'] ) . '</div>';
					}
					$sCurrent .= '
                        </div>';

					return do_shortcode( $sCurrent );
					break;
				case 'tpl-4':
				case 'tpl-4s':
					$sCurrent = '<div class="amazilon-tpl-4' . ( $args['template'] == 'tpl-4s' ? ' amazilon-shadow' : '' ) . ' amazilon-asin-' . esc_attr( $args['asin'] ) . '">
                            ' . ( isset( $atts['tpl-label'] ) && ! empty( $atts['tpl-label'] ) ? '<div class="label">' . esc_html( $atts['tpl-label'] ) . '</div>' : '' ) . '
                            ' . ( isset( $atts['tpl-infobox'] ) && ( $atts['tpl-infobox'] == '1' || $atts['tpl-infobox'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" typ="infobox"]' : '' ) . '
                            <div class="pic">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="link" true="$BILD"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']</div>
                            <div class="title"><a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $args['asin'] ) . '\' typ=\'url\'' . ( ! empty( $args['tag'] ) ? ' tag=\'' . esc_attr( $args['tag'] ) . '\'' : '' ) . ']' ) . '" target="_blank" rel="nofollow"' . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );
					if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
						$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
					}
					$sCurrent .= '>[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : 75 ) . '' . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']"</a></div>
                            <div class="price">
                                <span class="price-now">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="preis"]</span>
                                <span class="old-price">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="streichpreis" false=""]</span>
                            </div>
							' . ( isset( $atts['tpl-stars'] ) && ( $atts['tpl-stars'] == '1' || $atts['tpl-stars'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="bewertung"]' : '' ) . '
                            <div class="date">' . __( 'State',
							'amazilon' ) . ': [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="state"] ' . __( 'time',
							'amazilon' ) . '</div>
                            <div class="prime">[apnx _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="prime" false=""]<a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $args['asin'] ) . '\' typ=\'url\'' . ( ! empty( $args['tag'] ) ? ' tag=\'' . esc_attr( $args['tag'] ) . '\'' : '' ) . ']' ) . '" target="_blank" rel="nofollow"' . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );
					if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
						$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] . '|prime' ) . '"';
					}
					$sCurrent .= '><img src="' . plugins_url( 'gfx/ampr.png',
							__FILE__ ) . '" alt="' . __( 'Amazon Prime', 'amazilon' ) . '"></a>[/apnx]</div>
                            [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="button" template="' . ( ( isset( $atts['tpl-buttontpl'] ) && $atts['tpl-buttontpl'] != '' ) ? (int) $atts['tpl-buttontpl'] : '3' ) . '" true="' . ( ( isset( $atts['tpl-buttontext'] ) && ! empty( $atts['tpl-buttontext'] ) ) ? esc_attr( $atts['tpl-buttontext'] ) : __( 'Buy now on Amazon',
							'amazilon' ) ) . '"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']';
					if ( isset( $config['sAdnotice'] ) && ! empty( $config['sAdnotice'] ) ) {
						$sCurrent .= '<div class="amazilon-adnotice">' . esc_html( $config['sAdnotice'] ) . '</div>';
					}
					$sCurrent .= '
                        </div>';

					return do_shortcode( $sCurrent );
					break;
				case 'tpl-5':
				case 'tpl-5s':
					$sCurrent = '<div class="amazilon-tpl-5' . ( $args['template'] == 'tpl-5s' ? ' amazilon-shadow' : '' ) . ' amazilon-asin-' . esc_attr( $args['asin'] ) . '">
                            <div class="links">
                                    ' . ( isset( $atts['tpl-infobox'] ) && ( $atts['tpl-infobox'] == '1' || $atts['tpl-infobox'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" typ="infobox"]' : '' ) . '
                                    <div class="pic">
                                        [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="link" true="$BILDMEDIUM"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']
                                    </div>
                            </div>
                            <div class="rechts">
                                    <div class="info">
                                        <div class="title"><a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $args['asin'] ) . '\' typ=\'url\'' . ( ! empty( $args['tag'] ) ? ' tag=\'' . esc_attr( $args['tag'] ) . '\'' : '' ) . ']' ) . '" target="_blank" rel="nofollow"' . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );

					if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
						$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
					}
					$sCurrent .= '>[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : 75 ) . '"' . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']</a></div>';

					if ( (int) $atts['tpl-features'] > 0 ) {
						$sCurrent .= '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="features" tpl-count="' . (int) $atts['tpl-features'] . '" max="' . $atts['tpl-fmax'] . '"]';
					}

					$sCurrent .= '<div class="price">
                                             ' . ( isset( $atts['tpl-label'] ) && ! empty( $atts['tpl-label'] ) ? '<div class="label">' . esc_html( $atts['tpl-label'] ) . '</div>' : '' ) . '
                                             <span class="price-now">[apnx _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="prime" false=""]<img class="prime" src="' . plugins_url( 'gfx/ampr.png',
							__FILE__ ) . '" alt="' . __( 'Amazon Prime',
							'amazilon' ) . '">[/apnx][apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="preis"]</span> <span class="old-price">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="streichpreis" false=""]</span>
                                        </div>
										' . ( isset( $atts['tpl-stars'] ) && ( $atts['tpl-stars'] == '1' || $atts['tpl-stars'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="bewertung"]' : '' ) . '
                                        <div class="date">' . __( 'State',
							'amazilon' ) . ': [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="state"] ' . __( 'time',
							'amazilon' ) . '</div>
                                        [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="button" template="' . ( ( isset( $atts['tpl-buttontpl'] ) && $atts['tpl-buttontpl'] != '' ) ? (int) $atts['tpl-buttontpl'] : '3' ) . '" true="' . ( ( isset( $atts['tpl-buttontext'] ) && ! empty( $atts['tpl-buttontext'] ) ) ? esc_attr( $atts['tpl-buttontext'] ) : __( 'Buy now on Amazon',
							'amazilon' ) ) . '"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']
                                    </div>
                            </div>';
					if ( isset( $config['sAdnotice'] ) && ! empty( $config['sAdnotice'] ) ) {
						$sCurrent .= '<div class="amazilon-adnotice">' . esc_html( $config['sAdnotice'] ) . '</div>';
					}
					$sCurrent .= '
                        </div>';

					return do_shortcode( $sCurrent );
					break;
				case 'tpl-6':
				case 'tpl-6s':
					$sCurrent = '<div class="amazilon-tpl-6' . ( $args['template'] == 'tpl-6s' ? ' amazilon-shadow' : '' ) . ' amazilon-asin-' . esc_attr( $args['asin'] ) . '">
                            <div class="links">
                                    ' . ( isset( $atts['tpl-infobox'] ) && ( $atts['tpl-infobox'] == '1' || $atts['tpl-infobox'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" typ="infobox"]' : '' ) . '
                                    <div class="pic">
                                        [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="link" true="$BILDMEDIUM"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']
                                    </div>
                            </div>
                            <div class="rechts">
                                    <div class="info">
                                        <div class="title"><a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $args['asin'] ) . '\' typ=\'url\'' . ( ! empty( $args['tag'] ) ? ' tag=\'' . esc_attr( $args['tag'] ) . '\'' : '' ) . ']' ) . '" target="_blank" rel="nofollow"' . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );
					if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
						$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
					}
					$sCurrent .= '>[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : 75 ) . '"' . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']</a></div>';

					if ( (int) $atts['tpl-features'] > 0 ) {
						$sCurrent .= '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="features" tpl-count="' . (int) $atts['tpl-features'] . '" max="' . $atts['tpl-fmax'] . '"]';
					}

					$sCurrent .= '<div class="price">
                                             <span class="price-now">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="preis"]</span> <span class="old-price">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="streichpreis" false=""][apnx _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="prime" false=""]<img class="prime" src="' . plugins_url( 'gfx/ampr.png',
							__FILE__ ) . '" alt="' . __( 'Amazon Prime', 'amazilon' ) . '">[/apnx]</span>
                                             ' . ( isset( $atts['tpl-label'] ) && ! empty( $atts['tpl-label'] ) ? '<div class="label">' . esc_html( $atts['tpl-label'] ) . '</div>' : '' ) . '
                                         </div>
										' . ( isset( $atts['tpl-stars'] ) && ( $atts['tpl-stars'] == '1' || $atts['tpl-stars'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="bewertung"]' : '' ) . '
                                        <div class="date">' . __( 'State',
							'amazilon' ) . ': [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="state"] ' . __( 'time',
							'amzilon' ) . '</div>
                                        [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="button" template="' . ( ( isset( $atts['tpl-buttontpl'] ) && $atts['tpl-buttontpl'] != '' ) ? (int) $atts['tpl-buttontpl'] : '1' ) . '" true="' . ( ( isset( $atts['tpl-buttontext'] ) && ! empty( $atts['tpl-buttontext'] ) ) ? esc_attr( $atts['tpl-buttontext'] ) : __( 'Buy now on Amazon',
							'amazilon' ) ) . '"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']
                                    </div>
                            </div>';
					if ( isset( $config['sAdnotice'] ) && ! empty( $config['sAdnotice'] ) ) {
						$sCurrent .= '<div class="amazilon-adnotice">' . esc_html( $config['sAdnotice'] ) . '</div>';
					}
					$sCurrent .= '
                        </div>';

					return do_shortcode( $sCurrent );
					break;
				case 'tpl-7':
				case 'tpl-7s':
					$sCurrent = '<div class="amazilon-tpl-7' . ( $args['template'] == 'tpl-7s' ? ' amazilon-shadow' : '' ) . ' amazilon-asin-' . esc_attr( $args['asin'] ) . '"><span class="infobox">' . ( isset( $atts['tpl-infobox'] ) && ( $atts['tpl-infobox'] == '1' || $atts['tpl-infobox'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" typ="infobox"]' : '' ) . '</span>
								<div class="image">
									<a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $args['asin'] ) . '\' typ=\'url\' false=\'\']' ) . '" target="_blank" rel="nofollow"';
					if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
						$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] . ' (' . $args['template'] . '|img)' ) . '"';
					}
					$sCurrent .= '>[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="link" true="$BILDMEDIUM"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']</a>
								</div>
								<div class="productinfo">
									<a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $args['asin'] ) . '\' typ=\'url\' false=\'\']' ) . '" target="_blank" rel="nofollow"';
					if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
						$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
					}
					$sCurrent .= '>
										<span class="old-price">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="streichpreis" false=""]</span>
										<span class="price-now">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="preis"]</span>
										<span class="prime">[apnx _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="prime" false=""]<img class="prime" src="' . plugins_url( 'gfx/ampr.png',
							__FILE__ ) . '" alt="' . __( 'Amazon Prime', 'amazilon' ) . '">[/apnx]</span>
										<br>
										' . ( isset( $atts['tpl-stars'] ) && ( $atts['tpl-stars'] == 1 || $atts['tpl-stars'] == 'true' ) ? '<span class="rating">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="bewertung"] [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="anzahlbewertungen" false="" tpl-format="(%s)"]</span><br>' : '' ) . '
										<span class="title">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : '' ) . '"]</span>
									</a>
								</div><br style="clear: both;">';
					if ( isset( $config['sAdnotice'] ) && ! empty( $config['sAdnotice'] ) ) {
						$sCurrent .= '<div class="amazilon-adnotice">' . esc_html( $config['sAdnotice'] ) . '</div>';
					}
					$sCurrent .= '
                        </div>';

					return do_shortcode( $sCurrent );
					break;
				case 'tpl-1':
				case 'tpl-1s':
				default:
					$sCurrent = '<div class="amazilon-tpl-1' . ( $args['template'] == 'tpl-1s' ? ' amazilon-shadow' : '' ) . ' amazilon-asin-' . esc_attr( $args['asin'] ) . '">
                            ' . ( isset( $atts['tpl-label'] ) && ! empty( $atts['tpl-label'] ) ? '<div class="label">' . esc_html( $atts['tpl-label'] ) . '</div>' : '' ) . '
                            ' . ( isset( $atts['tpl-infobox'] ) && ( $atts['tpl-infobox'] == '1' || $atts['tpl-infobox'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" typ="infobox"]' : '' ) . '
                            <div class="pic">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="link" true="$BILD"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']</div>
                            <div class="title"><a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $args['asin'] ) . '\' typ=\'url\'' . ( ! empty( $args['tag'] ) ? ' tag=\'' . esc_attr( $args['tag'] ) . '\'' : '' ) . ']' ) . '" target="_blank" rel="nofollow"' . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );
					if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
						$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
					}
					$sCurrent .= '>[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : 75 ) . '"' . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']</a></div>
                            <div class="price">
                                <span class="price-now">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="preis"]</span>
                                <span class="old-price">[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="streichpreis" false=""]</span>
                            </div>
							' . ( isset( $atts['tpl-stars'] ) && ( $atts['tpl-stars'] == '1' || $atts['tpl-stars'] == 'true' ) ? '[apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="bewertung"]' : '' ) . '
                            <div class="date">' . __( 'State',
							'amazilon' ) . ': [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="state"] ' . __( 'time',
							'amazilon' ) . '</div>
                            <div class="prime">[apnx _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="prime" false=""]<a href="' . do_shortcode( '[apn _master=\'' . esc_attr( $args['_master'] ) . '\' asin=\'' . esc_attr( $args['asin'] ) . '\' typ=\'url\'' . ( ! empty( $args['tag'] ) ? ' tag=\'' . esc_attr( $args['tag'] ) . '\'' : '' ) . ']' ) . '" target="_blank" rel="nofollow"' . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );
					if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
						$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] . '|prime' ) . '"';
					}
					$sCurrent .= '><img src="' . plugins_url( 'gfx/ampr.png',
							__FILE__ ) . '" alt="' . __( 'Amazon Prime', 'amazilon' ) . '"></a>[/apnx]</div>
                            [apn _master="' . esc_attr( $args['_master'] ) . '" asin="' . esc_attr( $args['asin'] ) . '" typ="button" template="' . ( ( isset( $atts['tpl-buttontpl'] ) && $atts['tpl-buttontpl'] != '' ) ? (int) $atts['tpl-buttontpl'] : '1' ) . '" true="' . ( ( isset( $atts['tpl-buttontext'] ) && ! empty( $atts['tpl-buttontext'] ) ) ? esc_attr( $atts['tpl-buttontext'] ) : __( 'Buy now on Amazon',
							'amazilon' ) ) . '"' . ( ! empty( $args['tag'] ) ? ' tag="' . esc_attr( $args['tag'] ) . '"' : '' ) . ( isset( $atts['tpl-pname'] ) ? ' tpl-pname="' . esc_attr( $atts['tpl-pname'] ) . '"' : '' ) . ']';
					if ( isset( $config['sAdnotice'] ) && ! empty( $config['sAdnotice'] ) ) {
						$sCurrent .= '<div class="amazilon-adnotice">' . esc_html( $config['sAdnotice'] ) . '</div>';
					}
					$sCurrent .= '
                        </div>';

					return do_shortcode( $sCurrent );
			}
			break;
		default:
			return __( 'N/A', 'amazilon' );
	}

	return __( 'N/A', 'amazilon' );
}

function amazilonShortCodeX( $atts, $content ) {
	global $__amazilonVersion;
	$config = get_option( 'bowsxWpApn' );
	wp_enqueue_style( 'amazilon', plugins_url( 'gfx/style.css', __FILE__ ), array( 'dashicons' ), $__amazilonVersion );
	wp_enqueue_style( 'jquery-ui', plugins_url( 'gfx/jquery-ui.min.css', __FILE__ ), array(), '1.12.0' );
	wp_enqueue_script( 'jquery-ui-tooltip' );
	wp_enqueue_script( 'amazilon-lib', plugins_url( 'gfx/lib.js', __FILE__ ), array(), $__amazilonVersion );
	wp_localize_script( 'amazilon-lib', 'amazilonObj', array(
		'ajax_url' => admin_url( 'admin-ajax.php' ),
		'te'       => ( isset( $config['sTrackerEnabled'] ) ? (int) $config['sTrackerEnabled'] : 0 )
	) );
	if ( empty( $content ) ) {
		return amazilonShortCode( $atts, '' );
	}
	if ( ( $config = get_option( 'bowsxWpApn' ) ) === false || empty( $config['publicKey'] ) || empty( $config['privateKey'] ) || empty( $config['associateTag'] ) ) {
		return '';
	}
	$args = shortcode_atts(
		array(
			'asin'     => '',
			'typ'      => '',
			'false'    => false,
			'tag'      => '',
			'template' => '',
			'_master'  => ''
		),
		$atts
	);
	if ( empty( $args['_master'] ) ) {
		$args['_master'] = $args['typ'];
	} else {
		$args['_master'] .= '|' . $args['typ'];
	}

	if ( empty( $args['asin'] ) || empty( $args['typ'] ) ) {
		return '';
	}
	$aItem = amazilonGetItem( substr( $args['asin'], 0, 10 ) );
	if ( $aItem === false ) {
		if ( $args['false'] !== false ) {
			return $args['false'];
		}

		return __( 'N/A', 'amazilon' );
	}

	switch ( $args['typ'] ) {
		case 'prime':
			if ( ! isset( $aItem['isPrime'] ) || empty( $aItem['isPrime'] ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return __( 'No', 'amazilon' );
			}
			if ( (int) $aItem['isPrime'] == 1 ) {
				return ( ! empty( $content ) ? do_shortcode( $content ) : 'Yes' );
			}
			if ( $args['false'] !== false ) {
				return $args['false'];
			}

			return __( 'No', 'amazilon' );
			break;
		case 'link':
			if ( ! isset( $aItem['sLink'] ) || empty( $aItem['sLink'] ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return '';
			}
			$sOnClick = '';
			if ( isset( $config['sEventTracker'] ) && ! empty( $config['sEventTracker'] ) ) {
				$sEventInfo = ( isset( $config['sEventTrackerInfo'] ) && $config['sEventTrackerInfo'] == 'productname' ) ? $aItem['title'] : $args['asin'];
				switch ( $config['sEventTracker'] ) {
					case 'gajs':
						$sOnClick = 'amazilonTrack(\'gajs\', \'clickout\', \'' . esc_attr( $sEventInfo ) . '\');';
						break;
					case 'analyticsjs':
						$sOnClick = 'amazilonTrack(\'analyticsjs\', \'clickout\', \'' . esc_attr( $sEventInfo ) . '\');';
						break;
				}
			}
			$sCurrent = '<a href="' . esc_url( empty( $args['tag'] ) ? $aItem['sLink'] : str_replace( $config['associateTag'],
					urlencode( $args['tag'] ),
					$aItem['sLink'] ) ) . '" target="_blank"' . amazilonNofollow( $args['rel'] ) . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );
			if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
				$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
			}
			$sCurrent .= '>' . ( ! empty( $content ) ? do_shortcode( $content ) : __( 'click here to find on Amazon',
					'amazilon' ) ) . '</a>';

			return $sCurrent;
			break;
		case 'button':
			if ( ! isset( $aItem['sLink'] ) || empty( $aItem['sLink'] ) ) {
				if ( $args['false'] !== false ) {
					return $args['false'];
				}

				return '';
			}
			$sOnClick = '';
			if ( isset( $config['sEventTracker'] ) && ! empty( $config['sEventTracker'] ) ) {
				$sEventInfo = ( isset( $config['sEventTrackerInfo'] ) && $config['sEventTrackerInfo'] == 'productname' ) ? $aItem['title'] : $args['asin'];
				switch ( $config['sEventTracker'] ) {
					case 'gajs':
						$sOnClick = 'amazilonTrack(\'gajs\', \'clickout\', \'' . esc_attr( $sEventInfo ) . '\');';
						break;
					case 'analyticsjs':
						$sOnClick = 'amazilonTrack(\'analyticsjs\', \'clickout\', \'' . esc_attr( $sEventInfo ) . '\');';
						break;
				}
			}
			$sCurrent = '<a href="' . esc_url( empty( $args['tag'] ) ? amazilonMakeUrl( $aItem['sLink'],
					$aItem['asin'] ) : str_replace( $config['associateTag'], urlencode( $args['tag'] ),
					amazilonMakeUrl( $aItem['sLink'],
						$aItem['asin'] ) ) ) . '" class="amazilon-button-' . ( ! empty( $args['template'] ) ? (int) $args['template'] : '0' ) . '" target="_blank"' . amazilonNofollow( $args['rel'] ) . ( ! empty( $sOnClick ) ? ' onclick="' . $sOnClick . '"' : '' );
			if ( isset( $config['sTrackerEnabled'] ) && $config['sTrackerEnabled'] == '1' ) {
				$sCurrent .= ' data-amazilont="' . esc_attr( $aItem['title'] ) . '" data-amazilontag="' . esc_attr( $args['tag'] ) . '" data-amazilonasin="' . esc_attr( $args['asin'] ) . '" data-amazilonsc="' . esc_attr( $args['_master'] ) . '"';
			}
			$sCurrent .= '>' . ( ! empty( $content ) ? do_shortcode( $content ) : esc_html( $aItem['title'] ) ) . '</a>';

			return $sCurrent;
			break;
		default:
			return __( 'N/A', 'amazilon' );
	}

	return __( 'N/A', 'amazilon' );
}

function amazilonXchange( $sAsin, $sAsinNew ) {
	global $wpdb;
	$wpdb->delete( $wpdb->prefix . 'amazilon_xchange', array( 'asin' => $sAsin ), array( '%s' ) );
	if ( $sAsinNew != false && ! empty( $sAsinNew ) && trim( $sAsin ) != trim( $sAsinNew ) ) {
		$aItem  = amazilonGetItem( $sAsin, true, true );
		$sTitle = ( is_null( $aItem ) ) ? 'N/A' : $aItem['title'];

		$aItem     = amazilonGetItem( $sAsinNew, true, true );
		$sTitleNew = ( is_null( $aItem ) ) ? 'N/A' : $aItem['title'];

		$wpdb->insert( $wpdb->prefix . 'amazilon_xchange',
			array( 'asin' => $sAsin, 'title' => $sTitle, 'asinNew' => $sAsinNew, 'titleNew' => $sTitleNew ),
			array( '%s', '%s', '%s', '%s' ) );
	}
}

function amazilonCheckXchange( $sAsin ) {
	global $wpdb;
	$oAsinNew = $wpdb->get_row( 'SELECT asinNew FROM ' . $wpdb->prefix . 'amazilon_xchange WHERE asin="' . esc_sql( $sAsin ) . '"',
		OBJECT );
	if ( ! is_null( $oAsinNew ) && $oAsinNew !== false ) {
		$sAsin = $oAsinNew->asinNew;
	}

	return $sAsin;
}

function amazilonGetItem( $sAsin, $bLookup = true, $doNotReplace = false ) {
	global $wpdb, $__amazilonNoXchange;
	$config = get_option( 'bowsxWpApn' );

	if ( $doNotReplace !== true && $__amazilonNoXchange !== true ) {
		$sAsin = amazilonCheckXchange( $sAsin );
	}

	$item = get_transient( 'amazilon_ASIN_' . $sAsin );
	if ( $bLookup === false ) {
		return $item;
	} elseif ( $item === false ) {
		$item = amazilonItemLookup( $sAsin );
		if ( $item === false ) {
			$seconds = 300;
		} else {
			if ( ! isset( $config['iCaching'] ) || (int) $config['iCaching'] < 1 ) {
				$config['iCaching'] = 86400;
			}
			$seconds = (int) $config['iCaching'];
		}
		set_transient( 'amazilon_ASIN_' . $sAsin, $item, (int) $seconds );
	}
	if ( empty( $item ) ) {
		return false;
	}

	return $item;
}

function amazilonBrowseNodeLookup( $iBrowseNodeId ) {
	global $__amazilonApiCalls;
	$__amazilonApiCalls ++;
	if ( $__amazilonApiCalls > 2 ) {
		usleep( 300000 );
	}
	if ( ( $config = get_option( 'bowsxWpApn' ) ) === false || empty( $config['publicKey'] ) || empty( $config['privateKey'] ) || empty( $config['associateTag'] ) ) {
		return false;
	}
	$request = amazilon_aws_request(
		'de',
		array(
			'Operation'     => 'BrowseNodeLookup',
			'BrowseNodeId'  => (int) $iBrowseNodeId,
			'ResponseGroup' => 'BrowseNodeInfo,TopSellers'
		),
		trim( $config['publicKey'] ),
		trim( $config['privateKey'] ),
		trim( $config['associateTag'] )
	);

	$iCheck = 0;
	do {
		$response = wp_remote_get( $request );
		if ( ! is_wp_error( $response ) && wp_remote_retrieve_response_code( $response ) === 200 ) {
			return @simplexml_load_string( $response['body'] );
		}
		$iCheck ++;
		usleep( 300000 );
	} while ( $iCheck < 3 );

	return false;
}

function amazilonItemLookup( $sAsin, $iRetry = 0 ) {
	global $__amazilonApiCalls;
	global $wpdb;
	$__amazilonApiCalls ++;
	if ( $iRetry > 3 ) {
		amazilonLogAdd( $sAsin, 'Unknown',
			__( 'Amazon Web Service usage limit reached, will retry after 5 minutes', 'amazilon' ) );

		return false;
	}
	if ( $__amazilonApiCalls > 2 ) {
		usleep( 300000 );
	}
	if ( ( $config = get_option( 'bowsxWpApn' ) ) === false || empty( $config['publicKey'] ) || empty( $config['privateKey'] ) || empty( $config['associateTag'] ) ) {
		return false;
	}

	/**
	 * @todo Check PA-API5!
	 */
	if ( get_option( 'amazilon_paapi5mode' ) == '1' ) {
		require_once trailingslashit( dirname( __FILE__ ) ) . 'libs/paapi5.php';
		$return = paapi5_getItem( $sAsin );
		if ( ! $return ) {
			return amazilonItemLookup( $sAsin, $iRetry + 1 );
		}

		/**
		 * Artikel nicht bestellbar
		 */
		if ( ! isset( $return['title'] ) || empty( $return['title'] ) || ! isset( $return['preis']['preis'] ) || $return['preis']['preis'] === false || (int) $return['preis']['preis'] == 0 ) {
			$sNewAsin = amazilonCheckXchange( $sAsin, true );
			if ( $sAsin != $sNewAsin ) {
				return amazilonItemLookup( $sNewAsin, 0 );
			}
		}

		return $return;
	}

	try {
		$request = amazilon_aws_request(
			'de',
			array(
				'Operation'     => 'ItemLookup',
				'ItemId'        => $sAsin,
				'ResponseGroup' => 'Medium,Offers,VariationSummary,Reviews,BrowseNodes',
				'MerchantId'    => 'All'
			),
			trim( $config['publicKey'] ),
			trim( $config['privateKey'] ),
			trim( $config['associateTag'] )
		);

		$response = wp_remote_get( $request );
		if ( is_wp_error( $response ) ) {
			return false;
		} else {
			$pxml = @simplexml_load_string( $response['body'] );
			if ( $pxml === false ) {
				return false;
			} else {
				if ( isset( $config['bStatisticsAutoclear'] ) && $config['bStatisticsAutoclear'] == '1' ) {
					$wpdb->delete( $wpdb->prefix . 'wpapn_errors', array( 'asin' => $sAsin ), array( '%s' ) );
				}
				if ( isset( $pxml->Error ) ) {
					if ( (string) $pxml->Error->Code == 'RequestThrottled' ) {
						usleep( 750000 );
					}
					/**
					 * Wir gehen von nicht existentem Artikel aus und schauen nach Ersatz
					 */
					if ( $iRetry > 0 ) {
						$sNewAsin = amazilonCheckXchange( $sAsin, true );
						if ( $sAsin != $sNewAsin ) {
							return amazilonItemLookup( $sNewAsin, 0 );
						}
					}

					return amazilonItemLookup( $sAsin, $iRetry + 1 );
				}
				$aItem          = array();
				$aItem['state'] = date( 'Y-m-d H:i:s' );
				$aItem['asin']  = $sAsin;

				/**
				 * Artikel nicht bestellbar
				 */
				if ( ! isset( $pxml->Items->Item->ItemAttributes->Title ) || ! isset( $pxml->Items->Item->OfferSummary->TotalNew ) || (int) $pxml->Items->Item->OfferSummary->TotalNew == 0 ) {
					$sNewAsin = amazilonCheckXchange( $sAsin, true );
					if ( $sAsin != $sNewAsin ) {
						return amazilonItemLookup( $sNewAsin, 0 );
					}
				}

				if ( isset( $pxml->Items->Item->ItemAttributes->Title ) ) {

					$aItem['title']       = (string) $pxml->Items->Item->ItemAttributes->Title;
					$aItem['description'] = false;
					if ( isset( $pxml->Items->Item->EditorialReviews->EditorialReview->Content ) ) {
						$aItem['description'] = (string) $pxml->Items->Item->EditorialReviews->EditorialReview->Content;
					}
					$aItem['preis'] = array(
						'preis'    => false,
						'waehrung' => __( 'N/A', 'amazilon' ),
						'discount' => false
					);
					if ( isset( $pxml->Items->Item->OfferSummary->LowestNewPrice->Amount ) ) {
						$aItem['preis'] = array(
							'preis'    => (int) $pxml->Items->Item->OfferSummary->LowestNewPrice->Amount,
							'waehrung' => (string) $pxml->Items->Item->OfferSummary->LowestNewPrice->CurrencyCode,
							'discount' => false
						);
					}
					if ( $aItem['preis']['preis'] == false && isset( $pxml->Items->Item->VariationSummary->LowestPrice->Amount ) && (int) $pxml->Items->Item->VariationSummary->LowestPrice->Amount > 0 ) {
						$aItem['preis'] = array(
							'preis'    => (int) $pxml->Items->Item->VariationSummary->LowestPrice->Amount,
							'waehrung' => (string) $pxml->Items->Item->VariationSummary->LowestPrice->CurrencyCode,
							'discount' => false
						);
					}

					if ( ! isset( $pxml->Items->Item->OfferSummary->TotalNew ) || (int) $pxml->Items->Item->OfferSummary->TotalNew == 0 ) {
						if ( ! isset( $aItem['title'] ) || empty( $aItem['title'] ) || is_null( $aItem['title'] ) ) {
							$aItem['title'] = __( 'Productinformation not retrievable', 'amazilon' );
						}
						amazilonLogAdd( $sAsin, $aItem['title'], __( 'Item not available', 'amazilon' ) );
					}

					if ( isset( $pxml->Items->Item->ItemAttributes->ListPrice ) ) {
						$aItem['streichpreis'] = array(
							'preis'    => (int) $pxml->Items->Item->ItemAttributes->ListPrice->Amount,
							'waehrung' => (string) $pxml->Items->Item->ItemAttributes->ListPrice->CurrencyCode
						);
					} else {
						$aItem['streichpreis'] = array(
							'preis'    => false,
							'waehrung' => __( 'N/A', 'amazilon' )
						);
					}
					if ( $aItem['streichpreis']['preis'] > $aItem['preis']['preis'] ) {
						$aItem['preis']['discount'] = function_exists( 'bcsub' ) ? bcsub( $aItem['streichpreis']['preis'],
							$aItem['preis']['preis'], 8 ) : $aItem['streichpreis']['preis'] - $aItem['preis']['preis'];
					}
					$aItem['isPrime'] = isset( $pxml->Items->Item->Offers->Offer->OfferListing->IsEligibleForSuperSaverShipping ) ? (int) $pxml->Items->Item->Offers->Offer->OfferListing->IsEligibleForSuperSaverShipping : 0;
					$aItem['images']  = array(
						'0' => array(
							'small'  => (string) $pxml->Items->Item->SmallImage->URL, /* 75x75 */
							'medium' => (string) $pxml->Items->Item->MediumImage->URL, /* 160x160 */
							'large'  => (string) $pxml->Items->Item->LargeImage->URL /* 500x500 */
						)
					);
					if ( isset( $pxml->Items->Item->ImageSets ) ) {
						$aImageSets = (array) $pxml->Items->Item->ImageSets;
						if ( isset( $aImageSets['ImageSet'] ) && is_array( $aImageSets['ImageSet'] ) && count( $aImageSets['ImageSet'] ) > 0 ) {
							for ( $iImage = 0; $iImage < count( $aImageSets['ImageSet'] ); $iImage ++ ) {
								if ( ! isset( $aImageSets['ImageSet'][ $iImage ] ) ) {
									continue;
								}
								$aImage = $aImageSets['ImageSet'][ $iImage ];
								if ( is_object( $aImage ) ) {
									$aImage = (array) $aImage;
								}
								if ( isset( $aImage['@attributes']['Category'] ) && (string) $aImage['@attributes']['Category'] != 'variant' ) {
									continue;
								}
								array_push( $aItem['images'], array(
										'small'  => (string) $aImage['SmallImage']->URL,
										'medium' => (string) $aImage['MediumImage']->URL,
										'large'  => (string) $aImage['LargeImage']->URL
									)
								);
							}
						}
					}
					$aItem['sLink']          = (string) $pxml->Items->Item->DetailPageURL;
					$aItem['sReviewsIframe'] = false;
					$aItem['fReviewsStars']  = false;
					$aItem['iReviewsCount']  = 0;
					if ( $pxml->Items->Item->CustomerReviews->HasReviews ) {
						$aItem['sReviewsIframe'] = (string) $pxml->Items->Item->CustomerReviews->IFrameURL;
						$aReviews                = amazilonGetReviews( $aItem['sReviewsIframe'] );
						if ( $aReviews !== false ) {
							$aItem['fReviewsStars'] = $aReviews['avg'];
							$aItem['iReviewsCount'] = $aReviews['count'];
						}
					}
				}
				$aItem['aBrowseNodes'] = array();
				for ( $iBrowseNode = 0; isset( $pxml->Items->Item->BrowseNodes->BrowseNode[ $iBrowseNode ] ); $iBrowseNode ++ ) {
					$oBrowseNode = $pxml->Items->Item->BrowseNodes->BrowseNode[ $iBrowseNode ];
					if ( isset( $oBrowseNode->IsCategoryRoot ) && $oBrowseNode->IsCategoryRoot == '1' ) {
						continue;
					}
					array_push( $aItem['aBrowseNodes'],
						array( 'name' => (string) $oBrowseNode->Name, 'id' => (int) $oBrowseNode->BrowseNodeId ) );
				}

				$aItem['aFeatures'] = array();
				if ( isset( $pxml->Items->Item->ItemAttributes->Feature ) && count( (array) $pxml->Items->Item->ItemAttributes->Feature ) > 0 ) {
					for ( $iFeature = 0; $iFeature < count( (array) $pxml->Items->Item->ItemAttributes->Feature ); $iFeature ++ ) {
						array_push( $aItem['aFeatures'],
							(string) $pxml->Items->Item->ItemAttributes->Feature[ $iFeature ] );
					}
				}

				return $aItem;
			}
		}

	} catch ( Exception $e ) {
		update_option( 'bowsxWpApnError', $e->getMessage() );

		return false;
	}
}

function amazilonMakeSsl( $sUrl ) {
	$config = get_option( 'bowsxWpApn' );
	if ( ! isset( $config['useSSL'] ) || (int) $config['useSSL'] != 1 ) {
		return $sUrl;
	}

	return str_replace( 'http://ecx.', 'https://images-na.ssl-', $sUrl );
}

function amazilonMakeCurrency( $sCurrencyCode ) {
	$config = get_option( 'bowsxWpApn' );
	if ( ! isset( $config['useCurrencySymbol'] ) || (int) $config['useCurrencySymbol'] != 1 ) {
		return $sCurrencyCode;
	}

	return str_replace( 'EUR', '&euro;', $sCurrencyCode );
}

function amazilonMakeUrl( $sUrl, $sAsin ) {
	$config = get_option( 'bowsxWpApn' );
	if ( ! isset( $config['urlFormat'] ) || (int) $config['urlFormat'] == 0 ) {
		return $sUrl;
	}
	$sAsin = amazilonCheckXchange( $sAsin );
	switch ( $config['urlFormat'] ) {
		case '1':
			return 'https://www.amazon.de/exec/obidos/ASIN/' . urlencode( $sAsin ) . '/' . urlencode( $config['associateTag'] ) . '?linkCode=ogi';
			break;
		case '2':
			return 'https://www.amazon.de/dp/' . urlencode( $sAsin ) . '/?tag=' . urlencode( $config['associateTag'] ) . '&linkCode=ogi';
			break;
		default:
			return $sUrl;
	}
}

function amazilonNofollow( $sRel = '' ) {
	if ( ! empty( $sRel ) && substr_count( $sRel, 'follow' ) > 0 ) {
		return ' rel="' . esc_attr( $sRel ) . '"';
	}

	$config = get_option( 'bowsxWpApn' );
	if ( ! isset( $config['useNofollow'] ) || (int) $config['useNofollow'] != 1 ) {
		if ( ! empty( $sRel ) ) {
			return ' rel="' . esc_attr( $sRel ) . '"';
		} else {
			return '';
		}
	}

	if ( ! empty( $sRel ) ) {
		return ' rel="nofollow ' . esc_attr( $sRel ) . '"';
	}

	return ' rel="nofollow"';
}

function amazilonOnUpdateSettings() {
	if ( isset( $_GET['settings-updated'] ) && $_GET['settings-updated'] ) {
		amazilonCleanup();
		if ( amazilonCheckCredentials() ) {
			wp_redirect( get_admin_url( null, 'admin.php?page=amazilon-options&msg=1' ) );
			die();
		} else {
			wp_redirect( get_admin_url( null, 'admin.php?page=amazilon-options&msg=2' ) );
			die();
		}
		wp_redirect( get_admin_url( null, 'admin.php?page=amazilon-options' ) );
		die();
	}

	return true;
}

function amazilonCheckCredentials( $try = 0 ) {
	require_once trailingslashit( dirname( __FILE__ ) ) . 'libs/paapi5.php';

	if ( $try >= 3 ) {
		return false;
	}

	$config = get_option( 'bowsxWpApn' );
	if ( empty( $config['publicKey'] ) || empty( $config['privateKey'] ) || empty( $config['associateTag'] ) ) {

		return false;
	}

	$try ++;
	if ( paapi5_getItem( 'B07PHPXHQS' ) !== false ) {
		update_option( 'amazilon_paapi5mode', 1 );

		return true;
	}
	update_option( 'amazilon_paapi5mode', 0 );

	$request = amazilon_aws_request(
		'de',
		array(
			'Operation'     => 'ItemLookup',
			'ItemId'        => 'B07PHPXHQS',
			'ResponseGroup' => 'Small'
		),
		trim( $config['publicKey'] ),
		trim( $config['privateKey'] ),
		trim( $config['associateTag'] )
	);

	$response = wp_remote_get( $request );
	if ( is_wp_error( $response ) ) {
		return false;
	} elseif ( wp_remote_retrieve_response_code( $response ) != 200 ) {
		return false;
	} else {
		$pxml = @simplexml_load_string( $response['body'] );
		if ( $pxml === false ) {
			usleep( 500000 );

			return amazilonCheckCredentials( $try );
		} elseif ( count( $pxml->Items->Request->Errors ) > 0 ) {
			return false;
		} else {
			return true;
		}
	}
}

function amazilonAddActionLink( $aLinks ) {
	$clear_cache = '<a href="#" onclick="jQuery(document).ready(function($) { var data = { \'action\': \'amazilonClearCache\', \'security\': \'' . wp_create_nonce( 'amazilonCC' . date( 'Ym' ) ) . '\' }; jQuery.post(ajaxurl, data, function(response) { alert(response); }); }); return false;">' . __( 'Clear cache',
			'amazilon' ) . '</a>';
	array_unshift( $aLinks, $clear_cache );
	$help = '<a href="' . admin_url( 'admin.php?page=amazilon-help' ) . '">' . __( 'Instructions / Help',
			'amazilon' ) . '</a>';
	array_unshift( $aLinks, $help );

	return $aLinks;
}

function amazilonClearCache_callback() {
	if ( ! check_ajax_referer( 'amazilonCC' . date( 'Ym' ), 'security', false ) ) {
		echo __( 'Security mistake. Please the reload the page and try again. ', 'amazilon' );
		wp_die();
	}
	amazilonClearCache();
	echo __( 'Amazilon-Cache successfully emptied', 'amazilon' );
	wp_die();
}

function amazilonShorten_callback() {
	global $wpdb;
	$aReturn = array(
		'status' => 'error',
		'msg'    => '',
		'data'   => ''
	);
	if ( ! isset( $_POST['scode'] ) || empty( $_POST['scode'] ) ) {
		$aReturn['status'] = 'error';
		$aReturn['msg']    = __( 'No valid Shortcode transmitted!', 'amazilon' );
	} else {
		$sCode = stripslashes_deep( $_POST['scode'] );
		$c32   = crc32( trim( $sCode ) );
		$aRow  = $wpdb->get_row( $wpdb->prepare( 'SELECT id FROM ' . $wpdb->prefix . 'amazilon_scodes WHERE c32="%d" AND code="%s"',
			$c32, trim( $sCode ) ) );
		if ( ! is_null( $aRow ) ) {
			$aReturn['status'] = 'ok';
			$aReturn['msg']    = __( 'Shortened code already existed, it got copied to clipboard!', 'amazilon' );
			$aReturn['data']   = '[amazilon id=' . (int) $aRow->id . ']';
		} elseif ( $wpdb->insert( $wpdb->prefix . 'amazilon_scodes', array(
				'c32'   => $c32,
				'name'  => __( 'Generated at ',
						'amazilon' ) . date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ),
						time() ),
				'code'  => trim( $sCode ),
				'coded' => ''
			), array( '%d', '%s', '%s', '%s' ) ) !== false ) {
			$aReturn['status'] = 'ok';
			$aReturn['msg']    = __( 'Shortened and copied to clipboard!', 'amazilon' );
			$aReturn['data']   = '[amazilon id=' . (int) $wpdb->insert_id . ']';
		} else {
			$aReturn['status'] = 'error';
			$aReturn['msg']    = __( 'Internal Error, could not save to database. Please retry.', 'amazilon' );
		}
	}
	echo json_encode( $aReturn );
	wp_die();
}

function amazilonCT_callback() {
	global $wpdb;
	$iId = url_to_postid( $_POST['r'] );
	if ( $iId > 0 ) {
		$_POST['r'] = get_permalink( $iId );
	}
	$wpdb->insert( $wpdb->prefix . 'amazilon_clicktracker', array(
		'c32'     => crc32( $_POST['asin'] . $_POST['sc'] . $_POST['tag'] . $_POST['r'] ),
		'asin'    => $_POST['asin'],
		'sc'      => $_POST['sc'],
		'tag'     => $_POST['tag'],
		'referer' => $_POST['r'],
		'title'   => $_POST['t']
	), '%s' );
	wp_die();
}

function amazilonPreview_callback() {
	if ( ! check_ajax_referer( 'amazilonCC' . date( 'Ym' ), 'security', false ) ) {
		echo __( 'Security mistake. Please the reload the page and try again. ', 'amazilon' );
		wp_die();
	}
	if ( ! isset( $_POST['template'] ) || ! isset( $_POST['asin'] ) ) {
		echo __( 'Parameter error! Please reload the page and try again. ', 'amazilon' );
		wp_die();
	}

	switch ( $_POST['template'] ) {
		case 'tpl-1':
		case 'tpl-1s':
		case 'tpl-2':
		case 'tpl-2s':
		case 'tpl-3':
		case 'tpl-3s':
		case 'tpl-4':
		case 'tpl-4s':
		case 'tpl-5':
		case 'tpl-5s':
		case 'tpl-6':
		case 'tpl-6s':
		case 'tpl-7':
		case 'tpl-7s':
			$sReturn = '[apn typ="template" template="' . esc_attr( trim( $_POST['template'] ) ) . '" asin="' . esc_attr( trim( $_POST['asin'] ) ) . '" tag="' . esc_attr( trim( $_POST['tracking'] ) ) . '" tpl-infobox="' . (int) $_POST['bInfobox'] . '" tpl-stars="' . (int) $_POST['bStars'] . '" tpl-pname="' . esc_attr( trim( $_POST['sTplPname'] ) ) . '" tpl-buttontext="' . esc_attr( trim( $_POST['sTplButtontext'] ) ) . '" tpl-buttontpl="' . esc_attr( $_POST['sTplButtonTpl'] ) . '"';
			if ( isset( $_POST['iTplFeatures'] ) && (int) $_POST['iTplFeatures'] > 0 ) {
				$sReturn .= ' tpl-features="' . (int) $_POST['iTplFeatures'] . '"';
			}
			if ( isset( $_POST['iTplFmax'] ) && (int) $_POST['iTplFmax'] > 0 && (int) $_POST['iTplFmax'] < 500 ) {
				$sReturn .= ' tpl-fmax="' . (int) $_POST['iTplFmax'] . '"';
			}
			$sReturn .= ']';
			echo do_shortcode( $sReturn );
			break;
		case 'vergleich':
		case 'vergleich2':
			$sReturn = '[apn typ="' . esc_attr( $_POST['template'] ) . '" asin="';
			$sReturn .= esc_attr( trim( $_POST['asin'] ) );
			$sReturn .= '" tag="' . esc_attr( trim( $_POST['tracking'] ) ) . '" tpl-infobox="' . (int) $_POST['bInfobox'] . '" tpl-stars="' . (int) $_POST['bStars'] . '"';
			if ( isset( $_POST['tplSavings'] ) && $_POST['tplSavings'] == 'false' ) {
				$sReturn .= ' tpl-savings="false"';
			}
			if ( isset( $_POST['tplPrime'] ) && $_POST['tplPrime'] == 'false' ) {
				$sReturn .= ' tpl-prime="false"';
			}
			if ( isset( $_POST['sTplButtontext'] ) && ! empty( $_POST['sTplButtontext'] ) ) {
				$sReturn .= ' tpl-buttontext="' . esc_attr( $_POST['sTplButtontext'] ) . '"';
			}
			if ( isset( $_POST['sTplButtonTpl'] ) && $_POST['sTplButtonTpl'] != '' ) {
				$sReturn .= ' tpl-buttontpl="' . (int) $_POST['sTplButtonTpl'] . '"';
			}
			if ( isset( $_POST['iTplFeatures'] ) && (int) $_POST['iTplFeatures'] > 0 ) {
				$sReturn .= ' tpl-features="' . (int) $_POST['iTplFeatures'] . '"';
			}
			if ( isset( $_POST['iTplFmax'] ) && (int) $_POST['iTplFmax'] > 0 && (int) $_POST['iTplFmax'] < 500 ) {
				$sReturn .= ' tpl-fmax="' . (int) $_POST['iTplFmax'] . '"';
			}
			if ( $_POST['template'] == 'vergleich2' && isset( $_POST['bHidelegend'] ) && $_POST['bHidelegend'] != '' ) {
				$sReturn .= ' tpl-hidelegend="' . esc_attr( $_POST['bHidelegend'] ) . '"';
			} elseif ( $_POST['template'] == 'vergleich2' ) {
				if ( isset( $_POST['sTplHeaderlegend'] ) && $_POST['sTplHeaderlegend'] != '' ) {
					$sReturn .= ' tpl-headerlegend="' . esc_attr( $_POST['sTplHeaderlegend'] ) . '"';
				}
				if ( isset( $_POST['sTplImagelegend'] ) && $_POST['sTplImagelegend'] != '' ) {
					$sReturn .= ' tpl-imagelegend="' . esc_attr( $_POST['sTplImagelegend'] ) . '"';
				}
				if ( isset( $_POST['sTplProductlegend'] ) && $_POST['sTplProductlegend'] != '' ) {
					$sReturn .= ' tpl-productlegend="' . esc_attr( $_POST['sTplProductlegend'] ) . '"';
				}
				if ( isset( $_POST['sTplPricelegend'] ) && $_POST['sTplPricelegend'] != '' ) {
					$sReturn .= ' tpl-pricelegend="' . esc_attr( $_POST['sTplPricelegend'] ) . '"';
				}
				if ( isset( $_POST['sTplSavingslegend'] ) && $_POST['sTplSavingslegend'] != '' ) {
					$sReturn .= ' tpl-savingslegend="' . esc_attr( $_POST['sTplSavingslegend'] ) . '"';
				}
				if ( isset( $_POST['sTplRatingslegend'] ) && $_POST['sTplRatingslegend'] != '' ) {
					$sReturn .= ' tpl-ratingslegend="' . esc_attr( $_POST['sTplRatingslegend'] ) . '"';
				}
				if ( isset( $_POST['sTplPrimelegend'] ) && $_POST['sTplPrimelegend'] != '' ) {
					$sReturn .= ' tpl-primelegend="' . esc_attr( $_POST['sTplPrimelegend'] ) . '"';
				}
				if ( isset( $_POST['sTplButtonlegend'] ) && $_POST['sTplButtonlegend'] != '' ) {
					$sReturn .= ' tpl-buttonlegend="' . esc_attr( $_POST['sTplButtonlegend'] ) . '"';
				}
				if ( isset( $_POST['sTplStatelegend'] ) && $_POST['sTplStatelegend'] != '' ) {
					$sReturn .= ' tpl-statelegend="' . esc_attr( $_POST['sTplStatelegend'] ) . '"';
				}
			}
			$sReturn .= ']';
			echo do_shortcode( $sReturn );
			break;
		case 'button':
			$sReturn = '[apn asin="';
			$sReturn .= esc_attr( trim( $_POST['asin'] ) );
			$sReturn .= '" typ="button"';
			if ( isset( $_POST['button'] ) && (int) $_POST['button'] > 0 ) {
				$sReturn .= ' template="' . (int) $_POST['button'] . '"';
			}
			$sReturn .= ' tag="' . esc_attr( trim( $_POST['tracking'] ) ) . '"' . ( ! empty( $_POST['linktext'] ) ? ' true="' . esc_attr( trim( $_POST['linktext'] ) ) . '"' : '' ) . ' false="" tpl-pname="' . esc_attr( trim( $_POST['sTplPname'] ) ) . '"]';
			echo do_shortcode( $sReturn );
			break;
		default:
			echo __( 'Unkown template!', 'amazilon' );
			break;
	}

	wp_die();
}

function amazilonBestsellersPreview_callback() {
	if ( ! check_ajax_referer( 'amazilonCC' . date( 'Ym' ), 'security', false ) ) {
		echo __( 'Security mistake. Please the reload the page and try again. ', 'amazilon' );
		wp_die();
	}

	if ( ! isset( $_POST['sTemplate'] ) || ! isset( $_POST['sNode'] ) ) {
		echo __( 'Parameter error! Please reload the page and try again. ', 'amazilon' );
		wp_die();
	}

	if ( ! isset( $_POST['iMax'] ) || (int) $_POST['iMax'] < 1 || (int) $_POST['iMax'] > 10 ) {
		$_POST['iMax'] = 10;
	}

	$sHtml = '[apn typ="bestsellers" node="' . esc_attr( $_POST['sNode'] ) . '" max="' . (int) $_POST['iMax'] . '"';

	if ( isset( $_POST['bInfobox'] ) ) {
		$sHtml .= ' tpl-infobox="' . (int) $_POST['bInfobox'] . '"';
	}

	if ( isset( $_POST['sTag'] ) ) {
		$sHtml .= ' tag="' . esc_attr( $_POST['sTag'] ) . '"';
	}

	if ( isset( $_POST['sTplLabel'] ) && ! empty( $_POST['sTplLabel'] ) ) {
		$sHtml .= ' tpl-label="' . esc_attr( $_POST['sTplLabel'] ) . '"';
	}

	if ( isset( $_POST['sTplButtontext'] ) && ! empty( $_POST['sTplButtontext'] ) ) {
		$sHtml .= ' tpl-buttontext="' . esc_attr( $_POST['sTplButtontext'] ) . '"';
	}

	if ( isset( $_POST['sTplButtonTpl'] ) && $_POST['sTplButtonTpl'] != '' ) {
		$sHtml .= ' tpl-buttontpl="' . esc_attr( $_POST['sTplButtonTpl'] ) . '"';
	}

	if ( isset( $_POST['sTplSavings'] ) && ! empty( $_POST['sTplSavings'] ) ) {
		$sHtml .= ' tpl-savings="' . esc_attr( $_POST['sTplSavings'] ) . '"';
	}

	if ( isset( $_POST['sTplPrime'] ) && ! empty( $_POST['sTplPrime'] ) ) {
		$sHtml .= ' tpl-prime="' . esc_attr( $_POST['sTplPrime'] ) . '"';
	}

	if ( isset( $_POST['sTemplate'] ) ) {
		$sHtml .= ' template="' . esc_attr( $_POST['sTemplate'] ) . '"';
	}

	if ( isset( $_POST['bStars'] ) ) {
		$sHtml .= ' tpl-stars="' . (int) $_POST['bStars'] . '"';
	}

	if ( $_POST['sTemplate'] == 'vergleich2' && isset( $_POST['bHidelegend'] ) && ! empty( $_POST['bHidelegend'] ) ) {
		$sHtml .= ' tpl-hidelegend="1"';
	} elseif ( $_POST['sTemplate'] == 'vergleich2' && ( ! isset( $_POST['bHidelegend'] ) || empty( $_POST['bHidelegend'] ) ) ) {
		if ( isset( $_POST['sTplHeaderlegend'] ) && $_POST['sTplHeaderlegend'] != '' ) {
			$sHtml .= ' tpl-headerlegend="' . esc_attr( $_POST['sTplHeaderlegend'] ) . '"';
		}
		if ( isset( $_POST['sTplImagelegend'] ) && $_POST['sTplImagelegend'] != '' ) {
			$sHtml .= ' tpl-imagelegend="' . esc_attr( $_POST['sTplImagelegend'] ) . '"';
		}
		if ( isset( $_POST['sTplProductlegend'] ) && $_POST['sTplProductlegend'] != '' ) {
			$sHtml .= ' tpl-productlegend="' . esc_attr( $_POST['sTplProductlegend'] ) . '"';
		}
		if ( isset( $_POST['sTplPricelegend'] ) && $_POST['sTplPricelegend'] != '' ) {
			$sHtml .= ' tpl-pricelegend="' . esc_attr( $_POST['sTplPricelegend'] ) . '"';
		}
		if ( isset( $_POST['sTplSavingslegend'] ) && $_POST['sTplSavingslegend'] != '' ) {
			$sHtml .= ' tpl-savingslegend="' . esc_attr( $_POST['sTplSavingslegend'] ) . '"';
		}
		if ( isset( $_POST['sTplRatingslegend'] ) && $_POST['sTplRatingslegend'] != '' ) {
			$sHtml .= ' tpl-ratingslegend="' . esc_attr( $_POST['sTplRatingslegend'] ) . '"';
		}
		if ( isset( $_POST['sTplPrimelegend'] ) && $_POST['sTplPrimelegend'] != '' ) {
			$sHtml .= ' tpl-primelegend="' . esc_attr( $_POST['sTplPrimelegend'] ) . '"';
		}
		if ( isset( $_POST['sTplButtonlegend'] ) && $_POST['sTplButtonlegend'] != '' ) {
			$sHtml .= ' tpl-buttonlegend="' . esc_attr( $_POST['sTplButtonlegend'] ) . '"';
		}
		if ( isset( $_POST['sTplStatelegend'] ) && $_POST['sTplStatelegend'] != '' ) {
			$sHtml .= ' tpl-statelegend="' . esc_attr( $_POST['sTplStatelegend'] ) . '"';
		}
	}

	$sHtml .= ']';
	echo do_shortcode( $sHtml );
	wp_die();
}

function amazilonSimilar_callback() {
	global $__amazilonSearchindexes;
	if ( ! check_ajax_referer( 'amazilonCC' . date( 'Ym' ), 'security', false ) ) {
		echo __( 'Security mistake. Please the reload the page and try again. ', 'amazilon' );
		wp_die();
	}
	if ( ! isset( $_POST['q'] ) ) {
		echo __( 'Parameter error! Please reload the page and try again. ', 'amazilon' );
		wp_die();
	}
	$aItems = amazilonFindSimilarItems( $_POST['q'] );
	if ( count( $aItems ) > 0 ) {
		for ( $iItem = 0; $iItem < count( $aItems ); $iItem ++ ) {
			echo do_shortcode( '<a class="amazilon-search-result-entry" data-asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" href="#" style="min-height: 85px; display: block; border-bottom: 1px dashed black; padding: .5em 0; clear: both;"><p style="width: 105px; margin: 0; float: left;">[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="bild"]</p> <span style="overflow: hidden;"><span style="display: flex;"><span style="text-decoration: line-through; color: #C00; margin-right: .5em;">[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="streichpreis" false=""]</span> <span style="margin-right: .5em;">[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="preis"]</span> [apnx asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="prime" false=""]<img class="prime" src="' . plugins_url( 'gfx/ampr.png',
					__FILE__ ) . '" alt="' . __( 'Amazon Prime',
					'amazilon' ) . '">[/apnx][apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="bewertung"] [apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="anzahlbewertungen" false="" tpl-format="(%s)"]</span>[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : '' ) . '"]</span></a>' );
		}
	} else {
		echo '- ' . __( 'no events', 'amazilon' ) . ' - ';
	}
	wp_die();
}

function amazilonSearch_callback() {
	global $__amazilonSearchindexes, $__amazilonNoXchange;
	$__amazilonNoXchange = true;
	if ( ! check_ajax_referer( 'amazilonCC' . date( 'Ym' ), 'security', false ) ) {
		echo __( 'Security mistake. Please the reload the page and try again. ', 'amazilon' );
		wp_die();
	}
	if ( ! isset( $_POST['q'] ) ) {
		echo __( 'Parameter error! Please reload the page and try again. ', 'amazilon' );
		wp_die();
	}
	if ( ! isset( $_POST['sIndex'] ) || ! isset( $__amazilonSearchindexes['de'][ $_POST['sIndex'] ] ) ) {
		$_POST['sIndex'] = 'All';
	}
	$aItems = amazilonItemSearch( $_POST['q'], $_POST['sIndex'] );
	if ( count( $aItems ) > 0 ) {
		for ( $iItem = 0; $iItem < count( $aItems ); $iItem ++ ) {
			echo do_shortcode( '<a class="amazilon-search-result-entry" data-asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" href="#" style="min-height: 85px; display: block; border-bottom: 1px dashed black; padding: .5em 0; clear: both;"><p style="width: 105px; margin: 0; float: left;">[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="bild"]</p> <span style="overflow: hidden;"><span style="display: flex;"><span style="text-decoration: line-through; color: #C00; margin-right: .5em;">[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="streichpreis" false=""]</span> <span style="margin-right: .5em;">[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="preis"]</span> [apnx asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="prime" false=""]<img class="prime" src="' . plugins_url( 'gfx/ampr.png',
					__FILE__ ) . '" alt="' . __( 'Amazon Prime',
					'amazilon' ) . '">[/apnx][apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="bewertung"] [apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="anzahlbewertungen" false="" tpl-format="(%s)"]</span>[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : '' ) . '"]</span></a>' );
		}
	} else {
		echo '- ' . __( 'no events', 'amazilon' ) . ' - ';
	}
	wp_die();
}

function amazilonSearchCategories_callback() {
	global $__amazilonSearchindexes;
	if ( ! check_ajax_referer( 'amazilonCC' . date( 'Ym' ), 'security', false ) ) {
		echo __( 'Security mistake. Please the reload the page and try again. ', 'amazilon' );
		wp_die();
	}
	if ( ! isset( $_POST['q'] ) ) {
		echo __( 'Parameter error! Please reload the page and try again. ', 'amazilon' );
		wp_die();
	}
	if ( ! isset( $_POST['sIndex'] ) || ! isset( $__amazilonSearchindexes['de'][ $_POST['sIndex'] ] ) ) {
		$_POST['sIndex'] = 'All';
	}
	$aItems = amazilonItemSearch( $_POST['q'], $_POST['sIndex'] );
	if ( count( $aItems ) > 0 ) {
		for ( $iItem = 0; $iItem < count( $aItems ); $iItem ++ ) {
			$sHtml = '<div class="amazilon-search-result-entry" style="min-height: 85px; display: block; border-bottom: 1px dashed black; padding: .5em 0; clear: both;"><p style="width: 105px; margin: 0; float: left;">[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="bild"]</p> <span style="overflow: hidden;"><span style="display: flex;"><span style="text-decoration: line-through; color: #C00; margin-right: .5em;">[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="streichpreis" false=""]</span> <span style="margin-right: .5em;">[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="preis"]</span> [apnx asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="prime" false=""]<img class="prime" src="' . plugins_url( 'gfx/ampr.png',
					__FILE__ ) . '" alt="' . __( 'Amazon Prime',
					'amazilon' ) . '">[/apnx]</span>[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" typ="titel" max="' . ( isset( $atts['tpl-tmax'] ) && (int) $atts['tpl-tmax'] > 0 ? (int) $atts['tpl-tmax'] : '' ) . '"]</span><br style="clear: both;" /><b>' . __( 'Categories',
					'amazilon' ) . ':</b><br />';
			for ( $iNode = 0; $iNode < count( $aItems[ $iItem ]['aBrowseNodes'] ); $iNode ++ ) {
				if ( $iNode > 0 ) {
					$sHtml .= ', ';
				}
				$sHtml .= '<a href="#" class="browsenode" data-browsenodeid="' . esc_attr( (int) $aItems[ $iItem ]['aBrowseNodes'][ $iNode ]['id'] ) . '">' . esc_html( $aItems[ $iItem ]['aBrowseNodes'][ $iNode ]['name'] ) . '</a>';
			}
			$sHtml .= '</div>';
			echo do_shortcode( $sHtml );
		}
	} else {
		echo '- ' . __( 'no events', 'amazilon' ) . ' - ';
	}
	wp_die();
}

function amazilonBestsellers_callback() {
	global $__amazilonSearchindexes;

	if ( ! check_ajax_referer( 'amazilonCC' . date( 'Ym' ), 'security', false ) ) {
		echo __( 'Security mistake. Please the reload the page and try again. ', 'amazilon' );
		wp_die();
	}
	if ( isset( $_POST['BrowseNodeId'] ) ) {
		$iBrowseNodeId = (int) $_POST['BrowseNodeId'];
	} elseif ( isset( $_POST['MainBrowseNodeId'] ) ) {
		$iBrowseNodeId = (int) $_POST['MainBrowseNodeId'];
	} else {
		$iBrowseNodeId = - 1;
		$aKeys         = array_keys( $__amazilonSearchindexes['de'] );
		for ( $iKey = 0; $iKey < count( $aKeys ); $iKey ++ ) {
			$iBrowseNodeId = (int) $__amazilonSearchindexes['de'][ $aKeys[ $iKey ] ]['id'];
			if ( $iBrowseNodeId != - 1 ) {
				break;
			}
		}
	}

	$pxml = amazilonBrowseNodeLookup( $iBrowseNodeId );

	if ( $pxml === false ) {
		$aReturn = array(
			'success' => false,
			'msg'     => __( 'Error',
					'amazilon' ) . ': ' . __( 'Data retrieval at Amazon Webservices failed 3 times (Limit reached?), please try again.',
					'amazilon' )
		);
		$sReturn = json_encode( $aReturn );
		echo $sReturn;
		wp_die();
	} else {

		if ( isset( $pxml->BrowseNodes->Request->Errors ) ) {
			$aReturn = array(
				'success' => false,
				'msg'     => __( 'Error', 'amazilon' ) . ': ' . $pxml->BrowseNodes->Request->Errors->Error->Message
			);
			$sReturn = json_encode( $aReturn );
			echo $sReturn;
			wp_die();
		}
		$aAncestors = AmazilonGetAncestors( $pxml->BrowseNodes->BrowseNode->Ancestors );

		$aData = array(
			'breadcrumb' => array(),
			'childs'     => array()
		);

		for ( $iAncestor = - 1; isset( $aAncestors[ $iAncestor ] ); $iAncestor ++ ) {
			$aRow         = array();
			$aRow['id']   = $aAncestors[ $iAncestor ]->BrowseNodeId;
			$aRow['name'] = $aAncestors[ $iAncestor ]->Name;
			array_push( $aData['breadcrumb'], $aRow );
		}
		if ( ! isset( $pxml->BrowseNodes->BrowseNode->IsCategoryRoot ) || $pxml->BrowseNodes->BrowseNode->IsCategoryRoot != '1' ) {
			$aRow         = array();
			$aRow['id']   = (string) $pxml->BrowseNodes->BrowseNode->BrowseNodeId;
			$aRow['name'] = (string) $pxml->BrowseNodes->BrowseNode->Name;
			array_push( $aData['breadcrumb'], $aRow );
		} else {
			$aRow                = array_pop( $aData['breadcrumb'] );
			$aData['breadcrumb'] = array();
			$aRow['id']          = (string) $pxml->BrowseNodes->BrowseNode->BrowseNodeId;
			array_push( $aData['breadcrumb'], $aRow );
		}


		$oChildren = $pxml->BrowseNodes->BrowseNode->Children->BrowseNode;
		if ( count( $oChildren ) > 0 ) {
			for ( $iChild = 0; $iChild < count( $oChildren ); $iChild ++ ) {
				$aRow = array(
					'name' => (string) $oChildren[ $iChild ]->Name,
					'id'   => (string) $oChildren[ $iChild ]->BrowseNodeId
				);
				array_push( $aData['childs'], $aRow );
			}
		}
		$aReturn = array(
			'success' => true,
			'data'    => $aData
		);
		$sReturn = json_encode( $aReturn );
		echo $sReturn;
		wp_die();
	}
	wp_die();
}

function amazilonGetAncestors( &$oAncestors, $top = true ) {
	$aList = array();
	if ( isset( $oAncestors->BrowseNode ) && ( ! isset( $oAncestors->BrowseNode->IsCategoryRoot ) || $oAncestors->BrowseNode->IsCategoryRoot != '1' ) ) {
		$oAncestor               = new stdClass;
		$oAncestor->Name         = (string) $oAncestors->BrowseNode->Name;
		$oAncestor->BrowseNodeId = (string) $oAncestors->BrowseNode->BrowseNodeId;
		array_push( $aList, $oAncestor );
	}
	if ( isset( $oAncestors->BrowseNode->Ancestors ) ) {
		$aAncestors = AmazilonGetAncestors( $oAncestors->BrowseNode->Ancestors, false );
		$aList      = array_merge( $aList, $aAncestors );
	}
	if ( $top === true ) {
		$aFirst       = array_pop( $aList );
		$aList        = array_reverse( $aList );
		$aList[ - 1 ] = $aFirst;
	}

	return $aList;
}

function amazilonClearCache() {
	global $wpdb;
	$wpdb->query( 'DELETE FROM ' . $wpdb->prefix . 'options WHERE option_name LIKE "_transient_%amazilon_ASIN_%"' );
}

function amazilonAdminNotices() {
	if ( ! function_exists( 'simplexml_load_string' ) ) {
		echo '<div class="notice notice-error"><p><a href="' . get_admin_url( null,
				'admin.php?page=amazilon-options' ) . '">' . __( 'AmazonPartnernet',
				'amazilon' ) . '</a>: ' . esc_html( __( 'The php extension "SimpleXML" (enabled by default as of php 5.1.2) was forcefully disabled on this php environment! Amazilon requires this extension to parse and display data from Amazon.',
				'amazilon' ) ) . '</p></div>';
	}

	if ( ! get_option( 'amazilon_paapi5mode' ) ) {
		echo '<div class="notice notice-error"><p><a href="' . get_admin_url( null,
				'admin.php?page=amazilon-options' ) . '">' . __( 'AmazonPartnernet',
				'amazilon' ) . '</a>: ' . __( 'Your API-Credentials for Amazon Webservices are outdated and can not be used for current Amazon Webservices. You have to <a href="https://partnernet.amazon.de/gp/advertising/api/registration/welcome.html" target="_blank">create new Credentials on Amazon</a> in order to use Amazilon in future. Amazilon is running in deprecation mode and uses the old PA-API 4 which will be shut off by Amazon. When Amazon shuts it off Amazilon will not be able to retrieve and display any further information.',
				'amazilon' ) . '</p></div>';
	}

	$config = get_option( 'bowsxWpApn' );
	if ( $config !== false && ( empty( $config['publicKey'] ) || empty( $config['privateKey'] ) || empty( $config['associateTag'] ) ) ) {
		echo '<div class="notice notice-error"><p><a href="' . get_admin_url( null,
				'admin.php?page=amazilon-options' ) . '">' . __( 'AmazonPartnernet',
				'amazilon' ) . '</a>: ' . __( 'publicKey, privateKey or associateTag is empty!',
				'amazilon' ) . '</p></div>';
	}

	if ( ! amazilonCheck() ) {
		echo '<div class="notice notice-error"><p><a href="' . get_admin_url( null,
				'admin.php?page=amazilon-options' ) . '">' . __( 'AmazonPartnernet',
				'amazilon' ) . '</a>: ' . __( 'License number not entered, invalid or license comparison failed!',
				'amazilon' ) . ' <a href="' . get_admin_url( null,
				'admin.php?page=amazilon-options' ) . '">' . __( 'Enter the license number',
				'amazilon' ) . '</a></p></div>';
		$info = get_transient( 'bowsxWpApnInfo' );
		if ( $info !== false && ! empty( $info['msg'] ) ) {
			echo '<div class="notice notice-error"><p><a href="' . get_admin_url( null,
					'admin.php?page=amazilon-options' ) . '">' . __( 'AmazonPartnernet',
					'amazilon' ) . '</a>: ' . esc_html( $info['msg'] ) . '</p></div>';
		}
	}

	$msg = get_option( 'bowsxWpApnError' );
	if ( $msg !== false && ! empty( $msg ) ) {
		echo '<div class="notice notice-error"><p><a href="' . get_admin_url( null,
				'admin.php?page=amazilon-options' ) . '">' . __( 'AmazonPartnernet',
				'amazilon' ) . '</a>: ' . nl2br( esc_html( $msg ) ) . '</p></div>';
		update_option( 'bowsxWpApnError', '', false );
	}
}

function amazilonAdminBar( $adminBar ) {
	if ( ! is_admin_bar_showing() ) {
		return;
	}

	add_thickbox();
	echo '<style>#wp-admin-bar-amazilon{display:list-item !important} .amazilon-cache-icon,.amazilon-scg-icon,.amazilon-bg-icon,.amazilon-tplg-icon,.amazilon-bsg-icon{margin:0 !important}.ab-item .amazilon-cache-icon:before{content:"\f182";top:2px;margin:0}.ab-item .amazilon-scg-icon:before{content:"\f108";top:2px;margin:0}.ab-item .amazilon-bg-icon:before{content:"\f161";top:2px;margin:0}.ab-item .amazilon-tplg-icon:before{content:"\f123";top:2px;margin:0}.ab-item .amazilon-bsg-icon:before{content:"\f239";top:2px;margin:0}</style>';
	$adminBar->add_menu(
		array(
			'id'     => 'amazilon-cache',
			'href'   => '#',
			'parent' => 'top-secondary',
			'title'  => '<span class="amazilon-cache-icon ab-icon dashicons small"></span>',
			'meta'   => array(
				'title'   => __( 'Clear the Amazilon Cache', 'amazilon' ),
				'onclick' => 'jQuery(document).ready(function($) { var data = { "action": "amazilonClearCache", "security": "' . wp_create_nonce( 'amazilonCC' . date( 'Ym' ) ) . '" }; jQuery.post(ajaxurl, data, function(response) { alert(response); }); }); return false;'
			),
		)
	);
	if ( current_user_can( 'amazilon_use_generators' ) ) {
		$adminBar->add_menu(
			array(
				'id'     => 'amazilon-bsg',
				'href'   => admin_url( 'admin.php?page=amazilon-generators&jumpTo=generator-4&mini=true&TB_iframe=true' ),
				'parent' => 'top-secondary',
				'title'  => '<span class="amazilon-bsg-icon ab-icon dashicons small"></span>',
				'meta'   => array(
					'title'   => __( 'Amazilon Bestsellers-Generator', 'amazilon' ),
					'onclick' => 'jQuery(this).addClass("thickbox");'
				),
			)
		);
		$adminBar->add_menu(
			array(
				'id'     => 'amazilon-scg',
				'href'   => admin_url( 'admin.php?page=amazilon-generators&jumpTo=generator-1&mini=true&TB_iframe=true' ),
				'parent' => 'top-secondary',
				'title'  => '<span class="amazilon-scg-icon ab-icon dashicons small"></span>',
				'meta'   => array(
					'title'   => __( 'Amazilon Shortcode-Generator', 'amazilon' ),
					'onclick' => 'jQuery(this).addClass("thickbox");'
				),
			)
		);
		$adminBar->add_menu(
			array(
				'id'     => 'amazilon-bg',
				'href'   => admin_url( 'admin.php?page=amazilon-generators&jumpTo=generator-2&mini=true&TB_iframe=true' ),
				'parent' => 'top-secondary',
				'title'  => '<span class="amazilon-bg-icon ab-icon dashicons small"></span>',
				'meta'   => array(
					'title'   => __( 'Amazilon Button-Generator', 'amazilon' ),
					'onclick' => 'jQuery(this).addClass("thickbox");'
				),
			)
		);
		$adminBar->add_menu(
			array(
				'id'     => 'amazilon-tplg',
				'href'   => admin_url( 'admin.php?page=amazilon-generators&jumpTo=generator-3&mini=true&TB_iframe=true' ),
				'parent' => 'top-secondary',
				'title'  => '<span class="amazilon-tplg-icon ab-icon dashicons small"></span>',
				'meta'   => array(
					'title'   => __( 'Amazilon Template-Generator', 'amazilon' ),
					'onclick' => 'jQuery(this).addClass("thickbox");'
				),
			)
		);
	}
}

function amazilonStrShorter( $sIn, $iLength ) {
	$sReturn = $sIn;
	if ( strlen( $sIn ) > $iLength ) {
		$sReturn = substr( $sIn, 0, strrpos( substr( $sIn, 0, floor( $iLength - 2 ) ), ' ' ) ) . '...';
	}
	if ( $sReturn == '...' ) {
		$sReturn = substr( $sIn, 0, $iLength - 3 ) . '...';
	}

	return $sReturn;
}

function amazilonDaily() {
	global $wpdb;
	$config = get_option( 'bowsxWpApn' );
	if ( ! isset( $config['bReportAsin'] ) || (int) $config['bReportAsin'] != 1 ) {
		$wpdb->query( 'DELETE FROM ' . $wpdb->prefix . 'wpapn_errors' );

		return;
	}
	$aRows = $wpdb->get_results( 'SELECT asin, titel, msg, url FROM ' . $wpdb->prefix . 'wpapn_errors GROUP BY asin, url' );
	if ( count( $aRows ) < 1 ) {
		return;
	}

	for ( $i = 0; $i < count( $aRows ); $i ++ ) {
		$sMsg .= "\n\n" . $aRows[ $i ]->asin . ' | ' . $aRows[ $i ]->titel . "\n" . 'Fehlermeldung: ' . $aRows[ $i ]->msg . "\n" . 'aufgerufene URL: ' . $aRows[ $i ]->url;
	}

	if ( wp_mail( get_option( 'admin_email' ), 'amazilon: ASIN-Fehler im Blog "' . get_option( 'blogname' ) . '"',
		__( 'Hello,', 'amazilon' ) . "\n\n" . __( 'the following errors occurred', 'amazilon' ) . ': ' . $sMsg,
		'From: ' . get_option( 'admin_email' ) ) ) {
		$wpdb->query( 'DELETE FROM ' . $wpdb->prefix . 'wpapn_errors' );
	}
}

function amazilonInjectUpdate( $transient ) {
	global $__amazilonVersion;
	if ( empty( $transient->checked ) ) {
		return $transient;
	}
	$obj = amazilonGetUpdateInfo();
	if ( $obj !== false && isset( $obj->new_version ) && version_compare( $__amazilonVersion, $obj->new_version,
			'<' ) ) {
		$oInject                                      = new stdClass;
		$oInject->id                                  = - 1;
		$oInject->slug                                = 'amazilon';
		$oInject->plugin                              = 'amazilon/amazilon.php';
		$oInject->name                                = ( isset( $obj->name ) ? $obj->name : 'Amazilon' );
		$oInject->new_version                         = ( isset( $obj->new_version ) ? $obj->new_version : false );
		$oInject->url                                 = 'https://amazilon.com/';
		$oInject->package                             = ( isset( $obj->download_link ) ? $obj->download_link : false );
		$oInject->tested                              = ( isset( $obj->tested ) ? $obj->tested : false );
		$oInject->compatibility                       = new stdClass;
		$oInject->compatibility->scalar               = new stdClass;
		$oInject->compatibility->scalar->scalar       = '';
		$transient->response['amazilon/amazilon.php'] = $oInject;
	}

	return $transient;
}

function amazilonGetInfo( $false, $action, $arg ) {
	if ( isset( $arg->slug ) && $arg->slug == 'amazilon' ) {
		return amazilonGetUpdateInfo();
	}

	return false;
}

function amazilonGetUpdateInfo() {
	global $__amazilonVersion;
	$config  = get_option( 'bowsxWpApn' );
	$request = wp_remote_get( 'https://amazilon.com/license/updates.php?version=' . urlencode( $__amazilonVersion ) . '&license_key=' . urlencode( trim( $config['licenseKey'] ) ) );
	if ( ! is_wp_error( $request ) && wp_remote_retrieve_response_code( $request ) === 200 ) {
		return unserialize( $request['body'] );
	}

	return false;
}

function amazilonGetReviews( $sUrl ) {
	global $__amazilonVersion;
	$config = get_option( 'bowsxWpApn' );
	if ( ! isset( $config['bRetrieveStars'] ) || (int) $config['bRetrieveStars'] != 1 ) {
		return false;
	}

	$request = wp_remote_get( $sUrl );
	if ( ! is_wp_error( $request ) && wp_remote_retrieve_response_code( $request ) === 200 ) {
		$aReturn = array( 'avg' => .0, 'count' => 0 );
		if ( preg_match( '#<span class="asinReviewsSummary[^>]+>.+alt="(\d\.\d)\s[^"]+".+\(<a[^>]+>(\d+)\s#Umsi',
			$request['body'], $matches ) ) {
			$aReturn['avg']   = sprintf( '%.1F', $matches[1] );
			$aReturn['count'] = $matches[2];
		}

		return $aReturn;
	}

	return false;
}

add_filter( 'mce_buttons', 'amazilonMceButtons' );
function amazilonMceButtons( $buttons ) {
	if ( current_user_can( 'amazilon_use_generators' ) ) {
		array_push( $buttons, 'separator', 'amazilon-generators' );
	}

	return $buttons;
}

add_filter( 'mce_external_plugins', 'amazilonMceJs' );
function amazilonMceJs( $plugin_array ) {
	if ( current_user_can( 'amazilon_use_generators' ) ) {
		$plugin_array['amazilon'] = plugins_url( '/gfx/tinymce/mce.plugin.php', __FILE__ );
	}

	return $plugin_array;
}

function amazilonItemSetCache( $oItem, $iSeconds = 300 ) {
	if ( $oItem === false ) {
		return false;
	}
	$aItem          = array();
	$aItem['state'] = date( 'Y-m-d H:i:s' );
	$aItem['asin']  = (string) $oItem->ASIN;
	if ( isset( $oItem->ItemAttributes->Title ) ) {
		$aItem['title']       = (string) $oItem->ItemAttributes->Title;
		$aItem['description'] = false;
		if ( isset( $oItem->EditorialReviews->EditorialReview->Content ) ) {
			$aItem['description'] = (string) $oItem->EditorialReviews->EditorialReview->Content;
		}
		$aItem['preis'] = array(
			'preis'    => (int) $oItem->OfferSummary->LowestNewPrice->Amount,
			'waehrung' => (string) $oItem->OfferSummary->LowestNewPrice->CurrencyCode,
			'discount' => false
		);
		if ( isset( $oItem->ItemAttributes->ListPrice ) ) {
			$aItem['streichpreis'] = array(
				'preis'    => (int) $oItem->ItemAttributes->ListPrice->Amount,
				'waehrung' => (string) $oItem->ItemAttributes->ListPrice->CurrencyCode
			);
		} else {
			$aItem['streichpreis'] = array(
				'preis'    => false,
				'waehrung' => 'N/A'
			);
		}
		if ( $aItem['streichpreis']['preis'] > $aItem['preis']['preis'] ) {
			$aItem['preis']['discount'] = function_exists( 'bcsub' ) ? bcsub( $aItem['streichpreis']['preis'],
				$aItem['preis']['preis'], 8 ) : $aItem['streichpreis']['preis'] - $aItem['preis']['preis'];
		}
		$aItem['isPrime'] = (int) $oItem->Offers->Offer->OfferListing->IsEligibleForSuperSaverShipping;
		$aItem['images']  = array(
			0 => array(
				'small'  => (string) $oItem->SmallImage->URL, /* 75x75 */
				'medium' => (string) $oItem->MediumImage->URL, /* 160x160 */
				'large'  => (string) $oItem->LargeImage->URL /* 500x500 */
			)
		);
		if ( isset( $oItem->ImageSets ) ) {
			if ( count( (array) $oItem->ImageSets->ImageSet ) > 0 ) {
				for ( $iImage = 0; $iImage < count( (array) $oItem->ImageSets->ImageSet ); $iImage ++ ) {
					$aImage = (array) $oItem->ImageSets->ImageSet[ $iImage ];
					if ( is_object( $aImage ) ) {
						$aImage = (array) $aImage;
					}
					if ( ! isset( $aImage['@attributes'] ) || ( isset( $aImage['@attributes']['Category'] ) && (string) $aImage['@attributes']['Category'] != 'variant' ) ) {
						continue;
					}
					array_push( $aItem['images'], array(
							'small'  => (string) $aImage['SmallImage']->URL,
							'medium' => (string) $aImage['MediumImage']->URL,
							'large'  => (string) $aImage['LargeImage']->URL
						)
					);
				}
			}
		}
		$aItem['sLink']          = (string) $oItem->DetailPageURL;
		$aItem['sReviewsIframe'] = false;
		$aItem['fReviewsStars']  = false;
		$aItem['iReviewsCount']  = 0;
		if ( $oItem->CustomerReviews->HasReviews ) {
			$aItem['sReviewsIframe'] = (string) $oItem->CustomerReviews->IFrameURL;
			$aReviews                = amazilonGetReviews( $aItem['sReviewsIframe'] );
			if ( $aReviews !== false ) {
				$aItem['fReviewsStars'] = $aReviews['avg'];
				$aItem['iReviewsCount'] = $aReviews['count'];
			}
		}
		$aItem['aFeatures'] = array();
		if ( isset( $oItem->ItemAttributes->Feature ) && count( (array) $oItem->ItemAttributes->Feature ) > 0 ) {
			for ( $iFeature = 0; $iFeature < count( (array) $oItem->ItemAttributes->Feature ); $iFeature ++ ) {
				array_push( $aItem['aFeatures'], (string) $oItem->ItemAttributes->Feature[ $iFeature ] );
			}
		}
		$aItem['aBrowseNodes'] = array();
		for ( $iBrowseNode = 0; isset( $oItem->BrowseNodes->BrowseNode[ $iBrowseNode ] ); $iBrowseNode ++ ) {
			$oBrowseNode = $oItem->BrowseNodes->BrowseNode[ $iBrowseNode ];
			if ( isset( $oBrowseNode->IsCategoryRoot ) && $oBrowseNode->IsCategoryRoot == '1' ) {
				continue;
			}
			array_push( $aItem['aBrowseNodes'],
				array( 'name' => (string) $oBrowseNode->Name, 'id' => (int) $oBrowseNode->BrowseNodeId ) );
		}
	}
	if ( ! isset( $config['iCaching'] ) || (int) $config['iCaching'] < 1 ) {
		$config['iCaching'] = 86400;
	}
	$seconds = (int) $config['iCaching'];
	set_transient( 'amazilon_ASIN_' . $aItem['asin'], $aItem, (int) $seconds );

	return $aItem;
}

function amazilonFindSimilarItems( $sAsin ) {
	$aItems = array();
	$aItem  = amazilonGetItem( $sAsin, false, true );
	if ( $aItem === false ) {
		$aItem = array( 'title' => '' );
	}

	return amazilonItemSearch( $aItem['title'], 'All', 10 );
}

function amazilonItemSearch( $sKeywords, $sIndex = 'All', $iLimit = 10 ) {
	global $__amazilonSearchindexes;
	$aItems = array();

	if ( $iLimit > 10 || $iLimit < 1 ) {
		$iLimit = 10;
	}

	/**
	 * @todo Check PA-API5!
	 */
	if ( get_option( 'amazilon_paapi5mode' ) == '1' ) {
		require_once trailingslashit( dirname( __FILE__ ) ) . 'libs/paapi5.php';
		$return = paapi5_searchItems( $sKeywords, $sIndex, $iLimit );
		if ( ! $return ) {
			return $aItems;
		}
		$aItems = $return;

		return $aItems;
	}

	$config  = get_option( 'bowsxWpApn' );
	$request = amazilon_aws_request(
		'de',
		array(
			'Operation'     => 'ItemSearch',
			'SearchIndex'   => ( isset( $__amazilonSearchindexes['de'][ $sIndex ] ) ) ? $sIndex : 'All',
			'Keywords'      => $sKeywords,
			'ResponseGroup' => 'Medium,Offers,Reviews,BrowseNodes',
			'MerchantId'    => 'All'
		),
		trim( $config['publicKey'] ),
		trim( $config['privateKey'] ),
		trim( $config['associateTag'] )
	);

	$response = wp_remote_get( $request );
	if ( is_wp_error( $response ) ) {
		return $aItems;
	}
	if ( ( $pxml = simplexml_load_string( $response['body'] ) ) === false ) {
		return $aItems;
	}

	for ( $iItem = 0; $iItem < count( $pxml->Items->Item ) && $iItem < $iLimit; $iItem ++ ) {
		$aItem = amazilonGetItem( (string) $pxml->Items->Item[ $iItem ]->ASIN, false, true );
		if ( $aItem === false ) {
			$aItem = amazilonItemSetCache( $pxml->Items->Item[ $iItem ] );
		}
		array_push( $aItems, $aItem );
	}

	return $aItems;
}

function amazilonGetSearchindexes( $sLanguage = 'de' ) {
	global $__amazilonSearchindexes;
	if ( isset( $__amazilonSearchindexes[ $sLanguage ] ) ) {
		return $__amazilonSearchindexes[ $sLanguage ];
	}

	return array();
}

class amazilonWidget extends WP_Widget {
	private $stdObj;

	function __construct() {
		parent::__construct(
			'amazilon_widget',
			__( 'Amazilon Product Widget', 'amazilon' ),
			array(
				'description' => __( 'Amazilon Product Widget', 'amazilon' )
			)
		);
		$this->stdObj       = new stdClass;
		$this->stdObj->typ  = 'template';
		$this->stdObj->asin = '';
	}

	function widget( $args, $instance ) {
		if ( empty( $instance['tpl'] ) || ( $oTpl = @json_decode( $instance['tpl'] ) ) === false ) {
			return;
		}

		if ( is_object( $oTpl ) && isset( $instance['asinExchange'] ) && $instance['asinExchange'] && is_single() ) {
			global $post;
			$sAsin     = get_post_meta( $post->ID, 'amazilonAsin', true );
			$sTplPname = get_post_meta( $post->ID, 'amazilonTplPname', true );
			if ( ! empty( $sAsin ) ) {
				if ( isset( $oTpl->tplPname ) && ! empty( $oTpl->tplPname ) ) {
					$oTpl->tplPname = '';
				}
				$oTpl->tplPname = $sTplPname;
				$oTpl->asin     = $sAsin;
			}
		}

		if ( ! isset( $oTpl->typ ) || ! isset( $oTpl->asin ) || empty( $oTpl->asin ) ) {
			return;
		}

		if ( $oTpl->typ == 'template' && ! isset( $oTpl->template ) ) {
			$oTpl->template = 'tpl-1';
		}

		if ( ! isset( $oTpl->template ) ) {
			$oTpl->template = 'tpl-1';
		}

		$sTpl = '[apn typ="' . esc_html( $oTpl->typ ) . '" asin="' . esc_html( $oTpl->asin ) . '" template="' . esc_html( $oTpl->template ) . '"' . ( isset( $oTpl->tag ) ? ' tag="' . esc_html( $oTpl->tag ) . '"' : '' ) . ( isset( $oTpl->tplInfobox ) ? ' tpl-infobox="' . esc_html( $oTpl->tplInfobox ) . '"' : '' ) . ( isset( $oTpl->tplStars ) ? ' tpl-stars="' . esc_html( $oTpl->tplStars ) . '"' : '' ) . ( isset( $oTpl->tplPname ) ? ' tpl-pname="' . esc_html( $oTpl->tplPname ) . '"' : '' ) . ' false="' . esc_html( $oTpl->false ) . '"]<br style="clear: both;" />';

		echo $args['before_widget'];
		if ( ! empty( $instance['title'] ) ) {
			echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
		}
		echo do_shortcode( $sTpl );
		echo $args['after_widget'];
	}

	function update( $new_instance, $old_instance ) {
		$instance                 = array();
		$instance['title']        = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
		$instance['tpl']          = ( ! empty( $new_instance['tpl'] ) ) ? $new_instance['tpl'] : json_encode( $this->stdObj );
		$instance['asinExchange'] = ( ! empty( $new_instance['asinExchange'] ) ) ? $new_instance['asinExchange'] : false;

		return $instance;
	}

	function form( $instance ) {
		$title        = ! empty( $instance['title'] ) ? $instance['title'] : '';
		$tpl          = ! empty( $instance['tpl'] ) ? $instance['tpl'] : '';
		$asinExchange = ! empty( $instance['asinExchange'] ) ? $instance['asinExchange'] : false;
		?>
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php echo __( 'Title',
					'amazilon' ); ?>:</label>
            <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
                   name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text"
                   value="<?php echo esc_attr( $title ); ?>">
        </p>
        <p>
            <button class="button button-secondary" style="line-height: inherit;"
                    onclick="tb_show( '<?php esc_attr( __( 'Amazilon template generator',
				        'amazilon' ) ); ?>', '<?php echo admin_url( 'admin.php?page=amazilon-generators&jumpTo=generator-3&mini=true&fieldId=' . urlencode( $this->get_field_id( 'tpl' ) ) . '&TB_iframe=true' ); ?>'); return false;">
                <i class="mce-ico mce-i-amazilon"></i><span
                        style="vertical-align:top;"> <?php echo esc_attr( __( 'Configure using Amazilon Generator',
						'amazilon' ) ); ?></span></button>
            <input id="<?php echo esc_attr( $this->get_field_id( 'tpl' ) ); ?>"
                   name="<?php echo esc_attr( $this->get_field_name( 'tpl' ) ); ?>" type="hidden"
                   value="<?php echo esc_attr( $tpl ); ?>">
        </p>
        <p>
            <input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'asinExchange' ) ); ?>"
                   name="<?php echo esc_attr( $this->get_field_name( 'asinExchange' ) ); ?>"
                   value="1" <?php checked( $asinExchange ); ?>> <label
                    for="<?php echo esc_attr( $this->get_field_id( 'asinExchange' ) ); ?>"><?php echo __( 'Dynamic Widget',
					'amazilon' ); ?>
                <small><?php echo __( 'If an alternative ASIN is chosen inside currently shown article, use that one instead.',
						'amazilon' ); ?></small></label>
        </p>

		<?php
	}

}


class amazilonMetaBox {
	public function __construct() {
		if ( is_admin() ) {
			add_action( 'load-post.php', array( $this, 'setup' ) );
			add_action( 'load-post-new.php', array( $this, 'setup' ) );
		}
	}

	public function setup() {
		add_action( 'add_meta_boxes', array( $this, 'add' ) );
		add_action( 'save_post', array( $this, 'save' ), 10, 2 );
	}

	public function add() {
		add_meta_box(
			'amazilon-meta-asin',
			__( 'Amazilon - Dynamic Widget', 'amazilon' ),
			array( $this, 'render' ),
			'post',
			'advanced',
			'default'
		);
	}

	public function render( $post ) {
		$sAsin     = get_post_meta( $post->ID, 'amazilonAsin', true );
		$sTplPname = get_post_meta( $post->ID, 'amazilonTplPname', true );
		$oPostType = get_post_type_object( $post->post_type );
		?>
        <script type="text/javascript">
            jQuery(document).ready(function () {
                jQuery('#amazilon-search-button').click(function () {
                    apnSearch();
                    return false;
                });
            });
            apnSearch = function () {
                jQuery('#amazilon-search-results').show();
                jQuery('#amazilon-search-results-inner').html('<img src="<?php echo admin_url( 'images/spinner.gif' );  ?>">');
                var data = {
                    'action': 'amazilonSearch',
                    'security': '<?php echo wp_create_nonce( 'amazilonCC' . date( 'Ym' ) ); ?>',
                    'q': jQuery('#amazilon-search').val(),
                    'sIndex': jQuery('#amazilon-search-sindex').val()
                };

                jQuery.post(ajaxurl, data, function (response) {
                    jQuery('#amazilon-search-results-inner').html(response);
                    jQuery('a.amazilon-search-result-entry').each(function (index, value) {
                        jQuery(this).click(function () {
                            apnSetAsin('#amazilonAsin', this);
                            return false;
                        });
                    });
                    jQuery('#amazilon-search-results-inner').fadeIn();
                });
            }
            apnSetAsin = function (sObj, oObj) {
                if (sObj === undefined) {
                    sObj = '#asin';
                }
                oAsin = jQuery(sObj);
                oAsin.val(jQuery(oObj).data('asin'));
                oAsin.trigger('keyup');
                jQuery('#amazilon-search-results').fadeOut();
            }
        </script>
        <p>
            <label for="amazilonAsin"><?php echo __( 'Chosen ASIN for this ',
					'amazilon' ); ?> <?php echo $oPostType->labels->singular_name; ?>:</label>
            <input id="amazilonAsin" name="amazilonAsin" type="text" value="<?php echo esc_attr( $sAsin ); ?>"
                   placeholder="- <?php echo __( 'None', 'amazilon' ); ?> -"><br/>
            <label for="amazilonTplPname"><?php echo __( 'Use divergent product name', 'amazilon' ); ?>:</label>
            <input id="amazilonTplPname" name="amazilonTplPname" type="text"
                   value="<?php echo esc_attr( $sTplPname ); ?>"
                   placeholder="- <?php echo __( 'None', 'amazilon' ); ?> -"><br/>
        </p>

        <div class="block">
            <p><b><?php _e( 'Search on Amazon', 'amazilon' ); ?></b><br/>
                <label for="amazilon-search" style="display: inline-block; width: 150px;"><?php _e( 'Searchterm',
						'amazilon' ); ?>: </label><input type="text" id="amazilon-search" value="" size="35"
                                                         maxlength="" class="widefat"><br/><label for="sIndex"
                                                                                                  style="width: 150px; display: inline-block;"><?php _e( 'Area',
						'amazilon' ); ?>: </label><select id="amazilon-search-sindex" class="widefat"><?php
					$sIndexes = amazilonGetSearchindexes( 'de' );
					foreach ( $sIndexes as $sIndex => $aEntry ) {
						echo '<option value="' . esc_attr( $sIndex ) . '">' . esc_attr( $aEntry['title'] ) . '</option>';
					}

					?></select><br/>
                <a id="amazilon-search-button" class="amazilon-button-3" href="#"
                   style="width: initial;"><?php _e( 'Search on Amazon', 'amazilon' ); ?></a></p>
        </div>

        <div id="amazilon-search-results" class="block" style="display: none; position: relative;"><a href="#"
                                                                                                      onclick="jQuery('#amazilon-search-results').fadeOut();"><span
                        class="tb-close-icon"></span></a><b><?php _e( 'Search results', 'amazilon' ); ?></b><br/>
            <p><?php _e( 'Just click to select', 'amazilon' ); ?>:</p>
            <p id="amazilon-search-results-inner"></p></div>


		<?php
		wp_nonce_field( basename( __FILE__ ), 'amazilonNonce' );
	}

	/**
	 * Handles saving the meta box.
	 *
	 * @param int $post_id Post ID.
	 * @param WP_Post $post Post object.
	 *
	 * @return null
	 */
	public function save( $post_id, $post ) {
		$nonce_name   = isset( $_POST['amazilonNonce'] ) ? $_POST['amazilonNonce'] : '';
		$nonce_action = basename( __FILE__ );
		if ( ! isset( $nonce_name ) ) {
			return;
		}
		if ( ! wp_verify_nonce( $nonce_name, $nonce_action ) ) {
			return;
		}
		if ( ! current_user_can( 'amazilon_modify_dynamic_widget', $post_id ) ) {
			return;
		}
		if ( wp_is_post_autosave( $post_id ) ) {
			return;
		}
		if ( wp_is_post_revision( $post_id ) ) {
			return;
		}

		$sAsin = ( isset( $_POST['amazilonAsin'] ) ? sanitize_html_class( $_POST['amazilonAsin'] ) : '' );
		update_post_meta( $post->ID, 'amazilonAsin', $sAsin );
		$sTplPname = ( isset( $_POST['amazilonTplPname'] ) ? esc_html( $_POST['amazilonTplPname'] ) : '' );
		update_post_meta( $post->ID, 'amazilonTplPname', $sTplPname );
	}
}

function amazilonSearchPrepare( $template ) {
	$config = get_option( 'bowsxWpApn' );
	if ( ! isset( $config['search']['sPosition'] ) || ! in_array( $config['search']['sPosition'],
			array( 'after', 'before' ) ) ) {
		$config['search']['sPosition'] = 'after';
	}
	$sBox = '<p class="amazilonPrependSearch" style="display: none;"></p>';

	return ( $config['search']['sPosition'] == 'before' ? $sBox : '' ) . $template . ( $config['search']['sPosition'] == 'after' ? '<br style="clear: both;"/>' . $sBox : '' );
}

function amazilonSearchPrepareContent( $oQuery ) {
	if ( ! $oQuery->is_main_query() || ! in_the_loop() || ! is_search() ) {
		return;
	}
	$config = get_option( 'bowsxWpApn' );

	$sBox = '<p class="amazilonSearchLoop" style="display: none; clear: both;"></p>';
	echo $sBox;
}

function amazilonSearchFill() {
	$config = get_option( 'bowsxWpApn' );
	$sTerm  = get_search_query( false );
	if ( ! is_search() || empty( $sTerm ) || ! isset( $config['search']['bActive'] ) || $config['search']['bActive'] != '1' ) {
		return;
	}

	if ( ! isset( $config['search']['iProducts'] ) ) {
		$config['search']['iProducts'] = 3;
	}

	if ( ! isset( $config['search']['sIndex'] ) ) {
		$config['search']['sIndex'] = 'All';
	}

	$aItems = amazilonItemSearch( get_search_query( false ), $config['search']['sIndex'],
		$config['search']['iProducts'] );
	if ( count( $aItems ) < 1 ) {
		return;
	}

	$sResults = '<div class="amazilon-autosearch-results">';
	if ( isset( $config['search']['sTitle'] ) && ! empty( $config['search']['sTitle'] ) ) {
		$sResults .= '<h2>' . esc_html( str_replace( '%term%', get_search_query( false ),
				$config['search']['sTitle'] ) ) . '</h2>';
	}
	if ( ! isset( $config['search']['sSearchTemplate'] ) ) {
		$config['search']['sSearchTemplate'] = 'tpl-2';
	}
	if ( in_array( $config['search']['sSearchTemplate'], array( 'vergleich', 'vergleich2' ) ) ) {
		$sResult = '[apn asin="';
		for ( $iItem = 0; $iItem < count( $aItems ); $iItem ++ ) {
			if ( $iItem > 0 ) {
				$sResult .= ',';
			}
			$sResult .= esc_attr( $aItems[ $iItem ]['asin'] );
		}
		$sResult .= '" ';
		if ( isset( $config['search']['bInfobox'] ) && $config['search']['bInfobox'] == '1' ) {
			$sResult .= 'tpl-infobox="1" ';
		}
		if ( isset( $config['search']['bStars'] ) && $config['search']['bStars'] == '1' ) {
			$sResult .= 'tpl-stars="1" ';
		}
		if ( isset( $config['search']['sTag'] ) && ! empty( $config['search']['sTag'] ) ) {
			$sResult .= 'tag="' . esc_attr( $config['search']['sTag'] ) . '" ';
		}
		if ( isset( $config['search']['sSearchButtontext'] ) && ! empty( $config['search']['sSearchButtontext'] ) ) {
			$sResult .= 'tpl-buttontext="' . esc_attr( $config['search']['sSearchButtontext'] ) . '" ';
		}
		$sResult  .= 'typ="' . esc_attr( $config['search']['sSearchTemplate'] ) . '"]';
		$sResults .= do_shortcode( $sResult );
	} else {
		for ( $iItem = 0; $iItem < count( $aItems ); $iItem ++ ) {
			$sResult = '[apn asin="' . esc_attr( $aItems[ $iItem ]['asin'] ) . '" ';
			if ( isset( $config['search']['bInfobox'] ) && $config['search']['bInfobox'] == '1' ) {
				$sResult .= 'tpl-infobox="1" ';
			}
			if ( isset( $config['search']['bStars'] ) && $config['search']['bStars'] == '1' ) {
				$sResult .= 'tpl-stars="1" ';
			}
			if ( isset( $config['search']['sTag'] ) && ! empty( $config['search']['sTag'] ) ) {
				$sResult .= 'tag="' . esc_attr( $config['search']['sTag'] ) . '" ';
			}
			if ( isset( $config['search']['sSearchButtontext'] ) && ! empty( $config['search']['sSearchButtontext'] ) ) {
				$sResult .= 'tpl-buttontext="' . esc_attr( $config['search']['sSearchButtontext'] ) . '" ';
			}
			$sResult  .= 'typ="template" template="' . $config['search']['sSearchTemplate'] . '"]';
			$sResults .= do_shortcode( $sResult );
		}
	}
	$sResults .= '</div>';

	echo '<script> var amazilonResults = \'' . addslashes( preg_replace( '=[\r\n]+=Umsi', ' ', $sResults ) ) . '\';';
	if ( isset( $config['search']['sJquerySelector'] ) && ! empty( $config['search']['sJquerySelector'] ) ) {
		echo 'jQuery(\'' . esc_attr( $config['search']['sJquerySelector'] ) . ' .amazilonPrependSearch\').each( function() {
			jQuery( this ).after(amazilonResults);
			amazilonResults = \'\';
		});';
		echo 'jQuery(\'' . esc_attr( $config['search']['sJquerySelector'] ) . '\').each( function() {
			jQuery( this ).after(amazilonResults);
			amazilonResults = \'\';
		});';
	}
	echo '
	jQuery(\'#primary .amazilonPrependSearch,#main-content .amazilonPrependSearch,#content .amazilonPrependSearch\').each( function() {
		if ( jQuery( this ).parents(\'aside\').length > 0 || jQuery( this ).parents(\'.widget_search\').length > 0 ) { return; }
		jQuery( this ).after(amazilonResults);
		amazilonResults = \'\';
	});
	if ( amazilonResults != \'\' ) {
		jQuery(\'#primary .amazilonSearchLoop,#main-content .amazilonSearchLoop,#content .amazilonSearchLoop\').each( function() {
			if ( jQuery( this ).parents(\'aside\').length > 0 || jQuery( this ).parents(\'.widget_search\').length > 0 ) { return; }
			jQuery( this ).after(amazilonResults);
			amazilonResults = \'\';
		});
	}';
	echo '</script>';
}

function amazilonLogAdd( $sAsin, $sTitel, $sMsg ) {
	global $wpdb, $wp, $__amazilonCurrentShortcode;

	if ( is_admin() || ! is_singular() ) {
		return;
	}
	$sUrl = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
	if ( $sUrl === false ) {
		$sUrl = __( 'Unknown', 'amazilon' );
	}
	$wpdb->insert( $wpdb->prefix . 'wpapn_errors', array(
		'c32'       => crc32( $sAsin . $sMsg . $sUrl ),
		'asin'      => $sAsin,
		'titel'     => $sTitel,
		'msg'       => $sMsg,
		'url'       => $sUrl,
		'shortcode' => $__amazilonCurrentShortcode
	), array( '%d', '%s', '%s', '%s', '%s', '%s' ) );
}

function amazilonProcessActions() {
	global $wpdb;
	$page = ( isset( $_REQUEST['page'] ) ) ? esc_attr( $_REQUEST['page'] ) : false;
	switch ( $page ) {
		case 'amazilon-xchange':
			if ( ! current_user_can( 'amazilon_use_generators' ) ) {
				break;
			}
			if ( isset( $_REQUEST['action'] ) ) {
				switch ( $_REQUEST['action'] ) {
					case 'e_delete':
						if ( ! is_array( $_REQUEST['id'] ) ) {
							$_REQUEST['id'] = array( $_REQUEST['id'] );
						}
						for ( $i = 0; $i < count( $_REQUEST['id'] ); $i ++ ) {
							$wpdb->delete( $wpdb->prefix . 'amazilon_xchange', array( 'id' => $_REQUEST['id'][ $i ] ),
								array( '%d' ) );
						}
						wp_redirect( admin_url( 'admin.php?page=amazilon-xchange&m=1#xchangelist' ) );
						die();
						break;
					case 'e_add':
						if ( ! isset( $_REQUEST['asin'] ) ) {
							$_REQUEST['asin'] = '';
						}
						if ( ! isset( $_REQUEST['asinNew'] ) ) {
							$_REQUEST['asinNew'] = '';
						}
						if ( empty( $_REQUEST['asin'] ) || empty( $_REQUEST['asinNew'] ) ) {
							wp_redirect( admin_url( 'admin.php?page=amazilon-xchange&m=2&asin=' . urlencode( $_REQUEST['asin'] ) . '&asinNew=' . urlencode( $_REQUEST['asinNew'] ) . '#xchangenew' ) );
							die();
						}
						amazilonXchange( $_REQUEST['asin'], $_REQUEST['asinNew'] );
						delete_transient( 'amazilon_ASIN_' . $_REQUEST['asin'] );
						wp_redirect( admin_url( 'admin.php?page=amazilon-xchange&m=3#xchangelist' ) );
						die();
						break;
				}
			}
			break;
		case 'amazilon-statistics':
			if ( ! current_user_can( 'amazilon_use_statistics' ) ) {
				break;
			}
			if ( isset( $_REQUEST['action'] ) ) {
				switch ( $_REQUEST['action'] ) {
					case 'e_delete':
						if ( ! is_array( $_REQUEST['id'] ) ) {
							$_REQUEST['id'] = array( $_REQUEST['id'] );
						}
						for ( $i = 0; $i < count( $_REQUEST['id'] ); $i ++ ) {
							$aRow = $wpdb->get_row( 'SELECT c32, asin, msg, url  FROM ' . $wpdb->prefix . 'wpapn_errors WHERE id=' . intval( $_REQUEST['id'][ $i ] ) );
							if ( is_null( $aRow ) ) {
								continue;
							}
							$wpdb->delete( $wpdb->prefix . 'wpapn_errors', array(
								'c32'  => intval( $aRow->c32 ),
								'asin' => $aRow->asin,
								'msg'  => $aRow->msg,
								'url'  => $aRow->url
							) );
						}
						wp_redirect( admin_url( 'admin.php?page=amazilon-statistics&jumpTo=errors&m=1' ) );
						die();
						break;
					case 'e_deleteAsin':
						if ( ! is_array( $_REQUEST['id'] ) ) {
							$_REQUEST['id'] = array( $_REQUEST['id'] );
						}
						for ( $i = 0; $i < count( $_REQUEST['id'] ); $i ++ ) {
							$aRow = $wpdb->get_row( 'SELECT asin FROM ' . $wpdb->prefix . 'wpapn_errors WHERE id=' . intval( $_REQUEST['id'][ $i ] ) );
							if ( is_null( $aRow ) ) {
								continue;
							}
							$wpdb->query( 'DELETE FROM ' . $wpdb->prefix . 'wpapn_errors WHERE asin="' . esc_sql( $aRow->asin ) . '"' );
						}
						wp_redirect( admin_url( 'admin.php?page=amazilon-statistics&jumpTo=errors&m=1' ) );
						die();
						break;
					case 'e_deleteUrl':
						if ( ! is_array( $_REQUEST['id'] ) ) {
							$_REQUEST['id'] = array( $_REQUEST['id'] );
						}
						for ( $i = 0; $i < count( $_REQUEST['id'] ); $i ++ ) {
							$aRow = $wpdb->get_row( 'SELECT url FROM ' . $wpdb->prefix . 'wpapn_errors WHERE id=' . intval( $_REQUEST['id'][ $i ] ) );
							if ( is_null( $aRow ) ) {
								continue;
							}
							$wpdb->query( 'DELETE FROM ' . $wpdb->prefix . 'wpapn_errors WHERE url="' . esc_sql( $aRow->url ) . '"' );
						}
						wp_redirect( admin_url( 'admin.php?page=amazilon-statistics&jumpTo=errors&m=1' ) );
						die();
						break;
					case 'e_deleteGroup':
						if ( ! is_array( $_REQUEST['id'] ) ) {
							$_REQUEST['id'] = array( $_REQUEST['id'] );
						}
						for ( $i = 0; $i < count( $_REQUEST['id'] ); $i ++ ) {
							$aRow = $wpdb->get_row( 'SELECT CONCAT( asin, CONCAT( url, msg ) ) g FROM ' . $wpdb->prefix . 'wpapn_errors WHERE id=' . intval( $_REQUEST['id'][ $i ] ) );
							if ( is_null( $aRow ) ) {
								continue;
							}
							$wpdb->query( 'DELETE FROM ' . $wpdb->prefix . 'wpapn_errors WHERE CONCAT( asin, CONCAT( url, msg ) )="' . esc_sql( $aRow->g ) . '"' );
						}
						wp_redirect( admin_url( 'admin.php?page=amazilon-statistics&jumpTo=errors&m=1' ) );
						die();
						break;
				}
			}
	}
}

function amazilonUrl2path( $sUrl ) {
	$aParsed = wp_parse_url( $sUrl );
	$sReturn = '';
	$sReturn .= ( isset( $aParsed['scheme'] ) && ! empty( $aParsed['scheme'] ) ? $aParsed['scheme'] . '/' : '' );
	$sReturn .= ( isset( $aParsed['host'] ) && ! empty( $aParsed['host'] ) ? $aParsed['host'] . '/' : '' );
	$sReturn .= ( isset( $aParsed['path'] ) && ! empty( $aParsed['path'] ) ? substr( preg_replace( '#[^\w\d/]+#si', '_',
		$aParsed['path'] ), 1 ) : '' );
	if ( isset( $aParsed['query'] ) && ! empty( $aParsed['query'] ) ) {
		$sReturn .= '_' . preg_replace( '#\W+#si', '_', $aParsed['query'] );
	}
	$sExt    = pathinfo( $sUrl, PATHINFO_EXTENSION );
	$sReturn .= ( ! empty( $sExt ) ? '.' . $sExt : '' );

	return $sReturn;
}

add_action( 'wp_loaded', 'amazilonProcessActions' );

function amazilonCleanup() {
	global $__amazilonVersion;
	$w2245023265ae = get_option( base64_decode( 'Ym93c3hXcEFwbg==' ) );
	if ( ! isset( $w2245023265ae[ base64_decode( 'bGljZW5zZUtleQ==' ) ] ) || empty( $w2245023265ae[ base64_decode( 'bGljZW5zZUtleQ==' ) ] ) ) {
		delete_transient( base64_decode( 'Ym93c3hXcEFwbkluZm8=' ) );

		return false;
	}
	$cb56098a0e04c = wp_remote_get( base64_decode( 'aHR0cHM6Ly9hbWF6aWxvbi5jb20vbGljZW5zZS8/dmVyc2lvbj0=' ) . urlencode( $__amazilonVersion ) . base64_decode( 'JmxpY2Vuc2VLZXk9' ) . urlencode( $w2245023265ae[ base64_decode( 'bGljZW5zZUtleQ==' ) ] ) . base64_decode( 'JnVybD0=' ) . urlencode( get_site_url() ) );
	if ( is_wp_error( $cb56098a0e04c ) ) {
		set_transient( base64_decode( 'Ym93c3hXcEFwbkluZm8=' ), array(
			base64_decode( 'a2V5' ) => '',
			base64_decode( 'bXNn' ) => base64_decode( 'TGl6ZW56YWJnbGVpY2ggZmVobGdlc2NobGFnZW4gKEFicnVmIGZlaGxnZXNjaGxhZ2VuKS4=' )
		), 300 );

		return false;
	}
	if ( empty( $cb56098a0e04c[ base64_decode( 'Ym9keQ==' ) ] ) || ( $i443f4cf8e241 = @json_decode( $cb56098a0e04c[ base64_decode( 'Ym9keQ==' ) ],
			true ) ) === false ) {
		set_transient( base64_decode( 'Ym93c3hXcEFwbkluZm8=' ), array(
			base64_decode( 'a2V5' ) => '',
			base64_decode( 'bXNn' ) => base64_decode( 'TGl6ZW56YWJnbGVpY2ggZmVobGdlc2NobGFnZW4gKHVuZXJ3YXJ0ZXRlIEFudHdvcnQpLg==' )
		), 300 );

		return false;
	}
	if ( empty( $i443f4cf8e241[ base64_decode( 'a2V5' ) ] ) ) {
		set_transient( base64_decode( 'Ym93c3hXcEFwbkluZm8=' ), $i443f4cf8e241, 648000 );
	} else {
		set_transient( base64_decode( 'Ym93c3hXcEFwbkluZm8=' ), $i443f4cf8e241, 3600 );
	}

	return true;
}

function amazilonCheck( $kb38fcc31861c = true ) {
	$y2245023265ae = get_option( base64_decode( 'Ym93c3hXcEFwbg==' ) );
	if ( ! isset( $y2245023265ae[ base64_decode( 'bGljZW5zZUtleQ==' ) ] ) || empty( $y2245023265ae[ base64_decode( 'bGljZW5zZUtleQ==' ) ] ) ) {
		return false;
	}
	$g90272dda245a = get_option( base64_decode( 'X3RyYW5zaWVudF90aW1lb3V0X2Jvd3N4V3BBcG5JbmZv' ) );
	if ( $g90272dda245a !== false && ( (int) $g90272dda245a > time() + 658000 || (int) $g90272dda245a <= time() ) ) {
		delete_transient( base64_decode( 'Ym93c3hXcEFwbkluZm8=' ) );
	}
	$wcaf9b6b99962 = get_transient( base64_decode( 'Ym93c3hXcEFwbkluZm8=' ) );
	if ( $wcaf9b6b99962 === false ) {
		amazilonCleanup();
		if ( $kb38fcc31861c === true ) {
			return amazilonCheck( false );
		}

		return false;
	}
	if ( empty( $wcaf9b6b99962[ base64_decode( 'a2V5' ) ] ) ) {
		return false;
	}
	if ( $wcaf9b6b99962[ base64_decode( 'a2V5' ) ] != md5( trim( $y2245023265ae[ base64_decode( 'bGljZW5zZUtleQ==' ) ] ) . base64_decode( 'aWZubw==' ) ) ) {
		set_transient( base64_decode( 'Ym93c3hXcEFwbkluZm8=' ), array(
			base64_decode( 'a2V5' ) => false,
			base64_decode( 'bXNn' ) => base64_decode( 'TGl6ZW56IHVuZ8O8bHRpZy4=' )
		), 7200 );

		return false;
	}

	return true;
}
