Initial Commit

This commit is contained in:
2014-02-18 19:11:50 -07:00
commit 96d893fd58
54 changed files with 14181 additions and 0 deletions

124
classes/admin.php Normal file
View File

@@ -0,0 +1,124 @@
<?php
if ( !class_exists( 'SM_Admin' ) ){
class SM_Admin{
// Init the admin menu and pages
function sm_admin(){
add_action( 'admin_menu', array( &$this, 'menu_shuffle' ), 20 );
add_action( 'admin_head', array( &$this, 'load_admin_scripts' ) );
}
// Remove Menu added by WordPress UI and add my own as a subpage
function menu_shuffle(){
global $menu,$simple_map,$sm_options,$sm_help,$sm_import_export;
// Get options
$options = $simple_map->get_options();
// loop through menu and find the one I need to disable
foreach( $menu as $key => $value ) {
if ( in_array( 'edit.php?post_type=sm-location' , $value ) ) {
unset( $menu[$key] );
}
}
add_menu_page(__('SimpleMap Options', 'SimpleMap'), 'SimpleMap', apply_filters( 'sm-admin-permissions-sm-options', 'publish_posts' ), 'simplemap', array( &$sm_options, 'print_page' ), SIMPLEMAP_URL.'/inc/images/icon.png' );
add_submenu_page( 'simplemap', __('SimpleMap: General Options', 'SimpleMap'), __( 'General Options', 'SimpleMap'), apply_filters( 'sm-admin-permissions-sm-options', 'manage_options' ), 'simplemap', array( &$sm_options, 'print_page' ) );
add_submenu_page( 'simplemap', __('SimpleMap: Add Location', 'SimpleMap'), __( 'Add Location', 'SimpleMap' ), apply_filters( 'sm-admin-permissions-sm-add-locations', 'publish_posts' ), 'post-new.php?post_type=sm-location' );
add_submenu_page( 'simplemap', __('SimpleMap: Edit Locations', 'SimpleMap'), __( 'Edit Locations', 'SimpleMap' ), apply_filters( 'sm-admin-permissions-sm-edit-locations', 'publish_posts' ), 'edit.php?post_type=sm-location' );
foreach ( $options['taxonomies'] as $taxonomy => $tax_info ) {
add_submenu_page( 'simplemap', __('SimpleMap: Location ' . $tax_info['plural'], 'SimpleMap'), __( 'Location ' . $tax_info['plural'], 'SimpleMap' ), 'publish_posts', 'edit-tags.php?taxonomy=' . $taxonomy . '&amp;post_type=sm-location' );
}
add_submenu_page( 'simplemap', __('SimpleMap: Import / Export CSV', 'SimpleMap'), __('Import / Export CSV', 'SimpleMap'), 'publish_posts', 'simplemap-import-export', array( &$sm_import_export, 'print_page' ) );
add_submenu_page( 'simplemap', __('SimpleMap: Premium Support', 'SimpleMap'), __('Premium Support', 'SimpleMap'), 'publish_posts', 'simplemap-help', array( &$sm_help, 'print_page' ) );
}
// Print admin scripts
function load_admin_scripts(){
global $current_screen;
#### GENERAL OPTIONS PAGE ####
if ( 'toplevel_page_simplemap' == $current_screen->id ) :
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
if ($(document).width() < 1300) {
$('.postbox-container').css({'width': '99%'});
}
else {
$('.postbox-container').css({'width': '49%'});
}
if ($('#autoload').val() == 'none') {
$('#lock_default_location').attr('checked', false);
$('#lock_default_location').attr('disabled', true);
$('#lock_default_location_label').addClass('disabled');
}
$('#autoload').change(function() {
if ($(this).val() != 'none') {
$('#lock_default_location').attr('disabled', false);
$('#lock_default_location_label').removeClass('disabled');
}
else {
$('#lock_default_location').attr('checked', false);
$('#lock_default_location').attr('disabled', true);
$('#lock_default_location_label').addClass('disabled');
}
});
$('#address_format').siblings().addClass('hidden');
if ($('#address_format').val() == 'town, province postalcode')
$('#order_1').removeClass('hidden');
else if ($('#address_format').val() == 'town province postalcode')
$('#order_2').removeClass('hidden');
else if ($('#address_format').val() == 'town-province postalcode')
$('#order_3').removeClass('hidden');
else if ($('#address_format').val() == 'postalcode town-province')
$('#order_4').removeClass('hidden');
else if ($('#address_format').val() == 'postalcode town, province')
$('#order_5').removeClass('hidden');
else if ($('#address_format').val() == 'postalcode town')
$('#order_6').removeClass('hidden');
else if ($('#address_format').val() == 'town postalcode')
$('#order_7').removeClass('hidden');
$('#address_format').change(function() {
$(this).siblings().addClass('hidden');
if ($(this).val() == 'town, province postalcode')
$('#order_1').removeClass('hidden');
else if ($(this).val() == 'town province postalcode')
$('#order_2').removeClass('hidden');
else if ($(this).val() == 'town-province postalcode')
$('#order_3').removeClass('hidden');
else if ($(this).val() == 'postalcode town-province')
$('#order_4').removeClass('hidden');
else if ($(this).val() == 'postalcode town, province')
$('#order_5').removeClass('hidden');
else if ($(this).val() == 'postalcode town')
$('#order_6').removeClass('hidden');
else if ($(this).val() == 'town postalcode')
$('#order_7').removeClass('hidden');
});
// #autoload, #lock_default_location
});
</script>
<?php
endif;
}
function on_activate() {
//$current = get_site_transient( 'update_plugins' );
//if ( !isset( $current->checked[SIMPLEMAP_FILE] ) ) {
return; // <--- Remove to enable
$options = get_option( 'SimpleMap_options' );
if ( empty( $options ) ) {
$options = array( 'auto_locate' => 'html5' );
update_option( 'SimpleMap_options', $options );
}
}
}
}
?>

827
classes/ft-ps-client.php Normal file
View File

@@ -0,0 +1,827 @@
<?php
/**
* FullThrottle Premium Support Client
* Curious? Send me an email and you can beta it for me (glenn@fullthrottledevelopment.com)
*/
if ( ! class_exists( 'FT_Premium_Support_Client' ) ) {
class FT_Premium_Support_Client {
var $server_url;
var $product_id;
var $plugin_support_page_ids;
var $confirming_request;
var $receiving_sso;
var $learn_more_link;
var $ps_status = false;
var $sso_status = false;
var $paypal_button = false;
var $site_url;
var $plugin_basename = false;
var $plugin_slug = false;
// Constructer fires on admin page loads
function ft_premium_support_client( $config=array() ) {
// Populate properties
$this->server_url = isset( $config['server_url'] ) ? $config['server_url'] : false;
$this->product_id = isset( $config['product_id'] ) ? $config['product_id'] : false;
$this->plugin_support_page_ids = isset( $config['plugin_support_page_ids'] ) ? $config['plugin_support_page_ids'] : false;
$this->plugin_basename = isset( $config['plugin_basename'] ) ? $config['plugin_basename'] : false;
$this->plugin_slug = isset( $config['plugin_slug'] ) ? $config['plugin_slug'] : false;
$this->learn_more_link = isset( $config['learn_more_link'] ) ? $config['learn_more_link'] : false;
$this->confirming_request = isset( $_GET['ft-ps-confirm-request'] ) ? $_GET['ft-ps-confirm-request'] : false;
$this->receiving_sso = isset( $_POST['ft-ps-receiving-sso'] ) ? $_POST['ft-ps-receiving-sso'] : false;
$this->site_url = site_url();
// Register actions
add_action( 'admin_head', array( &$this, 'init' ) );
add_action( 'init', array( &$this, 'check_premium_upgrades' ) );
}
// Checks for premium upgrades
function check_premium_upgrades() {
// Build key
$exp_option_key = '_ftpssu_' . md5( 'ftpssue-' . $this->product_id . '-' . sanitize_title_with_dashes( $this->site_url ) . '-' . sanitize_title_with_dashes( $this->server_url ) );
// Check server for auto update?
if ( $expires = get_option( $exp_option_key ) ) {
if ( $expires > strtotime( 'now' ) )
$ft_ps_client_auto_update = new FT_Premium_Support_PluginUpdate_Checker( $this->server_url . '?ft-pss-upgrade-request=1&ft-pss-upgrade-request-product-id=' . $this->product_id . '&ft-pss-upgrade-request-site=' . $this->site_url . '&exp=' . $expires, $this->plugin_basename, $this->plugin_slug, 1 );
else
delete_option( 'external_updates-' . $this->plugin_slug );
}
}
// Inits the client if we're on the support page or receiving a request from the server
function init() {
global $current_screen;
// Return false if we don't have initial config settings and this isn't a request from the host server
if ( ( ! $this->server_url || ! $this->product_id || ! isset( $this->plugin_support_page_ids ) ) && ( ! $this->confirming_request || ! $this->receiving_sso ) )
return;
// Fire in the hole!
if ( $this->receiving_sso )
$this->receive_sso();
elseif ( $this->confirming_request )
$this->confirm_request();
elseif ( in_array( $current_screen->id, $this->plugin_support_page_ids ) )
$this->init_premium_support();
}
// This function inits premium support process
function init_premium_support() {
global $current_user;
wp_get_current_user();
// Check for premium support, sso, and paypal button transients
$status_key = md5( 'ft_premium_support_' . $this->product_id . '_' . sanitize_title_with_dashes( $this->site_url ) . '_' . sanitize_title_with_dashes( $this->server_url ) ) ;
$sso_key = md5( 'ft_premium_sso_' . $current_user->ID . '_' . $this->product_id . '_' . sanitize_title_with_dashes( $this->site_url ) . '_' . sanitize_title_with_dashes( $this->server_url ) );
$paypal_button_key = md5( 'ft_premium_signup_' . $this->product_id . '_' . sanitize_title_with_dashes( $this->site_url ) . '_' . sanitize_title_with_dashes( $this->server_url ) );
$exp_option_key = '_ftpssu_' . md5( 'ftpssue-' . $this->product_id . '-' . sanitize_title_with_dashes( $this->site_url ) . '-' . sanitize_title_with_dashes( $this->server_url ) );
// If we haven't set the status in the last 24 hours, or we haven't set a SSO for the current user in the last 3 hours, do it now.
if ( false === ( $ps_status = get_transient( $status_key ) ) || false === ( $sso_status = get_transient( $sso_key ) ) ) {
$body['ft-ps-status-request'] = true;
$body['site'] = urlencode( $this->site_url );
$body['user'] = $current_user->ID;
$body['product'] = $this->product_id;
$body['email'] = urlencode( $current_user->user_email );
$body['nicename'] = urlencode( $current_user->user_nicename );
// Ping server for response
if ( $request = wp_remote_post( $this->server_url, array( 'body' => $body, 'timeout' => 20 ) ) ) {
if ( isset( $request['response']['code'] ) && 200 == $request['response']['code'] ) {
// Response found a server, lets see if it hit a script we recognize
$response = json_decode( $request['body'] );
// Set the paypal button
if ( ! empty( $response->paypal_button->args ) && ! empty( $response->paypal_button->base) )
$this->paypal_button = add_query_arg( get_object_vars( $response->paypal_button->args ), $response->paypal_button->base );
// Set the expired flag
$this->support_expired = isset( $response->support_expired ) ? $response->support_expired : false;
// Do we have a premium status?
if ( isset( $response->support_status ) && $response->support_status ) {
// We have a premium support license for this domain / product combination. Set the transient and property
set_transient( $status_key, $response->support_status, 60*60*24 );
//set_transient( $status_key, $response->support_status, 60 );
$this->ps_status = $response->support_status;
// Did we get a user sso back as well? Set the property if we did
if ( isset( $response->user_sso ) && '' != $response->user_sso ) {
set_transient( $sso_key, $response->user_sso, 60*60*2.9 );
//set_transient( $sso_key, $response->user_sso, 60 );
$this->sso_status = $response->user_sso;
}
// Set an auto update option with expiration date
if ( isset( $response->support_status->exp_date ) && ! empty( $response->support_status->exp_date ) ) {
update_option( $exp_option_key, $response->support_status->exp_date );
// Check server for auto update?
if ( $this->ps_status ) {
delete_option( 'external_updates-' . $this->plugin_slug );
$ft_ps_client_auto_update = new FT_Premium_Support_PluginUpdate_Checker( $this->server_url . '?ft-pss-premium-request=1&ft-pss-upgrade-request-product-id=' . $this->product_id . '&ft-pss-upgrade-request-site=' . $this->site_url . '&exp=' . $response->support_status->exp_date, SIMPLEMAP_PATH, $this->plugin_slug, 1 );
}
}
} else {
// No premium support so lets delete the keys
delete_option( 'external_updates-' . $this->plugin_slug );
delete_option( $exp_option_key );
}
}
}
} else {
// Transients exist, therefore permission exists, set properties
$this->ps_status = $ps_status;
$this->sso_status = $sso_status;
}
// Check server for auto update?
if ( $this->ps_status )
$ft_ps_client_auto_update = new FT_Premium_Support_PluginUpdate_Checker( $this->server_url . '?ft-pss-upgrade-request=1&ft-pss-upgrade-request-product-id=' . $this->product_id . '&ft-pss-upgrade-request-site=' . $this->site_url, $this->plugin_basename, 'simplemap', 1 );
// Maybe Nag Renewal
$this->maybe_trigger_renewal_nag();
}
function maybe_trigger_renewal_nag() {
// Has support expired?
if ( ! empty( $this->support_expired ) && ! is_object( $this->support_expired ) ) {
add_action( 'admin_notices', array( $this, 'support_expired' ) );
return;
}
if ( ! empty( $this->ps_status->exp_date ) ) {
$onemonthout = $this->ps_status->exp_date - 2628000;
// If we are within a month of expiration date
if ( $onemonthout <= strtotime( 'now' ) ) {
add_action( 'admin_notices', array( $this, 'renew_soon' ) );
}
}
}
function support_expired() {
$link = ( $this->paypal_button ) ? esc_url( $this->paypal_button ) : 'http://simplemap-plugin.com';
echo "<div class='update-nag'>" . sprintf( __( "<strong style='color:red;'>Your license for SimpleMap has expired!</strong><br />You need to renew your license now for continued support and upgrades: <a href='%s' target='_blank'>Renew my license now</a>." ), $link ) . "</div>";
}
function renew_soon() {
$link = ( $this->paypal_button ) ? esc_url( $this->paypal_button ) : 'http://simplemap-plugin.com';
echo "<div class='update-nag'>" . sprintf( __( "<strong style='color:red;'>SimpleMap is expiring soon!</strong><br />You will need to renew your license for continued support and upgrades: <a href='%s' target='_blank'>Renew my license now</a>." ), $link ) . "</div>";
}
}
}
if ( !class_exists( 'FT_Premium_Support_PluginUpdate_Checker' ) ) :
/**
* A custom plugin update checker.
*
* @author Janis Elsts
* @copyright 2010
* @version 1.0
* @access public
*/
class FT_Premium_Support_PluginUpdate_Checker {
var $metadataUrl = ''; //The URL of the plugin's metadata file.
var $pluginFile = ''; //Plugin filename relative to the plugins directory.
var $slug = ''; //Plugin slug.
var $checkPeriod = 12; //How often to check for updates (in hours).
var $optionName = ''; //Where to store the update info.
/**
* Class constructor.
*
* @param string $metadataUrl The URL of the plugin's metadata file.
* @param string $pluginFile Fully qualified path to the main plugin file.
* @param string $slug The plugin's 'slug'. If not specified, the filename part of $pluginFile sans '.php' will be used as the slug.
* @param integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks.
* @param string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'.
* @return void
*/
function __construct( $metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '' ){
$this->metadataUrl = $metadataUrl;
$this->pluginFile = $pluginFile;
$this->checkPeriod = $checkPeriod;
$this->slug = $slug;
//If no slug is specified, use the name of the main plugin file as the slug.
//For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'.
if ( empty( $this->slug ) ){
$this->slug = basename( $this->pluginFile, '.php' );
}
if ( empty( $this->optionName ) ) {
$this->optionName = 'external_updates-' . $this->slug;
}
if ( '' == $optionName )
$this->optionName = 'external_updates-' . $this->slug;
else
$this->optionName = $optionName;
$this->installHooks();
}
/**
* Install the hooks required to run periodic update checks and inject update info
* into WP data structures.
*
* @return void
*/
function installHooks(){
//Override requests for plugin information
add_filter( 'plugins_api', array( &$this, 'injectInfo' ), 10, 3 );
//Insert our update info into the update array maintained by WP
add_filter( 'site_transient_update_plugins', array( &$this,'injectUpdate' )); //WP 3.0+
add_filter( 'transient_update_plugins', array( &$this,'injectUpdate' ) ); //WP 2.8+
//Set up the periodic update checks
$cronHook = 'check_plugin_updates-' . $this->slug;
if ( $this->checkPeriod > 0 ) {
//Trigger the check via Cron
add_filter( 'cron_schedules', array( &$this, '_addCustomSchedule' ) );
if ( ! wp_next_scheduled( $cronHook ) && ! defined( 'WP_INSTALLING' ) ) {
$scheduleName = 'every' . $this->checkPeriod . 'hours';
wp_schedule_event( time(), $scheduleName, $cronHook );
}
add_action( $cronHook, array( &$this, 'checkForUpdates' ) );
//In case Cron is disabled or unreliable, we also manually trigger
//the periodic checks while the user is browsing the Dashboard.
add_action( 'admin_init', array( &$this, 'maybeCheckForUpdates' ) );
} else {
//Periodic checks are disabled.
wp_clear_scheduled_hook( $cronHook );
}
}
/**
* Add our custom schedule to the array of Cron schedules used by WP.
*
* @param array $schedules
* @return array
*/
function _addCustomSchedule( $schedules ) {
if ( $this->checkPeriod && ( $this->checkPeriod > 0 ) ) {
$scheduleName = 'every' . $this->checkPeriod . 'hours';
$schedules[$scheduleName] = array(
'interval' => $this->checkPeriod * 3600,
'display' => sprintf( 'Every %d hours', $this->checkPeriod ),
);
}
return $schedules;
}
/**
* Retrieve plugin info from the configured API endpoint.
*
* @uses wp_remote_get()
*
* @param array $queryArgs Additional query arguments to append to the request. Optional.
* @return PluginInfo
*/
function requestInfo( $queryArgs = array() ) {
//Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()).
$queryArgs['installed_version'] = $this->getInstalledVersion();
$queryArgs = apply_filters( 'puc_request_info_query_args-' . $this->slug, $queryArgs );
//Various options for the wp_remote_get() call. Plugins can filter these, too.
$options = array(
'timeout' => 10, //seconds
'headers' => array(
'Accept' => 'application/json'
),
);
$options = apply_filters( 'puc_request_info_options-' . $this->slug, $options );
//The plugin info should be at 'http://your-api.com/url/here/$slug/info.json'
$url = $this->metadataUrl;
if ( ! empty( $queryArgs ) ){
$url = add_query_arg( $queryArgs, $url );
}
$result = wp_remote_get(
$url,
$options
);
//Try to parse the response
$ft_premium_support_plugin_info = null;
if ( !is_wp_error( $result ) && isset( $result['response']['code'] ) && ( $result['response']['code'] == 200 ) && !empty( $result['body'] ) ){
$ft_premium_support_plugin_info = FT_Premium_Support_PluginInfo::fromJson( $result['body'] );
}
$ft_premium_support_plugin_info = apply_filters( 'puc_request_info_result-' . $this->slug, $ft_premium_support_plugin_info, $result );
return $ft_premium_support_plugin_info;
}
/**
* Retrieve the latest update (if any) from the configured API endpoint.
*
* @uses PluginUpdateChecker::requestInfo()
*
* @return PluginUpdate An instance of PluginUpdate, or NULL when no updates are available.
*/
function requestUpdate() {
//For the sake of simplicity, this function just calls requestInfo()
//and transforms the result accordingly.
$ft_premium_support_plugin_info = $this->requestInfo( array( 'checking_for_updates' => '1' ) );
if ( $ft_premium_support_plugin_info == null )
return null;
return FT_Premium_Support_PluginUpdate::fromPluginInfo( $ft_premium_support_plugin_info );
}
/**
* Get the currently installed version of the plugin.
*
* @return string Version number.
*/
function getInstalledVersion() {
if ( ! function_exists( 'get_plugins' ) )
require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
$allPlugins = get_plugins();
if ( array_key_exists( $this->pluginFile, $allPlugins ) && array_key_exists( 'Version', $allPlugins[$this->pluginFile] ) )
return $allPlugins[$this->pluginFile]['Version'];
else
return ''; //This should never happen.
}
/**
* Check for plugin updates.
* The results are stored in the DB option specified in $optionName.
*
* @return void
*/
function checkForUpdates(){
$state = get_option( $this->optionName );
if ( empty($state) ){
$state = new StdClass;
$state->lastCheck = 0;
$state->checkedVersion = '';
$state->update = null;
}
$state->lastCheck = time();
$state->checkedVersion = $this->getInstalledVersion();
update_option( $this->optionName, $state ); //Save before checking in case something goes wrong
$state->update = $this->requestUpdate();
update_option( $this->optionName, $state );
}
/**
* Check for updates only if the configured check interval has already elapsed.
*
* @return void
*/
function maybeCheckForUpdates(){
if ( empty( $this->checkPeriod ) )
return;
$state = get_option( $this->optionName );
$shouldCheck =
empty( $state ) ||
! isset( $state->lastCheck ) ||
( ( time() - $state->lastCheck ) >= $this->checkPeriod*3600 );
if ( $shouldCheck ){
$this->checkForUpdates();
}
}
/**
* Intercept plugins_api() calls that request information about our plugin and
* use the configured API endpoint to satisfy them.
*
* @see plugins_api()
*
* @param mixed $result
* @param string $action
* @param array|object $args
* @return mixed
*/
function injectInfo( $result, $action = null, $args = null ) {
$relevant = ( $action == 'plugin_information') && isset( $args->slug ) && ( $args->slug == $this->slug );
if ( !$relevant ){
return $result;
}
$ft_premium_support_plugin_info = $this->requestInfo();
if ( $ft_premium_support_plugin_info )
return $ft_premium_support_plugin_info->toWpFormat();
return $result;
}
/**
* Insert the latest update (if any) into the update list maintained by WP.
*
* @param array $updates Update list.
* @return array Modified update list.
*/
function injectUpdate( $updates ){
$state = get_option( $this->optionName );
//Is there an update to insert?
if ( ! empty( $state ) && isset( $state->update ) && ! empty( $state->update ) ) {
//Only insert updates that are actually newer than the currently installed version.
if ( version_compare( $state->update->version, $this->getInstalledVersion(), '>' ) )
$updates->response[$this->pluginFile] = $state->update->toWpFormat();
}
return $updates;
}
/**
* Register a callback for filtering query arguments.
*
* The callback function should take one argument - an associative array of query arguments.
* It should return a modified array of query arguments.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callback $callback
* @return void
*/
function addQueryArgFilter( $callback ) {
add_filter( 'puc_request_info_query_args-' . $this->slug, $callback );
}
/**
* Register a callback for filtering arguments passed to wp_remote_get().
*
* The callback function should take one argument - an associative array of arguments -
* and return a modified array or arguments. See the WP documentation on wp_remote_get()
* for details on what arguments are available and how they work.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callback $callback
* @return void
*/
function addHttpRequestArgFilter($callback) {
add_filter( 'puc_request_info_options-' . $this->slug, $callback );
}
/**
* Register a callback for filtering the plugin info retrieved from the external API.
*
* The callback function should take two arguments. If the plugin info was retrieved
* successfully, the first argument passed will be an instance of PluginInfo. Otherwise,
* it will be NULL. The second argument will be the corresponding return value of
* wp_remote_get (see WP docs for details).
*
* The callback function should return a new or modified instance of PluginInfo or NULL.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callback $callback
* @return void
*/
function addResultFilter( $callback ) {
add_filter( 'puc_request_info_result-' . $this->slug, $callback, 10, 2 );
}
}
endif;
if ( ! class_exists( 'FT_Premium_Support_PluginInfo' ) ) :
/**
* A container class for holding and transforming various plugin metadata.
*
* @author Janis Elsts
* @copyright 2010
* @version 1.0
* @access public
*/
class FT_Premium_Support_PluginInfo {
//Most fields map directly to the contents of the plugin's info.json file.
//See the relevant docs for a description of their meaning.
var $name;
var $slug;
var $version;
var $homepage;
var $sections;
var $download_url;
var $author;
var $author_homepage;
var $requires;
var $tested;
var $upgrade_notice;
var $rating;
var $num_ratings;
var $downloaded;
var $last_updated;
var $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything.
/**
* Create a new instance of PluginInfo from JSON-encoded plugin info
* returned by an external update API.
*
* @param string $json Valid JSON string representing plugin info.
* @return PluginInfo New instance of PluginInfo, or NULL on error.
*/
function fromJson( $json ){
$apiResponse = json_decode( $json );
if ( empty( $apiResponse ) || !is_object( $apiResponse ) )
return null;
//Very, very basic validation.
$valid = isset( $apiResponse->name ) && ! empty( $apiResponse->name ) && isset( $apiResponse->version ) && ! empty( $apiResponse->version );
if ( ! $valid )
return null;
$info = new FT_Premium_Support_PluginInfo();
foreach( get_object_vars( $apiResponse ) as $key => $value ) {
$info->$key = $value;
}
return $info;
}
/**
* Transform plugin info into the format used by the native WordPress.org API
*
* @return object
*/
function toWpFormat(){
$info = new StdClass;
//The custom update API is built so that many fields have the same name and format
//as those returned by the native WordPress.org API. These can be assigned directly.
$sameFormat = array(
'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice',
'num_ratings', 'downloaded', 'homepage', 'last_updated',
);
foreach( $sameFormat as $field ){
if ( isset( $this->$field ) )
$info->$field = $this->$field;
}
//Other fields need to be renamed and/or transformed.
$info->download_link = $this->download_url;
if ( ! empty( $this->author_homepage ) )
$info->author = sprintf( '<a href="%s">%s</a>', $this->author_homepage, $this->author );
else
$info->author = $this->author;
if ( is_object( $this->sections ) ){
$info->sections = get_object_vars( $this->sections );
} elseif ( is_array( $this->sections ) ) {
$info->sections = $this->sections;
} else {
$info->sections = array( 'description' => '' );
}
return $info;
}
}
endif;
if ( ! class_exists( 'FT_Premium_Support_PluginUpdate' ) ):
/**
* A simple container class for holding information about an available update.
*
* @author Janis Elsts
* @copyright 2010
* @version 1.0
* @access public
*/
class FT_Premium_Support_PluginUpdate {
var $id = 0;
var $slug;
var $version;
var $homepage;
var $download_url;
var $upgrade_notice;
/**
* Create a new instance of PluginUpdate from its JSON-encoded representation.
*
* @param string $json
* @return PluginUpdate
*/
function fromJson( $json ){
//Since update-related information is simply a subset of the full plugin info,
//we can parse the update JSON as if it was a plugin info string, then copy over
//the parts that we care about.
$ft_premium_support_plugin_info = FT_Premium_Support_PluginInfo::fromJson( $json );
if ( $ft_premium_support_plugin_info != null )
return FT_Premium_Support_PluginUpdate::fromPluginInfo( $ft_premium_support_plugin_info );
else
return null;
}
/**
* Create a new instance of PluginUpdate based on an instance of PluginInfo.
* Basically, this just copies a subset of fields from one object to another.
*
* @param PluginInfo $info
* @return PluginUpdate
*/
function fromPluginInfo( $info ){
$update = new FT_Premium_Support_PluginUpdate();
$copyFields = array( 'id', 'slug', 'version', 'homepage', 'download_url', 'upgrade_notice' );
foreach( $copyFields as $field ) {
$update->$field = $info->$field;
}
return $update;
}
/**
* Transform the update into the format used by WordPress native plugin API.
*
* @return object
*/
function toWpFormat(){
$update = new StdClass;
$update->id = $this->id;
$update->slug = $this->slug;
$update->new_version = $this->version;
$update->url = $this->homepage;
$update->package = $this->download_url;
if ( ! empty( $this->upgrade_notice ) )
$update->upgrade_notice = $this->upgrade_notice;
return $update;
}
}
endif;
/**
* Checks for premium support
*/
function url_has_ftps_for_item( &$ps_object ) {
if ( is_object( $ps_object ) && $ps_object->ps_status )
return true;
return false;
}
/**
* Return paypal button
*/
function get_ftps_paypal_button( &$ps_object ) {
if ( is_object( $ps_object ) && isset( $ps_object->paypal_button ) )
return $ps_object->paypal_button;
return false;
}
/**
* Return learn more link
*/
function get_ftps_learn_more_link( &$ps_object ) {
if ( is_object( $ps_object ) && isset( $ps_object->learn_more_link ) )
return $ps_object->learn_more_link;
return false;
}
/**
* Return SSO key
*/
function get_ftps_sso_key( &$ps_object ) {
if ( is_object( $ps_object ) && isset( $ps_object->sso_status ) )
return $ps_object->sso_status;
return false;
}
/**
* Return this site URL that has premium support
*/
function get_ftps_site( &$ps_object ) {
if ( is_object( $ps_object ) && isset( $ps_object->ps_status->site ) )
return $ps_object->ps_status->site;
return false;
}
/**
* Return purchase date
*/
function get_ftps_purchase_date( &$ps_object ) {
if ( is_object( $ps_object ) && isset( $ps_object->ps_status->purchase_date ) )
return $ps_object->ps_status->purchase_date;
return false;
}
/**
* Return expiration date
*/
function get_ftps_exp_date( &$ps_object ) {
if ( is_object( $ps_object ) && isset( $ps_object->ps_status->exp_date ) )
return $ps_object->ps_status->exp_date;
return false;
}
/**
* Return email of person who purchased premium support
*/
function get_ftps_email( &$ps_object ) {
if ( is_object( $ps_object ) && isset( $ps_object->ps_status->email ) )
return $ps_object->ps_status->email;
return false;
}
/**
* Return name of person who purchased premium support
*/
function get_ftps_name( &$ps_object ) {
if ( is_object( $ps_object ) && isset( $ps_object->ps_status->name ) )
return $ps_object->ps_status->name;
return false;
}
?>

