<?php

/*

  .:AJ  Poll v3.1 :.
|===============================|
| http://www.ajsquare.com       |
| mail01: info@ajsquare.com     |
| mail02: sales@ajsquare.com    |
|===============================|

*/

//----------------------------
/* START OR REPLACE SESSION */
session_start();
ob_start();


//                   _______________________________________                   |
//------------------< INCLUDE AND SETTING UP SOME VARIABLES >------------------|
//		     ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ                   |
include 'includes/header.inc';
echo "<br>";
include 'config.php';
include 'includes/functions.php';
require_once("includes/configmagik.php");

// txt/db file path
$txtPath = "txt/txtdb.ini.php";
// create and configure new ConfigMagik-Object
$dbTXT = new ConfigMagik( $txtPath, true, true);
$dbTXT->SYNCHRONIZE = false;
// Current script name
$currentFile= $_SERVER['SCRIPT_NAME'];
?>
<link href="includes/style.css" rel="stylesheet" type="text/css">
<?php
//------------------------------
/* ADMIN RESTRICTED AREA TEST */
//------------------------------------------------------------------------------
// update session variables with "user name" and "password"
if ( isset($_POST['id']) && isset($_POST['pw']) ) {
     $_SESSION['userid']=$_POST['id']; $_SESSION['password']=$_POST['pw'];
}

