Exemplo n.º 1
0
 /**
  * Calls a controller's method from any location.
  *
  * @param string $url URL in the form of Cake URL ("/controller/method/parameter")
  * @param array $extra if array includes the key "return" it sets the AutoRender to true.
  * @return mixed Success (true/false) or contents if 'return' is set in $extra
  * @access public
  */
 function requestAction($url, $extra = array())
 {
     $app = Sanitize::getString($extra, 'app', 'jreviews');
     unset($extra['app']);
     if (empty($url)) {
         return false;
     }
     if (!class_exists('S2Dispatcher')) {
         require S2_FRAMEWORK . DS . 'dispatcher.php';
     }
     if (in_array('return', $extra, true)) {
         $extra = array_merge($extra, array('return' => 0, 'autoRender' => 1));
     }
     $params = array_merge(array('token' => cmsFramework::formIntegrityToken($extra, array('module', 'module_id', 'form', 'data'), false), 'autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1), $extra);
     $disable404 = true;
     $dispatcher = new S2Dispatcher($app, null, $disable404);
     return $dispatcher->dispatch($url, $params);
 }
 function listings()
 {
     // Initialize variables
     $id = Sanitize::getInt($this->params, 'id');
     $option = Sanitize::getString($this->params, 'option');
     $view = Sanitize::getString($this->params, 'view');
     $menu_id = Sanitize::getString($this->params, 'Itemid');
     // Read params
     $cat_id = '';
     $criteria_ids = '';
     $in_detail_view = false;
     $detail_view = 1;
     $dir_id = Sanitize::getString($this->params, 'dir');
     $section_id = Sanitize::getString($this->params, 'section');
     $cat_id = Sanitize::getString($this->params, 'cat');
     $extension = 'com_content';
     $custom_where = null;
     $custom_fields = array();
     $click2search_auto = false;
     $cache = 0;
     $radius = 0;
     $mode = 0;
     if (isset($this->params['module'])) {
         // Read module parameters
         $click2search_auto = Sanitize::getBool($this->params['module'], 'click2search_auto', false);
         $custom_where = Sanitize::getString($this->params['module'], 'custom_where');
         $filter = Sanitize::getString($this->params['module'], 'filter');
         $detail_view = Sanitize::getString($this->params['module'], 'detail_view', 1);
         $dir_id = Sanitize::getString($this->params['module'], 'dir');
         $section_id = Sanitize::getString($this->params['module'], 'section');
         $cat_id = Sanitize::getString($this->params['module'], 'category');
         $listing_id = Sanitize::getString($this->params['module'], 'listing');
         $criteria_ids = Sanitize::getString($this->params['module'], 'criteria');
         $limit_results = Sanitize::getInt($this->params['module'], 'limit_results');
         $mode = Sanitize::getInt($this->params['module'], 'mode', 0);
         $custom_fields = str_replace(" ", "", Sanitize::getString($this->Config, 'geomaps.infowindow_fields'));
         $custom_fields = $custom_fields != '' ? explode(",", $custom_fields) : array();
         /**
          * 0 - Normal
          * 1 - GeoTargeting
          * 2 - Custom center and zoom
          */
         $radius = Sanitize::getInt($this->params['module'], 'radius');
         $cache = $mode == 1 ? 0 : Sanitize::getInt($this->params['module'], 'cache_map');
         $custom_lat = Sanitize::getFloat($this->params['module'], 'custom_lat');
         $custom_lon = Sanitize::getFloat($this->params['module'], 'custom_lon');
         if ($mode == 2 && ($custom_lat == 0 || $custom_lon == 0)) {
             echo __t("You selected the Custom Center mode, but did not specify the coordinates.");
             return;
         }
     }
     # Prevent sql injection
     $token = Sanitize::getString($this->params, 'token');
     $tokenMatch = 0 === strcmp($token, cmsFramework::formIntegrityToken($this->params, array('module', 'module_id', 'form', 'data'), false));
     $filters = $listing_id != '' || $dir_id != '' || $section_id != '' || $cat_id != '';
     if (!$filters && $id > 0 && 'article' == $view && 'com_content' == $option) {
         $sql = "SELECT catid FROM #__content WHERE id = " . $id;
         $this->_db->setQuery($sql);
         $cat_id_host_page = $this->_db->loadResult();
         if (!empty($cat_id_host_page) && $this->Category->isJreviewsCategory($cat_id_host_page)) {
             $in_detail_view = true;
             $cat_id = $cat_id_host_page;
         }
     }
     $detail_view = $this->params['module']['detail_view'] = (int) ($detail_view && $in_detail_view);
     # Custom WHERE
     $tokenMatch and $custom_where and $conditions[] = $custom_where;
     if ($click2search_auto && isset($this->params['tag'])) {
         $field = 'jr_' . Sanitize::getString($this->params['tag'], 'field');
         $value = Sanitize::getString($this->params['tag'], 'value');
         $query = "SELECT Field.type FROM #__jreviews_fields AS Field WHERE Field.name = " . $this->quote($field);
         $this->_db->setQuery($query);
         $type = $this->_db->loadResult();
         if (in_array($type, array('select', 'selectmultiple', 'checkboxes', 'radiobuttons'))) {
             $conditions[] = "Field.{$field} LIKE " . $this->quoteLike('*' . $value . '*');
         } else {
             $conditions[] = "Field.{$field} = " . $this->quote($value);
         }
     }
     # Category auto detect
     if (isset($this->params['module']) && Sanitize::getInt($this->params['module'], 'cat_auto') && $extension == 'com_content') {
         $ids = CommonController::_discoverIDs($this);
         extract($ids);
     }
     $autodetect = compact('dir_id', 'section_id', 'cat_id');
     // Check for cached version if cache enabled
     if ($cache) {
         $params = array();
         foreach ($this->params as $key => $value) {
             if ((!is_array($value) || $key == 'module') && !in_array($key, array('page', 'limit', 'order', 'Itemid'))) {
                 $params[$key] = $value;
             }
         }
         $cache_key = array_merge($params, $autodetect, Sanitize::getVar($this->params, 'tag', array()));
         $json_filename = 'geomaps_' . md5(serialize($cache_key)) . '.json';
         $json_data = S2Cache::read($json_filename);
         if ($json_data && $json_data != '') {
             $this->set('json_data', $json_data);
             S2Cache::write($json_filename, $json_data);
             return $this->render('modules', 'geomaps');
         }
     }
     $this->Listing->fields = array('Listing.id AS `Listing.listing_id`', 'Listing.title AS `Listing.title`', 'Listing.images AS `Listing.images`', 'CASE WHEN CHAR_LENGTH(Listing.alias) THEN Listing.alias ELSE "" END AS `Listing.slug`', 'Category.id AS `Listing.cat_id`', 'CASE WHEN CHAR_LENGTH(Category.alias) THEN Category.alias ELSE Category.title END AS `Category.slug`', 'Listing.sectionid AS `Listing.section_id`', 'JreviewsCategory.criteriaid AS `Criteria.criteria_id`', 'JreviewsCategory.dirid AS `Directory.dir_id`', 'JreviewsCategory.marker_icon AS `Geomaps.icon`', 'Field.featured AS `Listing.featured`', 'Totals.user_rating AS `Review.user_rating`', 'Totals.user_rating_count AS `Review.user_rating_count`', 'Totals.editor_rating AS `Review.editor_rating`', 'Totals.editor_rating_count AS `Review.editor_rating_count`', "Field.{$this->jr_lat} `Geomaps.lat`", "Field.{$this->jr_lon} `Geomaps.lon`", 'ListingType.state AS `Criteria.state`', 'ListingType.config AS `ListingType.config`');
     if ($custom_lon != '' and $custom_lat != '') {
         $this->set('CustomCenter', array('lon' => $custom_lon, 'lat' => $custom_lat));
     }
     // Geo Targeting OR Custom Center modes
     if ($mode == 1 || $mode == 2) {
         if ($mode == 1) {
             $ch = curl_init();
             curl_setopt($ch, CURLOPT_URL, 'http://www.geoplugin.net/php.gp?ip=' . s2GetIpAddress());
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
             curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
             $geoData = unserialize(curl_exec($ch));
             curl_close($ch);
             if (!empty($geoData) && isset($geoData['geoplugin_latitude']) && $geoData['geoplugin_latitude'] != '' && $geoData['geoplugin_longitude'] != '') {
                 $center = array('lon' => $geoData['geoplugin_longitude'], 'lat' => $geoData['geoplugin_latitude']);
             }
             $this->set('geoLocation', $geoData);
         }
         if ($mode == 2) {
             $center = array('lon' => $custom_lon, 'lat' => $custom_lat);
         }
         if (!empty($center) && $radius > 0) {
             $distanceIn = Sanitize::getString($this->Config, 'geomaps.radius_metric', 'mi');
             $degreeDistance = $distanceIn == 'mi' ? 69.172 : 40076 / 360;
             // Send center coordinates to theme
             $this->set('GeomapsCenter', $center);
             $lat_range = $radius / $degreeDistance;
             $lon_range = $radius / abs(cos($center['lat'] * pi() / 180) * $degreeDistance);
             $min_lat = $center['lat'] - $lat_range;
             $max_lat = $center['lat'] + $lat_range;
             $min_lon = $center['lon'] - $lon_range;
             $max_lon = $center['lon'] + $lon_range;
             $squareArea = "`Field`.{$this->jr_lat} BETWEEN {$min_lat} AND {$max_lat} AND `Field`.{$this->jr_lon} BETWEEN {$min_lon} AND {$max_lon}";
             $conditions[] = $squareArea;
         }
     }
     // Create marker_icons array
     $marker_icons = array();
     $icon_fields = array();
     $field_images = array();
     $query = "SELECT DISTINCT marker_icon FROM #__jreviews_categories WHERE marker_icon != ''";
     $this->_db->setQuery($query);
     $icon_rows = $this->_db->loadAssocList();
     foreach ($icon_rows as $icons) {
         $icon = (array) json_decode($icons['marker_icon']);
         if ($icon['field'] != '') {
             $icon_fields[$icon['field']] = "'" . $icon['field'] . "'";
         }
     }
     if (!empty($icon_fields)) {
         foreach ($icon_fields as $field_key => $field) {
             if (substr($field_key, 0, 3) == 'jr_') {
                 $this->Listing->fields[] = "Field.{$field_key} AS `Field.{$field_key}`";
             }
         }
     }
     if (!empty($custom_fields)) {
         foreach ($custom_fields as $field) {
             $this->Listing->fields[] = "Field.{$field} AS `Field.{$field}`";
         }
     }
     $this->Listing->joins = array("LEFT JOIN #__categories AS Category ON Listing.catid = Category.id", 'ParentCategory' => "LEFT JOIN #__categories AS ParentCategory ON Category.lft BETWEEN ParentCategory.lft AND ParentCategory.rgt", "LEFT JOIN #__jreviews_listing_totals AS Totals ON Totals.listing_id = Listing.id AND Totals.extension = 'com_content'", "LEFT JOIN #__jreviews_content AS `Field` ON Field.contentid = Listing.id", "INNER JOIN #__jreviews_categories AS JreviewsCategory ON Listing.catid = JreviewsCategory.id AND JreviewsCategory.`option` = 'com_content'", "LEFT JOIN #__jreviews_criteria AS ListingType ON JreviewsCategory.criteriaid = ListingType.id", "LEFT JOIN #__jreviews_directories AS Directory ON JreviewsCategory.dirid = Directory.id");
     // Don't regroup the results by model name keys to save time
     $this->Listing->primaryKey = false;
     # Set conditionals based on configuration parameters
     if ($detail_view) {
         $conditions[] = 'Listing.id = ' . $id;
     }
     if (!empty($cat_id)) {
         $conditions[] = $this->cmsVersion == CMS_JOOMLA15 ? 'Listing.catid IN (' . cleanIntegerCommaList($cat_id) . ')' : 'ParentCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')';
     }
     if ($this->cmsVersion == CMS_JOOMLA15) {
         unset($this->Listing->joins['ParentCategory']);
     }
     empty($cat_id) and !empty($section_id) and $conditions[] = 'Listing.sectionid IN (' . cleanIntegerCommaList($section_id) . ')';
     empty($cat_id) and !empty($dir_id) and $conditions[] = 'JreviewsCategory.dirid IN (' . cleanIntegerCommaList($dir_id) . ')';
     empty($cat_id) and !empty($criteria_id) and $conditions[] = 'JreviewsCategory.criteriaid IN (' . cleanIntegerCommaList($criteria_id) . ')';
     if ($listing_id) {
         $conditions[] = 'Listing.id IN (' . $listing_id . ')';
     }
     if ($filter == 'featured' && !$detail_view) {
         $conditions[] = 'Field.featured = 1';
     }
     $conditions[] = "Field.{$this->jr_lat} <> ''";
     $conditions[] = "Field.{$this->jr_lon} <> ''";
     $conditions = array_merge($conditions, array('Listing.state = 1', '( Listing.publish_up = "' . NULL_DATE . '" OR DATE(Listing.publish_up) <= DATE("' . _CURRENT_SERVER_TIME . '") )', '( Listing.publish_down = "' . NULL_DATE . '" OR DATE(Listing.publish_down) >= DATE("' . _CURRENT_SERVER_TIME . '") )'));
     if ($this->cmsVersion == CMS_JOOMLA15) {
         //                    $conditions[] = 'Section.access <= ' . $this->Access->getAccessId();
         $conditions[] = 'Category.access <= ' . $this->Access->getAccessId();
         $conditions[] = 'Listing.access <= ' . $this->Access->getAccessId();
     } else {
         $conditions[] = 'Category.access IN (' . $this->Access->getAccessLevels() . ')';
         $conditions[] = 'Listing.access IN (' . $this->Access->getAccessLevels() . ')';
     }
     // Paid Listings - add plan cat id
     isset($this->PaidListings) and $this->PaidListings->applyBeforeFindListingChanges($this->Listing);
     $listings = $this->Listing->findAll(array('conditions' => $conditions, 'limit' => $limit_results), array());
     $custom_fields = array_filter(array_merge($custom_fields, array_keys($icon_fields)));
     $fieldOptionValues = array();
     // Extract custom field values to avoid loading all options for each fields
     // It's a trade-off between that and doing a foreach on all listings
     foreach ($listings as $key => $row) {
         $listings[$key]['Criteria']['state'] = $row['Criteria.state'];
         $listings[$key]['ListingType']['config'] = json_decode($row['ListingType.config'], true);
         unset($listings[$key]['Criteria.state'], $listings[$key]['ListingType.config']);
         foreach ($custom_fields as $field) {
             $optionValue = Sanitize::getVar($row, 'Field.' . $field);
             if ($optionValue != '' && $optionValue != '**') {
                 $fieldOptionValues = array_merge($fieldOptionValues, array_filter(explode('*', $optionValue)));
             }
         }
     }
     $fields = $this->Field->getFields($custom_fields, 'listing', $fieldOptionValues);
     $json_data = $this->Geomaps->makeJsonObject($listings, $fields, $this->params['module']);
     $this->set('json_data', $json_data);
     if ($cache) {
         S2Cache::write($json_filename, $json_data);
     }
     return $this->render('modules', 'geomaps');
 }
 function _saveEdit()
 {
     $this->autoRender = false;
     $this->autoLayout = false;
     $this->Discussion->isNew = false;
     $response = array();
     # Load the notifications observer model component and initialize it.
     # Done here so it only loads on save and not for all controlller actions.
     $this->components = array('security');
     $this->__initComponents();
     # Validate form token
     if ($this->invalidToken) {
         return $this->ajaxError(s2Messages::invalidToken());
     }
     $post_id = Sanitize::getInt($this->data['Discussion'], 'discussion_id');
     $isNew = (bool) (!$post_id);
     if ($isNew && !$this->Access->canAddPost()) {
         return $this->ajaxError(s2Messages::accessDenied());
     } elseif (!$isNew) {
         # Stop form data tampering
         $owner_id = $this->Discussion->getPostOwner($post_id);
         $formToken = cmsFramework::formIntegrityToken($this->data['Discussion'], $this->formTokenKeys, false);
         if (!$this->Access->canEditPost($owner_id) || !$this->__validateToken($formToken)) {
             return $this->ajaxError(s2Messages::accessDenied());
         }
     }
     $text = str_replace("\n", "<br />", htmlspecialchars($this->data['Discussion']['text'], ENT_QUOTES));
     $this->data['Discussion']['modified'] = date('Y-m-d H:i:s');
     $this->data['Discussion']['approved'] = 1;
     if ($this->Discussion->store($this->data)) {
         $update_text = __t("Your comment has been updated.", true);
         $response[] = "jQuery('#jr_post{$post_id}').hide('fast');";
         $response[] = "jQuery('#jr_post{$post_id} .jr_comments').html('{$text}');";
         $response[] = "jQuery('#jr_post{$post_id}').slideDown(1000);";
         return $this->ajaxUpdatePage('jr_post' . $post_id, $update_text, '', compact('response'));
     }
     return $this->ajaxError(__t("There was an error saving the comment.", true, true));
 }
Exemplo n.º 4
0
<?php

/**
 * jReviews - Reviews Extension
 * Copyright (C) 2006 ClickFWD LLC
 * This is not free software, do not distribute it.
 * For licencing information visit http://www.reviewsforjoomla.com
 * or contact sales@reviewsforjoomla.com
**/
defined('_VALID_MOS') || defined('_JEXEC') or die('Direct Access to this location is not allowed.');
# MVC initalization script
require JPATH_SITE . DS . 'components' . DS . 'com_jreviews' . DS . 'jreviews' . DS . 'framework.php';
# Populate $params array with module settings
$module_params = isset($params->_raw) ? stringToArray($params->_raw) : $params->toArray();
$moduleParams['module'] = $module_params;
$moduleParams['module_id'] = $module->id;
$moduleParams['page'] = 1;
$moduleParams['data']['module'] = true;
$moduleParams['data']['controller'] = 'module_totals';
$moduleParams['data']['action'] = 'index';
$moduleParams['token'] = cmsFramework::formIntegrityToken($moduleParams, array('module', 'module_id', 'form', 'data'), false);
$Dispatcher = new S2Dispatcher('jreviews');
echo $Dispatcher->dispatch($moduleParams);
unset($Dispatcher);
 function index()
 {
     /*        if($this->_user->id === 0) 
             {
                 $this->cacheAction = Configure::read('Cache.expires');        
             }*/
     // Required for ajax pagination to remember module settings
     $ids = $conditions = $joins = $order = $having = array();
     $module_id = Sanitize::getInt($this->params, 'module_id', Sanitize::getInt($this->data, 'module_id'));
     if (!isset($this->params['module'])) {
         $this->params['module'] = array();
     }
     // For direct calls to the controller
     # Find the correct set of params to use
     if ($this->ajaxRequest && Sanitize::getInt($this->params, 'listing_id')) {
         $this->params['module'] = array_merge($this->params['module'], $this->__processListingTypeWidgets($conditions));
     } elseif ($this->ajaxRequest && empty($this->params['module']) && $module_id) {
         $query = "SELECT params FROM #__modules WHERE id = " . $module_id;
         $this->_db->setQuery($query);
         $this->params['module'] = stringToArray($this->_db->loadResult());
     }
     if ($this->abort) {
         return $this->ajaxResponse('', false);
     }
     # Read module parameters
     $dir_id = Sanitize::getString($this->params['module'], 'dir');
     $section_id = Sanitize::getString($this->params['module'], 'section');
     $cat_id = Sanitize::getString($this->params['module'], 'category');
     $listing_id = Sanitize::getString($this->params['module'], 'listing');
     $created_by = Sanitize::getString($this->params['module'], 'owner');
     $criteria_id = Sanitize::getString($this->params['module'], 'criteria');
     $limit = Sanitize::getInt($this->params['module'], 'module_limit', 5);
     $total = min(50, Sanitize::getInt($this->params['module'], 'module_total', 10));
     $extension = Sanitize::getString($this->params['module'], 'extension');
     $extension = $extension != '' ? $extension : 'com_content';
     $sort = Sanitize::getString($this->params['module'], 'listing_order');
     if (in_array($sort, array('random', 'featuredrandom'))) {
         srand((double) microtime() * 1000000);
         $this->params['rand'] = rand();
     }
     # Prevent sql injection
     $token = Sanitize::getString($this->params, 'token');
     $tokenMatch = 0 === strcmp($token, cmsFramework::formIntegrityToken($this->params, array('module', 'module_id', 'form', 'data'), false));
     isset($this->params['module']) and $this->viewSuffix = Sanitize::getString($this->params['module'], 'tmpl_suffix');
     if (isset($this->Listing)) {
         $this->Listing->_user = $this->_user;
         // This parameter determines the module mode
         $custom_order = Sanitize::getString($this->params['module'], 'custom_order');
         $custom_where = Sanitize::getString($this->params['module'], 'custom_where');
         if ($extension != 'com_content' && in_array($sort, array('topratededitor', 'featuredrandom', 'rhits'))) {
             echo "You have selected the {$sort} mode which is not supported for components other than com_content. Please read the tooltips in the module parameters for more info on allowed settings.";
             return;
         }
         # Category auto detect
         if (Sanitize::getInt($this->params['module'], 'cat_auto') && $extension == 'com_content') {
             $ids = CommonController::_discoverIDs($this);
             extract($ids);
         }
         # Set conditionals based on configuration parameters
         if ($extension == 'com_content') {
             // Perform tag replacement for listing_id to allow for related listing queries
             if (Sanitize::getString($this->params, 'view') == 'article' && $custom_where != '') {
                 $curr_listing_id = Sanitize::getInt($this->params, 'id');
                 $custom_where = str_replace('{listing_id}', $curr_listing_id, $custom_where);
             }
             // Only works for core articles
             $conditions = array_merge($conditions, array('Listing.state = 1', '( Listing.publish_up = "' . NULL_DATE . '" OR DATE(Listing.publish_up) <= DATE("' . _CURRENT_SERVER_TIME . '") )', '( Listing.publish_down = "' . NULL_DATE . '" OR DATE(Listing.publish_down) >= DATE("' . _CURRENT_SERVER_TIME . '") )'));
             if ($this->cmsVersion == CMS_JOOMLA15) {
                 //                    $conditions[] = 'Section.access <= ' . $this->Access->getAccessId();
                 $conditions[] = 'Category.access <= ' . $this->Access->getAccessId();
                 $conditions[] = 'Listing.access <= ' . $this->Access->getAccessId();
             } else {
                 $conditions[] = 'Category.access IN (' . $this->Access->getAccessLevels() . ')';
                 $conditions[] = 'Listing.access IN (' . $this->Access->getAccessLevels() . ')';
             }
             // Remove unnecessary fields from model query
             $this->Listing->modelUnbind(array('Listing.fulltext AS `Listing.description`', 'Listing.metakey AS `Listing.metakey`', 'Listing.metadesc AS `Listing.metadesc`', 'User.email AS `User.email`'));
             if (!empty($cat_id)) {
                 $conditions[] = $this->cmsVersion == CMS_JOOMLA15 ? 'Listing.catid IN (' . cleanIntegerCommaList($cat_id) . ')' : 'ParentCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')';
             } else {
                 unset($this->Listing->joins['ParentCategory']);
             }
             empty($cat_id) and !empty($section_id) and $conditions[] = 'Listing.sectionid IN (' . cleanIntegerCommaList($section_id) . ')';
             empty($cat_id) and !empty($dir_id) and $conditions[] = 'JreviewsCategory.dirid IN (' . cleanIntegerCommaList($dir_id) . ')';
             empty($cat_id) and !empty($criteria_id) and $conditions[] = 'JreviewsCategory.criteriaid IN (' . cleanIntegerCommaList($criteria_id) . ')';
         } else {
             if (Sanitize::getInt($this->params['module'], 'cat_auto') && method_exists($this->Listing, 'catUrlParam')) {
                 if ($cat_id = Sanitize::getInt($this->passedArgs, $this->Listing->catUrlParam())) {
                     $conditions[] = 'JreviewsCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')';
                 }
             } elseif ($cat_id) {
                 $conditions[] = 'JreviewsCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')';
             }
         }
         $listing_id and $conditions[] = "Listing.{$this->Listing->realKey} IN (" . cleanIntegerCommaList($listing_id) . ")";
         switch ($sort) {
             case 'random':
                 $order[] = 'RAND(' . $this->params['rand'] . ')';
                 break;
             case 'featured':
                 $conditions[] = 'Field.featured = 1';
                 break;
             case 'featuredrandom':
                 $conditions[] = 'Field.featured = 1';
                 $order[] = 'RAND(' . $this->params['rand'] . ')';
                 break;
             case 'topratededitor':
                 //                    $conditions[] = 'Totals.editor_rating > 0';
                 $sort = 'editor_rating';
                 break;
                 // Editor rating sorting options dealt with in the Listing->processSorting method
         }
         # Custom WHERE
         $tokenMatch and $custom_where and $conditions[] = $custom_where;
         # Filtering options
         $having = array();
         // Listings submitted in the past x days
         $entry_period = Sanitize::getInt($this->params['module'], 'filter_listing_period');
         if ($entry_period > 0 && $this->Listing->dateKey) {
             $conditions[] = "Listing.{$this->Listing->dateKey} >= DATE_SUB('" . _CURRENT_SERVER_TIME . "', INTERVAL {$entry_period} DAY)";
         }
         // Listings with reviews submitted in past x days
         $review_period = Sanitize::getInt($this->params['module'], 'filter_review_period');
         if ($review_period > 0) {
             $conditions[] = "Review.created >= DATE_SUB(CURDATE(), INTERVAL {$review_period} DAY)";
             $joins[] = 'LEFT JOIN #__jreviews_comments AS Review ON Listing.' . $this->Listing->realKey . ' = Review.pid';
         }
         // Listings with review count higher than
         $filter_review_count = Sanitize::getInt($this->params['module'], 'filter_review_count');
         $filter_review_count > 0 and $conditions[] = "Totals.user_rating_count >= " . $filter_review_count;
         // Listings with avg rating higher than
         $filter_avg_rating = Sanitize::getFloat($this->params['module'], 'filter_avg_rating');
         $filter_avg_rating > 0 and $conditions[] = 'Totals.user_rating  >= ' . $filter_avg_rating;
         $this->Listing->group = array();
         // Exlude listings without ratings from the results
         $join_direction = in_array($sort, array('rating', 'rrating', 'topratededitor', 'reviews')) ? 'INNER' : 'LEFT';
         $this->Listing->joins['Total'] = "{$join_direction} JOIN #__jreviews_listing_totals AS Totals ON Totals.listing_id = Listing.{$this->Listing->realKey} AND Totals.extension = " . $this->quote($extension);
         # Modify query for correct ordering. Change FIELDS, ORDER BY and HAVING BY directly in Listing Model variables
         if ($tokenMatch and $custom_order) {
             $this->Listing->order[] = $custom_order;
         } elseif (empty($order) && $extension == 'com_content') {
             $this->Listing->processSorting('module', $sort);
             // Modifies Listing model order var directly
         } elseif (empty($order) && ($order = $this->__processSorting($sort))) {
             $order = array($order);
         }
         $fields = array('Totals.user_rating AS `Review.user_rating`', 'Totals.user_rating_count AS `Review.user_rating_count`', 'Totals.user_comment_count AS `Review.review_count`', 'Totals.editor_rating AS `Review.editor_rating`', 'Totals.editor_rating_count AS `Review.editor_rating_count`', 'Totals.editor_comment_count AS `Review.editor_review_count`');
         $queryData = array('fields' => !isset($this->Listing->fields['editor_rating']) ? $fields : array(), 'joins' => $joins, 'conditions' => $conditions, 'limit' => $total, 'having' => $having);
         isset($order) and !empty($order) and $queryData['order'] = $order;
         // Trigger addFields for $listing results. Checked in Everywhere model
         $this->Listing->addFields = true;
         $listings = $this->Listing->findAll($queryData);
         $count = count($listings);
     } else {
         $listings = array();
         $count = 0;
     }
     unset($this->Listing);
     # Send variables to view template
     $this->set(array('autodetect_ids' => $ids, 'subclass' => 'listing', 'listings' => $listings, 'total' => $count, 'limit' => $limit));
     $this->_completeModuleParamsArray();
     $page = $this->ajaxRequest && empty($listings) ? '' : $this->render('modules', 'listings');
     /*        if($this->_user->id === 0 && $this->ajaxRequest) 
             {
                 $path = $this->here;
     
                 $this->here == '/' and $path = 'home';
                 
                 $cache_fname = Inflector::slug($path) . '.php';
              
                 $now = time();
     
                 $cacheTime = is_numeric($this->cacheAction) ? $now + $this->cacheAction : strtotime($this->cacheAction, $now);
              
                 $fileHeader = '<!--cachetime:' . $cacheTime . '-->'; 
                 
                 cache('views' . DS . $cache_fname, $fileHeader . $this->ajaxResponse($page,false), $this->cacheAction);
             }*/
     return $this->ajaxRequest ? $this->ajaxResponse($page, false) : $page;
 }
 function _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 index()
 {
     /*        if($this->_user->id === 0) 
             {
                 $this->cacheAction = Configure::read('Cache.expires');        
             }   */
     $this->EverywhereAfterFind = true;
     // Triggers the afterFind in the Observer Model
     if (!isset($this->params['module'])) {
         $this->params['module'] = array();
     }
     // For direct calls to the controller
     $module_id = Sanitize::getInt($this->params, 'module_id', Sanitize::getInt($this->data, 'module_id'));
     if (empty($this->params)) {
         $query = "SELECT params FROM #__modules WHERE id = " . $module_id;
         $this->_db->setQuery($query);
         $this->params['module'] = stringToArray($this->_db->loadResult());
     }
     $ids = $conditions = $joins = $order = array();
     # Read module parameters
     $extension = Sanitize::getString($this->params['module'], 'extension');
     $reviews_type = Sanitize::getString($this->params['module'], 'reviews_type');
     $custom_where = Sanitize::getString($this->params['module'], 'custom_where');
     $cat_id = Sanitize::getString($this->params['module'], 'category');
     $listing_id = Sanitize::getString($this->params['module'], 'listing');
     $limit = Sanitize::getInt($this->params['module'], 'module_limit', 5);
     $total = min(50, Sanitize::getInt($this->params['module'], 'module_total', 10));
     if ($extension == 'com_content') {
         $dir_id = Sanitize::getString($this->params['module'], 'dir');
         $section_id = Sanitize::getString($this->params['module'], 'section');
         $criteria_id = Sanitize::getString($this->params['module'], 'criteria');
     } else {
         $dir_id = null;
         $section_id = null;
         $criteria_id = null;
     }
     # Prevent sql injection
     $token = Sanitize::getString($this->params, 'token');
     $tokenMatch = 0 === strcmp($token, cmsFramework::formIntegrityToken($this->params, array('module', 'module_id', 'form', 'data'), false));
     isset($this->params['module']) and $this->viewSuffix = Sanitize::getString($this->params['module'], 'tmpl_suffix');
     // This parameter determines the module mode
     $sort = Sanitize::getString($this->params['module'], 'reviews_order');
     if (in_array($sort, array('random'))) {
         srand((double) microtime() * 1000000);
         $this->params['rand'] = rand();
     }
     # Category auto detect
     if (Sanitize::getInt($this->params['module'], 'cat_auto') && $extension == 'com_content') {
         $ids = CommonController::_discoverIDs($this);
         extract($ids);
     }
     $extension != '' and $conditions[] = "Review.mode = " . $this->quote($extension);
     # Set conditionals based on configuration parameters
     if ($extension == 'com_content') {
         $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() . ')';
         }
         if (!empty($cat_id)) {
             if ($this->cmsVersion == CMS_JOOMLA15) {
                 $conditions[] = 'Listing.catid IN (' . cleanIntegerCommaList($cat_id) . ')';
             } else {
                 $this->Review->joins['ParentCategory'] = "LEFT JOIN #__categories AS ParentCategory ON Category.lft BETWEEN ParentCategory.lft AND ParentCategory.rgt";
                 $conditions[] = 'ParentCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')';
             }
         }
         empty($cat_id) and !empty($section_id) and $conditions[] = 'Listing.sectionid IN (' . cleanIntegerCommaList($section_id) . ')';
         empty($cat_id) and !empty($dir_id) and $conditions[] = 'JreviewsCategory.dirid IN (' . cleanIntegerCommaList($dir_id) . ')';
         empty($cat_id) and !empty($criteria_id) and $conditions[] = 'JreviewsCategory.criteriaid IN (' . cleanIntegerCommaList($criteria_id) . ')';
     } else {
         if (Sanitize::getInt($this->params['module'], 'cat_auto') && isset($this->Listing) && method_exists($this->Listing, 'catUrlParam')) {
             if ($cat_id = Sanitize::getInt($this->passedArgs, $this->Listing->catUrlParam())) {
                 $conditions[] = 'JreviewsCategory.id IN (' . $cat_id . ')';
             }
         } elseif ($cat_id) {
             $conditions[] = 'JreviewsCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')';
         }
     }
     $listing_id and $conditions[] = "Review.pid IN ( " . cleanIntegerCommaList($listing_id) . ")";
     $conditions[] = 'Review.published > 0';
     switch ($sort) {
         case 'latest':
             $order[] = $this->Review->processSorting('rdate');
             break;
         case 'helpful':
             $order[] = $this->Review->processSorting('helpful');
             break;
         case 'random':
             $order[] = 'RAND(' . $this->params['rand'] . ')';
             break;
         default:
             $order[] = $this->Review->processSorting('rdate');
             break;
     }
     switch ($reviews_type) {
         case 'all':
             break;
         case 'user':
             $conditions[] = 'Review.author = 0';
             break;
         case 'editor':
             $conditions[] = 'Review.author = 1';
             break;
     }
     # Custom WHERE
     $tokenMatch and $custom_where and $conditions[] = $custom_where;
     $queryData = array('joins' => $joins, 'conditions' => $conditions, 'order' => $order, 'limit' => $total);
     # Don't run it here because it's run in the Everywhere Observer Component
     $this->Review->runProcessRatings = false;
     // Excludes listing owner info in Everywhere component
     $this->Review->controller = 'module_reviews';
     $reviews = $this->Review->findAll($queryData);
     $count = count($reviews);
     # Send variables to view template
     $this->set(array('autodetect_ids' => $ids, 'reviews' => $reviews, 'total' => $count, 'limit' => $limit));
     $this->_completeModuleParamsArray();
     $page = $this->ajaxRequest && empty($reviews) ? '' : $this->render('modules', 'reviews');
     /*        if($this->_user->id === 0 && $this->ajaxRequest) 
             {
                 $path = $this->here;
     
                 $this->here == '/' and $path = 'home';
                 
                 $cache_fname = Inflector::slug($path) . '.php';
              
                 $now = time();
     
                 $cacheTime = is_numeric($this->cacheAction) ? $now + $this->cacheAction : strtotime($this->cacheAction, $now);
              
                 $fileHeader = '<!--cachetime:' . $cacheTime . '-->'; 
                 
                 cache('views' . DS . $cache_fname, $fileHeader . $this->ajaxResponse($page,false), $this->cacheAction);
             }*/
     return $this->ajaxRequest ? $this->ajaxResponse($page, false) : $page;
 }
