function index($params)
 {
     $this->action = 'directory';
     // Trigger assets helper method
     if ($this->_user->id === 0) {
         $this->cacheAction = Configure::read('Cache.expires');
     }
     $page = array('title' => '', 'show_title' => 0);
     $conditions = array();
     $order = array();
     if ($menu_id = Sanitize::getInt($this->params, 'Itemid')) {
         $menuParams = $this->Menu->getMenuParams($menu_id);
         $page['title'] = Sanitize::getString($menuParams, 'title');
         $page['show_title'] = Sanitize::getString($menuParams, 'dirtitle', 0);
     }
     $override_keys = array('dir_show_alphaindex', 'dir_cat_images', 'dir_columns', 'dir_cat_num_entries', 'dir_category_hide_empty', 'dir_category_levels', 'dir_cat_format');
     if (Sanitize::getBool($menuParams, 'dir_overrides')) {
         $overrides = array_intersect_key($menuParams, array_flip($override_keys));
         $this->Config->override($overrides);
     }
     if ($this->cmsVersion == CMS_JOOMLA15) {
         $directories = $this->Directory->getTree(Sanitize::getString($this->params, 'dir'));
     } else {
         $directories = $this->Category->findTree(array('level' => $this->Config->dir_cat_format === 0 ? 2 : $this->Config->dir_category_levels, 'menu_id' => true, 'dir_id' => Sanitize::getString($this->params, 'dir'), 'pad_char' => ''));
     }
     $this->set(array('page' => $page, 'directories' => $directories));
     return $this->render('directories', 'directory');
 }
Exemple #2
0
 function orderingListReviews($selected, $params = false)
 {
     $options_array = array('rdate' => __t("Most recent", true), 'date' => __t("Oldest", true), 'updated' => __t("Last updated", true), 'rating' => __t("Highest user rating", true), 'rrating' => __t("Lowest user rating", true), 'helpful' => __t("Most helpful", true), 'rhelpful' => __t("Least helpful", true), 'discussed' => __t("Most discussed", true));
     $orderingList = $options_array;
     if (Sanitize::getBool($params, 'return')) {
         return $orderingList;
     }
     $attributes = array('size' => '1', 'onchange' => "window.location=this.value;return false;");
     return $this->generateFormSelect($orderingList, $selected, $attributes);
 }
Exemple #3
0
 function orderingListReviews($selected, $options = array(), $params = false)
 {
     $options_array = array('rdate' => __t("Most recent", true), 'date' => __t("Oldest", true), 'rating' => __t("Highest user rating", true), 'rrating' => __t("Lowest user rating", true), 'helpful' => __t("Most helpful", true), 'rhelpful' => __t("Least helpful", true));
     if (!empty($options)) {
         foreach ($options as $key) {
             if (isset($options_array[$key])) {
                 $orderingList[$key] = $options_array[$key];
             }
         }
     } else {
         $orderingList = $options_array;
     }
     if (Sanitize::getBool($params, 'return')) {
         return $orderingList;
     }
     $attributes = array('size' => '1', 'onchange' => "window.location=this.value;return false;");
     return $this->generateFormSelect($orderingList, $selected, $attributes);
 }
 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 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 _save()
 {
     $this->autoRender = false;
     $this->autoLayout = false;
     $response = array();
     # Done here so it only loads on save and not for all controlller actions.
     $this->components = array('security', 'notifications');
     $this->__initComponents();
     # Validate form token
     if ($this->invalidToken) {
         return $this->ajaxError(s2Messages::invalidToken());
     }
     $selected = '';
     $msg = '';
     $msgAlert = '';
     $msgTags = array();
     # Clean formValues
     $review_id = Sanitize::getInt($this->data['Review'], 'id', 0);
     $this->data['Review']['pid'] = $pid = Sanitize::getInt($this->data['Review'], 'pid', 0);
     if ($review_id == 0) {
         $isNew = $this->Review->isNew = true;
     } else {
         $isNew = $this->Review->isNew = false;
         $this->action = '_edit';
     }
     $this->data['Criteria']['id'] = Sanitize::getInt($this->data['Criteria'], 'id', 0);
     $this->data['Criteria']['state'] = Sanitize::getInt($this->data['Criteria'], 'state', 0);
     $this->data['Review']['pid'] = Sanitize::getInt($this->data['Review'], 'pid');
     $this->data['Review']['email'] = Sanitize::html($this->data['Review'], 'email', '', true);
     $this->data['Review']['title'] = Sanitize::html($this->data['Review'], 'title', '', true);
     $this->data['Review']['comments'] = Sanitize::html($this->data['Review'], 'comments', '', true);
     $this->data['Review']['mode'] = Sanitize::html($this->data['Review'], 'mode', 'com_content', true);
     # Override configuration
     $listing_type = $this->Criteria->findRow(array('conditions' => array('Criteria.id = ' . $this->data['Criteria']['id'])));
     isset($listing_type['ListingType']) and $this->Config->override($listing_type['ListingType']['config']);
     if ($isNew || !$isNew && !$this->Access->isManager()) {
         $this->data['Review']['name'] = $this->data['Review']['username'] = Sanitize::html($this->data['Review'], 'name', '', true);
     }
     // Check if user allowed to post new review
     if ($isNew) {
         if (method_exists($this->Listing, 'getListingOwner')) {
             $owner = $this->Listing->getListingOwner($this->data['Review']['pid']);
             if (!$this->Access->canAddReview($owner['user_id'])) {
                 return $this->ajaxUpdatePage('jr_review0Form', __t("You are not allowed to review your own listing.", true));
             }
         }
         // Get reviewer type, for now editor reviews don't work in Everywhere components
         $this->data['Review']['author'] = $this->data['Review']['mode'] != 'com_content' ? 0 : (int) $this->Access->isJreviewsEditor($this->_user->id);
     } else {
         $currentReview = $this->Review->findRow(array('conditions' => array('Review.id = ' . $review_id)), array());
         # Stop form data tampering
         $formData = $this->data['Review'] + array('criteria_id' => Sanitize::getInt($this->data['Criteria'], 'id'));
         $formToken = cmsFramework::formIntegrityToken($formData, array_keys($this->formTokenKeys), false);
         if (!$this->Access->canEditReview($currentReview['User']['user_id']) || !$this->__validateToken($formToken)) {
             return $this->ajaxError(s2Messages::accessDenied());
         }
         $this->data['Review']['author'] = $currentReview['Review']['editor'];
     }
     # If we are in multiple editor review mode, and this editor has already posted an editor review,
     # he is not allowed to post any kind of review.
     # if we are in single-editor-review mode, his review will become a user review.
     if ($isNew && $this->data['Review']['mode'] == 'com_content' && $this->data['Review']['author']) {
         if ($this->Review->findCount(array('conditions' => array('Review.pid = ' . $this->data['Review']['pid'], 'Review.author = 1', "Review.mode = '" . $this->data['Review']['mode'] . "'", $this->Config->author_review == 2 ? 'Review.userid = ' . $this->_user->id : '1 = 1')))) {
             if ($this->Config->author_review == 2) {
                 return $this->ajaxUpdatePage('jr_review0Form', __t("You already submitted a review.", true));
             } else {
                 $this->data['Review']['author'] = 0;
             }
         }
     }
     # check for duplicate reviews
     $is_jr_editor = $this->Access->isJreviewsEditor($this->_user->id);
     $is_duplicate = false;
     // 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->review_ipcheck_disable && $this->ipaddress != '127.0.0.1') {
             // Do the ip address check everywhere except in localhost
             $is_duplicate = (bool) $this->Review->findCount(array('conditions' => array('Review.pid = ' . $this->data['Review']['pid'], "Review.ipaddress = '{$this->ipaddress}'", "Review.mode = '{$this->data['Review']['mode']}'", "Review.published >= 0")));
         }
     } elseif (!$is_jr_editor && !$this->Config->user_multiple_reviews || $is_jr_editor && $this->Config->author_review == 2) {
         $is_duplicate = (bool) $this->Review->findCount(array('conditions' => array('Review.pid = ' . $this->data['Review']['pid'], "(Review.userid = {$this->_user->id}" . ($this->ipaddress != '127.0.0.1' && !$this->Config->review_ipcheck_disable && !$is_jr_editor ? " OR Review.ipaddress = '{$this->ipaddress}') " : ')'), "Review.mode = '{$this->data['Review']['mode']}'", "Review.published >= 0")));
     }
     if ($isNew && $is_duplicate) {
         return $this->ajaxUpdatePage('jr_review0Form', __t("You already submitted a review.", true));
     }
     # Validate standard fields
     $this->Review->validateInput($this->data['Review']['name'], "name", "text", __t("You must fill in your name.", true), !$this->_user->id && ($this->Config->reviewform_name == 'required' ? true : false));
     $this->Review->validateInput($this->data['Review']['email'], "email", "email", __t("You must fill in a valid email address.", true), ($this->Config->reviewform_email == 'required' ? true : false) && !$this->_user->id && $isNew);
     $this->Review->validateInput($this->data['Review']['title'], "title", "text", __t("You must fill in a title for the review.", true), $this->Config->reviewform_title == 'required' ? true : false);
     if ($listing_type['Criteria']['state'] == 1) {
         # Validate rating fields
         $criteria_qty = $listing_type['Criteria']['quantity'];
         $ratingErr = 0;
         if (!isset($this->data['Rating'])) {
             $ratingErr = $criteria_qty;
         } else {
             for ($i = 0; $i < $criteria_qty; $i++) {
                 if (!isset($this->data['Rating']['ratings'][$i]) || (empty($this->data['Rating']['ratings'][$i]) || $this->data['Rating']['ratings'][$i] == 'undefined' || (double) $this->data['Rating']['ratings'][$i] > $this->Config->rating_scale)) {
                     $ratingErr++;
                 }
             }
         }
         $this->Review->validateInput('', "rating", "text", sprintf(__t("You are missing a rating in %s criteria.", true), $ratingErr), $ratingErr);
     }
     # Validate custom fields
     $review_valid_fields = $this->Field->validate($this->data, 'review', $this->Access);
     $this->Review->validateErrors = array_merge($this->Review->validateErrors, $this->Field->validateErrors);
     $this->Review->validateInput($this->data['Review']['comments'], "comments", "text", __t("You must fill in your comment.", true), $this->Config->reviewform_comment == 'required' ? true : false);
     # Validate security code
     if ($isNew && $this->Access->showCaptcha()) {
         if (!isset($this->data['Captcha']['code'])) {
             $this->Review->validateSetError("code", __t("The security code you entered was invalid.", true));
         } elseif ($this->data['Captcha']['code'] == '') {
             $this->Review->validateInput($this->data['Captcha']['code'], "code", "text", __t("You must fill in the security code.", true), 1);
         } else {
             if (!$this->Captcha->checkCode($this->data['Captcha']['code'], $this->ipaddress)) {
                 $this->Review->validateSetError("code", __t("The security code you entered was invalid.", true));
             }
         }
     }
     # Process validation errors
     $validation = $this->Review->validateGetErrorArray();
     if (!empty($validation)) {
         if ($isNew && $this->Access->showCaptcha()) {
             // Replace captcha with new instance
             $captcha = $this->Captcha->displayCode();
             $response[] = "jQuery('.jr_captcha').find('img').attr('src','{$captcha['src']}');";
             $response[] = "jQuery('.jr_captcha_code').val('');";
         }
         return $this->ajaxValidation(implode('<br />', $validation), $response);
     }
     $savedReview = $this->Review->save($this->data, $this->Access, $review_valid_fields);
     $review_id = $this->data['Review']['id'];
     // Error on review save
     if (Sanitize::getString($savedReview, 'err')) {
         return $this->ajaxError($savedReview['err']);
     }
     // Process moderated actions
     if ($isNew && $this->Access->moderateReview() && !$this->data['Review']['author'] || !$isNew && ($this->Config->moderation_review_edit && $this->Access->moderateReview()) && !$this->data['Review']['author'] || $isNew && $this->Config->moderation_editor_reviews && $this->data['Review']['author'] || !$isNew && ($this->Config->moderation_editor_review_edit && $this->Config->moderation_editor_reviews && $this->Access->moderateReview()) && $this->data['Review']['author']) {
         $target_id = $isNew ? 'jr_review0Form' : 'jr_review_' . $review_id;
         $update_text = __t("Thank you for your submission. It will be published once it is verified.", true);
         return $this->ajaxUpdatePage($target_id, $update_text, '');
     }
     // Get updated review info for non-moderated actions and plugin callback
     $fields = array('Criteria.id AS `Criteria.criteria_id`', 'Criteria.criteria AS `Criteria.criteria`', 'Criteria.state AS `Criteria.state`', 'Criteria.tooltips AS `Criteria.tooltips`', 'Criteria.weights AS `Criteria.weights`');
     $joins = $this->Listing->joinsReviews;
     // Triggers the afterFind in the Observer Model
     $this->EverywhereAfterFind = true;
     if (isset($this->viewVars['reviews'])) {
         $review = current($this->viewVars['reviews']);
     } else {
         $this->Review->runProcessRatings = true;
         $review = $this->Review->findRow(array('fields' => $fields, 'conditions' => 'Review.id = ' . $this->data['Review']['id'], 'joins' => $joins), array('afterFind'));
     }
     $this->set(array('reviewType' => 'user', 'User' => $this->_user, 'Access' => $this->Access, 'reviews' => array($review['Review']['review_id'] => $review)));
     $response = array();
     $fb_checkbox = Sanitize::getBool($this->data, 'fb_publish');
     $facebook_integration = Sanitize::getBool($this->Config, 'facebook_enable') && Sanitize::getBool($this->Config, 'facebook_reviews') && $fb_checkbox;
     // Process non moderated actions
     # New user review
     if ($isNew && !$this->data['Review']['author']) {
         $remove_class = true;
         $target_id = 'jr_user_reviews';
         $update_text = __t("Thank you for your submission.", true);
         $update_html = $this->render('reviews', 'reviews');
         # Facebook wall integration
         $token = cmsFramework::getCustomToken($review['Review']['review_id']);
         $facebook_integration and $response[] = "\n                    jQuery.get(s2AjaxUri+jreviews.ajax_params()+'&url=facebook/_postReview/id:{$review['Review']['review_id']}&{$token}=1');\n                ";
         return $this->ajaxUpdatePage($target_id, $update_text, $update_html, compact('response', 'remove_class'));
     }
     # Edited user review
     if (!$isNew && !$this->data['Review']['author']) {
         // Setup vars for post submit effects
         $target_id = 'jr_review_' . $review_id;
         $update_text = __t("Your changes were saved.", true);
         $update_html = $this->render('reviews', 'reviews');
         return $this->ajaxUpdatePage($target_id, $update_text, $update_html);
     }
     # New editor review
     if ($isNew && $this->data['Review']['author']) {
         $target_id = 'jr_review_' . $review_id;
         $update_text = Sanitize::getInt($review['Criteria'], 'state') != 2 ? __t("Thank you for your submission. Refresh the page to see your review.", true) : __t("Thank you for your submission. Refresh the page to see your comment.", true);
         # Facebook wall integration
         $token = cmsFramework::getCustomToken($review['Review']['review_id']);
         $facebook_integration and $response[] = "\n                    jQuery.get(s2AjaxUri+jreviews.ajax_params()+'&url=facebook/_postReview/id:{$review['Review']['review_id']}&{$token}=1');\n                ";
         return $this->ajaxUpdatePage($target_id, $update_text, '', compact('response'));
     }
     # Edited editor review
     if (!$isNew && $this->data['Review']['author']) {
         $target_id = 'jr_review_' . $review_id;
         $update_text = __t("Your changes were saved, refresh the page to see them.", true);
         return $this->ajaxUpdatePage($target_id, $update_text);
     }
 }
 function _plgReviewAfterSave(&$model)
 {
     $content = '';
     $activity_thumb = '';
     $stream = Sanitize::getInt($this->c->Config, 'jomsocial_reviews');
     /**
      * Check if there's something to do and run the query only if necessary. Then set it in the
      * controller (viewVars) to make it available in other plugins
      */
     if ($stream || $this->points) {
         $review = $this->_getReview($model);
     }
     /**
      * Publish activity to JomSocial stream
      */
     if ($stream) {
         // Treat moderated reviews as new
         $this->inAdmin and Sanitize::getBool($model->data, 'moderation') and $model->isNew = true;
         if ($stream == 1 && (!isset($model->isNew) || !$model->isNew)) {
             return;
         }
         // Don't run for edits
         if ($stream == 1 && $review['Review']['modified'] != NULL_DATE) {
             return;
         }
         // Don't run for edits
         if ($stream == 2 && (!isset($model->isNew) || !$model->isNew) && $this->c->_user->id != $review['User']['user_id']) {
             return;
         }
         // Don't run for edits by users other than the owner of this post
         if (isset($model->isNew) && $review['Review']['published'] == 1) {
             $listing_link = $this->Html->sefLink($review['Listing']['title'], $review['Listing']['url']);
             !empty($review['Listing']['images']) and $activity_thumb = $this->Thumbnail->thumb($review, 0, array('tn_mode' => $this->c->Config->jomsocial_tnmode, 'location' => 'activity', 'dimensions' => array($this->c->Config->jomsocial_tnsize)));
             $thumb_link = $activity_thumb ? $this->Html->sefLink($activity_thumb, $review['Listing']['url']) : '';
             if (isset($model->isNew) && $model->isNew && $review['Review']['modified'] == NULL_DATE) {
                 $title = sprintf($this->activities['review_new'], $listing_link);
             } else {
                 $title = sprintf($this->activities['review_edit'], $listing_link);
             }
             if ($activity_thumb || $review['Review']['comments'] != '') {
                 $content = '<ul class="cDetailList clrfix">';
                 $thumb_link and $content .= '<li style="float:left;">' . $thumb_link . '</li>';
                 $thumb_link and $content .= '<li class="detailWrap">';
                 $review['Review']['comments'] != '' and $content .= '<div class="newsfeed-quote">' . $this->Text->truncateWords($review['Review']['comments'], 25) . '</div>';
                 $thumb_link and $content .= '</li>';
                 $content .= '</ul>';
             }
             //begin activity stream
             $act = new stdClass();
             $act->cmd = 'wall.write';
             $act->actor = $review['User']['user_id'];
             $act->target = 0;
             // no target
             $act->title = $title;
             $act->content = $content;
             $act->app = 'wall';
             $act->cid = 0;
             CFactory::load('libraries', 'activities');
             CActivityStream::add($act);
         }
     }
     if ($this->points) {
         if (isset($model->isNew) && $model->isNew && $review['Review']['published'] == 1) {
             // Begin add points
             CuserPoints::assignPoint('jreviews.review.add', $review['User']['user_id']);
         }
     }
 }
