.
*******************************************************************************/
/**
*
*/
class ASException extends Exception {
}
/**
*
*/
class AgentStorm {
/**
* Register the Custom CSS Styles and Javascript used on the Admin pages
*/
function adminInit() {
wp_register_script('AgentStormJqueryUI', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js', array('jquery'));
wp_register_style('AgentStormDefault', WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/css/default.css');
wp_register_style('AgentStormJqueryUI', WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/css/custom.css');
$this->detectSEOPlugins();
}
/**
* Register the Admin Menu Item and add the action to load the admin styles when the page is requested
*/
function adminRegisterMenu() {
$page = add_menu_page('Agent Storm', 'Agent Storm', 'administrator', __FILE__, array(&$this, 'displayAdmin'), WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/images/icon.png');
add_action('admin_print_styles-' . $page, array($this, 'adminLoadStyles'));
}
/**
* Enqueue the CSS and Javascript used on the admin pages to be loaded.
*/
function adminLoadStyles() {
wp_enqueue_script("AgentStormJqueryUI");
wp_enqueue_style('AgentStormDefault');
wp_enqueue_style('AgentStormJqueryUI');
}
/**
* Detect various free SEO Plugins and check they are correctly configured to
* not process generated idx plugins
*/
function detectSEOPlugins() {
// If All In One SEO Pack is detected lets check we are configured not to
// process generate IDX pages
//
if (class_exists('All_in_One_SEO_Pack')) {
$aioseop = get_option('aioseop_options', array());
if (array_key_exists('aiosp_ex_pages', $aioseop)) {
$match = false;
foreach (explode(',', $aioseop['aiosp_ex_pages']) as $item) {
if (!empty($item) && substr('/' . get_option('as_idx_propertyprefix'), 0, strlen($item)) == $item) {
$match = true;
}
}
if (!$match) {
wp_cache_set('agentstorm_admin_notice', 'Agent Storm All In One SEO Pack was detected but does not appear to be correctly configured for use with Agent Storm. Search Engine Optimization may be compromized as a result. For more information see http://support.agentstorm.com/faqs/wordpress/wordpress-seo-plugin-compatibility');
add_action( 'admin_notices', array(&$this, 'displayAdminNotices'));
}
}
}
}
function displayAdminNotices() {
echo '
' . wp_cache_get('agentstorm_admin_notice') . '
';
}
/**
* Enqueue the CSS and Javascript used on the IDX pages
*/
function loadSiteStyles() {
// Require jQuery
//
wp_enqueue_script("jquery");
// Register the Javascript files
//
wp_register_script('jQueryCarosel', WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/js/jquery.jcarousel.min.js');
wp_register_script('jQueryPikachoose', WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/js/jquery.pikachoose.4.js');
wp_register_script('AgentStormGallery', WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/js/as.gallery-init.js');
wp_register_script('GoogleMaps', 'http://maps.google.com/maps/api/js?sensor=false®ion=US"');
// Register the Site Default Styles
//
wp_register_style('AgentStormSite', WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/css/site.css');
wp_register_style('AgentStormSiteRed', WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/css/site-red.css');
wp_register_style('AgentStormSiteBlue', WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/css/site-blue.css');
wp_register_style('AgentStormSiteGrey', WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/css/site-grey.css');
wp_register_style('AgentStormSiteBrown', WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/css/site-brown.css');
wp_register_style('jQueryPikachooseCSS', WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/css/styles.css');
wp_register_style('jQueryPikachooseSkin', WP_PLUGIN_URL . DIRECTORY_SEPARATOR . array_pop(explode('/', dirname(__FILE__))) . '/static/css/skin.css');
// Add the correct built in stylesheets
//
switch (get_option('as_usestyle', '')) {
case '1':
wp_enqueue_style('AgentStormSite');
break;
case '2':
wp_enqueue_style('AgentStormSite');
wp_enqueue_style('AgentStormSiteRed');
break;
case '3':
wp_enqueue_style('AgentStormSite');
wp_enqueue_style('AgentStormSiteBlue');
break;
case '4':
wp_enqueue_style('AgentStormSite');
wp_enqueue_style('AgentStormSiteGrey');
break;
case '5':
wp_enqueue_style('AgentStormSite');
wp_enqueue_style('AgentStormSiteBrown');
break;
}
// Add the required Javascript files
//
wp_enqueue_script('jQueryCarosel');
wp_enqueue_script('jQueryPikachoose');
wp_enqueue_script('AgentStormGallery');
wp_enqueue_script('GoogleMaps');
// Add the CSS Files
//
wp_enqueue_style('jQueryPikachooseCSS');
wp_enqueue_style('jQueryPikachooseSkin');
}
/**
* Add various SEO headers such as the canonical link if we need to.
*/
function siteHead() {
if (wp_cache_get('agentstorm_canonical')) {
echo '';
}
}
/**
* Helper function to check if we have a valid API key and hostname
*/
function isConfigured() {
return (get_option('as_hostname', false) && get_option('as_apikey', false));
}
/**
* Display the Admin page used to configure the plug-in
*/
function displayAdmin() {
if (!empty($_POST)) {
$this->saveAdmin();
}
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_admin.php';
}
/**
* Called on Form Postback to save the admin settings
*/
function saveAdmin() {
$as = new AgentStormRequest(get_option('as_hostname'), get_option('as_apikey'));
// Save the Settings Variables
//
if (isset($_POST['as_settings_save'])) {
// Save the Options
//
if (isset($_POST['as_usestyle'])) {
update_option('as_usestyle', $_POST['as_usestyle']);
}
if (isset($_POST['as_hostname'])) {
update_option('as_hostname', $_POST['as_hostname']);
}
if (isset($_POST['as_apikey'])) {
update_option('as_apikey', $_POST['as_apikey']);
}
// Force and Update of the Cities database
//
$as_tags = $as->getTags();
update_option('as_tags', $as_tags->Tags);
// Force update of the Property Metadata
//
$as_metadata = $as->getPropertyMetaData();
update_option('as_metadata', $as_metadata->MetaData);
// If we have previously selected a tag and it does not exist in the current
// dataset (maybe we switched hostnames) then reset the flag.
//
if (get_option('as_idx_settings_tag', '') != '') {
$tag_exists = false;
foreach ($as_tags->Tags as $tag) {
if (get_option('as_idx_settings_tag', '') == $tag->Name) {
$tag_exists = true;
}
}
if (!$tag_exists) update_option('as_idx_settings_tag', '');
}
// Get the cities
//
update_option('as_cities', $as->getCities());
// Schedule the Cities and Tags caches to be refreshed hourly
//
agentstorm_hourly();
}
// Save the Contact Manager Settings
//
if (isset($_POST['as_contact_save'])) {
if (isset($_POST['as_contact_emailnotification'])) {
update_option('as_contact_emailnotification', true);
} else {
update_option('as_contact_emailnotification', false);
}
if (isset($_POST['as_contact_tags'])) {
update_option('as_contact_tags', $_POST['as_contact_tags']);
}
if (isset($_POST['as_contact_source'])) {
update_option('as_contact_source', $_POST['as_contact_source']);
}
}
// Save the IDX Data Settings
//
if (isset($_POST['as_idx_save'])) {
if (isset($_POST['as_idx_template_result'])) {
update_option('as_idx_template_result', $_POST['as_idx_template_result']);
}
if (isset($_POST['as_idx_template_property'])) {
update_option('as_idx_template_property', $_POST['as_idx_template_property']);
}
if (isset($_POST['as_idx_template_noresults'])) {
update_option('as_idx_template_noresults', $_POST['as_idx_template_noresults']);
}
if (isset($_POST['as_idx_seo'])) {
update_option('as_idx_seo', true);
} else {
update_option('as_idx_seo', false);
}
if (isset($_POST['as_idx_schools'])) {
update_option('as_idx_schools', true);
} else {
update_option('as_idx_schools', false);
}
if (isset($_POST['as_idx_gmap'])) {
update_option('as_idx_gmap', true);
} else {
update_option('as_idx_gmap', false);
}
if (isset($_POST['as_idx_bview'])) {
update_option('as_idx_bview', true);
} else {
update_option('as_idx_bview', false);
}
if (isset($_POST['as_idx_walkscore'])) {
update_option('as_idx_walkscore', $_POST['as_idx_walkscore']);
}
if (isset($_POST['as_idx_searchtxt'])) {
update_option('as_idx_searchtxt', $_POST['as_idx_searchtxt']);
}
}
// Save the IDX Data Settings
//
if (isset($_POST['as_idx_settings_save'])) {
if (isset($_POST['as_idx_settings_field_type'])) {
update_option('as_idx_settings_field_type', true);
} else {
update_option('as_idx_settings_field_type', false);
}
if (isset($_POST['as_idx_settings_field_suburbzip'])) {
update_option('as_idx_settings_field_suburbzip', true);
} else {
update_option('as_idx_settings_field_suburbzip', false);
}
if (isset($_POST['as_idx_settings_field_price'])) {
update_option('as_idx_settings_field_price', true);
} else {
update_option('as_idx_settings_field_price', false);
}
if (isset($_POST['as_idx_settings_field_bedrooms'])) {
update_option('as_idx_settings_field_bedrooms', true);
} else {
update_option('as_idx_settings_field_bedrooms', false);
}
if (isset($_POST['as_idx_settings_field_bathrooms'])) {
update_option('as_idx_settings_field_bathrooms', true);
} else {
update_option('as_idx_settings_field_bathrooms', false);
}
if (isset($_POST['as_idx_settings_field_lotsize'])) {
update_option('as_idx_settings_field_lotsize', true);
} else {
update_option('as_idx_settings_field_lotsize', false);
}
if (isset($_POST['as_idx_settings_field_size'])) {
update_option('as_idx_settings_field_size', true);
} else {
update_option('as_idx_settings_field_size', false);
}
if (isset($_POST['as_idx_settings_field_shortsale'])) {
update_option('as_idx_settings_field_shortsale', true);
} else {
update_option('as_idx_settings_field_shortsale', false);
}
if (isset($_POST['as_idx_settings_field_foreclosure'])) {
update_option('as_idx_settings_field_foreclosure', true);
} else {
update_option('as_idx_settings_field_foreclosure', false);
}
if (isset($_POST['as_idx_settings_classes_res'])) {
update_option('as_idx_settings_classes_res', true);
} else {
update_option('as_idx_settings_classes_res', false);
}
if (isset($_POST['as_idx_settings_classes_com'])) {
update_option('as_idx_settings_classes_com', true);
} else {
update_option('as_idx_settings_classes_com', false);
}
if (isset($_POST['as_idx_settings_classes_lnd'])) {
update_option('as_idx_settings_classes_lnd', true);
} else {
update_option('as_idx_settings_classes_lnd', false);
}
if (isset($_POST['as_idx_settings_classes_mob'])) {
update_option('as_idx_settings_classes_mob', true);
} else {
update_option('as_idx_settings_classes_mob', false);
}
if (isset($_POST['as_idx_settings_classes_mfh'])) {
update_option('as_idx_settings_classes_mfh', true);
} else {
update_option('as_idx_settings_classes_mfh', false);
}
if (isset($_POST['as_idx_settings_classes_rnt'])) {
update_option('as_idx_settings_classes_rnt', true);
} else {
update_option('as_idx_settings_classes_rnt', false);
}
if (isset($_POST['as_idx_settings_pagelimit'])) {
update_option('as_idx_settings_pagelimit', $_POST['as_idx_settings_pagelimit']);
}
if (isset($_POST['as_idx_settings_tag'])) {
if (get_option('as_idx_settings_tag') !== $_POST['as_idx_settings_tag']) {
update_option('as_idx_settings_tag', $_POST['as_idx_settings_tag']);
update_option('as_cities', $as->getCities());
}
}
}
// Save the Agent Information
//
if (isset($_POST['as_idx_agent_save'])) {
if (isset($_POST['as_idx_agent_name'])) {
update_option('as_idx_agent_name', $_POST['as_idx_agent_name']);
}
if (isset($_POST['as_idx_agent_phone'])) {
update_option('as_idx_agent_phone', $_POST['as_idx_agent_phone']);
}
if (isset($_POST['as_idx_agent_email'])) {
update_option('as_idx_agent_email', $_POST['as_idx_agent_email']);
}
if (isset($_POST['as_idx_agent_extra'])) {
update_option('as_idx_agent_extra', $_POST['as_idx_agent_extra']);
}
}
// Save the IDX Data Settings
//
if (isset($_POST['as_idx_permalinks_save'])) {
if (isset($_POST['as_idx_searchprefix'])) {
update_option('as_idx_searchprefix', $_POST['as_idx_searchprefix']);
}
if (isset($_POST['as_idx_propertyprefix'])) {
update_option('as_idx_propertyprefix', $_POST['as_idx_propertyprefix']);
}
if (isset($_POST['as_idx_stateurlprefix'])) {
update_option('as_idx_stateurlprefix', $_POST['as_idx_stateurlprefix']);
}
if (isset($_POST['as_idx_cityurlprefix'])) {
update_option('as_idx_cityurlprefix', $_POST['as_idx_cityurlprefix']);
}
}
//
//
if (isset($_POST['as_install_templates'])) {
$this->installTemplates();
}
}
/**
* AJAX function that saves the display fields and their order
*/
function saveResultLayout() {
// Loop through the metadata and for each property type, if it has been passed, save the new order
//
foreach (get_option('as_metadata', array()) as $metadata) {
if (array_key_exists($metadata->id, $_POST)) {
update_option('as_metadata_' . $metadata->id . '_' . $_POST['target'], implode(',', $_POST[$metadata->id]));
foreach ($_POST[$metadata->id] as $field) {
if (!empty($_POST[$metadata->id . '_' . $field])) {
update_option('as_fields_' . $metadata->id . '_' . $field, $_POST[$metadata->id . '_' . $field]);
} else {
delete_option('as_fields_' . $metadata->id . '_' . $field);
}
}
}
}
}
/**
* Install the default Templates
*/
function installTemplates() {
// Check if the default templates already exist
//
$exists = false;
$d = @dir(TEMPLATEPATH);
while(false !== ($entry = $d->read())) {
if($entry == "agentstorm_results.php") {
$exists = true;
}
}
// If the Templates dont exist install them
//
if (!$exists) {
// Install the Result Template
copy(WP_PLUGIN_DIR . '/agent-storm/agentstorm_example_result.php', TEMPLATEPATH . '/agentstorm_result.php');
update_option('as_idx_template_result', 'agentstorm_result.php');
// Install the Property Template
copy(WP_PLUGIN_DIR . '/agent-storm/agentstorm_example_property.php', TEMPLATEPATH . '/agentstorm_property.php');
update_option('as_idx_template_property', 'agentstorm_property.php');
// Install the No Results Template
copy(WP_PLUGIN_DIR . '/agent-storm/agentstorm_example_noresults.php', TEMPLATEPATH . '/agentstorm_noresults.php');
update_option('as_idx_template_noresults', 'agentstorm_noresults.php');
}
}
/**
*
*/
static function getOneLiner() {
$one_liners = array(
'Our IDX Plugin is causing a storm in Real Estate.',
'Storm Repairs? Check out our Support Site!'
);
return $one_liners[array_rand($one_liners, 1)];
}
}
class AgentStormIDX extends stdClass {
public $wp = null;
public $var1 = '';
public $var2 = '';
public $var3 = '';
public $title = '';
/**
* On each page load check if the request relates to a IDX page, if so,
* override the page so the correct IDX page is returned
*/
function init(&$wp) {
// Keep a copy of the $wp variable for later use
//
$this->wp = $wp;
// Get the URL of the current request
//
$path = $this->wp->request;
$groups = array();
// Parse the current url against the known Permalinks for each page type
//
$property_url = $this->parseUrl('as_idx_propertyprefix');
if (!$property_url) $property_url = $this->parseUrl('as_idx_cityurlprefix');
if (!$property_url) $property_url = $this->parseUrl('as_idx_stateurlprefix');
// Get the URL of the search page
//
$search_url = trim(get_option('as_idx_searchprefix'), '/');
// If we have match against a SEO page..
//
if (!empty($property_url)) {
$this->var1 = str_replace('-', ' ', $property_url['state']);
$this->var2 = str_replace('-', ' ',$property_url['city']);
$this->var3 = str_replace('-', ' ',$property_url['id']);
if (!empty($this->var1) || !empty($this->var2) || !empty($this->var3)) {
$this->clearActions();
add_filter('the_posts', array(&$this, 'seoFilter'));
add_filter('wp_title', array(&$this, 'seoTitle'));
add_action('template_redirect', array(&$this, 'seoPage'));
}
// If we have a match for the search page...
//
} elseif (preg_match("/" . preg_quote($search_url, '/') . "\/?/", $path, $groups)) {
$this->clearActions();
add_filter('the_posts', array(&$this, 'searchFilter'));
add_filter('wp_title', array(&$this, 'searchTitle'));
add_action('template_redirect', array(&$this, 'searchPage'));
}
// Register the IDX Short codes
//
add_shortcode('agentstorm', array(&$this, 'addShortCode'));
}
/**
* Clears all wordpress query vars if we are in a dynamic idx page, prevents
* 404 errors being returned by Wordpress
*/
function processQueryVars($qv) {
$property_url = $this->parseUrl('as_idx_propertyprefix');
if (!$property_url) $property_url = $this->parseUrl('as_idx_cityurlprefix');
if (!$property_url) $property_url = $this->parseUrl('as_idx_stateurlprefix');
$search_url = trim(get_option('as_idx_searchprefix'), '/');
if (!empty($property_url) || preg_match("/" . preg_quote($search_url, '/') . "\/?/", $path)) {
return;
}
return $qv;
}
/**
* Remove various headers which could incorrectly report the page to SE's
*/
function clearActions() {
remove_action('wp_head','feed_links_extra');
remove_action('wp_head','rsd_link');
remove_action('wp_head','wlwmanifest_link');
remove_action('wp_head','index_rel_link');
remove_action('wp_head','parent_post_rel_link');
remove_action('wp_head','start_post_rel_link');
remove_action('wp_head','prev_post_rel_link');
remove_action('wp_head','adjacent_posts_rel_link_wp_head');
remove_action('wp_head','noindex');
remove_action('wp_head','wp_generator');
remove_action('wp_head','rel_canonical');
}
/**
* Process a short code is included on the current page
*/
function addShortCode($atts) {
// Extract the short code options into php variables
//
extract(shortcode_atts(array(
'template' => 'large',
'show_pager' => false,
'show_map' => false,
'show_count' => false,
'agent_id' => '',
'mls_number' => '',
'city' => '',
'subdivision' => '',
'beds' => '',
'baths' => '',
'zip' => '',
'price' => '',
'lotsqft' => '',
'sqft' => '',
'shortsale' => '',
'foreclosure' => '',
'waterfrontlocation' => '',
'sort' => 'ListPrice',
'sort_direction' => 'DESC',
'limit' => 5
), $atts));
// Process the template
//
$file = '';
switch ($template) {
// Simple search interface
//
case 'small':
$file = 'agentstorm_searchsmall.php';
break;
// Tabbed search interface
//
case 'tabbed':
$file = 'agentstorm_searchtabbed.php';
break;
// Latest Properties
//
case 'latest':
$sort = 'ModificationTimestamp';
$sort_direction = 'DESC';
// Short code Searches
//
case 'search':
$as = new AgentStormRequest(get_option('as_hostname'), get_option('as_apikey'));
$filters = array();
if (!empty($agent_id)) $filters['AgentId'] = $agent_id;
if (!empty($mls_number)) $filters['ListingId'] = $mls_number;
if (!empty($city)) $filters['City'] = $city;
if (!empty($subdivision)) $filters['SubDivision'] = $subdivision;
if (!empty($beds)) $filters['Bedrooms'] = $beds;
if (!empty($baths)) $filters['FullBaths'] = $baths;
if (!empty($zip)) $filters['Zip'] = $zip;
if (!empty($price)) $filters['ListPrice'] = $price;
if (!empty($lotsqft)) $filters['LotSqFt'] = $lotsqft;
if (!empty($sqft)) $filters['SqFt'] = $sqft;
if (!empty($shortsale)) $filters['IsShortSale'] = 'Y';
if (!empty($foreclosure)) $filters['IsForeclosure'] = 'Y';
if (!empty($waterfrontlocation)) $filters['WaterFrontLocation'] = $waterfrontlocation;
if (!empty($sort)) $filters['sort'] = $sort;
if (!empty($sort_direction)) $filters['sort_direction'] = $sort_direction;
if (!empty($limit)) $filters['limit'] = $limit;
if (array_key_exists('offset', $_GET)) $filters['offset'] = $_GET['offset'];
$properties = $as->getProperties($filters);
$results = $properties->Properties;
$file = 'agentstorm_results.php';
break;
default:
$file = 'agentstorm_search.php';
break;
}
ob_start();
include dirname(__FILE__) . DIRECTORY_SEPARATOR . $file;
$page_content = ob_get_contents();
ob_end_clean();
return $page_content;
}
function getUrlRegex($url_option_name) {
$regex = preg_quote(trim(get_option($url_option_name), '/'), '/');
$regex = str_replace('%state%', '([a-zA-Z- ]+)', $regex);
$regex = str_replace('%city%', '([a-zA-Z0-9- ]+)', $regex);
$regex = str_replace('%id%', '([0-9]+)', $regex);
$regex = str_replace('%full_address%', '([a-zA-Z0-9-]+)', $regex);
$regex = str_replace('%subdivision%', '([a-zA-Z0-9- ]+)', $regex);
return $regex;
}
function parseUrl($url_option_name) {
$return = array();
$empty = true;
$regex = $this->getUrlRegex($url_option_name);
preg_match_all('/(%[a-zA-Z_]+%)/', get_option($url_option_name), $regex_matches, PREG_OFFSET_CAPTURE);
preg_match_all('/' . $regex . '/', urldecode($this->wp->request), $url_matches);
foreach ($regex_matches[0] as $key => $match) {
if (!empty($url_matches[$key + 1][0])) {
$return[str_replace('%', '', $match[0])] = $url_matches[$key + 1][0];
$empty = false;
}
}
return ($empty) ? false : $return;
}
function getPermalink($url, $property) {
if (isset($property->State)) $url = str_replace('%state%', agentstorm_slugify($property->State), $url);
if (isset($property->City)) $url = str_replace('%city%', agentstorm_slugify($property->City), $url);
if (isset($property->Id)) $url = str_replace('%id%', agentstorm_slugify($property->Id), $url);
if (isset($property->FullAddress)) $url = str_replace('%full_address%', agentstorm_slugify($property->FullAddress), $url);
if (isset($property->SubDivision)) $url = str_replace('%subdivision%', agentstorm_slugify($property->SubDivision), $url);
return $url;
}
function getPropertyPermalink($property) {
return $this->getPermalink(get_bloginfo('url', 'display') . '/' . get_option('as_idx_propertyprefix'), $property);
}
function getStatePermalink($property) {
return $this->getPermalink(get_bloginfo('url', 'display') . '/' . get_option('as_idx_stateurlprefix'), $property);
}
function getCityPermalink($property) {
return $this->getPermalink(get_bloginfo('url', 'display') . '/' . get_option('as_idx_cityurlprefix'), $property);
}
function seoFilter($posts) {
$results = null;
$query = array();
$offset = (array_key_exists('offset', $_GET)) ? $_GET['offset'] : '0';
$limit = get_option('as_idx_pagelimit');
$as = new AgentStormRequest(trim(get_option('as_hostname')), trim(get_option('as_apikey')));
if (!empty($this->var3) && is_numeric($this->var3)) {
$properties = $as->getProperty($this->var3);
} elseif (!empty($this->var1) && !empty($this->var2)) {
$properties = $as->getProperties(array(
'State' => $this->var1,
'City' => $this->var2,
'limit' => get_option('as_idx_pagelimit', 10),
'offset' => $offset
));
} elseif (!empty($this->var1) && empty($this->var2)) {
$properties = $as->getProperties(array(
'State' => $this->var1,
'limit' => get_option('as_idx_pagelimit', 10),
'offset' => $offset
));
}
$results = $properties->Properties;
$state = $this->var1;
$city = $this->var2;
// Cache the results so we can easily retrieve them if a custom page template is selected
//
wp_cache_set('as_result_properties', $properties->Properties);
wp_cache_set('as_result_count', $properties->Count);
wp_cache_set('as_result_totalcount', $properties->TotalCount);
if (sizeof($results) == 0) {
$this->title = _('Properties for Sale in ');
$this->title .= (!empty($city)) ? ucwords(strtolower($city)) . ', ' : '';
$this->title .= (strlen($state) == 2) ? strtoupper($state) : ucwords(strtolower($state));
wp_cache_set('as_result_pagetype', 'noresults');
// Build the Response
//
ob_start();
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_noresults.php';
$page_content = ob_get_contents();
ob_end_clean();
} elseif (sizeof($results) == 1) {
$result = $results[0];
$this->title = $result->FullAddress . ', ' . ucwords(strtolower($result->City)) . ', ' . ((strlen($result->State) == 2) ? strtoupper($result->State) : ucwords(strtolower($result->State))) . '. ' . $result->Zip;
wp_cache_set('as_result_pagetype', 'property');
// We want to set the correct canoninal for individual properties
//
wp_cache_set('agentstorm_canonical', $this->getPropertyPermalink($result));
// Get the Walkscore
//
if (get_option('as_idx_walkscore')) {
$walkscore = @json_decode(@file_get_contents('http://api.walkscore.com/score?format=json&address=' . urlencode($result->StreetNumber . ' ' . $result->StreetPrefix . ' ' . $result->StreetName . ' ' . $result->StreetSuffix . ' ' . $result->City . ' ' . $result->State . ' ' . $result->Zip) . '&lat=' . $result->Latitude . '&lon=' . $result->Longitude . '&wsapikey=' . get_option('as_idx_walkscore')));
}
// Build the Response
//
ob_start();
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_result.php';
$page_content = ob_get_contents();
ob_end_clean();
} else {
$this->title = _('Properties for Sale in ');
$this->title .= (!empty($city)) ? ucwords($city) . ', ' : '';
$this->title .= ((strlen($state) == 2) ? strtoupper($state) : ucwords(strtolower($state)));
wp_cache_set('as_result_pagetype', 'results');
// Build the Response
//
ob_start();
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_results.php';
$page_content = ob_get_contents();
ob_end_clean();
}
return array(new AgentStormPage(-1, $this->title, $page_content));
}
function seoTitle() {
return $this->title . ' - ';
}
function seoPage() {
$results = wp_cache_get('as_result_properties');
$count = wp_cache_get('as_result_count');
$totalcount = wp_cache_get('as_result_totalcount');
switch (wp_cache_get('as_result_pagetype')) {
case 'noresults':
include(TEMPLATEPATH . '/' . get_option('as_idx_template_noresults', 'page.php'));
break;
case 'property':
include(TEMPLATEPATH . '/' . get_option('as_idx_template_property', 'page.php'));
break;
case 'results':
include(TEMPLATEPATH . '/' . get_option('as_idx_template_result', 'page.php'));
break;
default:
include(TEMPLATEPATH . '/page.php');
}
exit;
}
function searchFilter($post) {
$as = new AgentStormRequest(trim(get_option('as_hostname')), trim(get_option('as_apikey')));
$query = array();
if ($_GET['as_searchwidget_submit']) {
// MLS Number
//
if (isset($_GET['as_mlsnumber']) && !empty($_GET['as_mlsnumber'])) {
$query['ListingId'] = $_GET['as_mlsnumber'];
}
// Property Type
//
if (isset($_GET['as_propertytype']) && !empty($_GET['as_propertytype'])) {
$query['Type'] = $_GET['as_propertytype'];
}
// Zip Code / Suburb
//
if (isset($_GET['as_suburbzip']) && !empty($_GET['as_suburbzip'])) {
if (preg_match("/^[0-9]{5}$/", $_GET['as_suburbzip'])) {
$query['Zip'] = $_GET['as_suburbzip'];
} else {
$query['City'] = $_GET['as_suburbzip'];
}
}
// Price High to Low Handler
//
if (isset($_GET['as_pricerange_min']) && isset($_GET['as_pricerange_max']) && $_GET['as_pricerange_min'] > 0 && $_GET['as_pricerange_max'] > 0) {
$query['ListPrice'] = $_GET['as_pricerange_min'] . ':' . $_GET['as_pricerange_max'];
} elseif (isset($_GET['as_pricerange_min']) && $_GET['as_pricerange_min'] > 0) {
$query['ListPrice'] = $_GET['as_pricerange_min'] . '+';
} elseif (isset($_GET['as_pricerange_max']) && $_GET['as_pricerange_max'] > 0) {
$query['ListPrice'] = $_GET['as_pricerange_max'] . '-';
}
// Lot Size Handler
//
if (isset($_GET['as_lotsize_min']) && isset($_GET['as_lotsize_max']) && $_GET['as_lotsize_min'] > 0 && $_GET['as_lotsize_max'] > 0) {
$query['LotSqft'] = $_GET['as_lotsize_min'] . ':' . $_GET['as_lotsize_max'];
} elseif (isset($_GET['as_lotsize_min']) && $_GET['as_lotsize_min'] > 0) {
$query['LotSqft'] = $_GET['as_lotsize_min'] . '+';
} elseif (isset($_GET['as_lotsize_max']) && $_GET['as_lotsize_max'] > 0) {
$query['LotSqft'] = $_GET['as_lotsize_max'] . '-';
}
// Size Handler
//
if (isset($_GET['as_size_min']) && isset($_GET['as_size_max']) && $_GET['as_size_min'] > 0 && $_GET['as_size_max'] > 0) {
$query['Sqft'] = $_GET['as_size_min'] . ':' . $_GET['as_size_max'];
} elseif (isset($_GET['as_size_min']) && $_GET['as_size_min'] > 0) {
$query['Sqft'] = $_GET['as_size_min'] . '+';
} elseif (isset($_GET['as_size_max']) && $_GET['as_size_max'] > 0) {
$query['Sqft'] = $_GET['as_size_max'] . '-';
}
// Bedrooms
//
if (isset($_GET['as_bedrooms']) && !empty($_GET['as_bedrooms'])) {
$query['Bedrooms'] = $_GET['as_bedrooms'];
}
// Bathrooms
//
if (isset($_GET['as_bathrooms']) && !empty($_GET['as_bathrooms'])) {
$query['FullBathrooms'] = $_GET['as_bathrooms'];
}
// City Search
if (isset($_GET['as_city'])) {
$query['City'] = $_GET['as_city'];
}
// Short Sale Search
if (isset($_GET['as_shortsale'])) {
$query['IsShortSale'] = 'Y';
}
// Foreclosure/Bank Owned Search
if (isset($_GET['as_foreclosure'])) {
$query['IsForeclosure'] = 'Y';
}
// Paging
//
$offset = 0;
if (isset($_GET['offset'])) {
$query['offset'] = $offset = $_GET['offset'];
}
// Sort
//
if (isset($_GET['sort'])) {
$query['FullBathrooms'] = $_GET['sort'];
}
// Limit
//
$limit = $query['limit'] = get_option('as_idx_settings_pagelimit', 10);
// Query the API and get the Results for the search
//
$properties = $as->getProperties($query);
$this->title = _('Search Results');
// Cache the results so we can easily retrieve them if a custom page template is selected
//
wp_cache_set('as_result_properties', $properties->Properties);
wp_cache_set('as_result_count', $properties->Count);
wp_cache_set('as_result_totalcount', $properties->TotalCount);
$results = $properties->Properties;
if (sizeof($results) == 0) {
wp_cache_set('as_result_pagetype', 'noresults');
// Build the Response
//
ob_start();
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_noresults.php';
$page_content = ob_get_contents();
ob_end_clean();
} elseif (sizeof($results) == 1) {
$result = $results[0];
wp_cache_set('as_result_pagetype', 'property');
// We want to set the correct canoninal for individual properties
//
wp_cache_set('agentstorm_canonical', $this->getPropertyPermalink($result));
// Build the Response
//
ob_start();
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_result.php';
$page_content = ob_get_contents();
ob_end_clean();
} else {
wp_cache_set('as_result_pagetype', 'results');
// Build the Response
//
ob_start();
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_results.php';
$page_content = ob_get_contents();
ob_end_clean();
}
} else {
$this->title = _('Property Search');
// Build the Response
//
ob_start();
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_search.php';
$page_content = ob_get_contents();
ob_end_clean();
}
// Return a dummy page with the result
//
return array(new AgentStormPage(-1, $this->title, $page_content));
}
function searchTitle() {
$this->seoTitle();
}
function searchPage() {
$this->seoPage();
}
}
class AgentStormPagination {
var $base_url = ''; // The page we are linking to
var $total_rows = ''; // Total number of items (database results)
var $per_page = 10; // Max number of items you want shown per page
var $num_links = 2; // Number of "digit" links to show before/after the currently viewed page
var $cur_page = 0; // The current page being viewed
var $first_link = 'First';
var $next_link = '>';
var $prev_link = '<';
var $last_link = 'Last ›';
var $uri_segment = 3;
var $full_tag_open = '';
var $full_tag_close = '';
var $first_tag_open = '';
var $first_tag_close = ' ';
var $last_tag_open = ' ';
var $last_tag_close = '';
var $cur_tag_open = ' ';
var $cur_tag_close = '';
var $next_tag_open = ' ';
var $next_tag_close = ' ';
var $prev_tag_open = ' ';
var $prev_tag_close = '';
var $num_tag_open = ' ';
var $num_tag_close = '';
var $page_query_string = FALSE;
var $query_string_segment = 'per_page';
/**
* Constructor
*
* @access public
* @param array initialization parameters
*/
function AgentStormPagination($params = array())
{
if (count($params) > 0)
{
$this->initialize($params);
}
}
// --------------------------------------------------------------------
/**
* Initialize Preferences
*
* @access public
* @param array initialization parameters
* @return void
*/
function initialize($params = array())
{
if (count($params) > 0)
{
foreach ($params as $key => $val)
{
if (isset($this->$key))
{
$this->$key = $val;
}
}
}
}
// --------------------------------------------------------------------
/**
* Generate the pagination links
*
* @access public
* @return string
*/
function create_links()
{
// If our item count or per-page total is zero there is no need to continue.
if ($this->total_rows == 0 OR $this->per_page == 0)
{
return '';
}
// Calculate the total number of pages
$num_pages = ceil($this->total_rows / $this->per_page);
// Is there only one page? Hm... nothing more to do here then.
if ($num_pages == 1)
{
return '';
}
// Determine the current page number.
$this->num_links = (int)$this->num_links;
if ($this->num_links < 1)
{
echo _('Your number of links must be a positive number.');
}
if ( ! is_numeric($this->cur_page))
{
$this->cur_page = 0;
}
// Is the page number beyond the result range?
// If so we show the last page
if ($this->cur_page > $this->total_rows)
{
$this->cur_page = ($num_pages - 1) * $this->per_page;
}
$uri_page_number = $this->cur_page;
$this->cur_page = floor(($this->cur_page/$this->per_page) + 1);
// Calculate the start and end numbers. These determine
// which number to start and end the digit links with
$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
$end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
// Is pagination being used over GET or POST? If get, add a per_page query
// string. If post, add a trailing slash to the base URL if needed
$this->base_url = $this->base_url;
// And here we go...
$output = '';
// Render the "First" link
if ($this->cur_page > ($this->num_links + 1))
{
$output .= $this->first_tag_open.''.$this->first_link.''.$this->first_tag_close;
}
// Render the "previous" link
if ($this->cur_page != 1)
{
$i = $uri_page_number - $this->per_page;
if ($i == 0) $i = '';
$output .= $this->prev_tag_open.''.$this->prev_link.''.$this->prev_tag_close;
}
// Write the digit links
for ($loop = $start -1; $loop <= $end; $loop++)
{
$i = ($loop * $this->per_page) - $this->per_page;
if ($i >= 0)
{
if ($this->cur_page == $loop)
{
$output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page
}
else
{
$n = ($i == 0) ? '' : $i;
$output .= $this->num_tag_open.''.$loop.''.$this->num_tag_close;
}
}
}
// Render the "next" link
if ($this->cur_page < $num_pages)
{
$output .= $this->next_tag_open.''.$this->next_link.''.$this->next_tag_close;
}
// Render the "Last" link
if (($this->cur_page + $this->num_links) < $num_pages)
{
$i = (($num_pages * $this->per_page) - $this->per_page);
$output .= $this->last_tag_open.''.$this->last_link.''.$this->last_tag_close;
}
// Kill double slashes. Note: Sometimes we can end up with a double slash
// in the penultimate link so we'll kill all double slashes.
$output = preg_replace("#([^:])//+#", "\\1/", $output);
// Add the wrapper HTML if exists
$output = $this->full_tag_open.$output.$this->full_tag_close;
return $output;
}
}
class AgentStormCaptcha {
var $session_key = null;
var $temp_dir = null;
var $width = 160;
var $height = 60;
var $jpg_quality = 15;
/**
* Constructor - Initializes Captcha class!
*
* @param string $session_key
* @param string $temp_dir
* @return captcha
*/
function captcha( $session_key, $temp_dir ) {
$this->session_key = $session_key;
$this->temp_dir = $temp_dir;
}
/**
* Generates Image file for captcha
*
* @param string $location
* @param string $char_seq
* @return unknown
*/
function _generate_image( $location, $char_seq ) {
$num_chars = strlen($char_seq);
$img = imagecreatetruecolor( $this->width, $this->height );
imagealphablending($img, 1);
imagecolortransparent( $img );
// generate background of randomly built ellipses
for ($i=1; $i<=200; $i++)
{
$r = round( rand( 0, 100 ) );
$g = round( rand( 0, 100 ) );
$b = round( rand( 0, 100 ) );
$color = imagecolorallocate( $img, $r, $g, $b );
imagefilledellipse( $img, round(rand(0, $this->width)), round(rand(0, $this->height)), round(rand(0, $this->width/16)), round(rand(0, $this->height/4)), $color );
}
$start_x = round($this->width / $num_chars);
$max_font_size = $start_x;
$start_x = round(0.5*$start_x);
$max_x_ofs = round($max_font_size*0.9);
// set each letter with random angle, size and color
for ($i=0;$i<=$num_chars;$i++)
{
$r = round( rand( 127, 255 ) );
$g = round( rand( 127, 255 ) );
$b = round( rand( 127, 255 ) );
$y_pos = ($this->height/2)+round( rand( 5, 20 ) );
$fontsize = round( rand( 18, $max_font_size) );
$color = imagecolorallocate( $img, $r, $g, $b);
$presign = round( rand( 0, 1 ) );
$angle = round( rand( 0, 25 ) );
if ($presign==true) $angle = -1*$angle;
ImageTTFText( $img, $fontsize, $angle, $start_x+$i*$max_x_ofs, $y_pos, $color, 'default.ttf', substr($char_seq, $i, 1) );
}
// create image file
imagejpeg( $img, $location, $this->jpg_quality );
flush();
imagedestroy( $img );
return true;
}
/**
* Returns name of the new generated captcha image file
*
* @param unknown_type $num_chars
* @return unknown
*/
function get_pic( $num_chars=8 ) {
// define characters of which the captcha can consist
$alphabet = array(
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0' );
$max = sizeof( $alphabet );
// generate random string
$captcha_str = '';
for ($i=1;$i<=$num_chars;$i++) // from 1..$num_chars
{
// choose randomly a character from alphabet and append it to string
$chosen = rand( 1, $max );
$captcha_str .= $alphabet[$chosen-1];
}
// generate a picture file that displays the random string
if ( $this->_generate_image( $this->temp_dir.'/'.'cap_'.md5( strtolower( $captcha_str )).'.jpg' , $captcha_str ) )
{
$fh = fopen( $this->temp_dir.'/'.'cap_'.$this->session_key.'.txt', "w" );
fputs( $fh, md5( strtolower( $captcha_str ) ) );
return( md5( strtolower( $captcha_str ) ) );
}
else
{
return false;
}
}
/**
* check hash of password against hash of searched characters
*
* @param string $char_seq
* @return boolean
*/
function verify( $char_seq ) {
$fh = fopen( $this->temp_dir.'/'.'cap_'.$this->session_key.'.txt', "r" );
$hash = fgets( $fh );
if (md5(strtolower($char_seq)) == $hash)
return true;
else
return false;
}
}
class AgentStormPage {
public $ID = -1;
public $post_title = '';
public $post_content = '';
public $post_author;
public $post_status = 'publish';
public $post_type = 'page';
public $ping_status = 'closed';
public $comment_status = 'closed';
public $comment_count = 0;
public $post_date = '';
public $post_date_gmt = '';
/**
*
*/
function __construct($id, $title, $content) {
$this->post_date = current_time('mysql');
$this->post_date_gmt = current_time('mysql', 1);
$this->post_author = 1;
$this->ID = $id;
$this->post_title = $title;
$this->post_content = $content;
}
/**
*
*/
function toArray() {
$return = array();
foreach ($this as $key => $value) {
$return[$key] = $value;
}
return $return;
}
}
class AgentStormWidgetContact {
/**
*
*/
function init() {
register_sidebar_widget(_('Agent Storm Contact Manager Widget'), array($this, 'display'));
register_widget_control(_('Agent Storm Contact Manager Widget'), array($this, 'displayAdmin'));
}
/**
*
*/
function canCreateCaptcha() {
return function_exists('imagecreatetruecolor');
}
/**
*
*/
function display($args) {
// Build our captcha session code
//
if (array_key_exists('as_session_code', $_POST)) {
$session_code = $_POST['as_session_code'];
} else {
$session_code = md5(round(rand(0, 40000)));
}
$as_saved = false;
if (!empty($_POST)) {
if (isset($_POST['as_contactwidget_submit'])) {
// Build the basic document to be posted
//
$xmldoc = new SimpleXMLElement('');
$contact = $xmldoc->addChild("Contact");
$contact->addChild('Name', $_POST['as_contact_name']);
$contact->addChild('ContactSource', get_option('as_contact_source'));
// If we have been passed an Email Address add it to the XML to be posted
//
if (isset($_POST['as_contact_email']) && !empty($_POST['as_contact_email'])) {
$email_addresses = $contact->addChild('EmailAddresses');
$email_address_c = $email_addresses->addChild('EmailAddress');
$email_address = $email_address_c->addChild('EmailAddress', $_POST['as_contact_email']);
}
// If we have been passed a Phone Number add it to the XML to be posted
//
if (isset($_POST['as_contact_phone']) && !empty($_POST['as_contact_email'])) {
$phone_numbers = $contact->addChild('PhoneNumbers');
$phone_number_c = $phone_numbers->addChild('PhoneNumber');
$phone_number = $phone_number_c->addChild('Number', $_POST['as_contact_phone']);
}
// If we have been passed a Message add it to the XML to be posted
//
if (isset($_POST['as_contact_message']) && !empty($_POST['as_contact_email'])) {
$notes = $contact->addChild('Notes');
$note_c = $notes->addChild('Note');
$note = $note_c->addChild('Note', $_POST['as_contact_message']);
}
$request = new AgentStormRequest(get_option('as_hostname'), get_option('as_apikey'));
$as_saved = $request->postRemote('contacts', array(), $xmldoc->asXML());
}
}
extract($args);
echo $before_widget;
echo $before_title . get_option('as_contactwidget_title') . $after_title;
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_widget_contact.php';
echo $after_widget;
}
/**
*
*/
function displayAdmin() {
if (!empty($_POST)) {
$this->saveAdmin();
}
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_widget_contactoptions.php';
}
/**
*
*/
function saveAdmin() {
if (isset($_POST['as_contactwidget_save'])) {
update_option('as_contactwidget_title', $_POST['as_contactwidget_title']);
update_option('as_contactwidget_desc', $_POST['as_contactwidget_desc']);
update_option('as_contactwidget_success', $_POST['as_contactwidget_success']);
update_option('as_contactwidget_button', $_POST['as_contactwidget_button']);
}
}
}
class AgentStormWidgetSearchMLSNumber {
/**
*
*/
function init() {
register_sidebar_widget(_('Agent Storm Search by MLS Number'), array($this, 'display'));
register_widget_control(_('Agent Storm Search by MLS Number'), array($this, 'displayAdmin'));
}
/**
*
*/
function display($args) {
extract($args);
echo $before_widget;
echo $before_title . get_option('as_searchmlsnumberwidget_title') . $after_title;
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_widget_searchmlsnumber.php';
echo $after_widget;
}
/**
*
*/
function displayAdmin() {
if (!empty($_POST)) {
$this->saveAdmin();
}
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_widget_searchmlsnumberoptions.php';
}
/**
*
*/
function saveAdmin() {
if (isset($_POST['as_searchmlsnumberwidget_save'])) {
update_option('as_searchmlsnumberwidget_title', $_POST['as_searchmlsnumberwidget_title']);
update_option('as_searchmlsnumberwidget_desc', $_POST['as_searchmlsnumberwidget_desc']);
}
}
}
class AgentStormWidgetNavigation {
/**
*
*/
function init() {
register_sidebar_widget(_('Agent Storm Navigation Widget'), array($this, 'display'));
register_widget_control(_('Agent Storm Navigation Widget'), array($this, 'displayAdmin'));
}
/**
*
*/
function display($args) {
$as = new AgentStormRequest(get_option('as_hostname'), get_option('as_apikey'));
$cities = get_option('as_cities');
extract($args);
echo $before_widget;
echo $before_title . get_option('as_navigationwidget_title') . $after_title;
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_widget_navigation.php';
echo $after_widget;
}
/**
*
*/
function displayAdmin() {
if (!empty($_POST)) {
$this->saveAdmin();
}
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_widget_navigationoptions.php';
}
/**
*
*/
function saveAdmin() {
if (isset($_POST['as_navigationwidget_save'])) {
update_option('as_navigationwidget_title', $_POST['as_navigationwidget_title']);
update_option('as_navigationwidget_desc', $_POST['as_navigationwidget_desc']);
}
}
function getPermalink($url, $object) {
if (isset($object->State)) $url = str_replace('%state%', agentstorm_slugify($object->State), $url);
if (isset($object->City)) $url = str_replace('%city%', agentstorm_slugify($object->City), $url);
if (isset($object->Id)) $url = str_replace('%id%', agentstorm_slugify($object->Id), $url);
if (isset($object->FullAddress)) $url = str_replace('%full_address%', agentstorm_slugify($object->FullAddress), $url);
if (isset($object->SubDivision)) $url = str_replace('%subdivision%', agentstorm_slugify($object->SubDivision), $url);
return $url;
}
}
class AgentStormWidgetSearch {
/**
*
*/
function init() {
register_sidebar_widget(_('Agent Storm Search Widget'), array($this, 'display'));
register_widget_control(_('Agent Storm Search Widget'), array($this, 'displayAdmin'));
}
/**
*
*/
function display($args) {
$as = new AgentStormRequest(get_option('as_hostname'), get_option('as_apikey'));
$cities = get_option('as_cities');
extract($args);
echo $before_widget;
echo $before_title . get_option('as_searchwidget_title') . $after_title;
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_widget_search.php';
echo $after_widget;
}
/**
*
*/
function displayAdmin() {
if (!empty($_POST)) {
$this->saveAdmin();
}
include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'agentstorm_widget_searchoptions.php';
}
/**
*
*/
function saveAdmin() {
if (isset($_POST['as_searchwidget_save'])) {
update_option('as_searchwidget_title', $_POST['as_searchwidget_title']);
update_option('as_searchwidget_desc', $_POST['as_searchwidget_desc']);
}
}
}
class AgentStormRequest {
/**
*
*/
public $hostname = '';
/**
*
*/
public $apikey = '';
/**
*
*/
public $format = 'json';
/**
*
*/
function __construct($hostname, $apikey) {
$this->hostname = $hostname;
$this->apikey = $apikey;
}
/**
*
*/
private function buildParams($params) {
$return = '?';
foreach ($params as $key => $value) {
$return .= $key . '=' . urlencode($value) . '&';
}
return trim($return, '&');
}
/**
*
*/
function getRemote($path, $params = array()) {
$params['apikey'] = $this->apikey;
$param_string = $this->buildParams($params);
switch ($this->format) {
case 'json':
$ret = json_decode(@file_get_contents($this->hostname . $path . '.' . $this->format . $param_string));
break;
case 'xml':
if (!$ret=@simplexml_load_file($this->hostname . $path . '.' . $this->format . '?apikey=' . $this->apikey)) {
throw new ASException('An Error occurred while retrieving the results');
}
break;
}
return $ret;
}
/**
*
*/
function postRemote($path, $params = array(), $data) {
$params['apikey'] = $this->apikey;
$param_string = $this->buildParams($params);
$ch = curl_init($this->hostname . $path . '.' . $this->format . $param_string);
curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
if (!curl_errno($ch)) {
curl_close($ch);
return true;
}
return false;
}
/**
*
*/
function getContacts() {
return $this->getRemote('contacts');
}
/**
*
*/
function getContact($contact_id) {
return $this->getRemote('contacts/' . $contact_id);
}
/**
*
*/
function getProperties($search = array()) {
if (get_option(as_idx_settings_tag, '') != '') {
return $this->getRemote('properties/tags/' . get_option(as_idx_settings_tag, ''), $search);
} else {
return $this->getRemote('properties', $search);
}
}
/**
*
*/
function getProperty($property_id) {
return $this->getRemote('properties/' . $property_id);
}
/**
* Get Property Tags on this account
*/
function getTags() {
return $this->getRemote('properties/tags');
}
/**
* Get Property MetaData
*/
function getPropertyMetaData() {
return $this->getRemote('properties/fields');
}
/**
*
*/
function getCities() {
if (get_option(as_idx_settings_tag, '') != '') {
return $this->getRemote('properties/tags/' . get_option(as_idx_settings_tag, '') . '/cities', $search);
} else {
return $this->getRemote('properties/cities', $search);
}
}
}
/**
*
*/
function agentstorm_slugify($text) {
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
$text = trim($text, '-');
if (function_exists('iconv')) {
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
}
$text = strtolower($text);
$text = preg_replace('~[^-\w]+~', '', $text);
if (empty($text)) {
return 'n-a';
}
return $text;
}
/**
*
*/
function agentstorm_activate() {
// Schedule the Hourly cache update
//
wp_schedule_event(time(), 'hourly', 'agentstorm_hourly');
// Set some variables
//
if (get_option('as_usestyle', '') == '') update_option('as_usestyle', true);
if (get_option('as_idx_gmap', '') == '') update_option('as_idx_gmap', true);
if (get_option('as_idx_bview', '') == '') update_option('as_idx_bview', true);
if (get_option('as_contact_source', '') == '') update_option('as_contact_source', 'Wordpress Blog');
if (get_option('as_idx_settings_pagelimit', '') == '') update_option('as_idx_settings_pagelimit', '10');
// Set default API key
//
if (get_option('as_hostname', '') == '') update_option('as_hostname', 'http://example.agentstorm.com/');
if (get_option('as_apikey', '') == '') update_option('as_apikey', '26TZ9CYOi45N8SBM5BVLuRaqo3CkX50O');
// Enable all Property Classes
//
if (get_option('as_idx_settings_classes_res', '') == '') update_option('as_idx_settings_classes_res', true);
if (get_option('as_idx_settings_classes_com', '') == '') update_option('as_idx_settings_classes_com', true);
if (get_option('as_idx_settings_classes_lnd', '') == '') update_option('as_idx_settings_classes_lnd', true);
if (get_option('as_idx_settings_classes_mob', '') == '') update_option('as_idx_settings_classes_mob', false);
if (get_option('as_idx_settings_classes_mfh', '') == '') update_option('as_idx_settings_classes_mfh', false);
if (get_option('as_idx_settings_classes_rnt', '') == '') update_option('as_idx_settings_classes_rnt', false);
// Enable all Property Classes
//
if (get_option('as_idx_settings_field_type', '') == '') update_option('as_idx_settings_field_type', true);
if (get_option('as_idx_settings_field_suburbzip', '') == '') update_option('as_idx_settings_field_suburbzip', true);
if (get_option('as_idx_settings_field_price', '') == '') update_option('as_idx_settings_field_price', true);
if (get_option('as_idx_settings_field_bedrooms', '') == '') update_option('as_idx_settings_field_bedrooms', true);
if (get_option('as_idx_settings_field_bathrooms', '') == '') update_option('as_idx_settings_field_bathrooms', true);
if (get_option('as_idx_settings_field_lotsize', '') == '') update_option('as_idx_settings_field_lotsize', true);
if (get_option('as_idx_settings_field_size', '') == '') update_option('as_idx_settings_field_size', true);
if (get_option('as_idx_settings_field_shortsale', '') == '') update_option('as_idx_settings_field_shortsale', true);
if (get_option('as_idx_settings_field_foreclosure', '') == '') update_option('as_idx_settings_field_foreclosure', true);
// Setup Default Views for Property Tpes
//
if (get_option('as_metadata_COM_header', '') == '') update_option('as_metadata_COM_header', 'ListingId,BuildingName,NumberOfFloors,TenencyType');
if (get_option('as_metadata_COM_features', '') == '') update_option('as_metadata_COM_features', '');
if (get_option('as_metadata_LND_header', '') == '') update_option('as_metadata_LND_header', 'ListingId,LotSqFt');
if (get_option('as_metadata_LND_features', '') == '') update_option('as_metadata_LND_features', '');
if (get_option('as_metadata_RES_header', '') == '') update_option('as_metadata_RES_header', 'ListingId,Bedrooms,FullBathrooms,HalfBathrooms,YearBuilt');
if (get_option('as_metadata_RES_features', '') == '') update_option('as_metadata_RES_features', 'ConstructionMaterials,Cooling,DiningRoomDescription,EnergySavingFeatures,ExteriorFeatures,LotFeatures,Fencing,FireplaceFeatures,Flooring,Heating,KitchenDescription,LaundryDescription,OtherRoomsDescription,Roof,PoolFeatures,SpaFeatures,Utilities,Electric,Water,Gas,Sewer');
// Setup the Permalink Structure
//
if (get_option('as_idx_searchprefix', '') == '') update_option('as_idx_searchprefix', 'property-search/');
if (get_option('as_idx_propertyprefix', '') == '') update_option('as_idx_propertyprefix', 'property/%state%/%city%/%subdivision%/%id%-%full_address%.html');
if (get_option('as_idx_stateurlprefix', '') == '') update_option('as_idx_stateurlprefix', 'property/%state%');
if (get_option('as_idx_cityurlprefix', '') == '') update_option('as_idx_cityurlprefix', 'property/%state%/%city%');
// Setup the Permalink Structure
//
if (get_option('as_idx_template_result', '') == '') update_option('as_idx_template_result', 'page.php');
if (get_option('as_idx_template_property', '') == '') update_option('as_idx_template_property', 'page.php');
if (get_option('as_idx_template_noresults', '') == '') update_option('as_idx_template_noresults', 'page.php');
// Force update the cache
//
agentstorm_hourly();
}
/**
*
*/
function agentstorm_deactivate() {
wp_clear_scheduled_hook('agentstorm_hourly');
}
/**
*
*/
function agentstorm_hourly() {
if (get_option('as_hostname') && get_option('as_apikey')) {
$as = new AgentStormRequest(get_option('as_hostname'), get_option('as_apikey'));
$as_cities = $as->getCities();
update_option('as_cities', $as->getCities());
$as_tags = $as->getTags();
update_option('as_tags', $as_tags->Tags);
}
}
// Initialize the Agent Storm Plugin
//
$agentstorm = new AgentStorm();
add_action('admin_init', array(&$agentstorm, 'adminInit'));
add_action('admin_menu', array(&$agentstorm, 'adminRegisterMenu'));
add_action('wp_ajax_agentstorm_result_layout', array(&$agentstorm, 'saveResultLayout'));
add_action('wp_enqueue_scripts', array(&$agentstorm, 'loadSiteStyles'));
add_action('wp_head', array(&$agentstorm, 'siteHead'));
register_activation_hook(__FILE__, 'agentstorm_activate');
register_deactivation_hook(__FILE__, 'agentstorm_deactivate');
// Initialize the Contact Manager Sidebar Widget
//
$agentstorm_contact_widget = new AgentStormWidgetContact();
add_action('plugins_loaded', array(&$agentstorm_contact_widget, 'init'));
// Initialize the Navigation Widget
//
$agentstorm_navigation_widget = new AgentStormWidgetNavigation();
add_action('plugins_loaded', array(&$agentstorm_navigation_widget, 'init'));
// Initialize the Search Widget
//
$agentstorm_search_widget = new AgentStormWidgetSearch();
add_action('plugins_loaded', array(&$agentstorm_search_widget, 'init'));
// Initialize the MLS Number Search Widget
//
$agentstorm_mls_number_search_widget = new AgentStormWidgetSearchMLSNumber();
add_action('plugins_loaded', array(&$agentstorm_mls_number_search_widget, 'init'));
// Initialize the IDX Search/Display Controller
//
$agentstorm_idx = new AgentStormIDX();
add_action('parse_request', array(&$agentstorm_idx, 'init'));
add_filter('query_vars', array(&$agentstorm_idx, 'processQueryVars'));
// Fix