// check "user name" and "password"
if ($_SESSION['userid']==$id && $_SESSION['password']==$pw ) {


// print xhtml header
top();

// control panel header
//stampa_header();
require 'stampaheader.php';

//------------------------------------------------------------------------------
//************************** START MAIN LOOP ***********************************
//------------------------------------------------------------------------------

switch ($_GET['flag']) {
        
/*----------------------------------------------------------------------------*/
/**************************** NEW/EDIT POLL  **********************************/
/*----------------------------------------------------------------------------*/
?>
<?php
                case 'setup':
		      // create new poll
                      if ( isset($_POST['risposte']) )  {

                                $risposte=$_POST['risposte'];
                                // visualizza form per inserimento opzioni
                                stampa_form_risposte($risposte);
                      }
                      // edit poll
		      else {
		                $numRisposte = $dbTXT->get('numAnswers', 'MAIN');
				// visualizza form per editing opzioni
                                stampa_form_risposte($numRisposte, "edit");
		      }

                break; 
/*----------------------------------------------------------------------------*/
/****************************** CREATE POLL ***********************************/
/*----------------------------------------------------------------------------*/

                case 'create':
echo "<br><br><table border=0 align=\"center\" cellpadding=\"5\" cellspacing=\"2\" class=\"box\" width=\"50%\">";
			/********************* ANSWERS ************************/
                        $array_risposte = $_POST['array_risposte'];
                        // text adjustment
                        for ($i=0; $i<count($array_risposte); $i++) rectifyText($array_risposte[$i]);

			/******************** QUESTION ************************/
			$question=trim($_POST['domanda']);
			// text adjustment
                        rectifyText($question);

			/****************** VALIDATE POLL *********************/
			if ($errorMsg=validatePoll($array_risposte,$question)) {

                             // SHOW ERRORS FOUND
                             echo "<tr><td>
                                  Error :
				   $errorMsg
                                   </div>";

			     // $_POST['action'] è un hidden field del form stampa_form_risposte()
			     // che tiene traccia se si sta facnedo un inserimento o un update
                             stampa_form_risposte(count($array_risposte), $_POST['action']);
			}

                        // NO ERRORS FOUND: CREATE NEW POLL
                        else {
				// POLLID + UPDATE + RESET
				newPoll($array_risposte,$question);
				
	                        // salva su file
							
							echo "<tr><td align=center>";
                                if ($dbTXT->save()) success("Your Poll Has Been Created Successfully!");
                        	else print "Error: Write to File Fail<br />";
                        }
                        	
                break;  // fine case 'create'

echo "</table>";
/*----------------------------------------------------------------------------*/
/****************************** UPDATE POLL ***********************************/
/*----------------------------------------------------------------------------*/
		case 'update':
		
		        /********************* ANSWERS ************************/
                        $array_answers = $_POST['array_risposte'];
                        // text adjustment
                        for ($i=0; $i<count($array_risposte); $i++) rectifyText($array_risposte[$i]);

			/******************** QUESTION ************************/
			$question = trim($_POST['domanda']);
                        // text adjustment
                        rectifyText($question);

			/****************** VALIDATE POLL *********************/
			if ($errorMsg=validatePoll($array_answers,$question)) {

                             // SHOW ERRORS FOUND
                             echo "<div class=\"box\">
                                   <div class=\"titolo\">Error :</div>
				   $errorMsg
                                   </div>";

			     // $_POST['action'] è un hidden field del form stampa_form_risposte()
			     // che tiene traccia se si sta facnedo un inserimento o un update
                             stampa_form_risposte(count($array_answers), "edit");
			}
			// NO ERRORS FOUND: UPDATE POLL
			else {
			        // update poll (no votes reset)
				updatePoll($array_answers, $question);
				
				// salva su file
                                if ($dbTXT->save()) success("Poll updated successfully!");
                                else print "Error: write to file fail<br />";
			}

		break;


/*----------------------------------------------------------------------------*/
/************************* SHOW POLL CONTROL PANEL ****************************/
/*----------------------------------------------------------------------------*/

                case 'cp':

                        // controllo l'esistenza della tabella
                        if($dbTXT->get('pollid','MAIN')!=null) {
                        
				print "<div align=\"center\"><p>";
		                // Visualizza il sondaggio allo stato attuale
                                pollprint($dbTXT);
				print "</p></div>";
					  
				/******** SHOW EXTRA OPTIONS ********/
				extraMenu();
                        }
                        else {
                                // se la tabella non esiste...
                                echo "
                                      <font color=blue>At Present there is No poll, click Here to Create&nbsp;&nbsp; <a href='$currentFile?flag=wizard' style=text-decoration:underline><strong><font color=red>New Poll</a> </div>
				      </div>";
                        }

                break; 
                
/*----------------------------------------------------------------------------*/
/**************************** ERASE CURRENT POLL ******************************/
/*----------------------------------------------------------------------------*/

                case 'del':

                        // query di eliminazione
                        $dbTXT->removeSection('MAIN');
                        $dbTXT->removeSection('ANSWERS');
                        if ($dbTXT->save()) {
                                // cancello il cookie
                                setcookie( "poll4all", '');
				// redirect...forse è meglio sostituirlo con un messaggio di ok
	                        header ("location:".$currentFile."?flag=cp");
			}
			else print "Error: erase poll fail<br />";
                break;

/*----------------------------------------------------------------------------*/
/******************************** RESET POLL **********************************/
/*----------------------------------------------------------------------------*/

                case 'reset':

			    // reset votes to 0
			    resetVotes();
			    // salva su file
        		    if ($dbTXT->save()) {
        		        setcookie( "poll4all", '');
			    	header ("location:$currentFile?flag=cp");
					//echo '<meta http-equiv="refresh" content="0;url=$currentfile?flag=cp">';
			    }
                            else print "Error: write to file fail<br />";
                        
                break;
?><title></title>
/*----------------------------------------------------------------------------*/
/***************************** NEW POLL WIZARD ********************************/
/*----------------------------------------------------------------------------*/

       <?         case 'wizard':

                        echo "<br><br><table border=0 align=\"center\" cellpadding=\"5\" cellspacing=\"2\" class=\"box\" width=\"50%\">  <form name=\"poll\" method=\"post\" action=\"$currentfile?flag=setup\">
				     <tr><td bgcolor=#ECECEC><b>New Poll Wizard [step 1/2]</font>
					
				     <tr><td>Select the Number of Answers :</span>&nbsp;<select name=\"risposte\">";
                                    for ($i=2; $i<8; $i++) print "<option value=$i>$i</option>";
                        echo "       </select>
                        	    
			             <tr><td align=center><input type=\"submit\" name=\"submit\" value=\"Go Ahead >>\" class=button1>
				     </div>

                                 </div></form>";

                break;
         ?>
		 </table>       
                
/*----------------------------------------------------------------------------*/
/****************************** TEST NEW POLL *********************************/
/*----------------------------------------------------------------------------*/

		<?php case 'test':
		        
		        print "<div align=\"center\"><p>";
			poll();
			print "</p></div>";
			
			/******** SHOW EXTRA OPTIONS ********/
                        extraMenu();

		break;
		
		
/*----------------------------------------------------------------------------*/
/******************************* RESET COOKIE *********************************/
/*----------------------------------------------------------------------------*/

		case 'cookie':
		
			if (setcookie( "poll4all", '')) {
				// redirect to test
  				header ("location:$currentFile?flag=test");
			}
			else print "Cookie reset fail<br />";
			/******** SHOW EXTRA OPTIONS ********/
			extraMenu();

		break;
	?>	
		
/*----------------------------------------------------------------------------*/
/********************************* HELP ***************************************/
/*----------------------------------------------------------------------------*/
<?php
		case 'help':
				echo "<br><br><table border=0 align=\"center\" cellpadding=\"5\" cellspacing=\"2\" class=\"box\" width=\"70%\">"; ?>
				<tr><td bgcolor="#ECECEC">
				       <font color=black><b>Help</div></td></tr>
				    <tr><td><font color=black>
				        <strong>Main Menu</strong><br />
				        <ul>
					<p><strong>New Poll --></strong> create new poll, old poll will be overwrited.</p>
					<p><strong>View/Edit --></strong> view (and edit) current poll.</p>
					<p><strong>Help --></strong> show this page.</p>
					<p><strong>?--></strong> show author contact info.</p>
					</ul>
					<strong>Extra Options Menu</strong><br />
					<ul>
					<p><strong>Reset Votes --></strong> reset to \"0\" all votes.</p>
					<p><strong>Delete Poll --></strong> erase current poll from database file.</p>
					<p><strong>Reset Cookie --></strong> reset cookie on your browser so you can vote again.</p>
					<p><strong>Test Poll --></strong> try yourself current poll. Warning: your votes real affect the poll.</p>
					</ul>
					</div></font>
				        </div>
<?
echo "</table>";

		break;
		?>
		
/*----------------------------------------------------------------------------*/
/******************************** ABOUT ***************************************/
/*----------------------------------------------------------------------------*/
<?
		case 'about':
				echo "<br><br><table border=0 align=\"center\" cellpadding=\"5\" cellspacing=\"2\" class=\"box\" width=\"50%\">
				<tr><td>
				       <font color=blue><br><b>.: aboUt</div>
				    <tr><td><font color=blue>    
					Poll4All is freeware and open source.<br /><br />
					Visit mY hoMe paGe: <a href=\"http://www.code4fun.org\"><font color=red>http://www.code4fun.org</font></a><br /><br />
					<font color=blue>ConTact mE : <a href=\"mailto:info@code4fun.org\"><font color=red>info@code4fun.org</a><br /><br />
					</div>
				        </div>";
		

		break;
		
/*----------------------------------------------------------------------------*/
/******************************* WELCOME **************************************/
/*----------------------------------------------------------------------------*/
		
		default:

			$msg="";

			// visualizza il form iniziale con menu ed istruzioni
			echo "<div class=\"box\">
	      		      <div class=\"titolo\">WELCOME</div>";
				$msg.="Check database file...";
				if (file_exists($txtPath)) {
				$msg.="Ok<br />";
				$msg.="Check if is writable...";
		                	if (is_writable($txtPath)) $msg.="Ok<br />ALL OK!";
                			else {
						$msg.="Ko<br />";
						$msg.="Try to change mode...";
			                	if (chmod($txtPath, 0600)) $msg.="Ok<br />ALL OK!";
	        		        	else $msg.="Ko<br />Non ho i permessi per scriverci, modificarli a mano.";

	        			}
				}
				else {
 	        			$msg.="File doesn't exist.<br />";
 	        			$msg.="Try to create it...";
	        			if (@fopen($txtPath, "x+")) $msg.="Ok<br />";
  					else $msg.="Ko<br />Impossibile creare il file, assicurarsi di avere i permessi per scrivere nella dir ".$txtPath.".";
				}

			print "<div class=\"testo\">$msg</div>";
			print "</div>";


}// fine switch
        
//------------------------------------------------------------------------------
//**************************** END MAIN LOOP ***********************************
//------------------------------------------------------------------------------


// xhtml footer
foot();

} // fine if controllo pw e id

