Webylon 3.1 API Docs
  • Package
  • Class
  • Tree
  • Deprecated
  • Download
Version: current
  • 3.2
  • 3.1

Packages

  • auth
  • Booking
  • cart
    • shipping
    • steppedcheckout
  • Catalog
  • cms
    • assets
    • batchaction
    • batchactions
    • bulkloading
    • comments
    • content
    • core
    • export
    • newsletter
    • publishers
    • reports
    • security
    • tasks
  • Dashboard
  • DataObjectManager
  • event
  • faq
  • forms
    • actions
    • core
    • fields-basic
    • fields-dataless
    • fields-datetime
    • fields-files
    • fields-formatted
    • fields-formattedinput
    • fields-relational
    • fields-structural
    • transformations
    • validators
  • googlesitemaps
  • guestbook
  • installer
  • newsletter
  • None
  • photo
    • gallery
  • PHP
  • polls
  • recaptcha
  • sapphire
    • api
    • bulkloading
    • control
    • core
    • cron
    • dev
    • email
    • fields-formattedinput
    • filesystem
    • formatters
    • forms
    • i18n
    • integration
    • misc
    • model
    • parsers
    • search
    • security
    • tasks
    • testing
    • tools
    • validation
    • view
    • widgets
  • seo
    • open
      • graph
  • sfDateTimePlugin
  • spamprotection
  • stealth
    • captha
  • subsites
  • userform
    • pagetypes
  • userforms
  • webylon
  • widgets

Classes

  • Announcement_Controller
  • AnnouncementHolder_Controller
  • BookingAdminPage_Controller
  • BookingPage_Controller
  • Cart_Controller
  • CartPage_Controller
  • Catalog_Controller
  • CheckoutPage_Controller
  • ChequePayment_Handler
  • ContactsPage_Controller
  • ContentController
  • ContentNegotiator
  • Controller
  • DataObjectManager_Controller
  • DatePickerField_Controller
  • Director
  • DocPage_Controller
  • DocumentsPage_Controller
  • Event_Controller
  • EventHolder_Controller
  • FileDataObjectManager_Controller
  • FindCyrillic_Controller
  • HomePage_Controller
  • LastDoc_Controller
  • LiveCalendarWidget_Controller
  • MapObject_Controller
  • MapObjectGroup_Controller
  • MapPage_Controller
  • MediawebPage_Controller
  • ModelAsController
  • MultiUploadControls
  • NewsArchive
  • Orders1CExchange_Controller
  • Page_Controller
  • Payment_Handler
  • PhotoAlbumManager_Controller
  • Product_Controller
  • ProductSearchPage_Controller
  • ProfilePage_Controller
  • PublHolder_Controller
  • Publication_Controller
  • RatingExtension_Controller
  • RegistrationPage_Controller
  • RemoveOrphanedPagesTask
  • RequestHandler
  • Room_Controller
  • RoomCatalog_Controller
  • RootURLController
  • SapphireInfo
  • Search_Controller
  • Session
  • SimpleOrderPage_Controller
  • SiteMap_Controller
  • SpecialCatalog_Controller
  • SS_HTTPRequest
  • SS_HTTPResponse
  • StartCatalog_Controller
  • SubsitesSelectorPage_Controller
  • VideoBankPage_Controller

Interfaces

  • NestedController

