User:Sent~metawiki/Poll

From Meta, a Wikimedia project coordination wiki
 
A proposal to move this page to MediaWiki.org was rejected.

An extension that adds the ability to create polls that can be added to a page and then the votes can be displayed on the same page. This would be useful for users to vote on the quality of a book, for example.

- Wanted Extensions

 

WARNING - The documentation and code (below) is out-of-date and not up-to-date!

Because of a very busy year I wasn't able to maintain this page. And also did (almost) no development to this extension. That's why the version below is named v0.5.1beta, the dutch version of this page is v0.5 (my original version, developped for MediaWiki 1.4.7).

If you wish to get the most current 1.0alfa for MediaWiki 1.6.7 version, get it here (dutch).

- Sent

Poll is as an extension developed for use on sites using MediaWiki. This extension realizes the ability for several pages to contain a poll.

Also take a look at RandomPoll for the expansion to get a random poll on your page. And look at PollTemplate for the way graphical mark-up for Poll should be made.

How to use Poll[edit]

Poll is a MediaWiki extension. For using, just include the following HTML-like syntax in your page:

<Poll>
...parameters...
</Poll>

The parameters given to the poll, besides Question, the multiple Answers and Explanation, start all with a # and are optional. You can choose for the next: #ID, #REVOKE, #STYLE, #CLOSED, #RESULT, #BUTTON, [[Poll:Result]] and [[Poll:Revoke]]

For example the next Poll:

Poll-example.png











with its result:

Poll-example2.png






is made as the following:

<Poll>
 #RESULT AVERAGE PERCENT
 #REVOKE OFF
 #ID[[Poll:Balkenende moet direct aftreden]]
 ; Met het oog op de [[Nacht van Balkenende|recentelijke crisis]] binnen het [[kabinet]]...
 Moet [[Jan Peter Balkenende]] per direct aftreden?
 ;; {{SITENAME}} zal deze stemming als [[handtekeninglijst]] versturen, met vermelding van deze [[Poll:Result|uitslag]].
 =(100%) Ja
 -(0%) Nee
 : $1 van de {{total}} gestemde bezoekers is het met de stelling eens.
 #BUTTON Stem!
</Poll>

Question[edit]

Purpose:

To make clear to the visitor which question he is answering.

Example:

Moet [[Jan Peter Balkenende]] per direct aftreden?

There should only be one Question be defined.

QuestionElaboration[edit]

Purpose:

To make the question more clear, or more precise defined.

Example:

; Met het oog op de recentelijke crisis binnen het kabinet...

This parameter is being represented in relation and in order with the Question; so, it can be given before or after. By use of a double ; (;;), this line will not be mentioned in the result of the poll. Instead, Explanation will be included, on the end of the complete question-part.

Answers[edit]

Purpose:

To offer a choice to be made for the visitor, regarding the question.

Example:

- Yes

It is also possible to start the answer with -(100%) or an other percentage. In that case the percentage will be used. For example used in calculating the average vote by use of #RESULT AVERAGE PERCENT. Also possible is -(4) for giving the answer predeterment value. This comes in handy when the order of answers change. In combination with #RESULT AVERAGE MARK all these numbers will be interpreted as a meaningful row for a higher vote, a higher result.

To define a default selection is made by using = Yes for example.

Explanation[edit]

Purpose:

To give meaning to the result of the poll.

Example:

: $1 is het met de stelling eens.

Note: This should be used in combination with #RESULT AVERAGE-option. Else the default result will be represented... $1 will be replaced with the result: the average.

ID[edit]

Purpose:

To identify this poll. In the database a table collects all the votes. And because MediaWiki should support multiple polls -I say- it also should ensure the vote be part of the correct poll.

After the #ID comes the identifying key. By default, this one is a derivable of the entry containing the poll. (This is the reason why a page can only contain one poll [without ID]!).

When an #ID is part of the poll, then will the identifying key be derived of the value following it.

Example of identification by reference to an other page:

#ID[[other page]]

In this way, you should also be able to direct to a translation of the poll, standing on a translated page. Could be useful when you want the opinion of all your visitors on a multi-lingual site.

Example of identification by an existing identification key:

#ID:0123456789ABCDEF0123456789ABCDEF

This last variant uses the same key used in the table, to identify this poll. This key is already derived from an existing -or not- article by use of the MD5-function.

REVOKE[edit]

Purpose:

Define if it is allowed for the visitor to revoke his vote.

Example:

#REVOKE ON

By default this parameter is OFF.

STYLE[edit]

Purpose:

To make it possible for use of your own style, even for each poll. It comes in handy within a MediaWiki which knows several type of polls (e.g.: Normal polls and a Article Quality Poll).

Example:

#STYLE {{my PollTemplate}}

CLOSED[edit]

Purpose:

As it says: to close the poll. No visitor is/should be able to add an other vote.

Example:

#CLOSED

RESULT[edit]

Purpose:

To determine how to be dealt with the result of the poll. The poll can be defined so it will result into a percentage and an amount/total, per Answer by use of EACH ANSWER. Or as only 1(!) result with: AVERAGE PERCENT en AVERAGE MARK.

Example:

#RESULT AVERAGE PERCENT; DOUBLE 4,1

By default it is EACH ANSWER.

For both AVERAGE-options will the results being ordered (if possible). In the general example, the order will be maintained: in this case you first have option 1, followed by 0. To maintain the order of the Yes/No question.

Both options EACH ANSWER and AVERAGE PERCENT are allowed to be followed with ; DOUBLE x,y - to determine how the number should be formatted. By the default of 4,1, it results into '100,0%' and '  7,3%' for example.

Note: AVERAGE PERCENT works only when the collection of answers starts with 0% and ends with 100%, in each order (DESC/ASC).

BUTTON[edit]

Purpose:

To reset the default of Vote! to its new setting.

Example:

#BUTTON Stem!

Poll:Result[edit]

Purpose:

To insert the correct link to the result of this poll.

Example:

[[Poll:Result|result]]

Poll:Revoke[edit]

Purpose: To insert the correct link to change the vote made by the current visitor.

Example:

[[Poll:Revoke|change your vote]]

Source Code[edit]

free2xs/Poll.php: User:Sent/Poll/Source

poll.sql

CREATE TABLE `poll` (
  `poll_id` VARCHAR(32) NOT NULL DEFAULT '',
  `poll_user` INT(5) NOT NULL DEFAULT '0',
  `poll_user_text` VARCHAR(255) BINARY NOT NULL DEFAULT '',
  `poll_cur_id` INT(8) unsigned NOT NULL DEFAULT '0',
  `poll_answer` DOUBLE(3,1) NOT NULL DEFAULT '0.0',
  `poll_procent` ENUM('Y','N') NOT NULL DEFAULT 'N',
  `poll_date` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY  (`poll_id`,`poll_user_text`)
);

Installation[edit]

  1. Upload the free2xs/Poll.php the extensions-directory.
  2. Add the table poll into the database of MediaWiki (poll.sql).
  3. Add the following code - include("extensions/free2xs/Poll.php"); - at the end of your LocalSettings.php file.
  4. (Optional) Add the following Templates.
Installation question[edit]

phpMyAdmin is asking me the "Number of fields" the table should have, any ideas? -- 167.95.36.87 20:05, 27 February 2006 (UTC)

  • You should paste the above code into the SQL query field of the database holding the wikipedia tables.

Template:Poll[edit]

When this one doesn't exist in the MediaWiki database, it uses the default in the source.

<PollTemplate>
  <table border="0" cellSpacing="0" cellPadding="0">
  ;<form name="poll" method="POST">
  <input type="hidden" name="ID" value="{{ID}}"/>
  <tr><td>{{QuestionLines}}</td></tr>
  ;<tr><td>{{Answers}}</td></tr>
  ;<tr><td align="right">{{BUTTON}}</td></tr>
  :<tr><td>{{Explaination}}</td></tr>
  :<tr><td>{{REVOKE}}</td></tr>
  ;</form>
  </table>
  ----
  Question=<b>$i</b>
  QuestionElaboration=<i>$i</i>
  QuestionNewLine=<br/>
  Answer=<input type="radio" name="poll_{{ID}}" value="{{value}}" id="{{label}}"{{checked}}/><label for="{{label}}">$1</label>
  AnswerNewLine=</td></tr><tr><td>
  Checked= CHECKED="true"
  Explaination=<i>$1</>
  REVOKE=I changed my mind, I want to [[Poll:Revoke|revoke]] my vote.
  BUTTON=<input type="submit" value="$1"/>
</PollTemplate>

Template:Article Quality Poll[edit]