Exemplo n.º 8
0
 function index()
 {
     $this->EverywhereAfterFind = true;
     // Triggers the afterFind in the Observer Model
     if (!isset($this->params['module'])) {
         $this->params['module'] = array();
     }
     // For direct calls to the controller
     // Required for ajax pagination to remember module settings
     $Session = RegisterClass::getInstance('MvcSession');
     $module_id = Sanitize::getInt($this->params, 'module_id', Sanitize::getInt($this->data, 'module_id'));
     if ($this->ajaxRequest) {
         $this->params = $Session->get('module_params' . $module_id, null, S2Paths::get('jreviews', 'S2_CMSCOMP'));
     } else {
         srand((double) microtime() * 1000000);
         $this->params['rand'] = rand();
         $Session->set('module_rand' . $module_id, $this->params['rand'], S2Paths::get('jreviews', 'S2_CMSCOMP'));
         $Session->set('module_params' . $module_id, $this->params, S2Paths::get('jreviews', 'S2_CMSCOMP'));
     }
     # Prevent sql injection
     $token = Sanitize::getString($this->params, 'token');
     $tokenMatch = 0 === strcmp($token, cmsFramework::formIntegrityToken($this->params, array('module', 'module_id', 'form', 'data'), false));
     $this->viewSuffix = Sanitize::getString($this->params['module'], 'tmpl_suffix');
     $conditions = array();
     $joins = array();
     $order = array();
     # Read module parameters
     $extension = Sanitize::getString($this->params['module'], 'extension');
     $reviews_type = Sanitize::getString($this->params['module'], 'reviews_type');
     $custom_where = Sanitize::getString($this->params['module'], 'custom_where');
     $cat_id = Sanitize::getString($this->params['module'], 'category');
     $listing_id = Sanitize::getString($this->params['module'], 'listing');
     if ($extension == 'com_content') {
         $dir_id = Sanitize::getString($this->params['module'], 'dir');
         $section_id = Sanitize::getString($this->params['module'], 'section');
         $criteria_id = Sanitize::getString($this->params['module'], 'criteria');
     } else {
         $dir_id = null;
         $section_id = null;
         $criteria_id = null;
     }
     // This parameter determines the module mode
     $sort = Sanitize::getString($this->params['module'], 'reviews_order');
     # Category auto detect
     if (Sanitize::getInt($this->params['module'], 'cat_auto') && $extension == 'com_content') {
         $ids = CommonController::_discoverIDs($this);
         extract($ids);
     }
     $extension != '' and $conditions[] = "Review.mode = " . $this->quote($extension);
     # Set conditionals based on configuration parameters
     if ($extension == 'com_content') {
         $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 . '") )', 'Listing.access <= ' . $this->_user->gid));
         $cat_id != '' and $conditions[] = 'Listing.catid IN (' . cleanIntegerCommaList($cat_id) . ')';
         $cat_id == '' and $section_id != '' and $conditions[] = 'Listing.sectionid IN (' . cleanIntegerCommaList($section_id) . ')';
         $cat_id == '' and $dir_id != '' and $conditions[] = 'JreviewsCategory.dirid IN (' . cleanIntegerCommaList($dir_id) . ')';
         $cat_id == '' and $criteria_id != '' and $conditions[] = 'JreviewsCategory.criteriaid IN (' . cleanIntegerCommaList($criteria_id) . ')';
     } else {
         if (Sanitize::getInt($this->params['module'], 'cat_auto') && isset($this->Listing) && method_exists($this->Listing, 'catUrlParam')) {
             if ($cat_id = Sanitize::getInt($this->passedArgs, $this->Listing->catUrlParam())) {
                 $conditions[] = 'JreviewsCategory.id IN (' . $cat_id . ')';
             }
         } elseif ($cat_id) {
             $conditions[] = 'JreviewsCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')';
         }
     }
     $listing_id and $conditions[] = "Review.pid IN ( " . cleanIntegerCommaList($listing_id) . ")";
     $conditions[] = 'Review.published > 0';
     switch ($sort) {
         case 'latest':
             $order[] = $this->Review->processSorting('rdate');
             break;
         case 'helpful':
             $order[] = $this->Review->processSorting('helpful');
             break;
         case 'random':
             $order[] = 'RAND(' . $this->params['rand'] . ')';
             break;
         default:
             $order[] = $this->Review->processSorting('rdate');
             break;
     }
     switch ($reviews_type) {
         case 'all':
             break;
         case 'user':
             $conditions[] = 'Review.author = 0';
             break;
         case 'editor':
             $conditions[] = 'Review.author = 1';
             break;
     }
     # Custom WHERE
     $tokenMatch and $custom_where and $conditions[] = $custom_where;
     $queryData = array('joins' => $joins, 'conditions' => $conditions, 'order' => $order, 'limit' => $this->module_limit, 'offset' => $this->module_offset);
     # Don't run it here because it's run in the Everywhere Observer Component
     $this->Review->runProcessRatings = false;
     // Excludes listing owner info in Everywhere component
     $this->Review->controller = 'module_reviews';
     $reviews = $this->Review->findAll($queryData);
     if (Sanitize::getInt($this->params['module'], 'ajax_nav', 1)) {
         unset($queryData['order']);
         $count = $this->Review->findCount($queryData, 'DISTINCT Review.id');
     } else {
         $count = $this->module_limit;
     }
     # Send variables to view template
     $this->set(array('Access' => $this->Access, 'User' => $this->_user, 'reviews' => $reviews, 'total' => $count));
     $page = $this->render('modules', 'reviews');
     if ($this->ajaxRequest) {
         return $this->ajaxResponse($page, false);
     } else {
         return $page;
     }
 }
