]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiPoll.php
don't cache this at all
[SourceForge/phpwiki.git] / lib / plugin / WikiPoll.php
1 <?php // -*-php-*-
2 rcs_id('$Id: WikiPoll.php,v 1.4 2004-02-26 01:42:27 rurban Exp $');
3 /*
4  Copyright 2004 $ThePhpWikiProgrammingTeam
5  
6  This file is part of PhpWiki.
7
8  PhpWiki is free software; you can redistribute it and/or modify
9  it under the terms of the GNU General Public License as published by
10  the Free Software Foundation; either version 2 of the License, or
11  (at your option) any later version.
12
13  PhpWiki is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with PhpWiki; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22 /**
23  * This plugin provides configurable polls.
24  *
25  * Usage:
26 <?plugin WikiPoll require_all=0 require_least=2
27            question[1]="Do you like PhpWiki?"
28              answer[1][1]="Yes" answer[1][2]="Do not know" answer[1][3]="No"
29            question[2]="Do you have PhpWiki installed by your own?"
30              answer[2][1]="Yes" answer[2][2]="No"
31            question[3]="Did you install any other wiki engine?"
32              answer[3][1]="Yes" answer[3][2]="No"
33            question[4]="What wiki engine do you like most?"
34              answer[4][1]="c2Wiki" answer[4][2]="MoinMoin" answer[4][3]="PhpWiki"
35              answer[4][4]="usemod" answer[4][5]="Twiki" answer[4][5]="guiki"
36              answer[4][6]="Other"
37            question[5]="Which PhpWiki version do you use?"
38              answer[5][1]="1.2.x" answer[5][2]="1.3. 1-2" answer[5][3]="1.3.3-4"
39              answer[5][4]="1.3.5-8"
40 ?>
41  *
42  * Administration:
43  * <?plugin WikiPoll page=PhpWikiPoll admin=1 ?>
44  * and protect this page properly (e.g. PhpWikiPoll/Admin)
45  *
46  * TODO:
47  *     admin page (view and reset statistics)
48  *     for now only radio, support checkboxes (multiple selections) also?
49  *
50  * Author: ReiniUrban
51  */
52
53 class WikiPlugin_WikiPoll
54 extends WikiPlugin
55 {
56     var $_args; 
57     
58     function getName () {
59         return _("WikiPoll");
60     }
61
62     function getDescription () {
63         return _("Enable configurable polls");
64     }
65
66     function getVersion() {
67         return preg_replace("/[Revision: $]/", '',
68                             "\$Revision: 1.4 $");
69     }
70
71     function getDefaultArguments() {
72         return array('page'        => '[pagename]',
73                      'admin'       => false,
74                      'require_all' => 1,   // 1 if all questions must be answered
75                      'require_least' => 0, // how many at least
76                     );
77     }
78
79     function getArgs($argstr, $request=false, $defaults = false) {
80         if ($defaults === false)
81             $defaults = $this->getDefaultArguments();
82         //Fixme: on POST argstr is empty
83         $args = array();
84         list ($argstr_args, $argstr_defaults) = $this->parseArgStr($argstr);
85         if (isset($argstr_args["question_1"])) {
86           $args['question'] = $this->str2array("question",$argstr_args);
87           $args['answer'] = array();
88           for ($i = 0; $i <= count($args['question']); $i++) {
89               if ($array = $this->str2array(sprintf("%s_%d","answer",$i),$argstr_args))
90                   $args['answer'][$i] = $array;
91           }
92         }
93         
94         if (!empty($defaults))
95           foreach ($defaults as $arg => $default_val) {
96             if (isset($argstr_args[$arg]))
97                 $args[$arg] = $argstr_args[$arg];
98             elseif ( $request and ($argval = $request->getArg($arg)) !== false )
99                 $args[$arg] = $argval;
100             elseif (isset($argstr_defaults[$arg]))
101                 $args[$arg] = (string) $argstr_defaults[$arg];
102             else
103                 $args[$arg] = $default_val;
104
105             if ($request)
106                 $args[$arg] = $this->expandArg($args[$arg], $request);
107
108             unset($argstr_args[$arg]);
109             unset($argstr_defaults[$arg]);
110         }
111
112         foreach (array_merge($argstr_args, $argstr_defaults) as $arg => $val) {
113             if (!preg_match("/^(answer_|question_)/",$arg))
114                 trigger_error(sprintf(_("argument '%s' not declared by plugin"),
115                                       $arg), E_USER_NOTICE);
116         }
117
118         return $args;
119     }
120     
121     function handle_plugin_args_cruft($argstr, $args) {
122         $argstr = str_replace("\n"," ",$argstr);
123         $argstr = str_replace(array("[","]"),array("_",""),$argstr);
124         $this->_args = $this->getArgs($argstr, $GLOBALS['request']);
125         return;
126     }
127
128     function str2array($var, $obarray=false) {
129         if (!$obarray) $obarray = $GLOBALS;
130         $i = 0; $array = array();
131         $name = sprintf("%s_%d",$var,$i);
132         if (isset($obarray[$name])) $array[$i] = $obarray[$name];
133         do {
134           $i++;
135           $name = sprintf("%s_%d",$var,$i);
136           if (isset($obarray[$name])) $array[$i] = $obarray[$name];
137         } while (isset($obarray[$name]));
138         return $array;
139     }
140     
141     function run($dbi, $argstr, &$request, $basepage) {
142         $request->setArg('nocache','purge');
143         $args = $this->getArgs($argstr, $request);
144         if (!$args['page'])
145             return $this->error("No page specified");
146         if (!empty($args['admin']) and $request->_user->isAdmin()) {
147             // reset statistics
148             return $this->doPollAdmin($dbi, $request, $page);
149         }
150         extract($this->_args);
151         $page = $dbi->getPage($args['page']);
152         // check ip and last visit
153         $poll = $page->get("poll");
154         $ip = $_SERVER['REMOTE_ADDR'];
155         $disable_submit = false;
156         if (isset($poll['ip'][$ip]) and ((time() - $poll['ip'][$ip]) < 20*60)) {
157             //view at least the result or disable the Go button
158             $html = HTML(HTML::strong(
159                         _("Sorry! You must wait at least 20 minutes until you can vote again!")));
160             $html->pushContent($this->doPoll(&$page, &$request, $request->getArg('answer'),true));
161             return $html;
162         }
163             
164         $poll['ip'][$ip] = time();
165         // purge older ip's
166         foreach ($poll['ip'] as $ip => $time) {
167             if ((time() - $time) > 21*60)
168                 unset($poll['ip'][$ip]);
169         }
170         $html = HTML::form(array('action' => $request->getPostURL(),
171                                  'method' => 'POST'));
172
173         if ($request->isPost()) {
174             // checkme: check if all answers are answered
175             if ($request->getArg('answer') and (
176                  ($args['require_all'] and
177                   count($request->getArg('answer')) == count($question))
178                  or 
179                  ($args['require_least'] and
180                   count($request->getArg('answer')) >= $args['require_least']))) {
181                 $page->set("poll",$poll);
182                 // update statistics and present them the user
183                 return $this->doPoll(&$page, &$request, $request->getArg('answer'));
184             } else {
185                 $html->pushContent(HTML::p(HTML::strong(_("Not enough questions answered!"))));
186             }
187         }
188        
189         $init = isset($question[0]) ? 0 : 1;
190         for ($i = $init; $i <= count($question); $i++) {
191             if (!isset($question[$i])) break;
192             $q = $question[$i]; 
193             if (!isset($answer[$i]))
194                 trigger_error(fmt("Missing %s for %s","answer"."[$i]","question"."[$i]"),
195                               E_USER_ERROR);
196             $a = $answer[$i];
197             if (! is_array($a)) {
198                 // a simple checkbox
199                 $html->pushContent(HTML::p(HTML::strong($q)));
200                 $html->pushContent(HTML::div(
201                                        HTML::input(array('type' => 'checkbox',
202                                                          'name' => "answer[$i]",
203                                                          'value' => 1)),
204                                        HTML::raw("&nbsp;"), $a));
205             } else {
206                 $row = HTML();
207                 for ($j=0; $j <= count($a); $j++) {
208                     if (isset($a[$j]))
209                         $row->pushContent(HTML::div(
210                                               HTML::input(array('type' => 'radio',
211                                                                 'name' => "answer[$i]",
212                                                                 'value' => $j)),
213                                               HTML::raw("&nbsp;"), $a[$j]));
214                 }
215                 $html->pushContent(HTML::p(HTML::strong($q)),$row);
216             }
217         }
218         if (!$disable_submit)
219             $html->pushContent(HTML::p(
220                 HTML::input(array('type' => 'submit',
221                                   'name' => "WikiPoll",
222                                   'value' => _("Ok"))),
223                 HTML::input(array('type' => 'reset',
224                                   'name' => "reset",
225                                   'value' => _("Reset")))));
226         else 
227              $html->pushContent(HTML::p(),HTML::strong(
228                  _("Sorry! You must wait at least 20 minutes until you can vote again!")));
229         return $html;
230     }
231
232     function doPoll($page, $request, $answers, $readonly = false) {
233         $question = $this->_args['question'];
234         $answer   = $this->_args['answer'];
235         $html = HTML::table(array('cellspacing' => 2));
236         $init = isset($question[0]) ? 0 : 1;
237         for ($i = $init; $i <= count($question); $i++) {
238             if (!isset($question[$i])) break;
239             $poll = $page->get('poll');
240             @$poll['data']['all'][$i]++;
241             $q = $question[$i]; 
242             if (!isset($answer[$i]))
243                 trigger_error(fmt("Missing %s for %s","answer"."[$i]","question"."[$i]"),
244                               E_USER_ERROR);
245             if (!$readonly)
246                 $page->set('poll',$poll);
247             $a = $answer[$i];
248             if (! is_array($a) ) {
249                 $checkbox = HTML::input(array('type' => 'checkbox',
250                                               'name' => "answer[$i]",
251                                               'value' => $a));
252                 if ($answers[$i])
253                     $checkbox->setAttr('checked',1);
254                 if (!$readonly)
255                     list($percent,$count,$all) = $this->storeResult(&$page, $i, $answers[$i] ? 1 : 0);
256                 else 
257                     list($percent,$count,$all) = $this->getResult(&$page, $i, 1);
258                 $result = sprintf(_("  %d%% selected this (%d/%d)"),$percent,$count,$all);
259                 $html->pushContent(HTML::tr(HTML::th(array('colspan' => 3,'align'=>'left'),$q)));
260                 $html->pushContent(HTML::tr(HTML::td($checkbox),
261                                             HTML::td($a),
262                                             HTML::td($result)));
263             } else {
264                 $html->pushContent(HTML::tr(HTML::th(array('colspan' => 3,'align'=>'left'),$q)));
265                 $row = HTML();
266                 if (!$readonly)
267                     $this->storeResult(&$page,$i,$answers[$i]);
268                 for ($j=0; $j <= count($a); $j++) {
269                     if (isset($a[$j])) {
270                         list($percent,$count,$all) = $this->getResult(&$page,$i,$j);
271                         $result = sprintf(_("  %d%% selected this (%d/%d)"),$percent,$count,$all);
272                         $radio = HTML::input(array('type' => 'radio',
273                                                    'name' => "answer[$i]",
274                                                    'value' => $j));
275                         if ($answers[$i] == $j)
276                             $radio->setAttr('checked',1);
277                         $row->pushContent(HTML::tr(HTML::td($radio),
278                                                    HTML::td($a[$j]),
279                                                    HTML::td($result)));
280                     }
281                 }
282                 $html->pushContent($row);
283             }
284         }
285         if (!$readonly)
286             return HTML(HTML::h3(_("The result of this poll so far:")),$html,HTML::p(_("Thanks for participating!")));
287         else  
288             return HTML(HTML::h3(_("The result of this poll so far:")),$html);
289   
290     }
291     
292     function getResult($page,$i,$j) {
293         $poll = $page->get("poll");
294         @$count = $poll['data']['count'][$i][$j];
295         @$all = $poll['data']['all'][$i];
296         $percent = sprintf("%d", $count * 100.0 / $all);
297         return array($percent,$count,$all);
298     }
299     
300     function storeResult($page, $i, $j) {
301         $poll = $page->get("poll");
302         if (!$poll) {
303             $poll = array('data' => array('count' => array(),
304                                           'all'   => array()));
305         }
306         @$poll['data']['count'][$i][$j]++;
307         //@$poll['data']['all'][$i];
308         $page->set("poll",$poll);
309         $percent = sprintf("%d", $poll['data']['count'][$i][$j] * 100.0 / $poll['data']['all'][$i]);
310         return array($percent,$poll['data']['count'][$i][$j],$poll['data']['all'][$i]);
311     }
312
313 };
314
315 // $Log: not supported by cvs2svn $
316 // Revision 1.3  2004/02/24 03:54:46  rurban
317 // lock page, more questions, new require_least arg
318 //
319 // Revision 1.2  2004/02/24 03:21:46  rurban
320 // enabled require_all check in WikiPoll
321 // better handling of <20 min visiting client: display results so far
322 //
323 //
324
325 // For emacs users
326 // Local Variables:
327 // mode: php
328 // tab-width: 8
329 // c-basic-offset: 4
330 // c-hanging-comment-ender-p: nil
331 // indent-tabs-mode: nil
332 // End:
333 ?>