//-------------------------------------------------------------------
/* if check user name and password fail print restricted area form */
else {restrictedArea();}







//----------------------------------------------------------------------------//
//                          F U N C T I O N S                                 //
//____________________________________________________________________________//




// //
/****                       STAMPA_FORM_INIZIALE                           ****/

/*function stampa_header() {


                echo "  
               
				
   <!-- <div class=\"boxHeader\"> -->
                <!-- titolo -->
                <div class=\"logo\"><a href=\"http://www.code4fun.org\"><strong><font color=blue>POLL4ALL</a><br /><span class=\"testo\">[v.1.0 beta]</span></div>

                <!-- Menu -->
                <div class=\"menu\"><strong>.: MainMenu :</strong>&nbsp;&nbsp;<a href=\"$currentFile?flag=wizard\"><font color=red>New Poll</a></font> | <a href=\"$currentFile?flag=cp\"><font color=red>View / Edit current poll</a></font> | <a href=\"$currentFile?flag=help\"><font color=red>Help</a></font> | <a href=\"$currentFile?flag=about\"><font color=red>?</font></a></div>";

               


}*/


/*******************************************************************************
****                  STAMPA_FORM_DOMANDA_&_RISPOSTE                        ****
*******************************************************************************/
// $option = new  // i campi del form sono vuoti
// $option = edit // i campi del form sono inizializzati con i valori del sond. attuale