250
classes/help.php Normal file
View File

@@ -0,0 +1,250 @@
<?php
if ( !class_exists( 'SM_Help' ) ) {
class SM_Help {
// Prints the options page
function print_page(){
global $simple_map;
$options = $simple_map->get_options();
extract( $options );
?>
<div class="wrap">
<?php
// Title
$sm_page_title = 'SimpleMap: Premium Support';
// Toolbar
$simple_map->show_toolbar( $sm_page_title );
?>
<div><p><?php _e( 'Jump to a section:', 'SimpleMap' ); ?> <a href="#displaying_your_map"><?php _e( 'Displaying Your Map', 'SimpleMap' ); ?></a> | <a href="#general_options"><?php _e( 'General Options', 'SimpleMap' ); ?></a> | <a href="#adding_a_location"><?php _e( 'Adding a Location', 'SimpleMap' ); ?></a> | <a href="#everything_else"><?php _e( 'Everything Else', 'SimpleMap' ); ?></a></p></div>
<div id="dashboard-widgets-wrap" class="clear">
<div id='dashboard-widgets' class='metabox-holder'>
<div class='postbox-container' style='width:49%;'>
<div id='normal-sortables' class='meta-box-sortables ui-sortable'>
<a name="premium_features"></a>
<div class="postbox">
<h3><?php _e( 'Premium Features', 'SimpleMap' ); ?></h3>
<div class="inside" style="padding: 0 10px 10px 10px;">
<div class="table">
<table class="form-table">
<tr><td><?php _e( 'Custom category markers can now be used. Login to Premium support and look for the KB article for instructions.', 'SimpleMap' ); ?></td></tr>
<tr><td><?php _e( 'We now have a search widget. Login to Premium support and look for the KB article for instructions.', 'SimpleMap' ); ?></td></tr>
</table>
</div>
<div class="clear"></div>
</div> <!-- inside -->
</div> <!-- postbox -->
<!-- =========================================
==============================================
========================================== -->
<a name="displaying_your_map"></a>
<div class="postbox">
<h3><?php _e( 'Displaying Your Map', 'SimpleMap' ); ?></h3>
<div class="inside" style="padding: 0 10px 10px 10px;">
<div class="table">
<table class="form-table">
<tr><td><?php _e( 'To show your map on any post or page, insert the shortcode in the body:', 'SimpleMap' ); ?> <code style="font-size: 1.2em; background: #ffffe0;">[simplemap]</code></td></tr>
<tr><td><?php _e( 'If you want only certain categories or tags to show on a map, insert shortcode like this, where the numbers are replaced with the ID numbers of your desired categories and tags:', 'SimpleMap' ); ?> <code style="font-size: 1.2em; background: #ffffe0;">[simplemap categories=2,5,14 tags=3,6,15]</code></td></tr>
<tr><td><?php _e( 'If you want to hide the category or tag filters on the search form, insert shortcode like this:', 'SimpleMap' ); ?> <code style="font-size: 1.2em; background: #ffffe0;">[simplemap show_categories_filter=false show_tags_filter=false]</code></td></tr>
<tr><td><?php _e( 'If you want to hide the map, insert shortcode like this:', 'SimpleMap' ); ?> <code style="font-size: 1.2em; background: #ffffe0;">[simplemap hide_map=true]</code></td></tr>
<tr><td><?php _e( 'If you want to hide the list of results, insert shortcode like this:', 'SimpleMap' ); ?> <code style="font-size: 1.2em; background: #ffffe0;">[simplemap hide_list=true]</code></td></tr>
<tr><td><?php _e( 'If you want to override the default lat / lng for a specific map, insert shortcode like this:', 'SimpleMap' ); ?> <code style="font-size: 1.2em; background: #ffffe0;">[simplemap default_lat='34.1346702' default_lng='-118.4389877']</code></td></tr>
<tr><td><?php _e( 'You can combine tag attributes as needed:', 'SimpleMap' ); ?> <code style="font-size: 1.2em; background: #ffffe0;">[simplemap categories=2,5,14 show_tags_filter=false]</code></td></tr>
<tr><td><?php _e( 'You can place content above or below your map, just like in any other post. Note that any content placed below the map will be pushed down by the list of search results (unless you have them displaying differently with a custom theme).', 'SimpleMap' ); ?></td></tr>
<tr><td><?php printf( __( 'Configure the appearance of your map on the %s General Options page.%s', 'SimpleMap'), '<a href="' . esc_url( admin_url( 'admin.php?page=simplemap' ) ) . '">', '</a>' ); ?></td></tr>
</table>
</div>
<div class="clear"></div>
</div> <!-- inside -->
</div> <!-- postbox -->
<!-- =========================================
==============================================
========================================== -->
<a name="general_options"></a>
<div class="postbox">
<h3><?php _e( 'General Options', 'SimpleMap' ); ?></h3>
<div class="inside" style="padding: 0 10px 10px 10px;">
<div class="table">
<table class="form-table">
<tr valign="top">
<td width="150"><strong><?php _e( 'Starting Location', 'SimpleMap' ); ?></strong></td>
<td><?php _e( 'Enter the location the map should open to by default, when no location has been searched for. If you do not know the latitude and longitude of your starting location, enter the address in the provided text field and press "Geocode Address."', 'SimpleMap' ); ?></td>
</tr>
<tr valign="top">
<td width="150"><strong><?php _e('Auto-Load Database', 'SimpleMap'); ?></strong></td>
<td>
<?php printf( __( '%s No auto-load:%s Locations will not load automatically.', 'SimpleMap' ), '<strong>', '</strong>'); ?><br />
<?php printf( __( '%s Auto-load search results:%s The locations will load based on the default location, default search radius and zoom level you have set.', 'SimpleMap' ), '<strong>', '</strong>' ); ?><br />
<?php printf( __( '%s Auto-load all locations:%s All of the locations in your database will load at the default zoom level you have set, disregarding your default search radius. %s This option is not enabled if you have more than 100 locations in your database.%s', 'SimpleMap' ), '<strong>', '</strong>', '<em>', '</em>' ); ?><br /><br />
<?php _e( 'If you leave the checkbox unchecked, then the auto-load feature will automatically move the map to the center of all the loaded locations. If you check the box, your default location will be respected regardless of the locations the map is loading.', 'SimpleMap' ); ?>
</td>
</tr>
<tr valign="top">
<td width="150"><strong><?php _e( 'Special Location Label', 'SimpleMap' ); ?></strong></td>
<td><?php _e( 'This is meant to flag certain locations with a specific label. It shows up in the search results with a gold star next to it. Originally this was developed for an organization that wanted to highlight people that had been members for more than ten years. It could be used for something like that, or for "Favorite Spots," or "Free Wi-Fi," or anything you want. You can also leave it blank to disable it.', 'SimpleMap' ); ?></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div> <!-- inside -->
</div> <!-- postbox -->
<!-- =========================================
==============================================
========================================== -->
<a name="adding_a_location"></a>
<div class="postbox">
<h3><?php _e( 'Adding a Location', 'SimpleMap' ); ?></h3>
<div class="inside" style="padding: 0 10px 10px 10px;">
<div class="table">
<table class="form-table">
<tr><td>
<?php _e( 'To properly add a new location, you must enter one or both of the following:', 'SimpleMap' ); ?><br />
<span style="padding-left: 20px;"><?php _e( '1. A full address', 'SimpleMap'); ?></span><br />
<span style="padding-left: 20px;"><?php _e( '2. A latitude and longitude', 'SimpleMap' ); ?></span><br />
<?php _e( 'If you enter a latitude and longitude, then the address will not be geocoded, and your custom values will be left in place. Entering an address without latitude or longitude will result in the address being geocoded before it is submitted to the database.', 'SimpleMap' ); ?>
</td></tr>
<tr><td>
<?php _e( 'You must also enter a name for every location.', 'SimpleMap' ); ?>
</td></tr>
</table>
</div>
<div class="clear"></div>
</div> <!-- inside -->
</div> <!-- postbox -->
<!-- =========================================
==============================================
========================================== -->
</div> <!-- meta-box-sortables -->
</div> <!-- postbox-container -->
<div class='postbox-container' style='width:49%;'>
<div id='side-sortables' class='meta-box-sortables ui-sortable'>
<?php do_action( 'sm-help-side-sortables-top' ); ?>
<!-- #### PREMIUM SUPPORT #### -->
<div class="postbox" >
<h3 style='color:#fff;text-shadow:0 1px 0 #000;background: #fff url( <?php echo SIMPLEMAP_URL; ?>/inc/images/blue-grad.png ) top left repeat-x;'><?php _e( 'Premium Support and Features', 'SimpleMap' ); ?></h3>
<div class="inside" style='padding: 0pt 10px 10px;' >
<?php
// Check for premium support status
global $simplemap_ps;
if ( ! url_has_ftps_for_item( $simplemap_ps ) ) : ?>
<h4><?php printf( __( 'SimpleMap Premium Support Benefits', 'SimpleMap' ), esc_attr( site_url() ) ); ?></h4>
<p>
<?php printf( __( 'SimpleMap now offers a premium support package for the low cost of %s per year per domain.', 'SimpleMap' ), '$30.00 USD' ); ?>
</p>
<p>
<?php _e( 'By signing up for SimpleMap premium support, you help to ensure future enhancements to this excellent project as well as the following benefits:', 'SimpleMap' ); ?>
</p>
<ul style='margin-left:25px;list-style-type:disc'>
<li><?php _e( 'Around the clock access to our extensive knowledge base and support forum from within your WordPress dashboard', 'SimpleMap' ); ?></li>
<li><?php _e( 'Professional and timely response times to all your questions from the SimpleMap team', 'SimpleMap' ); ?></li>
<li><?php _e( 'A 10% discount for any custom functionality you request from the SimpleMap developers', 'SimpleMap' ); ?></li>
<li><?php _e( 'A 6-12 month advance access to new features integrated into the auto upgrade functionality of WordPress', 'SimpleMap' ); ?></li>
</ul>
<ul style='margin-left:25px;list-style-type:none'>
<li><a href='<?php echo get_ftps_paypal_button( $simplemap_ps ); ?>'><?php _e( 'Signup Now', 'SimpleMap' ); ?></a></li>
<li><a target='_blank' href='<?php echo get_ftps_learn_more_link( $simplemap_ps ); ?>'><?php _e( 'Learn More', 'SimpleMap' ); ?></a></li>
</ul>
<?php else : ?>
<p class='howto'><?php printf( "Your premium support for <code>%s</code> was purchased on <code>%s</code> by <code>%s</code> (%s). It will remain valid for this URL until <code>%s</code>.", get_ftps_site( $simplemap_ps ), date( "F d, Y", get_ftps_purchase_date( $simplemap_ps ) ), get_ftps_name( $simplemap_ps ), get_ftps_email( $simplemap_ps ), date( "F d, Y", get_ftps_exp_date( $simplemap_ps ) ) ); ?></p>
<p><a href='#' id='premium_help'><?php _e( 'Launch Premium Support widget', 'SimpleMap' ); ?></a> | <a target="blank" href="http://support.simplemap-plugin.com?sso=<?php echo get_ftps_sso_key( $simplemap_ps ); ?>"><?php _e( 'Visit Premium Support web site', 'SimpleMap' );?></a></p>
<script type="text/javascript" charset="utf-8">
Tender = {
hideToggle: true,
sso: "<?php echo get_ftps_sso_key( $simplemap_ps ); ?>",
widgetToggles: [document.getElementById('premium_help')]
}
</script>
<script src="https://simplemap.tenderapp.com/tender_widget.js" type="text/javascript"></script>
<?php endif; ?>
</div> <!-- inside -->
</div> <!-- postbox -->
<?php do_action( 'sm-help-side-sortables-bottom' ); ?>
</div> <!-- meta-box-sortables -->
</div> <!-- postbox-container -->
</div> <!-- dashboard-widgets -->
<div class="clear">
</div>
</div><!-- dashboard-widgets-wrap -->
</div> <!-- wrap -->
<?php
}
}
}
?>

803
classes/import-export.php Normal file
View File

