]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiPoll.php
oops, checked in the debug version. revert to IP check on
[SourceForge/phpwiki.git] / lib / plugin / WikiPoll.php
1 <?php // -*-php-*-
2 rcs_id('$Id: WikiPoll.php,v 1.6 2004-03-01 18:08:53 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.6 $");
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 bar($percent) {
233         global $Theme;
234         return HTML(HTML::img(array('src' => $Theme->getImageUrl('leftbar'),
235                                     'alt' => '<')),
236                     HTML::img(array('src' => $Theme->getImageUrl('mainbar'),
237                                     'alt' => '-',
238                                     'width' => sprintf("%02d",$percent),
239                                     'height' => 14)),
240                     HTML::img(array('src' => $Theme->getImageUrl('rightbar'),
241                                     'alt' => '>')));
242     }
243
244     function doPoll($page, $request, $answers, $readonly = false) {
245         $question = $this->_args['question'];
246         $answer   = $this->_args['answer'];
247         $html = HTML::table(array('cellspacing' => 2));
248         $init = isset($question[0]) ? 0 : 1;
249         for ($i = $init; $i <= count($question); $i++) {
250             if (!isset($question[$i])) break;
251             $poll = $page->get('poll');
252             @$poll['data']['all'][$i]++;
253             $q = $question[$i]; 
254             if (!isset($answer[$i]))
255                 trigger_error(fmt("Missing %s for %s","answer"."[$i]","question"."[$i]"),
256                               E_USER_ERROR);
257             if (!$readonly)
258                 $page->set('poll',$poll);
259             $a = $answer[$i];
260             $result = (isset($answers[$i])) ? $answers[$i] : -1;
261             if (! is_array($a) ) {
262                 $checkbox = HTML::input(array('type' => 'checkbox',
263                                               'name' => "answer[$i]",
264                                               'value' => $a));
265                 if ($result >= 0)
266                     $checkbox->setAttr('checked',1);
267                 if (!$readonly)
268                     list($percent,$count,$all) = $this->storeResult(&$page, $i, $result ? 1 : 0);
269                 else 
270                     list($percent,$count,$all) = $this->getResult(&$page, $i, 1);
271                 $print = sprintf(_("  %d%% (%d/%d)"),$percent,$count,$all);
272                 $html->pushContent(HTML::tr(HTML::th(array('colspan' => 4,'align'=>'left'),$q)));
273                 $html->pushContent(HTML::tr(HTML::td($checkbox),
274                                             HTML::td($a),
275                                             HTML::td($this->bar($percent)),
276                                             HTML::td($print)));
277             } else {
278                 $html->pushContent(HTML::tr(HTML::th(array('colspan' => 4,'align'=>'left'),$q)));
279                 $row = HTML();
280                 if (!$readonly)
281                     $this->storeResult(&$page,$i,$answers[$i]);
282                 for ($j=0; $j <= count($a); $j++) {
283                     if (isset($a[$j])) {
284                         list($percent,$count,$all) = $this->getResult(&$page,$i,$j);
285                         $print = sprintf(_("  %d%% (%d/%d)"),$percent,$count,$all);
286                         $radio = HTML::input(array('type' => 'radio',
287                                                    'name' => "answer[$i]",
288                                                    'value' => $j));
289                         if ($result == $j)
290                             $radio->setAttr('checked',1);
291                         $row->pushContent(HTML::tr(HTML::td($radio),
292                                                    HTML::td($a[$j]),
293                                                    HTML::td($this->bar($percent)),
294                                                    HTML::td($print)));
295                     }
296                 }
297                 $html->pushContent($row);
298             }
299         }
300         if (!$readonly)
301             return HTML(HTML::h3(_("The result of this poll so far:")),$html,HTML::p(_("Thanks for participating!")));
302         else  
303             return HTML(HTML::h3(_("The result of this poll so far:")),$html);
304   
305     }
306     
307     function getResult($page,$i,$j) {
308         $poll = $page->get("poll");
309         @$count = $poll['data']['count'][$i][$j];
310         @$all = $poll['data']['all'][$i];
311         $percent = sprintf("%d", $count * 100.0 / $all);
312         return array($percent,$count,$all);
313     }
314     
315     function storeResult($page, $i, $j) {
316         $poll = $page->get("poll");
317         if (!$poll) {
318             $poll = array('data' => array('count' => array(),
319                                           'all'   => array()));
320         }
321         @$poll['data']['count'][$i][$j]++;
322         //@$poll['data']['all'][$i];
323         $page->set("poll",$poll);
324         $percent = sprintf("%d", $poll['data']['count'][$i][$j] * 100.0 / $poll['data']['all'][$i]);
325         return array($percent,$poll['data']['count'][$i][$j],$poll['data']['all'][$i]);
326     }
327
328 };
329
330 // $Log: not supported by cvs2svn $
331 // Revision 1.5  2004/03/01 16:11:13  rurban
332 // graphical enhancement
333 //
334 // Revision 1.4  2004/02/26 01:42:27  rurban
335 // don't cache this at all
336 //
337 // Revision 1.3  2004/02/24 03:54:46  rurban
338 // lock page, more questions, new require_least arg
339 //
340 // Revision 1.2  2004/02/24 03:21:46  rurban
341 // enabled require_all check in WikiPoll
342 // better handling of <20 min visiting client: display results so far
343 //
344 //
345
346 // For emacs users
347 // Local Variables:
348 // mode: php
349 // tab-width: 8
350 // c-basic-offset: 4
351 // c-hanging-comment-ender-p: nil
352 // indent-tabs-mode: nil
353 // End:
354 ?>