For the use of this object, you should add {{Article Quality Poll}} in your article, on the place where you want the poll: most likely on top of the document.

<PollTemplate>
  <table border="0" cellSpacing="0" cellPadding="0">
  ;<form name="poll" method="POST">
  <input type="hidden" name="ID" value="{{ID}}"/>
  <tr><td colspan="6">{{QuestionLines}}</td></tr>
  ;<tr>
  ;  <td>{{Answers}}</td>
  ;  <td align="right">{{BUTTON}}</td>
  ;</tr>
  :<tr><td colspan="5">{{Explaination}}</td><td>{{REVOKE}}</td></tr>
  ;</form>
  </table>
  [[Category:Article Quality]]
  ----
  Question=<b>$i</b>
  QuestionElaboration=<i>$i</i>
  QuestionNewLine=<br/>
  Answer=<input type="radio" name="poll_{{ID}}" value="{{value}}" id="{{label}}"{{checked}}/><label for="{{label}}">$1</label>
  AnswerNewLine=</td><td>
  Checked= CHECKED="true"
  Explaination=<i>$1</>
  REVOKE=[[Poll:Revoke|revoke vote]].
  BUTTON=<input type="submit" value="Vote!"/>
</PollTemplate>
<Poll>
 #REVOKE ON
 #STYLE {{Article Quality Poll}}
 How much stars deserves this page?
 -(0) very bad
 -(1) bad
 =(2) ok
 -(3) good
 -(4) very good
 : This page is <b>{{Answer}}</b>!
 #RESULT AVERAGE MARK
</Poll>

ToDo List[edit]

  • Support for #STYLE. There is still an →StyleOpen()-handler missing. The way to interpreted the template already works!
  • Support for #RESULT. At this moment this parameter is being ignored. And is momentarily replaced with testing if Explanation exists and is valid.
  • Cleanup the source of free2xs/Poll.php.
  • To implement the correct method to communicate with the database, in the way MediaWiki is used to.
  • Detecting if the current visitor already had voted; If so, view result.
  • Extend the extension in a way it -temporary- disables the document-caching for the current visitor-document-relation.
  • Add a functionality like TOC/Sections-Menu (the menu with all documents paragraphs, when there are more than 3) and __NOTOC__ to disable this function. To add the Article Quality Poll by default to each new contribution. (Felipe Pablos suggested this by mail)
  • Test, debug, develop MORE!

Testing (outside MediaWiki)[edit]

Poll_Sandbox(no-MediaWiki).php:

<?php
require_once(dirname(__FILE__)."/../map/to/MediaWiki/extensions/free2xs/Poll.php");

$wgScript = dirname($_SERVER["SCRIPT_URL"]);
$wgUser->mId = 1;
$wgUser->mName = 'Webmaster';

$wgTitle->mUrlform = basename(__FILE__);
$wgTitle->mArticleID = 57;
$wgTitle->mTextform = str_replace("_", " ", basename(__FILE__));

$wgDBservers[0] = Array(
                    'host' => 'localhost',
                    'user' => '*******',
                    'password' => '*******',
                    'dbname' => '*******',
                    'type' => 'mysql',
                    'load' => '1',
                    'flags' => '16',
                );

$con->mConn = mysql_connect($wgDBservers[0]['host'], $wgDBservers[0]['user'], $wgDBservers[0]['password']);
mysql_select_db($wgDBservers[0]['dbname'], $con->mConn) or die('Unable to connect to DB: '.mysql_error());

$wgLoadBalancer->mConnections[0] &= $con; 


$str = '
 #RESULT AVERAGE PERCENT
 ; Met het oog op de [[Nacht van Balkenende|recentelijke crisis]] binnen het [[kabinet]]...
 Moet [[Jan Peter Balkenende]] per direct aftreden?
 ;; {{SITENAME}} zal deze stemming als [[handtekeninglijst]] versturen, met vermelding van deze [[Poll:Result|uitslag]].
 =(100%) Ja
 -(0%) Nee
 : $1 van de {{total}} gestemde bezoekers is het met de stelling eens.
';
?>

<!-- start content -->
<?php
echo renderPoll($str);
?>
<!-- end content -->

I added this during-development-testing-example-code because my complete installation (Apache/PHP/MediaWiki and Firefox) caches the output... I don't know yet if this is a bug or missing code-element in my extension -or- wrong configuration of MediaWiki.


Working cache version[edit]