@@ -0,0 +1,803 @@
<?php
if ( !class_exists( 'SM_Import_Export' ) ){
class SM_Import_Export{
// update options of form submission
function sm_import_export() {
//add_action( 'admin_init', array( &$this, 'import_csv' ) );
add_action( 'admin_init', array( &$this, 'export_csv' ) );
add_action( 'admin_init', array( &$this, 'export_legacy_csv' ) );
add_action( 'admin_init', array( &$this, 'delete_legacy_tables' ) );
}
// Exports a CSV file to WordPress
function export_csv() {
global $simple_map, $sm_locations;
if ( isset( $_POST['sm-action'] ) && 'export-csv' == $_POST['sm-action'] ) {
// Grab locations
$content = array();
set_time_limit( 0 );
$locations = query_posts( array( 'post_status' => 'publish', 'post_type' => 'sm-location', 'posts_per_page' => -1 ) );
// Include CSV library
require_once( SIMPLEMAP_PATH . '/classes/parsecsv.lib.php' );
$taxonomies = get_object_taxonomies( 'sm-location' );
foreach ( $locations as $key => $location ) {
$location_data = array(
'name' => esc_attr( $location->post_title ),
'address' => esc_attr( get_post_meta( $location->ID, 'location_address', true ) ),
'address2' => esc_attr( get_post_meta( $location->ID, 'location_address2', true ) ),
'city' => esc_attr( get_post_meta( $location->ID, 'location_city', true ) ),
'state' => esc_attr( get_post_meta( $location->ID, 'location_state', true ) ),
'zip' => esc_attr( get_post_meta( $location->ID, 'location_zip', true ) ),
'country' => esc_attr( get_post_meta( $location->ID, 'location_country', true ) ),
'phone' => esc_attr( get_post_meta( $location->ID, 'location_phone', true ) ),
'email' => esc_attr( get_post_meta( $location->ID, 'location_email', true ) ),
'fax' => esc_attr( get_post_meta( $location->ID, 'location_fax', true ) ),
'url' => esc_attr( get_post_meta( $location->ID, 'location_url', true ) ),
'description' => esc_attr( $location->post_content ),
'special' => esc_attr( get_post_meta( $location->ID, 'location_special', true ) ),
'lat' => esc_attr( get_post_meta( $location->ID, 'location_lat', true ) ),
'lng' => esc_attr( get_post_meta( $location->ID, 'location_lng', true ) ),
'dateUpdated' => esc_attr( $location->post_modified )
);
foreach ( $taxonomies as $tax ) {
$term_value = '';
if ( $terms = wp_get_object_terms( $location->ID, $tax, array( 'fields' => 'names' ) ) ) {
$term_value = implode( ',', $terms );
}
$location_data["tax_$tax"] = esc_attr( $term_value );
}
$content[] = $location_data;
}
if ( ! empty( $content ) ) {
$csv = new smParseCSV();
$csv->output( true, 'simplemap.csv', $content, array_keys( reset( $content ) ) );
die();
}
}
}
// Exports a LEGACY SimpleMap CSV file to WordPress
function export_legacy_csv() {
global $simple_map, $sm_locations,$wpdb;
if ( isset( $_GET['sm-action'] ) && 'export-legacy-csv' == $_GET['sm-action'] ) {
// Include CSV library
include_once( SIMPLEMAP_PATH . '/classes/parsecsv.lib.php' );
// Grab Categories
if ( $categories = $wpdb->get_results( "SELECT * FROM `" . $wpdb->prefix . "simple_map_cats`" ) ) {
foreach ( $categories as $key => $value ) {
$cats[$value->id] = $value;
}
}
// Grab locations
if ( $locations = $wpdb->get_results( "SELECT * FROM `" . $wpdb->prefix . "simple_map`" ) ) {
foreach( $locations as $key => $location ) {
$catnames = '';
// Do Cats
if ( isset( $location->category ) && 0 != $location->category ) {
if ( isset( $cats[$location->category] ) )
$catnames = $cats[$location->category]->name;
}
$content[] = array(
'name' => esc_attr( $location->name ),
'address' => esc_attr( $location->address ),
'address2' => esc_attr( $location->address2 ),
'city' => esc_attr( $location->city ),
'state' => esc_attr( $location->state ),
'zip' => esc_attr( $location->zip ),
'country' => esc_attr( $location->country ),
'phone' => esc_attr( $location->phone ),
'fax' => esc_attr( $location->fax ),
'url' => esc_attr( $location->url ),
'description' => esc_attr( $location->description ),
'category' => esc_attr( $catnames ),
'tags' => esc_attr( $location->tags ),
'special' => esc_attr( $location->special ),
'lat' => esc_attr( $location->lat ),
'lng' => esc_attr( $location->lng ),
'dateUpdated' => esc_attr( $location->dateUpdated )
);
}
$csv = new smParseCSV();
$csv->output (true, 'simplemap.csv', $content, array('name','address','address2','city','state','zip','country','phone','fax','url','description','category','tags','special','lat','lng','dateUpdated' ) );
die();
} else {
$csv = new smParseCSV();
$csv->output (true, 'simplemap.csv', array( array( 'You have no locations in your legacy database' ) ) );
die();
}
}
}
// Deletes legacy tables
function delete_legacy_tables() {
global $wpdb, $simple_map;
if ( isset( $_GET['sm-action'] ) && 'delete-legacy-simplemap' == $_GET['sm-action'] ) {
// Confirm we have both permisssion to do this and we have intent to do this.
if ( current_user_can( 'manage_options' ) && check_admin_referer( 'delete-legacy-simplemap' ) ) {
$drop_sm = 'DROP TABLE `' . $wpdb->prefix. 'simple_map`;';
$drop_cats = 'DROP TABLE `' . $wpdb->prefix . 'simple_map_cats`;';
$wpdb->query( $drop_sm );
$wpdb->query( $drop_cats );
if ( $simple_map->legacy_tables_exist() ) {
wp_redirect( admin_url( 'admin.php?page=simplemap-import-export&sm-msg=3' ) );
die();
} else {
wp_redirect( admin_url( 'admin.php?page=simplemap-import-export&sm-msg=2' ) );
die();
}
}
}
}
// All location data
function get_location_data_types( $init = array() ) {
static $types = null;
if ( empty( $types ) ) {
$types = array(
'name' => __( 'Name', 'SimpleMap' ),
'address' => __( 'Address', 'SimpleMap' ),
'address2' => __( 'Address 2', 'SimpleMap' ),
'city' => __( 'City', 'SimpleMap' ),
'state' => __( 'State', 'SimpleMap' ),
'zip' => __( 'Zip', 'SimpleMap' ),
'country' => __( 'Country', 'SimpleMap' ),
'phone' => __( 'Phone', 'SimpleMap' ),
'fax' => __( 'Fax', 'SimpleMap' ),
'email' => __( 'Email', 'SimpleMap' ),
'url' => __( 'URL', 'SimpleMap' ),
'description' => __( 'Description', 'SimpleMap' ),
'special' => __( 'Special', 'SimpleMap' ),
'lat' => __( 'Lat', 'SimpleMap' ),
'lng' => __( 'Lng', 'SimpleMap' ),
);
$legacy_types = array(
'category' => __( 'Legacy Taxonomy: Categories', 'SimpleMap' ),
'tags' => __( 'Legacy Taxonomy: Tags', 'SimpleMap' ),
'days' => __( 'Legacy Taxonomy: Days', 'SimpleMap' ),
'times' => __( 'Legacy Taxonomy: Times', 'SimpleMap' ),
);
foreach ( get_object_taxonomies( 'sm-location', 'objects' ) as $taxonomy => $tax_info ) {
$types['tax_' . $taxonomy] = __( 'Taxonomy: ' . $tax_info->label, 'SimpleMap' );
}
foreach ( $init as $key => $value ) {
if ( substr( $key, 0, 4 ) === 'tax_' ) {
$types[$key] = __( 'Taxonomy: ' . ucwords( substr( $key, strpos( $key, '-' ) + 1 ) ), 'SimpleMap' );
} elseif ( isset( $legacy_types[$key] ) ) {
$types[$key] = $legacy_types[$key];
}
}
$types = apply_filters( 'sm-data-types', $types );
}
return $types;
}
// Imports a CSV file to WordPress
function import_csv() {
global $simple_map, $sm_locations, $wpdb, $current_user, $blog_id;
// Define Importing Constant
define( 'WP_IMPORTING', true );
if ( isset( $_POST['sm-action'] ) && 'import-csv' == $_POST['sm-action'] && isset( $_POST['step'] ) && 2 == $_POST['step'] ) {
?>
<div class="wrap">
<?php
// Title
$sm_page_title = apply_filters( 'sm-import-export-page-title', 'SimpleMap: Import. Step One' );
// Toolbar
$simple_map->show_toolbar( $sm_page_title );
?>
<div id="dashboard-widgets-wrap" class="clear">
<div id="dashboard-widgets" class="metabox-holder">
<div class="postbox-container" >
<div id="normal-sortables" class="meta-box-sortables ui-sortable">
<div class="postbox">
<h3><?php _e('CSV Import: Step Two: Importing CSV', 'SimpleMap'); ?></h3>
<div class="inside" style="padding: 0 10px 10px 10px;">
<?php
// Include CSV library
require_once( SIMPLEMAP_PATH . '/classes/parsecsv.lib.php' );
$file_location = WP_PLUGIN_DIR . '/sm-temp-csv-' . $blog_id . '.csv';
if ( file_exists( $file_location ) && $csv = new smParseCSV() ) {
$csv->auto( $file_location );
if ( isset( $csv->data ) ) {
echo '<ol style="list-style-type:decimal">';
/* We're going to do some pre-processing to prevent WP's wp_get_unique_slug from pinging the database
* a ridiculous amount of times in the event that this file is importing several thousand locations with
* same name (like a franchise).
*/
$post_names = array();
$taxes = $simple_map->get_taxonomy_settings();
foreach ( $taxes as $taxonomy => $tax_info ) {
$taxes[$taxonomy] = $tax_info['field'];
}
$types = $this->get_location_data_types( current( $csv->data ) );
$columns = array();
foreach ( $types as $key => $value ) {
$taxonomy = null;
// If custom taxonomies don't exist, register them temporarily in the event that we need to import them.
if ( substr( $key, 0, 7 ) === 'tax_sm-' ) {
$taxonomy = substr( $key, 4 );
$taxes[$taxonomy] = $key;
}
// Allow legacy taxonomy column names
elseif ( array_search( $key, $taxes ) ) {
$taxonomy = $key;
}
if ( isset( $taxonomy ) ) {
$sm_locations->register_location_taxonomy( $taxonomy, $simple_map->get_taxonomy_settings( $taxonomy ) );
}
$columns[$key] = str_replace( 'col_', '', array_search( $key, $_POST ) );
}
$active_taxes = get_object_taxonomies( 'sm-location' );
$taxes = array_intersect_key( $taxes, array_flip( $active_taxes ) );
foreach ( $csv->data as $row => $location ) {
// Give me 20 seconds for each location. That should be more than enough time.
set_time_limit ( 20 );
// Convert assoc to int array since I can't trust the headings from the user
$location = array_values( $location );
// Use the information the user gave me via select boxes to map columns to correct attributes
foreach ( $columns as $key => $column ) {
if ( isset( $location[$column] ) ) {
$to_insert[$key] = trim( $location[$column] );
}
else {
$to_insert[$key] = '';
}
}
// Combine legacy taxonomy fields into new taxonomy fields.
$legacy_taxes = $simple_map->get_taxonomy_settings();
foreach ( $legacy_taxes as $taxonomy => $legacy_taxonomy ) {
$old_key = $legacy_taxonomy['field'];
$key = 'tax_' . $taxonomy;
if ( isset( $to_insert[$old_key] ) ) {
$to_insert += array( $key => '' );
$to_insert[$key] = implode( ',', array_filter( array( $to_insert[$key], $to_insert[$old_key] ) ) );
unset( $to_insert[$old_key] );
}
}
// Prep and insert
if ( isset( $to_insert ) ) {
$options = $simple_map->get_options();
$geocoded = '';
// Maybe geo encode
if ( ( empty( $to_insert['lat'] ) || empty( $to_insert['lng'] ) ) ) {
if ( $geo = $simple_map->geocode_location( $to_insert['address'], $to_insert['city'], $to_insert['state'], $to_insert['zip'], $to_insert['country'], '' ) ) {
$geocoded = __( 'geocoded and ', 'SimpleMap' );
if ( isset( $geo['lat'] ) ) {
$to_insert['lat'] = $geo['lat'];
}
if ( isset( $geo['lng'] ) ) {
$to_insert['lng'] = $geo['lng'];
}
}
}
// Prevent dup names before getting to wp_unique_slug function
$clean_name = sanitize_title( $to_insert['name'] );
// Start by check to see if this post's name has been used before
if ( isset( $post_names[$clean_name] ) ) {
// Set the int to the value of the post_name key (this is set the first time we import a post with this title).
$post_names_int = $post_names[$clean_name];
// Just to be safe, lets make sure the incremented name doesn't exist. Loop till we find one available.
while( isset( $post_names[$clean_name . '-' . $post_names_int] ) ) {
$post_names_int++;
}
// Set the new unique slug
$unique_title = $clean_name . '-' . $post_names_int;
// Add the post_name to the post attributes array we're about to insert
$vars['post_name'] = $unique_title;
// Update the original slug for this title with the new int
$post_names[$clean_name] = $post_names[$unique_title] = $post_names_int;
} else {
// If we made it here, its the first time we're inserting a post with this title (this import anyway).
// Add it to the post attributes array we're about to send to wp_insert_post
$vars['post_name'] = $clean_name;
// Log this title as used in the post_names array with an int of 1
$post_names[$clean_name] = 1;
}
// Prep for WordPress function
wp_get_current_user();
$vars['post_title'] = $to_insert['name'];
$vars['post_author'] = $current_user->ID;
$vars['post_type'] = 'sm-location';
$vars['post_status'] = 'publish';
$vars['post_content'] = $to_insert['description'];
// Insert into WordPress post table
if ( $id = wp_insert_post( $vars ) ) {
update_post_meta( $id, 'location_address', $to_insert['address'] );
update_post_meta( $id, 'location_address2', $to_insert['address2'] );
update_post_meta( $id, 'location_city', $to_insert['city'] );
update_post_meta( $id, 'location_state', $to_insert['state'] );
update_post_meta( $id, 'location_zip', $to_insert['zip'] );
update_post_meta( $id, 'location_country', $to_insert['country'] );
update_post_meta( $id, 'location_phone', $to_insert['phone'] );
update_post_meta( $id, 'location_fax', $to_insert['fax'] );
update_post_meta( $id, 'location_email', $to_insert['email'] );
update_post_meta( $id, 'location_url', $to_insert['url'] );
update_post_meta( $id, 'location_special', $to_insert['special'] );
update_post_meta( $id, 'location_lat', $to_insert['lat'] );
update_post_meta( $id, 'location_lng', $to_insert['lng'] );
foreach ( $taxes as $taxonomy => $tax_field ) {
if ( isset( $to_insert[$tax_field] ) ) {
// Place comma separated values into array
$terms = explode( ',', $to_insert[$tax_field] );
// Loop through array. If term does not exist, create it.
// Then associate the term with the location.
foreach ( (array) $terms as $key => $name ) {
$name = trim( $name );
// Skip it if we have bad data
if ( empty( $name ) ) {
continue;
}
// Grab or create and grab the category ID
if ( $term_obj = get_term_by( 'name', $name, $taxonomy ) ) {
$term_id = $term_obj->term_id;
} else {
$term_array = wp_insert_term( $name, $taxonomy );
if ( is_wp_error( $term_array ) ) {
continue;
}
$term_id = $term_array['term_id'];
}
// This is just a failsafe. It also gives us access to vars the WP API created rather than from the CSV
if ( ! is_wp_error( $term_id ) && $term = get_term( (int) $term_id, $taxonomy ) ) {
if ( ! is_wp_error( $term ) ) {
// Associate (last var appends term to rather than replaces existing terms)
wp_set_object_terms( $id, $term->name, $taxonomy, true );
unset( $term );
}
}
}
}
}
echo "<li>" . sprintf( esc_attr( $to_insert['name'] ) . __( ' was successfully %simported', 'SimpleMap' ), $geocoded ) . "</li>";
} else {
echo "<li>" . esc_attr( $to_insert['name'] ) . __( ' failed to import properly', 'SimpleMap' ) . "</li>";
}
unset( $to_insert );
unset( $geocoded );
}
}
echo "</ul>";
echo "<h2>" . sprintf( __( 'View them <a href="%s">here</a>', 'SimpleMap' ), admin_url( 'edit.php?post_type=sm-location' ) ) . "</h2>";
}
// Import is finished, delete csv and redirect to edit locaitons page
if ( file_exists( $file_location ) ) {
unlink( $file_location );
}
}
?>
</div>
</div>
</div>
</div>
</div>
<?php
}
}
// Generates the CSV Preview
function do_csv_preview() {
global $simple_map, $blog_id;
$options = $simple_map->get_options();
/*
if ( !isset( $options['api_key'] ) )
$options['api_key'] = '';
*/
extract( $options );
?>
<div class="wrap">
<?php
// Title
$sm_page_title = apply_filters( 'sm-import-export-page-title', 'SimpleMap: Import. Step One' );
// Toolbar
$simple_map->show_toolbar( $sm_page_title );
?>
<div id="dashboard-widgets-wrap" class="clear">
<div id='dashboard-widgets' class='metabox-holder'>
<div class='postbox-container' >
<div id='normal-sortables' class='meta-box-sortables ui-sortable'>
<div class="postbox">
<h3><?php _e('CSV Import: Step One', 'SimpleMap'); ?></h3>
<div class="inside" style="padding: 0 10px 10px 10px;">
<p class='howto'><?php printf( __( 'The first step is to confirm that we importing the data correctly. %sPlease match the following sample data%s from your CSV to the correct data type by selecting an attributes form the downdown boxes.', 'SimpleMap' ), '<strong><span style="color:red;">', '</span></strong>' );?></p>
<?php
// Include CSV library
include_once( SIMPLEMAP_PATH . '/classes/parsecsv.lib.php' );
$file_location = WP_PLUGIN_DIR . '/sm-temp-csv-'. $blog_id . '.csv';
if ( move_uploaded_file( $_FILES['simplemap-csv-upload']['tmp_name'], $file_location ) ) {
if ( $csv = new smParseCSV( $file_location ) ) {
?>
<form action="" method="post">
<input type="hidden" name="sm-action" value="import-csv" />
<input type="hidden" name="step" value="2" />
<p><input type="submit" class="button-primary" value="<?php _e( 'Import CSV', 'SimpleMap' ); ?>" /> | <a href=''><?php _e( 'Cancel', 'SimpleMap' ); ?></a></p>
<table>
<tr>
<?php
$this->get_location_data_types( current($csv->data) );
foreach( $csv->titles as $col => $title ) {
echo "<td>" . $this->column_select( $col, $title ) . "</td>";
}
?>
</form>
</tr>
<?php // Grab some random rows to display as a sample
$row_count = count( $csv->data );
if ( $row_count < 50 ) {
foreach( $csv->data as $csv_row => $csv_row_data ) {
?><tr><?php
foreach ( $csv_row_data as $td => $tdv ) {
?><td><?php echo esc_attr( $tdv ); ?></td><?php
}
?></tr><?php
}
} else {
for( $i=0;$i<=50;$i++ ) {
$numb = rand( 1, $row_count -1 );
?><tr><?php
foreach ( $csv->data[$numb] as $td => $tdv ) {
?><td><?php echo esc_attr( $tdv ); ?></td><?php
}
?></tr><?php
}
}
?>
</table>
<?php
}
} else {
_e( sprintf( 'Please make the following directory <a href="%s">writable by WordPress</a>: %s', 'http://codex.wordpress.org/Changing_File_Permissions#Permission_Scheme_for_WordPress', '<code>' . WP_PLUGIN_DIR . '</code>' ), 'SimpleMap' );
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
}
// This function creates a select box of all my data types to assign to this column
function column_select( $col, $title ) {
$select = "<select name='col_" . esc_attr( $col ) . "'>";
$select .= "<option value='-1' >Don't Import</option>";
foreach( $this->get_location_data_types() as $type => $label ) {
$select .= "<option value='" . $type . "' " . selected( trim( $type ), trim( $title ), false ) . " >" . $label . "</option>";
}
$select .= "</select>";
return $select;
}
// Prints the options page
function print_page() {
if ( isset( $_POST['sm-action'] ) && 'import-csv' == $_POST['sm-action'] ) {
$step = isset( $_POST['step'] ) ? absint( $_POST['step'] ) : 1;
// Check for uploaded file with no errors.
if ( ( 1 == $step && isset( $_FILES['simplemap-csv-upload'] ) && ! $_FILES['simplemap-csv-upload']['error'] > 0 ) || 2 == $step ) {
switch( $step ) {
case 2:
$this->import_csv();
break;
case 1:
default :
$this->do_csv_preview();
}
}
} else {
global $simple_map;
$options = $simple_map->get_options();
/*
if ( !isset( $options['api_key'] ) )
$options['api_key'] = '';
*/
extract( $options );
?>
<div class="wrap">
<?php
// Title
$sm_page_title = apply_filters( 'sm-import-export-page-title', 'SimpleMap: Import/Export CSV' );
// Toolbar
$simple_map->show_toolbar( $sm_page_title );
// Messages
if ( isset( $_GET['sm-msg'] ) && '2' == $_GET['sm-msg'] )
echo '<div class="updated fade"><p>'.__('Legacy SimpleMap settings deleted.', 'SimpleMap').'</p></div>';
if ( isset( $_GET['sm-msg'] ) && '3' == $_GET['sm-msg'] )
echo '<div class="error fade"><p>'.__('Legacy SimpleMap NOT settings deleted.', 'SimpleMap').'</p></div>';
?>
<div id="dashboard-widgets-wrap" class="clear">
<div id='dashboard-widgets' class='metabox-holder'>
<div class='postbox-container' style='width:49%'>
<div id='normal-sortables' class='meta-box-sortables ui-sortable'>
<div class="postbox">
<h3><?php _e('Import From File', 'SimpleMap'); ?></h3>
<div class="inside" style="padding: 0 10px 10px 10px;">
<h4><?php _e('If your file has fewer than 100 records and does not have latitude/longitude data:', 'SimpleMap'); ?></h4>
<p><?php _e('Make sure your CSV has a header row that gives the field names (in English). A good example of a header row would be as follows:', 'SimpleMap'); ?></p>
<p><em style="color: #777; font: italic 1.1em Georgia;"><?php _e('Name, Address, Address Line 2, City, State/Province, ZIP/Postal Code, Country, Phone, Fax, URL, Category, Tags, Days, Times, Description, Special (1 or 0), Latitude, Longitude', 'SimpleMap'); ?></em></p>
<p><?php _e('You can import your file with or without quotation marks around each field. However, if any of your fields contain commas, you should enclose your fields in quotation marks. Single ( \' ) or double ( " ) quotation marks will work.', 'SimpleMap') ?></p>
<h4><?php _e('If your file has more than 100 records:', 'SimpleMap'); ?></h4>
<p><?php _e('If you have more than 100 records to import, it is best to do one of the following:', 'SimpleMap'); ?></p>
<ul style="list-style-type: disc; margin-left: 3em;">
<li><?php _e('Geocode your own data before importing it'); ?></li>
<li><?php _e('Split your file into multiple files with no more than 100 lines each'); ?></li>
</ul>
<p><?php printf(__('Geocoding your own data will allow you to import thousands of records very quickly. If your locations need to be geocoded by SimpleMap, any file with more than 100 records might stall your server. %s Resources for geocoding your own locations can be found here.%s', 'SimpleMap'), '<a href="http://groups.google.com/group/Google-Maps-API/web/resources-non-google-geocoders" target="_blank">', '</a>'); ?></p>
<p><?php _e('If you are importing a file you exported from SimpleMap (and haven\'t changed since), be sure to check the box below since the locations are already geocoded.', 'SimpleMap'); ?></p>
<form name="import_form" method="post" action="<?php echo admin_url( 'admin.php?page=simplemap-import-export' ); ?>" enctype="multipart/form-data" class="inabox">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo (2 * 1024 * 1024); ?>" />
<input type="hidden" name="sm-action" value="import-csv" />
<p style="margin-top: 0;"><label for="simplemap-csv-upload"><?php _e('File to import (maximum size 2MB):', 'SimpleMap'); ?></label><input type="file" style="padding-left: 10px; border: none; font-size: 0.9em;" id="simplemap-csv-upload" name="simplemap-csv-upload" />
<br />
<?php
// Warn them if the simplemap path is not writable
if ( ! is_writable( WP_PLUGIN_DIR ) )
echo "<br />" . __( sprintf( 'Please make the following directory <a href="%s">writable by WordPress</a>: %s', 'http://codex.wordpress.org/Changing_File_Permissions#Permission_Scheme_for_WordPress', '<code>' . WP_PLUGIN_DIR . '</code>' ), 'SimpleMap' );
?>
</p>
<input type="submit" class="button-primary" value="<?php _e('Import CSV File', 'SimpleMap'); ?>" />
<?php /* if ( '' == $options['api_key'] ) : ?>
<?php printf( __( "Warning: You still need to enter an <a href='%s'>API key</a> if you need your locaitons geocoded.", 'SimpleMap' ), admin_url( "admin.php?page=simplemap" ) ); ?>
<?php endif; */ ?>
</form>
<p style="color: #777; font: italic 1.1em Georgia;"><?php _e('Importing a file may take several seconds; please be patient.', 'SimpleMap'); ?></p>
<div class="clear"></div>
</div> <!-- inside -->
</div> <!-- postbox -->
<!-- =========================================
==============================================
========================================== -->
<div class="postbox">
<h3><?php _e('Export To File', 'SimpleMap'); ?></h3>
<div class="inside" style="padding: 10px;">
<form name="export_form" method="post" action="" >
<input type="hidden" name="sm-action" value="export-csv" />
<input type="submit" class="button-primary" value="<?php _e('Export Database to CSV File', 'SimpleMap'); ?>" />
</form>
<div class="clear"></div>
</div> <!-- inside -->
</div> <!-- postbox -->
<!-- =========================================
==============================================
========================================== -->
</div> <!-- meta-box-sortables -->
</div> <!-- postbox-container -->
<div class='postbox-container' style='width:49%;'>
<div id='side-sortables' class='meta-box-sortables ui-sortable'>
<?php do_action( 'sm-import-export-side-sortables-top' ); ?>
<!-- #### PREMIUM SUPPORT #### -->
<div class="postbox" >
<h3 style='color:#fff;text-shadow:0 1px 0 #000;background: #fff url( <?php echo SIMPLEMAP_URL; ?>/inc/images/blue-grad.png ) top left repeat-x;'><?php _e( 'Premium Support and Features', 'SimpleMap' ); ?></h3>
<div class="inside" style='padding: 0pt 10px 10px;' >
<?php
// Check for premium support status
global $simplemap_ps;
if ( ! url_has_ftps_for_item( $simplemap_ps ) ) : ?>
<h4><?php printf( __( 'SimpleMap Premium Support Benefits', 'SimpleMap' ), esc_attr( site_url() ) ); ?></h4>
<p>
<?php printf( __( 'SimpleMap now offers a premium support package for the low cost of %s per year per domain.', 'SimpleMap' ), '$30.00 USD' ); ?>
</p>
<p>
<?php _e( 'By signing up for SimpleMap premium support, you help to ensure future enhancements to this excellent project as well as the following benefits:', 'SimpleMap' ); ?>
</p>
<ul style='margin-left:25px;list-style-type:disc'>
<li><?php _e( 'Around the clock access to our extensive knowledge base and support forum from within your WordPress dashboard', 'SimpleMap' ); ?></li>
<li><?php _e( 'Professional and timely response times to all your questions from the SimpleMap team', 'SimpleMap' ); ?></li>
<li><?php _e( 'A 10% discount for any custom functionality you request from the SimpleMap developers', 'SimpleMap' ); ?></li>
<li><?php _e( 'A 6-12 month advance access to new features integrated into the auto upgrade functionality of WordPress', 'SimpleMap' ); ?></li>
</ul>
<ul style='margin-left:25px;list-style-type:none'>
<li><a href='<?php echo get_ftps_paypal_button( $simplemap_ps ); ?>'><?php _e( 'Signup Now', 'SimpleMap' ); ?></a></li>
<li><a target='_blank' href='<?php echo get_ftps_learn_more_link( $simplemap_ps ); ?>'><?php _e( 'Learn More', 'SimpleMap' ); ?></a></li>
</ul>
<?php else : ?>
<p class='howto'><?php printf( "Your premium support for <code>%s</code> was purchased on <code>%s</code> by <code>%s</code> (%s). It will remain valid for this URL until <code>%s</code>.", get_ftps_site( $simplemap_ps ), date( "F d, Y", get_ftps_purchase_date( $simplemap_ps ) ), get_ftps_name( $simplemap_ps ), get_ftps_email( $simplemap_ps ), date( "F d, Y", get_ftps_exp_date( $simplemap_ps ) ) ); ?></p>
<p><a href='#' id='premium_help'><?php _e( 'Launch Premium Support widget', 'SimpleMap' ); ?></a> | <a target="blank" href="http://support.simplemap-plugin.com?sso=<?php echo get_ftps_sso_key( $simplemap_ps ); ?>"><?php _e( 'Visit Premium Support web site', 'SimpleMap' );?></a></p>
<script type="text/javascript" charset="utf-8">
Tender = {
hideToggle: true,
sso: "<?php echo get_ftps_sso_key( $simplemap_ps ); ?>",
widgetToggles: [document.getElementById('premium_help')]
}
</script>
<script src="https://simplemap.tenderapp.com/tender_widget.js" type="text/javascript"></script>
<?php endif; ?>
</div> <!-- inside -->
</div> <!-- postbox -->
<?php if ( $simple_map->legacy_tables_exist() ) : ?>
<!-- #### LEGACY EXPORT #### -->
<div class="postbox" >
<h3><?php _e( 'Legacy Data', 'SimpleMap' ); ?></h3>
<div class="inside" style="padding: 10px;">
<p class='howto'><?php _e( 'It appears that you have location data stored in legacy SimpleMap tables that existed prior to version 2.0. What would you like to do with that data?', 'SimpleMap' ); ?></p>
<ul style="list-style-type: disc; margin-left: 3em;">
<li><a href='<?php echo admin_url( 'admin.php?page=simplemap-import-export&amp;sm-action=export-legacy-csv' ); ?>'><?php _e( 'Export legacy data as a CSV file', 'SimpleMap' ); ?></a></li>
<!--<li><a href=''><?php _e( 'Port all legacy data over to custom post types', 'SimpleMap' ); ?></a></li>-->
<li><a onClick="javascript:return confirm('<?php _e( 'Last chance! Pressing OK will delete all Legacy SimpleMap data.'); ?>')" href="<?php echo wp_nonce_url( admin_url( 'admin.php?page=simplemap-import-export&sm-action=delete-legacy-simplemap' ), 'delete-legacy-simplemap' ); ?>" ><?php _e( 'Permanently delete the legacy data and tables', 'SimpleMap' ); ?></a></li>
</ul>
</div>
</div>
<?php endif; ?>
<?php do_action( 'sm-import-export-side-sortables-bottom' ); ?>
</div>
</div> <!-- dashboard-widgets -->
<div class="clear">
</div>
</div><!-- dashboard-widgets-wrap -->
</div> <!-- wrap -->
<?php
}
}
}
}
?>

749
classes/locations.php Normal file
View File

@@ -0,0 +1,749 @@
<?php
if ( !class_exists( 'SM_Locations' ) ) {
class SM_Locations {
function sm_locations(){
// Register my locations on init hook
add_action( 'init', array( &$this, 'register_locations' ) );
add_action( 'init', array( &$this, 'register_location_taxonomies' ) );
// Queue my JS
add_action( 'admin_enqueue_scripts', array( &$this, 'enqueue_location_add_edit_js' ) );
add_action( 'init', array( &$this, 'location_add_edit_js' ) );
// Save post meta
add_action( 'save_post', array( &$this, 'save_post_meta' ) );
add_action( 'wp_ajax_ajax_save_lat_lng', array( &$this, 'ajax_save_lat_lng' ) );
// Limit pages called for dropdown parent selector in quick edit
add_filter( 'parse_request', array( &$this, 'limit_edit_query' ) );
add_filter( 'quick_edit_dropdown_pages_args', array( &$this, 'limit_wp_dropdown_pages' ) );
add_filter( 'wp_dropdown_pages', array( &$this, 'modify_empty_wp_dropdown_pages' ) );
// Flush cache on manual location updates
add_action( 'save_post', array( &$this, 'flush_cache_data' ) );
add_action( 'trash_post', array( &$this, 'flush_cache_data' ) );
add_action( 'untrash_post', array( &$this, 'flush_cache_data' ) );
add_action( 'edit_post', array( &$this, 'flush_cache_data' ) );
add_action( 'delete_post', array( &$this, 'flush_cache_data' ) );
}
// Register locations post type
function register_locations() {
global $simple_map;
$args = array();
$options = $simple_map->get_options();
if ( !empty( $options['enable_permalinks'] ) ) {
$args += array(
'publicly_queryable' => true,
'exclude_from_search' => false,
'rewrite' => array( 'slug' => $options['permalink_slug'] ),
);
}
$args += array(
'public' => true,
'publicly_queryable' => false,
'exclude_from_search' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => false,
'query_var' => 'sm-location',
'register_meta_box_cb' => array( &$this, 'location_meta_cb' ),
'supports' => array(),
'labels' => array(
'name' => 'Locations',
'singular_name' => 'Location',
'add_new_item' => 'Add New Location',
'edit_item' => 'Edit Location',
'new_item' => 'New Location',
'view_item' => 'View Locations',
'search_items' => 'Search Locations',
'not_found' => 'No Locations found',
'not_found_in_trash' => 'No Locations found in trash',
)
);
// Register it
register_post_type( 'sm-location', $args );
}
// Register custom taxonomies for locations
function register_location_taxonomies() {
global $simple_map;
$options = $simple_map->get_options();
foreach ( $options['taxonomies'] as $taxonomy => $tax_info ) {
$this->register_location_taxonomy( $taxonomy, $tax_info );
}
}
// Register custom taxonomy for locations
function register_location_taxonomy( $taxonomy, $tax_info ) {
if ( taxonomy_exists( $taxonomy ) ) {
return;
}
$tax_info += array(
'singular' => $taxonomy,
'plural' => $taxonomy,
'hierarchical' => false,
);
$args = array(
'labels' => array(
'name' => 'Location ' . $tax_info['plural'],
'singular_name' => 'Location ' . $tax_info['singular'],
'search_items' => 'Search ' . $tax_info['plural'],
'popular_items' => 'Popular ' . $tax_info['plural'],
'all_items' => 'All ' . $tax_info['plural'],
'parent_item' => 'Parent ' . $tax_info['singular'],
'parent_item_colon' => 'Parent ' . $tax_info['singular'] . ':',
'edit_item' => 'Edit ' . $tax_info['singular'],
'update_item' => 'Update ' . $tax_info['singular'],
'add_new_item' => 'Add New ' . $tax_info['singular'],
'new_item_name' => 'New ' . $tax_info['singular'] . ' Name',
'separate_items_with_commas' => 'Separate ' . strtolower( $tax_info['plural'] ) . ' with commas',
'add_or_remove_items' => 'Add or remove ' . strtolower( $tax_info['plural'] ),
'choose_from_most_used' => 'Choose from the most used ' . strtolower( $tax_info['plural'] ),
),
'hierarchical' => $tax_info['hierarchical'],
'rewrite' => false,
'show_tagcloud' => false
);
register_taxonomy( $taxonomy, 'sm-location', $args );
}
// Add call back for meta box
function location_meta_cb(){
add_meta_box( 'sm-location-premium-support', __( 'Premium Support', 'SimpleMap' ), array( &$this, 'premium_support' ), 'sm-location', 'side', 'high' );
add_meta_box( 'sm-geo-location', __( 'Geographic Location', 'SimpleMap' ), array( &$this, 'geo_location' ), 'sm-location', 'normal' );
add_meta_box( 'sm-additional-information', __( 'Additional Information', 'SimpleMap' ), array( &$this, 'additional_information' ), 'sm-location', 'normal' );
add_meta_box( 'sm-location-drag-drop', __( 'Drag and Drop Location', 'SimpleMap' ), array( &$this, 'location_drag_drop' ), 'sm-location', 'side' );
}
// Add premium support box
function premium_support() {
global $simplemap_ps, $current_user;
wp_get_current_user();
$status_key = md5( 'ft_premium_support_' . $simplemap_ps->product_id . '_' . sanitize_title_with_dashes( $simplemap_ps->site_url ) . '_' . sanitize_title_with_dashes( $simplemap_ps->server_url ) ) ;
$sso_key = md5( 'ft_premium_sso_' . $current_user->ID . '_' . $simplemap_ps->product_id . '_' . sanitize_title_with_dashes( $simplemap_ps->site_url ) . '_' . sanitize_title_with_dashes( $simplemap_ps->server_url ) );
// Set status from transient if not set via global
if ( '' == $simplemap_ps->ps_status && '' != get_transient( $status_key ) )
$simplemap_ps->ps_status = get_transient( $status_key );
// Set sso key from transient if not set via global
if ( '' == $simplemap_ps->sso_status && '' != get_transient( $sso_key ) )
$simplemap_ps->sso_status = get_transient( $sso_key );
//echo "<pre>";print_r( $simplemap_ps );echo "</pre>";
if ( ! url_has_ftps_for_item( $simplemap_ps ) ) :
?>
<p>
<?php _e( 'By signing up for SimpleMap premium support, you help to ensure future enhancements to this excellent project as well as the following benefits:', 'SimpleMap' ); ?>
</p>
<ul style='margin-left:25px;list-style-type:disc'>
<li><?php _e( 'Around the clock access to our extensive knowledge base and support forum from within your WordPress dashboard', 'SimpleMap' ); ?></li>
<li><?php _e( 'Professional and timely response times to all your questions from the SimpleMap team', 'SimpleMap' ); ?></li>
<li><?php _e( 'A 10% discount for any custom functionality you request from the SimpleMap developers', 'SimpleMap' ); ?></li>
<li><?php _e( 'A 6-12 month advance access to new features integrated into the auto upgrade functionality of WordPress', 'SimpleMap' ); ?></li>
</ul>
<ul style='margin-left:25px;list-style-type:none'>
<li><a href='<?php echo get_ftps_paypal_button( $simplemap_ps ); ?>'><?php _e( 'Signup Now', 'SimpleMap' ); ?></a></li>
<li><a target='_blank' href='<?php echo get_ftps_learn_more_link( $simplemap_ps ); ?>'><?php _e( 'Learn More', 'SimpleMap' ); ?></a></li>
</ul>
<?php
else :
?>
<p class='howto aligncenter'><?php printf( __( 'Your premium support license for %s is valid until %s', 'SimpleMap' ), get_ftps_site( $simplemap_ps ), date( "F d, Y", get_ftps_exp_date( $simplemap_ps ) ) ); ?></p>
<ul style='margin-left:25px;list-style-type:disc'>
<li><a href="#" id="simplemap-pss"><?php _e( 'Launch Premium Support widget', 'SimpleMap' ); ?></a></li>
<li><a target='_blank' href="http://support.simplemap-plugin.com?sso=<?php echo get_ftps_sso_key( $simplemap_ps ); ?>"><?php _e( 'Visit Premium Support web site', 'SimpleMap' ); ?></a></li>
<script type="text/javascript" charset="utf-8">
Tender = {
hideToggle: true,
sso: "<?php echo get_ftps_sso_key( $simplemap_ps ); ?>",
widgetToggles: [document.getElementById('simplemap-pss')]
}
</script>
<script src="https://simplemap.tenderapp.com/tender_widget.js" type="text/javascript"></script>
<?php
endif;
}
// Geographic Location Information
function geo_location( $post ){
global $simple_map, $hook_suffix;
$options = $simple_map->get_options();
// Location data
$location_address = get_post_meta( $post->ID, 'location_address', true ) ? get_post_meta( $post->ID, 'location_address', true ) : '';
$location_address2 = get_post_meta( $post->ID, 'location_address2', true ) ? get_post_meta( $post->ID, 'location_address2', true ) : '';
$location_city = get_post_meta( $post->ID, 'location_city', true ) ? get_post_meta( $post->ID, 'location_city', true ) : '';
$location_state = get_post_meta( $post->ID, 'location_state', true ) ? get_post_meta( $post->ID, 'location_state', true ) : $options['default_state'];
$location_zip = get_post_meta( $post->ID, 'location_zip', true ) ? get_post_meta( $post->ID, 'location_zip', true ) : '';
$location_country = get_post_meta( $post->ID, 'location_country', true ) ? get_post_meta( $post->ID, 'location_country', true ) : $options['default_country'];
$location_lat = get_post_meta( $post->ID, 'location_lat', true ) ? get_post_meta( $post->ID, 'location_lat', true ) : '';
$location_lng = get_post_meta( $post->ID, 'location_lng', true ) ? get_post_meta( $post->ID, 'location_lng', true ) : '';
?>
<p class="sub"><?php _e('You must enter either an address or a latitude/longitude. If you enter both, the address will not be geocoded and your latitude/longitude values will remain intact.', 'SimpleMap'); ?></p>
<div class='hidden updated below-h2' id='js-geo-encode-msg'>
<p><?php echo __( "Your Server's IP is over the geocode threshold set by Google so we had fallback to a Javascript function. <span id='sm_js_update_lat_lng_result'></span>", "SimpleMap" ); ?></p>
</div>
<div class="table">
<table class="form-table">
<!-- Store Address -->
<tr valign="top">
<td width="150"><label for="location_address"><?php _e('Address', 'SimpleMap'); ?></label></td>
<td><input type="text" name="location_address" id="location_address" size="30" value="<?php echo esc_attr( $location_address ); ?>" /><br />
<input type="text" name="location_address2" size="30" value="<?php echo esc_attr( $location_address2 ); ?>" /></td>
</tr>
<!-- City / Town -->
<tr valign="top">
<td><label for="location_city"><?php _e('City/Town', 'SimpleMap'); ?></label></td>
<td><input type="text" name="location_city" id="location_city" value="<?php echo esc_attr( $location_city ); ?>" size="30" /></td>
</tr>
<!-- State / Providence -->
<tr valign="top">
<td><label for="location_state"><?php _e('State/Province', 'SimpleMap'); ?></label></td>
<td><input type="text" name="location_state" id="location_state" value="<?php echo esc_attr( $location_state ); ?>" size="30" /></td>
</tr>
<!-- Zip / Postal Code -->
<tr valign="top">
<td><label for="location_zip"><?php _e('Zip/Postal Code', 'SimpleMap'); ?></label></td>
<td><input type="text" name="location_zip" id="location_zip" value="<?php echo esc_attr( $location_zip ); ?>" size="30" maxlength="20" /></td>
</tr>
<!-- Country -->
<tr valign="top">
<td><label for="location_country"><?php _e('Country', 'SimpleMap'); ?></label></td>
<td>
<select name="location_country" id="location_country">
<?php
foreach ( $simple_map->get_country_options() as $key => $value ) {
echo '<option value="' . $key . '" ' . selected( $location_country, $key, false ) . '>' . $value . '</option>'."\n";
}
?>
</select>
</td>
</tr>
<!-- Lat / Lng -->
<tr valign="top">
<td><label for="location_lat"><?php _e('Latitude/Longitude', 'SimpleMap'); ?></label></td>
<td><input type="text" name="location_lat" id="location_lat" size="14" value="<?php echo esc_attr( $location_lat ); ?>" />
<input type="text" name="location_lng" id="location_lng" size="14" value="<?php echo esc_attr( $location_lng ); ?>" /> <span id='latlng_updated' class='updated' style='display:none;color:#666666;font-style:italic;font-size:11px;'>Lat / Lng updated. Update address too? <a href='#' onclick="dragDropUpdateAddress();jQuery('#latlng_updated').hide();jQuery('#latlng_dontforget').fadeIn();return false;" >yes</a> | <a href='#' onclick="jQuery('#latlng_updated').hide();jQuery('#latlng_dontforget').fadeIn();return false;">no</a></span> <span id='latlng_dontforget' class='error' style='display:none;color:#666666;font-style:italic;font-size:11px;'>Changes aren't saved until you update or publish</span></td>
</tr>
</table>
</div> <!-- table -->
<div class="clear"></div>
<?php
}
// Additional Information
function additional_information( $post ){
global $simple_map;
$options = $simple_map->get_options();
$location_phone = get_post_meta( $post->ID, 'location_phone', true ) ? get_post_meta( $post->ID, 'location_phone', true ) : '';
$location_fax = get_post_meta( $post->ID, 'location_fax', true ) ? get_post_meta( $post->ID, 'location_fax', true ) : '';
$location_url = get_post_meta( $post->ID, 'location_url', true ) ? get_post_meta( $post->ID, 'location_url', true ) : '';
$location_email = get_post_meta( $post->ID, 'location_email', true ) ? get_post_meta( $post->ID, 'location_email', true ) : '';
$location_special = get_post_meta( $post->ID, 'location_special', true ) ? get_post_meta( $post->ID, 'location_special', true ) : '';
?>
<div class="table">
<table class="form-table">
<!-- Phone -->
<tr valign="top">
<td width="150"><label for="location_phone"><?php _e('Phone', 'SimpleMap'); ?></label></td>
<td><input type="text" id="location_phone" name="location_phone" size="30" maxlength="28" value="<?php echo esc_attr( $location_phone ); ?>" /></td>
</tr>
<!-- Email -->
<tr valign="top">
<td><label for="location_email"><?php _e('Email', 'SimpleMap'); ?></label></td>
<td><input type="text" name="location_email" id="location_email" size="30" value="<?php echo esc_attr( $location_email ); ?>" />
</tr>
<!-- URL -->
<tr valign="top">
<td><label for="location_url"><?php _e('URL', 'SimpleMap'); ?></label></td>
<td><input type="text" name="location_url" id="location_url" size="30" value="<?php echo esc_attr( $location_url ); ?>" />
<br /><?php _e('Please include <strong>http://</strong>', 'SimpleMap'); ?></td>
</tr>
<!-- Fax -->
<tr valign="top">
<td><label for="location_fax"><?php _e('Fax', 'SimpleMap'); ?></label></td>
<td><input type="text" id="location_fax" name="location_fax" size="30" maxlength="28" value="<?php echo esc_attr( $location_fax ); ?>" /></td>
</tr>
<!-- Store Special -->
<?php if ( $options['special_text'] != '' ) { ?>
<tr valign="top">
<td><label for="location_special"><?php echo $options['special_text']; ?></label></td>
<td><input type="checkbox" id="location_special" name="location_special" value="1" <?php checked( $location_special ); ?> /></td>
</tr>
<?php } ?>
</table>
</div> <!-- table -->
<div class="clear"></div>
<?php
}
// This function contains the little map with the marker
function location_drag_drop( $post ) {
global $simple_map;
$options = $simple_map->get_options();
// Location data
$location_address = get_post_meta( $post->ID, 'location_address', true ) ? get_post_meta( $post->ID, 'location_address', true ) : '';
$location_address2 = get_post_meta( $post->ID, 'location_address2', true ) ? get_post_meta( $post->ID, 'location_address2', true ) : '';
$location_city = get_post_meta( $post->ID, 'location_city', true ) ? get_post_meta( $post->ID, 'location_city', true ) : '';
$location_state = get_post_meta( $post->ID, 'location_state', true ) ? get_post_meta( $post->ID, 'location_state', true ) : $options['default_state'];
$location_zip = get_post_meta( $post->ID, 'location_zip', true ) ? get_post_meta( $post->ID, 'location_zip', true ) : '';
$location_country = get_post_meta( $post->ID, 'location_country', true ) ? get_post_meta( $post->ID, 'location_country', true ) : $options['default_country'];
$location_lat = get_post_meta( $post->ID, 'location_lat', true ) ? get_post_meta( $post->ID, 'location_lat', true ) : '';
$location_lng = get_post_meta( $post->ID, 'location_lng', true ) ? get_post_meta( $post->ID, 'location_lng', true ) : '';
?>
<p class='howto'>Drag the marker to fine tune your location's placement on the map</p>
<div id="dragdrop_map_canvas" style="width:267px;height:200px;"></div>
<?php
}
// Enqueues the JS I need.
function enqueue_location_add_edit_js() {
global $current_screen, $post;
if ( ! is_admin() || 'sm-location' != $current_screen->id )
return;
wp_enqueue_script( 'sm-drag-drop-location-js', site_url() . '/?sm-drag-drop-location-js=' . $post->ID, array( 'jquery' ) );
}
// Javascript for add / edit location page
function location_add_edit_js() {
global $current_screen, $simple_map;
$options = $simple_map->get_options();
if ( !isset( $_GET['sm-drag-drop-location-js'] ) )
return;
$postid = (int) $_GET['sm-drag-drop-location-js'];
$drag_drop_lat = get_post_meta( $postid, 'location_lat', true ) ? get_post_meta( $postid, 'location_lat', true ) : '40.730885';
$drag_drop_lng = get_post_meta( $postid, 'location_lng', true ) ? get_post_meta( $postid, 'location_lng', true ) : '-73.997383';
$drag_drop_zoom = ( $drag_drop_lat == '40.730885' ) ? 2 : 17;
header( "Content-type: application/x-javascript" );
/*
if ( '' == $options['api_key'] ) {
die( "alert( '" . esc_js( __( "You will need to enter your API key in general options before your addresses will be coded properly.", 'SimpleMap' ) ) . "');" );
}
*/
?>
var map;
var geocoder;
var address;
var marker;
var place;
function location_add_edit_js_init() {
var latlng = new google.maps.LatLng( <?php echo esc_js( $drag_drop_lat ); ?>, <?php echo esc_js( $drag_drop_lng ); ?> );
var myOptions = {
zoom: <?php echo esc_js( $drag_drop_zoom ); ?>,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map( document.getElementById( "dragdrop_map_canvas" ), myOptions );
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: true,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener( map, 'click', dragDropGetAddress );
google.maps.event.addListener( marker, 'dragend', dragDropGetAddressTest );
geocoder = new google.maps.Geocoder();
<?php
// If PHP Geocode failed, do the ajax update
if ( $sm_js_update = get_post_meta( $postid, 'sm-needs-js-geocode', true ) ) {
$location_address_data = get_post_custom( $postid );
?>
jQuery( '#js-geo-encode-msg' ).removeClass( 'hidden' );
// Do geocode
var geo_address = '<?php echo esc_js( $location_address_data['location_address'][0] . ' ' . $location_address_data['location_city'][0] . ' ' . $location_address_data['location_state'][0] . ' ' . $location_address_data['location_zip'][0] . ' ' . $location_address_data['location_country'][0] ); ?>';
geocoder.geocode( { 'address': geo_address }, function( results, status ) {
if ( status == google.maps.GeocoderStatus.OK ) {
var latlng = results[0].geometry.location;
jQuery( "#location_lat" ).attr( 'value', latlng.lat() );
jQuery( "#location_lng" ).attr( 'value', latlng.lng() );
var smdata = {
action: 'ajax_save_lat_lng',
sm_id: <?php echo esc_js( $postid ); ?>,
sm_lat: latlng.lat(),
sm_lng: latlng.lng()
};
jQuery.post( ajaxurl, smdata, function( response ) {
jQuery( '#sm_js_update_lat_lng_result' ).html( response );
});
// Set drag/drop map to new location
map.setCenter( latlng );
map.setZoom( <?php echo esc_js( $drag_drop_zoom ); ?> );
marker = new google.maps.Marker({
map: map,
position: latlng,
draggable: true,
animation: google.maps.Animation.DROP
});
jQuery( '#js-geo-encode-msg' ).removeClass( 'hidden' );
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
<?php
delete_post_meta( $postid, 'sm-needs-js-geocode' );
}
?>
}
function dragDropGetAddressTest() {
var latlng = marker.getPosition();
geocoder.geocode( { 'latLng': latlng }, dragDropShowAddress );
}
function dragDropGetAddress( event ) {
if ( event.latlng != null ) {
geocoder.geocode( { 'latLng': event.latlng }, dragDropShowAddress );
}
}
function dragDropShowAddress( results, status ) {
marker.setMap(null);
if ( status != google.maps.GeocoderStatus.OK ) {
alert("Geocoder failed due to: " + status);
map.addOverlay(marker);
} else {
var latlng = results[0].geometry.location;
marker = new google.maps.Marker({
map: map,
position: latlng,
draggable: true,
animation: google.maps.Animation.DROP
});
dragDropUpdateFormFields( latlng );
place = results[0];
google.maps.event.addListener( marker, 'dragend', dragDropGetAddressTest );
}
}
jQuery(document).ready(function(){
location_add_edit_js_init();
});
function dragDropUpdateFormFields( latlng ) {
jQuery( "#location_lat" ).attr( 'value', latlng.lat() );
jQuery( "#location_lng" ).attr( 'value', latlng.lng() );
jQuery( "#latlng_dontforget" ).hide();
jQuery( "#latlng_updated" ).fadeIn();
}
function dragDropUpdateAddress() {
var newAddress = {};
for ( var i = 0; i < place.address_components.length; i++ ) {
var component = place.address_components[i];
newAddress[component.types[0]] = component.short_name;
}
var newStreet = '';
var newCity = '';
var newState = '';
var newZip = '';
var newCountry = '';
if ( newAddress.street_number ) {
newStreet += newAddress.street_number;
}
if ( newAddress.route ) {
if ( newStreet != '' ) {
newStreet += ' ';
}
newStreet += newAddress.route;
}
if ( newAddress.locality ) {
newCity += newAddress.locality;
}
if ( newAddress.administrative_area_level_1 ) {
newState += newAddress.administrative_area_level_1;
}
if ( newAddress.postal_code ) {
newZip += newAddress.postal_code;
}
if ( newAddress.country ) {
newCountry += newAddress.country;
}
/*
if ( place.AddressDetails.Country.AdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare != null )
newStreet = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
else if ( place.AddressDetails.Country.AdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.Locality != null && place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare != null )
newStreet = place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
if ( place.AddressDetails.Country.AdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName != null )
newCity = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
else if ( place.AddressDetails.Country.AdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.Locality != null && place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName != null )
newCity = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
if ( place.AddressDetails.Country.AdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName != null )
newState = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
if ( place.AddressDetails.Country.AdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber != null )
newZip = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
if ( place.AddressDetails.Country.AdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.Locality != null && place.AddressDetails.Country.AdministrativeArea.Locality.PostalCode != null && place.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber != null )
newZip = place.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
if ( place.AddressDetails.Country != null && place.AddressDetails.Country.CountryNameCode != null )
newCountry = place.AddressDetails.Country.CountryNameCode;
oldStreet = jQuery("#location_address").attr( 'value' );
oldCity = jQuery("#location_address").attr( 'value' );
oldState = jQuery("#location_address").attr( 'value' );
oldZip = jQuery("#location_address").attr( 'value' );
oldCountry = jQuery("#location_address").attr( 'value' );
*/
jQuery("#location_address").attr( 'value', newStreet );
jQuery("#location_city").attr( 'value', newCity );
jQuery("#location_state").attr( 'value', newState );
jQuery("#location_zip").attr( 'value', newZip );
jQuery("#location_country").val( newCountry );
}
<?php
die();
}
// This function saves the geo data as well as the additional info
function save_post_meta( $post ) {
global $simple_map, $current_screen;
// Bail if we're not editing a location
if ( ! is_object( $current_screen ) || 'sm-location' != $current_screen->id || 'sm-location' != $current_screen->post_type )
return;
$options = $simple_map->get_options();
$post_object = get_post( $post );
//$api_key = ( isset( $options['api_key'] ) && !empty( $options['api_key'] ) ) ? $options['api_key'] : '';
// Grab old data
$location_address = get_post_meta( $post, 'location_address', true ) ? get_post_meta( $post, 'location_address', true ) : ' ';
$location_address2 = get_post_meta( $post, 'location_address2', true ) ? get_post_meta( $post, 'location_address2', true ) : ' ';
$location_city = get_post_meta( $post, 'location_city', true ) ? get_post_meta( $post, 'location_city', true ) : ' ';
$location_state = get_post_meta( $post, 'location_state', true ) ? get_post_meta( $post, 'location_state', true ) : $options['default_state'];
$location_zip = get_post_meta( $post, 'location_zip', true ) ? get_post_meta( $post, 'location_zip', true ) : ' ';
$location_country = get_post_meta( $post, 'location_country', true ) ? get_post_meta( $post, 'location_country', true ) : $options['default_country'];
$location_lat = get_post_meta( $post, 'location_lat', true ) ? get_post_meta( $post, 'location_lat', true ) : ' ';
$location_lng = get_post_meta( $post, 'location_lng', true ) ? get_post_meta( $post, 'location_lng', true ) : ' ';
$location_phone = get_post_meta( $post, 'location_phone', true ) ? get_post_meta( $post, 'location_phone', true ) : ' ';
$location_fax = get_post_meta( $post, 'location_fax', true ) ? get_post_meta( $post, 'location_fax', true ) : ' ';
$location_url = get_post_meta( $post, 'location_url', true ) ? get_post_meta( $post, 'location_url', true ) : ' ';
$location_email = get_post_meta( $post, 'location_email', true ) ? get_post_meta( $post, 'location_email', true ) : ' ';
$location_special = get_post_meta( $post, 'location_special', true ) ? get_post_meta( $post, 'location_special', true ) : ' ';
// If adding new field that has a default (like state and country above), you must modify the update section below accordingly!
// Grab new data
$new_address = isset( $_POST['location_address'] ) ? $_POST['location_address'] : '';
$new_address2 = isset( $_POST['location_address2'] ) ? $_POST['location_address2'] : '';
$new_city = isset( $_POST['location_city'] ) ? $_POST['location_city'] : '';
$new_state = isset( $_POST['location_state'] ) ? $_POST['location_state'] : '';
$new_zip = isset( $_POST['location_zip'] ) ? $_POST['location_zip'] : '';
$new_country = isset( $_POST['location_country'] ) ? $_POST['location_country'] : '';
$new_lat = isset( $_POST['location_lat'] ) ? $_POST['location_lat'] : '';
$new_lng = isset( $_POST['location_lng'] ) ? $_POST['location_lng'] : '';
$new_phone = isset( $_POST['location_phone'] ) ? $_POST['location_phone'] : '';
$new_fax = isset( $_POST['location_fax'] ) ? $_POST['location_fax'] : '';
$new_url = isset( $_POST['location_url'] ) ? $_POST['location_url'] : '';
$new_email = isset( $_POST['location_email'] ) ? $_POST['location_email'] : '';
$new_special = isset( $_POST['location_special'] ) ? $_POST['location_special'] : '';
// Update
if ( $location_address != $new_address ) update_post_meta( $post, 'location_address', $new_address );
if ( $location_address2 != $new_address2 ) update_post_meta( $post, 'location_address2', $new_address2 );
if ( $location_city != $new_city ) update_post_meta( $post, 'location_city', $new_city );
if ( $location_state != $new_state || ( $new_state == $options['default_state'] && ! get_post_meta( $post, 'location_state', true ) ) ) update_post_meta( $post, 'location_state', $new_state );
if ( $location_zip != $new_zip ) update_post_meta( $post, 'location_zip', $new_zip );
if ( $location_country != $new_country || ( $new_country == $options['default_country'] && ! get_post_meta( $post, 'location_country', true ) ) ) update_post_meta( $post, 'location_country', $new_country );
if ( $location_lat != $new_lat ) update_post_meta( $post, 'location_lat', $new_lat );
if ( $location_lng != $new_lng ) update_post_meta( $post, 'location_lng', $new_lng );
if ( $location_phone != $new_phone ) update_post_meta( $post, 'location_phone', $new_phone );
if ( $location_fax != $new_fax ) update_post_meta( $post, 'location_fax', $new_fax );
if ( $location_url != $new_url ) update_post_meta( $post, 'location_url', $new_url );
if ( $location_email != $new_email ) update_post_meta( $post, 'location_email', $new_email );
if ( $location_special != $new_special ) update_post_meta( $post, 'location_special', $new_special );
// Lets not geocode on auto-draft
if ( 'auto-draft' == $post_object->post_status )
return;
/*
* Geocode here under the following conditions
* If address, city, state, or zip have changed
* If lat or lng is empty
*/
$updated_address = get_post_meta( $post, 'location_address', true );
$updated_city = get_post_meta( $post, 'location_city', true );
$updated_state = get_post_meta( $post, 'location_state', true );
$updated_zip = get_post_meta( $post, 'location_zip', true );
$updated_country = get_post_meta( $post, 'location_country', true );
$updated_lat = get_post_meta( $post, 'location_lat', true );
$updated_lng = get_post_meta( $post, 'location_lng', true );
if ( $location_address != $updated_address || $location_city != $updated_city || $location_state != $updated_state || $location_zip != $updated_zip || $location_country != $updated_country || '' == $updated_lat || '' == $updated_lng ) {
$geocode_result = $simple_map->geocode_location( $updated_address, $updated_city, $updated_state, $updated_zip, $updated_country, '' );
if ( $geocode_result && isset( $geocode_result['status'] ) && $geocode_result['status'] == 'OK' ) {
if ( isset( $geocode_result['lat'] ) && isset( $geocode_result['lng'] ) ) {
update_post_meta( $post, 'location_lat', $geocode_result['lat'] );
update_post_meta( $post, 'location_lng', $geocode_result['lng'] );
}
} else if ( $geocode_result && isset( $geocode_result['status'] ) ) {
// Parse response
switch( $geocode_result['status'] ) {
case 620 :
case 'OVER_QUERY_LIMIT' :
update_post_meta( $post, 'sm-needs-js-geocode', 'true' );
}
}
}
}
// Filter the main query run at top of edit.php
function limit_edit_query( $query ) {
global $current_screen, $wpdb;
if ( is_object( $current_screen ) && 'edit-sm-location' == $current_screen->id ) {
$sql = 'SELECT ID FROM `' . $wpdb->posts . '` WHERE post_type = "sm-location" AND post_status = "publish" LIMIT 10000';
if ( 10000 == count( $wpdb->get_results( $sql ) ) ) {
$query->query_vars['posts_per_page'] = $query->query_vars['posts_per_archive_page'] = 1000;
add_action( 'in_admin_footer', array( &$this, 'print_excessive_locations_message' ) );
}
}
return $query;
}
// Prints the excessive locations message
function print_excessive_locations_message() {
?>
<div id="message" class="error"><p><?php _e( '<strong>Warning</strong>: You have more than 10,000 locations in your database. We have limited the list here to 1,000. You may <strong>use the search field to access locations beyond the first 1,000</strong>.', 'SimpleMap' ); ?></p></div>
<?php
}
// Saves lat / lng data via ajax
function ajax_save_lat_lng() {
// If we're missing a var, return false
if ( empty( $_POST['sm_lat'] ) || empty( $_POST['sm_lng'] ) || empty( $_POST['sm_id'] ) )
die( __( "It doesn't look like that worked either. Please try again later.", "SimpleMap" ) );
// Save original lat for roleback if lng update fails
$orig_lat = get_post_meta( absint( $_POST['sm_id'] ), 'location_lat', esc_attr( $_POST['sm_lat'], true ) );
// Update or return false
if ( ! update_post_meta( absint( $_POST['sm_id'] ), 'location_lat', esc_attr( $_POST['sm_lat'] ) ) )
die( __( "It doesn't look like that worked either. Please try again later.", "SimpleMap" ) );
if ( ! update_post_meta( absint( $_POST['sm_id'] ), 'location_lng', esc_attr( $_POST['sm_lng'] ) ) ) {
update_post_meta( absint( $_POST['sm_id'] ), 'location_lat', esc_attr( $orig_lat ) );
die( __( "It doesn't look like that worked either. Please try again later.", "SimpleMap" ) );
}
// If we made it here, we're golden
die( __( "It looks like that worked!", "SimpleMap" ) );
}
// Filter get page dropdown if we have excessive locations
function limit_wp_dropdown_pages( $args ) {
global $current_screen;
if ( is_object( $current_screen ) && 'edit-sm-location' == $current_screen->id )
$args['include'] = 'This always returns an empty record set.';
return $args;
}
// Related to limit_wp_dropdown_pages. Now fill in what I erased above with fake data
function modify_empty_wp_dropdown_pages( $output ) {
global $current_screen;
if ( is_object( $current_screen ) && 'edit-sm-location' == $current_screen->id )
$output = "<select ide='post_parent' name='post_parent'><option value='0'>" . __( 'Main Page (no parent)' ) . "</option></select>";
return $output;
}
// Flushes location cached data
function flush_cache_data( $id=0 ) {
if ( 'sm-location' == get_post_type( $id ) || 'force' == $id )
delete_transient( 'simplemap-queries-cache' );
}
}
}
?>

279
classes/maps.php Normal file
View File

@@ -0,0 +1,279 @@
<?php
/**
* This file creates maps for us. We're all about generating some maps.
*/
/**
* SM_Map_Factory Class
*
* Handles all our map making duties (well it will be taking over shortly anyway).
*
* @since 2.4
*/
if ( ! class_exists( 'SM_Map_Factory' ) ) {
class SM_Map_Factory {
/**
* Map attributes
*/
var $map_atts;
/**
* Locations - An array of location data that we are adding to the map.
*/
var $locations;
/**
* Inits the templating system. Don't init class prior to template_redirect hook
*
* @since 2.4
*/
function __construct() {
// Lets load the map with some defaults. This should be overwritten by calling the method directly
$this->set_map_atts();
// Prints the iframe
if ( isset( $_GET['sm_map_iframe'] ) ) {
add_action( 'template_redirect', array( &$this, 'add_iframe_locations' ), 2 );
add_action( 'template_redirect', array( &$this, 'generate_iframe' ) );
}
}
/**
* This loads all the attributes for the map itself
*
* 'map_width'
* 'map_height'
* 'default_lat'
* 'default_lng'
* 'zoom_level'
* 'default_radius'
* 'map_type'
* 'special_text'
* 'default_state'
* 'default_country'
* 'default_language'
* 'default_domain'
* 'map_stylesheet'
* 'units'
* 'autoload'
* 'lock_default_location'
* 'results_limit'
* 'address_format'
* 'powered_by'
* 'enable_permalinks'
* 'permalink_slug'
* 'display_search'
* 'map_pages'
* 'adsense_for_maps'
* 'adsense_pub_id'
* 'adsense_channel_id'
* 'adsense_max_ads'
*
* @since 2.4
*/
function set_map_atts( $atts=array() ) {
global $simple_map;
$locations = ! empty ( $_GET['location_ids'] ) ? explode( ',', $_GET['location_ids'] ) : array();
// Do atts for iframes
if ( isset( $_GET['sm_map_iframe'] ) ) {
// Set atts from GET vars
if ( ! empty( $_GET['map_width'] ) )
$atts['map_width'] = $_GET['map_width'];
if ( ! empty( $_GET['map_height'] ) )
$atts['map_height'] = $_GET['map_height'];
if ( ! empty( $_GET['pan_control'] ) )
$atts['panControl'] = $_GET['pan_control'];
if ( ! empty( $_GET['zoom_control'] ) )
$atts['zoomControl'] = $_GET['zoom_control'];
if ( ! empty( $_GET['scale_control'] ) )
$atts['scaleControl'] = $_GET['scale_control'];
if ( ! empty( $_GET['street_view_control'] ) )
$atts['streetViewControl'] = $_GET['street_view_control'];
if ( ! empty( $_GET['map_type_control'] ) )
$atts['mapTypeControl'] = $_GET['map_type_control'];
if ( ! empty( $_GET['map_type'] ) )
$atts['mapType'] = $_GET['map_type'];
if ( empty( $_GET['default_lat'] ) )
$atts['default_lat'] = get_post_meta( $locations[0], 'location_lat', true );
if ( empty( $_GET['default_lng'] ) )
$atts['default_lng'] = get_post_meta( $locations[0], 'location_lng', true );
if ( empty( $_GET['zoom_level'] ) )
$atts['zoom_level'] = 15;
}
// Default Options
$defaults = $simple_map->get_options();
// Overwrite defaults with any vars passed in
$merged_atts = wp_parse_args( $atts, $defaults );
// Kick back to property
$this->map_atts = $merged_atts;
}
/**
* Adds a location to the map
*
* @since 2.4
*/
function add_location( $location ) {
// $location can be a post object or a post ID. If its an object, grab the id
if ( is_object( $location ) )
$location = $location->ID;
// Build array of important post data
if ( $location_data = get_metadata( 'post', $location ) ) {
$location_array = array(
'id' => $location,
'lat' => ! empty( $location_data['location_lat'][0] ) ? $location_data['location_lat'][0] : false,
'lng' => ! empty( $location_data['location_lng'][0] ) ? $location_data['location_lng'][0] : false
);
if ( $location_array['lat'] && $location_array['lng'] )
$this->locations[$location] = $location_array;
}
}
/**
* A wrapper for add_location for use when loading an iframe
*
* @since 2.4
*/
function add_iframe_locations() {
// Add locations from GET string in iframe embed
$locations = ! empty ( $_GET['location_ids'] ) ? explode( ',', $_GET['location_ids'] ) : array();
foreach( $locations as $location ) {
$this->add_location( $location );
}
}
/**
* Returns the map code
*
* @since 2.4
*/
function get_map() {
}
/**
* Returns the link for the iframe embed
*
* @since 2.4
*/
function get_iframe_embed() {
$atts = $this->map_atts;
$locations = array_keys( $this->locations );
$iframe = '<iframe width="' . $atts['map_width'] . '" height="' . $atts['map_height'] . '" frameborder=0 scrolling="no" src="' . esc_url( site_url() ) . '?sm_map_iframe=1&map_width=' . esc_attr( $atts['map_width'] ) . '&map_height=' . esc_attr( $atts['map_height'] ) . '&location_ids=' . esc_attr( implode( ',', $locations ) ) . '"></iframe>';
return $iframe;
}
/**
* Generates the actual iframe
*
* @since 1.0
*/
function generate_iframe() {
if ( ! empty( $_GET['sm_map_iframe'] ) ) {
global $simple_map;
$this->set_map_atts();
$atts = $this->map_atts;
wp_enqueue_script('jquery');
?>
<html style='margin-top:0 !important;padding-top:0 !important;'>
<head>
<?php wp_head(); ?>
<style type='text/css'>* { margin:0; padding:0; }</style>
<script src="<?php echo esc_url( SIMPLEMAP_MAPS_JS_API . '?v=3&amp;sensor=false&amp;language=' . $atts['default_language'] . '&amp;region=' . $atts['default_country'] ); ?>" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
var map = null;
var geocoder = null;
var latlng = new google.maps.LatLng( '<?php echo esc_js( $atts['default_lat'] ) ;?>', '<?php echo esc_js( $atts['default_lng'] ); ?>' );
function initialize() {
var myOptions = {
zoom: parseInt(<?php echo esc_js( $atts['zoom_level'] ); ?>),
center: latlng,
panControl: <?php echo ($atts['panControl']) ? 'true' : 'false'; ?>,
zoomControl: <?php echo ($atts['zoomControl']) ? 'true' : 'false'; ?>,
scaleControl: <?php echo ($atts['scaleControl']) ? 'true' : 'false'; ?>,
streetViewControl: <?php echo ($atts['streetViewControl']) ? 'true' : 'false'; ?>,
mapTypeControl: <?php echo ($atts['mapTypeControl']) ? 'true' : 'false'; ?>,
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggable: false
};
map = new google.maps.Map( document.getElementById( "map_canvas" ), myOptions );
geocoder = new google.maps.Geocoder();
}
function addMapMarkers() {
var markersArray = [];
<?php foreach( $this->locations as $location ) { ?>
<?php $customvals = get_metadata( 'post', $location['id'] ); ?>
var name = '<?php echo esc_js( get_the_title( $location['id'] ) ); ?>';
var address = '<?php echo esc_js( $customvals['location_address'][0] ); ?>';
var address2 = '<?php echo esc_js( $customvals['location_address2'][0] ); ?>';
var city = '<?php echo esc_js( $customvals['location_city'][0] ); ?>';
var state = '<?php echo esc_js( $customvals['location_state'][0] ); ?>';
var zip = '<?php echo esc_js( $customvals['location_zip'][0] ); ?>';
var country = '<?php echo esc_js( $customvals['location_country'][0] ); ?>';
var email = '<?php echo esc_js( $customvals['location_email'][0] ); ?>';
var url = '<?php echo esc_js( $customvals['location_url'][0] ); ?>';
var phone = '<?php echo esc_js( $customvals['location_phone'][0] ); ?>';
var fax = '<?php echo esc_js( $customvals['location_fax'][0] ); ?>';
var special = '<?php echo esc_js( $customvals['location_special'][0] ); ?>';
map.setCenter(latlng, 13);
var markerOptions = {};
if ( 'function' == typeof window.simplemapCustomMarkers ) {
markerOptions = simplemapCustomMarkers( name, address, address2, city, state, zip, country, '', url, phone, fax, email, special, '', '', '');
}
markerOptions.map = map;
markerOptions.position = new google.maps.LatLng( '<?php echo esc_js( $location['lat'] ) ;?>', '<?php echo esc_js( $location['lng'] ); ?>' );
var marker = new google.maps.Marker( markerOptions );
markersArray.push(marker);
<?php } ?>
}
jQuery(document).ready( function() { initialize(); addMapMarkers(); } );
</script>
<div id="map_canvas" style="height: <?php echo esc_attr( $_GET['map_height'] ); ?>; width: <?php echo esc_attr( $_GET['map_width'] ); ?>; border: 1px solid #eee; overflow: hidden"></div>
</body>
</html>
<?php
die();
}
}
}
}

755
classes/options-general.php Normal file
View File

@@ -0,0 +1,755 @@
<?php
if ( !class_exists( 'SM_Options' ) ) {
class SM_Options{
// update options of form submission
function sm_options() {
add_action( 'admin_init', array( &$this, 'update_options' ) );
}
// Processes Options form if loaded
function update_options() {
global $simple_map, $sm_locations;
// Delete all SimpleMap data.
if ( isset( $_GET['sm-action'] ) && 'delete-simplemap' == $_GET['sm-action'] ) {
// Confirm we have both permisssion to do this and we have intent to do this.
if ( current_user_can( 'manage_options' ) && ( check_admin_referer( 'delete-simplemap-locations' ) || check_admin_referer( 'delete-simplemap' ) ) ) {
// Delete locations
while ( $locations = query_posts( array( 'post_type' => 'sm-location', 'posts_per_page' => 200 ) ) ) {
// Delete posts (and therby postmeta as well). Second arg bypasses trash
foreach ( $locations as $key => $location ) {
set_time_limit( 20 );
wp_delete_post( $location->ID, true );
}
}
$options = $simple_map->get_options();
$taxonomies = $options['taxonomies'];
$original_taxonomies = array_keys( $simple_map->get_taxonomy_settings() );
if ( is_array( $original_taxonomies ) ) {
foreach ( $original_taxonomies as $taxonomy ) {
$taxonomies[$taxonomy] = true;
if ( ! taxonomy_exists( $taxonomy ) ) {
$sm_locations->register_location_taxonomy( $taxonomy, array() );
}
}
}
// Delete taxonomy terms
$args = array( 'hide_empty' => 0 );
if ( $terms = get_terms( array_keys( $taxonomies ), $args ) ) {
foreach ( $terms as $key => $term ) {
wp_delete_term( $term->term_id, $term->taxonomy );
}
}
// Delete Options
if ( get_option( 'SimpleMap_options' ) && empty( $_GET['locations-only'] ) ) {
delete_option( 'SimpleMap_options' );
}
do_action( 'sm-delete-all-data' );
wp_safe_redirect( admin_url( 'admin.php?page=simplemap' ) );
}
}
$options = $simple_map->get_options();
// Update Options if form was submitted or if WordPress options doesn't exist yet.
if ( isset( $_POST['sm_general_options_submitted'] ) ) {
check_admin_referer( 'sm-general-options' );
$new_options = $options;
// Validate POST Options
//$new_options['api_key'] = ( ! empty( $_POST['api_key'] ) ) ? $_POST['api_key'] : '';
$new_options['map_width'] = ( ! empty( $_POST['map_width'] ) ) ? $_POST['map_width'] : $options['map_width'];
$new_options['map_height'] = ( ! empty( $_POST['map_height'] ) ) ? $_POST['map_height'] : $options['map_height'];
$new_options['default_lat'] = ( ! empty( $_POST['default_lat'] ) ) ? $_POST['default_lat'] : $options['default_lat'] ;
$new_options['default_lng'] = ( ! empty( $_POST['default_lng'] ) ) ? $_POST['default_lng'] : $options['default_lng'] ;
$new_options['zoom_level'] = ( isset( $_POST['zoom_level'] ) ) ? absint( $_POST['zoom_level'] ) : $options['zoom_level'] ;
$new_options['default_radius'] = ( ! empty( $_POST['default_radius'] ) ) ? absint( $_POST['default_radius'] ) : $options['default_radius'] ;
$new_options['map_type'] = ( ! empty( $_POST['map_type'] ) ) ? $_POST['map_type'] : $options['map_type'];
$new_options['special_text'] = ( isset( $_POST['special_text'] ) ) ? $_POST['special_text'] : $options['special_text'];
$new_options['default_state'] = ( ! empty( $_POST['default_state'] ) ) ? $_POST['default_state'] : $options['default_state'];
$new_options['default_country'] = ( ! empty( $_POST['default_country'] ) ) ? esc_attr( $_POST['default_country'] ) : $options['default_country'];
$new_options['default_language'] = ( ! empty( $_POST['default_language'] ) ) ? esc_attr( $_POST['default_language'] ) : $options['default_language'];
$new_options['default_domain'] = ( ! empty( $_POST['default_domain'] ) ) ? $_POST['default_domain'] : $options['default_domain'];
$new_options['address_format'] = ( ! empty( $_POST['address_format'] ) ) ? $_POST['address_format'] : $options['address_format'];
$new_options['map_stylesheet'] = ( ! empty( $_POST['map_stylesheet'] ) ) ? $_POST['map_stylesheet'] : $options['map_stylesheet'];
$new_options['units'] = ( ! empty( $_POST['units'] ) ) ? $_POST['units'] : $options['units'];
$new_options['results_limit'] = ( isset( $_POST['results_limit'] ) ) ? absint( $_POST['results_limit'] ) : $options['results_limit'];
$new_options['autoload'] = ( ! empty( $_POST['autoload'] ) ) ? $_POST['autoload'] : $options['autoload'];
$new_options['map_pages'] = ( isset( $_POST['map_pages'] ) ) ? $_POST['map_pages'] : $options['map_pages'];
$new_options['lock_default_location'] = ( ! empty( $_POST['lock_default_location'] ) ) ? true : $options['lock_default_location'];
$new_options['powered_by'] = ( isset( $_POST['powered_by'] ) && 'on' == $_POST['powered_by'] ) ? 1 : 0;
$new_options['enable_permalinks'] = ( isset( $_POST['enable_permalinks'] ) && 'on' == $_POST['enable_permalinks'] ) ? 1 : 0;
$new_options['permalink_slug'] = ( ! empty( $_POST['permalink_slug'] ) ) ? $_POST['permalink_slug'] : $options['permalink_slug'];
$new_options['adsense_for_maps'] = ( isset( $_POST['adsense_for_maps'] ) && 'on' == $_POST['adsense_for_maps'] ) ? 1 : 0;
$new_options['adsense_pub_id'] = ( isset( $_POST['adsense_pub_id'] ) ) ? $_POST['adsense_pub_id'] : $options['adsense_pub_id'];
$new_options['adsense_channel_id'] = ( isset( $_POST['adsense_channel_id'] ) ) ? $_POST['adsense_channel_id'] : $options['adsense_channel_id'];
$new_options['adsense_max_ads'] = ( isset( $_POST['adsense_max_ads'] ) ) ? absint( $_POST['adsense_max_ads'] ) : $options['adsense_max_ads'];
$new_options['display_search'] = ( ! empty( $_POST['display_search'] ) ) ? $_POST['display_search'] : $options['display_search'];
$new_options['auto_locate'] = ( isset( $_POST['auto_locate'] ) ) ? $_POST['auto_locate'] : $options['auto_locate'];
foreach ( $new_options['taxonomies'] as $taxonomy => $tax_info ) {
if ( isset( $_POST['taxonomies'][$taxonomy]['active'] ) ) {
$new_tax_options = $_POST['taxonomies'][$taxonomy];
unset($new_tax_options['active']);
//echo 'UPDATE(' . $taxonomy . ' - ' . json_encode( array_diff_assoc( array_filter( $new_tax_options ), $tax_info ) ) . ')' . PHP_EOL;
$new_options['taxonomies'][$taxonomy] = array_filter( $new_tax_options ) + $tax_info;
unset($_POST['taxonomies'][$taxonomy]);
}
else {
//echo 'DISABLE(' . $taxonomy . ')' . PHP_EOL;
unset($new_options['taxonomies'][$taxonomy]);
}
}
if ( isset( $_POST['taxonomies'] ) ) {
foreach ( $_POST['taxonomies'] as $taxonomy => $tax_info ) {
if ( isset( $tax_info['active'] ) ) {
//echo 'ENABLE(' . $taxonomy . ')' . PHP_EOL;
$new_options['taxonomies'][$taxonomy] = $simple_map->get_taxonomy_settings( $taxonomy );
}
}
}
$new_options = apply_filters( 'sm-new-general-options', $new_options, $options );
if ( $new_options !== $options && update_option( 'SimpleMap_options', $new_options ) ) {
if ( $new_options['enable_permalinks'] !== $options['enable_permalinks'] || $new_options['permalink_slug'] !== $options['permalink_slug'] ) {
update_option( 'sm-rewrite-rules', true );
}
do_action( 'sm-general-options-updated' );
wp_redirect( admin_url( 'admin.php?page=simplemap&sm-msg=1' ) );
die();
}
}
}
// Prints the options page
function print_page(){
global $simple_map, $wpdb;
$options = $simple_map->get_options();
extract( $options );
// Set Autoload Vars
$count = $wpdb->get_col( "SELECT COUNT(ID) FROM `" . $wpdb->posts . "` WHERE post_type = 'sm-location' AND post_status = 'publish'" );
if ( $count >= 250 ) {
$disabled_autoload = false; // let it happen. we're limiting to 500 in the query
$disabledmsg = sprintf( __( 'You have to many locations to auto-load them all. Only the closest %d will be displayed if auto-load all is selected.', 'SimpleMap' ), '250' );
} else {
$disabled_autoload = false;
$disabledmsg = '';
}
// Extract styles
$themes1 = $themes2 = array();
if ( file_exists( SIMPLEMAP_PATH . '/inc/styles' ) )
$themes1 = $this->read_styles( SIMPLEMAP_PATH . '/inc/styles' );
if ( file_exists( WP_PLUGIN_DIR . '/simplemap-styles' ) )
$themes2 = $this->read_styles( WP_PLUGIN_DIR . '/simplemap-styles' );
$themes1 = apply_filters( 'sm-general-options-themes1', $themes1 );
$themes2 = apply_filters( 'sm-general-options-themes1', $themes2 );
?>
<div class="wrap">
<?php
// Title
$sm_page_title = apply_filters( 'sm-general-options-page-title', 'SimpleMap: General Options' );
// Toolbar
$simple_map->show_toolbar( $sm_page_title );
// Messages
if ( isset( $_GET['sm-msg'] ) && '1' == $_GET['sm-msg'] )
echo '<div class="updated fade"><p>'.__('SimpleMap settings saved.', 'SimpleMap').'</p></div>';
?>
<div id="dashboard-widgets-wrap" class="clear">
<form method="post" action="">
<input type="hidden" name="sm_general_options_submitted" value="1" />
<?php wp_nonce_field( 'sm-general-options' ); ?>
<?php do_action( 'sm-general-options-page-top' ); ?>
<div id='dashboard-widgets' class='metabox-holder'>
<?php do_action( 'sm-general-options-dash-widgets-top' ); ?>
<div class='postbox-container' style='width:49%;'>
<div id='normal-sortables' class='meta-box-sortables ui-sortable'>
<?php do_action( 'sm-general-options-normal-sortables-top' ); ?>
<div class="postbox">
<h3><?php _e( 'Location Defaults', 'SimpleMap' ); ?></h3>
<div class="inside">
<p class="sub"><?php _e( 'If most of your locations are in the same area, choose the country and state/province here to make adding new locations easier.', 'SimpleMap' ); ?></p>
<div class="table">
<table class="form-table">
<tr valign="top">
<td width="150"><label for="default_domain"><?php _e( 'Google Maps Domain', 'SimpleMap' ); ?></label></td>
<td>
<select name="default_domain" id="default_domain">
<?php
foreach ( $simple_map->get_domain_options() as $key => $value ) {
echo "<option value='" . $value . "' " . selected( $default_domain, $value, false ) . ">" . $key . " (" . $value . ")</option>\n";
}
?>
</select>
</td>
</tr>
<tr valign="top">
<td width="150"><label for="default_country"><?php _e( 'Default Country', 'SimpleMap' ); ?></label></td>
<td>
<select name="default_country" id="default_country">
<?php
foreach ( $simple_map->get_country_options() as $key => $value ) {
echo "<option value='" . $key . "' " . selected( $default_country, $key, false ) . ">" . $value . "</option>\n";
}
?>
</select>
</td>
</tr>
<tr valign="top">
<td width="150"><label for="default_language"><?php _e( 'Default Language', 'SimpleMap' ); ?></label></td>
<td>
<select name="default_language" id="default_language">
<?php
foreach ( $simple_map->get_language_options() as $key => $value ) {
echo "<option value='" . $key . "' " . selected( $default_language, $key, false ) . ">" . $value . "</option>\n";
}
?>
</select>
</td>
</tr>
<tr valign="top">
<td scope="row"><label for="default_state"><?php _e( 'Default State/Province', 'SimpleMap' ); ?></label></td>
<td><input type="text" name="default_state" id="default_state" size="30" value="<?php echo $default_state; ?>" /></td>
</tr>
<tr valign="top">
<td width="150"><label for="address_format"><?php _e( 'Address Format', 'SimpleMap' ); ?></label></td>
<td>
<select id="address_format" name="address_format">
<option value="town, province postalcode" <?php selected( $address_format, 'town, province postalcode' ); ?>><?php echo '[' . __( 'City/Town', 'SimpleMap' ) . '], [' . __( 'State/Province', 'SimpleMap' ) . ']&nbsp;&nbsp;[' . __( 'Zip/Postal Code', 'SimpleMap' ) . ']'; ?></option>
<option value="town province postalcode" <?php selected( $address_format, 'town province postalcode' ); ?>><?php echo '[' . __( 'City/Town', 'SimpleMap' ) . ']&nbsp;&nbsp;[' . __( 'State/Province', 'SimpleMap' ) . ']&nbsp;&nbsp;[' . __( 'Zip/Postal Code', 'SimpleMap' ) . ']'; ?></option>
<option value="town-province postalcode" <?php selected( $address_format, 'town-province postalcode' ); ?>><?php echo '[' . __( 'City/Town', 'SimpleMap' ) . '] - [' . __( 'State/Province', 'SimpleMap' ) . ']&nbsp;&nbsp;[' . __('Zip/Postal Code', 'SimpleMap' ) . ']'; ?></option>
<option value="postalcode town-province" <?php selected( $address_format, 'postalcode town-province' ); ?>><?php echo '[' . __( 'Zip/Postal Code', 'SimpleMap' ) . ']&nbsp;&nbsp;[' . __( 'City/Town', 'SimpleMap' ) . '] - [' . __( 'State/Province', 'SimpleMap' ) . ']'; ?></option>
<option value="postalcode town, province" <?php selected( $address_format, 'postalcode town, province' ); ?>><?php echo '[' . __( 'Zip/Postal Code', 'SimpleMap' ) . ']&nbsp;&nbsp;[' . __( 'City/Town', 'SimpleMap' ) . '], [' . __( 'State/Province', 'SimpleMap' ) . ']'; ?></option>
<option value="postalcode town" <?php selected( $address_format, 'postalcode town' ); ?>><?php echo '[' . __( 'Zip/Postal Code', 'SimpleMap' ) . ']&nbsp;&nbsp;[' . __( 'City/Town', 'SimpleMap' ) . ']'; ?></option>
<option value="town postalcode" <?php selected( $address_format, 'town postalcode' ); ?>><?php echo '[' . __( 'City/Town', 'SimpleMap' ) . ']&nbsp;&nbsp;[' . __( 'Zip/Postal Code', 'SimpleMap' ) . ']'; ?></option>
</select>
<span class="hidden" id="order_1"><br /><?php _e( 'Example', 'SimpleMap' ); ?>: Minneapolis, MN 55403</span>
<span class="hidden" id="order_2"><br /><?php _e( 'Example', 'SimpleMap' ); ?>: Minneapolis MN 55403</span>
<span class="hidden" id="order_3"><br /><?php _e( 'Example', 'SimpleMap' ); ?>: S&atilde;o Paulo - SP 85070</span>
<span class="hidden" id="order_4"><br /><?php _e( 'Example', 'SimpleMap' ); ?>: 85070 S&atilde;o Paulo - SP</span>
<span class="hidden" id="order_5"><br /><?php _e( 'Example', 'SimpleMap' ); ?>: 46800 Puerto Vallarta, JAL</span>
<span class="hidden" id="order_6"><br /><?php _e( 'Example', 'SimpleMap' ); ?>: 126 25&nbsp;&nbsp;Stockholm</span>
<span class="hidden" id="order_7"><br /><?php _e( 'Example', 'SimpleMap' ); ?>: London&nbsp;&nbsp;EC1Y 8SY</span>
</td>
</tr>
</table>
</div> <!-- table -->
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e( 'Save Options', 'SimpleMap' ) ?>" /><br /><br />
</p>
<div class="clear"></div>
</div> <!-- inside -->
</div> <!-- postbox -->
<!-- #### MAP CONFIGURATION #### -->
<div class="postbox">
<h3><?php _e( 'Map Configuration', 'SimpleMap' ); ?></h3>
<div class="inside">
<p class="sub"><?php printf( __( 'See %s the Help page%s for an explanation of these options.', 'SimpleMap' ), '<a href="' . get_bloginfo( 'wpurl' ) . '/wp-admin/admin.php?page=simplemap-help">', '</a>&nbsp;' ); ?></p>
<div class="table">
<table class="form-table">
<?php /*
<tr valign="top">
<td width="150"><label for="api_key"><?php _e( 'Google Maps API Key', 'SimpleMap' ); ?></label></td>
<td>
<input type="text" name="api_key" id="api_key" size="50" value="<?php echo esc_attr( $api_key ); ?>" /><br />
<small><em><?php printf( __( '%s Click here%s to sign up for a Google Maps API key for your domain.', 'SimpleMap' ), '<a href="' . $simple_map->get_api_link() . '">', '</a>'); ?></em></small>
</td>
</tr>
*/ ?>
<tr valign="top">
<?php
if ( TRUE ) {
$disabled_api = false;
$api_how_to = __( 'Type in an address, state, or zip to geocode the default location.', 'SimpleMap' );
} else {
$disabled_api = true;
$api_how_to = __( 'After you enter an API Key, you can type in an address, state, or zip here to geocode the default location.', 'SimpleMap' );
}
?>
<td width="150"><label for="default_lat"><?php _e( 'Starting Location', 'SimpleMap' ); ?></label></td>
<td>
<label for="default_lat" style="display: inline-block; width: 60px;"><?php _e( 'Latitude:', 'SimpleMap' ); ?> </label>
<input type="text" name="default_lat" id="default_lat" size="13" value="<?php echo esc_attr( $default_lat ); ?>" /><br />
<label for="default_lng" style="display: inline-block; width: 60px;"><?php _e( 'Longitude:', 'SimpleMap' ); ?> </label>
<input type="text" name="default_lng" id="default_lng" size="13" value="<?php echo esc_attr( $default_lng ); ?>" />
<p>
<input <?php disabled( $disabled_api ); ?> type="text" name="default_address" id="default_address" size="30" value="" />&nbsp;<a class="button" <?php disabled( $disabled_api ); ?> onclick="codeAddress();return false;" href="#"><?php _e( 'Geocode Address', 'SimpleMap' ); ?></a>
<br /><small><span class='howto'><?php echo $api_how_to; ?></span></small>
</p>
</td>
</tr>
<tr valign="top">
<td><label for="units"><?php _e( 'Distance Units', 'SimpleMap' ); ?></label></td>
<td>
<select name="units" id="units">
<option value="mi" <?php selected( $units, 'mi' ); ?>><?php _e( 'Miles', 'SimpleMap' ); ?></option>
<option value="km" <?php selected( $units, 'km' ); ?>><?php _e( 'Kilometers', 'SimpleMap' ); ?></option>
</select>
</td>
</tr>
<tr valign="top">
<td><label for="default_radius"><?php _e( 'Default Search Radius', 'SimpleMap' ); ?></label></td>
<td>
<select name="default_radius" id="default_radius">
<?php
foreach ( $simple_map->get_search_radii() as $value ) {
echo "<option value='" . esc_attr( $value ) . "' " . selected( $value, $default_radius, false ) . ">" . esc_attr( $value ) . " " . esc_attr( $units ) . "</option>\n";
}
?>
</select>
</td>
</tr>
<tr valign="top">
<td><label for="results_limit"><?php _e( 'Number of Results to Display', 'SimpleMap' ); ?></label></td>
<td>
<select name="results_limit" id="results_limit">
<option value="0" <?php selected( $results_limit, 0 ); ?>>No Limit</option>
<?php
for ( $i = 5; $i <= 50; $i += 5 ) {
echo "<option value='" . esc_attr( $i ) . "' " . selected( $results_limit, $i, false ) . ">" . esc_attr( $i ) . "</option>\n";
}
?>
</select><br />
<small><span class='howto'><?php _e( 'Select "No Limit" to display all results within the search radius.', 'SimpleMap' ); ?></span></small>
</td>
</tr>
<tr valign="top">
<td><label for="autoload"><?php _e( 'Auto-Load Database', 'SimpleMap' ); ?></label></td>
<td>
<select name="autoload" id="autoload">
<option value="none" <?php selected( $autoload, 'none' ); ?>><?php _e( 'No auto-load', 'SimpleMap' ); ?></option>
<option value="some" <?php selected( $autoload, 'some' ); ?>><?php _e('Auto-load search results', 'SimpleMap'); ?></option>
<option value="all" <?php selected( $autoload, 'all' );?> <?php disabled( $disabled_autoload ); ?>><?php _e('Auto-load all locations', 'SimpleMap'); ?></option>
</select>
<br />
<small><em><?php _e( sprintf ( '%sNo auto-load%s shows map without any locations.%s%sAuto-load search results%s displays map based on default values for search form.%s%sAuto-load all%s ignores default search form values and loads all locations.', '<strong>', '</strong>', '<br />', '<strong>', '</strong>', '<br />', '<strong>', '</strong>' ) ); ?></em></small>
<?php if ( $disabledmsg != '' ) { echo '<br /><small style="color:red";><em>' . $disabledmsg . '</small></em>'; } ?>
<!--<br /><label for="lock_default_location" id="lock_default_location_label"><input type="checkbox" name="lock_default_location" id="lock_default_location" value="1" <?php checked( $lock_default_location ); ?> /> <?php _e('Stick to default location set above', 'SimpleMap'); ?></label>-->
</td>
</tr>
<tr valign="top">
<td><label for="zoom_level"><?php _e('Default Zoom Level', 'SimpleMap'); ?></label></td>
<td>
<select name="zoom_level" id="zoom_level">
<option value='0' <?php selected( $zoom_level, 0 ); ?> >Auto Zoom</option>
<?php
for ( $i = 1; $i <= 19; $i++ ) {
echo "<option value='" . esc_attr( $i ) . "' " . selected( $zoom_level, $i, false ) . ">" . esc_attr( $i ) . "</option>\n";
}
?>
</select><br />
<small><em><?php _e( '1 is the most zoomed out (the whole world is visible) and 19 is the most zoomed in.', 'SimpleMap' ); ?></em></small>
</td>
</tr>
<tr valign="top">
<td><label for="special_text"><?php _e( 'Special Location Label', 'SimpleMap' ); ?></label></td>
<td>
<input type="text" name="special_text" id="special_text" size="30" value="<?php echo esc_attr( $special_text ); ?>" />
</td>
</tr>
<tr valign="top">
<td><label for="map_pages"><?php _e( 'Map Page IDs', 'SimpleMap' ); ?></label></td>
<td>
<input type="text" name="map_pages" id="map_pages" size="30" value="<?php echo esc_attr( $map_pages ); ?>" /><br />
<small><em><?php _e( 'Enter the IDs of the pages/posts the map will appear on, separated by commas. The map scripts will only be loaded on those pages. Leave blank or enter 0 to load the scripts on all pages.', 'SimpleMap' ); ?></em></small>
</td>
</tr>
</table>
</div> <!-- table -->
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e( 'Save Options', 'SimpleMap' ) ?>" /><br /><br />
</p>
<div class="clear"></div>
</div> <!-- inside -->
</div> <!-- postbox -->
<!-- Optional Features -->
<div class="postbox">
<h3><?php _e( 'Optional / Experimental Features', 'SimpleMap' ); ?></h3>
<div class="inside">
<p class="sub"><?php printf( __( 'See %s the Help page%s for an explanation of these options.', 'SimpleMap' ), '<a href="' . get_bloginfo( 'wpurl' ) . '/wp-admin/admin.php?page=simplemap-help">', '</a>&nbsp;' ); ?></p>
<div class="table">
<table class="form-table">
<tr valign="top">
<td width="150"><?php _e( 'Permalinks', 'SimpleMap' ); ?></td>
<td>
<label for="enable_permalinks"><input type="checkbox" name="enable_permalinks" id="enable_permalinks" <?php checked( $enable_permalinks ); ?> /> <?php _e( 'Enable location permalinks?', 'SimpleMap' ); ?></label>
<br /><label for="permalink_slug"><small><?php _e( 'Location permalink folder?', 'SimpleMap' ); ?></small> <input type="text" name="permalink_slug" id="permalink_slug" value="<?php echo esc_attr( $permalink_slug ); ?>" /></label>
</td>
</tr>
<tr valign="top">
<td width="150"><?php _e( 'Location Taxonomies', 'SimpleMap' ); ?></td>
<td>
<?php
$standard_taxonomies = $simple_map->get_taxonomy_settings();
$taxonomies += $standard_taxonomies;
foreach ( $taxonomies as $taxonomy => $tax_info ) {
$safe = str_replace( '-', '_', $taxonomy );
$label = isset( $tax_info['description'] ) ? $tax_info['description'] : str_replace( 'sm-', '', $taxonomy );
$active = !empty( $options['taxonomies'][$taxonomy] );
echo '<label for="taxonomies_' . $safe . '"><input type="checkbox" name="taxonomies[' . $taxonomy . '][active]" id="taxonomies_' . $safe . '" ' . checked( $active, true, false ) . ' /> ' . __( 'Enable ' . $label . ' taxonomies?', 'SimpleMap' ) . '</label>';
echo '<br />';
if ( $active && !isset( $standard_taxonomies[$taxonomy] ) ) {
echo '<div style="margin: 5px 0px 5px 15px; padding: 5px; border: 1px solid #ccc;">';
echo '<label for="taxonomies_' . $safe . '_singular">' . __( 'Singular Form', 'SimpleMap' );
echo ': <input type="text" name="taxonomies[' . $taxonomy . '][singular]" id="taxonomies_' . $safe . '_singular" value="' . esc_attr( $tax_info['singular'] ) . '" /></label>';
echo '<br />';
echo '<label for="taxonomies_' . $safe . '_plural">' . __( 'Plural Form', 'SimpleMap' );
echo ': <input type="text" name="taxonomies[' . $taxonomy . '][plural]" id="taxonomies_' . $safe . '_plural" value="' . esc_attr( $tax_info['plural'] ) . '" /></label>';
echo '</div>';
echo '<br />';
}
}
?>
</td>
</tr>
<tr valign="top">
<td width="150"><?php _e( 'Google Adsense for Maps', 'SimpleMap' ); ?></td>
<td>
<label for="adsense_for_maps"><input type="checkbox" name="adsense_for_maps" id="adsense_for_maps" <?php checked( $adsense_for_maps ); ?> /> <?php _e( 'Enable Adense for Maps?', 'SimpleMap' ); ?></label>
<br /><label for="adsense_pub_id"><small><?php _e( 'Default Adsense Publisher ID:', 'SimpleMap' ); ?></small> <input type="text" name="adsense_pub_id" id="adsense_pub_id" size="30" value="<?php echo esc_attr( $adsense_pub_id ); ?>" /></label>
<br /><label for="adsense_channel_id"><small><?php _e( 'Default Adsense Channel ID:', 'SimpleMap' ); ?></small> <input type="text" name="adsense_channel_id" id="adsense_channel_id" size="30" value="<?php echo esc_attr( $adsense_channel_id ); ?>" /></label>
<br /><label for="adsense_max_ads"><small><?php _e( 'Max number of ads on map:', 'SimpleMap' ); ?></small> <input type="text" name="adsense_max_ads" id="adsense_max_ads" size="10" value="<?php echo esc_attr( $adsense_max_ads ); ?>" /></label>
</td>
</tr>
<tr valign="top">
<td><label for="auto_locate"><?php _e( 'Auto-detect Location', 'SimpleMap' ); ?></label></td>
<td>
<select name="auto_locate" id="auto_locate">
<?php
foreach ( $simple_map->get_auto_locate_options() as $value => $label ) {
echo "<option value='" . esc_attr( $value ) . "' " . selected( $value, $auto_locate, false ) . ">" . esc_attr( $label ) . "</option>\n";
}
?>
</select><br />
<small><span class='howto'><?php _e( 'IP based detection does not prompt the user for permission and is faster than HTML5. HTML5 is more precise.' ); ?></span></small>
</td>
</tr>
</table>
</div>
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e( 'Save Options', 'SimpleMap' ) ?>" /><br /><br />
</p>
<div class="clear"></div>
</div>
</div>
<?php do_action( 'sm-general-options-normal-sortables-bottom' ); ?>
</div>
</div>
<div class='postbox-container' style='width:49%;'>
<div id='side-sortables' class='meta-box-sortables ui-sortable'>
<?php do_action( 'sm-general-options-side-sortables-top' ); ?>
<!-- #### PREMIUM SUPPORT #### -->
<div class="postbox" >
<h3 style='color:#fff;text-shadow:0 1px 0 #000;background: #fff url( <?php echo SIMPLEMAP_URL; ?>/inc/images/blue-grad.png ) top left repeat-x;'><?php _e( 'Premium Support and Features', 'SimpleMap' ); ?></h3>
<div class="inside" style='padding: 0pt 10px 10px;' >
<?php
// Check for premium support status
global $simplemap_ps;
if ( ! url_has_ftps_for_item( $simplemap_ps ) ) : ?>
<h4><?php printf( __( 'SimpleMap Premium Support Benefits', 'SimpleMap' ), esc_attr( site_url() ) ); ?></h4>
<p>
<?php printf( __( 'SimpleMap now offers a premium support package for the low cost of %s per year per domain.', 'SimpleMap' ), '$30.00 USD' ); ?>
</p>
<p>
<?php _e( 'By signing up for SimpleMap premium support, you help to ensure future enhancements to this excellent project as well as the following benefits:', 'SimpleMap' ); ?>
</p>
<ul style='margin-left:25px;list-style-type:disc'>
<li><?php _e( 'Around the clock access to our extensive knowledge base and support forum from within your WordPress dashboard', 'SimpleMap' ); ?></li>
<li><?php _e( 'Professional and timely response times to all your questions from the SimpleMap team', 'SimpleMap' ); ?></li>
<li><?php _e( 'A 10% discount for any custom functionality you request from the SimpleMap developers', 'SimpleMap' ); ?></li>
<li><?php _e( 'A 6-12 month advance access to new features integrated into the auto upgrade functionality of WordPress', 'SimpleMap' ); ?></li>
</ul>
<ul style='margin-left:25px;list-style-type:none'>
<li><a href='<?php echo get_ftps_paypal_button( $simplemap_ps ); ?>'><?php _e( 'Signup Now', 'SimpleMap' ); ?></a></li>
<li><a target='_blank' href='<?php echo get_ftps_learn_more_link( $simplemap_ps ); ?>'><?php _e( 'Learn More', 'SimpleMap' ); ?></a></li>
</ul>
<?php else : ?>
<p class='howto'><?php printf( "Your premium support for <code>%s</code> was purchased on <code>%s</code> by <code>%s</code> (%s). It will remain valid for this URL until <code>%s</code>.", get_ftps_site( $simplemap_ps ), date( "F d, Y", get_ftps_purchase_date( $simplemap_ps ) ), get_ftps_name( $simplemap_ps ), get_ftps_email( $simplemap_ps ), date( "F d, Y", get_ftps_exp_date( $simplemap_ps ) ) ); ?></p>
<p><a href='#' id='premium_help'><?php _e( 'Launch Premium Support widget', 'SimpleMap' ); ?></a> | <a target="blank" href="http://support.simplemap-plugin.com?sso=<?php echo get_ftps_sso_key( $simplemap_ps ); ?>"><?php _e( 'Visit Premium Support web site', 'SimpleMap' );?></a></p>
<script type="text/javascript" charset="utf-8">
Tender = {
hideToggle: true,
sso: "<?php echo get_ftps_sso_key( $simplemap_ps ); ?>",
widgetToggles: [document.getElementById('premium_help')]
}
</script>
<script src="https://simplemap.tenderapp.com/tender_widget.js" type="text/javascript"></script>
<?php endif; ?>
</div> <!-- inside -->
</div> <!-- postbox -->
<!-- #### MAP STYLES #### -->
<div class="postbox" >
<h3><?php _e( 'Map Style Defaults', 'SimpleMap' ); ?></h3>
<div class="inside">
<p class="sub"><?php printf( __( 'To insert SimpleMap into a post or page, type this shortcode in the body: %s', 'SimpleMap' ), '<code>[simplemap]</code>' ); ?></p>
<div class="table">
<table class="form-table">
<tr valign="top">
<td width="150"><label for="map_width"><?php _e( 'Map Size', 'SimpleMap' ); ?></label></td>
<td>
<label for="map_width" style="display: inline-block; width: 60px;"><?php _e( 'Width:', 'SimpleMap' ); ?> </label>
<input type="text" name="map_width" id="map_width" size="13" value="<?php echo esc_attr( $map_width ); ?>" /><br />
<label for="map_height" style="display: inline-block; width: 60px;"><?php _e( 'Height:', 'SimpleMap' ); ?> </label>
<input type="text" name="map_height" id="map_height" size="13" value="<?php echo esc_attr( $map_height ); ?>" /><br />
<small><em><?php printf( __( 'Enter a numeric value with CSS units, such as %s or %s.', 'SimpleMap' ), '</em><code>100%</code><em>', '</em><code>500px</code><em>' ); ?></em></small>
</td>
</tr>
<tr valign="top">
<td><label for="map_type"><?php _e( 'Default Map Type', 'SimpleMap' ); ?></label></td>
<td>
<div class="radio-thumbnail<?php if ( 'ROADMAP' == $map_type ) { echo ' radio-thumbnail-current'; } ?>">
<label style="display: block;" for="map_type_normal">
<img src="<?php echo SIMPLEMAP_URL; ?>/inc/images/map-type-normal.jpg" width="100" height="100" style="border: 1px solid #999;" /><br /><?php _e('Road map', 'SimpleMap'); ?><br />
<input type="radio" style="border: none;" name="map_type" id="map_type_normal" value="ROADMAP" <?php checked( $map_type, 'ROADMAP' ); ?> />
</label>
</div>
<div class="radio-thumbnail<?php if ( 'SATELLITE' == $map_type ) { echo ' radio-thumbnail-current'; } ?>">
<label style="display: block;" for="map_type_satellite">
<img src="<?php echo SIMPLEMAP_URL; ?>/inc/images/map-type-satellite.jpg" width="100" height="100" style="border: 1px solid #999;" /><br /><?php _e('Satellite map', 'SimpleMap'); ?><br />
<input type="radio" style="border: none;" name="map_type" id="map_type_satellite" value="SATELLITE" <?php checked( $map_type, 'SATELLITE' ); ?> />
</label>
</div>
<div class="radio-thumbnail<?php if ( 'HYBRID' == $map_type ) { echo ' radio-thumbnail-current'; } ?>">
<label style="display: block;" for="map_type_hybrid">
<img src="<?php echo SIMPLEMAP_URL; ?>/inc/images/map-type-hybrid.jpg" width="100" height="100" style="border: 1px solid #999;" /><br /><?php _e('Hybrid map', 'SimpleMap'); ?><br />
<input type="radio" style="border: none;" name="map_type" id="map_type_hybrid" value="HYBRID" <?php checked( $map_type, 'HYBRID' ); ?> />
</label>
</div>
<div class="radio-thumbnail<?php if ( 'TERRAIN' == $map_type ) { echo ' radio-thumbnail-current'; } ?>">
<label style="display: block;" for="map_type_terrain">
<img src="<?php echo SIMPLEMAP_URL; ?>/inc/images/map-type-terrain.jpg" width="100" height="100" style="border: 1px solid #999;" /><br /><?php _e('Terrain map', 'SimpleMap'); ?><br />
<input type="radio" style="border: none;" name="map_type" id="map_type_terrain" value="TERRAIN" <?php checked( $map_type, 'TERRAIN' ); ?> />
</label>
</div>
</td>
</tr>
<tr valign="top">
<td><label for="map_stylesheet"><?php _e( 'Theme', 'SimpleMap' ); ?></label></td>
<td>
<select name="map_stylesheet" id="map_stylesheet">
<?php
echo '<optgroup label="' . __( 'Default Themes', 'SimpleMap' ) . '">' . "\n";
foreach ( $themes1 as $file => $name ) {
$file_full = 'inc/styles/' . $file;
echo '<option value="' . esc_attr( $file_full ) . '" ' . selected( $map_stylesheet, $file_full, false ) . '>' . esc_attr( $name ) . '</option>' . "\n";
}
echo '</optgroup>' . "\n";
if (!empty($themes2)) {
echo '<optgroup label="'.__('Custom Themes', 'SimpleMap').'">'."\n";
foreach ($themes2 as $file => $name) {
$file_full = 'simplemap-styles/' . $file;
echo '<option value="' . esc_attr( $file_full ) . '" ' . selected( $map_stylesheet, $file_full, false ) . '>' . esc_attr( $name ) . '</option>' . "\n";
}
echo '</optgroup>'."\n";
}
?>
</select><br />
<small><em><?php printf( __( 'To add your own theme, upload your own CSS file to a new directory in your plugins folder called %s simplemap-styles%s. To give it a name, use the following header in the top of your stylesheet:', 'SimpleMap' ), '</em><code>', '</code><em>' ); ?></em></small><br />
<div style="margin-left: 20px;">
<code style="color: #060; background: none;">/*<br />Theme Name: THEME_NAME_HERE<br />*/</code>
</div>
</td>
</tr>
<tr valign="middle">
<td>
<label for="display_search"><?php _e( 'Display Search Form', 'SimpleMap' ); ?></label>
</td>
<td>
<label for="display_search_yes"><input type="radio" name="display_search" id="display_search_yes" value="show" <?php checked( $display_search, 'show' ); ?> /> <?php _e( 'Yes', 'SimpleMap' ); ?></label>&nbsp;&nbsp;
<label for="display_search_no"><input type="radio" name="display_search" id="display_search_no" value="hide" <?php checked( $display_search, 'hide' ); ?> /> <?php _e( 'No', 'SimpleMap' ); ?></label><br />
</td>
</tr>
<tr valign="middle">
<td>
<label for="powered_by"><?php _e('SimpleMap Link', 'SimpleMap'); ?></label>
</td>
<td>
<label for="powered_by"><input type="checkbox" name="powered_by" id="powered_by" <?php checked( $powered_by ); ?> /> <?php _e( 'Show the "Powered by SimpleMap" link', 'SimpleMap' ); ?></label>
</td>
</tr>
</table>
</div> <!-- table -->
<p class="submit" align="right">
<input type="submit" class="button-primary" value="<?php _e( 'Save Options', 'SimpleMap' ) ?>" />&nbsp;&nbsp;
</p>
<div class="clear"></div>
</div> <!-- inside -->
</div> <!-- postbox -->
<div class="postbox" >
<h3><?php _e( 'Delete SimpleMap Data', 'SimpleMap' ); ?></h3>
<div class="inside">
<p class="sub"><span style="color: red;"><?php _e( 'CAUTION! Uninstalling SimpleMap will completely delete all current locations, categories, tags and options. This is irreversible.' , 'SimpleMap' ); ?></span></p>
<p style='text-align:center;'><a onclick="javascript:return confirm('<?php _e( 'Last chance! Pressing OK will delete all SimpleMap locations. Your settings will not be deleted.'); ?>')" href="<?php echo wp_nonce_url( admin_url( 'admin.php?page=simplemap&sm-action=delete-simplemap&locations-only=true' ), 'delete-simplemap-locations' ); ?>" ><?php _e( 'Clicking this link will remove all locations but preserve your settings.'); ?></a></p>
<p style='text-align:center;'><a onclick="javascript:return confirm('<?php _e( 'Last chance! Pressing OK will delete all SimpleMap data.'); ?>')" href="<?php echo wp_nonce_url( admin_url( 'admin.php?page=simplemap&sm-action=delete-simplemap' ), 'delete-simplemap' ); ?>" ><?php _e( 'Clicking this link will remove all data from the database.'); ?></a></p>
</div>
</div>
<?php do_action( 'sm-general-options-side-sortables-bottom' ); ?>
</div> <!-- meta-box-sortables -->
</div> <!-- postbox-container -->
<?php do_action( 'sm-general-options-dash-widgets-bottom' ); ?>
</div> <!-- dashboard-widgets -->
</form>
<p style='float:right;margin-right:25px;'><a href='https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amp;hosted_button_id=DTJBYXGQFSW64'>Donate via PayPal</a></p>
<div class="clear">
</div>
</div><!-- dashboard-widgets-wrap -->
</div> <!-- wrap -->
<?php
}
// Locate and list style options / location
function read_styles( $dir ) {
$themes = array();
if ( $handle = opendir( $dir ) ) {
while ( false !== ( $file = readdir( $handle ) ) ) {
if ( $file != "." && $file != ".." && $file != ".svn" && $file != 'admin.css' ) {
$theme_data = implode( '', file( $dir . '/' . $file ) );
$name = '';
if (preg_match( '|Theme Name:(.*)$|mi', $theme_data, $matches ) )
$name = _cleanup_header_comment( $matches[1] );
else
$name = basename( $file );
$themes[$file] = $name;
}
}
closedir( $handle );
}
return( $themes );
}
}
}
?>

695
classes/parsecsv.lib.php Normal file
View File

@@ -0,0 +1,695 @@
<?php
class smParseCSV {
/*
Class: parseCSV v0.3.2
http://code.google.com/p/parsecsv-for-php/
Fully conforms to the specifications lined out on wikipedia:
- http://en.wikipedia.org/wiki/Comma-separated_values
Based on the concept of Ming Hong Ng's CsvFileParser class:
- http://minghong.blogspot.com/2006/07/csv-parser-for-php.html
Copyright (c) 2007 Jim Myhrberg (jim@zydev.info).
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Code Examples
----------------
# general usage
$csv = new parseCSV('data.csv');
print_r($csv->data);
----------------
# tab delimited, and encoding conversion
$csv = new parseCSV();
$csv->encoding('UTF-16', 'UTF-8');
$csv->delimiter = "\t";
$csv->parse('data.tsv');
print_r($csv->data);
----------------
# auto-detect delimiter character
$csv = new parseCSV();
$csv->auto('data.csv');
print_r($csv->data);
----------------
# modify data in a csv file
$csv = new parseCSV();
$csv->sort_by = 'id';
$csv->parse('data.csv');
# "4" is the value of the "id" column of the CSV row
$csv->data[4] = array('firstname' => 'John', 'lastname' => 'Doe', 'email' => 'john@doe.com');
$csv->save();
----------------
# add row/entry to end of CSV file
# - only recommended when you know the extact sctructure of the file
$csv = new parseCSV();
$csv->save('data.csv', array('1986', 'Home', 'Nowhere', ''), true);
----------------
# convert 2D array to csv data and send headers
# to browser to treat output as a file and download it
$csv = new parseCSV();
$csv->output (true, 'movies.csv', $array);
----------------
*/
/**
* Configuration
* - set these options with $object->var_name = 'value';
*/
# use first line/entry as field names
var $heading = true;
# override field names
var $fields = array();
# sort entries by this field
var $sort_by = null;
var $sort_reverse = false;
# delimiter (comma) and enclosure (double quote)
var $delimiter = ',';
var $enclosure = '"';
# basic SQL-like conditions for row matching
var $conditions = null;
# number of rows to ignore from beginning of data
var $offset = null;
# limits the number of returned rows to specified amount
var $limit = null;
# number of rows to analyze when attempting to auto-detect delimiter
var $auto_depth = 15;
# characters to ignore when attempting to auto-detect delimiter
var $auto_non_chars = "a-zA-Z0-9\n\r";
# preferred delimiter characters, only used when all filtering method
# returns multiple possible delimiters (happens very rarely)
var $auto_preferred = ",;\t.:|";
# character encoding options
var $convert_encoding = false;
var $input_encoding = 'ISO-8859-1';
var $output_encoding = 'ISO-8859-1';
# used by unparse(), save(), and output() functions
var $linefeed = "\r\n";
# only used by output() function
var $output_delimiter = ',';
var $output_filename = 'data.csv';
/**
* Internal variables
*/
# current file
var $file;
# loaded file contents
var $file_data;
# array of field values in data parsed
var $titles = array();
# two dimentional array of CSV data
var $data = array();
/**
* Constructor
* @param input CSV file or string
* @return nothing
*/
function smParseCSV ($input = null, $offset = null, $limit = null, $conditions = null) {
if ( $offset !== null ) $this->offset = $offset;
if ( $limit !== null ) $this->limit = $limit;
if ( count($conditions) > 0 ) $this->conditions = $conditions;
if ( !empty($input) ) $this->parse($input);
}
// ==============================================
// ----- [ Main Functions ] ---------------------
// ==============================================
/**
* Parse CSV file or string
* @param input CSV file or string
* @return nothing
*/
function parse ($input = null, $offset = null, $limit = null, $conditions = null) {
if ( !empty($input) ) {
if ( $offset !== null ) $this->offset = $offset;
if ( $limit !== null ) $this->limit = $limit;
if ( count($conditions) > 0 ) $this->conditions = $conditions;
if ( is_readable($input) ) {
$this->data = $this->parse_file($input);
} else {
$this->file_data = &$input;
$this->data = $this->parse_string();
}
if ( $this->data === false ) return false;
}
return true;
}
/**
* Save changes, or new file and/or data
* @param file file to save to
* @param data 2D array with data
* @param append append current data to end of target CSV if exists
* @param fields field names
* @return true or false
*/
function save ($file = null, $data = array(), $append = false, $fields = array()) {
if ( empty($file) ) $file = &$this->file;
$mode = ( $append ) ? 'at' : 'wt' ;
$is_php = ( preg_match('/\.php$/i', $file) ) ? true : false ;
return $this->_wfile($file, $this->unparse($data, $fields, $append, $is_php), $mode);
}
/**
* Generate CSV based string for output
* @param output if true, prints headers and strings to browser
* @param filename filename sent to browser in headers if output is true
* @param data 2D array with data
* @param fields field names
* @param delimiter delimiter used to separate data
* @return CSV data using delimiter of choice, or default
*/
function output ($output = true, $filename = null, $data = array(), $fields = array(), $delimiter = null) {
if ( empty($filename) ) $filename = $this->output_filename;
if ( $delimiter === null ) $delimiter = $this->output_delimiter;
$data = $this->unparse($data, $fields, null, null, $delimiter);
if ( $output ) {
header('Content-type: application/csv');
header('Content-Disposition: inline; filename="'.$filename.'"');
echo $data;
}
return $data;
}
/**
* Convert character encoding
* @param input input character encoding, uses default if left blank
* @param output output character encoding, uses default if left blank
* @return nothing
*/
function encoding ($input = null, $output = null) {
$this->convert_encoding = true;
if ( $input !== null ) $this->input_encoding = $input;
if ( $output !== null ) $this->output_encoding = $output;
}
/**
* Auto-Detect Delimiter: Find delimiter by analyzing a specific number of
* rows to determine most probable delimiter character
* @param file local CSV file
* @param parse true/false parse file directly
* @param search_depth number of rows to analyze
* @param preferred preferred delimiter characters
* @param enclosure enclosure character, default is double quote (").
* @return delimiter character
*/
function auto ($file = null, $parse = true, $search_depth = null, $preferred = null, $enclosure = null) {
if ( $file === null ) $file = $this->file;
if ( empty($search_depth) ) $search_depth = $this->auto_depth;
if ( $enclosure === null ) $enclosure = $this->enclosure;
if ( $preferred === null ) $preferred = $this->auto_preferred;
if ( empty($this->file_data) ) {
if ( $this->_check_data($file) ) {
$data = &$this->file_data;
} else return false;
} else {
$data = &$this->file_data;
}
$chars = array();
$strlen = strlen($data);
$enclosed = false;
$n = 1;
$to_end = true;
// walk specific depth finding posssible delimiter characters
for ( $i=0; $i < $strlen; $i++ ) {
$ch = $data{$i};
$nch = ( isset($data{$i+1}) ) ? $data{$i+1} : false ;
$pch = ( isset($data{$i-1}) ) ? $data{$i-1} : false ;
// open and closing quotes
if ( $ch == $enclosure && (!$enclosed || $nch != $enclosure) ) {
$enclosed = ( $enclosed ) ? false : true ;
// inline quotes
} elseif ( $ch == $enclosure && $enclosed ) {
$i++;
// end of row
} elseif ( ($ch == "\n" && $pch != "\r" || $ch == "\r") && !$enclosed ) {
if ( $n >= $search_depth ) {
$strlen = 0;
$to_end = false;
} else {
$n++;
}
// count character
} elseif (!$enclosed) {
if ( !preg_match('/['.preg_quote($this->auto_non_chars, '/').']/i', $ch) ) {
if ( !isset($chars[$ch][$n]) ) {
$chars[$ch][$n] = 1;
} else {
$chars[$ch][$n]++;
}
}
}
}
// filtering
$depth = ( $to_end ) ? $n-1 : $n ;
$filtered = array();
foreach( $chars as $char => $value ) {
if ( $match = $this->_check_count($char, $value, $depth, $preferred) ) {
$filtered[$match] = $char;
}
}
// capture most probable delimiter
ksort($filtered);
$delimiter = reset($filtered);
$this->delimiter = $delimiter;
// parse data
if ( $parse ) $this->data = $this->parse_string();
return $delimiter;
}
// ==============================================
// ----- [ Core Functions ] ---------------------
// ==============================================
/**
* Read file to string and call parse_string()
* @param file local CSV file
* @return 2D array with CSV data, or false on failure
*/
function parse_file ($file = null) {
if ( $file === null ) $file = $this->file;
if ( empty($this->file_data) ) $this->load_data($file);
return ( !empty($this->file_data) ) ? $this->parse_string() : false ;
}
/**
* Parse CSV strings to arrays
* @param data CSV string
* @return 2D array with CSV data, or false on failure
*/
function parse_string ($data = null) {
if ( empty($data) ) {
if ( $this->_check_data() ) {
$data = &$this->file_data;
} else return false;
}
$rows = array();
$row = array();
$row_count = 0;
$current = '';
$head = ( !empty($this->fields) ) ? $this->fields : array() ;
$col = 0;
$enclosed = false;
$was_enclosed = false;
$strlen = strlen($data);
// walk through each character
for ( $i=0; $i < $strlen; $i++ ) {
$ch = $data{$i};
$nch = ( isset($data{$i+1}) ) ? $data{$i+1} : false ;
$pch = ( isset($data{$i-1}) ) ? $data{$i-1} : false ;
// open and closing quotes
if ( $ch == $this->enclosure && (!$enclosed || $nch != $this->enclosure) ) {
$enclosed = ( $enclosed ) ? false : true ;
if ( $enclosed ) $was_enclosed = true;
// inline quotes
} elseif ( $ch == $this->enclosure && $enclosed ) {
$current .= $ch;
$i++;
// end of field/row
} elseif ( ($ch == $this->delimiter || ($ch == "\n" && $pch != "\r") || $ch == "\r") && !$enclosed ) {
if ( !$was_enclosed ) $current = trim($current);
$key = ( !empty($head[$col]) ) ? $head[$col] : $col ;
$row[$key] = $current;
$current = '';
$col++;
// end of row
if ( $ch == "\n" || $ch == "\r" ) {
if ( $this->_validate_offset($row_count) && $this->_validate_row_conditions($row, $this->conditions) ) {
if ( $this->heading && empty($head) ) {
$head = $row;
} elseif ( empty($this->fields) || (!empty($this->fields) && (($this->heading && $row_count > 0) || !$this->heading)) ) {
if ( !empty($this->sort_by) && !empty($row[$this->sort_by]) ) {
if ( isset($rows[$row[$this->sort_by]]) ) {
$rows[$row[$this->sort_by].'_0'] = &$rows[$row[$this->sort_by]];
unset($rows[$row[$this->sort_by]]);
for ( $sn=1; isset($rows[$row[$this->sort_by].'_'.$sn]); $sn++ ) {}
$rows[$row[$this->sort_by].'_'.$sn] = $row;
} else $rows[$row[$this->sort_by]] = $row;
} else $rows[] = $row;
}
}
$row = array();
$col = 0;
$row_count++;
if ( $this->sort_by === null && $this->limit !== null && count($rows) == $this->limit ) {
$i = $strlen;
}
}
// append character to current field
} else {
$current .= $ch;
}
}
$this->titles = $head;
if ( !empty($this->sort_by) ) {
( $this->sort_reverse ) ? krsort($rows) : ksort($rows) ;
if ( $this->offset !== null || $this->limit !== null ) {
$rows = array_slice($rows, ($this->offset === null ? 0 : $this->offset) , $this->limit, true);
}
}
return $rows;
}
/**
* Create CSV data from array
* @param data 2D array with data
* @param fields field names
* @param append if true, field names will not be output
* @param is_php if a php die() call should be put on the first
* line of the file, this is later ignored when read.
* @param delimiter field delimiter to use
* @return CSV data (text string)
*/
function unparse ( $data = array(), $fields = array(), $append = false , $is_php = false, $delimiter = null) {
if ( !is_array($data) || empty($data) ) $data = &$this->data;
if ( !is_array($fields) || empty($fields) ) $fields = &$this->titles;
if ( $delimiter === null ) $delimiter = $this->delimiter;
$string = ( $is_php ) ? "<?php header('Status: 403'); die(' '); ?>".$this->linefeed : '' ;
$entry = array();
// create heading
if ( $this->heading && !$append ) {
foreach( $fields as $key => $value ) {
$entry[] = $this->_enclose_value($value);
}
$string .= implode($delimiter, $entry).$this->linefeed;
$entry = array();
}
// create data
foreach( $data as $key => $row ) {
foreach( $row as $field => $value ) {
$entry[] = $this->_enclose_value($value);
}
$string .= implode($delimiter, $entry).$this->linefeed;
$entry = array();
}
return $string;
}
/**
* Load local file or string
* @param input local CSV file
* @return true or false
*/
function load_data ($input = null) {
$data = null;
$file = null;
if ( $input === null ) {
$file = $this->file;
} elseif ( file_exists($input) ) {
$file = $input;
} else {
$data = $input;
}
if ( !empty($data) || $data = $this->_rfile($file) ) {
if ( $this->file != $file ) $this->file = $file;
if ( preg_match('/\.php$/i', $file) && preg_match('/<\?.*?\?>(.*)/ims', $data, $strip) ) {
$data = ltrim($strip[1]);
}
if ( $this->convert_encoding ) $data = iconv($this->input_encoding, $this->output_encoding, $data);
if ( substr($data, -1) != "\n" ) $data .= "\n";
$this->file_data = &$data;
return true;
}
return false;
}
// ==============================================
// ----- [ Internal Functions ] -----------------
// ==============================================
/**
* Validate a row against specified conditions
* @param row array with values from a row
* @param conditions specified conditions that the row must match
* @return true of false
*/
function _validate_row_conditions ($row = array(), $conditions = null) {
if ( !empty($row) ) {
if ( !empty($conditions) ) {
$conditions = (strpos($conditions, ' OR ') !== false) ? explode(' OR ', $conditions) : array($conditions) ;
$or = '';
foreach( $conditions as $key => $value ) {
if ( strpos($value, ' AND ') !== false ) {
$value = explode(' AND ', $value);
$and = '';
foreach( $value as $k => $v ) {
$and .= $this->_validate_row_condition($row, $v);
}
$or .= (strpos($and, '0') !== false) ? '0' : '1' ;
} else {
$or .= $this->_validate_row_condition($row, $value);
}
}
return (strpos($or, '1') !== false) ? true : false ;
}
return true;
}
return false;
}
/**
* Validate a row against a single condition
* @param row array with values from a row
* @param condition specified condition that the row must match
* @return true of false
*/
function _validate_row_condition ($row, $condition) {
$operators = array(
'=', 'equals', 'is',
'!=', 'is not',
'<', 'is less than',
'>', 'is greater than',
'<=', 'is less than or equals',
'>=', 'is greater than or equals',
'contains',
'does not contain',
);
$operators_regex = array();
foreach( $operators as $value ) {
$operators_regex[] = preg_quote($value, '/');
}
$operators_regex = implode('|', $operators_regex);
if ( preg_match('/^(.+) ('.$operators_regex.') (.+)$/i', trim($condition), $capture) ) {
$field = $capture[1];
$op = $capture[2];
$value = $capture[3];
if ( preg_match('/^([\'\"]{1})(.*)([\'\"]{1})$/i', $value, $capture) ) {
if ( $capture[1] == $capture[3] ) {
$value = $capture[2];
$value = str_replace("\\n", "\n", $value);
$value = str_replace("\\r", "\r", $value);
$value = str_replace("\\t", "\t", $value);
$value = stripslashes($value);
}
}
if ( array_key_exists($field, $row) ) {
if ( ($op == '=' || $op == 'equals' || $op == 'is') && $row[$field] == $value ) {
return '1';
} elseif ( ($op == '!=' || $op == 'is not') && $row[$field] != $value ) {
return '1';
} elseif ( ($op == '<' || $op == 'is less than' ) && $row[$field] < $value ) {
return '1';
} elseif ( ($op == '>' || $op == 'is greater than') && $row[$field] > $value ) {
return '1';
} elseif ( ($op == '<=' || $op == 'is less than or equals' ) && $row[$field] <= $value ) {
return '1';
} elseif ( ($op == '>=' || $op == 'is greater than or equals') && $row[$field] >= $value ) {
return '1';
} elseif ( $op == 'contains' && preg_match('/'.preg_quote($value, '/').'/i', $row[$field]) ) {
return '1';
} elseif ( $op == 'does not contain' && !preg_match('/'.preg_quote($value, '/').'/i', $row[$field]) ) {
return '1';
} else {
return '0';
}
}
}
return '1';
}
/**
* Validates if the row is within the offset or not if sorting is disabled
* @param current_row the current row number being processed
* @return true of false
*/
function _validate_offset ($current_row) {
if ( $this->sort_by === null && $this->offset !== null && $current_row < $this->offset ) return false;
return true;
}
/**
* Enclose values if needed
* - only used by unparse()
* @param value string to process
* @return Processed value
*/
function _enclose_value ($value = null) {
if ( $value !== null && $value != '' ) {
$delimiter = preg_quote($this->delimiter, '/');
$enclosure = preg_quote($this->enclosure, '/');
if ( preg_match("/".$delimiter."|".$enclosure."|\n|\r/i", $value) || ($value{0} == ' ' || substr($value, -1) == ' ') ) {
$value = str_replace($this->enclosure, $this->enclosure.$this->enclosure, $value);
$value = $this->enclosure.$value.$this->enclosure;
}
}
return $value;
}
/**
* Check file data
* @param file local filename
* @return true or false
*/
function _check_data ($file = null) {
if ( empty($this->file_data) ) {
if ( $file === null ) $file = $this->file;
return $this->load_data($file);
}
return true;
}
/**
* Check if passed info might be delimiter
* - only used by find_delimiter()
* @return special string used for delimiter selection, or false
*/
function _check_count ($char, $array, $depth, $preferred) {
if ( $depth == count($array) ) {
$first = null;
$equal = null;
$almost = false;
foreach( $array as $key => $value ) {
if ( $first == null ) {
$first = $value;
} elseif ( $value == $first && $equal !== false) {
$equal = true;
} elseif ( $value == $first+1 && $equal !== false ) {
$equal = true;
$almost = true;
} else {
$equal = false;
}
}
if ( $equal ) {
$match = ( $almost ) ? 2 : 1 ;
$pref = strpos($preferred, $char);
$pref = ( $pref !== false ) ? str_pad($pref, 3, '0', STR_PAD_LEFT) : '999' ;
return $pref.$match.'.'.(99999 - str_pad($first, 5, '0', STR_PAD_LEFT));
} else return false;
}
}
/**
* Read local file
* @param file local filename
* @return Data from file, or false on failure
*/
function _rfile ($file = null) {
if ( is_readable($file) ) {
if ( !($fh = fopen($file, 'r')) ) return false;
$data = fread($fh, filesize($file));
fclose($fh);
return $data;
}
return false;
}
/**
* Write to local file
* @param file local filename
* @param string data to write to file
* @param mode fopen() mode
* @param lock flock() mode
* @return true or false
*/
function _wfile ($file, $string = '', $mode = 'wb', $lock = 2) {
if ( $fp = fopen($file, $mode) ) {
flock($fp, $lock);
$re = fwrite($fp, $string);
$re2 = fclose($fp);
if ( $re != false && $re2 != false ) return true;
}
return false;
}
}
?>

254
classes/shortcodes.php Normal file
View File

@@ -0,0 +1,254 @@
<?php
/**
* This file contains all my classes for the different shortcodes
*/
/**
* SM_Shortcodes Class
*
* Registers and handles shortcodes for SimpleMap Locations. The only exception right now is the
* main [simplemap] shortcode which is currently being handled by /classes/simplemap.php.
* It will eventually be moved here
*
* @since 2.4
*/
if ( ! class_exists( 'SM_Location_Shortcodes' ) ) {
class SM_Location_Shortcodes {
/**
* An array of all shortcodes related to locations
*
* @since 2.4
*/
var $shortcode_tags = array();
/**
* Class constructor
*
* @since 2.4
*/
function __construct() {
// Build shortcode tag list
$this->shortcode_tags = $this->get_shortcode_tags();
// Register shortcodes with WordPress
add_action( 'init', array( &$this, 'register_shortcodes' ) );
}
/**
* This method loops through all my location shortcodes and registers them.
*
* All shortcode tags actually use the same callback method
*
* @since 2.4
*/
function register_shortcodes() {
// Register
add_shortcode( 'sm-location', array( &$this, 'do_shortcode' ) );
}
/**
* Builds the array of tags used for location shortcodes
*
* @since 2.4
*/
function get_shortcode_tags() {
$shortcode_tags = array(
'address',
'city',
'state',
'zip',
'country',
'phone',
'fax',
'email',
'url'
);
return apply_filters( 'sm-location-shortcode-tag-array', $shortcode_tags );
}
/**
* Responsible for returning a location address
*
* @since 2.4
*/
function do_shortcode( $args ) {
global $post, $simple_map;
$options = $simple_map->get_options();
// Default args for map itself, not for locations on map
$map_defaults = array(
'data' => '',
'before' => '',
'after' => '',
'map_width' => '75px',
'map_height' => '75px',
'default_lat' => get_post_meta( $post->ID, 'location_lat', true ),
'default_lng' => get_post_meta( $post->ID, 'location_lng', true ),
'panControl' => false,
'zoomContorl' => false,
'scaleControl' => false,
'streetViewControl' => false,
'mapTypeContorl' => false,
'mapTypeId' => 'google.maps.MapTypeId.ROADMAP',
'format' => 'csv',
);
$atts = shortcode_atts( $map_defaults, $args );
// If the requested data is description, return the post content
if ( 'description' == $atts['data'] )
return $post->post_content;
// If we're looking for the full address, compose that from the options
if ( 'full-address' == $atts['data'] ) {
$postmeta = get_metadata( 'post', $post->ID );
$address_format = $options['address_format'];
switch ( $address_format ) {
case 'town province postalcode' :
$full_address = $postmeta['location_address'][0] . ' ' . $postmeta['location_address2'][0] . ' ' .$postmeta['location_city'][0] . $postmeta['location_state'][0] . ' ' . $postmeta['location_zip'][0];
break;
case 'town-province postalcode' :
$full_address = $postmeta['location_address'][0] . ' ' . $postmeta['location_address2'][0] . ' ' .$postmeta['location_city'][0] . '-' . $postmeta['location_state'][0] . ' ' . $postmeta['location_zip'][0];
break;
case 'postalcode town-province' :
$full_address = $postmeta['location_address'][0] . ' ' . $postmeta['location_address2'][0] . ' ' .$postmeta['location_zip'][0] . ' ' . $postmeta['location_city'][0] . '-' . $postmeta['location_state'][0];
break;
case 'postalcode town, province' :
$full_address = $postmeta['location_address'][0] . ' ' . $postmeta['location_address2'][0] . ' ' .$postmeta['location_zip'][0] . ' ' . $postmeta['location_city'][0] . ', ' . $postmeta['location_state'][0];
break;
case 'postalcode town' :
$full_address = $postmeta['location_address'][0] . ' ' . $postmeta['location_address2'][0] . ' ' .$postmeta['location_zip'][0] . ' ' . $postmeta['location_city'][0];
break;
case 'town postalcode' :
$full_address = $postmeta['location_address'][0] . ' ' . $postmeta['location_address2'][0] . ' ' .$postmeta['location_city'][0] . ' ' . $postmeta['location_zip'][0];
break;
case 'town, province postalcode' :
default :
$full_address = $postmeta['location_address'][0] . ' ' . $postmeta['location_address2'][0] . ' ' .$postmeta['location_city'][0] . ', ' . $postmeta['location_state'][0] . ' ' . $postmeta['location_zip'][0];
break;
}
return $full_address;
}
// if the requested data is 'directions' return the link to google maps
if ( 'directions' == $atts['data'] )
return $this->get_directions_link( $post->ID );
// if the requested data is a map, return the map
if ( 'iframe-map' == $atts['data'] ) {
// Args we need to make the map itself - not the locations on the map
$r = array(
'map_width' => $atts['map_width'],
'map_height' => $atts['map_height'],
'panControl' => $atts['pan_control'],
'default_lat' => $atts['default_lat'],
'default_lng' => $atts['default_lng'],
'zoomControl' => $atts['zoom_control'],
'scaleControl' => $atts['scale_control'],
'streetViewControl' => $atts['street_view_control'],
'mapTypeControl' => $atts['map_type_control'],
'mapType' => $atts['map_type']
);
// Determine location IDs
$location_ids = empty( $args['location_ids'] ) ? array( $post->ID ) : explode( ',', $args['location_ids'] );
// Init the object and return the iframe source
$map = new SM_Map_Factory();
$map->set_map_atts( $r );
// Add Locations
foreach( $location_ids as $location_id ) {
$map->add_location( $location_id );
}
return $map->get_iframe_embed();
}
// If the requested data is a taxonomy
$sm_taxes = $simple_map->get_sm_taxonomies( 'array', '', true, 'objects' ) ? $simple_map->get_sm_taxonomies( 'array', '', true, 'objects' ) : array();
foreach( $sm_taxes as $taxonomy ) {
if ( $taxonomy->name == $atts['data'] ) {
// Forward compatible format types
$tax_format = ( in_array( $atts['format'], array( 'csv' ) ) ) ? $atts['format'] : 'csv';
if ( $terms = wp_get_object_terms( $post->ID, $taxonomy->query_var ) ) {
foreach( $terms as $termk => $termv ) {
$term_names[] = $termv->name;
}
} else {
$term_names = array();
}
// Forward compatible format types
switch( $tax_format ) {
case 'csv':
default:
return ! empty( $term_names ) ? $args['before'] . implode( ', ', $term_names ) . $args['after'] : '' ;
break;
}
}
}
// Look for postmeta with location_ prepended to it
if ( $value = get_post_meta( absint( $post->ID ), 'location_' . $atts['data'], true ) )
return str_replace( '%self%', $value, $atts['before'] . $value . $atts['after'] );
// Look for postmeta of another type
if ( $value = get_post_meta( absint( $post->ID ), $atts['data'], true ) )
return str_replace( '%self%', $value, $atts['before'] . $value . $atts['after'] );
return false;
}
/**
* Returns a directions link
*
* @since 2.4
*/
function get_directions_link( $post ) {
global $simple_map;
$options = $simple_map->get_options();
$address = $directions_url = '';
if ( $pm = get_metadata( 'post', $post ) ) {
$address .= empty( $pm['location_address'][0] ) ? '' : $pm['location_address'][0];
$address .= empty( $pm['location_city'][0] ) ? '' : ' '.$pm['location_city'][0];
$address .= empty( $pm['location_state'][0] ) ? '' : ' '.$pm['location_state'][0];
$address .= empty( $pm['location_zip'][0] ) ? '' : ' '.$pm['location_zip'][0];
$address .= empty( $pm['location_country'][0] ) ? '' : ' '.$pm['location_country'][0];
$directions_url = 'http://google' . $options['default_domain'] . '/maps?saddr=&daddr=' . urlencode( $address );
}
return $directions_url;
}
}
}

2369
classes/simplemap.php Normal file

File diff suppressed because it is too large Load Diff

151
classes/templates.php Normal file
View File

@@ -0,0 +1,151 @@
<?php
/**
* This file contains all our classes for the different location templates
*/
/**
* SM_Template_Factory Class
*
* A templating system for SimpleMap
*
* @since 2.4
*/
if ( ! class_exists( 'SM_Template_Factory' ) ) {
class SM_Template_Factory {
/**
* Template Type - single-location, map, results
*/
var $template_type = false;
/**
* The post_id for the template used by the current instance of this class
* Won't be implemented in 2.4
*/
var $template_id;
/**
* The content of the active template (the template itself)
* @since 2.4
*/
var $template_structure = false;
/**
* Inits the templating system. Don't init class prior to template_redirect hook
*
* @since 2.4
*/
function __construct() {
// Set the template type
$this->template_type = $this->set_template_type();
// Set the specific template for this view
$this->set_active_template();
// Add the filter
add_filter( 'the_content', array( &$this, 'apply_template' ), 1 );
}
/**
* Parses wp_query to determine the template type we are going to use
* As of 2.4, the only opiton is single-location
*
* @since 2.4
*/
function set_template_type() {
global $post;
// Exit if we're not on a single disply of the location post type
if ( 'sm-location' != $post->post_type || ! is_single() )
return false;
return 'single-location';
}
/**
* Sets the template we will use for the current view based on a cascading set of rules
* If this is a single location view, do the following:
* <ul>
* <li>Check for specific template via post-meta
* <li>Check for default template</li>
* </ul>
*
* @since 2.4
*/
function set_active_template() {
global $post;
// Switch based on template type
switch ( $this->template_type ) {
case 'single-location' :
default :
// Grab the ID for the specific template for this post if it is present
$template_id = ( get_post_meta( $post->ID, 'sm-location-template', false ) ) ? get_post_meta( $post->ID, 'sm-location-template', false ) : 0;
break;
}
$this->template_id = $template_id;
$this->template_structure = $this->get_template_structure();
}
/**
* Returns the actual template structure we're going to use for this object
*
* @since 2.4
*/
function get_template_structure() {
// Grab the post that contains the template strucutre or the hard_coded structure
if ( 0 != $this->template_id ) {
// get post obejct via ID
// return post_content
} else {
$return = "<div class='sm-single-location-default-template'>";
$return .= "<div class='sm-single-map'>[sm-location data='iframe-map' map_width='100px' map_height='100px']</div>";
$return .= "<div class='sm-single-location-data'>[sm-location data='full-address']";
$return .= "<br /><a href=\"[sm-location data='directions']\">Get Directions</a>";
$return .= "<ul class='sm-single-location-data-ul'>[sm-location data='phone' before='<li>' after='</li>'] [sm-location data='email' before='<li><a href=\"mailto:%self%\">' after='</a></li>'] [sm-location data='sm_category' format='csv' before='<li>Categories: ' after='</li>'] [sm-location data='sm_tag' format='csv' before='<li>Tags: ' after='</li>']</ul>";
$return .= "</div>";
$return .= "<hr style='clear:both;' />";
$return .= "</div>";
$return .= "[sm-location data='description']";
return apply_filters( 'sm-single-location-default-template', $return );
}
return $return;
}
/**
* This method applies the template to the content
*
* @since 2.4
*/
function apply_template( $content ) {
// Return content untouched if not location data
if ( ! $this->template_type || ! $this->template_structure )
return $content;
// Return if not in the loop
if ( ! in_the_loop() )
return $content;
// Save the location 'description'
$location_description = $content;
// Send it through the shortcode parser
$content = do_shortcode( $this->template_structure );
return $content;
}
}
}

256
classes/widgets.php Normal file
View File

@@ -0,0 +1,256 @@
<?php
// Init Widgets
function simplemap_init_widgets() {
register_widget( 'SM_Search_Widget' );
}
add_action( 'widgets_init', 'simplemap_init_widgets' );
// Location Search Widget
class SM_Search_Widget extends WP_Widget {
// Define Widget
function SM_Search_Widget() {
$widget_ops = array( 'classname' => 'sm_search_widget', 'description' => __( "Adds a customizable search widget to your site" ) );
$this->WP_Widget('sm_search_widget', __('SimpleMap Search'), $widget_ops);
}
function widget( $args, $instance ) {
global $simple_map, $wp_rewrite;
extract( $args );
$options = $simple_map->get_options();
$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'] );
// Search Form Options
$show_address = $instance['show_address'] ? 1 : 0;
$show_city = $instance['show_city'] ? 1 : 0;
$show_state = $instance['show_state'] ? 1 : 0;
$show_zip = $instance['show_zip'] ? 1 : 0;
$show_distance = $instance['show_distance'] ? 1 : 0;
$default_lat = $instance['default_lat'] ? $instance['default_lat'] : 0;
$default_lng = $instance['default_lng'] ? $instance['default_lng'] : 0;
$simplemap_page = $instance['simplemap_page'] ? $instance['simplemap_page'] : 2;
// Set taxonomies to available equivalents
$show = array();
$terms = array();
foreach ( $options['taxonomies'] as $taxonomy => $tax_info ) {
$key = strtolower( $tax_info['plural'] );
$show[$taxonomy] = $instance['show_' . $key] ? 1 : 0;
$terms[$taxonomy] = $instance[$key] ? $instance[$key] : '';
}
$available = $terms;
echo $before_widget;
if ( $title )
echo '<span class="sm-search-widget-title">' . $before_title . $title . $after_title . '</span>';
// Form Field Values
$address_value = isset( $_REQUEST['location_search_address'] ) ? $_REQUEST['location_search_address'] : '';
$city_value = isset( $_REQUEST['location_search_city'] ) ? $_REQUEST['location_search_city'] : '';
$state_value = isset( $_REQUEST['location_search_state'] ) ? $_REQUEST['location_search_state'] : '';
$zip_value = isset( $_REQUEST['location_search_zip'] ) ? $_REQUEST['location_search_zip'] : '';
$radius_value = isset( $_REQUEST['location_search_distance'] ) ? $_REQUEST['location_search_distance'] : $options['default_radius'];
$limit_value = isset( $_REQUEST['location_search_limit'] ) ? $_REQUEST['location_search_limit'] : $options['results_limit'];
// Set action based on permalink structure
if ( ! $wp_rewrite->permalink_structure ) {
$method = 'get';
$action = site_url();
} else {
$method = 'post';
$action = get_permalink( absint( $simplemap_page ) );
}
$location_search = '<div id="location_widget_search" >';
$location_search .= '<form name="location_widget_search_form" id="location_widget_search_form" action="' . $action . '" method="' . $method . '">';
$location_search .= '<table class="location_search_widget">';
$location_search .= apply_filters( 'sm-location-search-widget-table-top', '' );
if ( $show_address )
$location_search .= '<tr><td class="location_search_widget_address_cell location_search_widget_cell">' . apply_filters( 'sm-search-label-street', __( 'Street', 'SimpleMap' ) ) . ':<br /><input type="text" id="location_search_widget_address_field" name="location_search_address" /></td></tr>';
if ( $show_city )
$location_search .= '<tr><td class="location_search_widget_city_cell location_search_widget_cell">' . apply_filters( 'sm-search-label-city', __( 'City', 'SimpleMap' ) ) . ':<br /><input type="text" id="location_search_widget_city_field" name="location_search_city" /></td></tr>';
if ( $show_state )
$location_search .= '<tr><td class="location_search_widget_state_cell location_search_widget_cell">' . apply_filters( 'sm-search-label-state', __( 'State', 'SimpleMap' ) ) . ':<br /><input type="text" id="location_search_widget_state_field" name="location_search_state" /></td></tr>';
if ( $show_zip )
$location_search .= '<tr><td class="location_search_widget_zip_cell location_search_widget_cell">' . apply_filters( 'sm-search-label-zip', __( 'Zip', 'SimpleMap' ) ) . ':<br /><input type="text" id="location_search_widget_zip_field" name="location_search_zip" /></td></tr>';
if ( $show_distance ) {
$location_search .= '<tr><td class="location_search_widget_distance_cell location_search_widget_cell">' . apply_filters( 'sm-search-label-distance', __( 'Select a distance', 'SimpleMap' ) ) . ':<br /><select id="location_search_widget_distance_field" name="location_search_distance" >';
foreach ( $simple_map->get_search_radii() as $value ) {
$r = (int) $value;
$location_search .= '<option value="' . $value . '"' . selected( $radius_value, $value, false ) . '>' . $value . ' ' . $options['units'] . "</option>\n";
}
$location_search .= '</select></td></tr>';
}
foreach ( $options['taxonomies'] as $taxonomy => $tax_info ) {
// Place available values in array
$available = explode( ',', $available[$taxonomy] );
$valid = array();
// Loop through all days and create array of available days
if ( $all_terms = get_terms( $taxonomy ) ) {
foreach ( $all_terms as $key => $value ) {
if ( '' == $available[0] || in_array( $value->term_id, $available ) ) {
$valid[] = $value->term_id;
}
}
}
// Show day filters if allowed
if ( ! empty( $show[$taxonomy] ) && $all_terms ) {
$php_taxonomy = str_replace( '-', '_', $taxonomy );
$term_search = '<tr><td class="location_search_' . strtolower( $tax_info['singular'] ) . '_cell location_search_cell">' . apply_filters( $php_taxonomy . '-text',__( $tax_info['plural'], 'SimpleMap' ) ) . ':<br />';
// Print checkbox for each available day
foreach( $valid as $key => $termid ) {
if( $term = get_term_by( 'id', $termid, $taxonomy ) ) {
$term_search .= '<label for="location_search_widget_' . strtolower( $tax_info['plural'] ) . '_field_' . esc_attr( $term->term_id ) . '" class="no-linebreak"><input type="checkbox" name="location_search_' . $php_taxonomy . '_' . esc_attr( $term->term_id ) . 'field" id="location_search_widget_' . strtolower( $tax_info['plural'] ) . '_field_' . esc_attr( $term->term_id ) . '" value="' . esc_attr( $term->term_id ) . '" /> ' . esc_attr( $term->name ) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label> ';
}
}
$term_search .= '</td></tr>';
} else {
// Default day_selected is none
$term_search = '<input type="hidden" name="location_search_' . strtolower( $tax_info['plural'] ) . '_field" value="" checked="checked" />';
}
// Hidden field for available days. We'll need this in the event that nothing is selected
$term_search .= '<input type="hidden" id="avail_' . strtolower( $tax_info['plural'] ) . '" value="' . esc_attr( $terms[$taxonomy] ) . '" />';
$term_search = apply_filters( 'sm-location-' . strtolower( $tax_info['singular'] ) . '-search-widget', $term_search );
$location_search .= $term_search;
}
// Default lat / lng from shortcode?
if ( ! $default_lat )
$default_lat = $options['default_lat'];
if ( ! $default_lng )
$default_lng = $options['default_lng'];
$location_search .= "<input type='hidden' id='location_search_widget_default_lat' value='" . $default_lat . "' />";
$location_search .= "<input type='hidden' id='location_search_widget_default_lng' value='" . $default_lng . "' />";
// Hidden value for limit
$location_search .= "<input type='hidden' name='location_search_widget_limit' id='location_search_widget_limit' value='" . $limit_value . "' />";
// Hidden value set to true if we got here via search
$location_search .= "<input type='hidden' id='location_is_search_widget_results' name='location_is_search_results' value='1' />";
// Hidden value referencing page_id
$location_search .= "<input type='hidden' name='page_id' value='" . absint( $simplemap_page ) . "' />";
$location_search .= apply_filters( 'sm-location-search-widget-before-submit', '' );
$location_search .= '<tr><td class="location_search_widget_submit_cell location_search_widget_cell"> <input type="submit" value="' . apply_filters( 'sm-search-label-search', __( 'Search', 'SimpleMap' ) ) . '" id="location_search_widget_submit_field" class="submit" /></td></tr>';
$location_search .= '</table>';
$location_search .= '</form>';
$location_search .= '</div>'; // close map_search div
echo $location_search;
echo $after_widget;
}
// Save settings in backend
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['show_address'] = $new_instance['show_address'] ? 1 : 0;
$instance['show_city'] = $new_instance['show_city'] ? 1 : 0;
$instance['show_state'] = $new_instance['show_state'] ? 1 : 0;
$instance['show_zip'] = $new_instance['show_zip'] ? 1 : 0;
$instance['show_distance'] = $new_instance['show_distance'] ? 1 : 0;
$instance['default_lat'] = $new_instance['default_lat'] ? $new_instance['default_lat'] : 0;
$instance['default_lng'] = $new_instance['default_lng'] ? $new_instance['default_lng'] : 0;
$instance['simplemap_page'] = $new_instance['simplemap_page'] ? $new_instance['simplemap_page'] : 2;
global $simple_map;
$options = $simple_map->get_options();
foreach ( $options['taxonomies'] as $taxonomy => $tax_info ) {
$key = strtolower( $tax_info['plural'] );
$instance['show_' . $key] = $new_instance['show_' . $key] ? 1 : 0;
$instance[$key] = $new_instance[$key] ? $new_instance[$key] : '';
}
return $instance;
}
function form( $instance ) {
//Defaults
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$title = esc_attr( $instance['title'] );
$show_address = isset( $instance['show_address'] ) ? (bool) $instance['show_address'] : false;
$show_city = isset( $instance['show_city'] ) ? (bool) $instance['show_city'] : false;
$show_state = isset( $instance['show_state'] ) ? (bool) $instance['show_state'] : false;
$show_zip = isset( $instance['show_zip'] ) ? (bool) $instance['show_zip'] : false;
$show_distance = isset( $instance['show_distance'] ) ? (bool) $instance['show_distance'] : false;
$default_lat = isset( $instance['default_lat'] ) ? esc_attr( $instance['default_lat'] ) : 0;
$default_lng = isset( $instance['default_lng'] ) ? esc_attr( $instance['default_lng'] ) : 0;
$simplemap_page = isset( $instance['simplemap_page'] ) ? esc_attr( $instance['simplemap_page'] ) : '';
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></p>
<p><input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'show_address' ); ?>" name="<?php echo $this->get_field_name( 'show_address' ); ?>"<?php checked( $show_address ); ?> />
<label for="<?php echo $this->get_field_id( 'show_address' ); ?>"><?php _e( 'Show Address', 'SimpleMap' ); ?></label><br />
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'show_city' ); ?>" name="<?php echo $this->get_field_name( 'show_city' ); ?>"<?php checked( $show_city ); ?> />
<label for="<?php echo $this->get_field_id( 'show_city' ); ?>"><?php _e( 'Show City', 'SimpleMap' ); ?></label><br />
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'show_state' ); ?>" name="<?php echo $this->get_field_name( 'show_state' ); ?>"<?php checked( $show_state ); ?> />
<label for="<?php echo $this->get_field_id( 'show_state' ); ?>"><?php _e( 'Show State', 'SimpleMap' ); ?></label><br />
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'show_zip' ); ?>" name="<?php echo $this->get_field_name( 'show_zip' ); ?>"<?php checked( $show_zip ); ?> />
<label for="<?php echo $this->get_field_id( 'show_zip' ); ?>"><?php _e( 'Show Zip', 'SimpleMap' ); ?></label><br />
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'show_distance' ); ?>" name="<?php echo $this->get_field_name( 'show_distance' ); ?>"<?php checked( $show_distance ); ?> />
<label for="<?php echo $this->get_field_id( 'show_distance' ); ?>"><?php _e( 'Show Distance', 'SimpleMap' ); ?></label><br />
<?php
global $simple_map;
$options = $simple_map->get_options();
foreach ( $options['taxonomies'] as $taxonomy => $tax_info ) {
$key = strtolower( $tax_info['plural'] );
$show_field = 'show_' . $key;
$show = isset( $instance[$show_field] ) ? (bool) $instance[$show_field] : false;
?>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( $show_field ); ?>" name="<?php echo $this->get_field_name( $show_field ); ?>"<?php checked( $show ); ?> />
<label for="<?php echo $this->get_field_id( $show_field ); ?>"><?php _e( 'Show ' . $tax_info['plural'], 'SimpleMap' ); ?></label><br />
<?php
/** TODO: The commented out code below isn't working yet. Implement it.
$values = isset( $instance[$key] ) ? esc_attr( $instance[$key] ) : '';
?>
<p><label for="<?php echo $this->get_field_id( $key ); ?>"><?php _e( $tax_info['plural'] . ':', 'SimpleMap' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( $key ); ?>" name="<?php echo $this->get_field_name( $key ); ?>" type="text" value="<?php echo $values; ?>" /></p>
<?php
*/
}
/** TODO: The commented out code below isn't working yet. Implement it.
<p><label for="<?php echo $this->get_field_id( 'default_lat' ); ?>"><?php _e( 'Default Lat:', 'SimpleMap' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'default_lat' ); ?>" name="<?php echo $this->get_field_name( 'default_lat' ); ?>" type="text" value="<?php echo $default_lat; ?>" /></p>
<p><label for="<?php echo $this->get_field_id( 'default_lng' ); ?>"><?php _e( 'Default Lng:', 'SimpleMap' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'default_lng' ); ?>" name="<?php echo $this->get_field_name( 'default_lng' ); ?>" type="text" value="<?php echo $default_lng; ?>" /></p>
*/
?>
<p><label for="<?php echo $this->get_field_id( 'simplemap_page' ); ?>"><?php _e( 'SimpleMap Page or Post ID:', 'SimpleMap' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'simplemap_page' ); ?>" name="<?php echo $this->get_field_name( 'simplemap_page' ); ?>" type="text" value="<?php echo $simplemap_page; ?>" /></p>
<?php
}
}
?>

