<?php

/**
  * BLOG:CMS: PHP/MySQL Personal Content Management System (CMS)
  * http://blogcms.com/
  * ----------------------------------------------------------------
  *
  * Copyright (C) 2003-2005 Radek HULÁN, Rodrigo Moraes
  * http://hulan.cz/contact/
  *
  * ----------------------------------------------------------------
  * This program 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.
**/

class NP_Poll extends NucleusPlugin {
	function getName() 		{ return 'Poll'; }
	function getAuthor()  	{ return 'Radek Hulan, Rodrigo Moraes'; }
	function getURL()  		{ return 'http://forum.nucleuscms.org/viewtopic.php?t=4184'; }
	function getVersion() 	{ return '0.5.1'; }
	function getDescription() { return 'Manage your polls.'; }
	function supportsFeature($feature) { if ($feature=='SqlTablePrefix') return 1; else return 0;}
	function getTableList() { return array(sql_table('plug_polladmin')); }
	function getEventList() { return array('PreSkinParse','PreItem','QuickMenu','PostPluginOptionsUpdate'); }
	function hasAdminArea() { return 1;	}
	function install() {
		$this->createOption('SubmitButton','Text for Submit poll results','text','Send your vote!');
		$this->createOption('ResultsText','Text for View poll results link','text','-- poll results --');
		$this->createOption('Option','Text for OPTION','text','Option');
		$this->createOption('Votes','Text for VOTES','text','Votes');
		$this->createOption('Percent','Text for PERCENT','text','%');
		$this->createOption('Total','Total number of votes text','text','Total votes: ');
		$this->createOption('Poll','Transfer data from old NP_Poll?','select','0', 'no|0|yes|1');
		$this->createOption('Class','CSS class for poll form (or empty)','text','');
	}
	
	function init(){
		$this->class=$this->getOption('Class');
		if (!empty($this->class)) $this->class=" class='".$this->class."' ";
	}

  // NP_Poll transfer
	function event_PostPluginOptionsUpdate(&$data) {
		if ($this->getOption('Poll')=='1') {
      $this->setOption('Poll','0');
      $query=sql_query("select PUID,POPTIONS,PVALUES from ".sql_table("POLL"));
      $pollnumbers=array();
      while ($row=sql_fetch_object($query)){
        if (!isset($pollnumbers[$row->PUID])) {
          $pollnumbers[$row->PUID]=true;
          $submit=sql_query("select inumber, ibody, imore, iauthor from ".sql_table("item")." where ".
            " ( ( (ibody like '%!++0,".$row->PUID.",%') or (ibody like '%!++1,".$row->PUID.",%') ) and ibody like '%++!%') ".
            " or ".
            " ( ( (imore like '%!++0,".$row->PUID.",%') or (imore like '%!++1,".$row->PUID.",%') ) and imore like '%++!%') ");
          if ($result=sql_fetch_object($submit)){
            unset($options);
            unset($question);
            unset($closed);
            if (preg_match("/\!\+\+([0|1]),".$row->PUID.",(.*?),(.*?)\+\+\!/",sql_unescape($result->ibody),$s)) {
              $pclosed=$s[1];
              $question=$s[2];
              $options=$s[3];
            }
            if (preg_match("/\!\+\+([0|1]),".$row->PUID.",(.*?),(.*?)\+\+\!/",sql_unescape($result->imore),$s)) {
              $pclosed=$s[1];
              $question=$s[2];
              $options=$s[3];
            }
            if (!empty($question)){
              $poptions = explode(",",$options);
              $values = explode(",",trim($row->PVALUES));
              $aOptions = array();
              $i=0;
		          foreach ($poptions as $poption) {
			          $poption = trim($poption);
			          $aOptions[$poption] = $values[$i++];
		          }
		          $options  = base64_encode(serialize($aOptions));
              $val = base64_encode(serialize($options));
              unset($submit);
              $submit="insert into ".
                      sql_table("plug_polladmin").
                      " (pauthor,pitem,pquestion,poptions,pclosed) values (".
                         $result->iauthor.",".$result->inumber.",'".sql_escape($question)."','$options',$pclosed)";
			  sql_query($submit);
              $pnumber=sql_insert_id();
              // old single poll syntax into a new one
              $result->ibody=sql_escape(preg_replace("/\!\+\+([0|1]),".$row->PUID.",(.*?),(.*?)\+\+\!/","!++".$pnumber."++!",sql_unescape($result->ibody)));
              $result->imore=sql_escape(preg_replace("/\!\+\+([0|1]),".$row->PUID.",(.*?),(.*?)\+\+\!/","!++".$pnumber."++!",sql_unescape($result->imore)));
              unset($submit);
              $submit="update ".sql_table("item")." set ibody='".$result->ibody."', imore='".$result->imore."' where inumber=".$result->inumber;
              sql_query($submit);
            }
          }
        }
      }
      $this->deleteOption('Poll');
		}
	}

