plugins/polls/functions.inc
author Dirk Haun <dirk@haun-online.de>
Sun, 11 Oct 2009 20:51:25 +0200
branchHEAD
changeset 7374 0ba218a98a1a
parent 7373 b04a760c72ea
child 7514 45420e4a6c33
permissions -rw-r--r--
Don't display "This poll has 0 more questions."
     1 <?php
     2 
     3 /* Reminder: always indent with 4 spaces (no tabs). */
     4 // +---------------------------------------------------------------------------+
     5 // | Polls Plugin 2.1                                                          |
     6 // +---------------------------------------------------------------------------+
     7 // | functions.inc                                                             |
     8 // |                                                                           |
     9 // | This file does two things: 1) it implements the necessary Geeklog Plugin  |
    10 // | API method and 2) implements all the common code needed by the Polls      |
    11 // | plugin' PHP files.                                                        |
    12 // +---------------------------------------------------------------------------+
    13 // | Copyright (C) 2000-2009 by the following authors:                         |
    14 // |                                                                           |
    15 // | Authors: Tony Bibbs       - tony AT tonybibbs DOT com                     |
    16 // |          Tom Willett      - twillett AT users DOT sourceforge DOT net     |
    17 // |          Blaine Lang      - langmail AT sympatico DOT ca                  |
    18 // |          Dirk Haun        - dirk AT haun-online DOT de                    |
    19 // +---------------------------------------------------------------------------+
    20 // |                                                                           |
    21 // | This program is free software; you can redistribute it and/or             |
    22 // | modify it under the terms of the GNU General Public License               |
    23 // | as published by the Free Software Foundation; either version 2            |
    24 // | of the License, or (at your option) any later version.                    |
    25 // |                                                                           |
    26 // | This program is distributed in the hope that it will be useful,           |
    27 // | but WITHOUT ANY WARRANTY; without even the implied warranty of            |
    28 // | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             |
    29 // | GNU General Public License for more details.                              |
    30 // |                                                                           |
    31 // | You should have received a copy of the GNU General Public License         |
    32 // | along with this program; if not, write to the Free Software Foundation,   |
    33 // | Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.           |
    34 // |                                                                           |
    35 // +---------------------------------------------------------------------------+
    36 
    37 /**
    38 * Implementation of the Plugin API for the Polls plugin
    39 *
    40 * @package Polls
    41 */
    42 
    43 if (strpos(strtolower($_SERVER['PHP_SELF']), 'functions.inc') !== false) {
    44     die('This file can not be used on its own.');
    45 }
    46 
    47 $plugin_path = $_CONF['path'] . 'plugins/polls/';
    48 
    49 /**
    50 * Language file include
    51 */
    52 $langfile = $plugin_path . 'language/' . $_CONF['language'] . '.php';
    53 if (file_exists($langfile)) {
    54     require_once $langfile;
    55 } else {
    56     require_once $plugin_path . 'language/english.php';
    57 }
    58 
    59 /**
    60 * Check and see if we need to load the plugin configuration
    61 */ 
    62 if (!isset($_PO_CONF['pollsloginrequired'])) {
    63     require_once $_CONF['path_system'] . 'classes/config.class.php';
    64     
    65     $po_config = config::get_instance();
    66     $_PO_CONF = $po_config->get_config('polls');
    67 }
    68 
    69 
    70 // +---------------------------------------------------------------------------+
    71 // | Geeklog Plugin API Implementations                                        |
    72 // +---------------------------------------------------------------------------+
    73 
    74 /**
    75 * Returns the items for this plugin that should appear on the main menu
    76 *
    77 * NOTE: this MUST return the url/value pairs in the following format
    78 * $<arrayname>[<label>] = <url>
    79 *
    80 * @return   mixed   menu entry, or boolean false if disabled / hidden
    81 */
    82 function plugin_getmenuitems_polls ()
    83 {
    84     global $_CONF, $_PO_CONF, $LANG_POLLS;
    85 
    86     if (($_PO_CONF['hidepollsmenu'] == 1) || (COM_isAnonUser() &&
    87                 ($_CONF['loginrequired'] || $_PO_CONF['pollsloginrequired']))) {
    88         return false;
    89     }
    90 
    91     $menuitems[$LANG_POLLS['polls']] = $_CONF['site_url'] . '/polls/index.php';
    92 
    93     return $menuitems;
    94 }
    95 
    96 /**
    97  * Poll saves a comment
    98  *
    99  * @param   string  $title  comment title
   100  * @param   string  $comment comment text
   101  * @param   string  $id     Item id to which $cid belongs
   102  * @param   int     $pid    comment parent
   103  * @param   string  $postmode 'html' or 'text'
   104  * @return  mixed   false for failure, HTML string (redirect?) for success
   105  */
   106 function plugin_savecomment_polls($title, $comment, $id, $pid, $postmode)
   107 {
   108     global $_CONF, $_TABLES, $LANG03, $_USER;
   109 
   110     $retval = '';
   111 
   112     $commentcode = DB_getItem($_TABLES['polltopics'], 'commentcode',
   113                               "pid = '$id'");
   114     if ($commentcode != 0) {
   115         return COM_refresh($_CONF['site_url'] . '/index.php');
   116     }
   117 
   118     $ret = CMT_saveComment($title, $comment, $id, $pid, 'polls', $postmode);
   119     if ($ret > 0) { // failure //FIXME: some failures should not return to comment form
   120         $retval .= COM_siteHeader('menu', $LANG03[1])
   121                 . CMT_commentForm($title, $comment, $id, $pid, 'polls',
   122                                   $LANG03[14], $postmode)
   123                 . COM_siteFooter();
   124     } else { // success
   125         $msg = '';
   126         if (($_CONF['commentsubmission'] == 1) &&
   127                 !SEC_hasRights('comment.submit')) {
   128             $msg = '&msg=15';
   129         }
   130         $retval = COM_refresh($_CONF['site_url']
   131                               . "/polls/index.php?pid=$id&amp;aid=-1$msg");
   132     }
   133 
   134     return $retval;
   135 }
   136 
   137 /**
   138  * polls: delete a comment
   139  *
   140  * @param   int     $cid    Comment to be deleted
   141  * @param   string  $id     Item id to which $cid belongs
   142  * @return  mixed   false for failure, HTML string (redirect?) for success
   143  */
   144 function plugin_deletecomment_polls($cid, $id)
   145 {
   146     global $_CONF, $_TABLES, $_USER;
   147 
   148     $retval = '';
   149 
   150     $has_editPermissions = SEC_hasRights ('polls.edit');
   151     $result = DB_query ("SELECT owner_id,group_id,perm_owner,perm_group,perm_members,perm_anon FROM {$_TABLES['polltopics']} WHERE pid = '{$id}'");
   152     $A = DB_fetchArray ($result);
   153 
   154     if ($has_editPermissions && SEC_hasAccess ($A['owner_id'],
   155             $A['group_id'], $A['perm_owner'], $A['perm_group'],
   156             $A['perm_members'], $A['perm_anon']) == 3) {
   157         CMT_deleteComment($cid, $id, 'polls');
   158         $retval .= COM_refresh ($_CONF['site_url']
   159                                  . "/polls/index.php?pid=$id&amp;aid=-1");
   160     } else {
   161         COM_errorLog ("User {$_USER['username']} (IP: {$_SERVER['REMOTE_ADDR']}) "
   162                     . "tried to illegally delete comment $cid from poll $id");
   163         $retval .= COM_refresh ($_CONF['site_url'] . '/index.php');
   164     }
   165 
   166     return $retval;
   167 }
   168 
   169 
   170 /**
   171 * Helper function: count number of polls and total number of votes
   172 *
   173 * @return   array(number of polls, number of votes);
   174 *
   175 */
   176 function POLLS_countPollsAndVotes ()
   177 {
   178     global $_TABLES;
   179 
   180     $total_polls = 0;
   181     $total_answers = 0;
   182 
   183     $result = DB_query ("SELECT COUNT(*) AS count FROM {$_TABLES['polltopics']}" . COM_getPermSQL ());
   184     $A = DB_fetchArray($result);
   185     $total_polls = $A['count'];
   186 
   187     $result = DB_query ("SELECT pid FROM {$_TABLES['polltopics']}" . COM_getPermSQL ());
   188     $nrows = DB_numRows ($result);
   189     if ($nrows > 0) {
   190         $topics = '';
   191         for ($i = 1; $i <= $nrows; $i++) {
   192             $A = DB_fetchArray($result);
   193             if ($i > 1) {
   194                 $topics .= ',';
   195             }
   196             $topics .= "'" . $A['pid'] . "'";
   197         }
   198         $result = DB_query ("SELECT SUM(votes) FROM {$_TABLES['pollanswers']} WHERE pid IN ({$topics})");
   199         $A = DB_fetchArray($result, true);
   200         $total_answers = $A[0];
   201     }
   202 
   203     return array ($total_polls, $total_answers);
   204 }
   205 
   206 /**
   207 * Shows the statistics for the Polls plugin on stats.php.
   208 * If $showsitestats is 1 then we are to only print the overall stats in the
   209 * 'site statistics box' otherwise we show the detailed stats
   210 *
   211 * @param    int     showsitestate   Flag to let us know which stats to get
   212 */
   213 function plugin_showstats_polls ($showsitestats)
   214 {
   215     global $_CONF, $_TABLES, $LANG_POLLS;
   216 
   217     require_once ($_CONF['path_system'] . 'lib-admin.php');
   218 
   219     $retval = '';
   220 
   221     $result = DB_query ("SELECT pid,topic,voters FROM {$_TABLES['polltopics']} WHERE (voters > 0)" . COM_getPermSQL ('AND') . " ORDER BY voters DESC LIMIT 10");
   222     $nrows  = DB_numRows ($result);
   223 
   224     if ($nrows > 0) {
   225         $header_arr = array(
   226             array('text'         => $LANG_POLLS['stats_topics'],
   227                   'field'        => 'pid',
   228                   'header_class' => 'stats-header-title'
   229             ),
   230             array('text'         => $LANG_POLLS['stats_votes'],
   231                   'field'        => 'voters',
   232                   'header_class' => 'stats-header-count',
   233                   'field_class'  => 'stats-list-count'
   234             ),
   235         );
   236         $data_arr = array();
   237         $text_arr = array('has_menu' => false,
   238                           'title'    => $LANG_POLLS['stats_top10'],
   239         );
   240         for ($i = 0; $i < $nrows; $i++) {
   241             $A = DB_fetchArray ($result);
   242             $url = $_CONF['site_url'] . '/polls/index.php?pid=' . $A['pid']
   243                  . '&amp;aid=-1';
   244             $pid = COM_createLink($A['topic'], $url);
   245             $voters = COM_NumberFormat ($A['voters']);
   246             $data_arr[] = array ('pid' => $pid, 'voters' => $voters);
   247         }
   248         $retval .= ADMIN_simpleList ('', $header_arr, $text_arr, $data_arr);
   249     } else {
   250         $retval .= COM_startBlock ($LANG_POLLS['stats_top10']);
   251         $retval .= $LANG_POLLS['stats_none'];
   252         $retval .= COM_endBlock ();
   253     }
   254 
   255     return $retval;
   256 }
   257 
   258 /**
   259 * New stats plugin API function for proper integration with the site stats
   260 *
   261 * @return   array(item text, item count);
   262 *
   263 */
   264 function plugin_statssummary_polls ()
   265 {
   266     global $LANG_POLLS;
   267 
   268     list($total_polls, $total_answers) = POLLS_countPollsAndVotes ();
   269 
   270     $item_count = COM_numberFormat ($total_polls)
   271                 . ' (' . COM_numberFormat ($total_answers) . ')';
   272 
   273     return array ($LANG_POLLS['stats_summary'], $item_count);
   274 }
   275 
   276 
   277 /**
   278 * This will put an option for polls in the command and control block on
   279 * moderation.php
   280 *
   281 */
   282 function plugin_cclabel_polls()
   283 {
   284     global $_CONF, $LANG_POLLS;
   285 
   286     if (SEC_hasRights ('polls.edit')) {
   287         return array ($LANG_POLLS['polls'],
   288                 $_CONF['site_admin_url'] . '/plugins/polls/index.php',
   289                 plugin_geticon_polls ());
   290     }
   291 
   292     return false;
   293 }
   294 
   295 
   296 /**
   297 * returns the administrative option for this plugin
   298 *
   299 */
   300 function plugin_getadminoption_polls()
   301 {
   302     global $_CONF, $_TABLES, $LANG_POLLS;
   303 
   304     if (SEC_hasRights ('polls.edit')) {
   305         $result = DB_query ("SELECT COUNT(*) AS cnt FROM {$_TABLES['polltopics']}" . COM_getPermSQL ());
   306         $A = DB_fetchArray ($result);
   307         $total_pages = $A['cnt'];
   308 
   309         return array ($LANG_POLLS['polls'],
   310                       $_CONF['site_admin_url'] . '/plugins/polls/index.php',
   311                       $total_pages);
   312     }
   313 }
   314 
   315 
   316 /**
   317 * A user is about to be deleted. Update ownership of any polls owned
   318 * by that user or delete them.
   319 *
   320 * @param   uid   int   User id of deleted user
   321 *
   322 */
   323 function plugin_user_delete_polls ($uid)
   324 {
   325     global $_TABLES, $_PO_CONF;
   326 
   327     if (DB_count ($_TABLES['polltopics'], 'owner_id', $uid) == 0) {
   328         // there are no polls owned by this user
   329         return;
   330     }
   331 
   332     if ($_PO_CONF['delete_polls'] == 1) {
   333         // delete the polls
   334         $result = DB_query ("SELECT pid FROM {$_TABLES['polltopics']} WHERE owner_id = $uid");
   335         $numPolls = DB_numRows ($result);
   336         for ($i = 0; $i < $numPolls; $i++) {
   337             list($pid) = DB_fetchArray($result);
   338             DB_delete($_TABLES['pollanswers'], 'pid', $pid);
   339             DB_delete($_TABLES['pollvoters'], 'pid', $pid);
   340             DB_delete($_TABLES['comments'], array('sid', 'type'),
   341                                             array($pid, 'polls'));
   342         }
   343         DB_delete($_TABLES['polltopics'], 'owner_id', $uid);
   344     } else {
   345         // assign ownership to a user from the Root group
   346         $rootgroup = DB_getItem ($_TABLES['groups'], 'grp_id',
   347                                  "grp_name = 'Root'");
   348         $result = DB_query ("SELECT DISTINCT ug_uid FROM {$_TABLES['group_assignments']} WHERE ug_main_grp_id = $rootgroup ORDER BY ug_uid LIMIT 1");
   349         list($rootuser) = DB_fetchArray ($result);
   350 
   351         DB_query ("UPDATE {$_TABLES['polltopics']} SET owner_id = $rootuser WHERE owner_id = $uid");
   352     }
   353 }
   354 
   355 /**
   356 * Return the current version of code.
   357 * Used in the Plugin Editor to show the registered version and code version
   358 */
   359 function plugin_chkVersion_polls()
   360 {
   361     global $_CONF;
   362 
   363     require_once $_CONF['path'] . 'plugins/polls/autoinstall.php';          
   364 
   365     $inst_parms = plugin_autoinstall_polls('polls'); 
   366 
   367     return $inst_parms['info']['pi_version'];
   368 }
   369 
   370 /**
   371 * Geeklog informs us that we're about to be enabled or disabled
   372 *
   373 * @param    boolean     $enable     true = we're being enabled, false = disabled
   374 * @return   void
   375 *
   376 */
   377 function plugin_enablestatechange_polls ($enable)
   378 {
   379     global $_TABLES;
   380 
   381     $is_enabled = $enable ? 1 : 0;
   382 
   383     // toggle Poll block
   384     DB_query ("UPDATE {$_TABLES['blocks']} SET is_enabled = $is_enabled WHERE (type = 'phpblock') AND (phpblockfn = 'phpblock_polls')");
   385 }
   386 
   387 /**
   388 * Automatic uninstall function for plugins
   389 *
   390 * @return   array
   391 *
   392 * This code is automatically uninstalling the plugin.
   393 * It passes an array to the core code function that removes
   394 * tables, groups, features and php blocks from the tables.
   395 * Additionally, this code can perform special actions that cannot be
   396 * foreseen by the core code (interactions with other plugins for example)
   397 *
   398 */
   399 function plugin_autouninstall_polls ()
   400 {
   401     $out = array (
   402         /* give the name of the tables, without $_TABLES[] */
   403         'tables' => array('pollanswers','polltopics','pollvoters','pollquestions'),
   404         /* give the full name of the group, as in the db */
   405         'groups' => array('Polls Admin'),
   406         /* give the full name of the feature, as in the db */
   407         'features' => array('polls.edit'),
   408         /* give the full name of the block, including 'phpblock_', etc */
   409         'php_blocks' => array('phpblock_polls'),
   410         /* give all vars with their name */
   411         'vars'=> array()
   412     );
   413     return $out;
   414 }
   415 
   416 /**
   417 * Get path for the template files.
   418 *
   419 * @param    string  $path   subdirectory within the base template path
   420 * @return   string          full path to template directory
   421 *
   422 */
   423 function polls_templatePath ($path = '')
   424 {
   425     global $_CONF;
   426 
   427     if (empty ($path)) {
   428         $layout_path = $_CONF['path_layout'] . polls;
   429     } else {
   430         $layout_path = $_CONF['path_layout'] . polls . '/' . $path;
   431     }
   432 
   433     if (is_dir ($layout_path)) {
   434         $retval = $layout_path;
   435     } else {
   436         $retval = $_CONF['path'] . 'plugins/polls/templates';
   437         if (!empty ($path)) {
   438             $retval .= '/' . $path;
   439         }
   440     }
   441 
   442     return $retval;
   443 }
   444 
   445 
   446 /**
   447 * Shows a poll form
   448 *
   449 * Shows an HTML formatted poll for the given topic ID
   450 *
   451 * @param      string      $pid      ID for poll topic
   452 * @param      boolean     $showall  Show only the first question in the poll or all?
   453 * @param        int        $displaytype       Possible values 0 = Normal, 1 = In Block, 2 = autotag
   454 * @see function COM_pollResults
   455 * @see function COM_showPoll
   456 * @return       string  HTML Formatted Poll
   457 *
   458 */
   459 
   460 function POLLS_pollVote($pid, $showall = true, $displaytype = 0)
   461 {
   462     global $_CONF, $_TABLES, $LANG_POLLS, $LANG01, $_USER, $LANG25, $_IMAGE_TYPE;
   463     $retval = '';
   464 
   465     $topic = DB_query("SELECT topic,voters,commentcode,is_open,hideresults,owner_id "
   466         . ",group_id,perm_owner,perm_group,perm_anon,perm_members "
   467         . "FROM {$_TABLES['polltopics']} WHERE pid='$pid'" . COM_getPermSql('AND'));
   468     $ntopics = DB_numRows($topic);
   469 
   470     if ($ntopics == 0) {
   471         return $retval;
   472     }
   473 
   474     $P = DB_fetchArray($topic);
   475     
   476     if ((!isset($_COOKIE[$pid]) && !POLLS_ipAlreadyVoted($pid)) or ($P['is_open'] == 1)) {
   477         if ($ntopics == 1) {
   478             $questions_sql = "SELECT question,qid "
   479                 . "FROM {$_TABLES['pollquestions']} "
   480                 . "WHERE pid='$pid' ORDER BY qid";
   481 
   482             $questions = DB_query($questions_sql);
   483             $nquestions = DB_numRows($questions );
   484 
   485             if ($nquestions > 0) {
   486                 $poll = new Template($_CONF['path']
   487                                      . 'plugins/polls/templates/');
   488                 $poll->set_file(array('panswer'    => 'pollanswer.thtml',
   489                                       'block'      => 'pollblock.thtml',
   490                                       'pquestions' => 'pollquestions.thtml',
   491                                       'comments'   => 'pollcomments.thtml'));
   492                 $poll->set_var('xhtml', XHTML);
   493                 $poll->set_var('site_url', $_CONF['site_url']);
   494                 $poll->set_var('layout_url', $_CONF['layout_url']);
   495                 $poll->set_var('site_admin_url', $_CONF['site_admin_url']);
   496                 $poll->set_var('poll_id', $pid );
   497                 $poll->set_var('poll_topic', $P['topic'] );
   498                 $poll->set_var('num_votes', COM_numberFormat($P['voters']));
   499                 $poll->set_var('poll_vote_url', $_CONF['site_url']
   500                                                 . '/polls/index.php');
   501                 if (($nquestions == 1) || $showall) {
   502                     $poll->set_var('lang_vote', $LANG_POLLS['vote']);
   503                 } else {
   504                     $poll->set_var('lang_vote', $LANG_POLLS['start_poll']);
   505                 }
   506                 $poll->set_var('lang_votes', $LANG_POLLS['votes']);
   507 
   508                 $results = '';
   509                 if (($P['is_open'] == 0) || ($P['hideresults'] == 0) ||
   510                     (($P['hideresults'] == 1) &&
   511                         (
   512                         SEC_inGroup('Root') ||
   513                         (isset($_USER['uid'])
   514                             && ($_USER['uid'] == $P['owner_id']))
   515                         ))) {
   516                     $results = COM_createLink($LANG_POLLS['results'],
   517                         $_CONF['site_url'] . '/polls/index.php?pid=' . $pid
   518                         . '&amp;aid=-1');
   519                 }
   520                 $poll->set_var('poll_results', $results);
   521 
   522                 $access = SEC_hasAccess($topic['owner_id'], $topic['group_id'],
   523                                 $topic['perm_owner'], $topic['perm_group'],
   524                                 $topic['perm_members'], $topic['perm_anon']);
   525                 if ($access == 3) {
   526                     $editlink = COM_createLink($LANG25[27], $_CONF['site_admin_url']
   527                         . '/plugins/polls/index.php?mode=edit&amp;pid=' . $pid);
   528                     $poll->set_var('edit_link', $editlink);
   529                     $editicon = $_CONF['layout_url'] . '/images/edit.' . $_IMAGE_TYPE;
   530                     $icon_attr = array('title' => $LANG25[27]);
   531                     $editiconhtml = COM_createImage($editicon, $LANG25[27], $icon_attr);
   532                     $editlink = COM_createLink($editiconhtml, $_CONF['site_admin_url']
   533                         . '/plugins/polls/index.php?mode=edit&amp;pid=' . $pid);
   534                     $poll->set_var('edit_icon', $editlink);
   535                 }
   536 
   537                 if (array_key_exists('aid', $_POST)) {
   538                     $aid = $_POST['aid'];
   539                 } else {
   540                     $aid = array();
   541                 }
   542 
   543                 for ($j = 0; $j < $nquestions; $j++) {
   544                     $Q = DB_fetchArray($questions);
   545                     $poll->set_var('poll_question', $Q['question']);
   546                     $poll->set_var('question_id', $j);
   547 
   548                     $notification = '';
   549                     $filter = '';
   550                     if (!$showall) {
   551                         $nquestions--;
   552                         if ($nquestions > 0) {
   553                             $notification = $LANG25[35] . " $nquestions "
   554                                           . $LANG25[36];
   555                         }
   556                         $filter = "AND qid='0'";
   557                         $nquestions = 1;
   558                     } else {
   559                         $filter = "AND qid = '{$Q['qid']}'";
   560                         $poll->set_var('lang_question_number', " ". ($j+1).":");
   561                     }
   562                     $answer_sql = "SELECT answer,aid "
   563                         . "FROM {$_TABLES['pollanswers']} "
   564                         . "WHERE pid='$pid'$filter ORDER BY qid, aid";
   565                     $answers = DB_query($answer_sql);
   566                     $nanswers = DB_numRows($answers );
   567                     for($i=0; $i<$nanswers; $i++) {
   568                         $A = DB_fetchArray($answers );
   569                         if (($j < count($aid)) && ($aid[$j] == $A['aid'])) {
   570                             $poll->set_var('selected', ' checked');
   571                         }
   572                         $poll->set_var('answer_id', $A['aid']);
   573                         $poll->set_var('answer_text', $A['answer']);
   574                         $poll->parse('poll_answers', 'panswer', true);
   575                         $poll->clear_var('selected');
   576                     }
   577                     $poll->parse('poll_questions', 'pquestions', true);
   578                     $poll->clear_var('poll_answers');
   579                 }
   580                 if ($nquestions > 1) {
   581                     $poll->set_var('poll_topic', $LANG25['34'] . " " . $P['topic']);
   582                     $poll->set_var('lang_question', $LANG25[31]);
   583                 }
   584                 $poll->set_var('lang_polltopics', $LANG_POLLS['polltopics']);
   585                 $poll->set_var('poll_notification', $notification);
   586                 if($P['commentcode'] >= 0 ) {
   587                     $num_comments = DB_count($_TABLES['comments'],
   588                             array('sid', 'type'), array($pid, 'polls'));
   589                     $poll->set_var('num_comments',
   590                             COM_numberFormat($num_comments));
   591                     $poll->set_var('lang_comments', $LANG01[3]);
   592                     $poll->set_var('poll_comments_url', $_CONF['site_url'] .
   593                         '/polls/index.php?pid=' . $pid . '#comments');
   594                     $poll->parse('poll_comments', 'comments', true);
   595                 } else {
   596                     $poll->set_var('poll_comments', '');
   597                     $poll->set_var('poll_comments_url', '');
   598                 }
   599                 $retval =  $poll->finish($poll->parse('output', 'block')) . LB;
   600 
   601                 if ($showall && ($P['commentcode'] >= 0 AND $displaytype != 2)) {
   602                     $delete_option = (SEC_hasRights('polls.edit') &&
   603                         SEC_hasAccess($P['owner_id'], $P['group_id'],
   604                         $P['perm_owner'], $P['perm_group'], $P['perm_members'],
   605                         $P['perm_anon']) == 3 ? true : false);
   606 
   607                     require_once $_CONF['path_system'] . 'lib-comment.php';
   608 
   609                     $order = '';
   610                     $mode  = '';
   611                     $retval .= CMT_userComments($pid, $P['topic'], 'polls',
   612                                                 $order, $mode, 0, 1, false,
   613                                                 $delete_option, $P['commentcode']);
   614                 }
   615             }
   616         }
   617     } else {
   618         $retval .= POLLS_pollResults($pid, 0, '', '', $displaytype);
   619     }
   620 
   621     return $retval;
   622 }
   623 
   624 /**
   625 * This shows a poll
   626 *
   627 * This will determine if a user needs to see the poll form OR the poll result.
   628 *
   629 * @param        int     $size           Size in pixels of poll results
   630 * @param        string  $pid            Poll topic ID to show (optional)
   631 * @param        bool    $showall        Show only the first question or all
   632 * @param        int     $displaytype    Possible values 0 = Normal, 1 = In Block, 2 = autotag 
   633 * @return       string  HTML formatted string of poll
   634 * @see function COM_pollVote
   635 * @see function COM_pollResults
   636 *
   637 */
   638 function POLLS_showPoll($size, $pid = '', $showall = false, $displaytype = 0)
   639 {
   640     global $_CONF, $_TABLES, $_PO_CONF, $LANG_POLLS;
   641 
   642     $retval = '';
   643 
   644     DB_query("DELETE FROM {$_TABLES['pollvoters']} WHERE date < UNIX_TIMESTAMP() - {$_PO_CONF['polladdresstime']}");
   645 
   646     if (!empty($pid)) {
   647         $Q['is_open'] = DB_getItem($_TABLES['polltopics'], 'is_open', "pid = '".$pid."'");
   648 
   649         if (($displaytype == 2) && ($Q['is_open'] == 0)) {
   650             $retval = '<div class="poll-autotag-message">'
   651                     . $LANG_POLLS['pollclosed'] . '</div>';
   652         }        
   653         if (!isset($_COOKIE['poll-' . $pid]) && !POLLS_ipAlreadyVoted($pid) &&
   654                 ($Q['is_open'] == 1)) {
   655             $retval .= POLLS_pollVote($pid, $showall, $displaytype);
   656         } else {
   657             $retval .= POLLS_pollResults($pid, $size, '', '', $displaytype);
   658         }
   659     } else {
   660         $result = DB_query("SELECT pid,topic,is_open FROM {$_TABLES['polltopics']} WHERE display = 1" . COM_getPermSql('AND') . " ORDER BY date DESC");
   661         $nrows = DB_numRows($result);
   662 
   663         $title = DB_getItem($_TABLES['blocks'], 'title', "name='poll_block'");
   664 
   665         if ($nrows > 0) {
   666             for ($i = 1; $i <= $nrows; $i++) {
   667                 $Q = DB_fetchArray($result);
   668                 $pid = $Q['pid'];
   669                 if ($displaytype == 1) { // in the poll block
   670                     $showall = false;
   671                 } else { // assume we're in polls/index.php
   672                     $retval .= COM_startBlock($title);
   673                     $showall = true;
   674                 }
   675 
   676                 if (!isset($_COOKIE['poll-' . $pid]) &&
   677                         !POLLS_ipAlreadyVoted($pid) && ($Q['is_open'] == 1)) {
   678                     $retval .= POLLS_pollVote($pid, $showall, $displaytype);
   679                 } else {
   680                     $retval .= POLLS_pollResults($pid, $size, '', '',
   681                                                  $displaytype);
   682                 }
   683 
   684                 if ($displaytype == 1) { // in the poll block
   685                     if (($i < $nrows) && !empty($retval)) {
   686                         $retval .= '<div class="poll-divider"></div>';
   687                     }
   688                 } else {
   689                     $retval .= COM_endBlock();
   690                 }
   691             }
   692         }
   693     }
   694 
   695     return $retval;
   696 }
   697 
   698 /**
   699 * Saves a user's vote
   700 *
   701 * Saves the users vote, if allowed for the poll $pid.
   702 * NOTE: all data comes from form post
   703 *
   704 * @param    string   $pid   poll id
   705 * @param    array    $aid   selected answers
   706 * @return   string   HTML for poll results
   707 *
   708 */
   709 function POLLS_pollsave($pid, $aid)
   710 {
   711     global $_TABLES, $LANG_POLLS;
   712 
   713     $retval = '';
   714 
   715     if (POLLS_ipAlreadyVoted ($pid)) {
   716         exit;
   717     }
   718 
   719     DB_change($_TABLES['polltopics'],'voters',"voters + 1",'pid',$pid,'',true);
   720     // This call to DB-change will properly supress the insertion of quotes around $value in the sql
   721     $answers = count($aid);
   722     for ($i = 0; $i < $answers; $i++) {
   723         DB_change(
   724             $_TABLES['pollanswers'],
   725             'votes',
   726             "votes + 1",
   727             array('pid', 'qid', 'aid'),
   728             array($pid,  $i,    COM_applyFilter($aid[$i], true)),
   729             '',
   730             true
   731         );
   732     }
   733 
   734     // This always does an insert so no need to provide key_field and key_value args
   735     DB_save($_TABLES['pollvoters'],'ipaddress,date,pid',"'{$_SERVER['REMOTE_ADDR']}'," . time() . ",'$pid'");
   736     $retval .= COM_startBlock ($LANG_POLLS['savedvotetitle'], '',
   737                        COM_getBlockTemplate ('_msg_block', 'header'))
   738         . $LANG_POLLS['savedvotemsg'] . ' "'
   739         . DB_getItem ($_TABLES['polltopics'], 'topic', "pid = '{$pid}'")
   740         . '"'
   741         . COM_endBlock (COM_getBlockTemplate ('_msg_block', 'footer'))
   742         . POLLS_pollResults($pid);
   743 
   744     return $retval;
   745 }
   746 
   747 /**
   748 * Shows the results of a poll
   749 *
   750 * Shows the poll results for a given poll topic
   751 *
   752 * @param        string      $pid        ID for poll topic to show
   753 * @param        int         $scale      Size in pixels to scale formatted results to
   754 * @param        string      $order      'ASC' or 'DESC' for Comment ordering (SQL statment ordering)
   755 * @param        string      $mode       Comment Mode possible values 'nocomment', 'flat', 'nested', 'threaded'
   756 * @param        int        $displaytype       Possible values 0 = Normal, 1 = In Block, 2 = autotag
   757 * @see POLLS_pollVote
   758 * @see POLLS_showPoll
   759 * @return     string   HTML Formated Poll Results
   760 *
   761 */
   762 function POLLS_pollResults($pid, $scale=400, $order='', $mode='', $displaytype = 0)
   763 {
   764     global $_CONF, $_TABLES, $_USER, $_IMAGE_TYPE,
   765            $_PO_CONF, $LANG01, $LANG_POLLS, $_COM_VERBOSE, $LANG25;
   766 
   767     $retval = '';
   768     $topic_sql = "SELECT topic,voters,is_open,hideresults,commentcode,owner_id,group_id,"
   769         . "perm_owner,perm_group,perm_members,perm_anon "
   770         . "FROM {$_TABLES['polltopics']} WHERE pid='$pid'";
   771     $topic = DB_query($topic_sql);
   772     $P = DB_fetchArray($topic);
   773 
   774     if(SEC_hasAccess($P['owner_id'], $P['group_id'], $P['perm_owner'],
   775         $P['perm_group'], $P['perm_members'], $P['perm_anon']) == 0 ) {
   776         return $retval;
   777     }
   778 
   779     if ((
   780             $P['hideresults'] == 0
   781         ) || (
   782             ($P['hideresults'] == 1) && (isset($_USER['uid']) &&
   783                                          ($_USER['uid'] == $P['owner_id']))
   784         ) || (
   785             ($P['hideresults'] == 1) && (SEC_inGroup('Root'))
   786         )
   787     ) {
   788         $retval = '';
   789     } else {
   790         if ($displaytype == 2) {
   791             $retval = '<div class="poll-autotag-message">' . $LANG_POLLS['pollhidden']. "</div>";
   792         }
   793         
   794         return $retval;
   795     }
   796     
   797     $ntopic = DB_numRows($topic );
   798     if ($ntopic == 1) {
   799         $questions_sql = "SELECT qid,pid,question "
   800             . "FROM {$_TABLES['pollquestions']} "
   801             . "WHERE pid='$pid' "
   802             . "ORDER BY qid";
   803         $questions = DB_query ($questions_sql);
   804         $nquestions = DB_numRows($questions);
   805 
   806         if ($_COM_VERBOSE) {
   807             COM_errorLog("got $questions questions in COM_pollResults", 1 );
   808         }
   809 
   810         if ($nquestions > 0){
   811             $poll = new Template($_CONF['path'] . 'plugins/polls/templates/' );
   812             $poll->set_file(array('result' => 'pollresult.thtml',
   813                 'question' => 'pollquestion.thtml',
   814                 'comments' => 'pollcomments.thtml',
   815                 'votes_bar' => 'pollvotes_bar.thtml',
   816                 'votes_num' => 'pollvotes_num.thtml' ));
   817             $poll->set_var('xhtml', XHTML);
   818             $poll->set_var('site_url', $_CONF['site_url']);
   819             $poll->set_var('site_admin_url', $_CONF['site_admin_url']);
   820             $poll->set_var('layout_url', $_CONF['layout_url']);
   821             $poll->set_var('poll_topic', $P['topic']);
   822             $poll->set_var('poll_id', $pid);
   823             $poll->set_var('num_votes', COM_numberFormat($P['voters']));
   824             $poll->set_var('lang_votes', $LANG_POLLS['votes']);
   825             $access = SEC_hasAccess($P['owner_id'],$P['group_id'],$P['perm_owner'],
   826                 $P['perm_group'],$P['perm_members'],$P['perm_anon']);
   827             if ($access == 3) {
   828                 $editlink = COM_createLink($LANG25[27], $_CONF['site_admin_url']
   829                     . '/plugins/polls/index.php?mode=edit&amp;pid=' . $pid );
   830                 $poll->set_var('edit_link', $editlink);
   831                 $editicon = $_CONF['layout_url'] . '/images/edit.' . $_IMAGE_TYPE;
   832                 $icon_attr = array('title' => $LANG25[27]);
   833                 $editiconhtml = COM_createImage($editicon, $LANG25[27], $icon_attr);
   834                 $editlink = COM_createLink($editiconhtml, $_CONF['site_admin_url']
   835                     . '/plugins/polls/index.php?mode=edit&amp;pid=' . $pid );
   836                 $poll->set_var('edit_icon', $editlink);
   837             }
   838             if ($_PO_CONF['answerorder'] == 'voteorder'){
   839                 $order = "votes DESC";
   840             } else {
   841                 $order = "aid";
   842             }
   843 
   844             for ($j = 0; $j < $nquestions; $j++) {
   845                 $Q = DB_fetchArray($questions);
   846 
   847                 if ($nquestions >= 1) {
   848                     $counter = ($j + 1) . "/$nquestions: " ;
   849                 }
   850                 $poll->set_var('poll_question', $counter . $Q['question']);
   851 
   852                 $answer_sql = "SELECT votes,answer,remark "
   853                     . "FROM {$_TABLES['pollanswers']} "
   854                     . "WHERE pid='$pid' and qid='{$Q['qid']}' "
   855                     . "ORDER BY $order";
   856                 $answers = DB_query ($answer_sql);
   857                 $nanswers = DB_numRows($answers);
   858 
   859                 $a_summ_sql = "SELECT SUM(votes) as votesumm FROM {$_TABLES['pollanswers']} "
   860                     . "WHERE pid='$pid' and qid='{$Q['qid']}' "
   861                     . "GROUP BY qid";
   862                 $a_summ = DB_query ($a_summ_sql);
   863                 $S = DB_fetchArray($a_summ);
   864 
   865                 if ($_COM_VERBOSE) {
   866                     COM_errorLog("got $answers answers in COM_pollResults", 1 );
   867                 }
   868                 for ($i=1; $i<=$nanswers; $i++) {
   869                     $A = DB_fetchArray($answers);
   870                     if ($S['votesumm'] == 0) {
   871                         $percent = 0;
   872                     } else {
   873                         $percent = $A['votes'] / $S['votesumm'];
   874                     }
   875                     $poll->set_var('cssida', 1);
   876                     $poll->set_var('cssidb', 2);
   877                     $poll->set_var('answer_text', $A['answer']);
   878                     $poll->set_var('remark_text', $A['remark']);
   879                     $poll->set_var('answer_counter', $i);
   880                     $poll->set_var('answer_odd', (($i - 1) % 2));
   881                     $poll->set_var('answer_num', COM_numberFormat($A['votes']));
   882                     $poll->set_var('answer_percent',
   883                                     sprintf('%.2f', $percent * 100));
   884                     if ($scale < 120) {
   885                         $poll->parse('poll_votes', 'votes_num', true );
   886                     } else {
   887                         $width = (int)($percent * $scale);
   888                         $poll->set_var('bar_width', $width);
   889                         $poll->parse('poll_votes', 'votes_bar', true);
   890                     }
   891                 }
   892                 $poll->parse('poll_questions', 'question', true);
   893                 $poll->clear_var('poll_votes');
   894                 if (($scale < 100) && ($j < 1)) {
   895                     $url = $_CONF['site_url'] . "/polls/index.php?pid=$pid";
   896                     $poll->set_var('notification', COM_createLink($LANG25[40], $url). "<br" . XHTML . ">");
   897                     break;
   898                 }
   899             }
   900 
   901             if($P['commentcode'] >= 0 ) {
   902                 $num_comments = DB_count($_TABLES['comments'],
   903                         array('sid', 'type' ), array($pid, 'polls' ));
   904                 $poll->set_var('num_comments',
   905                         COM_numberFormat($num_comments));
   906                 $poll->set_var('lang_comments', $LANG01[3]);
   907                 $poll->set_var('poll_comments_url', $_CONF['site_url'] .
   908                         '/polls/index.php?pid=' . $pid . '#comments');
   909                 $poll->parse('poll_comments', 'comments', true);
   910             } else {
   911                 $poll->set_var('poll_comments_url', '');
   912                 $poll->set_var('poll_comments', '');
   913             }
   914 
   915             $poll->set_var('lang_polltopics', $LANG_POLLS['polltopics'] );
   916 
   917             $retval .= $poll->finish($poll->parse('output', 'result' ));
   918 
   919             if($scale > 399 && $P['commentcode'] >= 0 && $displaytype != 2) {
   920                 $delete_option = (SEC_hasRights('polls.edit') &&
   921                     SEC_hasAccess($P['owner_id'], $P['group_id'],
   922                     $P['perm_owner'], $P['perm_group'], $P['perm_members'],
   923                     $P['perm_anon']) == 3 ? true : false);
   924                 require_once $_CONF['path_system'] . 'lib-comment.php';
   925                 $retval .= CMT_userComments($pid, $P['topic'], 'polls',
   926                                             $order, $mode, 0, 1, false,
   927                                             $delete_option, $P['commentcode']);
   928             }
   929         }
   930     }
   931 
   932     return $retval;
   933 }
   934 
   935 /**
   936 * Check if we already have a vote from this IP address
   937 *
   938 * @param    string  $pid    Poll ID
   939 * @param    string  $ip     (optional) IP address
   940 * @return   boolean         true: IP already voted; false: didn't
   941 *
   942 */
   943 function POLLS_ipAlreadyVoted($pid, $ip = '' )
   944 {
   945     global $_TABLES;
   946 
   947     $retval = false;
   948 
   949     if(empty($ip )) {
   950         $ip = $_SERVER['REMOTE_ADDR'];
   951     }
   952 
   953     if(DB_count($_TABLES['pollvoters'],
   954                  array('ipaddress', 'pid'),
   955                  array($ip, $pid)) > 0) {
   956         $retval = true;
   957     }
   958 
   959     return $retval;
   960 }
   961 
   962 /**
   963 * Display the current poll(s) in a side block
   964 *
   965 * @return   string  HTML for the poll(s) to be displayed (or an empty string)
   966 *
   967 */
   968 function phpblock_polls()
   969 {
   970     return POLLS_showPoll(60, '', false, 1);
   971 }
   972 
   973 
   974 /**
   975 * Returns the URL of the plugin's icon
   976 *
   977 * @return   string      URL of the icon
   978 *
   979 */
   980 function plugin_geticon_polls ()
   981 {
   982     global $_CONF;
   983     return $_CONF['site_url'] . '/polls/images/polls.png';
   984 }
   985 
   986 /**
   987 * Plugin should display [a] comment[s]
   988 *
   989 * @param   string  $id     Unique idenifier for item comment belongs to
   990 * @param   int     $cid    Comment id to display (possibly including sub-comments)
   991 * @param   string  $title  Page/comment title
   992 * @param   string  $order  'ASC' or 'DESC' or blank
   993 * @param   string  $format 'threaded', 'nested', or 'flat'
   994 * @param   int     $page   Page number of comments to display
   995 * @param   boolean $view   True to view comment (by cid), false to display (by $pid)
   996 * @return  mixed   results of calling the plugin_displaycomment_ function
   997 */
   998 function plugin_displaycomment_polls ($id, $cid, $title, $order, $format, $page, $view)
   999 {
  1000     global $_TABLES, $LANG_ACCESS;
  1001 
  1002     $retval = '';
  1003 
  1004     $sql = "SELECT COUNT(*) AS count, commentcode, owner_id, group_id, perm_owner, "
  1005         . "perm_group, perm_members, perm_anon "
  1006         . "FROM {$_TABLES['polltopics']} "
  1007         . "WHERE (pid = '$id')" . COM_getPermSQL('AND')
  1008         . ' GROUP BY pid';
  1009     $result = DB_query ($sql);
  1010     $A = DB_fetchArray ($result);
  1011     $allowed = $A['count'];
  1012 
  1013     if ($allowed == 1) {
  1014         $delete_option = (SEC_hasRights ('polls.edit') &&
  1015                 (SEC_hasAccess ($A['owner_id'], $A['group_id'],
  1016                     $A['perm_owner'], $A['perm_group'], $A['perm_members'],
  1017                     $A['perm_anon']) == 3));
  1018         $retval .= CMT_userComments ($id, $title, 'polls', $order, $format,
  1019                                      $cid, $page, $view, $delete_option,
  1020                                      $A['commentcode']);
  1021     } else {
  1022         $retval .= COM_startBlock ($LANG_ACCESS['accessdenied'], '',
  1023                         COM_getBlockTemplate ('_msg_block', 'header'))
  1024                 . $LANG_ACCESS['storydenialmsg']
  1025                 . COM_endBlock (COM_getBlockTemplate ('_msg_block', 'footer'));
  1026     }
  1027 
  1028     return $retval;
  1029 }
  1030 
  1031 function plugin_getListField_polls($fieldname, $fieldvalue, $A, $icon_arr)
  1032 {
  1033     global $_CONF, $LANG25, $LANG_ACCESS, $_USER;
  1034 
  1035     $retval = '';
  1036 
  1037     $access = SEC_hasAccess ($A['owner_id'], $A['group_id'],
  1038                              $A['perm_owner'], $A['perm_group'],
  1039                              $A['perm_members'], $A['perm_anon']);
  1040     if ($access > 0) {
  1041         switch($fieldname) {
  1042             case 'edit':
  1043                 if ($access == 3) {
  1044                     $retval = COM_createLink($icon_arr['edit'],
  1045                         "{$_CONF['site_admin_url']}/plugins/polls/index.php?mode=edit&amp;pid={$A['pid']}");
  1046                 }
  1047                 break;
  1048             case 'unixdate':
  1049                 $retval = strftime ($_CONF['daytime'], $A['unixdate']);
  1050                 break;
  1051             case 'topic':
  1052                 if (($A['hideresults'] == 0) ||
  1053                     (isset($_USER['uid']) && ($_USER['uid'] == $A['owner_id'])) || SEC_inGroup('Root')) {
  1054                     $retval = COM_createLink($fieldvalue,
  1055                         "{$_CONF['site_url']}/polls/index.php?pid={$A['pid']}");
  1056                 } else {
  1057                     $retval = $fieldvalue;
  1058                 }
  1059                 break;
  1060             case 'access':
  1061                 if ($access == 3) {
  1062                     $access = $LANG_ACCESS['edit'];
  1063                 } else {
  1064                     $access = $LANG_ACCESS['readonly'];
  1065                 }
  1066                 $retval = $access;
  1067                 break;
  1068             case 'is_open':
  1069                 if ($A['is_open'] == 1) {
  1070                     $retval = $LANG25[25];
  1071                 } else {
  1072                     $retval = $LANG25[26];
  1073                 }
  1074                 break;
  1075             case 'display':
  1076                 if ($A['display'] == 1) {
  1077                     $retval = $LANG25[25];
  1078                 } else {
  1079                     $retval = $LANG25[26];
  1080                 }
  1081                 break;
  1082             case 'voters':
  1083                 $retval = COM_numberFormat ($A['voters']);
  1084                 break;
  1085             default:
  1086                 $retval = $fieldvalue;
  1087                 break;
  1088         }
  1089     } else {
  1090         $retval = false;
  1091     }
  1092 
  1093     return $retval;
  1094 }
  1095 
  1096 /**
  1097 * Set template variables
  1098 *
  1099 * @param    string  $templatename   name of template, e.g. 'header'
  1100 * @param    ref     $template       reference of actual template
  1101 * @return   void
  1102 *
  1103 * Note: A plugin should use its name as a prefix for the names of its
  1104 * template variables, e.g. 'polls_xxx' and 'lang_polls_xxx'.
  1105 * 'button_polls' is an exception, as such a variable existed for header.thtml
  1106 * in Geeklog 1.3.11 and earlier, where the Polls were an integral part
  1107 * of Geeklog. It is added here for backward-compatibility.
  1108 *
  1109 */
  1110 function plugin_templatesetvars_polls ($templatename, &$template)
  1111 {
  1112     global $LANG_POLLS;
  1113 
  1114     if ($templatename == 'header') {
  1115         $template->set_var ('button_polls', $LANG_POLLS['polls']);
  1116     }
  1117 }
  1118 
  1119 function plugin_getheadercode_polls()
  1120 {
  1121     global $_CONF;
  1122 
  1123     $str = null;
  1124     $str = LB . '<link rel="stylesheet" type="text/css" href="'
  1125         . $_CONF['site_url'] . '/polls/style.css"' . XHTML . '>';
  1126 
  1127     return $str;
  1128 }
  1129 
  1130 /**
  1131 * Update the Polls plugin
  1132 *
  1133 * @return   int     Number of message to display (true = generic success msg)
  1134 *
  1135 */
  1136 function plugin_upgrade_polls()
  1137 {
  1138     global $_CONF, $_TABLES, $_DB_dbms;
  1139 
  1140     $installed_version = DB_getItem($_TABLES['plugins'], 'pi_version',
  1141                                     "pi_name = 'polls'");
  1142     $code_version = plugin_chkVersion_polls();
  1143     if ($installed_version == $code_version) {
  1144         // nothing to do
  1145         return true;
  1146     }
  1147 
  1148     require_once $_CONF['path'] . 'plugins/polls/autoinstall.php';
  1149 
  1150     if (! plugin_compatible_with_this_version_polls('polls')) {
  1151         return 3002;
  1152     }
  1153 
  1154     $inst_parms = plugin_autoinstall_polls('polls');
  1155     $pi_gl_version = $inst_parms['info']['pi_gl_version'];
  1156 
  1157     require_once $_CONF['path'] . 'plugins/polls/sql/'
  1158                                 . $_DB_dbms . '_updates.php';
  1159 
  1160     $current_version = $installed_version;
  1161     $done = false;
  1162     while (! $done) {
  1163         switch ($current_version) {
  1164         case '2.0.1':
  1165             $current_version = '2.0.2';
  1166             break;
  1167 
  1168         case '2.0.2':
  1169             $current_version = '2.1.0';
  1170             break;
  1171 
  1172         case '2.1.0':
  1173             if (isset($_UPDATES[$current_version])) {
  1174                 $_SQL = $_UPDATES[$current_version];
  1175                 foreach ($_SQL as $sql) {
  1176                     DB_query($sql);
  1177                 }
  1178             }
  1179             
  1180             update_ConfValues_2_1_0();            
  1181             
  1182             $current_version = '2.1.1';
  1183             break;
  1184             
  1185         default:
  1186             $done = true;
  1187         }
  1188     }
  1189 
  1190     DB_query("UPDATE {$_TABLES['plugins']} SET pi_version = '$code_version', pi_gl_version = '$pi_gl_version' WHERE pi_name = 'polls'");
  1191 
  1192     return true;
  1193 }
  1194 
  1195 /**
  1196 * Called during site migration - handle changed URLs or paths
  1197 *
  1198 * @param    array   $old_conf   contents of the $_CONF array on the old site
  1199 * @param    boolean             true on success, otherwise false
  1200 *
  1201 */
  1202 function plugin_migrate_polls($old_conf)
  1203 {
  1204     global $_CONF;
  1205 
  1206     $tables = array(
  1207         'pollanswers'   => 'aid, answer',
  1208         'pollquestions' => 'qid, question',
  1209         'polltopics'    => 'pid, topic'
  1210     );
  1211 
  1212     if ($old_conf['site_url'] != $_CONF['site_url']) {
  1213         INST_updateSiteUrl($old_conf['site_url'], $_CONF['site_url'], $tables);
  1214     }
  1215 
  1216     return true;
  1217 }
  1218 
  1219 /**
  1220 * Return information for a poll                                                                                                                     
  1221 *
  1222 * @param    string  $pid        poll ID or '*'
  1223 * @param    string  $what       comma-separated list of properties
  1224 * @param    int     $uid        user ID or 0 = current user
  1225 * @param    array   $options    (reserved for future extensions)
  1226 * @return   mixed               string or array of strings with the information
  1227 *
  1228 */
  1229 function plugin_getiteminfo_polls($pid, $what, $uid = 0, $options = array())
  1230 {
  1231     global $_CONF, $_TABLES;
  1232 
  1233     // parse $what to see what we need to pull from the database
  1234     $properties = explode(',', $what);
  1235     $fields = array();
  1236     foreach ($properties as $p) {
  1237         switch ($p) {
  1238         case 'date-modified':
  1239             $fields[] = 'UNIX_TIMESTAMP(date) AS unixdate';
  1240             break;
  1241         case 'id':
  1242             $fields[] = 'pid';
  1243             break;
  1244         case 'title':
  1245             $fields[] = 'topic';
  1246             break;
  1247         case 'url':
  1248             // needed for $pid == '*', but also in case we're only requesting
  1249             // the URL (so that $fields isn't emtpy)
  1250             $fields[] = 'pid';
  1251             break;
  1252         default:
  1253             // nothing to do
  1254             break;
  1255         }
  1256     }
  1257 
  1258     $fields = array_unique($fields);
  1259 
  1260     if (count($fields) == 0) {
  1261         $retval = array();
  1262 
  1263         return $retval;
  1264     }
  1265 
  1266     // prepare SQL request
  1267     if ($pid == '*') {
  1268         $where = '';
  1269         $permOp = 'WHERE';
  1270     } else {
  1271         $where = " WHERE pid = '" . addslashes($pid) . "'";
  1272         $permOp = 'AND';
  1273     }
  1274     if ($uid > 0) {
  1275         $permSql = COM_getPermSql($permOp, $uid);
  1276     } else {
  1277         $permSql = COM_getPermSql($permOp);
  1278     }
  1279     $sql = "SELECT " . implode(',', $fields)
  1280             . " FROM {$_TABLES['polltopics']}" . $where . $permSql;
  1281     if ($pid != '*') {
  1282         $sql .= ' LIMIT 1';
  1283     }
  1284 
  1285     $result = DB_query($sql);
  1286     $numRows = DB_numRows($result);
  1287 
  1288     $retval = array();
  1289     for ($i = 0; $i < $numRows; $i++) {
  1290         $A = DB_fetchArray($result);
  1291 
  1292         $props = array();
  1293         foreach ($properties as $p) {
  1294             switch ($p) {
  1295             case 'date-modified':
  1296                 $props['date-modified'] = $A['unixdate'];
  1297                 break;
  1298             case 'id':
  1299                 $props['id'] = $A['pid'];
  1300                 break;
  1301             case 'title':
  1302                 $props['title'] = $A['topic'];
  1303                 break;
  1304             case 'url':
  1305                 if (empty($A['pid'])) {
  1306                     $props['url'] = $_CONF['site_url']
  1307                                   . '/polls/index.php?pid=' . $pid
  1308                                   . '&amp;aid=-1';
  1309                 } else {
  1310                     $props['url'] = $_CONF['site_url']
  1311                                   . '/polls/index.php?pid=' . $A['pid']
  1312                                   . '&amp;aid=-1';
  1313                 }
  1314                 break;
  1315             default:
  1316                 // return empty string for unknown properties
  1317                 $props[$p] = '';
  1318                 break;
  1319             }
  1320         }
  1321 
  1322         $mapped = array();
  1323         foreach ($props as $key => $value) {
  1324             if ($pid == '*') {
  1325                 if ($value != '') {
  1326                     $mapped[$key] = $value;
  1327                 }
  1328             } else {
  1329                 $mapped[] = $value;
  1330             }
  1331         }
  1332 
  1333         if ($pid == '*') {
  1334             $retval[] = $mapped;
  1335         } else {
  1336             $retval = $mapped;
  1337             break;
  1338         }
  1339     }
  1340 
  1341     if (($pid != '*') && (count($retval) == 1)) {
  1342         $retval = $retval[0];
  1343     }
  1344 
  1345     return $retval;
  1346 }
  1347 
  1348 /**
  1349 * Provide URL of a documentation file
  1350 *
  1351 * @param    string  $file   documentation file being requested, e.g. 'config'
  1352 * @return   mixed           URL or false when not available
  1353 *
  1354 */
  1355 function plugin_getdocumentationurl_polls($file)
  1356 {
  1357     global $_CONF;
  1358 
  1359     static $docurl;
  1360 
  1361     switch ($file) {
  1362     case 'index':
  1363     case 'config':
  1364         if (isset($docurl)) {
  1365             $retval = $docurl;
  1366         } else {
  1367             $doclang = COM_getLanguageName();
  1368             $docs = 'docs/' . $doclang . '/polls.html';
  1369             if (file_exists($_CONF['path_html'] . $docs)) {
  1370                 $retval = $_CONF['site_url'] . '/' . $docs;
  1371             } else {
  1372                 $retval = $_CONF['site_url'] . '/docs/english/polls.html';
  1373             }
  1374             $docurl = $retval;
  1375         }
  1376         break;
  1377 
  1378     default:
  1379         $retval = false;
  1380         break;
  1381     }
  1382 
  1383     return $retval;
  1384 }
  1385 
  1386 /**
  1387 * Provide URL and ID for the link to a comment's parent
  1388 *
  1389 * @return   array   array consisting of the base URL and the ID name
  1390 *
  1391 */
  1392 function plugin_getcommenturlid_polls()
  1393 {
  1394     global $_CONF;
  1395 
  1396     $tmp = array(
  1397         $_CONF['site_url'] . '/polls/index.php',
  1398         'pid'
  1399     );
  1400 
  1401     return $tmp;
  1402 }
  1403 
  1404 /**
  1405 * Poll Autotags
  1406 * [poll: pid] - Displays a link to a poll using the Poll Topic as the title. A alternate title may be specified. 
  1407 * [poll_vote: pid pid class:poll-autotag showall:1] - Class and showall not required. Class specifies the css class and Showall if set to 1, shows all questions
  1408 * [poll_result: pid class:poll-autotag] - Class not required. Class specifies the css class
  1409 *
  1410 */
  1411 function plugin_autotags_polls($op, $content = '', $autotag = '')
  1412 {
  1413     global $_CONF, $_TABLES;
  1414 
  1415     if ($op == 'tagname' ) {
  1416         return array('poll_vote', 'poll_result', 'poll');
  1417     } elseif ($op == 'parse') {
  1418         $pid = COM_applyFilter($autotag['parm1']);
  1419         $showall = false;
  1420 
  1421         switch ($autotag['tag']) {
  1422         case 'poll':
  1423             if (!empty($autotag['parm2'])) {
  1424                 $title = COM_applyFilter($autotag['parm2']);
  1425             } else {
  1426                 $title = DB_getItem($_TABLES['polltopics'], 'topic',
  1427                                     "pid = '$pid'");
  1428             }
  1429 
  1430             $retval = COM_createLink($title, $_CONF['site_url']
  1431                             . '/polls/index.php?pid=' . $pid . '&amp;aid=-1');
  1432             break;
  1433 
  1434         case 'poll_vote':
  1435         case 'poll_result':
  1436             $px = explode(' ', trim($autotag['parm2']));
  1437             $css_class = "poll-autotag";
  1438 
  1439             if (is_array($px)) {
  1440                 foreach ($px as $part) {
  1441                     if (substr($part, 0, 6) == 'class:') {
  1442                         $a = explode(':', $part);
  1443                         $css_class = $a[1];
  1444                     } elseif (substr($part, 0, 8) == 'showall:') {
  1445                         $a = explode(':', $part);
  1446                         $val = $a[1];
  1447                         if ($val == 1) {
  1448                             $showall = true;
  1449                         }
  1450                     } else {
  1451                         break;
  1452                     }
  1453                 }
  1454             }
  1455 
  1456             if ($autotag['tag'] == 'poll_vote') {
  1457                 $retval = POLLS_showPoll(0, $pid, $showall, 2);
  1458             } else {
  1459                 $retval = POLLS_pollResults($pid, 0,'', '', 2);
  1460             }
  1461             $retval = '<div class="' . $css_class . '">' . $retval . '</div>';
  1462             break;
  1463         }
  1464 
  1465         $content = str_replace($autotag['tagstr'], $retval, $content);
  1466     }
  1467 
  1468     return $content;
  1469 }
  1470 
  1471 ?>