198
classes/xml-search.php Normal file
View File

@@ -0,0 +1,198 @@
<?php
if ( !class_exists( 'SM_XML_Search' ) ){
class SM_XML_Search{
// Register hook to perform the search
function sm_xml_search() {
add_action( 'template_redirect', array( &$this, 'init_search' ) );
}
// Inits the search process. Collects default options, search options, and queries DB
function init_search() {
if ( isset( $_GET['sm-xml-search'] ) ) {
global $wpdb, $simple_map;
remove_filter( 'the_title', 'at_title_check' );
$defaults = array(
'lat' => false,
'lng' => false,
'radius' => false,
'namequery' => false,
'query_type' => 'distance',
'address' => false,
'city' => false,
'state' => false,
'zip' => false,
'onlyzip' => false,
'country' => false,
'limit' => false,
'pid' => 0,
);
$input = array_filter( array_intersect_key( $_GET, $defaults ) ) + $defaults;
$smtaxes = array();
if ( $taxonomies = get_object_taxonomies( 'sm-location' ) ) {
foreach ( $taxonomies as $key => $tax ) {
$phpsafe = str_replace( '-', '_', $tax );
$_GET += array( $phpsafe => '' );
$smtaxes[$tax] = $_GET[$phpsafe];
}
}
// Define my empty strings
$distance_select = $distance_having = $distance_order = '';
// We're going to do a hard limit to 5000 for now.
if ( !$input['limit'] || $input['limit'] > 250 )
$limit = "LIMIT 250";
else
$limit = 'LIMIT ' . absint( $input['limit'] );
$limit = apply_filters( 'sm-xml-search-limit', $limit );
// Locations within specific distance or just get them all?
$distance_select = $wpdb->prepare( "( 3959 * ACOS( COS( RADIANS(%s) ) * COS( RADIANS( lat_tbl.meta_value ) ) * COS( RADIANS( lng_tbl.meta_value ) - RADIANS(%s) ) + SIN( RADIANS(%s) ) * SIN( RADIANS( lat_tbl.meta_value ) ) ) ) AS distance", $input['lat'], $input['lng'], $input['lat'] ) . ', ';
$distance_order = 'distance, ';
if ( $input['radius'] ) {
$input['radius'] = ( $input['radius'] < 1 ) ? 1 : $input['radius'];
$distance_having = $wpdb->prepare( "HAVING distance < %d", $input['radius'] );
}
$i = 1;
$taxonomy_join = '';
foreach ( array_filter( $smtaxes ) as $taxonomy => $tax_value ) {
$term_ids = explode( ',', $tax_value );
if ( $term_ids[0] == 'OR' ) {
unset( $term_ids[0] );
if ( empty( $term_ids ) ) {
continue;
}
$search_values = array( "IN (" . vsprintf( '%d' . str_repeat( ',%d', count( $term_ids ) - 1 ), $term_ids ) . ")" );
} else {
$search_values = array();
foreach ( $term_ids as $term_id ) {
$search_values[] = sprintf( '= %d', $term_id );
}
}
foreach ( $search_values as $search_value ) {
$taxonomy_join .= "
INNER JOIN
$wpdb->term_relationships AS term_rel_$i ON posts.ID = term_rel_$i.object_id
INNER JOIN
$wpdb->term_taxonomy AS tax_$i ON
term_rel_$i.term_taxonomy_id = tax_$i.term_taxonomy_id
AND tax_$i.taxonomy = '$taxonomy'
AND tax_$i.term_id $search_value
";
$i++;
}
}
$sql = "SELECT
lat_tbl.meta_value AS lat,
lng_tbl.meta_value AS lng,
$distance_select
posts.ID,
posts.post_content,
posts.post_title
FROM
$wpdb->posts AS posts
INNER JOIN
$wpdb->postmeta lat_tbl ON lat_tbl.post_id = posts.ID AND lat_tbl.meta_key = 'location_lat'
INNER JOIN
$wpdb->postmeta lng_tbl ON lng_tbl.post_id = posts.ID AND lng_tbl.meta_key = 'location_lng'
$taxonomy_join
WHERE
posts.post_type = 'sm-location'
AND posts.post_status = 'publish'
GROUP BY
posts.ID
$distance_having
ORDER BY " . apply_filters( 'sm-location-sort-order', $distance_order . ' posts.post_name ASC', $input ) . " " . $limit;
$sql = apply_filters( 'sm-xml-search-locations-sql', $sql );
// TODO: Consider using this to generate the marker node attributes in print_xml().
$location_field_map = array(
'location_address' => 'address',
'location_address2' => 'address2',
'location_city' => 'city',
'location_state' => 'state',
'location_zip' => 'zip',
'location_country' => 'country',
'location_phone' => 'phone',
'location_fax' => 'fax',
'location_email' => 'email',
'location_url' => 'url',
'location_special' => 'special',
);
$options = $simple_map->get_options();
$show_permalink = !empty( $options['enable_permalinks'] );
if ( $locations = $wpdb->get_results( $sql ) ) {
// Start looping through all locations i found in the radius
foreach ( $locations as $key => $value ) {
// Add postmeta data to location
$custom_fields = get_post_custom( $value->ID );
foreach ( $location_field_map as $key => $field ) {
if ( isset( $custom_fields[$key][0] ) ) {
$value->$field = $custom_fields[$key][0];
}
else {
$value->$field = '';
}
}
$value->postid = $value->ID;
$value->name = apply_filters( 'the_title', $value->post_title );
$the_content = trim( $value->post_content );
if ( !empty( $the_content ) ) {
$the_content = apply_filters( 'the_content', $the_content );
}
$value->description = $the_content;
$value->permalink = '';
if ( $show_permalink ) {
$value->permalink = get_permalink( $value->ID );
$value->permalink = apply_filters( 'the_permalink', $value->permalink );
}
// List all terms for all taxonomies for this post
$value->taxes = array();
foreach ( $smtaxes as $taxonomy => $tax_value ) {
$phpsafe_tax = str_replace( '-', '_', $taxonomy );
$local_tax_names = '';
// Get all taxes for this post
if ( $local_taxes = wp_get_object_terms( $value->ID, $taxonomy, array( 'fields' => 'names' ) ) ) {
$local_tax_names = implode( ', ', $local_taxes );
}
$value->taxes[$phpsafe_tax] = $local_tax_names;
}
}
} else {
// Print empty XML
$locations = array();
}
$locations = apply_filters( 'sm-xml-search-locations', $locations );
$this->print_json( $locations, $smtaxes );
}
}
// Prints the JSON output
function print_json( $dataset, $smtaxes ) {
header( 'Status: 200 OK', false, 200 );
header( 'Content-type: application/json' );
do_action( 'sm-xml-search-headers' );
do_action( 'sm-print-json', $dataset, $smtaxes );
echo json_encode( $dataset );
die();
}
}
}