	function event_QuickMenu(&$data) {
		global $member;
		// only show to blog admins
		$query=sql_query('SELECT tblog AS blogid FROM '.sql_table('team').' WHERE tadmin=1 AND tmember=' . $member->getID());
		$obj = sql_fetch_object($query);

		if (!($member->isLoggedIn() && $member->isBlogAdmin($obj->blogid))) return;
		array_push(
			$data['options'], 
			array(
				'title' => 'Polls',
				'url' => $this->getAdminURL(),
				'tooltip' => 'Manage your polls.',
				'plugin' => 'NP_Poll'
			)
		);
	}

	function event_PreSkinParse(&$data) {
		global $CONF;

		// voting - save results - single poll
		if (isset($_POST['singlepoll'])) {
			if (isset($_GET['results'])) {
				$pnumber=intval($_GET['results']);
				if ( isset($_POST['poll-'.$pnumber]) ) {
					// no voting yet??
					if ( !isset($_COOKIE['NEWPOLL-'.$pnumber])) {
						$mynumber = intval($_POST['poll-'.$pnumber]);
						$query=sql_query("SELECT poptions FROM ". sql_table('plug_polladmin') ." WHERE pnumber=".$pnumber);
						if ($msg=sql_fetch_array($query)) {
							$values = unserialize(base64_decode($msg['poptions']));
							$getvalues = array_values($values);
							$getvalues[$mynumber]++;
							$i=0;
							foreach ($values as $poption => $value) {
								$values[$poption] = $getvalues[$i];
								$i++;
							}
							$val = base64_encode(serialize($values));
							sql_query("UPDATE ". sql_table('plug_polladmin') ." set poptions='".$val."', pitem=". sql_escape(postVar('pitem')) ." WHERE pnumber=".$pnumber);
						}	
						// redirect, to save a cookie
						setCookie('NEWPOLL-'.strval($pnumber),"1",time()+2592000);
						setCookie('NEWPOLL-'.strval($pnumber),"1",time()+2592000,'/',serverVar('HTTP_HOST'));
						$this->urlRedirect();
					}
				}
			}
		}

	  // voting - save results - multiple poll
		if (isset($_POST['multiplepoll'])) {
			if ( isset($_POST['multiplefirst']) && isset($_POST['multiplelast']) ) {
				for ($pnumber=intval($_POST['multiplefirst']);$pnumber<=intval($_POST['multiplelast']);$pnumber++) {
					if ( isset($_POST['poll-'.strval($pnumber)]) ) {
						// no voting yet??
						$mynumber =intval($_POST['poll-'.strval($pnumber)]);
						$query=sql_query("SELECT poptions FROM ". sql_table('plug_polladmin') ." WHERE pnumber=".$pnumber);
						if ($msg=sql_fetch_array($query)) {
							$values = unserialize(base64_decode($msg['poptions']));
							$getvalues = array_values($values);
							$getvalues[$mynumber]++;
							$i=0;
							foreach ($values as $poption => $value) {
								$values[$poption] = $getvalues[$i];
								$i++;
							}							
							$val = base64_encode(serialize($values));
							sql_query("UPDATE ". sql_table('plug_polladmin') ." set poptions='".$val."', pitem=". sql_escape(postVar('pitem')) ." WHERE pnumber=".$pnumber);
						}
						setCookie('NEWPOLL-'.strval($pnumber),"1",time()+2592000);
						setCookie('NEWPOLL-'.strval($pnumber),"1",time()+2592000,'/',serverVar('HTTP_HOST'));
					} // POST[poll]
				} // for
				// redirect, to save cookies
				$this->urlRedirect();
			} // multiple
		}
	}