Hi ! I was looking for a poll board since a while and get boring to be unable to make this one work due to due cache trouble. Today i'm proud to show you my first result. This hack is correcting the timestamp of the page each time it's loaded. Ok, it's not really good if you have a huge traffic because the server will have to generate the new page each time. However I haven't find another solution and this one works well.

  • You might want to look at Write_your_own_MediaWiki_extension where it says that the render method gets a $parser parameter, having a method disableCache() which does exactly what you want: Disables the client and parser cache. Call this if the HTML you are returning changes regularly, without the source text changing. $parser is available since 1.5

Modifications[edit]

  • Here is the new fonction I added to free2xs_mediawiki_poll class :
		function update_timestamp()	{
			global $wgTitle;				
				// met à jour le timestamp	
				$dbr =& wfGetDB( DB_SLAVE );
				$cur = $dbr->tableName( 'cur' );
				
				$timestamp = wfTimestampNow();
				$invTimestamp = wfInvertTimestamp( $timestamp );				
				$sql = "UPDATE `cur` SET `cur_timestamp` = '".$timestamp."', `inverse_timestamp` = '".$invTimestamp."', "
								."`cur_touched` = '".$timestamp."' \tWHERE `cur_id` = '".$wgTitle->mArticleID."' ;";
				
				$wgTitle->invalidateCache();
				return $dbr->query( $sql );					
		}	

..and I call it this way :

# The callback function for converting the input text to HTML output
function renderPoll( $input, $argv=array() ) {

        global $wgPollTemplate;
        $free2xs_mediawiki_poll = new free2xs_mediawiki_poll($input);
			
        $input = $free2xs_mediawiki_poll->build($wgPollTemplate);		
		$free2xs_mediawiki_poll->update_timestamp();	
		
        # $argv is an array containing any arguments passed to the extension like <example argument="foo" bar>..
        $output = "<!-- poll=\"start\" -->$input<!-- poll=\"finish\" -->";
        return $output;
}


  • Something else.. I use another way to acces database ( the original don't work for me ).

Instead, I use this :

$dbr =& wfGetDB( DB_SLAVE );
$cur = $dbr->tableName( 'poll' );							
$result = 	$dbr->query( $sql );

Another correction : when I try to use EACH ANSWER type for my poll, result page was always show 0.0% for each line. This was because sql table poll consider answer as double, and the extension try to access the result in array with $id ( wich is an integer ). So I just convert the answer to int. I don't know hat could be the result for PERCENT type of poll.

( in getPollResults() )

                while($row = mysql_fetch_array($result)){
						$temp = (int)$row['poll_answer'].($row['poll_procent'] == 'Y' ? '%' : NULL);
                        $this->_poll_result[$temp] = $row['poll_amount'];
                }
  • The board pool now detect if the user has already vote and the results. If revoke is enable, the user can browse back and make another choice. ( CurrentUserAllreadyVoted() implemented )
  • .. and, I have also modify the original $_default_template to improve the result page.


        var $_default_template = '
<table border="0" cellSpacing="0" cellPadding="0">
;<form name="poll" method="POST">
;<input type="hidden" name="poll_ID[]" value="{{ID}}"/>
  <tr><td colspan=3>{{QuestionLines}}</td></tr>
  ;<tr><td>{{Answers}}</td></tr>
  ;<tr><td align="right">{{BUTTON}}</td></tr>
  :<tr><td>{{Explaination}}</td></tr>
  :<tr><td colspan=3>{{REVOKE}}</td></tr>
;</form>
</table>
----
Question=<b>$1</b>
QuestionElaboration=<i>$1</i>
QuestionNewLine=<br/>
Answer=<input type="radio" name="poll_{{ID}}" value="{{value}}" id="{{label}}"{{checked}}/><label for="{{label}}">$1</label>
AnswerResult=<b>{{percent}}</b></td><td> ({{amount}}/{{total}}) <i>$1</i>
AnswerNewLine=</td></tr><tr><td>
Checked= CHECKED="true"
Explaination=<i>$1</>
REVOKE=<br/>[[Poll:Revoke|Modifier votre vote !]]
BUTTON=<input type="submit" value="$1"/>
'; //<PollTemplate> ... </PollTemplate>

Full source code[edit]

free2xs/Poll.php: User:Sent/Poll/Source with cache

You can test this version and see the result at http://kerb.hn.org/wiki/index.php/Current_events