Exemple #8
0
 /**
  * Creates the json object used for map rendering
  *     
  * @param array $results listings
  * @param mixed $fields  custom fields, required when using the GeoMaps module
  * @param mixed $options mapUI options to override globals when using GeoMaps module
  */
 function makeJsonObject(&$results, &$fields = array(), $options = array())
 {
     $www_base = array_shift(pathinfo(WWW_ROOT));
     // Required for thumbnail path
     $paths = array(S2Paths::get('jreviews', 'S2_VIEWS_OVERRIDES') . 'themes' . DS . $this->c->Config->template . DS . 'theme_images' . DS, S2Paths::get('jreviews', 'S2_VIEWS') . 'themes' . DS . $this->c->Config->template . DS . 'theme_images' . DS, S2Paths::get('jreviews', 'S2_VIEWS_OVERRIDES') . 'themes' . DS . 'default' . DS . 'theme_images' . DS, S2Paths::get('jreviews', 'S2_VIEWS') . 'themes' . DS . 'default' . DS . 'theme_images' . DS);
     $path = fileExistsInPath(array('name' => '', 'suffix' => '', 'ext' => ''), $paths);
     App::import('Helper', array('html', 'routes', 'custom_fields', 'thumbnail'));
     $Html = new HtmlHelper();
     $Routes = new RoutesHelper();
     $CustomFields = new CustomFieldsHelper();
     $Thumbnail = new ThumbnailHelper();
     $Thumbnail->app = 'jreviews';
     $Thumbnail->name = $this->c->name;
     $Thumbnail->action = $this->c->action;
     $Routes->Config = $CustomFields->Config = $Thumbnail->Config = $this->c->Config;
     $Routes->Access = $CustomFields->Access = $Thumbnail->Access = $this->c->Access;
     $Routes->Html = $CustomFields->Html = $Thumbnail->Html = $Html;
     $CustomFields->viewTheme = $Thumbnail->viewTheme =& $this->c->viewTheme;
     $CustomFields->viewSuffix =& $this->c->viewSuffix;
     // Check format of results because we may need to re-format and add fields for Geomaps module
     $first = current($results);
     if (!isset($first['Listing'])) {
         $results = $this->buildListingArray($results, $fields);
     }
     // PaidListings - remove unpaid info
     Configure::read('PaidListings') and PaidListingsComponent::processPaidData($results);
     $marker_icons = array();
     $infowindow_data = array();
     $i = 1;
     $map_counter = 0;
     $default_icon = $this->c->name == 'categories' ? 'numbered' : 'default';
     if (!empty($results)) {
         $infowindow_fields = str_replace(" ", "", Sanitize::getString($this->c->Config, 'geomaps.infowindow_fields'));
         $infowindow_fields = $infowindow_fields != '' ? explode(",", $infowindow_fields) : array();
         foreach ($results as $key => $result) {
             $results[$key] = $this->injectDistanceGroup($result);
             // Override global setting for map display in lists if at least one listing has map enabled
             // For it's listing type and has valid coordinates
             if ($this->c->name == 'categories' && isset($result['ListingType']) && Sanitize::getBool($result['ListingType']['config'], 'geomaps.enable_map_list', true)) {
                 if (isset($result['Geomaps']) && abs($result['Geomaps']['lat']) > 0 && abs($result['Geomaps']['lon']) > 0) {
                     $map_counter++;
                 }
             }
             // Add menu id if not already there
             if (!isset($result['Listing']['menu_id'])) {
                 $results[$key]['Listing']['menu_id'] = $this->c->Menu->getCategory(array('cat_id' => $result['Listing']['cat_id'], 'dir_id' => $result['Directory']['dir_id'], 'section_id' => isset($result['Listing']['section_id']) ? $result['Listing']['section_id'] : null, 'listing' => $result['Listing']['listing_id']));
             }
             $listing_index = ($this->c->page - 1) * $this->c->limit + $i++;
             // Process and add icon info
             $icon = isset($result['Geomaps']) ? json_decode($result['Geomaps']['icon'], true) : array();
             $results[$key]['Geomaps']['icon'] = '';
             $icon_name = $default_icon;
             if (!empty($icon)) {
                 $foundIcon = false;
                 // Check if custom field assigned
                 if ($icon['field'] != '' && substr($icon['field'], 0, 3) == 'jr_') {
                     if (isset($result['Field']['pairs'][$icon['field']]) && isset($result['Field']['pairs'][$icon['field']]['image'][0])) {
                         $icon_name = substr($result['Field']['pairs'][$icon['field']]['image'][0], 0, strpos($result['Field']['pairs'][$icon['field']]['image'][0], '.'));
                         $marker_icons[$icon_name] = $results[$key]['Geomaps']['icon'] = $result['Field']['pairs'][$icon['field']]['image'][0];
                         $foundIcon = true;
                     }
                 } elseif ($icon['cat'] != '' && !$foundIcon) {
                     $icon_name = substr($icon['cat'], 0, strpos($icon['cat'], '.'));
                     if ($icon_name != 'default') {
                         $marker_icons[$icon_name] = $results[$key]['Geomaps']['icon'] = $icon['cat'];
                     }
                 }
             }
             if (isset($result['Geomaps']) && $result['Geomaps']['lat'] != '' && $result['Geomaps']['lon'] != '' && $result['Geomaps']['lat'] != 0 && $result['Geomaps']['lon']) {
                 # Create infowindow JSON object
                 // start with standard fields
                 $infowindow = array('id' => $result['Listing']['listing_id'], 'url' => str_replace(array($www_base, '&amp;'), array('', '&'), $Routes->content('', $results[$key], array('return_url' => true))), 'index' => $listing_index, 'title' => $result['Listing']['title'], 'image' => str_replace($www_base, '', $Thumbnail->thumb($result, 0, array('tn_mode' => $this->c->Config->list_thumb_mode, 'location' => 'list', 'dimensions' => array($this->c->Config->list_image_resize), 'return_src' => 1))), 'featured' => $result['Listing']['featured'], 'rating_scale' => $this->c->Config->rating_scale, 'user_rating' => $result['Review']['user_rating'], 'user_rating_count' => $result['Review']['user_rating_count'], 'editor_rating' => $result['Review']['editor_rating'], 'editor_rating_count' => $result['Review']['editor_rating_count'], 'lat' => (double) $result['Geomaps']['lat'], 'lon' => (double) $result['Geomaps']['lon'], 'icon' => $icon_name);
                 if (!empty($result['Field']['pairs'])) {
                     # Limit fields will included in the payload json object
                     $result['Field']['pairs'] = array_intersect_key($result['Field']['pairs'], array_flip($infowindow_fields));
                     foreach ($result['Field']['pairs'] as $name => $fieldArray) {
                         $infowindow['field'][$name] = $CustomFields->field($name, $result);
                     }
                 }
                 $infowindow_data['id' . $result['Listing']['listing_id']] = $infowindow;
             }
         }
     }
     $this->c->Config->{'geomaps.enable_map_list'} = $map_counter;
     $mapUI = array();
     $zoom = '';
     switch ($this->c->name) {
         case 'categories':
             $maptypes = Sanitize::getString($this->c->Config, 'geomaps.ui.maptype_list', 'buttons');
             //buttons|menu|none
             $maptype_def = Sanitize::getString($this->c->Config, 'geomaps.ui.maptype_def_list', 'G_NORMAL_MAP');
             $map = Sanitize::getBool($this->c->Config, 'geomaps.ui.map_list', 1);
             $hybrid = Sanitize::getBool($this->c->Config, 'geomaps.ui.hybrid_list', 1);
             $satellite = Sanitize::getBool($this->c->Config, 'geomaps.ui.satellite_list', 1);
             $terrain = Sanitize::getBool($this->c->Config, 'geomaps.ui.terrain_list', 1);
             $panzoom = Sanitize::getBool($this->c->Config, 'geomaps.ui.panzoom_list', 1);
             $scale = Sanitize::getBool($this->c->Config, 'geomaps.ui.scale_list', 0);
             $scrollwheel = Sanitize::getBool($this->c->Config, 'geomaps.ui.scrollwheel_list', 0);
             $doubleclick = Sanitize::getBool($this->c->Config, 'geomaps.ui.doubleclick_list', 1);
             $mapUI['title']['trim'] = Sanitize::getVar($this->c->Config, 'geomaps.ui.trimtitle_list', 0);
             $mapUI['title']['trimchars'] = Sanitize::getVar($this->c->Config, 'geomaps.ui.trimtitle_chars', 30);
             break;
         case 'com_content':
             $maptypes = Sanitize::getString($this->c->Config, 'geomaps.ui.maptype_detail', 'buttons');
             //buttons|menu|none
             $maptype_def = Sanitize::getString($this->c->Config, 'geomaps.ui.maptype_def_detail', 'G_NORMAL_MAP');
             $map = Sanitize::getBool($this->c->Config, 'geomaps.ui.map_detail', 1);
             $hybrid = Sanitize::getBool($this->c->Config, 'geomaps.ui.hybrid_detail', 1);
             $satellite = Sanitize::getBool($this->c->Config, 'geomaps.ui.satellite_detail', 1);
             $terrain = Sanitize::getBool($this->c->Config, 'geomaps.ui.terrain_detail', 1);
             $panzoom = Sanitize::getBool($this->c->Config, 'geomaps.ui.panzoom_detail', 1);
             $scale = Sanitize::getBool($this->c->Config, 'geomaps.ui.scale_detail', 0);
             $scrollwheel = Sanitize::getBool($this->c->Config, 'geomaps.ui.scrollwheel_detail', 0);
             $doubleclick = Sanitize::getBool($this->c->Config, 'geomaps.ui.doubleclick_detail', 1);
             $zoom = Sanitize::getInt($this->c->Config, 'geomaps.ui.zoom_detail', '');
             $mapUI['title']['trim'] = Sanitize::getVar($this->c->Config, 'geomaps.ui.trimtitle_detail', 0);
             $mapUI['title']['trimchars'] = Sanitize::getVar($this->c->Config, 'geomaps.ui.trimtitle_chars', 30);
             break;
         case 'module_geomaps':
             $maptypes = Sanitize::getString($options, 'ui_maptype', 2) == '2' ? Sanitize::getString($this->c->Config, 'geomaps.ui.maptype_module', 'buttons') : Sanitize::getString($options, 'ui_maptype');
             //buttons|menu|none
             $maptype_def = Sanitize::getString($options, 'ui_maptype_def', 2) == '2' ? Sanitize::getString($this->c->Config, 'geomaps.ui.maptype_def_module', 'G_NORMAL_MAP') : Sanitize::getString($options, 'ui_maptype_def', 'G_NORMAL_MAP');
             $map = Sanitize::getInt($options, 'ui_map', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.map_module', 1) : Sanitize::getBool($options, 'ui_map');
             $hybrid = Sanitize::getInt($options, 'ui_hybrid', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.hybrid_module', 1) : Sanitize::getBool($options, 'ui_hybrid');
             $satellite = Sanitize::getInt($options, 'ui_satellite', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.satellite_module', 1) : Sanitize::getBool($options, 'ui_satellite');
             $terrain = Sanitize::getInt($options, 'ui_terrain', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.terrain_module', 1) : Sanitize::getBool($options, 'ui_terrain');
             $panzoom = Sanitize::getInt($options, 'ui_panzoom', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.panzoom_module', 1) : Sanitize::getBool($options, 'ui_panzoom');
             $scale = Sanitize::getInt($options, 'ui_scale', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.scale_module', 0) : Sanitize::getBool($options, 'ui_scale');
             $scrollwheel = Sanitize::getInt($options, 'ui_scrollwheel', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.scrollwheel_module', 0) : Sanitize::getBool($options, 'ui_scrollwheel');
             $doubleclick = Sanitize::getInt($options, 'ui_doubleclick', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.doubleclick_module', 1) : Sanitize::getBool($options, 'ui_doubleclick');
             $mapUI['title']['trim'] = Sanitize::getInt($options, 'ui_trimtitle_module', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.trimtitle_module', 30) : Sanitize::getBool($options, 'ui_trimtitle_module');
             $mapUI['title']['trimchars'] = Sanitize::getInt($options, 'ui_trimtitle_chars', 2) == '2' ? Sanitize::getInt($this->c->Config, 'geomaps.ui.trimtitle_chars', 30) : Sanitize::getInt($options, 'ui_trimtitle_chars');
             if (Sanitize::getString($options, 'detail_view', 1)) {
                 $zoom = Sanitize::getInt($this->c->Config, 'geomaps.ui.zoom_detail', '');
             }
             break;
     }
     switch ($maptypes) {
         case 'buttons':
             $mapUI['controls']['maptypecontrol'] = true;
             $mapUI['controls']['menumaptypecontrol'] = false;
             break;
         case 'menu':
             $mapUI['controls']['maptypecontrol'] = false;
             $mapUI['controls']['menumaptypecontrol'] = true;
             break;
         default:
             $mapUI['controls']['maptypecontrol'] = false;
             $mapUI['controls']['menumaptypecontrol'] = false;
     }
     $mapUI['maptypes']['def'] = $maptype_def;
     $mapUI['maptypes']['map'] = $map;
     $mapUI['maptypes']['hybrid'] = $hybrid;
     $mapUI['maptypes']['satellite'] = $satellite;
     $mapUI['maptypes']['terrain'] = $terrain;
     if ($panzoom) {
         $mapUI['controls']['smallzoomcontrol3d'] = true;
         $mapUI['controls']['largemapcontrol3d'] = true;
     } else {
         $mapUI['controls']['smallzoomcontrol3d'] = false;
         $mapUI['controls']['largemapcontrol3d'] = false;
     }
     $mapUI['controls']['scalecontrol'] = $scale;
     $mapUI['zoom']['scrollwheel'] = $scrollwheel;
     $mapUI['zoom']['doubleclick'] = $doubleclick;
     $mapUI['zoom']['start'] = $zoom;
     $mapUI['anchor']['x'] = Sanitize::getVar($this->c->Config, 'geomaps.infowindow_x', 0);
     $mapUI['anchor']['y'] = Sanitize::getVar($this->c->Config, 'geomaps.infowindow_y', 0);
     unset($Html, $Routes, $CustomFields, $Thumbnail);
     return json_encode(array('count' => count($infowindow_data), 'mapUI' => $mapUI, 'infowindow' => Sanitize::getString($this->c->Config, 'geomaps.infowindow', '_google'), 'icons' => $this->processIcons($marker_icons), 'payload' => $infowindow_data));
 }
 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;
 }
 /**
  * Returns a json object of field options used to dynamicaly show and populate dependent fields
  *         
  */
 function _loadFieldData($json = true, $_data = array())
 {
     !empty($_data) and $this->data = $_data;
     $fields = $field_options = $selected_values = $group_ids = array();
     $selected_values_autocomplete = array();
     $dependent_fields = $dependent_groups = $control_fields = $fields = $responses = array();
     $location = strtolower(Sanitize::getString($this->data, 'fieldLocation', 'content'));
     $location == 'listing' and $location = 'content';
     $recursive = Sanitize::getBool($this->data, 'recursive');
     $field_names = Sanitize::getVar($this->data, 'fields');
     $control_field = $field_names = is_array($field_names) ? array_filter($field_names) : array($field_names);
     $page_setup = Sanitize::getInt($this->data, 'page_setup', false);
     $control_value = Sanitize::getVar($this->data, 'value');
     $entry_id = Sanitize::getInt($this->data, 'entry_id');
     $referrer = Sanitize::getString($this->data, 'referrer');
     $edit = (bool) $entry_id || is_array($control_value);
     // In adv. search module we make it work like edit for previously searched values which are passed as an array in $control_value
     # Access check
     # Need to pass token to validate the listing id and check user access.
     # Filter passed field names to fix those with double underscores which are checkboxes and radiobuttons
     foreach ($field_names as $key => $name) {
         if (substr_count($name, '_') > 1) {
             $tmp = explode('_', $name);
             array_pop($tmp);
             $field_names[$key] = implode('_', $tmp);
         }
     }
     $field_names = array_unique($field_names);
     /** 
      * We are in edit mode. Find selected values
      */
     if ($page_setup && $entry_id > 0) {
         # PaidListings integration
         if ($location == 'content' && Configure::read('PaidListings.enabled') && PaidPlanCategoryModel::isInPaidCategoryByListingId($entry_id)) {
             // Load the paid_listing_fields table instead of the jos_content table so users can see all their
             // fields when editing a listing
             Configure::write('ListingEdit', false);
             $curr_field_values = PaidListingFieldModel::edit($entry_id);
             if ($curr_field_values && !empty($curr_field_values)) {
                 $curr_field_values = (array) array_shift($curr_field_values);
                 $curr_field_values['contentid'] = $curr_field_values['element_id'];
                 unset($curr_field_values['element_id'], $curr_field_values['email']);
             }
         }
         if (empty($curr_field_values)) {
             $query = $location == 'content' ? "SELECT * FROM #__jreviews_content WHERE contentid = {$entry_id}" : "SELECT * FROM #__jreviews_review_fields WHERE reviewid = {$entry_id}";
             $this->_db->setQuery($query);
             $curr_field_values = array_shift($this->_db->loadAssocList());
         }
         if (!empty($curr_field_values)) {
             foreach ($curr_field_values as $key => $val) {
                 if (substr($key, 0, 3) == 'jr_') {
                     $selected_values[$key] = $val != '' ? is_array($val) ? $val : array($val) : array();
                 }
             }
         }
     } elseif (is_array($control_value)) {
         $selected_values = $control_value;
         $control_value = '';
     }
     /****************************************************************************************
      *  Control field option selected, so we find all dependent fields and groups
      *  Need to look in FieldOptions, Fields and FieldGroups
      ****************************************************************************************/
     if (!$page_setup) {
         # Find dependent FieldOptions
         $query = "\r\n                SELECT \r\n                    DISTINCT Field.name\r\n                FROM \r\n                    #__jreviews_fieldoptions AS FieldOption\r\n                LEFT JOIN\r\n                    #__jreviews_fields AS Field ON Field.fieldid = FieldOption.fieldid AND (\r\n                        Field.published = 1 AND Field.location = " . $this->quote($location) . "\r\n                    )\r\n                LEFT JOIN\r\n                    #__jreviews_groups AS FieldGroup ON Field.groupid = FieldGroup.groupid\r\n                WHERE\r\n                    Field.published = 1 AND Field.location = " . $this->quote($location) . "\r\n                    AND FieldOption.control_field = " . $this->quote($control_field) . " AND FieldOption.control_value LIKE " . $this->quoteLike('*' . $control_value . '*') . "\r\n                ORDER BY \r\n                    FieldGroup.ordering, Field.ordering \r\n            ";
         $this->_db->setQuery($query);
         $field_names = $this->_db->loadResultArray();
         # Find dependent Fields
         $query = "\r\n                SELECT \r\n                    DISTINCT Field.name\r\n                FROM \r\n                    #__jreviews_fields AS Field\r\n                LEFT JOIN\r\n                    #__jreviews_groups AS FieldGroup ON Field.groupid = FieldGroup.groupid\r\n                WHERE\r\n                    Field.published = 1 AND Field.location = " . $this->quote($location) . "\r\n                    AND Field.control_field = " . $this->quote($control_field) . " AND Field.control_value LIKE " . $this->quoteLike('*' . $control_value . '*') . "\r\n                ORDER BY \r\n                    FieldGroup.ordering, Field.ordering \r\n            ";
         $this->_db->setQuery($query);
         $field_names = is_array($field_names) ? array_merge($field_names, $this->_db->loadResultArray()) : $this->_db->loadResultArray();
         # Find depedent Field Groups
         $query = "\r\n                SELECT DISTINCT\r\n                   FieldGroup.groupid\r\n                FROM \r\n                    #__jreviews_groups AS FieldGroup\r\n                LEFT JOIN\r\n                    #__jreviews_fields AS Field ON Field.groupid = FieldGroup.groupid\r\n                WHERE\r\n                    Field.published = 1 AND Field.location = " . $this->quote($location) . "  \r\n                    AND FieldGroup.type = " . $this->quote($location) . "\r\n                    AND FieldGroup.control_field = " . $this->quote($control_field) . "\r\n                    AND FieldGroup.control_value LIKE " . $this->quoteLike('*' . $control_value . '*') . "\r\n                ORDER BY\r\n                    FieldGroup.ordering\r\n           ";
         $this->_db->setQuery($query);
         $group_ids = $this->_db->loadResultArray();
         !empty($field_names) and $field_names = array_unique($field_names);
         if (empty($field_names) && empty($group_ids)) {
             return json_encode(compact('control_field', 'dependent_fields', 'dependent_groups', 'data'));
         }
     }
     # Get info for all fields
     $query = "\r\n            SELECT \r\n                Field.fieldid, Field.groupid, Field.title, Field.name, Field.type, Field.options, Field.control_field, Field.control_value, FieldGroup.name AS group_name\r\n            FROM \r\n                #__jreviews_fields AS Field \r\n            LEFT JOIN\r\n                #__jreviews_groups AS FieldGroup ON Field.groupid = FieldGroup.groupid\r\n            WHERE \r\n                Field.published = 1 AND Field.location = " . $this->quote($location) . "\r\n                AND (\r\n                    " . (!empty($field_names) ? "Field.name IN (" . $this->quote($field_names) . ")" : '') . "\r\n                    " . (!empty($field_names) && !empty($group_ids) ? " OR " : '') . "\r\n                    " . (!empty($group_ids) ? "Field.groupid IN (" . $this->quote($group_ids) . ")" : '') . "\r\n                )\r\n            ORDER BY \r\n                FieldGroup.ordering, Field.ordering\r\n        ";
     $this->_db->setQuery($query);
     $curr_form_fields = $this->_db->loadAssocList('name');
     if (empty($curr_form_fields)) {
         return json_encode(compact('control_field', 'dependent_fields', 'dependent_groups', 'data'));
     }
     foreach ($curr_form_fields as $key => $curr_form_field) {
         $curr_form_fields[$key]['options'] = stringToArray($curr_form_field['options']);
     }
     /****************************************************************************************
      *  Check if fields have any dependents to avoid unnecessary ajax requests 
      *  Three tables need to be checked: fieldoptions, fields, and fieldgroups
      ****************************************************************************************/
     # FieldOptions
     $query = "\r\n            SELECT DISTINCT     \r\n                Field.name AS dependent_field, FieldOption.control_field\r\n            FROM \r\n                #__jreviews_fieldoptions AS FieldOption\r\n            LEFT JOIN\r\n                #__jreviews_fields AS Field ON Field.fieldid = FieldOption.fieldid\r\n            WHERE\r\n                Field.published = 1 AND Field.location = " . $this->quote($location) . "\r\n                AND FieldOption.control_field IN ( " . $this->quote($page_setup ? array_keys($curr_form_fields) : $control_field) . ")\r\n            " . (!$page_setup ? "AND FieldOption.control_value LIKE " . $this->quoteLike('*' . $control_value . '*') : '') . "\r\n            ORDER BY Field.ordering\r\n       ";
     $this->_db->setQuery($query);
     $controlling_and_dependent_fields = $this->_db->loadAssocList();
     # Fields
     $query = "\r\n            SELECT DISTINCT\r\n                Field.name AS dependent_field, Field.control_field\r\n            FROM \r\n                #__jreviews_fields AS Field\r\n            WHERE\r\n                Field.published = 1 AND Field.location = " . $this->quote($location) . "\r\n                AND Field.control_field IN ( " . $this->quote($page_setup ? array_keys($curr_form_fields) : $control_field) . ")\r\n            " . (!$page_setup ? "AND Field.control_value LIKE " . $this->quoteLike('*' . $control_value . '*') : '') . "\r\n            ORDER BY Field.ordering\r\n       ";
     $this->_db->setQuery($query);
     $controlling_and_dependent_fields = is_array($controlling_and_dependent_fields) ? array_merge($controlling_and_dependent_fields, $this->_db->loadAssocList()) : $this->_db->loadAssocList();
     # Groups
     $query = "\r\n            SELECT DISTINCT\r\n               FieldGroup.name AS dependent_group, FieldGroup.control_field\r\n            FROM \r\n                #__jreviews_groups AS FieldGroup\r\n            LEFT JOIN\r\n                #__jreviews_fields AS Field ON Field.groupid = FieldGroup.groupid\r\n            WHERE\r\n                Field.published = 1 AND Field.location = " . $this->quote($location) . "  \r\n                AND FieldGroup.type = " . $this->quote($location) . "\r\n                AND FieldGroup.control_field IN ( " . $this->quote($page_setup ? array_keys($curr_form_fields) : $control_field) . ")\r\n            " . (!$page_setup ? "AND FieldGroup.control_value LIKE " . $this->quoteLike('*' . $control_value . '*') : '') . "\r\n            ORDER BY\r\n                FieldGroup.ordering\r\n       ";
     $this->_db->setQuery($query);
     $controlling_and_dependent_fields = is_array($controlling_and_dependent_fields) ? array_merge($controlling_and_dependent_fields, $this->_db->loadAssocList()) : $this->_db->loadAssocList();
     #Extract controlling and dependent fields
     foreach ($controlling_and_dependent_fields as $row) {
         isset($row['dependent_field']) and $dependent_fields[$row['dependent_field']] = $row['dependent_field'];
         if (isset($row['dependent_group'])) {
             $group_name = str_replace(' ', '', $row['dependent_group']);
             $dependent_groups[$group_name] = $group_name;
         }
         $control_fields[$row['control_field']] = $row['control_field'];
     }
     $ids_to_names = $ids_to_names_autocomplete = $ids_to_names_noautocomplete = array();
     $control_fields_array = array();
     foreach ($curr_form_fields as $curr_form_field) {
         $ordering = Sanitize::getVar($curr_form_field['options'], 'option_ordering', null);
         $fields[$curr_form_field['name']]['name'] = $curr_form_field['name'];
         $fields[$curr_form_field['name']]['type'] = $curr_form_field['type'];
         $fields[$curr_form_field['name']]['group'] = $curr_form_field['group_name'];
         $fields[$curr_form_field['name']]['autocomplete'] = Sanitize::getVar($curr_form_field['options'], in_array($referrer, array('adv_search', 'adv_search_module')) ? 'autocomplete.search' : 'autocomplete', 0);
         $fields[$curr_form_field['name']]['autocompletetype'] = Sanitize::getVar($curr_form_field['options'], 'autocomplete.option_type', 'link');
         $fields[$curr_form_field['name']]['autocompletepos'] = Sanitize::getVar($curr_form_field['options'], 'autocomplete.option_pos', 'after');
         $fields[$curr_form_field['name']]['title'] = $curr_form_field['title'];
         $entry_id and $fields[$curr_form_field['name']]['selected'] = array();
         !is_null($ordering) and $fields[$curr_form_field['name']]['order_by'] = !$ordering ? 'ordering' : 'text';
         // Add selected value for text fields
         if (isset($selected_values[$curr_form_field['name']])) {
             switch ($fields[$curr_form_field['name']]['type']) {
                 case 'date':
                     if (isset($selected_values[$curr_form_field['name']][0])) {
                         if ($selected_values[$curr_form_field['name']][0] == NULL_DATE) {
                             $fields[$curr_form_field['name']]['selected'] = array();
                         } else {
                             $fields[$curr_form_field['name']]['selected'] = array(str_replace(" 00:00:00", "", $selected_values[$curr_form_field['name']][0]));
                         }
                     }
                     break;
                 case 'relatedlisting':
                     if (isset($selected_values[$curr_form_field['name']][0]) && $selected_values[$curr_form_field['name']][0] > 0) {
                         $fields[$curr_form_field['name']]['selected'] = $selected_values[$curr_form_field['name']];
                     }
                     break;
                 case 'radiobuttons':
                 case 'select':
                 case 'checkboxes':
                 case 'selectmultiple':
                     if (!empty($selected_values[$curr_form_field['name']])) {
                         $selected_values[$curr_form_field['name']] = explode('*', ltrim(rtrim($selected_values[$curr_form_field['name']][0], '*'), '*'));
                         $fields[$curr_form_field['name']]['selected'] = $selected_values[$curr_form_field['name']];
                     }
                     break;
                 default:
                     $fields[$curr_form_field['name']]['selected'] = $selected_values[$curr_form_field['name']];
                     break;
             }
         }
         // Add control related vars
         // If field is text type, then it has no control and we check the controlBy values
         if ($fields[$curr_form_field['name']]['type'] == 'text') {
             $fields[$curr_form_field['name']]['control'] = false;
             $fields[$curr_form_field['name']]['controlled'] = $curr_form_field['control_field'] != '' && $curr_form_field['control_value'];
         } else {
             $fields[$curr_form_field['name']]['control'] = $recursive ? true : in_array($curr_form_field['name'], $control_fields);
             $fields[$curr_form_field['name']]['controlled'] = in_array($curr_form_field['name'], $dependent_fields);
         }
         if (in_array($curr_form_field['groupid'], $group_ids)) {
             $fields[$curr_form_field['name']]['controlgroup'] = true;
         }
         // Create an array of field ids to field names used below to save on additional queries.
         // The initial field option values are loaded for the fields in this array
         if (!$page_setup || !$fields[$curr_form_field['name']]['autocomplete'] || !empty($fields[$curr_form_field['name']]['selected'])) {
             if (in_array($fields[$curr_form_field['name']]['type'], array('select', 'selectmultiple'))) {
                 $ids_to_names[$curr_form_field['fieldid']] = $curr_form_field['name'];
             }
             if (!empty($fields[$curr_form_field['name']]['selected']) && $fields[$curr_form_field['name']]['autocomplete'] && in_array($fields[$curr_form_field['name']]['type'], array('select', 'selectmultiple'))) {
                 $ids_to_names_autocomplete[$curr_form_field['fieldid']] = $curr_form_field['name'];
                 $selected_values_autocomplete = array_merge($selected_values_autocomplete, $selected_values[$curr_form_field['name']]);
             } elseif (!$fields[$curr_form_field['name']]['autocomplete'] && in_array($fields[$curr_form_field['name']]['type'], array('select', 'selectmultiple'))) {
                 $ids_to_names_noautocomplete[$curr_form_field['fieldid']] = $curr_form_field['name'];
             }
         }
         $control_fields_array[] = $curr_form_field['name'];
     }
     //prx($ids_to_names);
     //prx($ids_to_names_autocomplete);
     //prx($ids_to_names_noautocomplete);
     //prx('------------------BEGIN-------------------');
     //prx($recursive);
     //prx($curr_form_fields);
     //prx($fields);
     //prx($control_fields);
     //prx('------------------END-------------------');
     /****************************************************************************************
      * Build the fields array for control and controlled fields 
      ****************************************************************************************/
     # For FieldOption-FieldOption relationships get field options ordered by a-z ASC to start building the fields array.
     if (!empty($ids_to_names)) {
         if ($edit) {
             if (!empty($ids_to_names_autocomplete)) {
                 $query = "\r\n                        SELECT \r\n                            Field.name, Field.fieldid, FieldOption.optionid, FieldOption.text, FieldOption.value, FieldOption.image, FieldOption.ordering\r\n                        FROM \r\n                            #__jreviews_fieldoptions AS FieldOption\r\n                        LEFT JOIN\r\n                            #__jreviews_fields AS Field ON Field.fieldid = FieldOption.fieldid\r\n                        WHERE\r\n                            Field.published = 1 AND Field.location = " . $this->quote($location) . "  \r\n                            AND " . ($page_setup ? " FieldOption.fieldid IN (" . $this->quote(array_keys($ids_to_names_autocomplete)) . ") " : '1 = 1') . " \r\n                            " . ($page_setup ? " AND FieldOption.control_field = ''" : " AND FieldOption.control_field = " . $this->quote($control_field) . " AND FieldOption.control_value LIKE " . $this->quoteLike('*' . $control_value . '*')) . " \r\n                            " . (!empty($selected_values_autocomplete) ? "AND FieldOption.value IN ( " . $this->quote($selected_values_autocomplete) . ")" : '') . "\r\n                        ORDER BY \r\n                            FieldOption.fieldid, FieldOption.text\r\n                    ";
                 $this->_db->setQuery($query);
                 $field_options_ac = $this->_db->loadAssocList();
             }
             if (!empty($ids_to_names_noautocomplete)) {
                 $query = "\r\n                        SELECT \r\n                            Field.name, Field.fieldid, FieldOption.optionid, FieldOption.text, FieldOption.value, FieldOption.image, FieldOption.ordering\r\n                        FROM \r\n                            #__jreviews_fieldoptions AS FieldOption\r\n                        LEFT JOIN\r\n                            #__jreviews_fields AS Field ON Field.fieldid = FieldOption.fieldid\r\n                        WHERE\r\n                            Field.published = 1 AND Field.location = " . $this->quote($location) . "  \r\n                            AND " . ($page_setup ? " FieldOption.fieldid IN (" . $this->quote(array_keys($ids_to_names_noautocomplete)) . ") " : '1 = 1') . " \r\n                            " . ($page_setup ? " AND FieldOption.control_field = ''" : " AND FieldOption.control_field = " . $this->quote($control_field) . " AND FieldOption.control_value LIKE " . $this->quoteLike('*' . $control_value . '*')) . " \r\n                        ORDER BY \r\n                            FieldOption.fieldid, FieldOption.text\r\n                    ";
                 $this->_db->setQuery($query);
                 $field_options_noac = $this->_db->loadAssocList();
             }
             empty($field_options_ac) and $field_options_ac = array();
             empty($field_options_noac) and $field_options_noac = array();
             $field_options = array_merge($field_options_ac, $field_options_noac);
         } else {
             $query = "\r\n                    SELECT \r\n                        Field.name, Field.fieldid, FieldOption.optionid, FieldOption.text, FieldOption.value, FieldOption.image, FieldOption.ordering\r\n                    FROM \r\n                        #__jreviews_fieldoptions AS FieldOption\r\n                    LEFT JOIN\r\n                        #__jreviews_fields AS Field ON Field.fieldid = FieldOption.fieldid\r\n                    WHERE\r\n                        Field.published = 1 AND Field.location = " . $this->quote($location) . "  \r\n                        AND " . ($page_setup ? " FieldOption.fieldid IN (" . $this->quote(array_keys($ids_to_names)) . ") " : '1 = 1') . " \r\n                        " . ($page_setup ? " AND FieldOption.control_field = ''" : " AND FieldOption.control_field = " . $this->quote($control_field) . " AND FieldOption.control_value LIKE " . $this->quoteLike('*' . $control_value . '*')) . " \r\n                    ORDER BY \r\n                        FieldOption.fieldid, FieldOption.text\r\n                ";
             $this->_db->setQuery($query);
             $field_options = $this->_db->loadAssocList();
         }
     }
     # For FieldOption-Field relationships get field options ordered by a-z ASC to start building the fields array.
     if (!$page_setup && !empty($ids_to_names)) {
         $query = "\r\n                SELECT \r\n                    Field.name, Field.fieldid, FieldOption.optionid, FieldOption.text, FieldOption.value, FieldOption.image, FieldOption.ordering\r\n                FROM \r\n                    #__jreviews_fieldoptions AS FieldOption\r\n                LEFT JOIN\r\n                    #__jreviews_fields AS Field ON Field.fieldid = FieldOption.fieldid\r\n                WHERE\r\n                    Field.published = 1 AND Field.location = " . $this->quote($location) . "  \r\n                    AND " . ($page_setup ? " FieldOption.fieldid IN (" . $this->quote(array_keys($ids_to_names)) . ") " : '1 = 1') . " \r\n                    " . ($page_setup ? " AND Field.control_field = ''" : " AND Field.control_field = " . $this->quote($control_field) . " AND Field.control_value LIKE " . $this->quoteLike('*' . $control_value . '*')) . " \r\n                ORDER BY \r\n                    FieldOption.fieldid, FieldOption.text\r\n            ";
         $this->_db->setQuery($query);
         $field_options = array_merge($field_options, $this->_db->loadAssocList());
     }
     foreach ($field_options as $field_option) {
         $field_id = $field_option['fieldid'];
         $field_name = $field_option['name'];
         unset($field_option['fieldid'], $field_option['name']);
         if (isset($ids_to_names[$field_id])) {
             $fields[$ids_to_names[$field_id]]['options'][] = $field_option;
             isset($selected_values[$field_name]) and $fields[$ids_to_names[$field_id]]['selected'] = $selected_values[$field_name];
         }
     }
     if ($page_setup) {
         $control_field = array_values($control_fields_array);
         $dependent_fields = array();
     } else {
         $control_field = $control_field;
         $dependent_fields = array_values($dependent_fields);
     }
     # Edit mode: for each control field that has a selected value find dependent field options
     foreach ($selected_values as $key => $val) {
         if (!empty($val) && $val != '' && in_array($key, $field_names)) {
             foreach ($val as $selected) {
                 $res = $this->_loadFieldData(false, array('recursive' => true, 'fields' => $key, 'value' => array_shift($val), 'fieldLocation' => $location));
                 if (is_array($res)) {
                     $responses[$res['control_field'][0]][$res['control_value']] = $res;
                     foreach ($res['fields'] as $res_fields) {
                         if (isset($selected_values[$res_fields['name']]) && !empty($res_fields['options']) && empty($fields[$res_fields['name']]['options'])) {
                             $fields[$res_fields['name']] = $res_fields;
                             $fields[$res_fields['name']]['selected'] = $selected_values[$res_fields['name']];
                         }
                     }
                 } elseif ($fields[$key]['type'] != 'text') {
                     $responses[$key][$selected] = array('location' => $location, 'control_field' => array($key), 'control_value' => $selected, 'dependent_groups' => array(), 'dependent_fields' => array(), 'fields' => array());
                 }
             }
         }
     }
     /** DEBUG **/
     //if($json) {prx(compact('page_setup','control_field','control_value','dependent_fields','dependent_groups','fields','responses'));}
     //if($json && !$page_setup) {prx(compact('page_setup','control_field','control_value','dependent_fields','dependent_groups','fields','responses'));}
     $dependent_groups = array_values($dependent_groups);
     $location = $location == 'content' ? 'Listing' : 'Review';
     return $json ? json_encode(compact('page_setup', 'edit', 'location', 'control_field', 'control_value', 'dependent_groups', 'dependent_fields', 'fields', 'responses')) : compact('location', 'control_field', 'control_value', 'dependent_groups', 'dependent_fields', 'fields');
 }
 function beforeFilter()
 {
     # These should be called in each controller where they are required instead of globally
     $this->_db = cmsFramework::getDB();
     $this->_user = cmsFramework::getUser();
     # Overcome host restrictions
     $query = "SET SQL_BIG_SELECTS=1";
     $this->_db->setQuery($query);
     $this->_db->query();
     # Fix Joomla bug when language filter is active with default language code hidden in url
     if (isset($this->params['lang'])) {
         $this->params['lang'] = cmsFramework::getUrlLanguageCode();
     }
     # Init Access
     if (isset($this->Access)) {
         $this->Access->init($this->Config);
     }
     App::import('Component', 'theming', 'jreviews');
     $this->Theming = ClassRegistry::getClass('ThemingComponent');
     $this->Theming->startup($this);
     # Set pagination vars
     // First check url, then menu parameter. Otherwise the limit list in pagination doesn't respond b/c menu params always wins
     $this->limit = Sanitize::getInt($this->params, 'limit', Sanitize::getInt($this->data, 'limit_special', Sanitize::getInt($this->data, 'limit')));
     //		$this->passedArgs['limit'] = $this->limit;
     $this->page = Sanitize::getInt($this->data, 'page', Sanitize::getInt($this->params, 'page', 1));
     if (!$this->limit) {
         if (Sanitize::getVar($this->params, 'action') == 'myreviews') {
             $this->limit = Sanitize::getInt($this->params, 'limit', $this->Config->user_limit);
             $this->params['default_limit'] = $this->Config->user_limit;
         } else {
             $this->limit = Sanitize::getInt($this->params, 'limit', $this->Config->list_limit);
             $this->params['default_limit'] = $this->Config->list_limit;
         }
     }
     if (Sanitize::getVar($this->params, 'action') == 'myreviews') {
         $this->params['default_limit'] = $this->Config->user_limit;
     } else {
         $this->params['default_limit'] = $this->Config->list_limit;
     }
     // Set a hard code limit to prevent abuse
     $this->limit = max(min($this->limit, 50), 1);
     // Need to normalize the limit var for modules
     if (isset($this->params['module'])) {
         $module_limit = Sanitize::getInt($this->params['module'], 'module_limit', 5);
     } else {
         $module_limit = 5;
     }
     $this->module_limit = Sanitize::getInt($this->data, 'module_limit', $module_limit);
     $this->module_page = Sanitize::getInt($this->data, 'module_page', 1);
     $this->module_page = $this->module_page === 0 ? 1 : $this->module_page;
     $this->module_offset = (int) ($this->module_page - 1) * $this->module_limit;
     if ($this->module_offset < 0) {
         $this->module_offset = 0;
     }
     $this->page = $this->page === 0 ? 1 : $this->page;
     $this->offset = (int) ($this->page - 1) * $this->limit;
     if ($this->offset < 0) {
         $this->offset = 0;
     }
     # Required further below for Community Model init
     if (!isset($this->Menu)) {
         App::import('Model', 'menu', 'jreviews');
         $this->Menu = ClassRegistry::getClass('MenuModel');
     }
     if (!$this->ajaxRequest) {
         if (!($menu_id = Configure::read('_public_menu_id'))) {
             # Find and set one public Itemid to use for Ajax requests
             $menu_id = '';
             $menu_id = $this->Menu->get('jreviews_public');
             $menu_id = $menu_id != '' ? $menu_id : 99999;
             Configure::write('_public_menu_id', $menu_id);
         }
         if (!($search_itemid = Configure::read('_search_itemid'))) {
             // Set search menu Itemid used in several of the controllers
             $option = Sanitize::getString($this->params, 'option');
             $auto_itemid = Sanitize::getBool($this->Config, 'search_itemid', false);
             $hc_itemid = Sanitize::getInt($this->Config, 'search_itemid_hc', '');
             $search_menuid = $this->Menu->get('jr_advsearch');
             $search_itemid = '';
             switch ($option) {
                 case 'com_jreviews':
                     // page Itemid is enabled
                     if (!$auto_itemid && $hc_itemid > 0) {
                         $search_itemid = $hc_itemid;
                     } elseif (!$auto_itemid & $search_menuid > 0) {
                         $search_itemid = $search_menuid;
                     }
                     break;
                 default:
                     // Non-JReviews pages - can't use current page Itemid
                     if ($hc_itemid > 0) {
                         $search_itemid = $hc_itemid;
                     } else {
                         $search_itemid = $search_menuid;
                     }
                     break;
             }
             $search_itemid == '' and $option == 'com_jreviews' and $search_itemid = Sanitize::getString($this->params, 'Itemid');
             Configure::write('_search_itemid', $search_itemid);
         }
         $this->set(array('search_itemid' => $search_itemid, 'public_menu_id' => $menu_id));
     }
     if (!defined('MVC_GLOBAL_JS_VARS') && !$this->ajaxRequest && $this->action != '_save') {
         # Add global javascript variables
         $this->assets['head-top'][] = '<script type="text/javascript">
         /* <![CDATA[ */
         var s2AjaxUri = "' . getAjaxUri() . '",
             jrLanguage = new Array(),
             jrVars = new Array(),
             datePickerImage = "' . $this->viewImages . 'calendar.gif",
             jrPublicMenu = ' . $menu_id . ';
         jrLanguage["cancel"] = "' . __t("Cancel", true) . '";
         jrLanguage["submit"] = "' . __t("Submit", true) . '";
         jrLanguage["clearDate"] = "' . __t("Clear", true) . '";
         jrLanguage["field.select"] = "' . __t("-- Select --", true) . '";
         jrLanguage["field.select_field"] = "' . __t("-- Select %s --", true) . '";
         jrLanguage["field.no_results"] = "' . __t("No results found, try a different spelling.", true) . '";
         jrLanguage["field.ui_help"] = "' . __t("Start typing for suggestions", true) . '";
         jrLanguage["field.ui_add"] = "' . __t("Add", true) . '";
         jrLanguage["compare.heading"] = "' . __t("Compare", true) . '";
         jrLanguage["compare.compare_all"] = "' . __t("Compare All", true) . '";
         jrLanguage["compare.remove_all"] = "' . __t("Remove All", true) . '";
         jrLanguage["compare.select_more"] = "' . __t("You need to select more than one listing for comparison.", true) . '";
         jrLanguage["compare.select_max"] = "' . __t("You selected maximum number of listings for comparison.", true) . '";
         jrVars["locale"] = "' . cmsFramework::getLocale() . '";
         /* ]]> */
         </script>';
         if ($item_id = Sanitize::getInt($this->params, 'Itemid')) {
             $menu = $this->Menu->getMenuParams($item_id);
             $meta_desc = Sanitize::getString($menu, 'menu-meta_description');
             $meta_keys = Sanitize::getString($menu, 'menu-meta_keywords');
             $meta_desc != '' and cmsFramework::meta('description', $meta_desc);
             $meta_keys != '' and cmsFramework::meta('keywords', $meta_keys);
         }
         define('MVC_GLOBAL_JS_VARS', 1);
     }
     # Dynamic Community integration loading
     $community_extension = Configure::read('Community.extension');
     $community_extension = $community_extension != '' ? $community_extension : 'community_builder';
     App::import('Model', $community_extension, 'jreviews');
     $this->Community = new CommunityModel();
     # Init plugin system
     $this->_initPlugins();
 }
 function search()
 {
     $urlSeparator = "_";
     //Used for url parameters that pass something more than just a value
     $simplesearch_custom_fields = 1;
     // Search custom fields in simple search
     $simplesearch_query_type = 'all';
     // any|all
     $min_word_chars = 3;
     // Only words with min_word_chars or higher will be used in any|all query types
     $category_ids = '';
     $criteria_ids = Sanitize::getString($this->params, 'criteria');
     $dir_id = Sanitize::getString($this->params, 'dir', '');
     $accepted_query_types = array('any', 'all', 'exact');
     $query_type = Sanitize::getString($this->params, 'query');
     $keywords = urldecode(Sanitize::getString($this->params, 'keywords'));
     $scope = Sanitize::getString($this->params, 'scope');
     $author = urldecode(Sanitize::getString($this->params, 'author'));
     $ignored_search_words = $keywords != '' ? cmsFramework::getIgnoredSearchWords() : array();
     if (!in_array($query_type, $accepted_query_types)) {
         $query_type = 'all';
         // default value if value used is not recognized
     }
     // Build search where statement for standard fields
     $wheres = array();
     # SIMPLE SEARCH
     if ($keywords != '' && $scope == '') {
         //            $scope = array("Listing.title","Listing.introtext","Listing.fulltext","Review.comments","Review.title");
         $scope = array("Listing.title", "Listing.introtext", "Listing.fulltext", "Listing.metakey");
         $words = array_unique(explode(' ', $keywords));
         // Include custom fields
         if ($simplesearch_custom_fields == 1) {
             $tbcols = $this->_db->getTableFields(array('#__jreviews_content'));
             $fields = array_keys($tbcols['#__jreviews_content']);
             $ignore = array("email", "contentid", "featured");
             // TODO: find out which fields have predefined selection values to get the searchable values instead of reference
         }
         $whereFields = array();
         foreach ($scope as $contentfield) {
             $whereContentFields = array();
             foreach ($words as $word) {
                 if (strlen($word) >= $min_word_chars && !in_array($word, $ignored_search_words)) {
                     $word = urldecode(trim($word));
                     $whereContentFields[] = " {$contentfield} LIKE " . $this->quoteLike($word);
                 }
             }
             if (!empty($whereContentFields)) {
                 $whereFields[] = " (" . implode($simplesearch_query_type == 'all' ? ') AND (' : ') OR (', $whereContentFields) . ')';
             }
         }
         if ($simplesearch_custom_fields == 1) {
             // add custom fields to where statement
             foreach ($fields as $field) {
                 $whereCustomFields = array();
                 foreach ($words as $word) {
                     $word = urldecode($word);
                     if (strlen($word) >= $min_word_chars && !in_array($word, $ignored_search_words)) {
                         if (!in_array($field, $ignore)) {
                             $whereCustomFields[] = "{$field} LIKE " . $this->quoteLike($word);
                         }
                     }
                 }
                 if (!empty($whereCustomFields) && !in_array($field, $ignore)) {
                     $whereFields[] = "\n(" . implode($simplesearch_query_type == 'all' ? ') AND (' : ') OR (', $whereCustomFields) . ')';
                 }
             }
         }
         if (!empty($whereFields)) {
             $wheres[] = "\n(" . implode(') OR (', $whereFields) . ')';
         }
     } else {
         # ADVANCED SEARCH
         // Process core content fields and reviews
         if ($keywords != '' && $scope != '') {
             $allowedContentFields = array("title", "introtext", "fulltext", "reviews", "metakey");
             $scope = explode($urlSeparator, $scope);
             $scope[] = 'metakey';
             switch ($query_type) {
                 case 'exact':
                     foreach ($scope as $contentfield) {
                         if (in_array($contentfield, $allowedContentFields)) {
                             $w = array();
                             if ($contentfield == 'reviews') {
                                 $w[] = " Review.comments LIKE " . $this->quoteLike($keywords);
                                 $w[] = " Review.title LIKE " . $this->quoteLike($keywords);
                             } else {
                                 $w[] = " Listing.{$contentfield} LIKE " . $this->quoteLike($keywords);
                             }
                             $whereContentOptions[] = "\n" . implode(' OR ', $w);
                         }
                     }
                     $wheres[] = implode(' OR ', $whereContentOptions);
                     break;
                 case 'any':
                 case 'all':
                 default:
                     $words = array_unique(explode(' ', $keywords));
                     $whereFields = array();
                     foreach ($scope as $contentfield) {
                         if (in_array($contentfield, $allowedContentFields)) {
                             $whereContentFields = array();
                             $whereReviewComment = array();
                             $whereReviewTitle = array();
                             foreach ($words as $word) {
                                 if (strlen($word) >= $min_word_chars && !in_array($word, $ignored_search_words)) {
                                     if ($contentfield == 'reviews') {
                                         $whereReviewComment[] = "Review.comments LIKE " . $this->quoteLike($word);
                                         $whereReviewTitle[] = "Review.title LIKE " . $this->quoteLike($word);
                                     } else {
                                         $whereContentFields[] = "Listing.{$contentfield} LIKE " . $this->quoteLike($word);
                                     }
                                 }
                             }
                             if ($contentfield == 'reviews') {
                                 $whereFields[] = "\n(" . implode($query_type == 'all' ? ') AND (' : ') OR (', $whereReviewTitle) . ")";
                                 $whereFields[] = "\n(" . implode($query_type == 'all' ? ') AND (' : ') OR (', $whereReviewComment) . ")";
                             } else {
                                 $whereFields[] = "\n(" . implode($query_type == 'all' ? ') AND (' : ') OR (', $whereContentFields) . ")";
                             }
                         }
                     }
                     $wheres[] = '(' . implode(') OR (', $whereFields) . ')';
                     break;
             }
         } else {
             $scope = array();
         }
         // Process author field
         if ($author && $this->Config->search_item_author) {
             $wheres[] = "( User.name LIKE " . $this->quoteLike($author) . " OR " . "\n User.username LIKE " . $this->quoteLike($author) . " OR " . "\n Listing.created_by_alias LIKE " . $this->quoteLike($author) . " )";
         }
         // Process custom fields
         $query_string = Sanitize::getString($this->passedArgs, 'url');
         if ($tag = Sanitize::getVar($this->params, 'tag')) {
             $this->click2search = true;
             // Field value underscore fix: remove extra menu parameter not removed in routes regex
             $tag['value'] = preg_replace(array('/_m[0-9]+$/', '/_m$/', '/_$/'), '', $tag['value']);
             // Below is included fix for dash to colon change in J1.5
             $query_string = 'jr_' . $tag['field'] . _PARAM_CHAR . str_replace(':', '-', $tag['value']) . '/' . $query_string;
         }
         $url_array = explode("/", $query_string);
         // Include external parameters for custom fields - this is required for components such as sh404sef
         foreach ($this->params as $varName => $varValue) {
             if (substr($varName, 0, 3) == "jr_" && false === array_search($varName . _PARAM_CHAR . $varValue, $url_array)) {
                 $url_array[] = $varName . _PARAM_CHAR . $varValue;
             }
         }
         // Get names of custom fields to eliminate queries on non-existent fields
         $customFieldsMeta = $this->_db->getTableFields(array('#__jreviews_content'));
         $customFields = is_array($customFieldsMeta['#__jreviews_content']) ? array_keys($customFieldsMeta['#__jreviews_content']) : array();
         /****************************************************************************
          * First pass of url params to get all field names and then find their types
          ****************************************************************************/
         $fieldNameArray = array();
         foreach ($url_array as $url_param) {
             $param = explode(":", $url_param);
             $key = $param[0];
             $value = Sanitize::getVar($param, '1', null);
             // '1' is the key where the value is stored in $param
             if (substr($key, 0, 3) == "jr_" && in_array($key, $customFields) && !is_null($value) && $value != '') {
                 $fieldNameArray[$key] = $value;
             }
         }
         // Find out the field type to determine whether it's an AND or OR search
         if (!empty($fieldNameArray)) {
             $query = '
                 SELECT 
                     name, type 
                 FROM 
                     #__jreviews_fields 
                 WHERE 
                     name IN (' . $this->quote(array_keys($fieldNameArray)) . ')';
             $this->_db->setQuery($query);
             $fieldTypesArray = $this->_db->loadAssocList('name');
         }
         $OR_fields = array("select", "radiobuttons");
         // Single option
         $AND_fields = array("selectmultiple", "checkboxes");
         // Multiple option
         foreach ($fieldNameArray as $key => $value) {
             $searchValues = explode($urlSeparator, $value);
             $fieldType = $fieldTypesArray[$key]['type'];
             // Process values with separator for multiple values or operators. The default separator is an underscore
             if (substr_count($value, $urlSeparator)) {
                 // Check if it is a numeric or date value
                 $allowedOperators = array("equal" => '=', "higher" => '>=', "lower" => '<=', "between" => 'between');
                 $operator = $searchValues[0];
                 $isDate = false;
                 if ($searchValues[1] == "date") {
                     $isDate = true;
                 }
                 if (in_array($operator, array_keys($allowedOperators)) && (is_numeric($searchValues[1]) || $isDate)) {
                     if ($operator == "between") {
                         if ($isDate) {
                             @($searchValues[1] = low($searchValues[2]) == 'today' ? _TODAY : $searchValues[2]);
                             @($searchValues[2] = low($searchValues[3]) == 'today' ? _TODAY : $searchValues[3]);
                         }
                         $low = is_numeric($searchValues[1]) ? $searchValues[1] : $this->quote($searchValues[1]);
                         $high = is_numeric($searchValues[2]) ? $searchValues[2] : $this->quote($searchValues[2]);
                         $wheres[] = "\n" . $key . " BETWEEN " . $low . ' AND ' . $high;
                     } else {
                         if ($searchValues[1] == "date") {
                             $searchValues[1] = low($searchValues[2]) == 'today' ? _TODAY : $searchValues[2];
                         }
                         $value = is_numeric($searchValues[1]) ? $searchValues[1] : $this->quote($searchValues[1]);
                         $wheres[] = "\n" . $key . $allowedOperators[$operator] . $value;
                     }
                 } else {
                     // This is a field with pre-defined options
                     $whereFields = array();
                     if (isset($tag) && ($key = 'jr_' . $tag['field'])) {
                         // Field value underscore fix
                         if (in_array($fieldType, $OR_fields)) {
                             $whereFields[] = " {$key} = '*" . $this->quote('*' . urldecode($value) . '*');
                         } else {
                             $whereFields[] = " {$key} LIKE " . $this->quote('%*' . urldecode($value) . '*%');
                         }
                     } elseif (!empty($searchValues)) {
                         foreach ($searchValues as $value) {
                             $searchValue = urldecode($value);
                             if (in_array($fieldType, $OR_fields)) {
                                 $whereFields[] = " {$key} = " . $this->quote('*' . $value . '*');
                             } else {
                                 $whereFields[] = " {$key} LIKE " . $this->quote('%*' . $value . '*%');
                             }
                         }
                     }
                     if (in_array($fieldType, $OR_fields)) {
                         // Single option field
                         $wheres[] = '(' . implode(') OR (', $whereFields) . ')';
                     } else {
                         // Multiple option field
                         $wheres[] = '(' . implode(') AND (', $whereFields) . ')';
                     }
                 }
             } else {
                 $value = urldecode($value);
                 $whereFields = array();
                 if (in_array($fieldType, $OR_fields)) {
                     $whereFields[] = " {$key} = " . $this->quote('*' . $value . '*');
                 } elseif (in_array($fieldType, $AND_fields)) {
                     $whereFields[] = " {$key} LIKE " . $this->quote('%*' . $value . '*%');
                 } elseif (in_array($fieldType, array('integer', 'decimal'))) {
                     // Does an exact search for numeric fields
                     $words = explode(' ', trim($value));
                     foreach ($words as $word) {
                         $whereFields[] = "{$key} = " . $this->quote($word);
                     }
                 } else {
                     $whereFields[] = " {$key} LIKE " . $this->quoteLike($value);
                 }
                 $wheres[] = " (" . implode(') AND (', $whereFields) . ")";
             }
         }
         // endforeach
     }
     $where = !empty($wheres) ? "\n (" . implode(") AND (", $wheres) . ")" : '';
     // Determine which categories to include in the queries
     if ($cat_id = Sanitize::getString($this->params, 'cat')) {
         $section_ids = array();
         $category_ids = explode($urlSeparator, $this->params['cat']);
         // Remove empty or nonpositive values from array
         if (!empty($category_ids)) {
             foreach ($category_ids as $index => $value) {
                 // Check if it's a section
                 if ($value[0] == 's' && is_numeric(substr($value, 1)) && substr($value, 1) > 0) {
                     $section_ids[] = substr($value, 1);
                     unset($category_ids[$index]);
                     // It's a section, not a category
                 } elseif (empty($value) || $value < 1 || !is_numeric($value)) {
                     unset($category_ids[$index]);
                 }
             }
         }
         $section_ids = implode(',', $section_ids);
         $category_ids = is_array($category_ids) ? implode(',', $category_ids) : $category_ids;
         $category_ids != '' and $this->params['cat'] = $category_ids;
         $section_ids != '' and $this->params['section'] = $section_ids;
     } elseif (isset($criteria_ids) && trim($criteria_ids) != '') {
         $criteria_ids = str_replace($urlSeparator, ',', $criteria_ids);
         $criteria_ids != '' and $this->params['criteria'] = $criteria_ids;
     } elseif (isset($dir_id) && trim($dir_id) != '') {
         $dir_id = str_replace($urlSeparator, ',', $dir_id);
         $dir_id != '' and $this->params['dir'] = $dir_id;
     }
     # Add search conditions to Listing model
     if ($where != '') {
         $this->Listing->conditions[] = $where;
     } elseif (empty($this->Listing->conditions) && $dir_id == '' && $category_ids == '' && $criteria_ids == '' && ($this->cmsVersion == CMS_JOOMLA15 && $section_ids == '' || $this->cmsVersion != CMS_JOOMLA15) && !Sanitize::getBool($this->Config, 'search_return_all', false)) {
         return $this->render('listings', 'listings_noresults');
     }
     return $this->listings();
 }
Exemple #13
0
 /**
  * Creates the json object used for map rendering
  *     
  * @param array $results listings
  * @param mixed $fields  custom fields, required when using the GeoMaps module
  * @param mixed $options mapUI options to override globals when using GeoMaps module
  */
 function makeJsonObject(&$results, &$fields = array(), $options = array())
 {
     $www_base = array_shift(pathinfo(WWW_ROOT));
     // Required for thumbnail path
     $paths = array(S2Paths::get('jreviews', 'S2_VIEWS_OVERRIDES') . 'themes' . DS . $this->c->Config->template . DS . 'theme_images' . DS, S2Paths::get('jreviews', 'S2_VIEWS') . 'themes' . DS . $this->c->Config->template . DS . 'theme_images' . DS, S2Paths::get('jreviews', 'S2_VIEWS_OVERRIDES') . 'themes' . DS . 'default' . DS . 'theme_images' . DS, S2Paths::get('jreviews', 'S2_VIEWS') . 'themes' . DS . 'default' . DS . 'theme_images' . DS);
     $path = fileExistsInPath(array('name' => '', 'suffix' => '', 'ext' => ''), $paths);
     App::import('Helper', array('html', 'routes', 'custom_fields', 'thumbnail'));
     $Html = new HtmlHelper();
     $Routes = new RoutesHelper();
     $CustomFields = new CustomFieldsHelper();
     $Thumbnail = new ThumbnailHelper();
     $Thumbnail->app = 'jreviews';
     $Thumbnail->name = $this->c->name;
     $Thumbnail->action = $this->c->action;
     $Routes->Config = $CustomFields->Config = $Thumbnail->Config = $this->c->Config;
     $Routes->Access = $CustomFields->Access = $Thumbnail->Access = $this->c->Access;
     $Routes->Html = $CustomFields->Html = $Thumbnail->Html = $Html;
     $CustomFields->viewTheme = $Thumbnail->viewTheme =& $this->c->viewTheme;
     $CustomFields->viewSuffix =& $this->c->viewSuffix;
     // Check format of results because we may need to re-format and add fields for Geomaps module
     $first = current($results);
     if (!isset($first['Listing'])) {
         $results = $this->buildListingArray($results, $fields);
     }
     // PaidListings - remove unpaid info
     Configure::read('PaidListings') and PaidListingsComponent::processPaidData($results);
     $marker_icons = array();
     $infowindow_data = array();
     $i = 1;
     $default_icon = $this->c->name == 'categories' ? 'numbered' : 'default';
     // make sure we only have the numeric part of the id from request when checking against listing ids
     $request_id = explode(':', JRequest::getVar('id'));
     $request_id = $request_id[0];
     if (!empty($results)) {
         foreach ($results as $key => $result) {
             $results[$key] = $this->injectDistanceGroup($result);
             // Add menu id if not already there
             if (!isset($result['Listing']['menu_id'])) {
                 $results[$key]['Listing']['menu_id'] = $this->c->Menu->getCategory($result['Listing']['cat_id'], $result['Listing']['section_id'], $result['Directory']['dir_id'], $result['Listing']['listing_id']);
             }
             // Added to support extra coordinates
             //$coords = $result["Field"]["groups"]["Location Info"]["Fields"]["jr_extracoords"]["value"][0];
             //$xtracoords = $CustomFields->field('jr_extracoords', $listing, false, false);
             if (isset($result["Field"]["groups"]["Location Info"]) && isset($result["Field"]["groups"]["Location Info"]["Fields"]["jr_extracoords"])) {
                 $coords = $result["Field"]["groups"]["Location Info"]["Fields"]["jr_extracoords"]["value"][0];
                 if ($coords) {
                     $coords = json_decode($coords);
                     $results[$key]["ExtraCoords"] = $coords;
                     if (JRequest::getString("option") != "com_content") {
                         $results[$key]["ExtraCoords"] = 0;
                     }
                     // HTGMOD
                 }
             } elseif (isset($result["Field"]["pairs"]["jr_extracoords"])) {
                 //detail page
                 $coords = $result["Field"]["pairs"]["jr_extracoords"]["value"][0];
                 if ($coords) {
                     $coords = json_decode($coords);
                     $results[$key]["ExtraCoords"] = $coords;
                     if ($results[$key]["Listing"]["listing_id"] != $request_id) {
                         // "if the current listing_id in the loop == the listing_id being viewed on the detail page...."
                         $results[$key]["ExtraCoords"] = 0;
                     }
                 }
             }
             $listing_index = ($this->c->page - 1) * $this->c->limit + $i++;
             // Process and add icon info
             $icon = isset($result['Geomaps']) ? json_decode($result['Geomaps']['icon'], true) : array();
             $results[$key]['Geomaps']['icon'] = '';
             $icon_name = $default_icon;
             if (!empty($icon)) {
                 $foundIcon = false;
                 // Check if custom field assigned
                 if ($icon['field'] != '' && substr($icon['field'], 0, 3) == 'jr_') {
                     if (isset($result['Field']['pairs'][$icon['field']]) && isset($result['Field']['pairs'][$icon['field']]['image'][0])) {
                         $icon_name = substr($result['Field']['pairs'][$icon['field']]['image'][0], 0, strpos($result['Field']['pairs'][$icon['field']]['image'][0], '.'));
                         $marker_icons[$icon_name] = $results[$key]['Geomaps']['icon'] = $result['Field']['pairs'][$icon['field']]['image'][0];
                         $foundIcon = true;
                     }
                 } elseif ($icon['cat'] != '' && !$foundIcon) {
                     $icon_name = substr($icon['cat'], 0, strpos($icon['cat'], '.'));
                     if ($icon_name != 'default') {
                         $marker_icons[$icon_name] = $results[$key]['Geomaps']['icon'] = $icon['cat'];
                     }
                 }
             }
             if (isset($result['Geomaps']) && $result['Geomaps']['lat'] != '' && $result['Geomaps']['lon'] != '' && $result['Geomaps']['lat'] != 0 && $result['Geomaps']['lon']) {
                 # Create infowindow JSON object
                 // start with standard fields
                 $infowindow = array('id' => $result['Listing']['listing_id'], 'url' => str_replace(array($www_base, '&amp;'), array('', '&'), $Routes->content('', $results[$key], array('return_url' => true))), 'index' => $listing_index, 'title' => $result['Listing']['title'], 'image' => str_replace($www_base, '', $Thumbnail->thumb($result, 0, 'scale', 'list', array($this->c->Config->list_image_resize), array('return_src' => 1))), 'featured' => $result['Listing']['featured'], 'rating_scale' => $this->c->Config->rating_scale, 'user_rating' => $result['Review']['user_rating'], 'user_rating_count' => $result['Review']['user_rating_count'], 'editor_rating' => $result['Review']['editor_rating'], 'editor_rating_count' => $result['Review']['editor_rating_count'], 'lat' => (double) $result['Geomaps']['lat'], 'lon' => (double) $result['Geomaps']['lon'], 'icon' => $icon_name);
                 // Added for Hooked
                 $infowindow['criteria_id'] = $result['Criteria']['criteria_id'];
                 if (isset($results[$key]["ExtraCoords"])) {
                     $infowindow['extracoords'] = $results[$key]["ExtraCoords"];
                 }
                 if (isset($results[$key]['Listing']['relations'])) {
                     $infowindow['relations'] = $results[$key]['Listing']['relations'];
                 }
                 if ($results[$key]['Listing']['section_id'] != 1) {
                     $infowindow['hascontent'] = 1;
                 } else {
                     if (isset($results[$key]['Listing']['summary']) && $results[$key]['Listing']['summary'] != '') {
                         $infowindow['hascontent'] = 1;
                     } else {
                         $infowindow['hascontent'] = 0;
                     }
                 }
                 if (!empty($result['Field']['pairs'])) {
                     foreach ($result['Field']['pairs'] as $name => $fieldArray) {
                         $infowindow['field'][$name] = $CustomFields->field($name, $result);
                     }
                 }
                 $infowindow_data['id' . $result['Listing']['listing_id']] = $infowindow;
             }
         }
     }
     $mapUI = array();
     $zoom = '';
     switch ($this->c->name) {
         case 'categories':
             $maptypes = Sanitize::getString($this->c->Config, 'geomaps.ui.maptype_list', 'buttons');
             //buttons|menu|none
             $maptype_def = Sanitize::getString($this->c->Config, 'geomaps.ui.maptype_def_list', 'G_NORMAL_MAP');
             $map = Sanitize::getBool($this->c->Config, 'geomaps.ui.map_list', 1);
             $hybrid = Sanitize::getBool($this->c->Config, 'geomaps.ui.hybrid_list', 1);
             $satellite = Sanitize::getBool($this->c->Config, 'geomaps.ui.satellite_list', 1);
             $terrain = Sanitize::getBool($this->c->Config, 'geomaps.ui.terrain_list', 1);
             $panzoom = Sanitize::getBool($this->c->Config, 'geomaps.ui.panzoom_list', 1);
             $scale = Sanitize::getBool($this->c->Config, 'geomaps.ui.scale_list', 0);
             $scrollwheel = Sanitize::getBool($this->c->Config, 'geomaps.ui.scrollwheel_list', 0);
             $doubleclick = Sanitize::getBool($this->c->Config, 'geomaps.ui.doubleclick_list', 1);
             $mapUI['title']['trim'] = Sanitize::getVar($this->c->Config, 'geomaps.ui.trimtitle_list', 0);
             $mapUI['title']['trimchars'] = Sanitize::getVar($this->c->Config, 'geomaps.ui.trimtitle_chars', 30);
             break;
         case 'com_content':
             $maptypes = Sanitize::getString($this->c->Config, 'geomaps.ui.maptype_detail', 'buttons');
             //buttons|menu|none
             $maptype_def = Sanitize::getString($this->c->Config, 'geomaps.ui.maptype_def_detail', 'G_NORMAL_MAP');
             $map = Sanitize::getBool($this->c->Config, 'geomaps.ui.map_detail', 1);
             $hybrid = Sanitize::getBool($this->c->Config, 'geomaps.ui.hybrid_detail', 1);
             $satellite = Sanitize::getBool($this->c->Config, 'geomaps.ui.satellite_detail', 1);
             $terrain = Sanitize::getBool($this->c->Config, 'geomaps.ui.terrain_detail', 1);
             $panzoom = Sanitize::getBool($this->c->Config, 'geomaps.ui.panzoom_detail', 1);
             $scale = Sanitize::getBool($this->c->Config, 'geomaps.ui.scale_detail', 0);
             $scrollwheel = Sanitize::getBool($this->c->Config, 'geomaps.ui.scrollwheel_detail', 0);
             $doubleclick = Sanitize::getBool($this->c->Config, 'geomaps.ui.doubleclick_detail', 1);
             $zoom = Sanitize::getInt($this->c->Config, 'geomaps.ui.zoom_detail', '');
             $mapUI['title']['trim'] = Sanitize::getVar($this->c->Config, 'geomaps.ui.trimtitle_detail', 0);
             $mapUI['title']['trimchars'] = Sanitize::getVar($this->c->Config, 'geomaps.ui.trimtitle_chars', 30);
             break;
         case 'module_geomaps':
             $maptypes = Sanitize::getString($options, 'ui_maptype', 2) == '2' ? Sanitize::getString($this->c->Config, 'geomaps.ui.maptype_module', 'buttons') : Sanitize::getString($options, 'ui_maptype');
             //buttons|menu|none
             $maptype_def = Sanitize::getString($options, 'ui_maptype_def', 2) == '2' ? Sanitize::getString($this->c->Config, 'geomaps.ui.maptype_def_module', 'G_NORMAL_MAP') : Sanitize::getString($options, 'ui_maptype_def', 'G_NORMAL_MAP');
             $map = Sanitize::getInt($options, 'ui_map', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.map_module', 1) : Sanitize::getBool($options, 'ui_map');
             $hybrid = Sanitize::getInt($options, 'ui_hybrid', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.hybrid_module', 1) : Sanitize::getBool($options, 'ui_hybrid');
             $satellite = Sanitize::getInt($options, 'ui_satellite', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.satellite_module', 1) : Sanitize::getBool($options, 'ui_satellite');
             $terrain = Sanitize::getInt($options, 'ui_terrain', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.terrain_module', 1) : Sanitize::getBool($options, 'ui_terrain');
             $panzoom = Sanitize::getInt($options, 'ui_panzoom', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.panzoom_module', 1) : Sanitize::getBool($options, 'ui_panzoom');
             $scale = Sanitize::getInt($options, 'ui_scale', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.scale_module', 0) : Sanitize::getBool($options, 'ui_scale');
             $scrollwheel = Sanitize::getInt($options, 'ui_scrollwheel', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.scrollwheel_module', 0) : Sanitize::getBool($options, 'ui_scrollwheel');
             $doubleclick = Sanitize::getInt($options, 'ui_doubleclick', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.doubleclick_module', 1) : Sanitize::getBool($options, 'ui_doubleclick');
             $mapUI['title']['trim'] = Sanitize::getInt($options, 'ui_trimtitle_module', 2) == '2' ? Sanitize::getBool($this->c->Config, 'geomaps.ui.trimtitle_module', 30) : Sanitize::getBool($options, 'ui_trimtitle_module');
             $mapUI['title']['trimchars'] = Sanitize::getInt($options, 'ui_trimtitle_chars', 2) == '2' ? Sanitize::getInt($this->c->Config, 'geomaps.ui.trimtitle_chars', 30) : Sanitize::getInt($options, 'ui_trimtitle_chars');
             if (Sanitize::getString($options, 'detail_view', 1)) {
                 $zoom = Sanitize::getInt($this->c->Config, 'geomaps.ui.zoom_detail', '');
             }
             break;
     }
     switch ($maptypes) {
         case 'buttons':
             $mapUI['controls']['maptypecontrol'] = true;
             $mapUI['controls']['menumaptypecontrol'] = false;
             break;
         case 'menu':
             $mapUI['controls']['maptypecontrol'] = false;
             $mapUI['controls']['menumaptypecontrol'] = true;
             break;
         default:
             $mapUI['controls']['maptypecontrol'] = false;
             $mapUI['controls']['menumaptypecontrol'] = false;
     }
     $mapUI['maptypes']['def'] = $maptype_def;
     $mapUI['maptypes']['map'] = $map;
     $mapUI['maptypes']['hybrid'] = $hybrid;
     $mapUI['maptypes']['satellite'] = $satellite;
     $mapUI['maptypes']['terrain'] = $terrain;
     if ($panzoom) {
         $mapUI['controls']['smallzoomcontrol3d'] = true;
         $mapUI['controls']['largemapcontrol3d'] = true;
     } else {
         $mapUI['controls']['smallzoomcontrol3d'] = false;
         $mapUI['controls']['largemapcontrol3d'] = false;
     }
     $mapUI['controls']['scalecontrol'] = $scale;
     $mapUI['zoom']['scrollwheel'] = $scrollwheel;
     $mapUI['zoom']['doubleclick'] = $doubleclick;
     $mapUI['zoom']['start'] = $zoom;
     $mapUI['anchor']['x'] = Sanitize::getVar($this->c->Config, 'geomaps.infowindow_x', 0);
     $mapUI['anchor']['y'] = Sanitize::getVar($this->c->Config, 'geomaps.infowindow_y', 0);
     unset($Html, $Routes, $CustomFields, $Thumbnail);
     return json_encode(array('count' => count($infowindow_data), 'mapUI' => $mapUI, 'infowindow' => Sanitize::getString($this->c->Config, 'geomaps.infowindow', '_google'), 'icons' => $this->processIcons($marker_icons), 'payload' => $infowindow_data));
 }
Exemple #14
0
 function select($fieldName, $options = array(), $selected = null, $attributes = array())
 {
     $sel = '';
     if (!is_null($selected) && $selected != '') {
         if (!is_array($selected)) {
             $selected = array(strtolower($selected));
         }
     } else {
         if (isset($attributes['value'])) {
             if (!is_array($attributes['value'])) {
                 $selected = array(strtolower($attributes['value']));
             } else {
                 $selected = $attributes['value'];
             }
             unset($attributes['value']);
         }
     }
     if (isset($attributes['multiple'])) {
         $select = sprintf($this->Html->tags['selectmultiplestart'], $fieldName, $this->_parseAttributes($attributes));
         unset($attributes['multiple']);
     } else {
         $select = sprintf($this->Html->tags['selectstart'], $fieldName, $this->_parseAttributes($attributes));
     }
     foreach ($options as $value => $text) {
         $disabled = false;
         $sel = '';
         if (is_array($text) || is_object($text)) {
             $text = (array) $text;
             $disabled = Sanitize::getBool($text, 'disabled', false);
             if (!isset($text['text'])) {
                 $text = current($text);
             }
             $value = isset($text['value']) ? $text['value'] : $value;
             $text = $text['text'];
             // For CMS db query results w/o having to do an additional foreach
         }
         $text = htmlspecialchars($text, ENT_QUOTES, 'utf-8', false);
         # Multiple select list
         if ($selected && is_array($selected)) {
             $sel = deep_in_array($value, $selected, true) ? ' selected="selected"' : '';
             # Single select list
         } elseif ($selected) {
             $sel = $value == $selected ? ' selected="selected"' : '';
         }
         $disabled and $sel .= ' disabled="disabled"';
         $select .= sprintf($this->Html->tags['selectoption'], $value, $sel, $text);
     }
     $select .= $this->Html->tags['selectend'];
     return $select;
 }
Exemple #15
0
 function store(&$data, $updateNulls = false, $callbacks = array('beforeSave', 'afterSave', 'plgBeforeSave', 'plgAfterSave'))
 {
     Sanitize::getBool($data, 'insert') and $insert = true or $insert = false;
     if (method_exists($this, 'beforeSave') && in_array('beforeSave', $callbacks)) {
         $this->beforeSave($data);
     }
     if (method_exists($this, 'plgBeforeSave') && in_array('plgBeforeSave', $callbacks)) {
         $data = $this->plgBeforeSave($data);
     }
     $table = substr($this->useTable, 0, strpos($this->useTable, ' AS'));
     $primaryKeyString = isset($this->realKey) ? $this->realKey : $this->primaryKey;
     $keyName = end(explode('.', str_replace('`', '', $primaryKeyString)));
     if (isset($data[$this->name][$keyName]) && $data[$this->name][$keyName] > 0 && !$insert) {
         $ret = $this->update($table, $this->name, $data, $keyName, $updateNulls);
     } else {
         $ret = $this->insert($table, $this->name, $data, $keyName);
     }
     if (!$ret) {
         $this->_error = strtolower(get_class($this)) . "::store failed <br />" . $this->_db->getErrorMsg();
     }
     $this->data =& $data;
     if (method_exists($this, 'afterSave') && in_array('afterSave', $callbacks)) {
         $this->afterSave($ret);
     }
     if (method_exists($this, 'plgAfterSave') && in_array('plgAfterSave', $callbacks)) {
         $this->plgAfterSave($ret);
     }
     clearCache('', 'views');
     clearCache('', '__data');
     return $ret;
 }
 function _save()
 {
     $this->action = 'index';
     $criteriaid = $this->data['Criteria']['id'];
     $reviews = array();
     $apply = Sanitize::getBool($this->data, 'apply', false);
     // revert all input arrays to strings
     foreach (array('criteria', 'required', 'weights', 'tooltips') as $v) {
         if ($v == 'tooltips') {
             $this->data['Criteria'][$v] = implode("\n", $this->data['__raw']['Criteria'][$v]);
         } else {
             $this->data['Criteria'][$v] = implode("\n", $this->data['Criteria'][$v]);
         }
     }
     # Configuration overrides - save as json object
     // Pre-process access overrides first
     $keys = array_keys($this->data['Criteria']['config']);
     $access_keys = array('addnewaccess', 'addnewaccess_reviews');
     while ($access_key = array_shift($access_keys)) {
         $this->data['Criteria']['config'][$access_key] = in_array($access_key, $keys) ? implode(',', $this->data['Criteria']['config'][$access_key]) : 'none';
     }
     $this->data['Criteria']['config'] = json_encode(Sanitize::getVar($this->data['Criteria'], 'config'));
     // Lets remove any blank lines from the new criteria
     $newCriteria = cleanString2Array($this->data['Criteria']['criteria'], "\n");
     // clean Required field
     $newRequired = cleanString2Array($this->data['Criteria']['required'], "\n");
     // Lets remove any blank lines from the new criteria
     $newTooltips = cleanString2Array($this->data['Criteria']['tooltips'], "\n");
     // New weights
     $newWeights = cleanString2Array($this->data['Criteria']['weights'], "\n");
     // Begin basic validation
     $msg = array();
     if ($this->data['Criteria']['title'] == '') {
         $msg[] = "Fill in the criteria set name.";
     }
     if ($this->data['Criteria']['state'] == 1) {
         if ($this->data['Criteria']['criteria'] == '') {
             $msg[] = "Add at least one criteria to rate your items.";
         }
         if ($this->data['Criteria']['weights'] != '') {
             if (round(array_sum(explode("\n", $this->data['Criteria']['weights']))) != 100 && trim($this->data['Criteria']['weights']) != '') {
                 $msg[] = "The criteria weights have to add up to 100.";
             }
         }
         if (count($newCriteria) != count($newWeights) && count($newWeights) > 0) {
             $msg[] = "The number of criteria does not match the number of weights. Check your entries.";
         }
         if (count($newTooltips) > count($newCriteria)) {
             $msg[] = "There are more tooltips than criteria, please remove the extra tooltips. You may leave blank lines for tooltips if there's a criteria that will not have a tooltip, but the number of lines must match the number of criteria";
         }
         if (count($newRequired) != count($newCriteria)) {
             $msg[] = "The number of criteria does not match the number of the 'Required' fields.";
         }
     } else {
         // if input invalid default to 0
         if (!in_array($this->data['Criteria']['state'], array(0, 2))) {
             $this->data['Criteria']['state'] = 0;
         }
     }
     if (count($msg) > 0) {
         $action = 'error';
         $text = implode("<br />", $msg);
         return $this->ajaxResponse(compact('action', 'text'), false);
     }
     // If this is a new criteria, proceed to save
     if ($criteriaid) {
         // We are in edit mode so let's check if the number of criteria has changed
         $criteria = $this->Criteria->findRow(array('conditions' => array('id = ' . $criteriaid)));
         if (count($newCriteria) != count(cleanString2Array($criteria['Criteria']['criteria']))) {
             $query = "\n                    SELECT\n                        COUNT(*)\n\n                    FROM\n                        #__jreviews_comments AS Reviews\n                    INNER JOIN\n                        #__content AS Content ON Content.id = Reviews.pid\n                    INNER JOIN\n                        #__categories AS Cat ON Cat.id = Content.catid    \n                    INNER JOIN\n                        #__jreviews_categories AS JreviewsCategory ON JreviewsCategory.id = Cat.id\n                    WHERE\n\t\t\t\t\t\tReview.mode = 'com_content' \n\t\t\t\t\t\tAND \n                        JreviewsCategory.criteriaid = {$criteriaid}\n                ";
             $this->_db->setQuery($query);
             $reviews = $this->_db->loadResult();
             // Todo: there are no 'everywhere' checks. will have to go component by component..
             if ($reviews) {
                 // There are reviews so saving is denied.
                 $action = 'error';
                 $text = "There are {$reviews} reviews in the system for listings using this listing type which prevent you from changing the number of criteria. You can only edit the criteria labels, but not add or remove criteria unless you first delete the existing {$reviews} reviews.";
                 return $this->ajaxResponse(compact('action', 'text'), false);
             }
         }
     }
     // Lets remove any blank lines from the new criteria
     $newCriteriaArray = cleanString2Array($this->data['Criteria']['criteria'], "\n");
     $this->data['Criteria']['criteria'] = implode("\n", $newCriteriaArray);
     //Reconstruct the string using the cleaned-up array
     $this->data['Criteria']['qty'] = count($newCriteriaArray);
     // Remove blank lines from weights
     $newWeightsArray = cleanString2Array($this->data['Criteria']['weights'], "\n");
     $this->data['Criteria']['weights'] = implode("\n", $newWeightsArray);
     // for Required
     $newRequiredArray = cleanString2Array($this->data['Criteria']['required'], "\n");
     $this->data['Criteria']['required'] = implode("\n", $newRequiredArray);
     // Convert groupid array to list
     if (isset($this->data['Criteria']['groupid'][0]) && is_array($this->data['Criteria']['groupid'][0])) {
         $this->data['Criteria']['groupid'] = implode(',', $this->data['Criteria']['groupid'][0]);
     } elseif (isset($this->data['Criteria']['groupid']) && is_array($this->data['Criteria']['groupid'])) {
         $this->data['Criteria']['groupid'] = implode(',', $this->data['Criteria']['groupid']);
     } else {
         $this->data['Criteria']['groupid'] = '';
     }
     $this->Criteria->store($this->data);
     if ($apply) {
         $action = 'apply';
         return $this->ajaxResponse(compact('action'), false);
     }
     $action = 'success';
     $page = $this->index();
     $row_id = "criteria" . $this->data['Criteria']['id'];
     return $this->ajaxResponse(compact('action', 'page', 'row_id'), false);
 }
 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;
     }
     # Stop form data tampering
     $formToken = cmsFramework::getCustomToken($review_id);
     if (!cmsFramework::isAdmin() && !$this->__validateToken($formToken)) {
         return s2Messages::accessDenied();
     }
     $facebook = $this->_getFBClass();
     $uid = $facebook->getUser();
     if ($uid) {
         try {
             //get user id
             //                $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']);
                 $review['Review']['comments'] = strip_tags($review['Review']['comments']);
                 if ($this->Config->facebook_posts_trim >= 0 && $review['Review']['comments'] != '') {
                     App::import('Helper', 'text', 'jreviews');
                     $Text = ClassRegistry::getClass('TextHelper');
                     $message = $this->Config->facebook_posts_trim == '' ? $review['Review']['comments'] : $Text->truncateWords($review['Review']['comments'], $this->Config->facebook_posts_trim);
                     $review['Review']['comments'] = $message;
                 }
                 # 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' => $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) {
                     $fbArray['display'] = Configure::read('System.isMobile') ? 'touch' : 'popup';
                     return json_encode($fbArray);
                 }
                 $fb_update = $facebook->api($fbArray);
                 return true;
             }
         } catch (Exception $o) {
             // Error reading permissions
             return false;
         }
     }
     return false;
 }
Exemple #18
0
 function _plgDiscussionAfterSave(&$model)
 {
     $tweet = '';
     /**
      * Run the query only if necessary. Then set it in the
      * controller (viewVars) to make it available in other plugins
      */
     $post = $this->_getReviewPost($model);
     $listing = $this->_getListingEverywhere($post['Listing']['listing_id'], $post['Listing']['extension']);
     // Treat moderated reviews as new
     $this->inAdmin and Sanitize::getBool($model->data, 'moderation') and $model->isNew = true;
     /**
      * Publish activity to Twitter
      */
     if (isset($model->isNew) && $model->isNew && $post['Discussion']['approved'] == 1) {
         $tweet = sprintf(__t($this->activities['comment_new'], true), $listing['Listing']['title'], $post['Discussion']['text']);
         $url = $this->Routes->reviewDiscuss(__t("review", true), $post, array('return_url' => true));
         $url = $this->shortenUrl($url);
         if ($tweet != '') {
             $this->sendTweet($this->truncateTweet($tweet, $url));
         }
     }
 }
Exemple #19
0
 /**
  * Returns simple tree array
  * Uses: cat tree in paidlistings
  * @param mixed $options
  */
 function getTree($options = array())
 {
     $nodes = array();
     $json = Sanitize::getBool($options, 'json');
     $conditions = Sanitize::getVar($options, 'conditions') ? implode(' AND ', $options['conditions']) : false;
     $query = "\n            SELECT \n               Section.id AS section_id, Section.title AS section_title, Category.id AS cat_id, Category.title AS cat_title\n            FROM \n                #__categories AS Category\n            RIGHT JOIN \n                #__sections AS Section ON Section.id = Category.section\n            WHERE \n                1 = 1 \n            " . ($conditions ? " AND (" . $conditions . ") " : '') . "\n             ORDER BY\n               Section.title, Category.title        \n        ";
     $this->_db->setQuery($query);
     $rows = $this->_db->loadAssocList();
     // Build auxiliary arrays
     foreach ($rows as $row) {
         $sections[$row['section_id']] = array("attributes" => array("id" => "s" . $row['section_id']), "data" => $row['section_title'], "state" => "closed");
         $cat = array("attributes" => array("id" => $row['cat_id']), "data" => $row['cat_title']);
         $categories[$row['section_id']][] = $cat;
     }
     foreach ($sections as $section_id => $section) {
         $section['children'] = $categories[$section_id];
         $nodes[] = $section;
     }
     return $json ? json_encode($nodes) : $nodes;
 }
Exemple #20
0
 /**
  * Saves review ratings, fields and recalculates listing totals
  * 
  * @param mixed $status
  */
 function afterSave($status)
 {
     $isNew = Sanitize::getBool($this->data, 'new');
     $ratings_col_empty = Sanitize::getBool($this->data, 'ratings_col_empty');
     $weights = '';
     if (isset($this->data['Criteria']) && Sanitize::getInt($this->data['Criteria'], 'state') == 1) {
         // Process rating data
         // to account for "n/a" values in the ratings and weights, changing the source arrays rather than the whole computation procedure.
         // init variables
         $applicableRatings = array_filter($this->data['Rating']['ratings'], create_function('$el', 'return is_numeric($el);'));
         $ratings_qty = count($applicableRatings);
         $this->data['average_rating'] = $ratings_sum = 'na';
         if ($ratings_qty > 0) {
             if (trim($this->data['Criteria']['weights']) != '') {
                 $weights = explode("\n", $this->data['Criteria']['weights']);
                 // we have to remove the irrelevant weights so to produce clean weights_sum to be used later for proportion calculations
                 $sumWeights = array_sum(array_intersect_key($weights, $applicableRatings));
                 if ($sumWeights > 0) {
                     foreach ($applicableRatings as $key => $rating) {
                         $ratings_sum += $rating * $weights[$key] / $sumWeights;
                     }
                     $ratings_sum = $ratings_sum * $ratings_qty;
                     // This is not the real sum, but it is divided again in the queries.
                 }
             } else {
                 $ratings_sum = array_sum($applicableRatings);
             }
             // Makes average rating easily available in Everywhere model afterSave method
             $this->data['average_rating'] = $ratings_sum / $ratings_qty;
             $this->data['Rating']['ratings_sum'] = $ratings_sum;
             $this->data['Rating']['ratings_qty'] = $ratings_qty;
         }
         # if ( $ratings_qty > 0  )i
         $this->data['Rating']['reviewid'] = $this->data['Review']['id'];
         $this->data['Rating']['ratings'] = implode(',', $this->data['Rating']['ratings']);
         # Save rating fields
         appLogMessage('*******Save standard rating fields', 'database');
         if ($isNew || !$isNew && $ratings_col_empty) {
             $save = $this->insert('#__jreviews_ratings', 'Rating', $this->data, 'reviewid');
         } else {
             $save = $this->update('#__jreviews_ratings', 'Rating', $this->data, 'reviewid');
         }
         if (!$save) {
             appLogMessage('*******There was a problem saving the ratings', 'database');
             return false;
         }
     }
     # if ( $criteria['Criteria']['state'] == 1 )
     // save listing totals
     if (!$this->saveListingTotals($this->data['Review']['pid'], $this->data['Review']['mode'], $weights)) {
         return false;
     }
     # Save custom fields
     appLogMessage('*******Save review custom fields', 'database');
     $this->data['Field']['Review']['reviewid'] = $this->data['Review']['id'];
     App::import('Model', 'field', 'jreviews');
     $FieldModel = ClassRegistry::getClass('FieldModel');
     if (count($this->data['Field']['Review']) > 1 && !$FieldModel->save($this->data, 'review', $isNew, $this->valid_fields)) {
         return false;
     }
 }
Exemple #21
0
 function onDisplay($field, $showImage = true, $value = false, $return = false)
 {
     if (empty($field)) {
         return null;
     }
     $values = array();
     $option = $value ? 'value' : 'text';
     foreach ($field[$option] as $key => $text) {
         switch ($field['type']) {
             case 'date':
                 $format = Sanitize::getString($field['properties'], 'date_format');
                 $text = $this->Time->nice($text, $format, 0);
                 break;
             case 'integer':
                 $text = Sanitize::getInt($field['properties'], 'curr_format') ? number_format($text) : $text;
                 break;
             case 'decimal':
                 $text = Sanitize::getInt($field['properties'], 'curr_format') ? number_format($text, 2, __l('DECIMAL_SEPARATOR', true), __l('THOUSANDS_SEPARATOR', true)) : round($text, 2);
                 break;
             case 'email':
                 break;
             case 'website':
                 $text = S2ampReplace($text);
                 break;
             case 'code':
                 $text = stripslashes($text);
                 break;
             case 'textarea':
             case 'text':
                 if (!Sanitize::getBool($field['properties'], 'allow_html')) {
                     $text = nl2br($text);
                 }
                 break;
             case 'selectmultiple':
             case 'checkboxes':
             case 'select':
             case 'radiobuttons':
                 $imgSrc = '';
                 if ($showImage && isset($field['image'][$key]) && $field['image'][$key] != '') {
                     if ($imgSrc = $this->locateThemeFile('theme_images', cmsFramework::language() . '.' . $field['image'][$key], '', true)) {
                         $imgSrc = pathToUrl($imgSrc);
                     } elseif ($imgSrc = $this->locateThemeFile('theme_images', $field['image'][$key], '', true)) {
                         $imgSrc = pathToUrl($imgSrc);
                     }
                     if ($imgSrc != '') {
                         $text = '<img src="' . $imgSrc . '" title="' . $text . '" alt="' . $text . '" border="0" />';
                     }
                 }
                 break;
             default:
                 $text = stripslashes($text);
                 break;
         }
         $values[] = $text;
         $this->output[] = $text;
     }
     if ($return) {
         return $values;
     }
 }
 function _save()
 {
     /*******************************************************************
      * This method is processed inside an iframe
      * To access any of the DOM elements via jQuery it's necessary to prepend
      * all jQuery calls with $parentFrame (i.e. $parentFrame.jQuery)
      ********************************************************************/
     $this->autoRender = false;
     $this->autoLayout = false;
     $response = array();
     $parentFrame = 'window.parent';
     $validation = '';
     $listing_id = Sanitize::getInt($this->data['Listing'], 'id', 0);
     $isNew = $this->Listing->isNew = $listing_id == 0 ? true : false;
     $this->data['email'] = Sanitize::getString($this->data, 'email');
     $this->data['name'] = Sanitize::getString($this->data, 'name');
     $this->data['categoryid_hidden'] = Sanitize::getInt($this->data['Listing'], 'categoryid_hidden');
     $cat_id = Sanitize::getVar($this->data['Listing'], 'catid');
     $this->data['Listing']['catid'] = is_array($cat_id) ? (int) array_pop(array_filter($cat_id)) : (int) $cat_id;
     /*J16*/
     $this->data['Listing']['title'] = Sanitize::getString($this->data['Listing'], 'title', '');
     $this->data['Listing']['created_by_alias'] = Sanitize::getString($this->data, 'name', '');
     if ($this->cmsVersion == CMS_JOOMLA15) {
         $this->data['sectionid_hidden'] = Sanitize::getInt($this->data['Listing'], 'sectionid_hidden');
         $this->data['Listing']['sectionid'] = Sanitize::getInt($this->data['Listing'], 'sectionid');
     } else {
         $this->data['Listing']['language'] = '*';
         $this->data['Listing']['access'] = 1;
     }
     $category_id = $this->data['Listing']['catid'] ? $this->data['Listing']['catid'] : $this->data['categoryid_hidden'];
     # Get criteria info
     $criteria = $this->Criteria->findRow(array('conditions' => array('Criteria.id = 
             (SELECT criteriaid FROM #__jreviews_categories WHERE id = ' . (int) $category_id . ' AND `option` = "com_content")
         ')));
     if (!$criteria) {
         $validation = __t("The category selected is invalid.", true, true);
         $response[] = "{$parentFrame}.jQuery('#jr_listingFormValidation').html('{$validation}');";
         $response[] = "{$parentFrame}.jQuery('.button').removeAttr('disabled');";
         $response[] = "{$parentFrame}.jQuery('.jr_loadingSmall').hide();";
         return $this->makeJS($response);
     }
     $this->data['Criteria']['id'] = $criteria['Criteria']['criteria_id'];
     # Override global configuration
     isset($criteria['ListingType']) and $this->Config->override($criteria['ListingType']['config']);
     # Perform access checks
     if ($isNew && !$this->Access->canAddListing()) {
         return $this->makeJS("{$parentFrame}.s2Alert('" . __t("You are not allowed to submit listings in this category.", true, true) . "')");
     } elseif (!$isNew) {
         $query = "SELECT created_by FROM #__content WHERE id = " . $listing_id;
         $this->_db->setQuery($query);
         $listing_owner = $this->_db->loadResult();
         if (!$this->Access->canEditListing($listing_owner)) {
             return $this->makeJS("{$parentFrame}.s2Alert('" . s2Messages::accessDenied() . "')");
         }
     }
     # 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', 'notifications');
     $this->__initComponents();
     if ($this->invalidToken == true) {
         return $this->makeJS("{$parentFrame}.s2Alert('" . s2Messages::invalidToken() . "')");
     }
     # Override configuration
     $category = $this->Category->findRow(array('conditions' => array('Category.id = ' . $this->data['Listing']['catid'])));
     $this->Config->override($category['ListingType']['config']);
     if ($this->Access->loadWysiwygEditor()) {
         $this->data['Listing']['introtext'] = Sanitize::stripScripts(Sanitize::stripWhitespace(Sanitize::getVar($this->data['__raw']['Listing'], 'introtext')));
         $this->data['Listing']['fulltext'] = Sanitize::stripScripts(Sanitize::stripWhitespace(Sanitize::getVar($this->data['__raw']['Listing'], 'fulltext')));
         $this->data['Listing']['introtext'] = html_entity_decode($this->data['Listing']['introtext'], ENT_QUOTES, cmsFramework::getCharset());
         $this->data['Listing']['fulltext'] = html_entity_decode($this->data['Listing']['fulltext'], ENT_QUOTES, cmsFramework::getCharset());
     } else {
         $this->data['Listing']['introtext'] = Sanitize::stripAll($this->data['Listing'], 'introtext', '');
         if (isset($this->data['Listing']['fulltext'])) {
             $this->data['Listing']['fulltext'] = Sanitize::stripAll($this->data['Listing'], 'fulltext', '');
         } else {
             $this->data['Listing']['fulltext'] = '';
         }
     }
     $this->data['Listing']['introtext'] = str_replace('<br>', '<br />', $this->data['Listing']['introtext']);
     $this->data['Listing']['fulltext'] = str_replace('<br>', '<br />', $this->data['Listing']['fulltext']);
     if ($this->Access->canAddMeta()) {
         $this->data['Listing']['metadesc'] = Sanitize::getString($this->data['Listing'], 'metadesc');
         $this->data['Listing']['metakey'] = Sanitize::getString($this->data['Listing'], 'metakey');
     }
     // Title alias handling
     $slug = '';
     $alias = Sanitize::getString($this->data['Listing'], 'alias');
     if ($isNew && $alias == '') {
         $slug = S2Router::sefUrlEncode($this->data['Listing']['title']);
         if (trim(str_replace('-', '', $slug)) == '') {
             $slug = date("Y-m-d-H-i-s");
         }
     } elseif ($alias != '') {
         // Alias filled in so we convert it to a valid alias
         $slug = S2Router::sefUrlEncode($alias);
         if (trim(str_replace('-', '', $slug)) == '') {
             $slug = date("Y-m-d-H-i-s");
         }
     }
     $slug != '' and $this->data['Listing']['alias'] = $slug;
     # Check for duplicates
     switch ($this->Config->content_title_duplicates) {
         case 'category':
             // Checks for duplicates in the same category
             $query = "\r\n                        SELECT \r\n                            count(*) \r\n                        FROM \r\n                            #__content AS Listing WHERE Listing.title = " . $this->_db->Quote($this->data['Listing']['title']) . "\r\n                            AND Listing.state >= 0 \r\n                            AND Listing.catid = " . $this->data['Listing']['catid'] . (!$isNew ? " AND Listing.id <> " . $listing_id : '');
             $this->_db->setQuery($query);
             $titleExists = $this->_db->loadResult();
             break;
         case 'no':
             // Checks for duplicates all over the place
             $query = "\r\n                        SELECT \r\n                            count(*) \r\n                        FROM \r\n                            #__content AS Listing\r\n                        WHERE \r\n                            Listing.title = " . $this->_db->Quote($this->data['Listing']['title']) . "\r\n                           AND Listing.state >= 0\r\n                           " . (!$isNew ? " AND Listing.id <> " . $listing_id : '');
             $this->_db->setQuery($query);
             $titleExists = $this->_db->loadResult();
             break;
         case 'yes':
             // Duplicates are allowed, no checking necessary
             $titleExists = false;
             break;
     }
     if ($titleExists && $this->data['Listing']['title'] != '') {
         // if listing exists
         $validation = '<span>' . __t("A listing with that title already exists.", true, true) . "</span>";
         $response[] = "{$parentFrame}.jQuery('#jr_listingFormValidation').html('{$validation}');";
         $response[] = "{$parentFrame}.jQuery('.button').removeAttr('disabled');";
         $response[] = "{$parentFrame}.jQuery('.jr_loadingSmall').hide();";
         return $this->makeJS($response);
     }
     // Review form display check logic used several times below
     $revFormSetting = $this->Config->content_show_reviewform;
     if ($revFormSetting == 'noteditors' && !$this->Config->author_review) {
         $revFormSetting = 'all';
     }
     $revFormEnabled = !isset($this->data['review_optional']) && $this->Access->canAddReview() && $isNew && ($revFormSetting == 'all' && ($this->Config->author_review || $this->Config->user_reviews) || $revFormSetting == 'authors' && $this->Access->isJreviewsEditor($this->_user->id) || $revFormSetting == 'noteditors' && !$this->Access->isJreviewsEditor($this->_user->id));
     // Validation of content default input fields
     if ($this->cmsVersion == CMS_JOOMLA15) {
         if (!$this->data['Listing']['catid'] || !$this->data['Listing']['sectionid']) {
             $this->Listing->validateSetError("sec_cat", __t("You need to select both a section and a category.", true));
         }
     } else {
         !$this->data['Listing']['catid'] and $this->Listing->validateSetError("sec_cat", __t("You need to select a category.", true));
     }
     // Validate only if it's a new listing
     if ($isNew) {
         if (!$this->_user->id) {
             $this->Listing->validateInput($this->data['name'], "name", "text", __t("You must fill in your name.", true), $this->Config->content_name == "required" ? 1 : 0);
             $this->Listing->validateInput($this->data['email'], "email", "email", __t("You must fill in a valid email address.", true), $this->Config->content_email == "required" ? 1 : 0);
             $this->data['name'] = Sanitize::getString($this->data, 'name', '');
             $this->data['email'] = Sanitize::getString($this->data, 'email', '');
         } else {
             $this->data['name'] = $this->_user->name;
             $this->data['email'] = $this->_user->email;
         }
     }
     $this->Listing->validateInput($this->data['Listing']['title'], "title", "text", __t("You must fill in a title for the new listing.", true, true), 1);
     # Validate listing custom fields
     $listing_valid_fields =& $this->Field->validate($this->data, 'listing', $this->Access);
     $this->Listing->validateErrors = array_merge($this->Listing->validateErrors, $this->Field->validateErrors);
     $this->Listing->validateInput($this->data['Listing']['introtext'], "introtext", "text", __t("You must fill in a summary for the new listing.", true, true), $this->Config->content_summary == "required" ? 1 : 0);
     $this->Listing->validateInput($this->data['Listing']['fulltext'], "fulltext", "text", __t("You must fill in a description for the new listing.", true, true), $this->Config->content_description == "required" ? 1 : 0);
     # Validate review custom fields
     if ($revFormEnabled && $criteria['Criteria']['state']) {
         // Review inputs
         $this->data['Review']['userid'] = $this->_user->id;
         $this->data['Review']['email'] = $this->data['email'];
         $this->data['Review']['name'] = $this->data['name'];
         $this->data['Review']['username'] = Sanitize::getString($this->data, 'name', '');
         $this->data['Review']['title'] = Sanitize::getString($this->data['Review'], 'title');
         $this->data['Review']['location'] = Sanitize::getString($this->data['Review'], 'location');
         // deprecated
         $this->data['Review']['comments'] = Sanitize::getString($this->data['Review'], 'comments');
         // Review standard fields
         $this->Listing->validateInput($this->data['Review']['title'], "rev_title", "text", __t("You must fill in a title for the review.", true, true), $this->Config->reviewform_title == 'required' ? true : false);
         if ($criteria['Criteria']['state'] == 1) {
             $criteria_qty = $criteria['Criteria']['quantity'];
             $ratingErr = 0;
             if (!isset($this->data['Rating'])) {
                 $ratingErr = $criteria_qty;
             } else {
                 for ($i = 0; $i < $criteria_qty; $i++) {
                     if (!isset($this->data['Rating']['ratings'][$i]) || (empty($this->data['Rating']['ratings'][$i]) || $this->data['Rating']['ratings'][$i] == 'undefined' || (double) $this->data['Rating']['ratings'][$i] > $this->Config->rating_scale)) {
                         $ratingErr++;
                     }
                 }
             }
             $this->Listing->validateInput('', "rating", "text", sprintf(__t("You are missing a rating in %s criteria.", true, true), $ratingErr), $ratingErr);
         }
         // Review custom fields
         $this->Field->validateErrors = array();
         // Clear any previous validation errors
         $review_valid_fields = $this->Field->validate($this->data, 'review', $this->Access);
         $this->Listing->validateErrors = array_merge($this->Listing->validateErrors, $this->Field->validateErrors);
         $this->Listing->validateInput($this->data['Review']['comments'], "comments", "text", __t("You must fill in your comment.", true, true), $this->Config->reviewform_comment == 'required' ? true : false);
     }
     // if ($revFormEnabled && $criteria['Criteria']['state'])
     # Validate image fields
     $this->Uploads->validateImages();
     # Validate Captcha security code
     if ($isNew && $this->Access->showCaptcha()) {
         if (!isset($this->data['Captcha']['code'])) {
             $this->Listing->validateSetError("code", __t("The security code you entered was invalid.", true, true));
         } elseif ($this->data['Captcha']['code'] == '') {
             $this->Listing->validateInput($this->data['Captcha']['code'], "code", "text", __t("You must fill in the security code.", true), 1);
         } else {
             if (!$this->Captcha->checkCode($this->data['Captcha']['code'], $this->ipaddress)) {
                 $this->Listing->validateSetError("code", __t("The security code you entered was invalid.", true, true));
             }
         }
     }
     # Get all validation messages
     $validation = $this->Listing->validateGetError() . $this->Uploads->getMsg();
     # Validation failed
     if ($validation != '') {
         $response[] = "var parentForm = {$parentFrame}.jQuery('#jr_listingForm');";
         $response[] = "{$parentFrame}.jQuery('#jr_listingFormValidation').html('{$validation}');";
         $response[] = "parentForm.find('.button').removeAttr('disabled');";
         // Transform textareas into wysiwyg editors
         if ($this->Access->loadWysiwygEditor()) {
             App::import('Helper', 'Editor', 'jreviews');
             $Editor = new EditorHelper();
             $response[] = $parentFrame . '.' . $Editor->transform(true);
         }
         // Replace captcha with new instance
         if ($this->Access->in_groups($this->Config->security_image)) {
             $captcha = $this->Captcha->displayCode();
             $response[] = "{$parentFrame}.jQuery('#captcha').attr('src','{$captcha['src']}');";
             $response[] = "{$parentFrame}.jQuery('#jr_captchaCode').val('');";
         }
         $response[] = "parentForm.find('.jr_loadingSmall').hide();";
         return $this->makeJS($response);
         // Can't use ajaxResponse b/c we are in an iframe
     }
     # Validation passed, continue...
     if ($isNew) {
         $this->data['Listing']['created'] = _CURRENT_SERVER_TIME;
         //gmdate('Y-m-d H:i:s');
         $this->data['Listing']['publish_up'] = _CURRENT_SERVER_TIME;
         //gmdate('Y-m-d H:i:s');
         $this->data['Listing']['created_by'] = $this->_user->id;
         $this->data['Listing']['publish_down'] = NULL_DATE;
         $this->data['Field']['Listing']['email'] = $this->data['email'];
         // If visitor, assign name field to content Alias
         if (!$this->_user->id) {
             $this->data['Listing']['created_by_alias'] = $this->data['name'];
         }
         // Check moderation settings
         $this->data['Listing']['state'] = (int) (!$this->Access->moderateListing());
         // If listing moderation is enabled, then the review is also moderated
         if (!$this->data['Listing']['state']) {
             $this->Config->moderation_reviews = $this->Config->moderation_editor_reviews = $this->Config->moderation_item;
         }
     } else {
         if ($this->Config->moderation_item_edit) {
             $this->data['Listing']['state'] = (int) (!$this->Access->moderateListing());
         }
         $this->data['Listing']['modified'] = _CURRENT_SERVER_TIME;
         //gmdate('Y-m-d H:i:s');
         $this->data['Listing']['modified_by'] = $this->_user->id;
         $query = 'SELECT images FROM #__content WHERE id = ' . $this->data['Listing']['id'];
         $this->_db->setQuery($query);
         $this->data['Listing']['images'] = $this->_db->loadResult();
         // Check total number of images
         if (!$this->Uploads->checkImageCount($this->data['Listing']['images'])) {
             $validation .= '<span>' . sprintf(__t("The total number of images is limited to %s", true, true), $this->Config->content_images) . '</span><br />';
             $response[] = "{$parentFrame}.jQuery('#jr_listingFormValidation').html('{$validation}');";
             $response[] = "{$parentFrame}.jQuery('.button').removeAttr('disabled');";
             $response[] = "{$parentFrame}.jQuery('.jr_loadingSmall').hide();";
             return $this->makeJS($response);
         }
     }
     // Process images and update data array
     if ($this->Uploads->success) {
         $imageUploadPath = PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS;
         $this->Uploads->uploadImages($this->data['Listing']['id'], $imageUploadPath);
         if ($isNew) {
             // New item
             $currImages = $this->Uploads->images;
         } elseif ($this->data['Listing']['images'] != '') {
             // Editing and there are existing images
             $currImages = array_merge(explode("\n", $this->data['Listing']['images']), $this->Uploads->images);
         } else {
             // Editing and there are no existing images
             $currImages = $this->Uploads->images;
         }
         $this->data['Listing']['images'] = implode("\n", $currImages);
     }
     # Save listing
     $savedListing = $this->Listing->store($this->data);
     $listing_id = $this->data['Listing']['id'];
     if (!$savedListing) {
         $validation .= __t("The was a problem saving the listing", true, true);
     }
     // Error on listing save
     if ($validation != '') {
         $response[] = "{$parentFrame}.jQuery('#jr_listingFormValidation').html('{$validation}');";
         $response[] = "{$parentFrame}.jQuery('.button').removeAttr('disabled');";
         $response[] = "{$parentFrame}.jQuery('.jr_loadingSmall').hide();";
         return $this->makeJS($response);
     }
     # Save listing custom fields
     $this->data['Field']['Listing']['contentid'] = $this->data['Listing']['id'];
     $this->Field->save($this->data, 'listing', $isNew, $listing_valid_fields);
     # Begin insert review in table
     if ($revFormEnabled && $criteria['Criteria']['state']) {
         // Get reviewer type, for now editor reviews don't work in Everywhere components
         $this->data['Review']['author'] = (int) $this->Access->isJreviewsEditor($this->_user->id);
         $this->data['Review']['mode'] = 'com_content';
         $this->data['Review']['pid'] = (int) $this->data['Listing']['id'];
         // Force plugin loading on Review model
         $this->_initPlugins('Review');
         $this->Review->isNew = true;
         $savedReview = $this->Review->save($this->data, $this->Access, $review_valid_fields);
     }
     # Before render callback
     if ($isNew && isset($this->Listing->plgBeforeRenderListingSaveTrigger)) {
         $plgBeforeRenderListingSave = $this->Listing->plgBeforeRenderListingSave();
         switch ($plgBeforeRenderListingSave) {
             case '0':
                 $this->data['Listing']['state'] = 1;
                 break;
             case '1':
                 $this->data['Listing']['state'] = 0;
                 break;
             case '':
                 break;
             default:
                 return $plgBeforeRenderListingSave;
                 break;
         }
     }
     # Moderation disabled
     if (!isset($this->data['Listing']['state']) || $this->data['Listing']['state']) {
         $fields = array('Criteria.criteria AS `Criteria.criteria`', 'Criteria.tooltips AS `Criteria.tooltips`');
         $listing = $this->Listing->findRow(array('fields' => $fields, 'conditions' => array('Listing.id = ' . $listing_id)), array('afterFind'));
         # Facebook wall integration
         $fb_checkbox = Sanitize::getBool($this->data, 'fb_publish');
         $facebook_integration = Sanitize::getBool($this->Config, 'facebook_enable') && Sanitize::getBool($this->Config, 'facebook_listings') && $fb_checkbox;
         $token = cmsFramework::getCustomToken($listing_id);
         $facebook_integration and $response[] = $parentFrame . '.jQuery.get(' . $parentFrame . '.s2AjaxUri+' . $parentFrame . '.jreviews.ajax_params()+\'&url=facebook/_postListing/id:' . $listing_id . '&' . $token . '=1\');
             ';
         $url = cmsFramework::route($listing['Listing']['url']);
         $update_text = $isNew ? __t("Thank you for your submission.", true, true) : __t("The listing was successfully saved.", true, true);
         //JOEYG CODE
         //THE FOLLOWING GETS THE LISTING TYPE FROM THE DB FOR THE NEWLY SAVED LISTING
         //IF THE TYPE IS BUSINESS PROFILE OR PROJECT LISTING THEN DISPLAY THE after_submit.thtml file
         //ELSE DISPLAY NORMAL MESSAGE
         //IF WE ONLY WANT TO ADD THE after_submit.thtml if the listing is new then add
         if ($isNew) {
             $query = "SELECT `listing_type` FROM `jos_vpbd_content_criteria` WHERE `jos_vpbd_content_criteria`.`listing_id` = " . $this->data['Listing']['id'];
             $this->_db->setQuery($query);
             $jg_listing_type = $this->_db->loadResult();
             if ($jg_listing_type == 2 || $jg_listing_type == 7) {
                 $update_html = $this->render('listings', 'after_submit');
             } else {
                 $update_html = "<a href=\"{$url}\">" . __t("Click here to view your listing", true) . "</a>";
             }
             //ends if/else
         } else {
             //not new
             $update_html = "<a href=\"{$url}\">" . __t("Click here to view your listing", true) . "</a>";
         }
         //ends if($isNew)
         //ENDS JOEYG ALTER CODE
         $jsonObject = json_encode(compact('target_id', 'update_text', 'update_html'));
         $response[] = '
                 var $parentForm = ' . $parentFrame . '.jQuery(\'#jr_listingForm\');
                 $parentForm.scrollTo({duration:400,offset:-100});
                 $parentForm.s2ShowUpdate(' . $jsonObject . ');                                                       
             ';
         return $this->makeJS($response);
     }
     # Moderation enabled
     $update_text = __t("Thank you for your submission. It will be published once it is verified.", true);
     $update_html = '<div id=\\"s2Msgjr_listingForm\\" class=\\"jr_postUpdate\\">' . $update_text . '</div>';
     $response[] = '
         var $parentForm = ' . $parentFrame . '.jQuery(\'#jr_listingForm\');
         $parentForm.scrollTo({duration:400,offset:-100},function(){
             $parentForm.fadeOut(250,function(){$parentForm.html("' . $update_html . '").show();});
         });
     ';
     return $this->makeJS($response);
 }
 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');
 }
Exemple #24
0
    function ListingsDetail()
    {
        $assets = array('js' => array('jreviews', 'jreviews.compare', 'jquery', 'jq.ui.core', 'jreviews.fields', 'jq.ui.rating', 'jq.jreviews.plugins', 'jq.tooltip', 'jq.json', 'jq.jsoncookie'), 'css' => array('theme', 'theme.detail', 'theme.form', 'paginator', 'jq.ui.core'));
        $facebook_id = Sanitize::getString($this->Config, 'facebook_appid');
        $facebook_opengraph = Sanitize::getBool($this->Config, 'facebook_opengraph', true);
        $facebook_xfbml = $facebook_id && $facebook_opengraph;
        $facebook_post = $facebook_id && $this->Access->canAddReview() && !$this->Access->moderateReview() && $this->Config->facebook_enable && $this->Config->facebook_reviews;
        ?>
        <script type="text/javascript">    
        /* <![CDATA[ */
        jQuery(document).ready(function() 
        {         
            jreviewsCompare.set({
                'numberOfListingsPerPage':<?php 
        echo Sanitize::getInt($this->Config, 'list_compare_columns', 3);
        ?>
,
                'maxNumberOfListings' : 15,
                'compareURL':'<?php 
        echo cmsFramework::route('index.php?option=com_jreviews&url=categories/compare/type:type_id/');
        ?>
'
            });
            jreviewsCompare.initCompareDashboard();
            jreviewsCompare.initListingsSelection();            

            <?php 
        if ($facebook_xfbml || $facebook_post) {
            ?>
                               
            if(!jQuery('#fb-root').length) jQuery("body").append('<div id="fb-root"></div>');
            jreviews.facebook.init({
                'appid':'<?php 
            echo $this->Config->facebook_appid;
            ?>
'
            });
            <?php 
        }
        ?>
                   
        });       
        /* ]]> */
        </script> 
        <?php 
        $this->send($assets);
    }
 function _save()
 {
     $this->autoRender = false;
     $this->autoLayout = false;
     $this->Discussion->isNew = true;
     $response = array();
     $parent_id = Sanitize::getInt($this->data['Discussion'], 'parent_post_id');
     $isNew = Sanitize::getBool($this->data['Discussion'], 'discussion_id');
     # 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());
     }
     if (!$this->Config->review_discussions || !$this->Access->canAddPost()) {
         // Server side validation
         return $this->ajaxError(__t("You are not allowed to submit comments.", true, true));
     }
     # Validate input fields
     $this->Discussion->validateInput(Sanitize::getString($this->data['Discussion'], 'name'), "name", "text", __t("You must fill in your name.", true), !$this->_user->id && ($this->Config->discussform_name == 'required' ? true : false));
     $this->Discussion->validateInput(Sanitize::getString($this->data['Discussion'], 'email'), "email", "email", __t("You must fill in a valid email address.", true), ($this->Config->discussform_email == 'required' ? true : false) && !$this->_user->id && $isNew);
     $this->Discussion->validateInput($this->data['Discussion']['text'], "text", "text", __t("You must fill in your comment.", true), true);
     # Validate security code
     if ($this->Access->showCaptcha()) {
         if (!isset($this->data['Captcha']['code'])) {
             $this->Discussion->validateSetError("code", __t("The security code you entered was invalid.", true));
         } elseif ($this->data['Captcha']['code'] == '') {
             $this->Discussion->validateInput($this->data['Captcha']['code'], "code", "text", __t("You must fill in the security code.", true), 1);
         } else {
             if (!$this->Captcha->checkCode($this->data['Captcha']['code'], $this->ipaddress)) {
                 $this->Discussion->validateSetError("code", __t("The security code you entered was invalid.", true));
             }
         }
     }
     $validation_text = implode('<br />', $this->Discussion->validateGetErrorArray());
     if ($validation_text != '') {
         $response[] = "jQuery('#jr_postCommentSubmit{$parent_id}').removeAttr('disabled');";
         $response[] = "jQuery('#jr_postCommentCancel{$parent_id}').removeAttr('disabled');";
         // Replace captcha with new instance
         $captcha = $this->Captcha->displayCode();
         $response[] = "jQuery('.jr_captcha').find('img').attr('src','{$captcha['src']}');";
         $response[] = "jQuery('.jr_captcha_code').val('');";
         return $this->ajaxValidation($validation_text, $response);
     }
     $this->data['Discussion']['user_id'] = $this->_user->id;
     $this->data['Discussion']['ipaddress'] = $this->ipaddress;
     if ($this->_user->id) {
         $this->data['Discussion']['name'] = $this->_user->name;
         $this->data['Discussion']['username'] = $this->_user->username;
         $this->data['Discussion']['email'] = $this->_user->email;
     } else {
         $this->data['Discussion']['username'] = $this->data['Discussion']['name'];
     }
     $this->data['Discussion']['created'] = date('Y-m-d H:i:s');
     $this->data['Discussion']['approved'] = (int) (!$this->Access->moderatePost());
     if ($this->Discussion->store($this->data)) {
         if (!$this->data['Discussion']['approved']) {
             $submit_text = __t("Thank you for your submission. It will be published once it is verified.", true, true);
             return $this->ajaxUpdatePage('jr_postCommentForm' . $parent_id, $submit_text);
         }
         // Query post to get full info for instant refresh
         $discussion = $this->Discussion->findRow(array('conditions' => array('Discussion.type = "review"', 'Discussion.discussion_id = ' . $this->data['Discussion']['discussion_id'])));
         $this->set(array('Access' => $this->Access, 'User' => $this->_user, 'post' => $discussion));
         $update_text = __t("Thank you for your submission.", true, true);
         $update_html = $this->render('discussions', 'post');
         $target_id_after = 'jr_post' . $parent_id;
         $response[] = 'jreviews.discussion.parentCommentPopOver();';
         return $this->ajaxUpdatePage('jr_postCommentFormOuter' . $parent_id, $update_text, $update_html, compact('target_id_after', 'response'));
     }
 }
 function listings()
 {
     // Initialize variables
     $id = Sanitize::getInt($this->params, 'id');
     $option = Sanitize::getString($this->params, 'option');
     $view = Sanitize::getString($this->params, 'view');
     $task = Sanitize::getString($this->params, 'task');
     $menu_id = Sanitize::getString($this->params, 'Itemid');
     // Read params
     $cat_id = '';
     $criteria_ids = '';
     $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;
     $fishingmap = 0;
     $this->set('listing_id', $id);
     $extracoords = array();
     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');
         $custom_fields = Sanitize::getString($this->params['module'], 'custom_fields', '');
         $custom_fields = $custom_fields != '' ? explode(',', str_replace(' ', '', $custom_fields)) : array();
         $limit_results = Sanitize::getInt($this->params['module'], 'limit_results');
         $mode = Sanitize::getInt($this->params['module'], 'mode', 0);
         /**
          * 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;
         }
         // Added for Hooked
         $extracoords = $this->params['module']['extracoords'];
         //$extracoords = "";
         $fishingmap = Sanitize::getInt($this->params['module'], 'fishingmap', 0);
     }
     $in_detail_view = $id > 0 && ('article' == $view || 'view' == $task) && 'com_content' == $option;
     $detail_view = $this->params['module']['detail_view'] = $detail_view && $in_detail_view;
     # Custom WHERE
     if ($custom_where) {
         $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') {
         // Only works for core articles
         switch ($option) {
             case 'com_jreviews':
                 # Get url params for current controller/action
                 $url = Sanitize::getString($this->passedArgs, 'url');
                 $route['url']['url'] = $url;
                 $route = S2Router::parse($route);
                 //                    $route = $route['url'];
                 $dir_id = Sanitize::getString($route, 'dir');
                 $section_id = Sanitize::getString($route, 'section');
                 $cat_id = Sanitize::getString($route, 'cat');
                 $criteria_ids = Sanitize::getString($route, 'criteria');
                 if ($cat_id != '') {
                     $category_ids = $this->makeParamsUsable($cat_id);
                     $category_ids = explode(",", $category_ids);
                     $this->cleanArray($category_ids);
                     $cat_id = implode(",", $category_ids);
                 } elseif ($section_id != '') {
                     $cat_id = $this->sectionToCat($section_id);
                 } elseif ($criteria_ids != '') {
                     // check criteriaids {
                     $criteriaids_url = $this->makeParamsUsable($criteria_ids);
                     $cat_id = $this->criteriaToCat($criteria_ids);
                 } else {
                     //Discover the params from the menu_id
                     $params = $this->Menu->getMenuParams($menu_id);
                     $dir_id = Sanitize::getString($params, 'dirid');
                     $cat_id = Sanitize::getString($params, 'catid');
                     $section_id = Sanitize::getString($params, 'sectionid');
                 }
                 break;
             case 'com_content':
                 if ('article' == $view || 'view' == $task) {
                     $sql = "SELECT catid FROM #__content WHERE id = " . $id;
                     $this->_db->setQuery($sql);
                     $cat_id = $this->_db->loadResult();
                 } elseif ($view == "section") {
                     $cat_id = $this->sectionToCat($id);
                 } elseif ($view == "category") {
                     $cat_id = $id;
                 }
                 break;
             default:
                 //                    $cat_id = null; // Catid not detected because the page is neither content nor jreviews
                 break;
         }
     }
     $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`', '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`", 'JreviewsCategory.marker_icon AS `Geomaps.icon`');
     if ($fishingmap) {
         $this->Listing->fields[] = 'GROUP_CONCAT(Related.id2) AS `Listing.relations`';
     }
     // 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) && $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}";
             // Added for Hooked
             if ($extracoords) {
                 $squareArea = "((" . $squareArea . ")";
                 foreach ($extracoords as $extra) {
                     $e_lat = $extra->y;
                     $e_lon = $extra->x;
                     $lon_range = $radius / abs(cos($e_lat * pi() / 180) * $degreeDistance);
                     $min_lat = $e_lat - $lat_range;
                     $max_lat = $e_lat + $lat_range;
                     $min_lon = $e_lon - $lon_range;
                     $max_lon = $e_lon + $lon_range;
                     $squareArea .= " OR (`Field`.{$this->jr_lat} BETWEEN {$min_lat} AND {$max_lat} AND `Field`.{$this->jr_lon} BETWEEN {$min_lon} AND {$max_lon})";
                 }
                 $squareArea .= ")";
             }
             $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) {
             $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", "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_directories AS Directory ON JreviewsCategory.dirid = Directory.id");
     if ($fishingmap) {
         $this->Listing->joins[] = "LEFT JOIN #__relate_listings AS Related ON Related.id1 = Listing.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 ($dir_id) {
         $conditions[] = 'JreviewsCategory.dirid IN (' . $dir_id . ')';
     }
     if ($section_id) {
         $conditions[] = 'Listing.sectionid IN (' . $section_id . ')';
     }
     if ($cat_id) {
         $conditions[] = 'Listing.catid IN (' . $cat_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[] = 'Listing.state = 1';
     if ($fishingmap) {
         $this->Listing->group = array('Listing.id');
     }
     // 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)));
     $fields = $this->Field->getFields($custom_fields);
     $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');
 }
Exemple #27
0
    function relatedListingsJS($listing)
    {
        # Detail page widgets
        $key = 0;
        $listingtype = Sanitize::getInt($listing['Criteria'], 'criteria_id');
        $listing_id = Sanitize::getInt($listing['Listing'], 'listing_id');
        $listing_title = Sanitize::getString($listing['Listing'], 'title');
        $ajax_init = true;
        $target_id = $target_class = '';
        // Process related listings
        $related_listings = Sanitize::getVar($listing['ListingType']['config'], 'relatedlistings', array());
        $related_listings = array_filter($related_listings);
        $created_by = Sanitize::getVar($listing['User'], 'user_id');
        $field_pairs = $listing['Field']['pairs'];
        $type = 'relatedlistings';
        // Created an array of tab ids => tab indices
        ?>
        <script type="text/javascript">    
        /* <![CDATA[ */
        var jrTabArray = {};
        jQuery(document).ready(function() 
        {         
            jQuery('.jr_tabs').find('li>a').each(function(i,t) {
                var tabId = jQuery(t).attr('href');
                jrTabArray[tabId] = jQuery(t).parent('li');
            });
        });
        /* ]]> */
        </script>
        <?php 
        foreach ($related_listings as $key => $related_listing) {
            if (!Sanitize::getInt($related_listing, 'enable', 0)) {
                continue;
            }
            $module_id = 10000 + $listing_id + $key;
            $target_id = Sanitize::getString($related_listing, 'target_id', 'jrRelatedListings');
            $target_class = Sanitize::getString($related_listing, 'target_class');
            $moduleParams = compact('module_id', 'ajax_init', 'listing_id', 'type', 'key');
            extract($related_listing);
            $title = str_ireplace('{title}', $listing_title, __t(Sanitize::getString($related_listing, 'title'), true, true));
            $title = htmlspecialchars($title, ENT_QUOTES, 'utf-8');
            $targetElement = $target_class ? $target_class : $target_id;
            ?>
            <script type="text/javascript">    
            /* <![CDATA[ */
            jQuery(document).ready(function() 
            {                    
                jreviews.dispatch({'controller':'module_listings','action':'index',
                    'type':'json',
                    'data':<?php 
            echo json_encode($moduleParams);
            ?>
,
                    'onComplete':function(res){     
                        var $<?php 
            echo $targetElement;
            ?>
 = <?php 
            if ($target_class) {
                ?>
jQuery('.<?php 
                echo $target_class;
                ?>
');<?php 
            } else {
                ?>
jQuery('#<?php 
                echo $target_id;
                ?>
');<?php 
            }
            ?>
                        if(res.response != '') {  
                            var $widget = jQuery('<div id="<?php 
            echo $targetElement;
            ?>
Widget<?php 
            echo $key;
            ?>
"></div>').addClass('jrWidget')
                                    <?php 
            if ($title != '') {
                ?>
.append('<h4><?php 
                echo $title;
                ?>
</h4>')<?php 
            }
            ?>
                                    .append(res.response);
                            $<?php 
            echo $targetElement;
            ?>
.append($widget);

                            var array = [0,1,2,3,4];
                            for(var i=0; i < array.length; i++) { array[i] = jQuery('#<?php 
            echo $targetElement;
            ?>
Widget'+ array[i]); }    
                            $<?php 
            echo $targetElement;
            ?>
.html();  
                            for(var i=0; i < array.length; i++) { $<?php 
            echo $targetElement;
            ?>
.append(array[i]); }                                 

                            if(jrTabArray['#<?php 
            echo $targetElement;
            ?>
'] != undefined && $<?php 
            echo $targetElement;
            ?>
.html() != '') {   
                                jrTabArray['#<?php 
            echo $targetElement;
            ?>
'].show();
                            }
                        }
                        else {
                            if(jrTabArray['#<?php 
            echo $targetElement;
            ?>
'] != undefined && $<?php 
            echo $targetElement;
            ?>
.html() == '') {   
                                jrTabArray['#<?php 
            echo $targetElement;
            ?>
'].hide();
                            }
                        }
                        jreviews.module.pageNavInit(<?php 
            echo json_encode(compact('module_id', 'columns', 'orientation', 'slideshow', 'slideshow_interval', 'nav_position'));
            ?>
);
                    }
                });
            });
            /* ]]> */
            </script>  
        <?php 
        }
        // Process favorite users
        $key++;
        $module_id = 11000 + $listing_id;
        $userfavorites = Sanitize::getVar($listing['ListingType']['config'], 'userfavorites', array());
        if (Sanitize::getBool($userfavorites, 'enable')) {
            $target_id = Sanitize::getString($userfavorites, 'target_id', 'jrRelatedListings');
            $target_class = Sanitize::getString($userfavorites, 'target_class');
            $id = $listing_id;
            $moduleParams = compact('module_id', 'listingtype', 'ajax_init', 'id');
            extract($userfavorites);
            $title = str_ireplace('{title}', $listing_title, __t(Sanitize::getString($userfavorites, 'title'), true, true));
            $title = htmlspecialchars($title, ENT_QUOTES, 'utf-8');
            $targetElement = $target_class ? $target_class : $target_id;
            ?>
            <script type="text/javascript">    
            /* <![CDATA[ */
            jQuery(document).ready(function() 
            {           
                jreviews.dispatch({'controller':'module_favorite_users','action':'index',
                    'type':'json',
                    'data':<?php 
            echo json_encode($moduleParams);
            ?>
,
                    'onComplete':function(res){
                        var $<?php 
            echo $targetElement;
            ?>
 = <?php 
            if ($target_class) {
                ?>
jQuery('.<?php 
                echo $target_class;
                ?>
');<?php 
            } else {
                ?>
jQuery('#<?php 
                echo $target_id;
                ?>
');<?php 
            }
            ?>
                        if(res.response != '') {
                            var $widget = jQuery('<div id="<?php 
            echo $targetElement;
            ?>
Widget<?php 
            echo $key;
            ?>
"></div>').addClass('jrWidget')
                                    <?php 
            if ($title != '') {
                ?>
.append('<h4><?php 
                echo $title;
                ?>
</h4>')<?php 
            }
            ?>
                                    .append(res.response);
                                    
                            $<?php 
            echo $targetElement;
            ?>
.append($widget);
                            
                            var array = [0,1,2,3,4];
                            for(var i=0; i < array.length; i++) { array[i] = jQuery('#<?php 
            echo $targetElement;
            ?>
Widget'+ array[i]); }    
                            $<?php 
            echo $targetElement;
            ?>
.html();  
                            for(var i=0; i < array.length; i++) { $<?php 
            echo $targetElement;
            ?>
.append(array[i]); }                                 
                            
                            if(jrTabArray['#<?php 
            echo $targetElement;
            ?>
'] != undefined && $<?php 
            echo $targetElement;
            ?>
.html() != '') {   
                                jrTabArray['#<?php 
            echo $targetElement;
            ?>
'].show();
                            }                        
                        }
                        else {
                            if(jrTabArray['#<?php 
            echo $targetElement;
            ?>
'] != undefined && $<?php 
            echo $targetElement;
            ?>
.html() == '') {   
                                jrTabArray['#<?php 
            echo $targetElement;
            ?>
'].hide();
                            }                            
                        }
                        jreviews.module.pageNavInit(<?php 
            echo json_encode(compact('module_id', 'columns', 'orientation', 'slideshow', 'slideshow_interval', 'nav_position'));
            ?>
);
                    }
                });
            });
            /* ]]> */
            </script> 
            <?php 
        }
    }
Exemple #28
0
 function send($assets, $inline = false)
 {
     # Load javascript libraries
     $findjQuery = false;
     $this->Html->app = $this->app;
     // Incorporate controller set assets before sending
     if (!empty($this->assets['js'])) {
         $assets['js'] = array_merge($assets['js'], $this->assets['js']);
     }
     if (!empty($this->assets['css'])) {
         $assets['css'] = array_merge($assets['css'], $this->assets['css']);
     }
     cmsFramework::isRTL() and $assets['css'][] = 'rtl';
     // For CB and JomSocial prevent jQuery from loading twice
     // Check is done against constants defined in those applications
     if (isset($assets['js']) && !empty($assets['js'])) {
         $findjQuery = array_search('jquery', $assets['js']);
         $findjQueryUI = array_search('jq.ui.core', $assets['js']);
         $findjQueryUICss = array_search('jq.ui.core', $assets['css']);
         if ($findjQuery !== false) {
             if (defined('J_JQUERY_LOADED') || defined('C_ASSET_JQUERY')) {
                 unset($assets['js'][$findjQuery]);
                 //                        unset($assets['js'][$findjQueryUI],$assets['css'][$findjQueryUI]);
             } else {
                 define('J_JQUERY_LOADED', 1);
                 define('C_ASSET_JQUERY', 1);
             }
         }
     }
     if (isset($assets['js']) && !empty($assets['js'])) {
         $this->Html->js(arrayFilter($assets['js'], $this->Libraries->js()), $inline);
     }
     # Load CSS stylesheets
     if (isset($assets['css']) && !empty($assets['css'])) {
         $findjQueryUI = array_search('jq.ui.core', $assets['css']);
         if ($findjQueryUI !== false) {
             if (defined('J_JQUERYUI_LOADED')) {
                 unset($assets['css'][array_search('jq.ui.core', $assets['css'])]);
             } else {
                 define('J_JQUERYUI_LOADED', 1);
             }
         }
         $this->Html->css(arrayFilter($assets['css'], $this->Libraries->css()), $inline);
     }
     # Set jQuery defaults
     if ($findjQuery && isset($assets['js']['jreviews'])) {
         ?>
         <script type="text/javascript">
         jreviews.ajax_init();
         </script>
     <?php 
     }
     if (Sanitize::getBool($this->Config, 'ie6pngfix')) {
         $App =& App::getInstance($this->app);
         $AppPaths = $App->{$this->app . 'Paths'};
         $jsUrl = isset($AppPaths['Javascript']['jquery/jquery.pngfix.pack.js']) ? $AppPaths['Javascript']['jquery/jquery.pngfix.pack.js'] : false;
         if ($jsUrl) {
             cmsFramework::addScript('<!--[if lte IE 6]><script type="text/javascript" src="' . $jsUrl . '"></script><script type="text/javascript">jQuery(document).ready(function(){jQuery(document).pngFix();});</script><![endif]-->');
         }
         unset($App, $AppPaths);
     }
 }
 function index()
 {
     $response = array();
     if (Sanitize::getString($this->params, 'task') == 'upgrade') {
         // Where running the install script for upgrade we want a json object returned
         $this->autoLayout = false;
         $this->autoRender = false;
     } else {
         $this->autoLayout = true;
         $this->autoRender = true;
     }
     $this->name = 'install';
     # Remove views folder in J1.5
     if ($this->cmsVersion == CMS_JOOMLA15) {
         $Folder = ClassRegistry::getClass('Folder');
         $target = PATH_ROOT . 'components' . DS . 'com_jreviews' . DS . 'views';
         $Folder->rm($target);
     }
     # Create database tables
     // Start db upgrade logic
     $action = array();
     $action['db_install'] = true;
     $tables = $this->_db->getTableList();
     $dbprefix = cmsFramework::getConfig('dbprefix');
     $old_build = 0;
     // Get current version number
     $jreviewsxml = $this->cmsVersion == CMS_JOOMLA15 ? 'jreviews.xml' : 'jreviewg.xml';
     $xml = file(S2_CMS_ADMIN . $jreviewsxml);
     foreach ($xml as $xml_line) {
         if (strstr($xml_line, 'version')) {
             $new_version = trim(strip_tags($xml_line));
             continue;
         }
     }
     $version_parts = explode('.', $new_version);
     $new_build = array_pop($version_parts);
     if (is_array($tables) && in_array($dbprefix . 'jreviews_categories', array_values($tables))) {
         // Tables exist so we check the current build and upgrade accordingly, otherwise it's a clean install and no upgrade is necessary
         $query = "SELECT value FROM #__jreviews_config WHERE id = 'version'";
         $this->_db->setQuery($query);
         $old_version = trim(strip_tags($this->_db->loadResult()));
         if ($old_version != '') {
             $version_parts = explode('.', $old_version);
             $old_build = array_pop($version_parts);
         }
         if (Sanitize::getBool($this->params, 'sql')) {
             $old_build = 0;
         }
         //            prx($old_build . '<br/>' . $new_build) ;
         if ($new_build > $old_build) {
             $i = $old_build + 1;
             for ($i = $old_build + 1; $i <= $new_build; $i++) {
                 // Run sql updates
                 $sql_file = S2Paths::get('jreviews', 'S2_APP') . 'upgrades' . DS . 'upgrade_build' . $i . '.sql';
                 if (file_exists($sql_file)) {
                     $action['db_install'] = $this->__parseMysqlDump($sql_file, $dbprefix) && $action['db_install'];
                 }
                 // Run php updates
                 $php_file = S2Paths::get('jreviews', 'S2_APP') . 'upgrades' . DS . 'upgrade_build' . $i . '.php';
                 if (file_exists($php_file)) {
                     include $php_file;
                 }
             }
         }
     } else {
         // It's a clean install so we use the whole jReviews sql file
         $sql_file = S2Paths::get('jreviews', 'S2_APP') . 'upgrades' . DS . 'jreviews.sql';
         $action['db_install'] = $this->__parseMysqlDump($sql_file, $dbprefix);
     }
     # Update component id in pre-existing jReviews menus
     if ($this->cmsVersion == CMS_JOOMLA16) {
         $query = "\n                SELECT \n                    extension_id AS id\n                FROM \n                    #__extensions \n                WHERE \n                    element = '" . S2Paths::get('jreviews', 'S2_CMSCOMP') . "' AND type = 'component'\n            ";
     } else {
         $query = "\n                SELECT \n                    id \n                FROM \n                    #__components \n                WHERE \n                    admin_menu_link = 'option=" . S2Paths::get('jreviews', 'S2_CMSCOMP') . "'\n            ";
     }
     $this->_db->setQuery($query);
     if ($id = $this->_db->loadResult()) {
         if ($this->cmsVersion == CMS_JOOMLA16) {
             $query = "\n                    UPDATE \n                        `#__menu` \n                    SET \n                        component_id = {$id} \n                    WHERE \n                        type IN ('component','components') \n                            AND \n                        link LIKE 'index.php?option=" . S2Paths::get('jreviews', 'S2_CMSCOMP') . "%'\n                ";
         } else {
             $query = "\n                    UPDATE \n                        `#__menu` \n                    SET \n                        componentid = {$id} \n                    WHERE \n                        type IN ('component','components') \n                            AND \n                        link = 'index.php?option=" . S2Paths::get('jreviews', 'S2_CMSCOMP') . "'\n                ";
         }
         $this->_db->setQuery($query);
         $this->_db->query();
     }
     # Update version number in the database
     $this->Config->version = $new_version;
     $this->Config->store();
     $action['plugin_install'] = $this->_installPlugin();
     # Create image upload and thumbnail folders
     if (!is_dir(PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS)) {
         $Config = new JConfig();
         if (isset($Config->ftp_enable) && $Config->ftp_enable) {
             // set up basic connection
             $conn_id = ftp_connect($Config->ftp_host, $Config->ftp_port);
             // login with username and password
             $login_result = ftp_login($conn_id, $Config->ftp_user, $Config->ftp_pass);
             ftp_chdir($conn_id, $Config->ftp_root);
             ftp_mkdir($conn_id, _JR_PATH_IMAGES . 'jreviews');
             ftp_mkdir($conn_id, _JR_PATH_IMAGES . 'jreviews' . DS . 'tn');
             ftp_close($conn_id);
             @copy(PATH_ROOT . _JR_PATH_IMAGES . 'index.html', PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS . 'index.html');
             @copy(PATH_ROOT . _JR_PATH_IMAGES . 'index.html', PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS . 'tn' . DS . 'index.html');
         }
     }
     if (!is_dir(PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS)) {
         $result = mkdir(PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS, 0755);
         if (!$result) {
             $action['thumbnail_dir'] = false;
         } else {
             @copy(PATH_ROOT . _JR_PATH_IMAGES . 'index.html', PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS . 'index.html');
             $result = mkdir(PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS . 'tn', 0755);
             if (!$result) {
                 $action['thumbnail_dir'] = false;
             } else {
                 @copy(PATH_ROOT . _JR_PATH_IMAGES . 'index.html', PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS . 'tn' . DS . 'index.html');
             }
         }
     }
     if (!is_dir(PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS . 'tn' . DS)) {
         $result = mkdir(PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS . 'tn', 0755);
         if (!$result) {
             $action['thumbnail_dir'] = false;
         } else {
             @copy(PATH_ROOT . _JR_PATH_IMAGES . 'index.html', PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS . 'tn' . DS . 'index.html');
         }
     }
     if (is_dir(PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS) && is_dir(PATH_ROOT . _JR_PATH_IMAGES . 'jreviews' . DS . 'tn' . DS)) {
         $action['thumbnail_dir'] = true;
     }
     # Ensure that all field group names are slugs
     $query = "\n            SELECT \n                groupid, name\n            FROM\n                #__jreviews_groups\n        ";
     $this->_db->setQuery($query);
     $groups = $this->_db->loadAssocList();
     if (!empty($groups)) {
         foreach ($groups as $group) {
             if (strpos($group['name'], ' ') !== false) {
                 $name = cmsFramework::StringTransliterate($group['name']) . $group['groupid'];
                 $query = "\n                        UPDATE\n                            #__jreviews_groups\n                        SET \n                            name = " . $this->quote($name) . "\n                        WHERE\n                            groupid = " . $group['groupid'];
                 $this->_db->setQuery($query);
                 $this->_db->query();
             }
         }
     }
     # Clear data and core caches
     clearCache('', '__data');
     clearCache('', 'core');
     //var_dump($action);
     if (Sanitize::getString($this->params, 'task') == 'upgrade') {
         $response = array('error' => false, 'html' => '');
         // {"db_install":true,"plugin_install":true,"thumbnail_dir":true}
         if (!$action['db_install']) {
             $response['error'] = true;
             $response['html'] = '<div style="color:red>There was a problem upgrading the database</div>';
         }
         if (!$action['plugin_install']) {
             $response['error'] = true;
             $response['html'] .= '<div style="color:red>There was a problem upgrading the JReviews plugin</div>';
         }
         return json_encode($response);
     }
     $this->set(array('action' => $action));
 }
 function _plgReviewAfterSave(&$model)
 {
     $review = $this->_getReview($model);
     // Treat moderated reviews as new
     $this->inAdmin and Sanitize::getBool($model->data, 'moderation') and $model->isNew = true;
     if (isset($model->isNew) && $model->isNew && $review['Review']['published'] == 1) {
         // Begin add points
         $aupid = AlphaUserPointsHelper::getAnyUserReferreID($review['User']['user_id']);
         if ($aupid) {
             AlphaUserPointsHelper::newpoints('plgaup_jreviews_review_add', $aupid);
         }
     }
 }