function stampa_form_risposte($num_risposte, $option="new") {

        global $currentFile,$dbTXT;

	

	// setting question value
        if ($option=="edit") {
		$questionValue = $dbTXT->get('question', 'MAIN');
		$flag='update';
		$title=".: Edit Current Poll";
	}
        else { $questionValue = ""; $flag='create'; $title=".: New Poll Wizard [step 2/2]";}
        
        echo "<br><br><table border=0 align=\"center\" cellpadding=\"5\" cellspacing=\"2\" class=\"box\" width=\"50%\"><form name=\"init_poll\" method=\"post\" action=\"$currentFile?flag=".$flag."\">
		<tr><td bgcolor=#F7F7F7>
		".$title."
		<tr><td align=center>
               Poll question :&nbsp;<input type=\"text\" size=\"61\" name=\"domanda\" value=\"".$questionValue."\"></div>
                <hr />";
                
                if ($option=="edit") print "<input type=\"hidden\" value=\"edit\" name=\"action\" />";

                // ciclo for per la visualizzazione delle caselle di testo, una per ogni risposta del sondaggio
                for ($i=1; $i<=$num_risposte; $i++) {

			// setting answer value
			$val="";
			if ($option=="edit") {
				$answerKey = "an".$i;
				$val = $answer = $dbTXT->get($answerKey,"ANSWERS");
			}
				

                        print ".: answers [".$i."] :&nbsp;<input type=\"text\" size=\"61\" name=\"array_risposte[]\" value=\"".$val."\"></div>";
                }
	// setting submit button value
	if ($option=="edit") $submitVal = ">> Update Poll <<";
	else $submitVal = ">> Create Poll <<";
        echo "  <br><br><input type=\"submit\" name=\"submit\" value=\"".$submitVal."\"></div>

                </div></form>";


}