Exemplo n.º 9
0
 function index()
 {
     // Required for ajax pagination to remember module settings
     $Session = RegisterClass::getInstance('MvcSession');
     $module_id = Sanitize::getInt($this->params, 'module_id', Sanitize::getInt($this->data, 'module_id'));
     if (!isset($this->params['module'])) {
         $this->params['module'] = array();
     }
     // For direct calls to the controller
     if ($this->ajaxRequest) {
         $this->params = $Session->get('module_params' . $module_id, null, S2Paths::get('jreviews', 'S2_CMSCOMP'));
     } else {
         srand((double) microtime() * 1000000);
         $this->params['rand'] = rand();
         $Session->set('module_rand' . $module_id, $this->params['rand'], S2Paths::get('jreviews', 'S2_CMSCOMP'));
         $Session->set('module_params' . $module_id, $this->params, S2Paths::get('jreviews', 'S2_CMSCOMP'));
     }
     # Prevent sql injection
     $token = Sanitize::getString($this->params, 'token');
     $tokenMatch = 0 === strcmp($token, cmsFramework::formIntegrityToken($this->params, array('module', 'module_id', 'form', 'data'), false));
     $this->viewSuffix = Sanitize::getString($this->params['module'], 'tmpl_suffix');
     $conditions = array();
     $joins = array();
     $order = array();
     $having = array();
     # Read module parameters
     $dir_id = Sanitize::getString($this->params['module'], 'dir');
     $section_id = Sanitize::getString($this->params['module'], 'section');
     $cat_id = Sanitize::getString($this->params['module'], 'category');
     $listing_id = Sanitize::getString($this->params['module'], 'listing');
     $criteria_id = Sanitize::getString($this->params['module'], 'criteria');
     $limit = Sanitize::getString($this->params['module'], 'module_limit', 5);
     $extension = Sanitize::getString($this->params['module'], 'extension');
     $extension = $extension != '' ? $extension : 'com_content';
     if (isset($this->Listing)) {
         $this->Listing->_user = $this->_user;
         // This parameter determines the module mode
         $sort = Sanitize::getString($this->params['module'], 'listing_order');
         $custom_order = Sanitize::getString($this->params['module'], 'custom_order');
         $custom_where = Sanitize::getString($this->params['module'], 'custom_where');
         if ($extension != 'com_content' && in_array($sort, array('topratededitor', 'featuredrandom', 'rhits'))) {
             echo "You have selected the {$sort} mode which is not supported for components other than com_content. Please read the tooltips in the module parameters for more info on allowed settings.";
             return;
         }
         # Category auto detect
         if (Sanitize::getInt($this->params['module'], 'cat_auto') && $extension == 'com_content') {
             $ids = CommonController::_discoverIDs($this);
             extract($ids);
         }
         # Set conditionals based on configuration parameters
         if ($extension == 'com_content') {
             // Only works for core articles
             $conditions = array_merge($conditions, array('Listing.state = 1', '( Listing.publish_up = "' . NULL_DATE . '" OR DATE(Listing.publish_up) <= DATE("' . _CURRENT_SERVER_TIME . '") )', '( Listing.publish_down = "' . NULL_DATE . '" OR DATE(Listing.publish_down) >= DATE("' . _CURRENT_SERVER_TIME . '") )', 'Listing.access <= ' . $this->_user->gid));
             // Remove unnecessary fields from model query
             $this->Listing->modelUnbind(array('Listing.fulltext AS `Listing.description`', 'Listing.metakey AS `Listing.metakey`', 'Listing.metadesc AS `Listing.metadesc`', 'User.email AS `User.email`'));
             $cat_id != '' and $conditions[] = 'Listing.catid IN (' . cleanIntegerCommaList($cat_id) . ')';
             $cat_id == '' and $section_id != '' and $conditions[] = 'Listing.sectionid IN (' . cleanIntegerCommaList($section_id) . ')';
             $cat_id == '' and $dir_id != '' and $conditions[] = 'JreviewsCategory.dirid IN (' . cleanIntegerCommaList($dir_id) . ')';
             $cat_id == '' and $criteria_id != '' and $conditions[] = 'JreviewsCategory.criteriaid IN (' . cleanIntegerCommaList($criteria_id) . ')';
         } else {
             if (Sanitize::getInt($this->params['module'], 'cat_auto') && method_exists($this->Listing, 'catUrlParam')) {
                 if ($cat_id = Sanitize::getInt($this->passedArgs, $this->Listing->catUrlParam())) {
                     $conditions[] = 'JreviewsCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')';
                 }
             } elseif ($cat_id) {
                 $conditions[] = 'JreviewsCategory.id IN (' . cleanIntegerCommaList($cat_id) . ')';
             }
         }
         $listing_id and $conditions[] = "Listing.{$this->Listing->realKey} IN (" . cleanIntegerCommaList($listing_id) . ")";
         switch ($sort) {
             case 'random':
                 $order[] = 'RAND(' . $this->params['rand'] . ')';
                 break;
             case 'featuredrandom':
                 $conditions[] = 'featured > 0';
                 $order[] = 'RAND(' . $this->params['rand'] . ')';
                 break;
             case 'topratededitor':
                 $conditions[] = 'Totals.editor_rating > 0';
                 break;
                 // Editor rating sorting options dealt with in the Listing->processSorting method
         }
         # Custom WHERE
         $tokenMatch and $custom_where and $conditions[] = $custom_where;
         # Filtering options
         $having = array();
         // Listings submitted in the past x days
         $entry_period = Sanitize::getInt($this->params['module'], 'filter_listing_period');
         if ($entry_period > 0 && $this->Listing->dateKey) {
             $conditions[] = "Listing.{$this->Listing->dateKey} >= DATE_SUB('" . _CURRENT_SERVER_TIME . "', INTERVAL {$entry_period} DAY)";
         }
         // Listings with reviews submitted in past x days
         $review_period = Sanitize::getInt($this->params['module'], 'filter_review_period');
         if ($review_period > 0) {
             $conditions[] = "Review.created >= DATE_SUB(CURDATE(), INTERVAL {$review_period} DAY)";
             $joins[] = 'LEFT JOIN #__jreviews_comments AS Review ON Listing.' . $this->Listing->realKey . ' = Review.pid';
         }
         // Listings with review count higher than
         $filter_review_count = Sanitize::getInt($this->params['module'], 'filter_review_count');
         $filter_review_count > 0 and $conditions[] = "Totals.user_rating_count >= " . $filter_review_count;
         // Listings with avg rating higher than
         $filter_avg_rating = Sanitize::getFloat($this->params['module'], 'filter_avg_rating');
         $filter_avg_rating > 0 and $conditions[] = 'Totals.user_rating  >= ' . $filter_avg_rating;
         $this->Listing->group = array();
         // Exlude listings without ratings from the results
         $join_direction = in_array($sort, array('rating', 'rrating', 'topratededitor', 'reviews')) ? 'INNER' : 'LEFT';
         $this->Listing->joins['Total'] = "{$join_direction} JOIN #__jreviews_listing_totals AS Totals ON Totals.listing_id = Listing.{$this->Listing->realKey} AND Totals.extension = " . $this->quote($extension);
         # Modify query for correct ordering. Change FIELDS, ORDER BY and HAVING BY directly in Listing Model variables
         if ($tokenMatch and $custom_order) {
             $this->Listing->order[] = $custom_order;
         } elseif (empty($order) && $extension == 'com_content') {
             $this->Listing->processSorting($sort, '');
         } elseif (empty($order) && ($order = $this->_processSorting($sort))) {
             $order = array($order);
         }
         $queryData = array('fields' => array('Totals.user_rating AS `Review.user_rating`', 'Totals.user_rating_count AS `Review.user_rating_count`', 'Totals.user_comment_count AS `Review.review_count`', 'Totals.editor_rating AS `Review.editor_rating`', 'Totals.editor_rating_count AS `Review.editor_rating_count`', 'Totals.editor_comment_count AS `Review.editor_review_count`'), 'joins' => $joins, 'conditions' => $conditions, 'limit' => $this->module_limit, 'offset' => $this->module_offset, 'having' => $having);
         isset($order) and !empty($order) and $queryData['order'] = $order;
         // Trigger addFields for $listing results. Checked in Everywhere model
         $this->Listing->addFields = true;
         $listings = $this->Listing->findAll($queryData);
         if (Sanitize::getInt($this->params['module'], 'ajax_nav', 1)) {
             unset($queryData['joins']['Section'], $queryData['joins']['Category'], $queryData['joins']['Directory'], $queryData['joins']['Criteria'], $queryData['joins']['User'], $queryData['order']);
             $count = $this->Listing->findCount($queryData, 'DISTINCT Listing.' . $this->Listing->realKey);
         } else {
             $count = $this->module_limit;
         }
     } else {
         $listings = array();
         $count = 0;
     }
     unset($this->Listing);
     # Send variables to view template
     $this->set(array('Access' => $this->Access, 'User' => $this->_user, 'subclass' => 'listing', 'listings' => $listings, 'total' => $count));
     $page = $this->render('modules', 'listings');
     if ($this->ajaxRequest) {
         return $this->ajaxResponse($page, false);
     } else {
         return $page;
     }
 }
