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

Last change on this file since 3417 was 3397, checked in by grum, 15 years ago

Add plugin MyPolls - this release is not published in PEM (functionnal but not tested yet...)

  • Property svn:executable set to *
File size: 18.6 KB
Line 
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
214        if(!isset($_REQUEST['fmypolls_comment']))
215        { $_REQUEST['fmypolls_comment']=''; }
216        $this->do_vote($poll_id, $_REQUEST['fmypolls_results'], $_REQUEST['fmypolls_comment'], $user['user_id'], $_SERVER['REMOTE_ADDR'],  $user['language']);
217      }
218      $this->display_page($poll_id);
219    }
220  }
221
222  /*
223    initialise menubar's menu
224    called by menubar object when making menu
225  */
226  public function blockmanager_apply( $menu_ref_arr )
227  {
228    global $user, $template;
229    $menu = & $menu_ref_arr[0];
230
231    if ( ($block = $menu->get_block( 'mbMYPOLLS_menu' ) ) != null )
232    {
233      if($user['id']==2)
234      {
235        $vote_id = $_SERVER['REMOTE_ADDR'];
236      }
237      else
238      {
239        $vote_id = $user['id'];
240      }
241
242      $polls_list=$this->get_polls_list($vote_id, is_admin(), $user['language']);
243      $menu_list=array();
244
245      if(is_admin())
246      {
247        array_push($menu_list,
248          array(
249            'nfo' => "",
250            'text' => l10n('mypolls_admin_add'),
251            'link' => PHPWG_ROOT_PATH.$this->page_link.'&amp;f_tabsheet=polls&amp;action=create',
252            'edit' => ""
253          )
254        );
255      }
256
257      foreach($polls_list as $key => $val)
258      {
259        $nfo="";
260        if($val['enabled']=='n')
261        { $nfo.='<i>['.l10n('mypolls_menu_not_enabled').']</i>'; }
262        if($val['visible']=='n')
263        { $nfo.='<i>['.l10n('mypolls_menu_not_visible').']</i>'; }
264        if($val['public_results']=='n')
265        { $nfo.='<i>['.l10n('mypolls_menu_not_publicr').']</i>'; }
266        array_push($menu_list,
267          array(
268            'nfo' => $nfo,
269            'text' => $val['title'],
270            'link' => './index.php?/'.$this->section_name.'/'.$val['id'],
271            'edit' => (is_admin())?PHPWG_ROOT_PATH.$this->page_link."&amp;f_tabsheet=polls&amp;action=modify&amp;fmypolls_att_id=".$val['id']:""
272          )
273        );
274      }
275
276      $block->set_title($this->my_config['mypolls_menubar_title'][$user['language']]);
277      $block->template = dirname(__FILE__).'/templates/mypolls_public_menu.tpl';
278      $block->data = $menu_list;
279    }
280
281  }
282
283
284  protected function extract_poll_id_from_uri()
285  {
286    $poll_id=explode($this->section_name.'/', $_SERVER['REQUEST_URI']);
287    $poll_id=explode('&', $poll_id[1]);
288
289    return($poll_id[0]);
290  }
291
292
293
294  /* ---------------------------------------------------------------------------
295    FUNCTIONS TO MANAGE POLL'S VOTES
296  --------------------------------------------------------------------------- */
297
298  /*
299    analyse formated string "fq_N_a_M_P"
300    return an array(N,M,P)
301  */
302  protected function analyse_answer($answer)
303  {
304    $tmp=explode("_",$answer);
305    if(!isset($tmp[4]))
306    { $tmp[4]=1; }
307    $return=array($tmp[1],$tmp[3],$tmp[4]);
308    return($return);
309  }
310
311  /*
312    do vote
313    return true if Ok, else a number
314      -1 : database problem
315      -2 : user has already vote
316      -3 : ip has already vote
317  */
318  protected function do_vote($poll_id, $vote_results, $vote_comment, $user_id, $ip, $lang)
319  {
320    $vote_resultsa=unserialize(stripslashes($vote_results));
321
322    if($user_id==2) { $vote_id = $ip; } else { $vote_id = $user_id; }
323    $sql='INSERT INTO '.$this->tables['polls_votes']."
324          VALUES ('".$poll_id."',
325                  '".$vote_id."',
326                  '".date('Y-m-d H:i:s')."',
327                  '".htmlspecialchars(stripslashes($vote_comment), ENT_QUOTES)."')";
328    if(pwg_query($sql))
329    {
330      $sql="UPDATE ".$this->tables['polls']."
331            SET total_votes = total_votes + 1,
332                last_vote = '".date('Y-m-d H:i:s')."',
333                visit_without_vote = visit_without_vote - 1";
334      if($vote_comment!="")
335      {
336        $sql.=", nb_comments = nb_comments + 1 ";
337      }
338      $sql.=" WHERE id = '".$poll_id."' ";
339      if(pwg_query($sql))
340      {
341        foreach($vote_resultsa as $key => $val)
342        {
343          $nb_votes=0;
344          //first, updating "nb_votes, used for ordering result and apply frequency
345          foreach($val as $key2 => $val2)
346          {
347            $vote_result=$this->analyse_answer($val2);
348            $sql="UPDATE ".$this->tables['polls_answers']."
349                  SET nb_votes = nb_votes + ".$vote_result[2]."
350                  WHERE id_poll = '".$poll_id."'
351                    AND id_question = '".$vote_result[0]."'
352                    AND answer_num = '".$vote_result[1]."'; ";
353            $result=pwg_query($sql);
354
355            $sql="UPDATE ".$this->tables['polls_answers_lang']."
356                  SET nb_votes = nb_votes + ".$vote_result[2]."
357                  WHERE id_poll = '".$poll_id."'
358                    AND id_question = '".$vote_result[0]."'
359                    AND id_answer = '".$vote_result[1]."'
360                    AND lang = '".$lang."' ";
361            $result=pwg_query($sql);
362            $nb_votes+=$vote_result[2];
363          }
364          //"nb_votes" updated, reload order and apply frequency
365          $question_num=$vote_result[0];
366          $poll_answers=$this->get_poll_answers($poll_id, $question_num, $lang, " nb_votes ASC, ans_order ASC", true);
367          $num=0;
368          foreach($val as $key2 => $val2)
369          {
370            $vote_result=$this->analyse_answer($val2);
371            if($vote_result[2]!=$poll_answers[$vote_result[1]]['order'])
372            {
373              $sql="UPDATE ".$this->tables['polls_answers']."
374                    SET frequency = frequency + 1,
375                        ans_order = '".$poll_answers[$vote_result[1]]['order']."'
376                    WHERE id_poll = '".$poll_id."'
377                    AND id_question = '".$vote_result[0]."'
378                    AND answer_num = '".$vote_result[1]."'; ";
379              $result=pwg_query($sql);
380            }
381            else
382            {
383              $sql="UPDATE ".$this->tables['polls_answers']."
384                    SET ans_order = '".$poll_answers[$vote_result[1]]['order']."'
385                    WHERE id_poll = '".$poll_id."'
386                    AND id_question = '".$vote_result[0]."'
387                    AND answer_num = '".$vote_result[1]."'; ";
388              $result=pwg_query($sql);
389            }
390          }
391
392          $sql="UPDATE ".$this->tables['polls_questions']."
393                SET nb_votes = nb_votes + ".$nb_votes."
394                WHERE id_poll = '".$poll_id."'
395                  AND question_num = '".$vote_result[0]."' ;";
396          $result=pwg_query($sql);
397        }
398      }
399    }
400  }
401
402  /*
403    looks if user/ip has already make a vote
404      return true if yes, else false
405  */
406  protected function get_user_already_vote($poll_id, $user_id, $ip)
407  {
408    $sql="SELECT user_id FROM ".$this->tables['polls_votes']."
409          WHERE poll_id = '".$poll_id."'
410            AND user_id = '".$ip."'
411          UNION
412          SELECT user_id FROM ".$this->tables['polls_votes']."
413          WHERE poll_id = '".$poll_id."'
414            AND user_id = '".$user_id."'";
415    $result=pwg_query($sql);
416    if($result)
417    {
418      if(mysql_num_rows($result)>0)
419      { return(true); }
420    }
421    return(false);
422  }
423
424  /*
425    count visit on vote's page
426    $step=
427      'before' = before vote
428      'after' = after vote
429  */
430  protected function count_visit($poll_id, $step)
431  {
432    $field=array('before' => 'visit_without_vote', 'after' => 'visit_after_vote');
433    $sql="UPDATE ".$this->tables['polls']."
434          SET ".$field[$step]." = ".$field[$step]." + 1
435          WHERE id = '".$poll_id."'";
436    pwg_query($sql);
437  }
438
439  /*
440    return user's group as an array
441  */
442  protected function get_user_groups($user_id)
443  {
444    $returned=array();
445    $sql="SELECT group_id FROM ".USER_GROUP_TABLE."
446          WHERE user_id = ".$user_id." ";
447    $result=pwg_query($sql);
448    if($result)
449    {
450      while($row=mysql_fetch_assoc($result))
451      {
452        array_push($returned, $row['group_id']);
453      }
454    }
455    return($returned);
456  }
457
458  /* ---------------------------------------------------------------------------
459    ajax functions
460  --------------------------------------------------------------------------- */
461  /*
462    return ajax content if request is ajax else return nothing (script allowed to continue)
463  */
464  public function return_ajax_content()
465  {
466    global $user, $ajax;
467    if(isset($_REQUEST['ajaxfct']))
468    {
469      $poll_id=$this->extract_poll_id_from_uri();
470      //$user['language'] = $_REQUEST['lang'];
471      switch($_REQUEST['ajaxfct'])
472      {
473        case 'poll_question_blocks':
474          $result=$this->ajax_poll_question_blocks($poll_id, $_REQUEST['question'], $_REQUEST['lang']);
475          break;
476        case 'poll_comment_list':
477          $result=$this->ajax_poll_comment_list($poll_id, $_REQUEST['vpage']);
478          break;
479      }
480      $this->ajax->return_result($result);
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.