We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 24844
    • 25 Posts
    Здравствуйте все! smiley
    Решил поставить для некоторых статей возможность оценивать их (как сайты на Modx.ru, например), нашёл сниппет CSS Star Rating 1.1. Вроде простенький такой, но я ним разобраться никак не могу... короче говоря, я нуб во всём что так или иначе касается php, а значит и MODx embarrassed. Инструкция к сниппету скупая и какая-то непонятная. Я создал сниппет star_rating, tv-параметр с таким же названием, прописал в шаблоне путь к css-файлу star.css. Звёздочки появляются, но голосования не происходит — пишет ошибку 404. Я читал английские топики, но тольком ничего не понял. Подскажите, плиз, что я сделал не так? У меня включены дружественныые ссылки, MODx версии 0.9.6.1p2. Я так предполагаю, ошибка связана с tv-параметрами?
      • 24844
      • 25 Posts
      Решение проблемы найдено — мне его лично предоставил Garry (на форуме известный как garryn, создатель CSS Star Rating), за что ему большое спасибо wink
      Начну с того, что проблема была связана с «дружественными» ссылками, и решается она заменой кода сниппета, если у вас возникла такая-же проблема, вставьте следующий код вместо текущего кода сниппета (обычно star_rating):

      <?php
      //<?php
      
      /**
       * Created on 30-May-2006
       *
       * Snippet: CSS Star Rating
       * Author: Garry Nutting
       * For: MODx 0.9.2.1 and above
       *
       * Modified:
       *  06/26/2006 - Added output template support - kylej
       *  06/29/2006 - Added language variables
       * 
       * Placeholder Values
       * ------------------
       *
       * [+starRating+] - output of the <ul> list for the star rating
       * [+totalVotes+] - output the total number of votes
       *  
       */
       
      //-- start session
      session_start();
      
      //-- snippet parameters
      $tvName = (isset ($tvName)) ? $tvName : 'star_rating'; // TV name where data will be stored
      $useSession = (isset ($useSession)) ? true : false; // Whether to only one vote per session
      $docID = (isset ($docID)) ? $docID : $modx->documentObject['id']; //see if document is set
      $pid = (isset ($_GET['pid']) && is_numeric($_GET['pid'])) ? $_GET['pid'] : ''; //see if pid has been passed back
      $viewOnly = (isset ($viewOnly)) ? true : false; //disable voting
      $cssFile = (isset ($cssFile)) ? $cssFile : 1; //see if alternate css should be used
      $imgWidth = (isset ($imgWidth)) ? $imgWidth : 25; //get the image width, used when displaying current rating
      $onevote = (isset ($onevote)) ? $onevote : false; //use cookie restrictions to only allow one vote
      $ovtime = (isset ($ovtime)) ? $ovtime : 608400; //expire in one week
      
      //-- language variables
      $_lang['no_display'] = 'Unable to display rating';
      $_lang['current_1'] = 'Currently';
      $_lang['current_2'] = '/5 Stars';
      $_lang['one_star'] = '1 star out of 5';
      $_lang['two_stars'] = '2 stars out of 5';
      $_lang['three_stars'] = '3 stars out of 5';
      $_lang['four_stars'] = '4 stars out of 5';
      $_lang['five_stars'] = '5 stars out of 5';
      $_lang['no_vote'] = 'You may only vote once';
      
      $cssFiles = array (
      	'1' => 'assets/snippets/star_rating/star.css'
      );
      
      $starTpl = isset ($starTpl) ? $modx->getChunk($starTpl) : '[+starRating+]<span class="totalvotes">Votes: [+totalVotes+]</span>';
      
      if (array_key_exists($cssFile, $cssFiles)) {
      	$cssFile = $cssFiles[$cssFile];
      }
      
      //-- check if visitor is logged in
      session_start();
      
      //-- cookie check - if $onevote, check if visitor is allowed to vote
      if (!$viewOnly && $onevote == true) {
      	if (isset ($_COOKIE['cssStarRating' . $docID])) {
      		$viewOnly = true;
      	}
      	elseif (isset ($_GET['starvote'])) {
      		//-- set cookie
      		setcookie('cssStarRating' . $docID, 'novote', time() + $ovtime);
      	}
      }
      
      if (!function_exists('setTemplateVar')) {
      	function setTemplateVar($value, $docID, $tplVarName) {
      		global $modx;
      
      		//-- get tmplvar id
      		$tplName = $modx->getFullTableName('site_tmplvars');
      		$tplRS = $modx->db->select('id', $tplName, 'name="' . $tplVarName . '"');
      		$tplRow = $modx->db->getRow($tplRS);
      
      		$tblName = $modx->getFullTableName('site_tmplvar_contentvalues');
      
      		$selectQuery = $modx->db->select('*', $tblName, 'contentid=' . $docID . ' AND tmplvarid=' . $tplRow['id']);
      
      		$updFields = array (
      			'value' => $value
      		);
      		$insFields = array (
      			'tmplvarid' => $tplRow['id'],
      			'contentid' => $docID,
      			'value' => $value
      		);
      
      		if ($modx->db->getRecordCount($selectQuery) < 1) {
      			$modx->db->insert($insFields, $tblName);
      		} else {
      			$modx->db->update($updFields, $tblName, 'contentid=' . $docID . ' AND tmplvarid=' . $tplRow['id']);
      		}
      	}
      }
      
      //-- get TV value
      $tvValue = $modx->getTemplateVar($tvName, '*', $docID);
      
      //-- check session variable to see if already voted
      $novote = ($useSession == true && isset ($_SESSION['starRating']['voted' . $docID])) ? true : false;
      
      //-- exit if no TV found
      if (!$tvValue)
      	return $_lang['no_display'];
      
      //-- split out TV values and calculate current Rating
      $splitVals = explode(':', $tvValue['value']);
      
      //-- check to ensure that a vote can be cast
      if ($pid <> '' && isset ($_GET['starvote']) && $novote == false && is_numeric($_GET['starvote']) && $_GET['starvote'] >= 0 && $_GET['starvote'] <= 5) {
      
      	//-- get TV value
      	$tvValue = $modx->getTemplateVar($tvName, '*', $pid);
      
      	//-- split out TV values and calculate current Rating
      	$splitVals = explode(':', $tvValue['value']);
      
      	$newCount = $splitVals[0] + $_GET['starvote'];
      	$newVoteNumber = $splitVals[1] + 1;
      
      	@ setTemplateVar("$newCount:$newVoteNumber", $pid, $tvName);
      	//-- as this code is run for each instance of the Star Rating,
      	//-- the $_GET variable is unset so the update is only run once
      	//-- useful for when star rating multiple times on same page ;)
      	unset ($_GET);
      
      	if ($useSession == true) {
      		$_SESSION['starRating']['voted' . $pid] = true;
      	}
      
      	//-- refresh page to show correct ratings
      	$curURL = $modx->makeUrl($modx->documentObject['id']);
      	$modx->sendRedirect($curURL);
      }
      
      if ($splitVals[1] > 0) {
      	$currentStarValue = $splitVals[0] / $splitVals[1];
      	$totalVotes = $splitVals[1];
      } else {
      	$currentStarValue = 0;
      	$totalVotes = '0';
      }
      
      $starPhArray = array ();
      
      $output = '';
      $width = $currentStarValue * $imgWidth;
      
      if (!$viewOnly) {
      	$starPhArray['starRating'] = "<ul class='star-rating'>
      		<li class='current-rating' style='width:" . $width . "px;'>" . $_lang['current_1'] . $currentStarValue . $_lang['current_2'] . "</li>
      		<li><a href='" . $modx->makeUrl($modx->documentObject['id'], '', 'starvote=1&pid=' . $docID) . "' title='" . $_lang['one_star'] . "' class='one-star'>1</a></li>
      		<li><a href='" . $modx->makeUrl($modx->documentObject['id'], '', 'starvote=2&pid=' . $docID) . "' title='" . $_lang['two_stars'] . "' class='two-stars'>2</a></li>
      		<li><a href='" . $modx->makeUrl($modx->documentObject['id'], '', 'starvote=3&pid=' . $docID) . "' title='" . $_lang['three_stars'] . "' class='three-stars'>3</a></li>
      		<li><a href='" . $modx->makeUrl($modx->documentObject['id'], '', 'starvote=4&pid=' . $docID) . "' title='" . $_lang['four_stars'] . "' class='four-stars'>4</a></li>
      		<li><a href='" . $modx->makeUrl($modx->documentObject['id'], '', 'starvote=5&pid=' . $docID) . "' title='" . $_lang['five_stars'] . "' class='five-stars'>5</a></li>
      	</ul>";
      } else {
      	$starPhArray['starRating'] = "<ul class='star-rating'>
      	<li class='current-rating' style='width:" . $width . "px;'>" . $_lang['current_1'] . $currentStarValue . $_lang['current_2'] . "</li>
      		<li class='one-star'>1</li>
      		<li class='two-stars'>2</li>
      		<li class='three-stars'>3</li>
      		<li class='four-stars'>4</li>
      		<li class='five-stars'>5</li>
      	</ul>";
      }
      
      $starPhArray['totalVotes'] = $totalVotes;
      
      foreach ($starPhArray as $n => $v) {
      	$starTpl = str_replace('[+' . $n . '+]', $v, $starTpl);
      }
      
      if ($novote) {
      	$output .= '<div class="star-rating-warning">' . $_lang['no_vote'] . '</div>';
      } else {
      	$output .= $starTpl;
      }
      
      return $output;
      ?>


      Ссылка, где опубликован этот код: http://php.pastebin.com/d1f133a3c (срок существования истекает через сутки)

      Не забудьте также создать tv-параметр star_rating с текстовым (Text) типом ввода. У меня всё smiley