File: WikiPoll.php

package info (click to toggle)
phpwiki 1.3.12p3-5etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 16,956 kB
  • ctags: 21,608
  • sloc: php: 82,335; xml: 3,840; sh: 1,522; sql: 1,198; perl: 625; makefile: 562; awk: 28
file content (379 lines) | stat: -rw-r--r-- 15,403 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
<?php // -*-php-*-
rcs_id('$Id: WikiPoll.php,v 1.9 2004/06/16 10:38:59 rurban Exp $');
/*
 Copyright 2004 $ThePhpWikiProgrammingTeam
 
 This file is part of PhpWiki.

 PhpWiki is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 PhpWiki is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with PhpWiki; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
/**
 * This plugin provides configurable polls.
 *
 * Usage:
<?plugin WikiPoll require_all=0 require_least=2
           question[1]="Do you like PhpWiki?"
             answer[1][1]="Yes" answer[1][2]="Do not know" answer[1][3]="No"
           question[2]="Do you have PhpWiki installed by your own?"
             answer[2][1]="Yes" answer[2][2]="No"
           question[3]="Did you install any other wiki engine?"
             answer[3][1]="Yes" answer[3][2]="No"
           question[4]="What wiki engine do you like most?"
             answer[4][1]="c2Wiki" answer[4][2]="MoinMoin" answer[4][3]="PhpWiki"
             answer[4][4]="usemod" answer[4][5]="Twiki" answer[4][5]="guiki"
             answer[4][6]="Other"
           question[5]="Which PhpWiki version do you use?"
             answer[5][1]="1.2.x" answer[5][2]="1.3. 1-2" answer[5][3]="1.3.3-4"
             answer[5][4]="1.3.5-8"
?>
 *
 * Administration:
 * <?plugin WikiPoll page=PhpWikiPoll admin=1 ?>
 * and protect this page properly (e.g. PhpWikiPoll/Admin)
 *
 * TODO:
 *     admin page (view and reset statistics)
 *     for now only radio, support checkboxes (multiple selections) also?
 *
 * Author: ReiniUrban
 */