Exemplo n.º 10
0
 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['sectionid_hidden'] = Sanitize::getInt($this->data['Listing'], 'sectionid_hidden');
     $this->data['categoryid_hidden'] = Sanitize::getInt($this->data['Listing'], 'categoryid_hidden');
     $this->data['Listing']['sectionid'] = Sanitize::getInt($this->data['Listing'], 'sectionid');
     $this->data['Listing']['catid'] = Sanitize::getInt($this->data['Listing'], 'catid');
     $this->data['Listing']['title'] = Sanitize::getString($this->data['Listing'], 'title', '');
     $this->data['Listing']['created_by_alias'] = Sanitize::getString($this->data, 'name', '');
     # Check submit access
     $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);
         $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']);
     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) {
         # Stop form data tampering
         $owner = $this->Listing->getListingOwner($listing_id);
         $formToken = cmsFramework::formIntegrityToken($this->data['Listing'], array_keys($this->formTokenKeys), false);
         if (!$this->Access->canEditListing($owner['user_id']) || !Sanitize::getString($this->params['form'], $formToken)) {
             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 = trim(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 = trim(S2Router::sefUrlEncode($alias));
         if (trim(str_replace('-', '', $slug)) == '') {
             $slug = date("Y-m-d-H-i-s");
         }
     }
     $slug != '' and $this->data['Listing']['alias'] = mb_strtolower($slug);
     # Check for duplicates
     switch ($this->Config->content_title_duplicates) {
         case 'category':
             // Checks for duplicates in the same category
             $query = "\n                        SELECT \n                            count(*) \n                        FROM \n                            #__content AS Listing WHERE Listing.title = " . $this->_db->Quote($this->data['Listing']['title']) . "\n                            AND Listing.state >= 0 \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 = "\n                        SELECT \n                            count(*) \n                        FROM \n                            #__content AS Listing\n                        WHERE \n                            Listing.title = " . $this->_db->Quote($this->data['Listing']['title']) . "\n                           AND Listing.state >= 0\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) . "</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->data['Listing']['catid'] || !$this->data['Listing']['sectionid']) {
         $this->Listing->validateSetError("sec_cat", __t("You need to select both a section and 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), 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), $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), $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), $this->Config->reviewform_title == 'required' ? true : false);
         if ($criteria['Criteria']['state'] == 1) {
             $criteria_qty = count($this->data['Rating']['ratings']);
             $ratingErr = 0;
             for ($i = 0; $i < $criteria_qty; $i++) {
                 if (isset($this->data['Rating']['ratings'][$i]) && (!$this->data['Rating']['ratings'][$i] || $this->data['Rating']['ratings'][$i] == '' || $this->data['Rating']['ratings'][$i] == 'undefined')) {
                     $ratingErr++;
                 }
             }
             $this->Listing->validateInput('', "rating", "text", sprintf(__t("You are missing a rating in %s criteria.", 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), $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));
         } 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));
             }
         }
     }
     # 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}');";
         if (isset($this->Security)) {
             $response[] = "{$parentFrame}.jQuery('#jr_ListingToken').val('" . $this->Security->reissueToken() . "');";
         }
         $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'] = !$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), $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);
     }
     // 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;
         $facebook_integration and $response[] = $parentFrame . '.jQuery.get(' . $parentFrame . '.s2AjaxUri+' . $parentFrame . '.jreviews.ajax_params()+\'&url=facebook/_postListing/id:' . $listing_id . '\');
             ';
         $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);
         $update_html = "<a href=\"{$url}\">" . __t("Click here to view the listing", true) . "</a>";
         $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);
 }