source: extensions/mypolls/mypolls_pip.class.inc.php @ 7690

Last change on this file since 7690 was 3680, checked in by grum, 15 years ago

Update MyPolls to 2.1.0 alpha-2
Minor changes (ajax management is modified to be compatible with AMM 2.1.0)

  • Property svn:executable set to *
File size: 18.6 KB
RevLine 
[3397]1<?php
2/* -----------------------------------------------------------------------------
3  Plugin     : MyPolls.2
4  Author     : Grum
5    email    : grum@piwigo.org
6    website  : http://photos.grum.dnsalias.com
7
8    << May the Little SpaceFrog be with you ! >>
9  ------------------------------------------------------------------------------
10  See main.inc.php for release information
11
12  MyPolls_PIP : classe to manage plugin public pages
13
14  --------------------------------------------------------------------------- */
15
16include_once('mypolls_root.class.inc.php');
17include_once(PHPWG_PLUGINS_PATH.'grum_plugins_classes-2/public_integration.class.inc.php');
18
19class MyPolls_PIP extends MyPolls_root
20{
21  protected $section_page;
22
23  public function MyPolls_PIP($prefixeTable, $filelocation)
24  {
25    parent::__construct($prefixeTable, $filelocation);
26    $this->load_config();
27
28    // don't create this object inside root classe otherwise header is modified
29    // everywhere in admin pages
30    $this->ajax = new Ajax();
31
32    $this->section_page = new public_integration($this->section_name);
33    $this->init_events();
34  }
35
36  /*
37    load language file
38  */
39  public function load_lang()
40  {
41    global $lang;
42
43    load_language('plugin.lang', MYPOLLS_PATH);
44
45    // ajax is managed here ; this permit to use user&language properties inside
46    // ajax content
47    $this->return_ajax_content();
48  }
49
50  /*
51    initialize events call for the plugin
52  */
53  public function init_events()
54  {
55    parent::init_events();
56    $this->section_page->set_callback_page_function(array(&$this, 'manage_page'));
57    $this->section_page->init_events();
58    add_event_handler('blockmanager_apply', array(&$this, 'blockmanager_apply') );
59    add_event_handler('loading_lang', array(&$this, 'load_lang'));
60    add_event_handler('loc_end_page_header', array(&$this->css, 'apply_CSS'));
61  }
62
63
64
65  /* -------------------------------------------------------------------------
66    FUNCTIONS TO MANAGE POLL'S DISPLAY
67  ------------------------------------------------------------------------- */
68
69  /*
70    display mypolls page ; no parameters, all is in $_REQUEST
71    this function is a called by a menubar's callback only when it is necessary
72  */
73  protected function display_page($poll_id)
74  {
75    global $template, $user;
76
77    $poll_values=$this->get_poll_values($poll_id, $user['language']);
78    if(!$poll_values)
79    {
80      page_not_found('This page does not exist', 'index.php?');
81      return(false);
82    }
83
84    $users = new users($poll_values['allowed_users']);
85    $groups = new groups($poll_values['allowed_groups']);
86    $datas = array();
87
88    $user_groups=$this->get_user_groups($user['id']);
89
90    //looks if user/group is allowed to access page
91    if((!$users->is_allowed($user['status']) ||
92      (($poll_values['allowed_groups']!='') && !$groups->are_allowed($user_groups))) &&
93      !is_admin())
94    {
95      page_not_found('User not allowed', 'index.php?');
96    }
97
98    if($user['id']!=2)
99    {
100      $datas['GENERIC_TEXT']=$this->my_config['mypolls_generic_text_users'][$user['language']];
101    }
102    else
103    {
104      $datas['GENERIC_TEXT']=$this->my_config['mypolls_generic_text_guests'][$user['language']];
105    }
106
107    $datas['TITLE']=$poll_values['title'];
108    //displayed nfo even if results are not public
109    $datas['DESCRIPTION']=html_entity_decode($poll_values['description'], ENT_QUOTES);
110
111
112    if(!$this->get_user_already_vote($poll_id, $user['id'], $_SERVER['REMOTE_ADDR']))
113    {
114      // no vote for this poll by user, display poll in 'vote' mode
115
116      //count visit on page
117      $this->count_visit($poll_id, 'before');
118      $first_question=array('mono' => 0, 'multi' => 1);
119
120      $template_file=dirname($this->filelocation).'/templates/mypolls_public_question.tpl';
121
122      $datas['ATT_ID']=$poll_id;
123      $datas['AJAX_URL_POLL_DETAIL']='./index.php?/'.$this->section_name.'/'.$poll_id.'&ajaxfct=poll_question_blocks';
124      $datas['LANG']=$user['language'];
125      $datas['FIRST_QUESTION']=$first_question[$poll_values['display_type']];
126      $datas['NBQUESTIONS']=$poll_values['nb_questions'];
127    }
128    else
129    {
130      //user/ip have already voted
131      $template_file=dirname($this->filelocation).'/templates/mypolls_public_results.tpl';
132
133      $datas['AFTER_VOTE_TEXT']=html_entity_decode($poll_values['after_vote_text'], ENT_QUOTES);
134
135      if($poll_values['public_results']=='n')
136      {
137        $not_public_text=html_entity_decode($this->my_config['mypolls_not_public_results'][$user['language']]);
138        if($not_public_text=="")
139        {
140          $not_public_text=l10n('mypolls_not_public_results');
141        }
142        $datas['NOT_PUBLIC_RESULT_TEXT']=$not_public_text;
143      }
144      else
145      {
146        if($poll_values['show_comments']=='y')
147        {
148          $datas["AJAX_URL_POLL_COMMENT_LIST"]='./index.php?/'.$this->section_name.'/'.$poll_id.'&ajaxfct=poll_comment_list&vpage=';
149        }
150         $this->display_results_block($poll_id, $user['language'], $poll_values);
151      }
152
153      //count visit on page
154      $this->count_visit($poll_id, 'after');
155    }
156
157    $template->set_filename('body_page', $template_file);
158    $template->assign('TITLE', $datas['TITLE']);
159    $template->assign('datas', $datas);
160
161
162    // add icon in title bar
163    if (is_admin())
164    {
165      $this->make_icons(PHPWG_ROOT_PATH.$this->page_link."&amp;f_tabsheet=polls&amp;action=modify&amp;fmypolls_att_id=".$poll_id, 'mypolls_msg_modify_poll','preferences.png', 'edit', 'icon_category_edit');
166    }
167    $this->make_icons(make_index_url(),'return to homepage', 'home.png', 'home', 'icon_home');
168
169    //remote icons from the title bar
170    unset($template->smarty->_tpl_vars["U_MODE_CREATED"]);
171    unset($template->smarty->_tpl_vars["U_MODE_POSTED"]);
172
173    $template->assign_var_from_handle('PLUGIN_INDEX_CONTENT_BEGIN', 'body_page');
174  }
175
176  protected function make_icons($url, $title, $icon, $alt, $id="")
177  {
178    global $template;
179
180    //method to make icon change with template
181    // assume yoga method by default
182    switch($template->smarty->_tpl_vars["themeconf"]['template'])
183    {
184      case 'gally':
185        $template->concat( 'PLUGIN_INDEX_ACTIONS',
186            '<li><a href="'.$url.'" title="'.l10n($title).'" class="button" '.(($id=="")?'':'id="'.$id.'"').'></a></li>');
187
188        break;
189      default:
190        $template->concat( 'PLUGIN_INDEX_ACTIONS',
191            '<li><a href="'.$url.'" title="'.l10n($title).'">
192            <img src="'.$template->smarty->_tpl_vars["themeconf"]['icon_dir'].'/'.$icon.'" class="button" alt="'.l10n($alt).'"/></a></li>');
193    }
194  }
195 
196
197  /*
198    analyse uri request, do vote and load the page
199  */
200  public function manage_page()
201  {
202    global $page, $user;
203
204    $this->load_lang();
205
206    if($page['section'] == $this->section_name)
207    {
208
209      $poll_id=$this->extract_poll_id_from_uri();
210
211      if((isset($_POST['submit_results']))&&(!$this->get_user_already_vote($poll_id, $user['user_id'], $_SERVER['REMOTE_ADDR'])))
212      {
213        if(!isset($_REQUEST['fmypolls_comment']))
214        { $_REQUEST['fmypolls_comment']=''; }
215        $this->do_vote($poll_id, $_REQUEST['fmypolls_results'], $_REQUEST['fmypolls_comment'], $user['user_id'], $_SERVER['REMOTE_ADDR'],  $user['language']);
216      }
217      $this->display_page($poll_id);
218    }
219  }
220
221  /*
222    initialise menubar's menu
223    called by menubar object when making menu
224  */
225  public function blockmanager_apply( $menu_ref_arr )
226  {
227    global $user, $template;
228    $menu = & $menu_ref_arr[0];
229
230    if ( ($block = $menu->get_block( 'mbMYPOLLS_menu' ) ) != null )
231    {
232      if($user['id']==2)
233      {
234        $vote_id = $_SERVER['REMOTE_ADDR'];
235      }
236      else
237      {
238        $vote_id = $user['id'];
239      }
240
241      $polls_list=$this->get_polls_list($vote_id, is_admin(), $user['language']);
242      $menu_list=array();
243
244      if(is_admin())
245      {
246        array_push($menu_list,
247          array(
248            'nfo' => "",
249            'text' => l10n('mypolls_admin_add'),
250            'link' => PHPWG_ROOT_PATH.$this->page_link.'&amp;f_tabsheet=polls&amp;action=create',
251            'edit' => ""
252          )
253        );
254      }
255
256      foreach($polls_list as $key => $val)
257      {
258        $nfo="";
259        if($val['enabled']=='n')
260        { $nfo.='<i>['.l10n('mypolls_menu_not_enabled').']</i>'; }
261        if($val['visible']=='n')
262        { $nfo.='<i>['.l10n('mypolls_menu_not_visible').']</i>'; }
263        if($val['public_results']=='n')
264        { $nfo.='<i>['.l10n('mypolls_menu_not_publicr').']</i>'; }
265        array_push($menu_list,
266          array(
267            'nfo' => $nfo,
268            'text' => $val['title'],
269            'link' => './index.php?/'.$this->section_name.'/'.$val['id'],
270            'edit' => (is_admin())?PHPWG_ROOT_PATH.$this->page_link."&amp;f_tabsheet=polls&amp;action=modify&amp;fmypolls_att_id=".$val['id']:""
271          )
272        );
273      }
274
275      $block->set_title($this->my_config['mypolls_menubar_title'][$user['language']]);
276      $block->template = dirname(__FILE__).'/templates/mypolls_public_menu.tpl';
277      $block->data = $menu_list;
278    }
279
280  }
281
282
283  protected function extract_poll_id_from_uri()
284  {
285    $poll_id=explode($this->section_name.'/', $_SERVER['REQUEST_URI']);
286    $poll_id=explode('&', $poll_id[1]);
287
288    return($poll_id[0]);
289  }
290
291
292
293  /* ---------------------------------------------------------------------------
294    FUNCTIONS TO MANAGE POLL'S VOTES
295  --------------------------------------------------------------------------- */
296
297  /*
298    analyse formated string "fq_N_a_M_P"
299    return an array(N,M,P)
300  */
301  protected function analyse_answer($answer)
302  {
303    $tmp=explode("_",$answer);
304    if(!isset($tmp[4]))
305    { $tmp[4]=1; }
306    $return=array($tmp[1],$tmp[3],$tmp[4]);
307    return($return);
308  }
309
310  /*
311    do vote
312    return true if Ok, else a number
313      -1 : database problem
314      -2 : user has already vote
315      -3 : ip has already vote
316  */
317  protected function do_vote($poll_id, $vote_results, $vote_comment, $user_id, $ip, $lang)
318  {
319    $vote_resultsa=unserialize(stripslashes($vote_results));
320
321    if($user_id==2) { $vote_id = $ip; } else { $vote_id = $user_id; }
322    $sql='INSERT INTO '.$this->tables['polls_votes']."
323          VALUES ('".$poll_id."',
324                  '".$vote_id."',
325                  '".date('Y-m-d H:i:s')."',
326                  '".htmlspecialchars(stripslashes($vote_comment), ENT_QUOTES)."')";
327    if(pwg_query($sql))
328    {
329      $sql="UPDATE ".$this->tables['polls']."
330            SET total_votes = total_votes + 1,
331                last_vote = '".date('Y-m-d H:i:s')."',
332                visit_without_vote = visit_without_vote - 1";
333      if($vote_comment!="")
334      {
335        $sql.=", nb_comments = nb_comments + 1 ";
336      }
337      $sql.=" WHERE id = '".$poll_id."' ";
338      if(pwg_query($sql))
339      {
340        foreach($vote_resultsa as $key => $val)
341        {
342          $nb_votes=0;
343          //first, updating "nb_votes, used for ordering result and apply frequency
344          foreach($val as $key2 => $val2)
345          {
346            $vote_result=$this->analyse_answer($val2);
347            $sql="UPDATE ".$this->tables['polls_answers']."
348                  SET nb_votes = nb_votes + ".$vote_result[2]."
349                  WHERE id_poll = '".$poll_id."'
350                    AND id_question = '".$vote_result[0]."'
351                    AND answer_num = '".$vote_result[1]."'; ";
352            $result=pwg_query($sql);
353
354            $sql="UPDATE ".$this->tables['polls_answers_lang']."
355                  SET nb_votes = nb_votes + ".$vote_result[2]."
356                  WHERE id_poll = '".$poll_id."'
357                    AND id_question = '".$vote_result[0]."'
358                    AND id_answer = '".$vote_result[1]."'
359                    AND lang = '".$lang."' ";
360            $result=pwg_query($sql);
361            $nb_votes+=$vote_result[2];
362          }
363          //"nb_votes" updated, reload order and apply frequency
364          $question_num=$vote_result[0];
365          $poll_answers=$this->get_poll_answers($poll_id, $question_num, $lang, " nb_votes ASC, ans_order ASC", true);
366          $num=0;
367          foreach($val as $key2 => $val2)
368          {
369            $vote_result=$this->analyse_answer($val2);
370            if($vote_result[2]!=$poll_answers[$vote_result[1]]['order'])
371            {
372              $sql="UPDATE ".$this->tables['polls_answers']."
373                    SET frequency = frequency + 1,
374                        ans_order = '".$poll_answers[$vote_result[1]]['order']."'
375                    WHERE id_poll = '".$poll_id."'
376                    AND id_question = '".$vote_result[0]."'
377                    AND answer_num = '".$vote_result[1]."'; ";
378              $result=pwg_query($sql);
379            }
380            else
381            {
382              $sql="UPDATE ".$this->tables['polls_answers']."
383                    SET ans_order = '".$poll_answers[$vote_result[1]]['order']."'
384                    WHERE id_poll = '".$poll_id."'
385                    AND id_question = '".$vote_result[0]."'
386                    AND answer_num = '".$vote_result[1]."'; ";
387              $result=pwg_query($sql);
388            }
389          }
390
391          $sql="UPDATE ".$this->tables['polls_questions']."
392                SET nb_votes = nb_votes + ".$nb_votes."
393                WHERE id_poll = '".$poll_id."'
394                  AND question_num = '".$vote_result[0]."' ;";
395          $result=pwg_query($sql);
396        }
397      }
398    }
399  }
400
401  /*
402    looks if user/ip has already make a vote
403      return true if yes, else false
404  */
405  protected function get_user_already_vote($poll_id, $user_id, $ip)
406  {
407    $sql="SELECT user_id FROM ".$this->tables['polls_votes']."
408          WHERE poll_id = '".$poll_id."'
409            AND user_id = '".$ip."'
410          UNION
411          SELECT user_id FROM ".$this->tables['polls_votes']."
412          WHERE poll_id = '".$poll_id."'
413            AND user_id = '".$user_id."'";
414    $result=pwg_query($sql);
415    if($result)
416    {
417      if(mysql_num_rows($result)>0)
418      { return(true); }
419    }
420    return(false);
421  }
422
423  /*
424    count visit on vote's page
425    $step=
426      'before' = before vote
427      'after' = after vote
428  */
429  protected function count_visit($poll_id, $step)
430  {
431    $field=array('before' => 'visit_without_vote', 'after' => 'visit_after_vote');
432    $sql="UPDATE ".$this->tables['polls']."
433          SET ".$field[$step]." = ".$field[$step]." + 1
434          WHERE id = '".$poll_id."'";
435    pwg_query($sql);
436  }
437
438  /*
439    return user's group as an array
440  */
441  protected function get_user_groups($user_id)
442  {
443    $returned=array();
444    $sql="SELECT group_id FROM ".USER_GROUP_TABLE."
445          WHERE user_id = ".$user_id." ";
446    $result=pwg_query($sql);
447    if($result)
448    {
449      while($row=mysql_fetch_assoc($result))
450      {
451        array_push($returned, $row['group_id']);
452      }
453    }
454    return($returned);
455  }
456
457  /* ---------------------------------------------------------------------------
458    ajax functions
459  --------------------------------------------------------------------------- */
460  /*
461    return ajax content if request is ajax else return nothing (script allowed to continue)
462  */
463  public function return_ajax_content()
464  {
465    global $user, $ajax;
466    if(isset($_REQUEST['ajaxfct']))
467    {
[3680]468      if($_REQUEST['ajaxfct'] == 'poll_question_blocks' || $_REQUEST['ajaxfct'] == 'poll_comment_list')
[3397]469      {
[3680]470        switch($_REQUEST['ajaxfct'])
471        {
472          case 'poll_question_blocks':
473            $result=$this->ajax_poll_question_blocks($this->extract_poll_id_from_uri(), $_REQUEST['question'], $_REQUEST['lang']);
474            break;
475          case 'poll_comment_list':
476            $result=$this->ajax_poll_comment_list($this->extract_poll_id_from_uri(), $_REQUEST['vpage']);
477            break;
478        }
479        $this->ajax->return_result($result);
[3397]480      }
481    }
482  }
483
484  protected function ajax_poll_question_blocks($poll_id, $question_num, $lang)
485  {
486    $local_tpl = new Template(MYPOLLS_PATH."templates/", "");
487    $local_tpl->set_filename('body_page',
488                  dirname($this->filelocation).'/templates/mypolls_public_question2.tpl');
489
490
491    $poll_values=$this->get_poll_values($poll_id, $lang);
492    $poll_questions=$this->get_poll_questions($poll_id, "", $lang);
493    $datas=array();
494
495    $numq=1;
496    foreach($poll_questions as $key => $val)
497    {
498      if(($question_num==0)||($numq==$question_num))
499      {
500        $ansnfo="";
501        switch($val['question_type'])
502        {
503          case 'multi':
504            $ansnfo=sprintf(l10n('mypolls_answer_maxi'), $val['multi_max_answers']);
505            break;
506          case 'order':
507            $ansnfo=l10n("mypolls_answer_order");
508            break;
509        }
510
511        $datas['question'][$numq]=array(
512          'NUMQ' => $numq,
513          'NBQ' => $poll_values['nb_questions'],
514          'DESCRIPTION' => html_entity_decode($val['description']),
515          'ANSNFO' => $ansnfo
516        );
517
518        $poll_answers=$this->get_poll_answers($poll_id, $val['question_num'], $lang);
519        foreach($poll_answers as $key2 => $val2)
520        {
521          $inputfield="";
522          switch($val['question_type'])
523          {
524            case 'mono':
525              $inputfield="<input type='radio' name='fq_".$val['question_num']."'
526                            id='iq_".$val['question_num']."_a_".$val2['answer_num']."'
527                            value='".$val2['answer_num']."'
528                            onclick='check_mono(\"fq_".$val['question_num']."\", ".$numq.")' > ";
529              break;
530            case 'multi':
531              $inputfield="<input type='checkbox' name='fq_".$val['question_num']."'
532                            id='iq_".$val['question_num']."_a_".$val2['answer_num']."'
533                            value='".$val2['answer_num']."'
534                            onclick='check_multi(".$val['multi_max_answers'].", \"fq_".$val['question_num']."\", ".$numq.")' >";
535              break;
536            case 'order':
537              $inputfield="<select name='fq_".$val['question_num']."'
538                            id='iq_".$val['question_num']."_a_".$val2['answer_num']."'
539                            onchange='check_order(\"fq_".$val['question_num']."\", ".$numq.", \"iq_".$val['question_num']."_a_".$val2['answer_num']."\")' >";
540              $inputfield.="<option value='-'>-</option>";
541              for($i=1;$i<=count($poll_answers);$i++)
542              {
543                $inputfield.="<option value='$i'>$i</option>";
544              }
545              $inputfield.="</select>";
546              break;
547          }
548
549          $datas['question'][$numq]['answers'][$val2['answer_num']]=array(
550            'INPUTFIELD' => $inputfield,
551            'ANSWER' => html_entity_decode($val2['answer'])
552          );
553        }
554      }
555      $numq++;
556    }
557
558    if(($question_num==$poll_values['nb_questions'])||($question_num==0))
559    {
560      $datas['LASTQUESTION']='y';
561      $datas['ALLOWCOMMENT']=$poll_values['allow_comment'];
562    }
563    else
564    {
565      $datas['NEXTQUESTION']=$question_num+1;
566    }
567
568    $local_tpl->assign("datas", $datas);
569
570    return($local_tpl->parse('body_page', true));
571  }
572
573} //class
574
575?>
Note: See TracBrowser for help on using the repository browser.