class WikiPlugin_WikiPoll
extends WikiPlugin
{
    var $_args;	
    
    function getName () {
        return _("WikiPoll");
    }

    function getDescription () {
        return _("Enable configurable polls");
    }

    function getVersion() {
        return preg_replace("/[Revision: $]/", '',
                            "\$Revision: 1.9 $");
    }

    function getDefaultArguments() {
        return array('page'        => '[pagename]',
                     'admin'       => false,
                     'require_all' => 1,   // 1 if all questions must be answered
                     'require_least' => 0, // how many at least
                    );
    }

    function getArgs($argstr, $request=false, $defaults = false) {
        if ($defaults === false)
            $defaults = $this->getDefaultArguments();
        //Fixme: on POST argstr is empty
        $args = array();
        list ($argstr_args, $argstr_defaults) = $this->parseArgStr($argstr);
        if (isset($argstr_args["question_1"])) {
          $args['question'] = $this->str2array("question",$argstr_args);
          $args['answer'] = array();
          for ($i = 0; $i <= count($args['question']); $i++) {
              if ($array = $this->str2array(sprintf("%s_%d","answer",$i),$argstr_args))
                  $args['answer'][$i] = $array;
          }
        }
        
        if (!empty($defaults))
          foreach ($defaults as $arg => $default_val) {
            if (isset($argstr_args[$arg]))
                $args[$arg] = $argstr_args[$arg];
            elseif ( $request and ($argval = $request->getArg($arg)) !== false )
                $args[$arg] = $argval;
            elseif (isset($argstr_defaults[$arg]))
                $args[$arg] = (string) $argstr_defaults[$arg];
            else
                $args[$arg] = $default_val;

            if ($request)
                $args[$arg] = $this->expandArg($args[$arg], $request);

            unset($argstr_args[$arg]);
            unset($argstr_defaults[$arg]);
        }

        foreach (array_merge($argstr_args, $argstr_defaults) as $arg => $val) {
            if (!preg_match("/^(answer_|question_)/",$arg))
                trigger_error(sprintf(_("argument '%s' not declared by plugin"),
                                      $arg), E_USER_NOTICE);
        }

        return $args;
    }
    
    function handle_plugin_args_cruft($argstr, $args) {
    	$argstr = str_replace("\n"," ",$argstr);
    	$argstr = str_replace(array("[","]"),array("_",""),$argstr);
    	$this->_args = $this->getArgs($argstr, $GLOBALS['request']);
        return;
    }

    function str2array($var, $obarray=false) {
    	if (!$obarray) $obarray = $GLOBALS;
    	$i = 0; $array = array();
    	$name = sprintf("%s_%d",$var,$i);
    	if (isset($obarray[$name])) $array[$i] = $obarray[$name];
    	do {
          $i++;
          $name = sprintf("%s_%d",$var,$i);
          if (isset($obarray[$name])) $array[$i] = $obarray[$name];
    	} while (isset($obarray[$name]));
    	return $array;
    }
    
    function run($dbi, $argstr, &$request, $basepage) {
        if (!isset($_SERVER))
            $_SERVER =& $GLOBALS['HTTP_SERVER_VARS'];
    	$request->setArg('nocache','purge');
        $args = $this->getArgs($argstr, $request);
        if (!$args['page'])
            return $this->error("No page specified");
        if (!empty($args['admin']) and $request->_user->isAdmin()) {
            // reset statistics
            return $this->doPollAdmin($dbi, $request, $page);
        }
	extract($this->_args);
	$page = $dbi->getPage($args['page']);
        // check ip and last visit
        $poll = $page->get("poll");
        $ip = $_SERVER['REMOTE_ADDR'];
        $disable_submit = false;
        if (isset($poll['ip'][$ip]) and ((time() - $poll['ip'][$ip]) < 20*60)) {
            //view at least the result or disable the Go button
            $html = HTML(HTML::strong(
                        _("Sorry! You must wait at least 20 minutes until you can vote again!")));
            $html->pushContent($this->doPoll($page, $request, $request->getArg('answer'),true));
            return $html;
        }
            
        $poll['ip'][$ip] = time();
        // purge older ip's
        foreach ($poll['ip'] as $ip => $time) {
            if ((time() - $time) > 21*60)
                unset($poll['ip'][$ip]);
        }
        $html = HTML::form(array('action' => $request->getPostURL(),
                                 'method' => 'POST'));

        if ($request->isPost()) {
            // checkme: check if all answers are answered
            if ($request->getArg('answer') and (
                 ($args['require_all'] and
                  count($request->getArg('answer')) == count($question))
                 or 
                 ($args['require_least'] and
                  count($request->getArg('answer')) >= $args['require_least']))) {
                $page->set("poll", $poll);
                // update statistics and present them the user
                return $this->doPoll($page, $request, $request->getArg('answer'));
            } else {
                $html->pushContent(HTML::p(HTML::strong(_("Not enough questions answered!"))));
            }
        }
       
        $init = isset($question[0]) ? 0 : 1;
        for ($i = $init; $i <= count($question); $i++) {
            if (!isset($question[$i])) break;
            $q = $question[$i]; 
            if (!isset($answer[$i]))
            	trigger_error(fmt("Missing %s for %s","answer"."[$i]","question"."[$i]"),
            	              E_USER_ERROR);
            $a = $answer[$i];
            if (! is_array($a)) {
                // a simple checkbox
                $html->pushContent(HTML::p(HTML::strong($q)));
                $html->pushContent(HTML::div(
                                       HTML::input(array('type' => 'checkbox',
                                                         'name' => "answer[$i]",
                                                         'value' => 1)),
                                       HTML::raw("&nbsp;"), $a));
            } else {
                $row = HTML();
                for ($j=0; $j <= count($a); $j++) {
                    if (isset($a[$j]))
                        $row->pushContent(HTML::div(
                                              HTML::input(array('type' => 'radio',
                                                                'name' => "answer[$i]",
                                                                'value' => $j)),
                                              HTML::raw("&nbsp;"), $a[$j]));
                }
                $html->pushContent(HTML::p(HTML::strong($q)),$row);
            }
        }
        if (!$disable_submit)
            $html->pushContent(HTML::p(
        	HTML::input(array('type' => 'submit',
                                  'name' => "WikiPoll",
                                  'value' => _("Ok"))),
        	HTML::input(array('type' => 'reset',
                                  'name' => "reset",
                                  'value' => _("Reset")))));
        else 
             $html->pushContent(HTML::p(),HTML::strong(
                 _("Sorry! You must wait at least 20 minutes until you can vote again!")));
        return $html;
    }

    function bar($percent) {
        global $WikiTheme;
        return HTML(HTML::img(array('src' => $WikiTheme->getImageUrl('leftbar'),
                                    'alt' => '<')),
                    HTML::img(array('src' => $WikiTheme->getImageUrl('mainbar'),
                                    'alt' => '-',
                                    'width' => sprintf("%02d",$percent),
                                    'height' => 14)),
                    HTML::img(array('src' => $WikiTheme->getImageUrl('rightbar'),
                                    'alt' => '>')));
    }

    function doPoll($page, $request, $answers, $readonly = false) {
    	$question = $this->_args['question'];
    	$answer   = $this->_args['answer'];
        $html = HTML::table(array('cellspacing' => 2));
        $init = isset($question[0]) ? 0 : 1;
        for ($i = $init; $i <= count($question); $i++) {
            if (!isset($question[$i])) break;
            $poll = $page->get('poll');
            @$poll['data']['all'][$i]++;
            $q = $question[$i]; 
            if (!isset($answer[$i]))
            	trigger_error(fmt("Missing %s for %s","answer"."[$i]","question"."[$i]"),
            	              E_USER_ERROR);
            if (!$readonly)
                $page->set('poll',$poll);
            $a = $answer[$i];
            $result = (isset($answers[$i])) ? $answers[$i] : -1;
            if (! is_array($a) ) {
                $checkbox = HTML::input(array('type' => 'checkbox',
                                              'name' => "answer[$i]",
                                              'value' => $a));
                if ($result >= 0)
                    $checkbox->setAttr('checked',1);
	        if (!$readonly)
                    list($percent,$count,$all) = $this->storeResult($page, $i, $result ? 1 : 0);
                else 
                    list($percent,$count,$all) = $this->getResult($page, $i, 1);
                $print = sprintf(_("  %d%% (%d/%d)"), $percent, $count, $all);
                $html->pushContent(HTML::tr(HTML::th(array('colspan' => 4,'align'=>'left'),$q)));
                $html->pushContent(HTML::tr(HTML::td($checkbox),
                                            HTML::td($a),
                       		            HTML::td($this->bar($percent)),
                                            HTML::td($print)));
            } else {
                $html->pushContent(HTML::tr(HTML::th(array('colspan' => 4,'align'=>'left'),$q)));
                $row = HTML();
                if (!$readonly)
                    $this->storeResult($page, $i, $answers[$i]);
                for ($j=0; $j <= count($a); $j++) {
                    if (isset($a[$j])) {
                    	list($percent,$count,$all) = $this->getResult($page,$i,$j);
                        $print = sprintf(_("  %d%% (%d/%d)"), $percent, $count, $all);
                        $radio = HTML::input(array('type' => 'radio',
                                                   'name' => "answer[$i]",
                                                   'value' => $j));
                        if ($result == $j)
                            $radio->setAttr('checked',1);
                        $row->pushContent(HTML::tr(HTML::td($radio),
                        		           HTML::td($a[$j]),
                        		           HTML::td($this->bar($percent)),
                                                   HTML::td($print)));
                    }
                }
                $html->pushContent($row);
            }
        }
        if (!$readonly)
            return HTML(HTML::h3(_("The result of this poll so far:")),$html,HTML::p(_("Thanks for participating!")));
        else  
            return HTML(HTML::h3(_("The result of this poll so far:")),$html);
  
    }
    
    function getResult($page,$i,$j) {
    	$poll = $page->get("poll");
    	@$count = $poll['data']['count'][$i][$j];
    	@$all = $poll['data']['all'][$i];
    	$percent = sprintf("%d", $count * 100.0 / $all);
    	return array($percent,$count,$all);
    }
    
    function storeResult($page, $i, $j) {
    	$poll = $page->get("poll");
    	if (!$poll) {
    	    $poll = array('data' => array('count' => array(),
    	    				  'all'   => array()));
    	}
    	@$poll['data']['count'][$i][$j]++;
    	//@$poll['data']['all'][$i];
    	$page->set("poll",$poll);
  	$percent = sprintf("%d", $poll['data']['count'][$i][$j] * 100.0 / $poll['data']['all'][$i]);
	return array($percent,$poll['data']['count'][$i][$j],$poll['data']['all'][$i]);
    }

};