/*******************************************************************************
****                VALIDAZIONE_DATI_SONDAGGIO_INSERITI                     ****
*******************************************************************************/
// in: array delle domande; out: string error message if any or 0 if all ok
function validatePoll(&$answersArray, &$question) {

			// Variabile Validazione
                        $numErrors = 0;
                        $msg = "";

                        // Controllo sul campo "domanda"
                        if (!isset($question) || $question=="" ) {
                             $numErrors++;
                             $msg.="Question can't be empty sentence!<br />";
                        }

                        // Controllo che non ci siano due risposte uguali...
                        $array_no_doppi = array_unique($answersArray);
                        if ( count($array_no_doppi)!=count($answersArray) ) {
                             $numErrors++;
                             $msg.="Warning!!! Two or more answers are the same!<br />";
                        }

                        // Controllo che non ci siano risposte nulle
                        if (array_search( '' , $answersArray)!==false) {
                             $numErrors++;
                             $msg.="Answers can't be empty sentences!<br />";
                        }
                        if (!$numErrors) return false;
                        else return $msg;
}


/*******************************************************************************
****                       ADATTA IL TESTO INSERITO                         ****
*******************************************************************************/
// converte alcuni caratteri html come "<" e ">" oltre che le virgolette ed
// i singoli apici per una corretta visualizzazione
function rectifyText(&$string) {
	
	$string = str_replace("\\'","'",$string);
	$string = str_replace('\"',"&quot;",$string);
	$string = str_replace("<", "&lt;", $string);
	$string = str_replace(">", "&gt;", $string);

}


/*******************************************************************************
****                            CREATE NEW POLL                             ****
*******************************************************************************/
function newPoll(&$answers, &$question) {

	global $currentFile,$dbTXT;
	
	/**************** NEW POLL ID *****************/
	$pollid=time();
        $dbTXT->set('pollid', $pollid, 'MAIN');

	/******** INSERIMENTO DOMANDA E RISPOSTE ******/
	updatePoll($answers,$question);
	/**************** RESET ALL VOTES *************/
	resetVotes();
	

}


/*******************************************************************************
****                            UPDATE POLL                                 ****
*******************************************************************************/
// aggiorna il sondaggio corrente senza resettare i voti registrati
function updatePoll(&$answers, &$question) {

	global $currentFile,$dbTXT;
	$oldNumAnswers = $dbTXT->get('numAnswers', 'MAIN');
	$numAnswers = count($answers);

	// update poll question
        $dbTXT->set('question', $question, 'MAIN');
        $dbTXT->set('numAnswers', $numAnswers, 'MAIN');
	// update answers
	for ($i=0; $i<$numAnswers; $i++) {

                // converto i caratteri "speciali"
                rectifyText($answers[$i]);
                $answerKey = "an".($i+1);
	        $dbTXT->set($answerKey, $answers[$i], 'ANSWERS');
        }
        // remove superfluous questions if exist
        // sarà sempre falsa se si sta aggiornando
        
        if ( ($oldNumAnswers - $numAnswers) > 0 ) {
		for ($i=($numAnswers+1); $i<=$oldNumAnswers; $i++) {
                        $answerKey = "an".$i;
			$pollKey = "an".$i."poll";
			$dbTXT->removeKey($answerKey, 'ANSWERS');
		    	$dbTXT->removeKey($pollKey, 'ANSWERS');
		}
        }
        
}


/*******************************************************************************
**                       POLL CREATION SUCCESSFULL                            **
*******************************************************************************/
function success($msg) {

	echo "<div class=\"box\">
	      <div class=\"cBox\">
              <span class=\"testo\"><strong>".$msg."</strong></span><br />
	      <p>[<a href='$currentFile?flag=test'> TEST POLL </a>]</p>
	      </div>";
}