  function browserAgent(){
    $xagent = strtolower(serverVar("HTTP_USER_AGENT"));
    if(!(strpos(strtolower($xagent),"opera")===false)){$xagent=substr($xagent,strpos(strtolower($xagent),"opera"),10);};
    if(!(strpos(strtolower($xagent),"msie")===false)){$xagent=substr($xagent,strpos(strtolower($xagent),"msie"),8);};
    if(!(strpos(strtolower($xagent),"mozilla")===false)){$xagent="Gecko";};
    $xagent=substr($xagent,0,20);
    return $xagent;
  }

	function event_PreItem(&$data) {
		$parts=array('body','more');

		foreach ($parts as $part) {
			$pos1=strpos($data['item']->$part,"!++");

			while ($pos1!==false) {
				$r='';
				$pos2=strpos(substr($data['item']->$part,$pos1),"++!");

				if (!$pos2===false) {
					// extract poll data
					$text=substr($data['item']->$part,$pos1+3,$pos2-3);			
					$aNumbers = explode(",", $text);

					$is_multiple=( count($aNumbers) > 1);
					
					$pollresult='';
					$is_first=true;

					foreach ($aNumbers as $pnumber) {
						$query = sql_query("SELECT pquestion, poptions, pclosed FROM ". sql_table('plug_polladmin') ." WHERE pnumber=$pnumber");
						if (!$row=sql_fetch_object($query)) { $pos2=false; break; }
						$pquestion = sql_unescape($row->pquestion);
						$poptions = unserialize(base64_decode($row->poptions));
						$pclosed = $row->pclosed;

						// display poll if nothing submitted and not closed
						if ( $pclosed==0 && (!isset($_COOKIE['NEWPOLL-'.$pnumber])) ) {

							if (!$is_multiple) $r.= "\n";
							
							if ($is_first || $is_multiple) {
								// form 
								if ($is_first) {
									// url to redirect to
									$url = "http://".serverVar('HTTP_HOST').serverVar('REQUEST_URI');
									if (strpos($url,"results")!==false) $url=substr($url,0,strpos($url,"results")-1);
									if (strpos($url,"#")!==false) $url=substr($url,0,strpos($url,"#")-1);
									if (!$is_multiple) 
									  if (strpos($url,'?')===false) $url=$url."?results=".$pnumber.'#poll'.$pnumber; else $url=$url."&amp;results=".$pnumber.'#poll'.$pnumber;
									else
									  if (strpos($url,'?')===false) $url=$url."?multiple=".$pnumber.'#multiple'.$pnumber; else $url=$url."&amp;multiple=".$pnumber.'#multiple'.$pnumber;
									$url=str_replace('&','&amp;',str_replace('&amp;','&',$url));
									// form
									if ($is_multiple)
									  $r.= "<form method='post' id='multiple$pnumber' action='$url' ".$this->class."><div>\n";
									else {
									  if (isset($_GET['results']) && intval($_GET['results'])==$pnumber)
									  	$_formid='';
									  else
									    $_formid="id='poll$pnumber'";
									  $r.= "<form method='post' $_formid action='$url' ".$this->class.">\n";
									}
									$id_first=$pnumber;
								}
								// poll question
								if ( (strpos('msie',$this->browserAgent())!==false) || strlen($pquestion)<60)
								  $r.= "<fieldset><legend>".$pquestion."</legend>\n";
  							    else
  							      $r.= "<fieldset><h4>".$pquestion."</h4>\n";
								if ($is_first) $r.= "<input type='hidden' name='pitem' value='". $data['item']->itemid ."'/>\n";
								$is_first=false;
							}

							
							$id_last=$pnumber;
							if (!$is_multiple) $r.= "\n";

							$i=0;
							foreach ($poptions as $poption => $value) {
								$r.= "<input type='radio' value='".$i."' id='poll-$pnumber-id-$i' name='poll-".$pnumber."'/>";
								$r.= "<label for='poll-$pnumber-id-$i'>".trim(sql_unescape($poption))."</label><br />\n";
								$i++;
							}

							if (!$is_multiple) {
								$r.= "<input type='submit' name='singlepoll' value='". $this->getOption('SubmitButton') ."'/><br />\n"; }

							if ( (!isset($_GET['results'])) || (strcmp($_GET['results'],$pnumber)!=0) ) {
								if (!$is_multiple) $r.= "<a href='$url' title='poll results'>". $this->getOption('ResultsText') ."</a>\n";
							}
							$r.= "</fieldset>\n";

							if (!$is_multiple) $r.= "</form>\n";

						} // if ( $pclosed==0...

						// display poll results if submit or results equal to poll id
						if ( (isset($_GET['multiple'])) || (isset($_GET['results']) && intval($_GET['results'])==$pnumber) || ($pclosed==1) || isset($_COOKIE['NEWPOLL-'.$pnumber]) ) {
							$total=0;
							foreach ($poptions as $poption => $value) $total+=intval($value);
							$xtotal = $total;
							if ($total==0) $total=1;
							$pollresult.= "<h4 id='poll".$pnumber."'>".$pquestion."</h4>";
							$pollresult.= "<table summary=\"Poll Results\">\n";
							$pollresult.= "<tfoot><tr><th colspan=\"3\">".$this->getOption('Total').$xtotal."</th></tr></tfoot>\n";
							$pollresult.= "<tbody>\n";
							$pollresult.= "<tr><th scope=\"col\">".$this->getOption('Option')."</th><th scope=\"col\">".$this->getOption('Votes')."</th><th scope=\"col\">".$this->getOption('Percent')."</th></tr>\n";
							foreach ($poptions as $poption => $value)
								$pollresult.= "<tr><td>".sql_unescape($poption)."</td><td>".$value."</td><td>".floatval(intval((floatval($value)*100.0 / floatval($total) * 10) + 0.5) / floatval(10) ) ."</td></tr>\n";
							$pollresult.= "</tbody></table>\n";
							if (!$is_multiple) $r.=$pollresult;
						}
						
					} // foreach ($aNumbers as $pnumber)

				} // if (!$pos2===false)

				// poll end for multiple polls
				if ($is_multiple && !$is_first) {
					$r.= "<input type='hidden' name='multiplefirst' value='".$id_first."'/>\n";
					$r.= "<input type='hidden' name='multiplelast' value='".$id_last."'/>\n";
					if ( !isset($_GET['multiple']) ) {
						$r.= "<p><a href='$url' title='poll results'>". $this->getOption('ResultsText') ."</a></p>\n";
					}
					$r.= "<input type='submit' name='multiplepoll' value='". $this->getOption('SubmitButton') ."'/>\n";
					$r.= "</div>\n";
					$r.= "</form>\n";
					$r.= $pollresult;
				}
				if ($is_multiple && $is_first) $r.= $pollresult;
				
				// generate poll code
				$data['item']->$part = substr($data['item']->$part,0,$pos1).$r.substr($data['item']->$part,$pos1+$pos2+3);

				// another poll?
				$pos1=strpos($data['item']->$part,"!++");
				if ($pclosed==1) break;
				if ($pos2===false) break;

			} // while (! ($pos1===false) )
		} // foreach ($parts as $part)
	} // event_PreItem

	function urlRedirect() {
		$url = "http://".serverVar('HTTP_HOST').serverVar('REQUEST_URI');
		header('Expires: 0');
		header('Pragma: no-cache');
		header("Location: $url");
		$url = htmlspecialchars($url);
		die("Redirected: <a href=\"$url\">$url</a>");	
	}
} // class
?>