// $Log: WikiPoll.php,v $
// Revision 1.9  2004/06/16 10:38:59  rurban
// Disallow refernces in calls if the declaration is a reference
// ("allow_call_time_pass_reference clean").
//   PhpWiki is now allow_call_time_pass_reference = Off clean,
//   but several external libraries may not.
//   In detail these libs look to be affected (not tested):
//   * Pear_DB odbc
//   * adodb oracle
//
// Revision 1.8  2004/06/14 11:31:39  rurban
// renamed global $Theme to $WikiTheme (gforge nameclash)
// inherit PageList default options from PageList
//   default sortby=pagename
// use options in PageList_Selectable (limit, sortby, ...)
// added action revert, with button at action=diff
// added option regex to WikiAdminSearchReplace
//
// Revision 1.7  2004/05/01 15:59:29  rurban
// more php-4.0.6 compatibility: superglobals
//
// Revision 1.6  2004/03/01 18:08:53  rurban
// oops, checked in the debug version. revert to IP check on
//
// Revision 1.5  2004/03/01 16:11:13  rurban
// graphical enhancement
//
// Revision 1.4  2004/02/26 01:42:27  rurban
// don't cache this at all
//
// Revision 1.3  2004/02/24 03:54:46  rurban
// lock page, more questions, new require_least arg
//
// Revision 1.2  2004/02/24 03:21:46  rurban
// enabled require_all check in WikiPoll
// better handling of <20 min visiting client: display results so far
//
//

// For emacs users
// Local Variables:
// mode: php
// tab-width: 8
// c-basic-offset: 4
// c-hanging-comment-ender-p: nil
// indent-tabs-mode: nil
// End:
?>