function __construct() { parent::__construct(); Configure::write('Community.profileUrl', $this->profileUrl); if (file_exists(PATH_ROOT . 'components' . _DS . 'com_community' . _DS . 'community.php')) { $this->community = true; $Menu = ClassRegistry::getClass('MenuModel'); $this->menu_id = $Menu->getComponentMenuId('com_community&view=frontpage'); if (!$this->menu_id) { $this->menu_id = $Menu->getComponentMenuId('com_community&view=profile'); } if (!$this->menu_id) { $this->menu_id = $Menu->getComponentMenuId('com_community'); } // For JomSocial <= 2.1 if (!file_exists(PATH_ROOT . 'components/com_community/assets/user_thumb.png')) { $this->default_thumb = 'components/com_community/assets/default_thumb.jpg'; } $cache_key = 'jomsocial_config_' . md5(cmsFramework::getConfig('secret')); $JSConfig = S2Cache::read($cache_key); if (false == $JSConfig) { // Read the JomSocial configuration to determine the storage location for avatars $JSConfig = json_decode($this->query("SELECT params FROM #__community_config WHERE name = 'config'", 'loadResult'), true); $JSConfigForJReviews = array('user_avatar_storage' => $JSConfig['user_avatar_storage'], 'storages3bucket' => $JSConfig['storages3bucket']); S2Cache::write($cache_key, $JSConfigForJReviews); } $this->avatar_storage = $JSConfig['user_avatar_storage']; $this->s3_bucket = $JSConfig['storages3bucket']; Configure::write('Community.register_url', sprintf($this->registerUrl, $this->menu_id)); } }
function reviewVoting($review) { $review_id = $review['Review']['review_id']; $User = cmsFramework::getUser(); $output = '<div class="reviewHelpful">'; $output .= '<div class="jrHelpfulTitle">' . __t("Was this review helpful to you?", true) . ' </div>'; $output .= '<div id="jr_reviewVote' . $review_id . '" style="float:left;">'; if ($this->Access->canVoteHelpful($review['User']['user_id'])) { $output .= '<span class="jrVote jrButton" onclick="jreviews.review.voteYes(this,{review_id:' . $review_id . '})">'; } elseif ($User->id > 0) { $output .= '<span class="jrVote jrButton" onclick="s2Alert(\'' . __t("You are not allowed to vote", true, true) . '\');">'; } else { $output .= '<span class="jrVote jrButton" onclick="s2Alert(\'' . __t("Login or register to vote", true, true) . '\');">'; } $output .= '<span class="jrButtonText" style="color: green;">' . $review['Vote']['yes'] . '</span><span class="jrIcon jrIconThumbUp"></span>'; $output .= '</span>'; if ($this->Access->canVoteHelpful($review['User']['user_id'])) { $output .= '<span class="jrVote jrButton" onclick="jreviews.review.voteNo(this,{review_id:' . $review_id . '})">'; } elseif ($User->id > 0) { $output .= '<span class="jrVote jrButton" onclick="s2Alert(\'' . __t("You are not allowed to vote", true, true) . '\');">'; } else { $output .= '<span class="jrVote jrButton" onclick="s2Alert(\'' . __t("Login or register to vote", true, true) . '\');">'; } $output .= '<span class="jrButtonText" style="color: red;">' . $review['Vote']['no'] . '</span><span class="jrIcon jrIconThumbDown"></span>'; $output .= '</span>'; $output .= '<span class="jr_loadingSmall jr_hidden"></span>'; $output .= '</div>'; $output .= '</div>'; return $output; }
function addFavorite($results) { $listing_ids = array_keys($results); if (!isset($this->Config)) { App::import('Component', 'config', 'jreviews'); $this->Config = ClassRegistry::getClass('ConfigComponent'); } if ($this->Config->favorites_enable) { # Get favoured count $query = "\n SELECT \n content_id AS listing_id, count(*) AS favored FROM #__jreviews_favorites AS Favorite\n\t\t\t WHERE \n Favorite.content_id IN (" . implode(',', $listing_ids) . ")\n\t\t\t GROUP BY \n listing_id\n "; $this->_db->setQuery($query); $favored = $this->_db->loadAssocList('listing_id'); # Check if in user's favorites list $User =& cmsFramework::getUser(); if ($User->id) { $query = "\n SELECT \n Favorite.user_id, Favorite.content_id AS listing_id\n\t\t\t\t FROM \n #__jreviews_favorites AS Favorite\n\t\t\t\t WHERE \n Favorite.content_id IN (" . implode(',', $listing_ids) . ")\n\t\t\t\t AND Favorite.user_id = " . $User->id; $this->_db->setQuery($query); $my_favorite = $this->_db->loadAssocList('listing_id'); } foreach ($results as $key => $result) { if (isset($favored[$result['Listing']['listing_id']]['favored'])) { $results[$key]['Favorite']['favored'] = $favored[$result['Listing']['listing_id']]['favored']; } else { $results[$key]['Favorite']['favored'] = 0; } if (isset($my_favorite[$result['Listing']['listing_id']]['user_id'])) { $results[$key]['Favorite']['my_favorite'] = 1; } else { $results[$key]['Favorite']['my_favorite'] = 0; } } } return $results; }
function reviews() { $access = $this->cmsVersion == CMS_JOOMLA15 ? $this->Access->getAccessId() : $this->Access->getAccessLevels(); $feed_filename = PATH_ROOT . 'cache' . DS . 'jreviewsfeed_' . md5($access . $this->here) . '.xml'; $this->Feeds->useCached($feed_filename, 'reviews'); $extension = Sanitize::getString($this->params, 'extension', 'com_content'); $cat_id = Sanitize::getInt($this->params, 'cat'); $section_id = Sanitize::getInt($this->params, 'section'); $dir_id = Sanitize::getInt($this->params, 'dir'); $listing_id = Sanitize::getInt($this->params, 'id'); $this->encoding = cmsFramework::getCharset(); $feedPage = null; $this->EverywhereAfterFind = true; // Triggers the afterFind in the Observer Model $this->limit = $this->Config->rss_limit; $rss = array('title' => $this->Config->rss_title, 'link' => WWW_ROOT, 'description' => $this->Config->rss_description, 'image_url' => WWW_ROOT . "images/stories/" . $this->Config->rss_image, 'image_link' => WWW_ROOT); $queryData = array('conditions' => array('Review.published = 1', "Review.mode = '{$extension}'"), 'fields' => array('Review.mode AS `Review.extension`'), 'limit' => $this->limit, 'order' => array('Review.created DESC')); if ($extension == 'com_content') { $queryData['conditions'][] = 'Listing.state = 1'; $queryData['conditions'][] = '( Listing.publish_up = "' . NULL_DATE . '" OR Listing.publish_up <= "' . _CURRENT_SERVER_TIME . '" )'; $queryData['conditions'][] = '( Listing.publish_down = "' . NULL_DATE . '" OR Listing.publish_down >= "' . _CURRENT_SERVER_TIME . '" )'; # Shows only links users can access if ($this->cmsVersion == CMS_JOOMLA15) { $access_id = $this->Access->getAccessId(); $queryData['conditions'][] = 'Listing.access <= ' . $access_id; $queryData['conditions'][] = 'Category.access <= ' . $access_id; } else { $cat_id > 0 and $cat_id = array_keys($this->Category->getChildren($cat_id)); $access_id = $this->Access->getAccessLevels(); $queryData['conditions'][] = 'Listing.access IN ( ' . $access_id . ')'; $queryData['conditions'][] = 'Category.access IN ( ' . $access_id . ')'; } } if (!empty($cat_id) && $extension == 'com_content') { // Category feeds only supported for core content $queryData['conditions'][] = 'JreviewsCategory.id IN (' . $this->quote($cat_id) . ')'; $feedPage = 'category'; } elseif ($section_id > 0 && $extension == 'com_content') { $queryData['conditions'][] = 'Listing.sectionid= ' . $section_id; $feedPage = 'section'; } elseif ($dir_id > 0 && $extension == 'com_content') { $queryData['conditions'][] = 'JreviewsCategory.dirid= ' . $dir_id; $feedPage = 'directory'; } elseif ($extension != 'com_content') { unset($this->Review->joins['listings'], $this->Review->joins['jreviews_categories'], $this->Review->joins['listings']); $feedPage = 'everywhere'; } if ($listing_id > 0) { $queryData['conditions'][] = 'Review.pid = ' . $listing_id; $feedPage = 'listing'; } # Don't run it here because it's run in the Everywhere Observer Component $this->Review->runProcessRatings = false; $reviews = $this->Review->findAll($queryData); $this->set(array('feedPage' => $feedPage, 'encoding' => $this->encoding, 'rss' => $rss, 'reviews' => $reviews)); return $this->Feeds->saveFeed($feed_filename, 'reviews'); }
function startup(&$controller) { # Check feed cache if (Sanitize::getString($controller->params, 'action') == 'xml') { $this->useCached(PATH_ROOT . DS . 'cache' . DS . 'jreviewsfeed_' . md5($controller->here) . '.xml'); } $this->encoding = cmsFramework::getCharset(); $this->params =& $controller->params; $this->c =& $controller; }
function __construct() { parent::__construct(); $User =& cmsFramework::getUser(); // Used in MyReviews page to differentiate from other component reviews $this->tag = __t("MYBLOG_TAG", true); // Uncomment line below to show tag in My Reviews page $this->fields[] = "'{$this->tag}' AS `Listing.tag`"; // Set default WHERE statement $this->conditions = array('Listing.state = 1', '( Listing.publish_up = "' . NULL_DATE . '" OR Listing.publish_up <= "' . _CURRENT_SERVER_TIME . '" )', '( Listing.publish_down = "' . NULL_DATE . '" OR Listing.publish_down >= "' . _CURRENT_SERVER_TIME . '" )', 'Listing.catid > 0'); }
function &getInstance() { static $instance = array(); if (!isset($instance[0]) || !$instance[0]) { $instance[0] = new sef_jreviews(); require dirname(__FILE__) . DS . 'jreviews' . DS . 'framework.php'; App::import('Model', 'Menu', 'jreviews'); $instance[0]->__Menu = ClassRegistry::getClass('MenuModel'); // Read url param style setting from JReviews config cache file $cache_file = 'jreviews_config_' . md5(cmsFramework::getConfig('secret')); $Config = S2Cache::read($cache_file); $instance[0]->joomla_style_params = is_object($Config) and isset($Config->url_param_joomla) ? $Config->url_param_joomla : false; $version = new JVersion(); $instance[0]->cmsVersion = $version->RELEASE; } return $instance[0]; }
function onProfileDisplay() { if (!file_exists($this->_path . DS . 'admin.jreviews.php')) { return JText::_('jReviews is not installed. Please contact site administrator.'); } else { $user = CFactory::getActiveProfile(); $userId = $user->id; $cacheSetting = $this->params->get('cache', 1) ? JApplication::getCfg('caching') : 0; # Load CSS stylesheets -- done here because when cache is on css is not loaded if ($cacheSetting) { # MVC initalization script if (!defined('DS')) { define('DS', DIRECTORY_SEPARATOR); } require 'components' . DS . 'com_jreviews' . DS . 'jreviews' . DS . 'framework.php'; $cache_file = 'jreviews_config_' . md5(cmsFramework::getConfig('secret')); $Config =& S2Cache::read($cache_file); if (!is_object($Config)) { //Create config file $eParams['data']['controller'] = 'common'; $eParams['data']['action'] = 'index'; $Dispatcher = new S2Dispatcher('jreviews', false, true); $Dispatcher->dispatch($eParams); $Config =& S2Cache::read($cache_file); unset($Dispatcher); } App::import('Helper', 'html'); $Html =& RegisterClass::getInstance('HtmlHelper'); $Html->viewTheme = $Config->template; $Html->app = 'jreviews'; $Html->startup(); App::import('Helper', 'libraries', 'jreviews'); $Libraries =& RegisterClass::getInstance('LibrariesHelper'); $Html->css(array('theme', 'plugins', 'paginator')); $Html->js(array('jreviews', 'jquery' => 'jquery', 'jq.scrollable'), $Libraries->js()); } $cache =& JFactory::getCache('plgCommunityJreviews_myfavorites'); $cache->setCaching($cacheSetting); $callback = array('plgCommunityJreviews_myfavorites', '_getPage'); $contents = $cache->call($callback, $userId, $this->params, $cacheSetting); return $contents; } }
function getVersion() { $page = ''; $new_version = 'none'; $session_var = cmsFramework::getSessionVar('new_version', 'jreviews'); if (empty($session_var)) { if (function_exists('curl_init')) { // Version checker $curl_handle = curl_init('http://www.reviewsforjoomla.com/updates_server/files.php'); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); // return instead of echo @curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl_handle, CURLOPT_HEADER, 0); $data = curl_exec($curl_handle); curl_close($curl_handle); $current_versions = json_decode($data, true); $this->Config->updater_betas and isset($current_versions['jreviews']['beta']) and $current_versions['jreviews'] = array_merge($current_versions['jreviews'], $current_versions['jreviews']['beta']); $remoteVersion = $current_versions['components']['jreviews']['version']; $remoteVersion = (int) str_replace('.', '', $remoteVersion); $localVersion = (int) str_replace('.', '', strip_tags($this->Config->version)); if ($remoteVersion > $localVersion) { $new_version = 'new'; } } else { $new_version = 'curl'; } cmsFramework::setSessionVar('new_version', $new_version, 'jreviews'); } else { $new_version = $session_var; } switch ($new_version) { case 'new': $page = '<a style="font-weight:normal;font-size:13px;color:red;" href="#updater_version_check" id="updater_notification">' . __a("New version available", true) . '</a>'; break; case 'curl': $page = '<span style="font-weight:normal;font-size:13px;color:red;">Version checker requires curl</span>'; break; default: $page = ''; break; } return $this->ajaxResponse(array(), false, compact('page')); }
function __construct() { parent::__construct(); $User =& cmsFramework::getUser(); // Used in MyReviews page to differentiate from other component reviews $this->tag = __t("MYBLOG_TAG", true); // Uncomment line below to show tag in My Reviews page $this->fields[] = "'{$this->tag}' AS `Listing.tag`"; // Set default WHERE statement $this->conditions = array('Listing.state = 1', '( Listing.publish_up = "' . NULL_DATE . '" OR Listing.publish_up <= "' . _CURRENT_SERVER_TIME . '" )', '( Listing.publish_down = "' . NULL_DATE . '" OR Listing.publish_down >= "' . _CURRENT_SERVER_TIME . '" )', 'Listing.catid > 0'); if (!defined('MVC_FRAMEWORK_ADMIN')) { # Shows only links users can access $Access = Configure::read('JreviewsSystem.Access'); if ($this->cmsVersion == CMS_JOOMLA15) { $this->conditions[] = 'Listing.access <= ' . $User->gid; } else { $this->conditions[] = 'Listing.access IN ( ' . $Access->getAccessLevels() . ')'; } } }
function _save() { $response = array(); $this->data['Vote']['user_id'] = $this->_user->id; $this->data['Vote']['review_id'] = (int) $this->data['Vote']['review_id']; # Exact vote check to prevent form tampering. User can cheat the js and enter any interger, thus increasing the count $this->data['Vote']['vote_yes'] = Sanitize::getInt($this->data['Vote'], 'vote_yes') ? 1 : 0; $this->data['Vote']['vote_no'] = Sanitize::getInt($this->data['Vote'], 'vote_no') ? 1 : 0; $this->data['Vote']['created'] = gmdate('Y-m-d H:i:s'); $this->data['Vote']['ipaddress'] = $this->ipaddress; if (!$this->data['Vote']['review_id']) { return $this->ajaxError(s2Messages::submitErrorGeneric()); } // Find duplicates $duplicate = $this->Vote->findCount(array('conditions' => array('review_id = ' . $this->data['Vote']['review_id'], 'ipaddress = ' . $this->Vote->Quote($this->data['Vote']['ipaddress'])))); // It's a guest so we only care about checking the IP address if this feature is not disabled and // server is not localhost if (!$this->_user->id) { if (!$this->Config->vote_ipcheck_disable && $this->ipaddress != '127.0.0.1') { // Do the ip address check everywhere except in localhost $duplicate = $this->Vote->findCount(array('conditions' => array('review_id = ' . $this->data['Vote']['review_id'], 'ipaddress = ' . $this->Vote->Quote($this->ipaddress)))); } } else { $duplicate = $this->Vote->findCount(array('conditions' => array('review_id = ' . $this->data['Vote']['review_id'], "(user_id = {$this->_user->id}" . ($this->ipaddress != '127.0.0.1' && !$this->Config->vote_ipcheck_disable ? " OR ipaddress = " . $this->Vote->Quote($this->ipaddress) . ") " : ')')))); } if ($duplicate > 0) { # Hides vote buttons and shows message alert $response[] = "jQuery('#jr_reviewVote{$this->data['Vote']['review_id']}').fadeOut('medium',function(){\n jQuery(this).html('" . __t("You already voted.", true, true) . "').fadeIn();\n });"; return $this->ajaxResponse($response); } if ($this->Vote->store($this->data)) { # Hides vote buttons and shows message alert $response[] = "jQuery('#jr_reviewVote{$this->data['Vote']['review_id']}').fadeOut('medium',function(){\n jQuery(this).html('" . __t("Thank you for your vote.", true, true) . "').fadeIn();\n });"; # Facebook wall integration only for positive votes $facebook_integration = Sanitize::getBool($this->Config, 'facebook_enable') && Sanitize::getBool($this->Config, 'facebook_votes'); $token = cmsFramework::getCustomToken($this->data['Vote']['review_id']); $facebook_integration and $this->data['Vote']['vote_yes'] and $response[] = "\n jQuery.ajax({url:s2AjaxUri+jreviews.ajax_params()+'&url=facebook/_postVote/id:{$this->data['Vote']['review_id']}&{$token}=1',dataType:'script'});\n "; return $this->ajaxResponse($response); } return $this->ajaxError(s2Messages::submitErrorDb()); }
function _save() { $response = array(); $formToken = cmsFramework::getCustomToken($this->review_id); if ($this->denyAccess == true || !Sanitize::getString($this->params['form'], $formToken)) { return $this->ajaxError(s2Messages::accessDenied()); } # Validate form token $this->components = array('security'); $this->__initComponents(); if ($this->invalidToken) { return $this->ajaxError(s2messages::invalidToken()); } // Check if an owner reply already exists $this->OwnerReply->fields = array(); if ($reply = $this->OwnerReply->findRow(array('fields' => array('OwnerReply.owner_reply_text', 'OwnerReply.owner_reply_approved'), 'conditions' => array('OwnerReply.id = ' . $this->review_id)))) { if ($reply['OwnerReply']['owner_reply_approved'] == 1) { $error_text = __t("A reply for this review already exists.", true); $response[] = "jQuery('#jr_ownerReplyLink{$this->review_id}').remove();"; return $this->ajaxError($error_text, $response); } } if ($this->Config->owner_replies) { if ($this->data['OwnerReply']['owner_reply_text'] != '' && $this->data['OwnerReply']['id'] > 0) { $this->data['OwnerReply']['owner_reply_created'] = date('Y-m-d H:i:s'); $this->data['OwnerReply']['owner_reply_approved'] = 1; // Replies will be moderated by default if ($this->OwnerReply->store($this->data)) { $update_text = $this->data['OwnerReply']['owner_reply_approved'] ? __t("Your reply was submitted and has been approved.", true) : __t("Your reply was submitted and will be published once it is verified.", true); $response[] = "jQuery('#jr_ownerReplyLink{$this->review_id}').remove();"; return $this->ajaxUpdateDialog($update_text, $response); } return $this->ajaxError(s2Messages::submitErrorDb()); } # Validation failed if (isset($this->Security)) { $reponse[] = "jQuery('s2Token').val('" . $this->Security->reissueToken() . "')"; } return $this->ajaxValidation(__t("The reply is empty.", true), $response); } }
function reviews() { $extension = Sanitize::getString($this->params, 'extension', 'com_content'); $cat_id = Sanitize::getInt($this->params, 'cat'); $section_id = Sanitize::getInt($this->params, 'section'); $dir_id = Sanitize::getInt($this->params, 'dir'); $listing_id = Sanitize::getInt($this->params, 'id'); $this->encoding = cmsFramework::getCharset(); $feedPage = null; $this->EverywhereAfterFind = true; // Triggers the afterFind in the Observer Model $this->limit = $this->Config->rss_limit; $rss = array('title' => $this->Config->rss_title, 'link' => WWW_ROOT, 'description' => $this->Config->rss_description, 'image_url' => WWW_ROOT . "images/stories/" . $this->Config->rss_image, 'image_link' => WWW_ROOT); $queryData = array('conditions' => array('Review.published = 1', "Review.mode = '{$extension}'"), 'fields' => array('Review.mode AS `Review.extension`'), 'limit' => $this->limit, 'order' => array('Review.created DESC')); if ($cat_id > 0 && $extension == 'com_content') { // Category feeds only supported for core content $queryData['conditions'][] = 'JreviewsCategory.id= ' . $cat_id; // $queryData['joins'] = $this->Listing->joinsReviews; $feedPage = 'category'; } elseif ($section_id > 0 && $extension == 'com_content') { $queryData['conditions'][] = 'Listing.sectionid= ' . $section_id; // $queryData['joins'] = $this->Listing->joinsReviews; $feedPage = 'section'; } elseif ($dir_id > 0 && $extension == 'com_content') { $queryData['conditions'][] = 'JreviewsCategory.dirid= ' . $dir_id; // $queryData['joins'] = $this->Listing->joinsReviews; $feedPage = 'directory'; } elseif ($extension != 'com_content') { unset($this->Review->joins['listings'], $this->Review->joins['jreviews_categories'], $this->Review->joins['listings']); $feedPage = 'everywhere'; } if ($listing_id > 0) { $queryData['conditions'][] = 'Review.pid = ' . $listing_id; $feedPage = 'listing'; } # Don't run it here because it's run in the Everywhere Observer Component $this->Review->runProcessRatings = false; $reviews = $this->Review->findAll($queryData); $this->set(array('feedPage' => $feedPage, 'encoding' => $this->encoding, 'rss' => $rss, 'reviews' => $reviews)); return $this->Feeds->saveFeed(PATH_ROOT . DS . 'cache' . DS . 'jreviewsfeed_' . md5($this->here) . '.xml', 'reviews'); }
function uninstall() { $db = cmsFramework::getDB(); // Delete GeoMaps module $query = "DELETE FROM #__modules WHERE module = 'mod_jreviews_geomaps'"; $db->setQuery($query); $db->query(); if ($this->cmsVersion == CMS_JOOMLA16) { $query = "DELETE FROM #__extensions WHERE name = 'mod_jreviews_geomaps'"; $db->setQuery($query); $db->query(); } // Remove GeoMaps module files $target = PATH_ROOT . 'modules' . DS . 'mod_jreviews_geomaps'; $Folder = new Folder(); if (@$Folder->delete($target)) { return '<div style="color:green;">GeoMaps Module successfully uninstalled.</div>'; } else { return '<div style="color:red;">There was a problem uninstalling the GeoMaps module.</div>'; } }
function favorite($listing) { $output = ''; $listing_id = $listing['Listing']['listing_id']; $User = cmsFramework::getUser(); $output .= '<span class="jrFavoriteWidget" title="' . __t("Favorites", true) . '">'; $output .= '<span class="jrIcon jrIconFavorites"></span>'; $output .= '<span id="jr_favoriteCount' . $listing_id . '">' . $listing['Favorite']['favored'] . '</span>'; $output .= '</span>'; if ($listing['Favorite']['my_favorite']) { // Already in user's favorites $output .= '<span id="jr_favoriteImg' . $listing_id . '" class="jrFavoriteButton jrButton" title="' . __t("Remove from favorites", true) . '" onclick="jreviews.favorite.remove(this,{listing_id:' . $listing_id . '})">' . __t("Remove", true) . '</span>'; } elseif ($User->id) { // Not in user's favorites $output .= '<span id="jr_favoriteImg' . $listing_id . '" class="jrFavoriteButton jrButton" title="' . __t("Add to favorites", true) . '" onclick="jreviews.favorite.add(this,{listing_id:' . $listing_id . '})">' . __t("Add", true) . '</span>'; } else { // This is a guest user, needs to register to use the favorites widget $output .= '<span id="jr_favoriteImg' . $listing_id . '" class="jrFavoriteButton jrButton" title="' . __t("Add to favorites", true) . '" onclick="s2Alert(\'' . __t("Register to add this entry to your favorites", true) . '\');">' . __t("Add", true) . '</span>'; } return $output; }
function install() { $db = cmsFramework::getDB(); // Create the marker_icon column in the JReviews categories table $cat_table_cols = current($db->getTableFields('#__jreviews_categories')); if (!in_array('marker_icon', array_keys($cat_table_cols))) { $query = "ALTER TABLE `#__jreviews_categories` ADD `marker_icon` VARCHAR(150) AFTER `tmpl_suffix`;"; $db->setQuery($query); $db->query(); } // Install GeoMaps module $query = "SELECT count(*) FROM #__modules WHERE module = 'mod_jreviews_geomaps'"; $db->setQuery($query); $count = $db->loadResult(); if (!$count) { // create module entry in database $query = "\r\n INSERT INTO #__modules \r\n (`title`, `module`, `published`, `params`) \r\n VALUES \r\n ('Jreviews GeoMaps Module', 'mod_jreviews_geomaps', 0, '');"; $db->setQuery($query); $db->query(); } if ($this->cmsVersion == CMS_JOOMLA16) { // Need to add entry to the extensions table $query = "SELECT count(*) FROM #__extensions WHERE name = 'mod_jreviews_geomaps'"; $db->setQuery($query); if (!$db->loadResult()) { $query = "\r\n INSERT INTO #__extensions\r\n (`name`,`type`,`element`,`client_id`,`enabled`,`access`,`protected`)\r\n VALUES\r\n ('mod_jreviews_geomaps','module','mod_jreviews_geomaps',0,1,1,0)\r\n "; $db->setQuery($query); $db->query(); } } // First extract packages $package = PATH_ROOT . 'components' . DS . 'com_jreviews_addons' . DS . 'geomaps' . DS . 'packages' . DS . 'mod_jreviews_geomaps.zip'; $target = PATH_ROOT . 'modules'; if ($this->_extract($package, $target)) { @copy(PATH_ROOT . 'modules' . DS . 'mod_jreviews_geomaps' . DS . 'en-GB.mod_jreviews_geomaps.ini', PATH_ROOT . 'language' . DS . 'en-GB' . DS . 'en-GB.mod_jreviews_geomaps.ini'); return '<div style="color:green;">GeoMaps module was successfully installed/updated. You will find it in modules manager.</div>'; } else { return '<div style="color:red;">There was a problem installing/updating the GeoMaps module.</div>'; } }
function JreviewsParseRoute($segments) { $vars = array(); # Load own uri to overcome Joomla encoding issues with Greek params $uri = cmsFramework::_getUri(); // Fix for Joomfish. Remove the language segment from the url if (class_exists('JoomFishManager')) { $lang = JFactory::getLanguage(); $language = $lang->getTag(); $jfm = JoomFishManager::getInstance(); $lang_shortcode = $jfm->getLanguageCode($language); if (strstr($uri, '/' . $lang_shortcode . '/')) { $uri = str_replace('/' . $lang_shortcode . '/', '/', $uri); } } $new_segments = cmsFramework::_parseSefRoute($uri); if (end($new_segments) == 'index.php') { $new_segments = $segments; } // Remove Joomla language segment from url if (isset($_GET['language']) && $_GET['language'] != '' && strlen($new_segments[0]) == 2) { $new_segments[0] = 'index.php'; } # Fix for sef without mod rewrite. Without it the sort urls don't work. // Remove the Itemid related segments when mod rewrite is disabled and Itemid exists if ($new_segments[0] == 'index.php' && $new_segments[1] != 'component') { foreach ($new_segments as $key => $segment) { if (!in_array(str_replace(' ', '+', $segment), $segments) && !in_array(JreviewsStrReplaceOnce('-', ':', urlencode($segment)), $segments)) { unset($new_segments[$key]); } } } if (count($new_segments) >= 3 && isset($new_segments[0]) && $new_segments[0] == 'index.php' && isset($new_segments[1]) && $new_segments[1] == 'component' && isset($new_segments[2]) && $new_segments[2] == 'jreviews') { array_shift($new_segments); array_shift($new_segments); array_shift($new_segments); } $vars['url'] = implode('/', $new_segments); return $vars; }
function socialBookmarks($listing) { $googlePlusOne = $twitter = $facebook = ''; $facebook_xfbml = Sanitize::getBool($this->Config, 'facebook_opengraph') && Sanitize::getBool($this->Config, 'facebook_appid'); $href = cmsFramework::makeAbsUrl($listing['Listing']['url'], array('sef' => true)); $twitter = ' <a href="http://twitter.com/share" data-url="' . $href . '" class="twitter-share-button" data-count="horizontal">Tweet</a> <script type="text/javascript">jQuery(document).ready(function(){jQuery.getScript("http://platform.twitter.com/widgets.js");})</script>'; if ($facebook_xfbml) { $facebook = '<fb:like href="' . $href . '" action="like" colorscheme="light" layout="button_count" show_faces="false"></fb:like>'; } else { $facebook = '<script src="http://connect.facebook.net/' . cmsFramework::getLocale() . '/all.js#xfbml=1"></script><fb:like layout="button_count" show_faces="false"></fb:like>'; } if ($this->Config->facebook_send) { $facebook .= '<div style="display:inline;margin-right: 15px;"><fb:send href="' . $href . '" colorscheme="light"></fb:send></div>'; } $googlePlusOne = ' <g:plusone href="' . $href . '" size="medium"></g:plusone> <script type="text/javascript" src="http://apis.google.com/js/plusone.js"></script> '; return $googlePlusOne . $twitter . $facebook; }
function _postVote() { # Check if FB integration for reviews is enabled $facebook_integration = Sanitize::getBool($this->Config, 'facebook_enable') && Sanitize::getBool($this->Config, 'facebook_reviews'); if (!$facebook_integration) { return; } $review_id = Sanitize::getInt($this->params, 'id'); # First check - review id if (!$review_id) { return; } $facebook = $this->_getFBClass(); # Second check - FB session if ($fbsession = $facebook->getSession()) { try { //get user id $uid = $facebook->getUser(); $user = $facebook->api('/me'); $fql = "SELECT publish_stream FROM permissions WHERE uid = " . $uid; $param = array('method' => 'fql.query', 'query' => $fql, 'callback' => ''); $fqlResult = $facebook->api($param); if (!$fqlResult[0]['publish_stream']) { return false; } else { $review = $this->Review->findRow(array('conditions' => array('Review.id = ' . $review_id)), array()); $this->Everywhere->loadListingModel($this, $review['Review']['extension']); $listing = $this->Listing->findRow(array('conditions' => array('Listing.' . $this->Listing->realKey . ' = ' . $review['Review']['listing_id'])), array('afterFind')); $listing_url = $this->makeUrl($listing['Listing']['url']); # Publish stream permission granted so we can post on the user's wall! # Begin building the stream $fbArray $fbArray = array(); $fbArray['method'] = 'stream.publish'; $fbArray['message'] = sprintf($this->activities['vote helpful'], $listing['Listing']['title']); $fbArray['attachment'] = array('name' => $listing['Listing']['title'], 'href' => $listing_url, 'description' => strip_tags($review['Review']['comments'])); $fbArray['attachment']['properties'][__t("Website", true)] = array('text' => cmsFramework::getConfig('sitename'), 'href' => WWW_ROOT); $review['Rating']['average_rating'] > 0 and $fbArray['attachment']['properties'][__t("Rating", true)] = sprintf(__t("%s stars", true), round($review['Rating']['average_rating'], 1)); isset($listing['Listing']['images'][0]) and $fbArray['attachment']['media'] = array(array('type' => 'image', 'src' => WWW_ROOT . _JR_WWW_IMAGES . $listing['Listing']['images'][0]['path'], 'href' => $listing_url)); $fbArray['attachment'] = json_encode($fbArray['attachment']); $fbArray['action_links'] = json_encode(array(array('text' => __t("Read review", true), 'href' => $listing_url))); $fbArray['comments_xid'] = $listing['Listing']['listing_id']; if ($this->Config->facebook_optout) { return "FB.ui(" . json_encode($fbArray) . ")"; } $fb_update = $facebook->api($fbArray); return true; } } catch (Exception $o) { // Error reading permissions return false; } } return false; }
function _installfix() { // Load fields model App::import('Model', 'field', 'jreviews'); $FieldModel = new FieldModel(); $task = Sanitize::getString($this->data, 'task'); $msg = ''; $mambot_error = 0; switch ($task) { case 'fix_install_jreviews': if (!$this->_installPlugin()) { $msg = "There was a problem updating the database or copying the plugin files. Make sure the Joomla plugins/content folder is writable."; } break; case 'fix_content_fields': $output = ''; $rows = $this->_db->getTableFields(array('#__jreviews_content')); $columns = array_keys($rows['#__jreviews_content']); $sql = "SELECT name,type FROM #__jreviews_fields WHERE location = 'content'"; $this->_db->setQuery($sql); $fields = $this->_db->loadObjectList('name'); $missing = array(); foreach ($fields as $field) { if (!in_array($field->name, $columns)) { $output = $FieldModel->addTableColumn($field->name, $field->type, 'content'); } } $query = "DELETE FROM #__jreviews_fields WHERE name = ''"; $this->_db->setQuery($query); $output = $this->_db->query(); if ($output != '') { $msg = "There was a problem fixing one or more of the content fields"; } break; case 'fix_review_fields': $output = ''; $rows = $this->_db->getTableFields(array('#__jreviews_review_fields')); $columns = array_keys($rows['#__jreviews_review_fields']); $sql = "SELECT name,type FROM #__jreviews_fields WHERE location = 'review'"; $this->_db->setQuery($sql); $fields = $this->_db->loadObjectList('name'); $missing = array(); foreach ($fields as $field) { if (!in_array($field->name, $columns)) { $output = $FieldModel->addTableColumn($field->name, $field->type, 'review'); } } $query = "DELETE FROM #__jreviews_fields WHERE name = ''"; $this->_db->setQuery($query); $output = $this->_db->query(); if ($output != '') { $msg = "There was a problem fixing one or more of the review fields"; } break; default: break; } cmsFramework::redirect("index.php?option=com_jreviews", $msg); }
function plgAfterSave(&$model) { $data = array(); App::import('Model', 'activity', 'jreviews'); App::import('Helper', 'routes', 'jreviews'); $Activity = new ActivityModel(); $Routes = RegisterClass::getInstance('RoutesHelper'); $data['Activity']['user_id'] = $this->c->_user->id; $data['Activity']['email'] = $this->c->_user->email; $data['Activity']['created'] = gmdate('Y-m-d H:i:s'); $data['Activity']['ipaddress'] = $this->c->ipaddress; $data['Activity']['activity_new'] = isset($model->data['insertid']) ? 1 : 0; switch ($this->activityModel->name) { case 'Claim': //Get the full listing info to create proper permalinks $listing = $this->c->Listing->findRow(array('conditions' => array('Listing.id = ' . (int) $model->data['Claim']['listing_id'])), array()); $permalink = $Routes->content('', $listing, array('return_url' => true)); $permalink = cmsFramework::makeAbsUrl($permalink); $data['Activity']['activity_type'] = 'claim'; $data['Activity']['listing_id'] = $model->data['Claim']['listing_id']; $data['Activity']['extension'] = 'com_content'; $data['Activity']['activity_new'] = 1; $data['Activity']['permalink'] = $permalink; $Activity->store($data); break; case 'Listing': // Skip logging of admin actions on user listings // if($this->c->_user->id != $model->data['Listing']['created_by']) break; //Get the full listing info to create proper permalinks $listing = $this->c->Listing->findRow(array('conditions' => array('Listing.id = ' . (int) $model->data['Listing']['id']))); $permalink = $Routes->content('', $listing, array('return_url' => true)); $permalink = cmsFramework::makeAbsUrl($permalink); $data['Activity']['activity_type'] = 'listing'; $data['Activity']['email'] = Sanitize::getString($model->data, 'email'); $data['Activity']['listing_id'] = $model->data['Listing']['id']; $data['Activity']['extension'] = 'com_content'; $data['Activity']['permalink'] = $permalink; $Activity->store($data); break; case 'Review': // Skip logging of admin actions on user listings // if($this->c->_user->id != $model->data['Review']['userid']) break; $data['Activity']['activity_type'] = 'review'; $data['Activity']['listing_id'] = $model->data['Review']['pid']; $data['Activity']['review_id'] = $model->data['Review']['id']; $data['Activity']['extension'] = $model->data['Review']['mode']; $data['Activity']['value'] = round(Sanitize::getVar($model->data, 'average_rating'), 0); $data['Activity']['permalink'] = $Routes->reviewDiscuss('', array('review_id' => $data['Activity']['review_id']), array('return_url' => true)); $Activity->store($data); break; case 'OwnerReply': // Skip logging of admin actions on user listings // if($this->c->_user->id != $model->data['Listing']['created_by']) break; $data['Activity']['activity_type'] = 'owner_reply'; $data['Activity']['listing_id'] = $model->data['Listing']['listing_id']; $data['Activity']['review_id'] = $model->data['OwnerReply']['id']; $data['Activity']['extension'] = $model->data['Listing']['extension']; // Editing not yet implemented so all replies are new $data['Activity']['activity_new'] = 1; $data['Activity']['permalink'] = $Routes->reviewDiscuss('', array('review_id' => $data['Activity']['review_id']), array('return_url' => true)); $Activity->store($data); break; case 'Discussion': // Skip logging of admin actions on user listings // if($this->c->_user->id != $model->data['Discussion']['user_id']) break; // Get listing id and extension $this->c->_db->setQuery("\n SELECT \n Review.pid AS listing_id, Review.`mode` AS extension\n FROM \n #__jreviews_comments AS Review\n WHERE \n Review.id = " . $model->data['Discussion']['review_id']); // Get listing owner id and check if it matches the current user if ($listing = current($this->c->_db->loadAssocList())) { $data['Activity']['activity_type'] = 'review_discussion'; $data['Activity']['listing_id'] = $listing['listing_id']; $data['Activity']['review_id'] = $model->data['Discussion']['review_id']; $data['Activity']['post_id'] = $model->data['Discussion']['discussion_id']; $data['Activity']['extension'] = $listing['extension']; $data['Activity']['permalink'] = $Routes->reviewDiscuss('', array('review_id' => $data['Activity']['review_id']), array('return_url' => true)); $Activity->store($data); } break; case 'Report': $data['Activity']['activity_type'] = $model->data['Report']['post_id'] ? 'discussion_report' : 'review_report'; $data['Activity']['listing_id'] = $model->data['Report']['listing_id']; $data['Activity']['review_id'] = $model->data['Report']['review_id']; $data['Activity']['extension'] = $model->data['Report']['extension']; // Editing not yet implemented so all replies are new $data['Activity']['activity_new'] = 1; $data['Activity']['permalink'] = $Routes->reviewDiscuss('', array('review_id' => $data['Activity']['review_id']), array('return_url' => true)); $Activity->store($data); break; case 'Vote': // Get listing id and extension $this->c->_db->setQuery("\n SELECT \n Review.pid AS listing_id, Review.`mode` AS extension\n FROM \n #__jreviews_comments AS Review\n WHERE \n Review.id = " . $model->data['Vote']['review_id']); // Get listing owner id and check if it matches the current user if ($listing = current($this->c->_db->loadAssocList())) { $data['Activity']['activity_type'] = 'helpful_vote'; $data['Activity']['listing_id'] = $listing['listing_id']; $data['Activity']['review_id'] = $model->data['Vote']['review_id']; $data['Activity']['helpful_vote_id'] = $model->data['Vote']['vote_id']; $data['Activity']['extension'] = $listing['extension']; $data['Activity']['value'] = $model->data['Vote']['vote_yes']; $data['Activity']['permalink'] = $Routes->reviewDiscuss('', array('review_id' => $data['Activity']['review_id']), array('return_url' => true)); $Activity->store($data); } break; } $this->published = false; // Run once. With paid listings it is possible for a plugin to run a 2nd time when the order is processed together with the listing (free) }
function startup(&$controller) { $this->c =& $controller; if (!$this->runPlugin($controller)) { return false; } // Initialize vars $center = array(); $address = ''; $lat = 0; $lon = 0; if (!isset($controller->Config)) { $controller->Config = Configure::read('JreviewsSystem.Config'); } if (!isset($controller->Access)) { $controller->Config = Configure::read('JreviewsSystem.Access'); } $this->max_radius = Sanitize::getInt($controller->Config, 'geomaps.max_radius', $this->max_radius); $this->jr_lat = Sanitize::getString($controller->Config, 'geomaps.latitude'); $this->jr_lon = Sanitize::getString($controller->Config, 'geomaps.longitude'); if ($this->jr_lat == '' || $this->jr_lon == '') { return false; } // Setup vars used in startup and other plugin methods $this->google_url = Sanitize::getString($this->c->Config, 'geomaps.google_url', 'http://maps.google.com'); $this->google_api_key = trim(Sanitize::getString($controller->Config, 'geomaps.google_key')); $this->google_api_url = $this->google_url . "/maps?file=api&v=2&async=2&key={$this->google_api_key}&sensor=false"; $search_method = Sanitize::getString($controller->Config, 'geomaps.search_method', 'address'); // address/disabled $search_address_field = Sanitize::getString($controller->Config, 'geomaps.advsearch_input'); $default_radius = Sanitize::getString($controller->Config, 'geomaps.radius'); $this->distance_metric = array('mi' => __t("Miles", true), 'km' => __t("Km", true)); $this->distance_in = Sanitize::getString($controller->Config, 'geomaps.radius_metric', 'mi'); $this->jr_address1 = Sanitize::getString($controller->Config, 'geomaps.address1'); $this->jr_address2 = Sanitize::getString($controller->Config, 'geomaps.address2'); $this->jr_city = Sanitize::getString($controller->Config, 'geomaps.city'); $this->jr_state = Sanitize::getString($controller->Config, 'geomaps.state'); $this->jr_postal_code = Sanitize::getString($controller->Config, 'geomaps.postal_code'); $this->jr_country = Sanitize::getString($controller->Config, 'geomaps.country'); $this->country_def = Sanitize::getString($controller->Config, 'geomaps.default_country'); $this->gid = $controller->Access->gid; $this->address_fields = array_filter(array('address1' => $this->jr_address1, 'address2' => $this->jr_address2, 'city' => $this->jr_city, 'state' => $this->jr_state, 'postal_code' => $this->jr_postal_code, 'country' => $this->jr_country)); $this->geo_fields = array('lat' => $this->jr_lat, 'lon' => $this->jr_lon); $this->c->set(array('address_fields' => $this->address_fields, 'geo_fields' => $this->geo_fields)); /** * Address search checks */ if (isset($controller->data['Field']['Listing'])) { $address = Sanitize::getString($controller->data['Field']['Listing'], $search_address_field); } else { $address = Sanitize::getString($controller->params, $search_address_field); $lat = Sanitize::getFloat($controller->params, $this->jr_lat); $lon = Sanitize::getFloat($controller->params, $this->jr_lon); } /** * Plugin does different things for different controller methods */ switch ($controller->name) { case 'com_content': $this->published = true; $controller->Listing->cacheCallbacks[] = 'plgAfterAfterFind'; $controller->Listing->fields[] = "`Field`.{$this->jr_lat} AS `Geomaps.lat`"; $controller->Listing->fields[] = "`Field`.{$this->jr_lon} AS `Geomaps.lon`"; $controller->Listing->fields[] = "JreviewsCategory.marker_icon AS `Geomaps.icon`"; break; case 'listings': switch ($controller->action) { // Load the geomaps js library case 'create': // Submit a new listing // Submit a new listing case 'edit': // Edit a listing $this->published = true; $Html = new HtmlHelper(); $Html->app = 'jreviews'; $jsGlobals = 'var GeomapsGoogleApi = "' . $this->google_api_url . '";'; $jsGlobals .= 'var jr_lat = "' . $this->jr_lat . '";'; $jsGlobals .= 'var jr_lon = "' . $this->jr_lon . '";'; $jsGlobals .= 'var jr_country_def = "' . $this->country_def . '";'; $jsGlobals .= 'var geoAddressObj = {};'; foreach ($this->address_fields as $key => $field) { $jsGlobals .= "geoAddressObj.{$key} = '{$field}';"; } cmsFramework::addScript($controller->makeJS($jsGlobals), true); $Html->js('geomaps', true); if ($controller->action == 'edit') { $mapit_field = Sanitize::getString($controller->Config, 'geomaps.mapit_field'); if ($mapit_field) { $response = "jQuery(document).ready(function() { \r\n jQuery('#{$mapit_field}','#jr_listingForm').after('<span id=\"gm_geocode\">\r\n <input class=\"jrButton\" type=\"button\" onclick=\"geomaps.mapPopupSimple();\" value=\"" . __t("Map it", true) . "\" /> \r\n <input class=\"jrButton\" type=\"button\" onclick=\"geomaps.clearLatLng();\" value=\"" . __t("Clear LatLng", true) . "\" />\r\n </span>');\r\n });"; cmsFramework::addScript($controller->makeJS($response), true); } } break; // Add geomaps buttons after form is loaded // Add geomaps buttons after form is loaded case '_loadForm': // New listing - Loads submit listing form after category selection $this->published = true; $mapit_field = Sanitize::getString($controller->Config, 'geomaps.mapit_field'); if ($mapit_field) { $response = array(); $response[] = "\r\n jQuery('#gm_geocode').remove();jQuery('#{$mapit_field}','#jr_listingForm').after('<span id=\"gm_geocode\"><input class=\"jrButton\" type=\"button\" onclick=\"geomaps.mapPopupSimple();\" value=\"" . __t("Map it", true) . "\" /> <input class=\"jrButton\" type=\"button\" onclick=\"geomaps.clearLatLng();\" value=\"" . __t("Clear LatLng", true) . "\" /></span>');\r\n jQuery('#gm_geocode').find(':input').removeAttr('disabled');\r\n "; $controller->afterAjaxResponse = $response; } break; case '_save': // Checks if $isNew = Sanitize::getInt($controller->data['Listing'], 'id', 0) == 0 ? true : false; if (Sanitize::getInt($controller->Config, 'geomaps.autogeocode_new') && $isNew && isset($controller->data['Field']) && (Sanitize::getFloat($controller->data['Field']['Listing'], $this->jr_lat, null) == null || Sanitize::getFloat($controller->data['Field']['Listing'], $this->jr_lon, null) == null)) { // Build whole address from fields $address = ''; foreach ($this->address_fields as $key => $field) { ${$field} = Sanitize::getVar($controller->data['Field']['Listing'], $field, ''); if (${$field} != '') { $address .= ' ' . ${$field}; } elseif ($field == 'section') { $address .= " " . Sanitize::getString($controller->data, 'section'); } elseif ($field == 'parent_category') { $address .= " " . Sanitize::getString($controller->data, 'parent_category'); } elseif ($field == 'category') { $address .= " " . Sanitize::getString($controller->data, 'category'); } } if ($address != '' && !Sanitize::getVar($controller->data['Field']['Listing'], $this->jr_country, false) && $this->country_def != '') { $address .= ' ' . $this->country_def; } if ($address != '') { // Geocode address App::import('Component', 'geocoding'); $Geocoding = ClassRegistry::getClass('GeocodingComponent'); $Geocoding->Config =& $controller->Config; $response = $Geocoding->geocode($address); if ($response['status'] == 200) { $controller->data['Field']['Listing'][$this->jr_lat] = $response['lat']; $controller->data['__raw']['Field']['Listing'][$this->jr_lat] = $response['lat']; $controller->data['Field']['Listing'][$this->jr_lon] = $response['lon']; $controller->data['__raw']['Field']['Listing'][$this->jr_lon] = $response['lon']; } } } break; } break; case 'admin_listings': switch ($controller->action) { case 'index': case 'browse': case 'moderation': App::import('Helper', 'html'); $Html = new HtmlHelper(); $Html->app = 'jreviews'; $jsGlobals = 'var GeomapsGoogleApi = "' . $this->google_api_url . '";'; $jsGlobals .= 'var jr_lat = "' . $this->jr_lat . '";'; $jsGlobals .= 'var jr_lon = "' . $this->jr_lon . '";'; $jsGlobals .= 'var jr_country_def = "' . $this->country_def . '";'; $jsGlobals .= 'var geoAddressObj = {};'; foreach ($this->address_fields as $key => $field) { $jsGlobals .= "geoAddressObj.{$key} = '{$field}';"; } if ($controller->action == 'moderation') { ?> <script type="text/javascript"> /* <![CDATA[ */ <?php echo $jsGlobals; ?> if(null==jQuery('body').data('geomaps')){ jQuery.getScript('<?php echo $this->locateScript('geomaps'); ?> ',function(){jQuery('body').data('geomaps',1)}); } /* ]]> */ </script> <?php } else { cmsFramework::addScript($controller->makeJS($jsGlobals), true); $Html->js('geomaps', true); } break; case 'edit': $mapit_field = Sanitize::getString($controller->Config, 'geomaps.mapit_field'); if ($mapit_field) { $response = "jQuery('#{$mapit_field}').after('<span id=\"gm_geocode\"><input class=\"jrButton\" type=\"button\" onclick=\"geomaps.mapPopupSimple();\" value=\"" . __t("Map it", true) . "\" /> <input class=\"jrButton\" type=\"button\" onclick=\"geomaps.clearLatLng();\" value=\"" . __t("Clear LatLng", true) . "\" /></span>');"; $controller->pluginResponse = $response; } break; } break; // A search was performed, make distance the default ordering and copy the entered address to the search address field // A search was performed, make distance the default ordering and copy the entered address to the search address field case 'search': if ($search_method == 'disabled' || $address == '') { return; } if ($controller->action == '_process') { $this->published = true; // Enable the callbacks for this controller/method // Make distance the default ordering $controller->Config->list_order_default = 'distance'; if ($address != '' && in_array($search_method, array('address'))) { $controller->data['Field']['Listing'][$search_address_field] = $address; // Append default country if ($this->country_def != '') { $address .= ' ' . $this->country_def; } // Geocode address App::import('Component', 'geocoding'); $Geocoding = ClassRegistry::getClass('GeocodingComponent'); $Geocoding->Config =& $controller->Config; $response = $Geocoding->geocode($address); if ($response['status'] == 200) { $center = $response; } if ($center && !empty($center)) { $controller->data['Field']['Listing'][$this->jr_lat] = $center['lat']; $controller->data['Field']['Listing'][$this->jr_lon] = $center['lon']; unset($controller->data['Field']['Listing'][$this->jr_lat . '_operator']); unset($controller->data['Field']['Listing'][$this->jr_lon . '_operator']); } } } break; // Display search results // Display search results case 'categories': $controller->Listing->fields[] = "`Field`.{$this->jr_lat} AS `Geomaps.lat`"; $controller->Listing->fields[] = "`Field`.{$this->jr_lon} AS `Geomaps.lon`"; $controller->Listing->fields[] = "JreviewsCategory.marker_icon AS `Geomaps.icon`"; $this->published = true; // Enable the callbacks for this controller/method if ($search_method == 'disabled' || $lat == 0 || $lon == 0) { return; } if ($controller->action == 'search') { $radius = min(Sanitize::getFloat($controller->params, $this->radius_field, $default_radius), $this->max_radius); if ($search_method == 'disabled') { $this->published = false; return; } if ($lat != 0 && $lon != 0) { Configure::write('geomaps.enabled', true); // Used to show the Distance ordering in the jreviews.php helper in JReviews. $center = array('lat' => $lat, 'lon' => $lon); // Send center coordinates to theme $controller->set('GeomapsCenter', $center); $sort = $controller->params['order'] = Sanitize::getString($controller->params, 'order', 'distance'); // Clear address and coordinate field from parameters because it shouldn't be used on distance searches. Instead we use lat/lon via custom condition below unset($controller->params[$search_address_field], $controller->params['url'][$search_address_field], $controller->params[$this->jr_lat], $controller->params['url'][$this->jr_lat], $controller->params[$this->jr_lon], $controller->params['url'][$this->jr_lon]); $controller->passedArgs['url'] = preg_replace('/\\/' . $search_address_field . _PARAM_CHAR . '[\\p{L}-\\s0-9]+/i', '', $controller->passedArgs['url']); $controller->passedArgs['url'] = preg_replace('/\\/' . $search_address_field . _PARAM_CHAR . '[a-z0-9-\\s]+/i', '', $controller->passedArgs['url']); // One above doesn't work well in all cases, but required for non-latin characters in address $controller->passedArgs['url'] = preg_replace('/\\/' . $this->jr_lat . _PARAM_CHAR . '[\\-a-z0-9\\.\\s]+/i', '', $controller->passedArgs['url']); $controller->passedArgs['url'] = preg_replace('/\\/' . $this->jr_lon . _PARAM_CHAR . '[\\-a-z0-9\\.\\s]+/i', '', $controller->passedArgs['url']); // Create a square around the center to limite the number of rows processed in the zip code table // http://www.free-zipcodes.com/ // http://www.mysqlconf.com/mysql2008/public/schedule/detail/347 $degreeDistance = $this->distance_in == 'mi' ? 69.172 : 40076 / 360; $lat_range = $radius / $degreeDistance; $lon_range = $radius / abs(cos($center['lat'] * pi() / 180) * $degreeDistance); $min_lat = $center['lat'] - $lat_range; $max_lat = $center['lat'] + $lat_range; $min_lon = $center['lon'] - $lon_range; $max_lon = $center['lon'] + $lon_range; $squareArea = "`Field`.{$this->jr_lat} BETWEEN {$min_lat} AND {$max_lat} AND `Field`.{$this->jr_lon} BETWEEN {$min_lon} AND {$max_lon}"; // calculate the distance between two sets of longitude/latitude coordinates // From http://www.mysqlconf.com/mysql2008/public/schedule/detail/347 if ($this->distance_in == 'km') { $controller->Listing->fields['distance'] = "6371 * 2 * ASIN(SQRT( POWER(SIN(({$center['lat']} - {$this->jr_lat}) * pi()/180 / 2), 2) + \r\n COS({$center['lat']} * pi()/180) * COS({$this->jr_lat} * pi()/180) * POWER(SIN(({$center['lon']} -{$this->jr_lon}) * pi()/180 / 2), 2) )) AS `Geomaps.distance`"; } if ($this->distance_in == 'mi') { $controller->Listing->fields['distance'] = "3956 * 2 * ASIN(SQRT( POWER(SIN(({$center['lat']} - {$this->jr_lat}) * pi()/180 / 2), 2) + \r\n COS({$center['lat']} * pi()/180) * COS({$this->jr_lat} * pi()/180) * POWER(SIN(({$center['lon']} -{$this->jr_lon}) * pi()/180 / 2), 2) )) AS `Geomaps.distance`"; } $controller->Listing->conditions[] = $squareArea; if ($sort == 'distance') { $controller->Listing->order[] = '`Geomaps.distance` ASC'; } // Makes sure that only listings within given radius are shown because square limit might include further points // $controller->Listing->having[] = '`Geomaps.distance` <= ' . (int) $radius; // Override search theme suffix $theme_suffix = Sanitize::getString($controller->Config, 'geomaps.search_suffix'); if ($theme_suffix != '') { $controller->viewSuffix = $theme_suffix; } } } break; } }
/** * Dynamic form creation for custom fields using custom layout - {field tags} in view file * * @param unknown_type $formFields * @param unknown_type $fieldLocation * @param unknown_type $search * @param unknown_type $selectLabel * @return array of form inputs for each field */ function getFormFields(&$formFields, $fieldLocation = 'listing', $search = null, $selectLabel = 'Select') { if (!is_array($formFields)) { return ''; } $groupSet = array(); $fieldLocation = Inflector::camelize($fieldLocation); foreach ($formFields as $group => $fields) { $inputs = array(); foreach ($fields['Fields'] as $key => $value) { // Convert radio button to checkbox if multiple search is enabled in the config settings if ($search && $this->Config->search_field_conversion && $value['type'] == 'radiobuttons') { $value['type'] = 'checkboxes'; } $inputs["data[Field][{$fieldLocation}][{$key}]"] = array('id' => $value['name'] . $this->form_id, 'type' => $this->types[$value['type']]); // $inputs["data[Field][$fieldLocation][$key]"]['label'] = $value['title']; $inputs["data[Field][{$fieldLocation}][{$key}]"]['div'] = array(); # Add tooltip if (!$search && Sanitize::getString($value, 'description', null)) { $inputs["data[Field][{$fieldLocation}][{$key}]"]['label']['text'] .= '<span class="jr_infoTip" title="' . htmlspecialchars($value['description'], ENT_QUOTES, cmsFramework::getCharset()) . '"> </span>'; } // Assign field classes switch ($value['type']) { case 'decimal': case 'integer': $inputs["data[Field][{$fieldLocation}][{$key}]"]['class'] = 'shortField'; break; case 'website': $inputs["data[Field][{$fieldLocation}][{$key}]"]['class'] = 'mediumField'; break; case 'text': $inputs["data[Field][{$fieldLocation}][{$key}]"]['class'] = 'mediumField'; break; } if (in_array($value['type'], $this->multipleTypes)) { $inputs["data[Field][{$fieldLocation}][{$key}]"]['multiple'] = 'multiple'; $inputs["data[Field][{$fieldLocation}][{$key}]"]['size'] = $value['properties']['size']; } if (isset($value['optionList']) && $value['type'] == 'select') { $value['optionList'] = array('' => $selectLabel) + $value['optionList']; } if (isset($value['optionList'])) { $inputs["data[Field][{$fieldLocation}][{$key}]"]['options'] = $value['optionList']; } # Add click2add capability for select lists if ($fieldLocation == 'Listing' && !$search && $this->types[$value['type']] == 'select' && $value['properties']['click2add']) { $click2AddLink = $this->Html->link($this->Html->image($this->viewImages . 'option_add.png', array('border' => 0, 'style' => 'margin-left:5px;')), 'javascript:void(0);', array('sef' => false, 'onclick' => "jQuery('#click2Add_{$value['field_id']}').toggle('slow');")); $click2AddInput = $this->Form->text('option' . $value['field_id'], array('id' => 'option' . $value['field_id'])); $click2AddButton = $this->Form->button(__t("Submit", true), array('onclick' => "submitOption({$value['field_id']},'{$value['name']}');", 'div' => false, 'id' => 'submitButton' . $value['field_id'], 'class' => 'button')); $inputs["data[Field][{$fieldLocation}][{$key}]"]['after'] = $click2AddLink . "<div id='click2Add_{$value['field_id']}' class='jr_fieldDiv jr_newFieldOption'>" . $click2AddInput . ' ' . $click2AddButton . "<span id='spinner" . $value['field_id'] . "' style='display: none;'><img alt='loading' src='" . $this->viewImages . "loading.gif' /></span>" . '</div>'; } # Prefill values when editing if (isset($value['selected'])) { $inputs["data[Field][{$fieldLocation}][{$key}]"]['value'] = $value['selected']; } # Add search operator fields for date, decimal and integer fields if ($search && in_array($value['type'], $this->operatorTypes)) { $options = array('equal' => '=', 'higher' => '>=', 'lower' => '<=', 'between' => __t("between", true)); $inputs["data[Field][{$fieldLocation}][{$key}]"]['multiple'] = true; // convert field to array input for range searches $attributes = array('id' => $key . 'high', 'multiple' => true, 'class' => 'shortField'); $selected = ''; if ($this->types[$value['type']] == 'date') { $attributes['class'] = 'dateField datepicker'; } // This is the high value input in a range search $inputs["data[Field][{$fieldLocation}][{$key}]"]['after'] = '<span id="' . $key . 'highDiv" style="display:none;"> ' . $this->Form->text("data[Field][Listing][{$key}]", $attributes) . '</span>'; $inputs["data[Field][{$fieldLocation}][{$key}]"]['between'] = $this->Form->select("data[Field][Listing][{$key}_operator]", $options, $selected, array('class' => 'jr_dateOperator input', 'onchange' => "jreviews.search.showRange(this,'{$key}high');")); } # Input styling if ($this->types[$value['type']] == 'date') { $inputs["data[Field][{$fieldLocation}][{$key}]"]['class'] = 'dateField datepicker'; $inputs["data[Field][{$fieldLocation}][{$key}]"]['readonly'] = 'readonly'; } if (in_array($this->types[$value['type']], $this->legendTypes)) { // Input styling $inputs["data[Field][{$fieldLocation}][{$key}]"]['option_class'] = 'jr_fieldOption'; $inputs["data[Field][{$fieldLocation}][{$key}]"]['after'] = $this->Html->div('clr', ' '); // To break the float } } $groupSet[$group] = array('fieldset' => false, 'legend' => false); foreach ($inputs as $dataKey => $dataValue) { $groupSet[$group][$dataKey] = $dataValue; } } $output = array(); foreach ($groupSet as $group => $form) { $output = array_merge($output, $this->Form->inputs($form, null, null, true)); } return $output; }
function index() { /* if($this->_user->id === 0) { $this->cacheAction = Configure::read('Cache.expires'); }*/ // Required for ajax pagination to remember module settings $ids = $conditions = $joins = $order = $having = array(); $module_id = Sanitize::getInt($this->params, 'module_id', Sanitize::getInt($this->data, 'module_id')); if (!isset($this->params['module'])) { $this->params['module'] = array(); } // For direct calls to the controller # Find the correct set of params to use if ($this->ajaxRequest && Sanitize::getInt($this->params, 'listing_id')) { $this->params['module'] = array_merge($this->params['module'], $this->__processListingTypeWidgets($conditions)); } elseif ($this->ajaxRequest && empty($this->params['module']) && $module_id) { $query = "SELECT params FROM #__modules WHERE id = " . $module_id; $this->_db->setQuery($query); $this->params['module'] = stringToArray($this->_db->loadResult()); } if ($this->abort) { return $this->ajaxResponse('', false); } # Read module parameters $dir_id = Sanitize::getString($this->params['module'], 'dir'); $section_id = Sanitize::getString($this->params['module'], 'section'); $cat_id = Sanitize::getString($this->params['module'], 'category'); $listing_id = Sanitize::getString($this->params['module'], 'listing'); $created_by = Sanitize::getString($this->params['module'], 'owner'); $criteria_id = Sanitize::getString($this->params['module'], 'criteria'); $limit = Sanitize::getInt($this->params['module'], 'module_limit', 5); $total = min(50, Sanitize::getInt($this->params['module'], 'module_total', 10)); $extension = Sanitize::getString($this->params['module'], 'extension'); $extension = $extension != '' ? $extension : 'com_content'; $sort = Sanitize::getString($this->params['module'], 'listing_order'); if (in_array($sort, array('random', 'featuredrandom'))) { srand((double) microtime() * 1000000); $this->params['rand'] = rand(); } # Prevent sql injection $token = Sanitize::getString($this->params, 'token'); $tokenMatch = 0 === strcmp($token, cmsFramework::formIntegrityToken($this->params, array('module', 'module_id', 'form', 'data'), false)); isset($this->params['module']) and $this->viewSuffix = Sanitize::getString($this->params['module'], 'tmpl_suffix'); if (isset($this->Listing)) { $this->Listing->_user = $this->_user; // This parameter determines the module mode $custom_order = Sanitize::getString($this->params['module'], 'custom_order'); $custom_where = Sanitize::getString($this->params['module'], 'custom_where'); if ($extension != 'com_content' && in_array($sort, array('topratededitor', 'featuredrandom', 'rhits'))) { echo "You have selected the {$sort} mode which is not supported for components other than com_content. Please read the tooltips in the module parameters for more info on allowed settings."; return; } # Category auto detect if (Sanitize::getInt($this->params['module'], 'cat_auto') && $extension == 'com_content') { $ids = CommonController::_discoverIDs($this); extract($ids); } # Set conditionals based on configuration parameters if ($extension == 'com_content') { // Perform tag replacement for listing_id to allow for related listing queries if (Sanitize::getString($this->params, 'view') == 'article' && $custom_where != '') { $curr_listing_id = Sanitize::getInt($this->params, 'id'); $custom_where = str_replace('{listing_id}', $curr_listing_id, $custom_where); } // Only works for core articles $conditions = array_merge($conditions, array('Listing.state = 1', '( Listing.publish_up = "' . NULL_DATE . '" OR DATE(Listing.publish_up) <= DATE("' . _CURRENT_SERVER_TIME . '") )', '( Listing.publish_down = "' . NULL_DATE . '" OR DATE(Listing.publish_down) >= DATE("' . _CURRENT_SERVER_TIME . '") )')); if ($this->cmsVersion == CMS_JOOMLA15) { // $conditions[] = 'Section.access <= ' . $this->Access->getAccessId(); $conditions[] = 'Category.access <= ' . $this->Access->getAccessId(); $conditions[] = 'Listing.access <= ' . $this->Access->getAccessId(); } else { $conditions[] = 'Category.access IN (' . $this->Access->getAccessLevels() . ')'; $conditions[] = 'Listing.access IN (' . $this->Access->getAccessLevels() . ')'; } // Remove unnecessary fields from model query $this->Listing->modelUnbind(array('Listing.fulltext AS `Listing.description`', 'Listing.metakey AS `Listing.metakey`', 'Listing.metadesc AS `Listing.metadesc`', 'User.email AS `User.email`')); if (!empty($cat_id)) { $conditions[] = $this->cmsVersion == CMS_JOOMLA15 ? 'Listing.catid IN (' . cleanIntegerCommaList($cat_id) . ')' : 'ParentCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')'; } else { unset($this->Listing->joins['ParentCategory']); } empty($cat_id) and !empty($section_id) and $conditions[] = 'Listing.sectionid IN (' . cleanIntegerCommaList($section_id) . ')'; empty($cat_id) and !empty($dir_id) and $conditions[] = 'JreviewsCategory.dirid IN (' . cleanIntegerCommaList($dir_id) . ')'; empty($cat_id) and !empty($criteria_id) and $conditions[] = 'JreviewsCategory.criteriaid IN (' . cleanIntegerCommaList($criteria_id) . ')'; } else { if (Sanitize::getInt($this->params['module'], 'cat_auto') && method_exists($this->Listing, 'catUrlParam')) { if ($cat_id = Sanitize::getInt($this->passedArgs, $this->Listing->catUrlParam())) { $conditions[] = 'JreviewsCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')'; } } elseif ($cat_id) { $conditions[] = 'JreviewsCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')'; } } $listing_id and $conditions[] = "Listing.{$this->Listing->realKey} IN (" . cleanIntegerCommaList($listing_id) . ")"; switch ($sort) { case 'random': $order[] = 'RAND(' . $this->params['rand'] . ')'; break; case 'featured': $conditions[] = 'Field.featured = 1'; break; case 'featuredrandom': $conditions[] = 'Field.featured = 1'; $order[] = 'RAND(' . $this->params['rand'] . ')'; break; case 'topratededitor': // $conditions[] = 'Totals.editor_rating > 0'; $sort = 'editor_rating'; break; // Editor rating sorting options dealt with in the Listing->processSorting method } # Custom WHERE $tokenMatch and $custom_where and $conditions[] = $custom_where; # Filtering options $having = array(); // Listings submitted in the past x days $entry_period = Sanitize::getInt($this->params['module'], 'filter_listing_period'); if ($entry_period > 0 && $this->Listing->dateKey) { $conditions[] = "Listing.{$this->Listing->dateKey} >= DATE_SUB('" . _CURRENT_SERVER_TIME . "', INTERVAL {$entry_period} DAY)"; } // Listings with reviews submitted in past x days $review_period = Sanitize::getInt($this->params['module'], 'filter_review_period'); if ($review_period > 0) { $conditions[] = "Review.created >= DATE_SUB(CURDATE(), INTERVAL {$review_period} DAY)"; $joins[] = 'LEFT JOIN #__jreviews_comments AS Review ON Listing.' . $this->Listing->realKey . ' = Review.pid'; } // Listings with review count higher than $filter_review_count = Sanitize::getInt($this->params['module'], 'filter_review_count'); $filter_review_count > 0 and $conditions[] = "Totals.user_rating_count >= " . $filter_review_count; // Listings with avg rating higher than $filter_avg_rating = Sanitize::getFloat($this->params['module'], 'filter_avg_rating'); $filter_avg_rating > 0 and $conditions[] = 'Totals.user_rating >= ' . $filter_avg_rating; $this->Listing->group = array(); // Exlude listings without ratings from the results $join_direction = in_array($sort, array('rating', 'rrating', 'topratededitor', 'reviews')) ? 'INNER' : 'LEFT'; $this->Listing->joins['Total'] = "{$join_direction} JOIN #__jreviews_listing_totals AS Totals ON Totals.listing_id = Listing.{$this->Listing->realKey} AND Totals.extension = " . $this->quote($extension); # Modify query for correct ordering. Change FIELDS, ORDER BY and HAVING BY directly in Listing Model variables if ($tokenMatch and $custom_order) { $this->Listing->order[] = $custom_order; } elseif (empty($order) && $extension == 'com_content') { $this->Listing->processSorting('module', $sort); // Modifies Listing model order var directly } elseif (empty($order) && ($order = $this->__processSorting($sort))) { $order = array($order); } $fields = array('Totals.user_rating AS `Review.user_rating`', 'Totals.user_rating_count AS `Review.user_rating_count`', 'Totals.user_comment_count AS `Review.review_count`', 'Totals.editor_rating AS `Review.editor_rating`', 'Totals.editor_rating_count AS `Review.editor_rating_count`', 'Totals.editor_comment_count AS `Review.editor_review_count`'); $queryData = array('fields' => !isset($this->Listing->fields['editor_rating']) ? $fields : array(), 'joins' => $joins, 'conditions' => $conditions, 'limit' => $total, 'having' => $having); isset($order) and !empty($order) and $queryData['order'] = $order; // Trigger addFields for $listing results. Checked in Everywhere model $this->Listing->addFields = true; $listings = $this->Listing->findAll($queryData); $count = count($listings); } else { $listings = array(); $count = 0; } unset($this->Listing); # Send variables to view template $this->set(array('autodetect_ids' => $ids, 'subclass' => 'listing', 'listings' => $listings, 'total' => $count, 'limit' => $limit)); $this->_completeModuleParamsArray(); $page = $this->ajaxRequest && empty($listings) ? '' : $this->render('modules', 'listings'); /* if($this->_user->id === 0 && $this->ajaxRequest) { $path = $this->here; $this->here == '/' and $path = 'home'; $cache_fname = Inflector::slug($path) . '.php'; $now = time(); $cacheTime = is_numeric($this->cacheAction) ? $now + $this->cacheAction : strtotime($this->cacheAction, $now); $fileHeader = '<!--cachetime:' . $cacheTime . '-->'; cache('views' . DS . $cache_fname, $fileHeader . $this->ajaxResponse($page,false), $this->cacheAction); }*/ return $this->ajaxRequest ? $this->ajaxResponse($page, false) : $page; }
function _saveEdit() { $this->autoRender = false; $this->autoLayout = false; $this->Discussion->isNew = false; $response = array(); # Load the notifications observer model component and initialize it. # Done here so it only loads on save and not for all controlller actions. $this->components = array('security'); $this->__initComponents(); # Validate form token if ($this->invalidToken) { return $this->ajaxError(s2Messages::invalidToken()); } $post_id = Sanitize::getInt($this->data['Discussion'], 'discussion_id'); $isNew = (bool) (!$post_id); if ($isNew && !$this->Access->canAddPost()) { return $this->ajaxError(s2Messages::accessDenied()); } elseif (!$isNew) { # Stop form data tampering $owner_id = $this->Discussion->getPostOwner($post_id); $formToken = cmsFramework::formIntegrityToken($this->data['Discussion'], $this->formTokenKeys, false); if (!$this->Access->canEditPost($owner_id) || !$this->__validateToken($formToken)) { return $this->ajaxError(s2Messages::accessDenied()); } } $text = str_replace("\n", "<br />", htmlspecialchars($this->data['Discussion']['text'], ENT_QUOTES)); $this->data['Discussion']['modified'] = date('Y-m-d H:i:s'); $this->data['Discussion']['approved'] = 1; if ($this->Discussion->store($this->data)) { $update_text = __t("Your comment has been updated.", true); $response[] = "jQuery('#jr_post{$post_id}').hide('fast');"; $response[] = "jQuery('#jr_post{$post_id} .jr_comments').html('{$text}');"; $response[] = "jQuery('#jr_post{$post_id}').slideDown(1000);"; return $this->ajaxUpdatePage('jr_post' . $post_id, $update_text, '', compact('response')); } return $this->ajaxError(__t("There was an error saving the comment.", true, true)); }
function listings() { // Initialize variables $id = Sanitize::getInt($this->params, 'id'); $option = Sanitize::getString($this->params, 'option'); $view = Sanitize::getString($this->params, 'view'); $menu_id = Sanitize::getString($this->params, 'Itemid'); // Read params $cat_id = ''; $criteria_ids = ''; $in_detail_view = false; $detail_view = 1; $dir_id = Sanitize::getString($this->params, 'dir'); $section_id = Sanitize::getString($this->params, 'section'); $cat_id = Sanitize::getString($this->params, 'cat'); $extension = 'com_content'; $custom_where = null; $custom_fields = array(); $click2search_auto = false; $cache = 0; $radius = 0; $mode = 0; if (isset($this->params['module'])) { // Read module parameters $click2search_auto = Sanitize::getBool($this->params['module'], 'click2search_auto', false); $custom_where = Sanitize::getString($this->params['module'], 'custom_where'); $filter = Sanitize::getString($this->params['module'], 'filter'); $detail_view = Sanitize::getString($this->params['module'], 'detail_view', 1); $dir_id = Sanitize::getString($this->params['module'], 'dir'); $section_id = Sanitize::getString($this->params['module'], 'section'); $cat_id = Sanitize::getString($this->params['module'], 'category'); $listing_id = Sanitize::getString($this->params['module'], 'listing'); $criteria_ids = Sanitize::getString($this->params['module'], 'criteria'); $limit_results = Sanitize::getInt($this->params['module'], 'limit_results'); $mode = Sanitize::getInt($this->params['module'], 'mode', 0); $custom_fields = str_replace(" ", "", Sanitize::getString($this->Config, 'geomaps.infowindow_fields')); $custom_fields = $custom_fields != '' ? explode(",", $custom_fields) : array(); /** * 0 - Normal * 1 - GeoTargeting * 2 - Custom center and zoom */ $radius = Sanitize::getInt($this->params['module'], 'radius'); $cache = $mode == 1 ? 0 : Sanitize::getInt($this->params['module'], 'cache_map'); $custom_lat = Sanitize::getFloat($this->params['module'], 'custom_lat'); $custom_lon = Sanitize::getFloat($this->params['module'], 'custom_lon'); if ($mode == 2 && ($custom_lat == 0 || $custom_lon == 0)) { echo __t("You selected the Custom Center mode, but did not specify the coordinates."); return; } } # Prevent sql injection $token = Sanitize::getString($this->params, 'token'); $tokenMatch = 0 === strcmp($token, cmsFramework::formIntegrityToken($this->params, array('module', 'module_id', 'form', 'data'), false)); $filters = $listing_id != '' || $dir_id != '' || $section_id != '' || $cat_id != ''; if (!$filters && $id > 0 && 'article' == $view && 'com_content' == $option) { $sql = "SELECT catid FROM #__content WHERE id = " . $id; $this->_db->setQuery($sql); $cat_id_host_page = $this->_db->loadResult(); if (!empty($cat_id_host_page) && $this->Category->isJreviewsCategory($cat_id_host_page)) { $in_detail_view = true; $cat_id = $cat_id_host_page; } } $detail_view = $this->params['module']['detail_view'] = (int) ($detail_view && $in_detail_view); # Custom WHERE $tokenMatch and $custom_where and $conditions[] = $custom_where; if ($click2search_auto && isset($this->params['tag'])) { $field = 'jr_' . Sanitize::getString($this->params['tag'], 'field'); $value = Sanitize::getString($this->params['tag'], 'value'); $query = "SELECT Field.type FROM #__jreviews_fields AS Field WHERE Field.name = " . $this->quote($field); $this->_db->setQuery($query); $type = $this->_db->loadResult(); if (in_array($type, array('select', 'selectmultiple', 'checkboxes', 'radiobuttons'))) { $conditions[] = "Field.{$field} LIKE " . $this->quoteLike('*' . $value . '*'); } else { $conditions[] = "Field.{$field} = " . $this->quote($value); } } # Category auto detect if (isset($this->params['module']) && Sanitize::getInt($this->params['module'], 'cat_auto') && $extension == 'com_content') { $ids = CommonController::_discoverIDs($this); extract($ids); } $autodetect = compact('dir_id', 'section_id', 'cat_id'); // Check for cached version if cache enabled if ($cache) { $params = array(); foreach ($this->params as $key => $value) { if ((!is_array($value) || $key == 'module') && !in_array($key, array('page', 'limit', 'order', 'Itemid'))) { $params[$key] = $value; } } $cache_key = array_merge($params, $autodetect, Sanitize::getVar($this->params, 'tag', array())); $json_filename = 'geomaps_' . md5(serialize($cache_key)) . '.json'; $json_data = S2Cache::read($json_filename); if ($json_data && $json_data != '') { $this->set('json_data', $json_data); S2Cache::write($json_filename, $json_data); return $this->render('modules', 'geomaps'); } } $this->Listing->fields = array('Listing.id AS `Listing.listing_id`', 'Listing.title AS `Listing.title`', 'Listing.images AS `Listing.images`', 'CASE WHEN CHAR_LENGTH(Listing.alias) THEN Listing.alias ELSE "" END AS `Listing.slug`', 'Category.id AS `Listing.cat_id`', 'CASE WHEN CHAR_LENGTH(Category.alias) THEN Category.alias ELSE Category.title END AS `Category.slug`', 'Listing.sectionid AS `Listing.section_id`', 'JreviewsCategory.criteriaid AS `Criteria.criteria_id`', 'JreviewsCategory.dirid AS `Directory.dir_id`', 'JreviewsCategory.marker_icon AS `Geomaps.icon`', 'Field.featured AS `Listing.featured`', 'Totals.user_rating AS `Review.user_rating`', 'Totals.user_rating_count AS `Review.user_rating_count`', 'Totals.editor_rating AS `Review.editor_rating`', 'Totals.editor_rating_count AS `Review.editor_rating_count`', "Field.{$this->jr_lat} `Geomaps.lat`", "Field.{$this->jr_lon} `Geomaps.lon`", 'ListingType.state AS `Criteria.state`', 'ListingType.config AS `ListingType.config`'); if ($custom_lon != '' and $custom_lat != '') { $this->set('CustomCenter', array('lon' => $custom_lon, 'lat' => $custom_lat)); } // Geo Targeting OR Custom Center modes if ($mode == 1 || $mode == 2) { if ($mode == 1) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://www.geoplugin.net/php.gp?ip=' . s2GetIpAddress()); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); $geoData = unserialize(curl_exec($ch)); curl_close($ch); if (!empty($geoData) && isset($geoData['geoplugin_latitude']) && $geoData['geoplugin_latitude'] != '' && $geoData['geoplugin_longitude'] != '') { $center = array('lon' => $geoData['geoplugin_longitude'], 'lat' => $geoData['geoplugin_latitude']); } $this->set('geoLocation', $geoData); } if ($mode == 2) { $center = array('lon' => $custom_lon, 'lat' => $custom_lat); } if (!empty($center) && $radius > 0) { $distanceIn = Sanitize::getString($this->Config, 'geomaps.radius_metric', 'mi'); $degreeDistance = $distanceIn == 'mi' ? 69.172 : 40076 / 360; // Send center coordinates to theme $this->set('GeomapsCenter', $center); $lat_range = $radius / $degreeDistance; $lon_range = $radius / abs(cos($center['lat'] * pi() / 180) * $degreeDistance); $min_lat = $center['lat'] - $lat_range; $max_lat = $center['lat'] + $lat_range; $min_lon = $center['lon'] - $lon_range; $max_lon = $center['lon'] + $lon_range; $squareArea = "`Field`.{$this->jr_lat} BETWEEN {$min_lat} AND {$max_lat} AND `Field`.{$this->jr_lon} BETWEEN {$min_lon} AND {$max_lon}"; $conditions[] = $squareArea; } } // Create marker_icons array $marker_icons = array(); $icon_fields = array(); $field_images = array(); $query = "SELECT DISTINCT marker_icon FROM #__jreviews_categories WHERE marker_icon != ''"; $this->_db->setQuery($query); $icon_rows = $this->_db->loadAssocList(); foreach ($icon_rows as $icons) { $icon = (array) json_decode($icons['marker_icon']); if ($icon['field'] != '') { $icon_fields[$icon['field']] = "'" . $icon['field'] . "'"; } } if (!empty($icon_fields)) { foreach ($icon_fields as $field_key => $field) { if (substr($field_key, 0, 3) == 'jr_') { $this->Listing->fields[] = "Field.{$field_key} AS `Field.{$field_key}`"; } } } if (!empty($custom_fields)) { foreach ($custom_fields as $field) { $this->Listing->fields[] = "Field.{$field} AS `Field.{$field}`"; } } $this->Listing->joins = array("LEFT JOIN #__categories AS Category ON Listing.catid = Category.id", 'ParentCategory' => "LEFT JOIN #__categories AS ParentCategory ON Category.lft BETWEEN ParentCategory.lft AND ParentCategory.rgt", "LEFT JOIN #__jreviews_listing_totals AS Totals ON Totals.listing_id = Listing.id AND Totals.extension = 'com_content'", "LEFT JOIN #__jreviews_content AS `Field` ON Field.contentid = Listing.id", "INNER JOIN #__jreviews_categories AS JreviewsCategory ON Listing.catid = JreviewsCategory.id AND JreviewsCategory.`option` = 'com_content'", "LEFT JOIN #__jreviews_criteria AS ListingType ON JreviewsCategory.criteriaid = ListingType.id", "LEFT JOIN #__jreviews_directories AS Directory ON JreviewsCategory.dirid = Directory.id"); // Don't regroup the results by model name keys to save time $this->Listing->primaryKey = false; # Set conditionals based on configuration parameters if ($detail_view) { $conditions[] = 'Listing.id = ' . $id; } if (!empty($cat_id)) { $conditions[] = $this->cmsVersion == CMS_JOOMLA15 ? 'Listing.catid IN (' . cleanIntegerCommaList($cat_id) . ')' : 'ParentCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')'; } if ($this->cmsVersion == CMS_JOOMLA15) { unset($this->Listing->joins['ParentCategory']); } empty($cat_id) and !empty($section_id) and $conditions[] = 'Listing.sectionid IN (' . cleanIntegerCommaList($section_id) . ')'; empty($cat_id) and !empty($dir_id) and $conditions[] = 'JreviewsCategory.dirid IN (' . cleanIntegerCommaList($dir_id) . ')'; empty($cat_id) and !empty($criteria_id) and $conditions[] = 'JreviewsCategory.criteriaid IN (' . cleanIntegerCommaList($criteria_id) . ')'; if ($listing_id) { $conditions[] = 'Listing.id IN (' . $listing_id . ')'; } if ($filter == 'featured' && !$detail_view) { $conditions[] = 'Field.featured = 1'; } $conditions[] = "Field.{$this->jr_lat} <> ''"; $conditions[] = "Field.{$this->jr_lon} <> ''"; $conditions = array_merge($conditions, array('Listing.state = 1', '( Listing.publish_up = "' . NULL_DATE . '" OR DATE(Listing.publish_up) <= DATE("' . _CURRENT_SERVER_TIME . '") )', '( Listing.publish_down = "' . NULL_DATE . '" OR DATE(Listing.publish_down) >= DATE("' . _CURRENT_SERVER_TIME . '") )')); if ($this->cmsVersion == CMS_JOOMLA15) { // $conditions[] = 'Section.access <= ' . $this->Access->getAccessId(); $conditions[] = 'Category.access <= ' . $this->Access->getAccessId(); $conditions[] = 'Listing.access <= ' . $this->Access->getAccessId(); } else { $conditions[] = 'Category.access IN (' . $this->Access->getAccessLevels() . ')'; $conditions[] = 'Listing.access IN (' . $this->Access->getAccessLevels() . ')'; } // Paid Listings - add plan cat id isset($this->PaidListings) and $this->PaidListings->applyBeforeFindListingChanges($this->Listing); $listings = $this->Listing->findAll(array('conditions' => $conditions, 'limit' => $limit_results), array()); $custom_fields = array_filter(array_merge($custom_fields, array_keys($icon_fields))); $fieldOptionValues = array(); // Extract custom field values to avoid loading all options for each fields // It's a trade-off between that and doing a foreach on all listings foreach ($listings as $key => $row) { $listings[$key]['Criteria']['state'] = $row['Criteria.state']; $listings[$key]['ListingType']['config'] = json_decode($row['ListingType.config'], true); unset($listings[$key]['Criteria.state'], $listings[$key]['ListingType.config']); foreach ($custom_fields as $field) { $optionValue = Sanitize::getVar($row, 'Field.' . $field); if ($optionValue != '' && $optionValue != '**') { $fieldOptionValues = array_merge($fieldOptionValues, array_filter(explode('*', $optionValue))); } } } $fields = $this->Field->getFields($custom_fields, 'listing', $fieldOptionValues); $json_data = $this->Geomaps->makeJsonObject($listings, $fields, $this->params['module']); $this->set('json_data', $json_data); if ($cache) { S2Cache::write($json_filename, $json_data); } return $this->render('modules', 'geomaps'); }
function startup(&$controller) { $controller->invalidToken = true; $token = cmsFramework::getToken(); Sanitize::getString($controller->params['form'], $token) and $controller->invalidToken = false; }
function _send() { $recipient = ''; $error = array(); $response = array(); $this->components = array('security'); $this->__initComponents(); if ($this->invalidToken) { $error[] = 'jQuery("#jr_inquiryTokenValidation").show();'; return json_encode(array('error' => $this->makeJS($error))); } // Required fields $fields = array('name', 'email', 'text'); // $fields = array('name','email','phone','text'); foreach ($fields as $id) { $input_id = '#jr_inquiry' . Inflector::camelize($id) . 'Validation'; if ($this->data['Inquiry'][$id] == '') { $error[] = 'jQuery("' . $input_id . '").show();'; } else { $reponse[] = 'jQuery("' . $input_id . '").hide();'; } } # Validate user's email $this->Listing->validateInput($this->data['Inquiry']['email'], "email", "email", __t("You must fill in a valid email address.", true), 1); # Validate security code if ($this->Access->showCaptcha()) { if (!isset($this->data['Captcha']['code'])) { $this->Listing->validateSetError("code", __t("The security code you entered was invalid.", true)); } elseif ($this->data['Captcha']['code'] == '') { $this->Listing->validateSetError("code", __t("You must fill in the security code.", true)); } else { if (!$this->Captcha->checkCode($this->data['Captcha']['code'], $this->ipaddress)) { $this->Listing->validateSetError("code", __t("The security code you entered was invalid.", true)); } } } # Process validation errors $validation = $this->Listing->validateGetErrorArray(); $validation = is_array($validation) ? implode("<br />", $validation) : ''; if (!empty($error) || $validation != '') { // Reissue form token if (isset($this->Security)) { $error[] = "jQuery('#jr_inquiryToken').val('" . $this->Security->reissueToken() . "');"; } if ($this->Access->showCaptcha()) { // Replace captcha with new instance $captcha = $this->Captcha->displayCode(); $error[] = "jQuery('#captcha').attr('src','{$captcha['src']}');"; $error[] = "jQuery('#jr_inquiryCode').val('');"; } if ($validation != '') { $error[] = "jQuery('#jr_inquiryCodeValidation').html('{$validation}').show();"; } return json_encode(array('error' => $this->makeJS($error))); } // Now we can send the email # Read cms mail config settings $configSendmailPath = cmsFramework::getConfig('sendmail'); $configSmtpAuth = cmsFramework::getConfig('smtpauth'); $configSmtpUser = cmsFramework::getConfig('smtpuser'); $configSmtpPass = cmsFramework::getConfig('smtppass'); $configSmtpHost = cmsFramework::getConfig('smtphost'); $configSmtpSecure = cmsFramework::getConfig('smtpsecure'); $configSmtpPort = cmsFramework::getConfig('smtpport'); $configMailFrom = cmsFramework::getConfig('mailfrom'); $configFromName = cmsFramework::getConfig('fromname'); $configMailer = cmsFramework::getConfig('mailer'); # Get the recipient email Configure::write('Cache.query', false); $listing = $this->Listing->findRow(array('fields' => array('User.email AS `Listing.email`'), 'conditions' => array('Listing.id = ' . (int) $this->data['Inquiry']['listing_id']))); $url = cmsFramework::makeAbsUrl($listing['Listing']['url'], array('sef' => true)); $link = '<a href="' . $url . '">' . $listing['Listing']['title'] . '</a>'; switch ($this->Config->inquiry_recipient) { case 'owner': $recipient = Sanitize::getString($listing['Listing'], 'email'); break; case 'admin': $recipient = $configMailFrom; break; case 'field': if (isset($listing['Field']['pairs'][$this->Config->inquiry_field])) { $recipient = $listing['Field']['pairs'][$this->Config->inquiry_field]['value'][0]; } break; } if ($recipient == '') { $recipient = $configMailFrom; } if (!class_exists('PHPMailer')) { App::import('Vendor', 'phpmailer' . DS . 'class.phpmailer'); } $mail = new PHPMailer(); $mail->CharSet = cmsFramework::getCharset(); $mail->SetLanguage('en', S2_VENDORS . 'phpmailer' . DS . 'language' . DS); $mail->Mailer = $configMailer; // Mailer used mail,sendmail,smtp switch ($configMailer) { case 'smtp': $mail->Host = $configSmtpHost; $mail->SMTPAuth = $configSmtpAuth; $mail->Username = $configSmtpUser; $mail->Password = $configSmtpPass; $mail->SMTPSecure = $configSmtpSecure != '' ? $configSmtpSecure : ''; $mail->Port = $configSmtpPort; break; case 'sendmail': $mail->Sendmail = $configSendmailPath; break; default: break; } $mail->isHTML(true); $mail->From = $configMailFrom; $mail->FromName = $configFromName; $mail->addReplyTo($this->data['Inquiry']['email']); $mail->AddAddress($recipient); $mail->Subject = sprintf(__t("New inquiry for: %s", true), $listing['Listing']['title']); $mail->Body = sprintf(__t("From: %s", true), Sanitize::getString($this->data['Inquiry'], 'name')) . "<br />"; $mail->Body .= sprintf(__t("Email: %s", true), Sanitize::getString($this->data['Inquiry'], 'email')) . "<br />"; // $mail->Body .= sprintf(__t("Phone number: %s",true),Sanitize::getString($this->data['Inquiry'],'phone')) . "<br />"; $mail->Body .= sprintf(__t("Listing: %s", true), $listing['Listing']['title']) . "<br />"; $mail->Body .= sprintf(__t("Listing link: %s", true), $link) . "<br />"; $mail->Body .= $this->data['Inquiry']['text']; if (!$mail->Send()) { unset($mail); $error[] = 'jQuery("#jr_inquiryTokenValidation").show();'; return json_encode(array('error' => $this->makeJS($error))); } $mail->ClearAddresses(); $bccAdmin = $this->Config->inquiry_bcc; if ($bccAdmin != '' && $bccAdmin != $recipient) { $mail->AddAddress($bccAdmin); $mail->Send(); } unset($mail); return json_encode(array('error' => $this->makeJS($response), 'html' => true)); }
/** * Calls a controller's method from any location. * * @param string $url URL in the form of Cake URL ("/controller/method/parameter") * @param array $extra if array includes the key "return" it sets the AutoRender to true. * @return mixed Success (true/false) or contents if 'return' is set in $extra * @access public */ function requestAction($url, $extra = array()) { $app = Sanitize::getString($extra, 'app', 'jreviews'); unset($extra['app']); if (empty($url)) { return false; } if (!class_exists('S2Dispatcher')) { require S2_FRAMEWORK . DS . 'dispatcher.php'; } if (in_array('return', $extra, true)) { $extra = array_merge($extra, array('return' => 0, 'autoRender' => 1)); } $params = array_merge(array('token' => cmsFramework::formIntegrityToken($extra, array('module', 'module_id', 'form', 'data'), false), 'autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1), $extra); $disable404 = true; $dispatcher = new S2Dispatcher($app, null, $disable404); return $dispatcher->dispatch($url, $params); }
function quoteLike($text) { $dbResource = cmsFramework::getConnection(); if (is_object($dbResource) && get_class($dbResource) == 'mysqli') { $quoted = mysqli_real_escape_string($dbResource, $text); } else { $quoted = mysql_real_escape_string($text, $dbResource); } return '\'%' . $quoted . '%\''; }