Exceptions

  • SS_HTTPResponse_Exception
  1 <?php
  2 
  3 /**
  4  * Расширение которе можно повесить на объект
  5  * DataObject::add_extension('Image','RatingExtension');
  6  *
  7  * @author inxo
  8  */
  9 class RatingExtension extends DataObjectDecorator {
 10 
 11     public $RatingInt = null;
 12     public $RatingFloat = null;
 13     public $Votes = null;
 14 
 15     /**
 16      * Переопределим конструктор, чтобы сразу вычислить необходимые значения
 17      */
 18     function __construct() {
 19         parent::__construct();
 20     }
 21 
 22     /**
 23      * Дополнительный поля для объекта
 24      * @return <type>
 25      */
 26     function extraStatics() {
 27         return array(
 28             'casting' => array(
 29                 'RatingInt' => 'Int',
 30                 'RatingFloat' => 'Decimal',
 31                 'Votes' => 'Int',
 32                 'AlreadyVote' =>'Boolean'
 33             ),
 34         );
 35     }
 36 
 37     private function run_calc_rate(){
 38         $this->RatingFloat = 0;
 39         $this->RatingInt = 0;
 40         $this->Votes = 0;
 41         
 42         $clazz = $this->owner->ClassName;
 43         $id = $this->owner->ID;
 44         
 45         $votes = DataObject::get('RatingDataObject', 'ObjectClass LIKE \''.$clazz.'\' AND ObjectID = '.$id.'');
 46         if(!$votes){
 47             return false;
 48         }
 49         $summ = 0;
 50         $this->Votes = Int::create('Int', count($votes));
 51 
 52         foreach ($votes as $vote)
 53         {
 54             $summ += $vote->Rate;
 55         }
 56         $this->RatingFloat = Decimal::create('Decimal',$summ/$this->Votes->getValue());
 57         $this->RatingInt = Int::create('Int', round($summ/$this->Votes->getValue()));
 58 
 59         return true;
 60     }
 61     function getRatingInt(){
 62         if(is_null($this->RatingInt))
 63                 $this->run_calc_rate();
 64         return $this->RatingInt;
 65     }
 66 
 67     function getRatingFloat(){
 68         if(is_null($this->RatingFloat))
 69                 $this->run_calc_rate();
 70         return $this->RatingFloat;
 71     }
 72 
 73     function getVotes(){
 74         if(is_null($this->Votes))
 75                 $this->run_calc_rate();
 76         return $this->Votes;
 77     }
 78 
 79     function getAlreadyVote(){
 80         return !RatingDataObject::is_unique(session_id(),$this->owner->ClassName,$this->owner->ID);
 81     }
 82 
 83     // rating/class/id
 84 
 85     public function VoteForm() {
 86         $form = new MediawebForm(
 87 
 88                         new RatingExtension_Controller(),
 89                         "vote",
 90                         new FieldSet(
 91                                 new HiddenField("objid", "objid", $this->owner->ID),
 92                                 new HiddenField("objcls", "objcls", $this->owner->ClassName),
 93                                 new OptionsetField('vote', 'Оценка', array(1, 2, 3, 4, 5), 0)
 94                         ),
 95                         new FieldSet(
 96                                 new FormAction(
 97                                         'rating',
 98                                         'Проголосовать'
 99                                 )
100                         )
101         );
102         $form->disableSecurityToken();
103         return $form;
104     }
105 
106 }
107 
108 class RatingExtension_Controller extends ContentController {
109     function vote($data) {
110         $error = false;
111         // Подготовка параметров
112         // POST
113         if(isset($data) && isset($data['objid']) && isset($data['objcls']) && isset($data['vote'])){
114             if(is_numeric($data['objid']) && is_numeric($data['vote'])){
115                 $vote = $data['vote'];
116                 $cls = Convert::raw2sql($data['objcls']);
117                 $id = Convert::raw2sql($data['objid']);
118             }
119             else{
120                 $error = true;
121                 $error_msg = _t('Rating.Error',"Недопустимое действие");
122             }
123         }
124         // GET
125         else{ // TODO: в этом варианте стратегия должна быть голосуем за одного от общего родителя?
126             $cls = Convert::raw2sql(Director::urlParam('ID'));
127             $id = (int) Director::urlParam('OtherID');
128             $vote = (isset($_REQUEST['vote']) && is_int($_REQUEST['vote'])) ? (int) $_REQUEST['vote'] : 1; // Так как у нас просто вариант проголосовать.
129         }
130 
131         // Сохраняем результат голосования
132         if(!$error && isset($vote) && isset($cls) && isset($id)){
133             // Проверим существование класса и что на нем висит расширение Rating
134             if(ClassInfo::exists($cls) && ClassInfo::is_subclass_of($cls, 'DataObject') && DataObject::has_extension($cls, 'RatingExtension')){
135                 $session_id = session_id(); // Сессия для идентификации
136                 if(RatingDataObject::is_unique($session_id,$cls,$id)){
137                     $rateData = new RatingDataObject(
138                             array(
139                                 'SessionID'=> $session_id,
140                                 'ObjectClass' => $cls,
141                                 'ObjectID' => $id,
142                                 'Rate' => $vote
143                                 )
144                     );
145                     $rateData->write();
146                 }
147                 else{
148                     $error = true;
149                     $error_msg = _t('Rating.Voted',"Вы уже голосовали");
150                 }
151 
152             }else{
153                 $error = true;
154                 $error_msg = _t('Rating.Error',"Недопустимое действие");
155             }
156         }
157 
158         // Решаем, какой запрос был
159         if($this->isAjax()){
160             // Возращаем данные
161             if($error){
162                 return Convert::array2json(array('error'=>$error_msg));
163             }
164             $obj = DataObject::get_by_id($cls, $id);
165             return Convert::array2json(array(
166                 'RatingInt' => $obj->getRatingInt()->getValue(),
167                 'RatingFloat' => $obj->getRatingFloat()->Nice(),
168                 'Votes' => $obj->getVotes()->getValue(),
169                 'AlreadyVote' => $obj->getAlreadyVote()
170             ));
171         }
172         if($error && isset($error_msg)){
173             return $this->renderWith(array('Page'),array('Title'=>_t('Rating.ErrorTitle','Ошибка'),'Content' => $error_msg));
174         }
175         Director::redirectBack();
176         return null;
177     }
178 
179 }
180 
[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -
Webylon 3.1 API Docs API documentation generated by ApiGen 2.8.0