/*******************************************************************************
**                             VOTES RESET                                    **
*******************************************************************************/
function resetVotes() {

	global $currentFile,$dbTXT;
        
        // azzero i voti
	$numAnswers = $dbTXT->get('numAnswers', 'MAIN');
	
	    for ($i=1; $i<=$numAnswers; $i++) {
	        $pollKey = "an".$i."poll";
	        $dbTXT->set($pollKey, 0, 'ANSWERS');
	    }
}



/*******************************************************************************
**                             SHOW EXTRA MENU                                **
*******************************************************************************/
function extraMenu() {

	
		?><hr color="#000000"> <?php
        echo "<center>
              <div class=\"extraMenu\">
              <strong>Extra options :</strong>
              <span class=\"testo\"
              <font color=red>
              <a href='$currentFile?flag=reset'><font color=red>Reset Votes</a></font>&nbsp;|&nbsp;
	      <a href='$currentFile?flag=del'><font color=red>Delete Poll</a></font>&nbsp;|&nbsp;
              <a href='$currentFile?flag=cookie'><font color=red>Reset Cookie</a></font>&nbsp;|&nbsp;
              <a href='$currentFile?flag=test'><font color=red>Test Poll</a></font>&nbsp;
              </span>
              </div>
              </form>
	      </center>";
}




/*******************************************************************************
**             Visualizza Form per accesso alla Restricted Area               **
*******************************************************************************/
function restrictedArea() {

         echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
               <html xmlns=\"http://www.w3.org/1999/xhtml\">
                <head>
                 <title>Poll4All Restricted Area</title>
                 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\" />
                 <style type=\"text/css\">
                 <!--
                 body {
                       background-color: #FFFFFF;
                       margin-top: 30px;
                       margin-right: 0px;
                       margin-bottom: 0px;
                       margin-left: 0px;
                       font-family: Verdana, Arial, Courier, Serif;



                 }

                

                 .box {

                        background-color: #CCCCCC;
                        width: 200px;
                        text-align: center;
                        border-color: #000000;
                        border-style: solid;
                        border-width: 2px 2px 2px 2px;
                        padding: 10px 4px 4px 4px;
                        margin: 0px 0px 0px 0px;
                        font-family: Verdana, Arial, sans-serif;
                        font-size: 13px;
                 }
                 -->
                 </style>
                </head>
                <body>
                     <!-- <div align=\"center\">
                      <div class=\"container\">
                      <div class=\"box\"> -->
                      <b><center>Poll4All</b><br><center><font color=\"#FF0000\">Restricted Area</p>
                      <form name=\"restricted\" action=\"$currentFile\" method=\"post\">
                      <center><font color=\"#000000\">User Name:&nbsp;&nbsp; <input name=\"id\" type=\"text\" value=\"\" /><br><br>
                      <center>Password:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input name=\"pw\" type=\"password\" value=\"\" />
                      <p><center><input type=\"submit\" value=\"submit\" style=\"background:#F3F3F3;cursor:hand\"/></p>
                      </form>
					  <!--
                      </div>
                      </div>
                      </div>
					  -->
                </body>
                </html>
         ";
}


/*******************************************************************************
*****                           HEADER XHTML                               *****
*******************************************************************************/
function top() {

echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
      <html xmlns=\"http://www.w3.org/1999/xhtml\">
       <head>
        <title>AJ Square Inc</title>
        <meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\" />
        <style type=\"text/css\">
               </head>
        <body>
        <div class=\"container\">
        ";


}


/*******************************************************************************
*****                           FOOTER XHTML                               *****
*******************************************************************************/
function foot() { echo "</div></body></html>"; }

?>
<tr><td valign="bottom"><br>
<?php
require 'includes/footer.inc';

?>
</td></tr>
