From 1437eaf47e578667e8a1314dc849f080504a6b93 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 3 Dec 2014 21:08:08 +0100 Subject: [PATCH 001/151] Refactoring some code: * Store all informations about forms into an object "Form" stored in $_SESSION['form'] * Replace connection to database by PDO object * Check if database is ready in bandeaux.php file --- app/classes/Framadate/Choice.php | 42 +++++++++++++ app/classes/Framadate/Form.php | 58 +++++++++++++++++ app/classes/Framadate/FramaDB.php | 39 ++++++++++++ app/classes/Framadate/Utils.php | 61 +++++++++--------- app/inc/init.php | 12 +++- bandeaux.php | 8 +++ choix_date.php | 100 ++++++++++++++++++++---------- creation_sondage.php | 74 ++++++++-------------- index.php | 5 -- infos_sondage.php | 69 ++++++++------------- 10 files changed, 306 insertions(+), 162 deletions(-) create mode 100644 app/classes/Framadate/Choice.php create mode 100644 app/classes/Framadate/Form.php create mode 100644 app/classes/Framadate/FramaDB.php diff --git a/app/classes/Framadate/Choice.php b/app/classes/Framadate/Choice.php new file mode 100644 index 0000000..d1eec51 --- /dev/null +++ b/app/classes/Framadate/Choice.php @@ -0,0 +1,42 @@ +name = $name; + $this->slots = array(); + } + + public function addSlot($slot) + { + $this->slots[] = $slot; + } + + public function getName() + { + return $this->name; + } + + public function getSlots() + { + return $this->slots; + } + + static function compare(Choice $a, Choice $b) + { + return strcmp($a->name, $b->name); + } + +} diff --git a/app/classes/Framadate/Form.php b/app/classes/Framadate/Form.php new file mode 100644 index 0000000..641f0f1 --- /dev/null +++ b/app/classes/Framadate/Form.php @@ -0,0 +1,58 @@ +clearChoices(); + } + + public function clearChoices() { + $this->choices = array(); + } + + public function addChoice(Choice $choice) + { + $this->choices[] = $choice; + } + + public function getChoices() + { + return $this->choices; + } + + public function sortChoices() + { + usort($this->choices, array('Framadate\Choice', 'compare')); + } + + public function lastChoice() + { + return end($this->choices); + } + +} \ No newline at end of file diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php new file mode 100644 index 0000000..a10884e --- /dev/null +++ b/app/classes/Framadate/FramaDB.php @@ -0,0 +1,39 @@ +pdo = new \PDO($connection_string, $user, $password); + } + + function areTablesCreated() + { + $result= $this->pdo->query('SHOW TABLES'); + $schemas = $result->fetchAll(\PDO::FETCH_COLUMN); + return !empty(array_diff($schemas, ['comments', 'sondage', 'sujet_studs', 'user_studs'])); + } + + function prepare($sql) { + return $this->pdo->prepare($sql); + } + + function beginTransaction() { + $this->pdo->beginTransaction(); + } + + function commit() { + $this->pdo->commit(); + } + + function query($sql) { + return $this->pdo->query($sql); + } + +} diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index 7dfd953..c48aff2 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -23,9 +23,10 @@ class Utils public static function get_server_name() { $scheme = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https' : 'http'; - $port = in_array($_SERVER['SERVER_PORT'], [80, 443]) ? '/' : ':' . $_SERVER['SERVER_PORT'] . '/'; - $server_name = $_SERVER['SERVER_NAME'] . $port . dirname($_SERVER['SCRIPT_NAME']) . '/'; - + $port = in_array($_SERVER['SERVER_PORT'], [80, 443]) ? '' : ':' . $_SERVER['SERVER_PORT']; + $dirname = dirname($_SERVER['SCRIPT_NAME']); + $dirname = $dirname === '\\' ? '/' : $dirname . '/'; + $server_name = $_SERVER['SERVER_NAME'] . $port . $dirname; return $scheme . '://' . str_replace('/admin','',str_replace('//','/',str_replace('///','/',$server_name))); } @@ -222,43 +223,41 @@ class Utils return $url; } - public static function remove_sondage($connect, $numsondage) + /** + * Completly delete data about the given poll + */ + public static function removeSondage($poll_id) { - $connect->StartTrans(); + global $connect; - $req = 'DELETE FROM sondage WHERE id_sondage = ' . $connect->Param('numsondage') ; - $sql = $connect->Prepare($req); - $connect->Execute($sql, [$numsondage]); + $prepared = $connect->prepare('DELETE FROM sujet_studs WHERE id_sondage = ?'); + $prepared->execute(array($poll_id)); - $req = 'DELETE FROM sujet_studs WHERE id_sondage = ' . $connect->Param('numsondage') ; - $sql = $connect->Prepare($req); - $connect->Execute($sql, [$numsondage]); + $prepared = $connect->prepare('DELETE FROM user_studs WHERE id_sondage = ?'); + $prepared->execute(array($poll_id)); - $req = 'DELETE FROM user_studs WHERE id_sondage = ' . $connect->Param('numsondage') ; - $sql = $connect->Prepare($req); - $connect->Execute($sql, [$numsondage]); + $prepared = $connect->prepare('DELETE FROM comments WHERE id_sondage = ?'); + $prepared->execute(array($poll_id)); - $req = 'DELETE FROM comments WHERE id_sondage = ' . $connect->Param('numsondage') ; - $sql = $connect->Prepare($req); - $connect->Execute($sql, [$numsondage]); - - $suppression_OK = ! $connect->HasFailedTrans(); - $connect->CompleteTrans(); - - return $suppression_OK ; + $prepared = $connect->prepare('DELETE FROM sondage WHERE id_sondage = ?'); + $prepared->execute(array($poll_id)); + } - public static function cleaning_polls($connect, $log_txt) { - $connect->StartTrans(); - $req = 'SELECT * FROM sondage WHERE date_fin < NOW() LIMIT 20'; - $sql = $connect->Prepare($req); - $cleaning = $connect->Execute($sql); + public static function cleaningOldPolls($log_txt) { + global $connect; + + $resultSet = $connect->query('SELECT id_sondage, format, nom_admin, mail_admin FROM sondage WHERE date_fin < NOW() LIMIT 20'); + $toClean = $resultSet->fetchAll(\PDO::FETCH_CLASS); + + echo '
toClean:'.print_r($toClean, true).'
'; - while ($dcleaning = $cleaning->FetchNextObject(false)) { - if (self::remove_sondage($connect, $dcleaning->id_sondage)) { - error_log(date('H:i:s d/m/Y:') . ' EXPIRATION: '. $dcleaning->id_sondage."\t".$dcleaning->format."\t".$dcleaning->nom_admin."\t".$dcleaning->mail_admin."\n", 3, $log_txt); + $connect->beginTransaction(); + foreach ($toClean as $row) { + if (self::removeSondage($row->id_sondage)) { + error_log(date('H:i:s d/m/Y:') . ' EXPIRATION: '. $row->id_sondage."\t".$row->format."\t".$row->nom_admin."\t".$row->mail_admin."\n", 3, $log_txt); } } - $connect->CompleteTrans(); + $connect->commit(); } } diff --git a/app/inc/init.php b/app/inc/init.php index 2a13d2b..4068df0 100644 --- a/app/inc/init.php +++ b/app/inc/init.php @@ -26,6 +26,14 @@ require_once __DIR__ . '/../../vendor/autoload.php'; include_once __DIR__ . '/constants.php'; include_once __DIR__ . '/i18n.php'; -$connect = NewADOConnection(BASE_TYPE); -$connect->Connect(SERVEURBASE, USERBASE, USERPASSWD, BASE); +use Framadate\FramaDB; +use Framadate\Form; +use Framadate\Choice; +use Framadate\Utils; + +if (session_id() == "") { + session_start(); +} + +$connect = new Framadate\FramaDB(DB_CONNECTION_STRING, DB_USER, DB_PASSWORD); $err = 0; diff --git a/bandeaux.php b/bandeaux.php index efbe726..7f86cde 100644 --- a/bandeaux.php +++ b/bandeaux.php @@ -43,6 +43,14 @@ function bandeau_titre($titre)
'; + + global $connect; + if ($connect->areTablesCreated()) { + echo '
'. _('Framadate is not properly installed, please check the "INSTALL" to setup the database before continuing.') .'
'; + bandeau_pied(); + die(); + } + } function liste_lang() diff --git a/choix_date.php b/choix_date.php index b9f6314..4d33ca3 100644 --- a/choix_date.php +++ b/choix_date.php @@ -18,7 +18,7 @@ */ namespace Framadate; -session_start(); +include_once __DIR__ . '/app/inc/init.php'; include_once('creation_sondage.php'); @@ -29,7 +29,7 @@ if (is_readable('bandeaux_local.php')) { } // Step 1/3 : error if $_SESSION from info_sondage are not valid -if (Utils::issetAndNoEmpty('titre', $_SESSION) === false || Utils::issetAndNoEmpty('nom', $_SESSION) === false || (($config['use_smtp']) ? Utils::issetAndNoEmpty('adresse', $_SESSION) === false : false)) { +if (!isset($_SESSION['form']->titre) || !isset($_SESSION['form']->nom) || (($config['use_smtp']) ? !isset($_SESSION['form']->adresse) : false)) { Utils::print_header ( _("Error!") ); bandeau_titre(_("Error!")); @@ -73,70 +73,103 @@ if (Utils::issetAndNoEmpty('titre', $_SESSION) === false || Utils::issetAndNoEmp } } - $_SESSION["toutchoix"]=substr($choixdate,1); + $_SESSION['form']->toutchoix=substr($choixdate,1); // Expiration date → 6 months after last day if not filled or in bad format - $_SESSION["champdatefin"]=end($temp_results)+(86400 * $config['default_poll_duration']); + $_SESSION['form']->champdatefin=end($temp_results)+(86400 * $config['default_poll_duration']); if (Utils::issetAndNoEmpty('champdatefin')) { $registredate = explode("/",$_POST["champdatefin"]); if (is_array($registredate) == true && count($registredate) == 3) { $time = mktime(0,0,0,$registredate[1],$registredate[0],$registredate[2]); if ($time > time() + (24*60*60)) { - $_SESSION["champdatefin"]=$time; + $_SESSION['form']->champdatefin=$time; } } } - ajouter_sondage(); +exit('
'.print_r($_SESSION, true).'
'); + $admin_poll_id = ajouter_sondage( + $_SESSION['form']->titre, + $_SESSION['form']->commentaires, + $_SESSION['form']->nom, + $_SESSION['form']->adresse, + $_SESSION['form']->formatsondage, + $_SESSION['form']->champdatefin, + $_SESSION['form']->mailsonde, + $_SESSION['form']->toutchoix + ); + + unset($_SESSION['form']); +exit('
'.print_r($_SESSION, true).'
'); + + + Utils::cleaningOldPolls($connect, 'admin/logs_studs.txt'); + + // TODO cleanup $_SESSION + Redirect + + // Don't keep days, hours and choices in memory (in order to make new polls) + //for ($i = 0; $i < count($_SESSION['totalchoixjour']); $i++) { + // unset($_SESSION['horaires'.$i]); + //} + //unset($_SESSION['totalchoixjour']); + //unset($_SESSION['choices']); + + //header('Location:' . Utils::getUrlSondage($sondage_admin, true)); + + exit; } else { + if (Utils::issetAndNoEmpty('days')) { - if (!isset($_SESSION["totalchoixjour"])) { - $_SESSION["totalchoixjour"]=array(); - } - $k = 0; - for ($i = 0; $i < count($_POST["days"]); $i++) { - if (isset($_POST["days"][$i]) && $_POST["days"][$i] !='') { - $_SESSION['totalchoixjour'][$k] = mktime(0, 0, 0, substr($_POST["days"][$i],3,2),substr($_POST["days"][$i],0,2),substr($_POST["days"][$i],6,4)); + + // Clear previous choices + $_SESSION['form']->clearChoices(); - $l = 0; - for($j = 0; $j < count($_POST['horaires'.$i]); $j++) { - if (isset($_POST['horaires'.$i][$j]) && $_POST['horaires'.$i][$j] != '') { - $_SESSION['horaires'.$k][$l] = $_POST['horaires'.$i][$j]; - $l++; + for ($i = 0; $i < count($_POST['days']); $i++) { + $day = $_POST['days'][$i]; + + if (!empty($day)) { + // Add choice to Form data + $time = mktime(0, 0, 0, substr($_POST["days"][$i],3,2),substr($_POST["days"][$i],0,2),substr($_POST["days"][$i],6,4)); + $choice = new Choice($time); + $_SESSION['form']->addChoice($choice); + + $schedules = $_POST['horaires'.$i]; + for($j = 0; $j < count($schedules); $j++) { + if (!empty($schedules[$j])) { + $choice->addSlot($schedules[$j]); } } - $k++; } } } } //le format du sondage est DATE - $_SESSION["formatsondage"] = "D".$_SESSION["studsplus"]; + $_SESSION['form']->formatsondage = "D".$_SESSION['form']->studsplus; // Step 3/3 : Confirm poll creation - if (Utils::issetAndNoEmpty('choixheures') && Utils::issetAndNoEmpty('totalchoixjour', $_SESSION)) { + if (Utils::issetAndNoEmpty('choixheures') && !isset($_SESSION['form']->totalchoixjour)) { Utils::print_header ( _("Removal date and confirmation (3 on 3)") ); bandeau_titre(_("Removal date and confirmation (3 on 3)")); - $temp_array = array_unique($_SESSION["totalchoixjour"]); - sort($temp_array); - $removal_date=utf8_encode(strftime($date_format['txt_full'], end($temp_array)+ (86400 * $config['default_poll_duration']))); + $_SESSION['form']->sortChoices(); + $last_date = $_SESSION['form']->lastChoice()->getName(); + $removal_date = utf8_encode(strftime($date_format['txt_full'], $last_date + (86400 * $config['default_poll_duration']))); - // Sumary + // Summary $summary = ''; @@ -177,6 +210,7 @@ if (Utils::issetAndNoEmpty('titre', $_SESSION) === false || Utils::issetAndNoEmp '."\n"; +//exit('
POST
'.print_r($_POST, true).'
SESSION
'.print_r($_SESSION, true).'
'); bandeau_pied(); diff --git a/creation_sondage.php b/creation_sondage.php index 1e7f982..1226637 100644 --- a/creation_sondage.php +++ b/creation_sondage.php @@ -16,20 +16,20 @@ * Auteurs de STUdS (projet initial) : Guilhem BORGHESI (borghesi@unistra.fr) et Raphaël DROZ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ +// TODO Move this file into a class into app/classes/Framadate namespace Framadate; -if (session_id() == "") { - session_start(); -} - include_once __DIR__ . '/app/inc/init.php'; -//Generer une chaine de caractere unique et aleatoire +/** + * Generer une chaine de caractere unique et aleatoire + */ function random($car) { - $string = ""; - $chaine = "abcdefghijklmnopqrstuvwxyz123456789"; +// TODO Better random ? + $string = ''; + $chaine = 'abcdefghijklmnopqrstuvwxyz123456789'; srand((double)microtime()*1000000); for($i=0; $i<$car; $i++) { $string .= $chaine[rand()%strlen($chaine)]; @@ -38,63 +38,43 @@ function random($car) return $string; } -function ajouter_sondage() +function ajouter_sondage($title, $comment, $adminName, $adminMail, $format, $endDate, $mailsonde, $slots) { global $connect; + global $config; + $poll_id = random(16); + $admin_poll_id = $poll_id.random(8); - $sondage=random(16); - $sondage_admin=$sondage.random(8); - - $date_fin = $_SESSION["champdatefin"]; // provided by choix_autre.php or choix_date.php - $_SESSION["champdatefin"]=""; //clean param cause 2 polls created by the same user in the same session can be affected by this param during the 2nd creation. + $date_fin = $_SESSION['champdatefin']; // provided by choix_autre.php or choix_date.php + $_SESSION['champdatefin'] = ''; //clean param cause 2 polls created by the same user in the same session can be affected by this param during the 2nd creation. $sql = 'INSERT INTO sondage (id_sondage, commentaires, mail_admin, nom_admin, titre, id_sondage_admin, date_fin, format, mailsonde) - VALUES ( - '.$connect->Param('id_sondage').', - '.$connect->Param('commentaires').', - '.$connect->Param('mail_admin').', - '.$connect->Param('nom_admin').', - '.$connect->Param('titre').', - '.$connect->Param('id_sondage_admin').', - FROM_UNIXTIME('.$date_fin.'), - '.$connect->Param('format').', - '.$connect->Param('mailsonde').' - )'; - $sql = $connect->Prepare($sql); - $res = $connect->Execute($sql, array($sondage, $_SESSION['commentaires'], $_SESSION['adresse'], $_SESSION['nom'], $_SESSION['titre'], $sondage_admin, $_SESSION['formatsondage'], $_SESSION['mailsonde'])); + VALUES (?,?,?,?,?,?,?,?)'; + $prepared = $connect->prepare($sql); + $res = $prepared->execute(array($poll_id, $comment, $adminMail, $adminName, $title, $admin_poll_id, $format, $mailsonde)); - $sql = 'INSERT INTO sujet_studs values ('.$connect->Param('sondage').', '.$connect->Param('choix').')'; - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($sondage, $_SESSION['toutchoix'])); + $prepared = $connect->prepare('INSERT INTO sujet_studs values (?, ?)'); + $prepared->execute(array($poll_id, $slots)); - if($config['use_smtp']==true){ + if($config['use_smtp'] === true){ $message = _("This is the message you have to send to the people you want to poll. \nNow, you have to send this message to everyone you want to poll."); $message .= "\n\n"; - $message .= stripslashes(html_entity_decode($_SESSION["nom"],ENT_QUOTES,"UTF-8"))." " . _("hast just created a poll called") . " : \"".stripslashes(htmlspecialchars_decode($_SESSION["titre"],ENT_QUOTES))."\".\n"; + $message .= stripslashes(html_entity_decode($adminName, ENT_QUOTES, "UTF-8"))." " . _("hast just created a poll called") . " : \"".stripslashes(htmlspecialchars_decode($title,ENT_QUOTES))."\".\n"; $message .= _("Thanks for filling the poll at the link above") . " :\n\n%s\n\n" . _("Thanks for your confidence.") . "\n".NOMAPPLICATION; $message_admin = _("This message should NOT be sent to the polled people. It is private for the poll's creator.\n\nYou can now modify it at the link above"); $message_admin .= " :\n\n"."%s \n\n" . _("Thanks for your confidence.") . "\n".NOMAPPLICATION; - $message = sprintf($message, Utils::getUrlSondage($sondage)); - $message_admin = sprintf($message_admin, Utils::getUrlSondage($sondage_admin, true)); + $message = sprintf($message, Utils::getUrlSondage($poll_id)); + $message_admin = sprintf($message_admin, Utils::getUrlSondage($admin_poll_id, true)); if (Utils::isValidEmail($_SESSION['adresse'])) { - Utils::sendEmail( "$_SESSION[adresse]", "[".NOMAPPLICATION."][" . _("Author's message") . "] " . _("Poll") . " : ".stripslashes(htmlspecialchars_decode($_SESSION["titre"],ENT_QUOTES)), $message_admin, $_SESSION['adresse'] ); - Utils::sendEmail( "$_SESSION[adresse]", "[".NOMAPPLICATION."][" . _("For sending to the polled users") . "] " . _("Poll") . " : ".stripslashes(htmlspecialchars_decode($_SESSION["titre"],ENT_QUOTES)), $message, $_SESSION['adresse'] ); + Utils::sendEmail( $adminMail, "[".NOMAPPLICATION."][" . _("Author's message") . "] " . _("Poll") . " : ".stripslashes(htmlspecialchars_decode($title,ENT_QUOTES)), $message_admin, $_SESSION['adresse'] ); + Utils::sendEmail( $adminMail, "[".NOMAPPLICATION."][" . _("For sending to the polled users") . "] " . _("Poll") . " : ".stripslashes(htmlspecialchars_decode($title,ENT_QUOTES)), $message, $_SESSION['adresse'] ); } } - error_log(date('H:i:s d/m/Y:') . ' CREATION: '.$sondage."\t".$_SESSION[formatsondage]."\t".$_SESSION[nom]."\t".$_SESSION[adresse]."\t \t".$_SESSION[toutchoix]."\n", 3, 'admin/logs_studs.txt'); - Utils::cleaning_polls($connect, 'admin/logs_studs.txt'); + + error_log(date('H:i:s d/m/Y:') . ' CREATION: '.$poll_id."\t".$format."\t".$adminName."\t".$adminMail."\t \t".$slots."\n", 3, 'admin/logs_studs.txt'); - // Don't keep days, hours and choices in memory (in order to make new polls) - for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) { - unset($_SESSION['horaires'.$i]); - } - unset($_SESSION["totalchoixjour"]); - unset($_SESSION['choices']); - - header("Location:".Utils::getUrlSondage($sondage_admin, true)); - - exit(); + return $admin_poll_id; } diff --git a/index.php b/index.php index 6fed009..4e46fbe 100644 --- a/index.php +++ b/index.php @@ -18,8 +18,6 @@ */ namespace Framadate; -use Framadate\Utils; - include_once __DIR__ . '/app/inc/init.php'; if (is_readable('bandeaux_local.php')) { @@ -28,12 +26,9 @@ if (is_readable('bandeaux_local.php')) { include_once('bandeaux.php'); } -session_start(); - // affichage de la page Utils::print_header( _("Home") ); bandeau_titre(_("Make your polls")); - echo '
diff --git a/infos_sondage.php b/infos_sondage.php index 59d5848..99f27c3 100644 --- a/infos_sondage.php +++ b/infos_sondage.php @@ -18,8 +18,10 @@ */ namespace Framadate; -session_start(); include_once __DIR__ . '/app/inc/init.php'; +if (!isset($_SESSION['form'])) { + $_SESSION['form'] = new Form(); +} if (file_exists('bandeaux_local.php')) { include_once('bandeaux_local.php'); @@ -27,14 +29,14 @@ if (file_exists('bandeaux_local.php')) { include_once('bandeaux.php'); } -// Type de sondage :
-

' . _("Your poll will be automatically removed "). $config['default_poll_duration'] . ' ' . _("days") ._(" after the last date of your poll:") . ' '.$removal_date.'.
' . _("You can fix another removal date for it.") .'

+

' . _("Your poll will be automatically removed "). $config['default_poll_duration'] . ' ' . _("days") . ' ' ._("after the last date of your poll") . '.
' . _("You can fix another removal date for it.") .'

- +
- +
'. _("(dd/mm/yyyy)") .' @@ -200,11 +179,10 @@ if (!isset($_SESSION['form']->titre) || !isset($_SESSION['form']->nom) || (($con
'."\n"; -//exit('
POST
'.print_r($_POST, true).'
SESSION
'.print_r($_SESSION, true).'
'); bandeau_pied(); - // Step 2/3 : Select dates of the poll + // Step 2/4 : Select dates of the poll } else { Utils::print_header ( _("Poll dates (2 on 3)") ); bandeau_titre(_("Poll dates (2 on 3)")); diff --git a/creation_sondage.php b/creation_sondage.php index 1226637..77ab9e0 100644 --- a/creation_sondage.php +++ b/creation_sondage.php @@ -38,24 +38,34 @@ function random($car) return $string; } -function ajouter_sondage($title, $comment, $adminName, $adminMail, $format, $endDate, $mailsonde, $slots) +function ajouter_sondage($title, $comment, $adminName, $adminMail, $format, $editable, $endDate, $receiveNewVotes, $choices) { global $connect; global $config; + + // Generate poll ids $poll_id = random(16); $admin_poll_id = $poll_id.random(8); + + // Insert poll + slots + $connect->beginTransaction(); - $date_fin = $_SESSION['champdatefin']; // provided by choix_autre.php or choix_date.php - $_SESSION['champdatefin'] = ''; //clean param cause 2 polls created by the same user in the same session can be affected by this param during the 2nd creation. $sql = 'INSERT INTO sondage - (id_sondage, commentaires, mail_admin, nom_admin, titre, id_sondage_admin, date_fin, format, mailsonde) - VALUES (?,?,?,?,?,?,?,?)'; + (poll_id, admin_poll_id, title, comment, admin_name, admin_mail, end_date, format, editable, receiveNewVotes) + VALUES (?,?,?,?,?,?,FROM_UNIXTIME(?),?,?,?)'; $prepared = $connect->prepare($sql); - $res = $prepared->execute(array($poll_id, $comment, $adminMail, $adminName, $title, $admin_poll_id, $format, $mailsonde)); + $prepared->execute(array($poll_id, $admin_poll_id, $title, $comment, $adminName, $adminMail, $endDate, $format, $editable, $receiveNewVotes)); - $prepared = $connect->prepare('INSERT INTO sujet_studs values (?, ?)'); - $prepared->execute(array($poll_id, $slots)); + $prepared = $connect->prepare('INSERT INTO sujet_studs (id_sondage, sujet) VALUES (?, ?)'); + foreach ($choices as $choice) { + foreach ($choice->getSlots() as $slot) { + $prepared->execute(array($poll_id, $choice->getName().'@'.$slot)); + } + } + $connect->commit(); + + // Send confirmation by mail if enabled if($config['use_smtp'] === true){ $message = _("This is the message you have to send to the people you want to poll. \nNow, you have to send this message to everyone you want to poll."); $message .= "\n\n"; @@ -74,7 +84,7 @@ function ajouter_sondage($title, $comment, $adminName, $adminMail, $format, $end } } - error_log(date('H:i:s d/m/Y:') . ' CREATION: '.$poll_id."\t".$format."\t".$adminName."\t".$adminMail."\t \t".$slots."\n", 3, 'admin/logs_studs.txt'); + error_log(date('H:i:s d/m/Y:') . ' CREATION: '.$poll_id."\t".$format."\t".$adminName."\t".$adminMail."\n", 3, 'admin/logs_studs.txt'); return $admin_poll_id; } diff --git a/infos_sondage.php b/infos_sondage.php index 99f27c3..dc773bf 100644 --- a/infos_sondage.php +++ b/infos_sondage.php @@ -41,7 +41,7 @@ if ((isset($_GET['choix_sondage']) && $_GET['choix_sondage'] == 'date') || // On teste toutes les variables pour supprimer l'ensemble des warnings PHP // On transforme en entites html les données afin éviter les failles XSS -$post_var = array('poursuivre', 'titre', 'nom', 'adresse', 'commentaires', 'studsplus', 'mailsonde', 'creation_sondage_date', 'creation_sondage_autre'); +$post_var = array('poursuivre', 'titre', 'nom', 'adresse', 'commentaires', 'editable', 'receiveNewVotes', 'creation_sondage_date', 'creation_sondage_autre'); foreach ($post_var as $var) { if (isset($_POST[$var]) === true) { $$var = htmlentities($_POST[$var], ENT_QUOTES, 'UTF-8'); @@ -55,8 +55,6 @@ $erreur_adresse = false; $erreur_injection_titre = false; $erreur_injection_nom = false; $erreur_injection_commentaires = false; -$cocheplus = ''; -$cochemail = ''; #tests if (Utils::issetAndNoEmpty("poursuivre")){ @@ -64,8 +62,8 @@ if (Utils::issetAndNoEmpty("poursuivre")){ $_SESSION['form']->nom = $nom; $_SESSION['form']->adresse = $adresse; $_SESSION['form']->commentaires = $commentaires; - $_SESSION['form']->studsplus = ($studsplus !== null) ? '+' : $_SESSION['form']->studsplus = ''; - $_SESSION['form']->mailsonde = ($mailsonde !== null) ? true : false; + $_SESSION['form']->editable = ($editable !== null) ? true : false; + $_SESSION['form']->receiveNewVotes = ($receiveNewVotes !== null) ? true : false; if ($config['use_smtp']==true){ if (Utils::isValidEmail($adresse) === false) { @@ -86,7 +84,7 @@ if (Utils::issetAndNoEmpty("poursuivre")){ } // Si pas d'erreur dans l'adresse alors on change de page vers date ou autre - if($config['use_smtp']==true){ + if($config['use_smtp'] == true){ $email_OK = $adresse && !$erreur_adresse; } else{ $email_OK = true; @@ -189,19 +187,15 @@ if (USE_REMOTE_USER && isset($_SERVER['REMOTE_USER'])) { } // Checkbox checked ? -if (!$_SESSION['form']->studsplus && !Utils::issetAndNoEmpty('creation_sondage_date') && !Utils::issetAndNoEmpty('creation_sondage_autre')) { - $_SESSION['form']->studsplus="+"; +if ($_SESSION['form']->editable) { + $editable = 'checked'; } -if ($_SESSION['form']->studsplus=="+") { - $cocheplus="checked"; +if ($_SESSION['form']->receiveNewVotes) { + $receiveNewVotes = 'checked'; } -if ($_SESSION['form']->mailsonde) { - $cochemail="checked"; -} - -// Affichage du formulaire +// Display form echo '
@@ -247,7 +241,7 @@ echo '
@@ -257,7 +251,7 @@ if($config['use_smtp']==true){
diff --git a/install.mysql.sql b/install.mysql.sql index c873a75..3980fd7 100644 --- a/install.mysql.sql +++ b/install.mysql.sql @@ -23,18 +23,19 @@ CREATE TABLE IF NOT EXISTS `comments` ( -- CREATE TABLE IF NOT EXISTS `sondage` ( - `id_sondage` char(16) NOT NULL, - `commentaires` text, - `mail_admin` varchar(128) DEFAULT NULL, - `nom_admin` varchar(64) DEFAULT NULL, - `titre` text, - `id_sondage_admin` char(24) DEFAULT NULL, - `date_creation` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `date_fin` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', - `format` varchar(2) DEFAULT NULL, - `mailsonde` tinyint(1) DEFAULT '0', + `poll_id` char(16) NOT NULL, + `admin_poll_id` char(24) DEFAULT NULL, + `title` text NOT NULL, + `comment` text, + `admin_name` varchar(64) DEFAULT NULL, + `admin_mail` varchar(128) DEFAULT NULL, + `creation_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `end_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', + `format` varchar(1) DEFAULT NULL, + `editable` tinyint(1) DEFAULT '0', + `receiveNewVotes` tinyint(1) DEFAULT '0', `statut` int(11) NOT NULL DEFAULT '1' COMMENT '1 = actif ; 0 = inactif ; ', - UNIQUE KEY `id_sondage` (`id_sondage`) + UNIQUE KEY `poll_id` (`poll_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- From de04d474347dcb39b4e8faea40accda0317006a9 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Fri, 5 Dec 2014 01:09:14 +0100 Subject: [PATCH 004/151] Minor changes on "constants.php.template" --- app/inc/constants.php.template | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/inc/constants.php.template b/app/inc/constants.php.template index 82567d6..c9e31de 100644 --- a/app/inc/constants.php.template +++ b/app/inc/constants.php.template @@ -24,7 +24,7 @@ const VERSION = 0.8; const STUDS_URL = ''; // Application name -const NOMAPPLICATION = ""; +const NOMAPPLICATION = ''; // Database administrator email const ADRESSEMAILADMIN = ''; @@ -36,7 +36,7 @@ const ADRESSEMAILREPONSEAUTO = ''; const BASE = ''; // Database user -const USERBASE = ""; +const USERBASE = ''; // Database password const USERPASSWD = ''; @@ -44,7 +44,7 @@ const USERPASSWD = ''; // Database server name, leave empty to use a socket const SERVEURBASE = ''; -// Database type (mysql, postgres…) http://phplens.com/lens/adodb/docs-adodb.htm#drivers +// Database type (pdo, mysql, postgres…) http://phplens.com/lens/adodb/docs-adodb.htm#drivers const BASE_TYPE = ''; // Default Language using POSIX variant of BC P47 standard (choose in $ALLOWED_LANGUAGES) From 46ea697cb6bb0743965facebeebb0c8a2067663b Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sat, 6 Dec 2014 19:42:01 +0100 Subject: [PATCH 005/151] Refactor on choix_autre.php * Utils::issetAndNoEmpty is now removed * Use Form object to store value from page to page --- app/classes/Framadate/Choice.php | 2 +- app/classes/Framadate/Utils.php | 12 ++- choix_autre.php | 138 +++++++++++++++++-------------- choix_date.php | 4 +- infos_sondage.php | 10 +-- 5 files changed, 94 insertions(+), 72 deletions(-) diff --git a/app/classes/Framadate/Choice.php b/app/classes/Framadate/Choice.php index d1eec51..6375945 100644 --- a/app/classes/Framadate/Choice.php +++ b/app/classes/Framadate/Choice.php @@ -13,7 +13,7 @@ class Choice */ private $slots; - public function __construct($name) + public function __construct($name='') { $this->name = $name; $this->slots = array(); diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index ae431c0..78da6e3 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -185,18 +185,19 @@ class Utils /** * Fonction vérifiant l'existance et la valeur non vide d'une clé d'un tableau + * @deprecated * @param string $name La clé à tester * @param array $tableau Le tableau où rechercher la clé ($_POST par défaut) * @return bool Vrai si la clé existe et renvoie une valeur non vide */ - public static function issetAndNoEmpty($name, $tableau = null) + /*public static function issetAndNoEmpty($name, $tableau = null) { if (is_null($tableau)) { $tableau = $_POST; } return isset($tableau[$name]) && ! empty($tableau[$name]); - } + }*/ /** * Fonction permettant de générer les URL pour les sondage @@ -258,4 +259,11 @@ class Utils } $connect->commit(); } + + public static function debug($object) + { + echo '
';
+        print_r($object);
+        echo '
'; + } } diff --git a/choix_autre.php b/choix_autre.php index fd69bd5..7ebca4d 100644 --- a/choix_autre.php +++ b/choix_autre.php @@ -18,7 +18,8 @@ */ namespace Framadate; -session_start(); +include_once __DIR__ . '/app/inc/init.php'; + include_once('creation_sondage.php'); if (file_exists('bandeaux_local.php')) { @@ -27,82 +28,90 @@ if (file_exists('bandeaux_local.php')) { include_once('bandeaux.php'); } -// Step 1/3 : error if $_SESSION from info_sondage are not valid -if (Utils::issetAndNoEmpty('titre', $_SESSION) === false || Utils::issetAndNoEmpty('nom', $_SESSION) === false || (($config['use_smtp']) ? Utils::issetAndNoEmpty('adresse', $_SESSION) === false : false)) { +// Step 1/4 : error if $_SESSION from info_sondage are not valid +if (empty($_SESSION['form']->titre) || empty($_SESSION['form']->nom) || (($config['use_smtp']) ? empty($_SESSION['form']->adresse) : false)) { Utils::print_header ( _("Error!") ); bandeau_titre(_("Error!")); echo '
-

' . _("You haven't filled the first section of the poll creation.") . ' !

-

' . _("Back to the homepage of ") . ' ' . NOMAPPLICATION . '

+

' . _('You haven\'t filled the first section of the poll creation.') . ' !

+

' . _('Back to the homepage of') . ' ' . NOMAPPLICATION . '

'."\n"; bandeau_pied(); } else { + // Step 4 : Data prepare before insert in DB - if (isset($_POST["confirmecreation"])) { - //recuperation des données de champs textes - $temp_results = ''; - if (isset($_SESSION['choices'])) { - for ($i = 0; $i < count($_SESSION['choices']); $i++) { - if ($_SESSION['choices'][$i]!="") { - $temp_results.=','.str_replace(",", " ", htmlentities(html_entity_decode($_SESSION['choices'][$i], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8')); - } + if (isset($_POST['confirmecreation'])) { + + $registredate = explode('/', $_POST['champdatefin']); + if (is_array($registredate) == true && count($registredate) == 3) { + $time = mktime(0,0,0,$registredate[1],$registredate[0],$registredate[2]); + if ($time > time() + (24*60*60)) { + $_SESSION['form']->champdatefin = $time; } } - $temp_results=substr($temp_results,1); - $_SESSION["toutchoix"]=$temp_results; + // format du sondage AUTRE + $_SESSION['form']->formatsondage = 'A'; + + // Insert poll in database + $admin_poll_id = ajouter_sondage( + $_SESSION['form']->titre, + $_SESSION['form']->commentaires, + $_SESSION['form']->nom, + $_SESSION['form']->adresse, + $_SESSION['form']->formatsondage, + $_SESSION['form']->editable, + $_SESSION['form']->champdatefin, + $_SESSION['form']->receiveNewVotes, + $_SESSION['form']->getChoices() + ); + + // Clean Form data in $_SESSION + unset($_SESSION['form']); - - if (Utils::issetAndNoEmpty('champdatefin')) { - $registredate = explode("/",$_POST["champdatefin"]); - if (is_array($registredate) == true && count($registredate) == 3) { - $time = mktime(0,0,0,$registredate[1],$registredate[0],$registredate[2]); - if ($time > time() + (24*60*60)) { - $_SESSION["champdatefin"]=$time; - } - } - } - - //format du sondage AUTRE - $_SESSION["formatsondage"]="A".$_SESSION["studsplus"]; - - ajouter_sondage(); + // Delete old polls + Utils::cleaningOldPolls($connect, 'admin/logs_studs.txt'); + + // Redirect to poll administration + header('Location:' . Utils::getUrlSondage($admin_poll_id, true)); + exit; } - // recuperation des sujets pour sondage AUTRE - if (isset($_POST['choices'])) { - $k = 0; - for ($i = 0; $i < count($_POST['choices']); $i++) { - if (Utils::issetAndNoEmpty($i, $_POST['choices'])) { - $_SESSION['choices'][$k]=htmlentities(html_entity_decode($_POST['choices'][$i], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - $k++; + // Step 3/4 : Confirm poll creation and choose a removal date + else if (isset($_POST['fin_sondage_autre'])) { + Utils::print_header ( _('Removal date and confirmation (3 on 3)') ); + bandeau_titre(_('Removal date and confirmation (3 on 3)')); + + + // Store choices in $_SESSION + if (isset($_POST['choices'])) { + $_SESSION['form']->clearChoices(); + foreach ($_POST['choices'] as $c) + { + if (!empty($c)) + { + $choice = new Choice(htmlentities(html_entity_decode($c, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8')); + $_SESSION['form']->addChoice($choice); + } } } - } - - // Step 3/3 : Confirm poll creation and choose a removal date - if (isset($_POST["fin_sondage_autre"])) { - Utils::print_header ( _("Removal date and confirmation (3 on 3)") ); - bandeau_titre(_("Removal date and confirmation (3 on 3)")); // Expiration date is initialised with config parameter. Value will be modified in step 4 if user has defined an other date - $_SESSION["champdatefin"]= time()+ (86400 * $config['default_poll_duration']); //60 sec * 60 min * 24 hours * config - - $removal_date= utf8_encode(strftime($date_format['txt_full'], ($_SESSION["champdatefin"])));//textual date + $_SESSION['form']->champdatefin = time() + (86400 * $config['default_poll_duration']); //60 sec * 60 min * 24 hours * config // Summary $summary = '
    '; - for ($i=0;$igetChoices() as $choice) { - preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$_SESSION['choices'][$i],$md_a_img); // Markdown [![alt](src)](href) - preg_match_all('/!\[(.*?)\]\((.*?)\)/',$_SESSION['choices'][$i],$md_img); // Markdown ![alt](src) - preg_match_all('/\[(.*?)\]\((.*?)\)/',$_SESSION['choices'][$i],$md_a); // Markdown [text](href) + preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/', $choice->getName(), $md_a_img); // Markdown [![alt](src)](href) + preg_match_all('/!\[(.*?)\]\((.*?)\)/', $choice->getName(), $md_img); // Markdown ![alt](src) + preg_match_all('/\[(.*?)\]\((.*?)\)/', $choice->getName(), $md_a); // Markdown [text](href) if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) $li_subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); @@ -120,7 +129,7 @@ if (Utils::issetAndNoEmpty('titre', $_SESSION) === false || Utils::issetAndNoEmp } else { // text only - $li_subject_text = stripslashes($_SESSION['choices'][$i]); + $li_subject_text = stripslashes($choice->getName()); $li_subject_html = $li_subject_text; } @@ -129,6 +138,8 @@ if (Utils::issetAndNoEmpty('titre', $_SESSION) === false || Utils::issetAndNoEmp } $summary .= '
'; + $end_date_str = utf8_encode(strftime('%d/%M/%Y', $_SESSION['form']->champdatefin));//textual date + echo '
@@ -138,13 +149,13 @@ if (Utils::issetAndNoEmpty('titre', $_SESSION) === false || Utils::issetAndNoEmp '. $summary .'
-

' . _("Your poll will be automatically removed after"). " " . $config['default_poll_duration'] . " " . _("days") . ': '.$removal_date.'.
' . _("You can fix another removal date for it.") .'

+

' . _('Your poll will be automatically removed after'). ' ' . $config['default_poll_duration'] . ' ' . _('days') . '.
' . _("You can fix another removal date for it.") .'

- +
'. _("(dd/mm/yyyy)") .' @@ -168,10 +179,10 @@ if (Utils::issetAndNoEmpty('titre', $_SESSION) === false || Utils::issetAndNoEmp bandeau_pied(); - // Step 2/3 : Select choices of the poll + // Step 2/4 : Select choices of the poll } else { - Utils::print_header( _("Poll subjects (2 on 3)")); - bandeau_titre(_("Poll subjects (2 on 3)")); + Utils::print_header( _('Poll subjects (2 on 3)')); + bandeau_titre(_('Poll subjects (2 on 3)')); echo ' @@ -187,16 +198,17 @@ if (Utils::issetAndNoEmpty('titre', $_SESSION) === false || Utils::issetAndNoEmp echo '
'."\n"; // Fields choices : 5 by default - $nb_choices = (isset($_SESSION['choices'])) ? max(count($_SESSION['choices']), 5) : 5; + $choices = $_SESSION['form']->getChoices(); + $nb_choices = max(count($choices), 5); for ($i = 0; $i < $nb_choices; $i++) { - $choice_value = (isset($_SESSION['choices'][$i])) ? str_replace("\\","",$_SESSION['choices'][$i]) : ''; + $choice = isset($choices[$i]) ? $choices[$i] : new Choice(); echo '
- +
- '; + '; if($config['user_can_add_img_or_link']){ - echo ' '; + echo ' '; } echo '
@@ -206,8 +218,8 @@ if (Utils::issetAndNoEmpty('titre', $_SESSION) === false || Utils::issetAndNoEmp echo '
- - + +
diff --git a/choix_date.php b/choix_date.php index 200b8a9..99f5a5b 100644 --- a/choix_date.php +++ b/choix_date.php @@ -28,7 +28,7 @@ if (is_readable('bandeaux_local.php')) { include_once('bandeaux.php'); } -// Step 1/3 : error if $_SESSION from info_sondage are not valid +// Step 1/4 : error if $_SESSION from info_sondage are not valid if (!isset($_SESSION['form']->titre) || !isset($_SESSION['form']->nom) || (($config['use_smtp']) ? !isset($_SESSION['form']->adresse) : false)) { Utils::print_header ( _("Error!") ); @@ -39,6 +39,7 @@ if (!isset($_SESSION['form']->titre) || !isset($_SESSION['form']->nom) || (($con

' . _("You haven't filled the first section of the poll creation.") . ' !

' . _("Back to the homepage of ") . ' ' . '' . NOMAPPLICATION . '.

'; + bandeau_pied(); @@ -66,6 +67,7 @@ if (!isset($_SESSION['form']->titre) || !isset($_SESSION['form']->nom) || (($con $_SESSION['form']->champdatefin=end($temp_results)+(86400 * $config['default_poll_duration']); } + // Insert poll in database $admin_poll_id = ajouter_sondage( $_SESSION['form']->titre, $_SESSION['form']->commentaires, diff --git a/infos_sondage.php b/infos_sondage.php index dc773bf..58e00d8 100644 --- a/infos_sondage.php +++ b/infos_sondage.php @@ -57,7 +57,7 @@ $erreur_injection_nom = false; $erreur_injection_commentaires = false; #tests -if (Utils::issetAndNoEmpty("poursuivre")){ +if (!empty($_POST['poursuivre'])){ $_SESSION['form']->titre = $titre; $_SESSION['form']->nom = $nom; $_SESSION['form']->adresse = $adresse; @@ -140,7 +140,7 @@ $errors = array( ) ); -if (!$_SESSION['form']->titre && Utils::issetAndNoEmpty("poursuivre") ) { +if (!$_SESSION['form']->titre && !empty($_POST['poursuivre'])) { $errors['title']['aria'] = 'aria-describeby="poll_title_error" '; $errors['title']['class'] = ' has-error'; $errors['title']['msg'] = '

' . _("Enter a title") . '

'; } elseif ($erreur_injection_titre) { @@ -153,7 +153,7 @@ if ($erreur_injection_commentaires) { $errors['description']['msg'] = '

' . _("Characters < > and \" are not permitted") . '

'; } -if (!$_SESSION['form']->nom && Utils::issetAndNoEmpty("poursuivre")) { +if (!$_SESSION['form']->nom && !empty($_POST['poursuivre'])) { $errors['name']['aria'] = 'aria-describeby="poll_name_error" '; $errors['name']['class'] = ' has-error'; $errors['name']['msg'] = '

' . _("Enter a name") . '

'; } elseif ($erreur_injection_nom) { @@ -161,10 +161,10 @@ if (!$_SESSION['form']->nom && Utils::issetAndNoEmpty("poursuivre")) { $errors['name']['msg'] = '

' . _("Characters < > and \" are not permitted") . '

'; } -if (!$_SESSION['form']->adresse && Utils::issetAndNoEmpty("poursuivre")) { +if (!$_SESSION['form']->adresse && !empty($_POST['poursuivre'])) { $errors['email']['aria'] = 'aria-describeby="poll_name_error" '; $errors['email']['class'] = ' has-error'; $errors['email']['msg'] = '

' . _("Enter an email address") . '

'; -} elseif ($erreur_adresse && Utils::issetAndNoEmpty("poursuivre")) { +} elseif ($erreur_adresse && !empty($_POST['poursuivre'])) { $errors['email']['aria'] = 'aria-describeby="poll_email_error" '; $errors['email']['class'] = ' has-error'; $errors['email']['msg'] = '

' . _("The address is not correct! You should enter a valid email address (like r.stallman@outlock.com) in order to receive the link to your poll.") . '

'; } From 3d0e167e770d016d61440a60db67d1f4698d0c75 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 7 Dec 2014 16:47:35 +0100 Subject: [PATCH 006/151] Clean a lot of adminstuds.php --- adminstuds.php | 186 ++++++++++++++---------------- app/classes/Framadate/FramaDB.php | 6 + creation_sondage.php | 13 ++- 3 files changed, 106 insertions(+), 99 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index 3c3f017..daee4b7 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -34,37 +34,36 @@ $numsondageadmin = false; $sondage = false; // recuperation du numero de sondage admin (24 car.) dans l'URL -if (Utils::issetAndNoEmpty('sondage', $_GET) && is_string($_GET['sondage']) && strlen($_GET['sondage']) === 24) { - $numsondageadmin=$_GET["sondage"]; - //on découpe le résultat pour avoir le numéro de sondage (16 car.) - $numsondage=substr($numsondageadmin, 0, 16); +if (!empty($_GET['sondage']) && is_string($_GET['sondage']) && strlen($_GET['sondage']) === 24) { + $admin_poll_id = $_GET["sondage"]; + // on découpe le résultat pour avoir le numéro de sondage (16 car.) + $poll_id = substr($admin_poll_id, 0, 16); } -if (preg_match(";[\w\d]{24};i", $numsondageadmin)) { - $sql = 'SELECT * FROM sondage WHERE id_sondage_admin = '.$connect->Param('numsondageadmin'); - $sql = $connect->Prepare($sql); - $sondage = $connect->Execute($sql, array($numsondageadmin)); +if (preg_match(";[\w\d]{24};i", $admin_poll_id)) { + $prepared = $connect->prepare('SELECT * FROM sondage WHERE admin_poll_id = ?'); + $prepared->execute(array($admin_poll_id)); + $poll = $prepared->fetch(); + $prepared->closeCursor(); + + $prepared = $connect->prepare('SELECT * FROM sujet_studs WHERE id_sondage = ?'); + $prepared->execute(array($poll_id)); + $sujets = $prepared->fetchAll(); - if ($sondage !== false) { - $sql = 'SELECT * FROM sujet_studs WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $sujets = $connect->Execute($sql, array($numsondage)); - - $sql = 'SELECT * FROM user_studs WHERE id_sondage = '.$connect->Param('numsondage').' order by id_users'; - $sql = $connect->Prepare($sql); - $user_studs = $connect->Execute($sql, array($numsondage)); - } + $prepared = $connect->prepare('SELECT * FROM user_studs WHERE id_sondage = ? order by id_users'); + $prepared->execute(array($poll_id)); + $users = $prepared->fetchAll(); } //verification de l'existence du sondage, s'il n'existe pas on met une page d'erreur -if (!$sondage || $sondage->RecordCount() != 1){ - Utils::print_header( _("Error!")); +if (!$poll || !$sujets) { + Utils::print_header( _('Error!')); - bandeau_titre(_("Error!")); + bandeau_titre(_('Error!')); echo '
-

' . _("This poll doesn't exist !") . '

+

' . _('This poll doesn\'t exist !') . '

' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

'."\n"; @@ -73,12 +72,9 @@ if (!$sondage || $sondage->RecordCount() != 1){ die(); } -$dsujet=$sujets->FetchObject(false); -$dsondage=$sondage->FetchObject(false); - // Send email (only once during the session) to alert admin of the change he made. ==> two modifications (comment, title, description, ...) on differents polls in the same session will generate only one mail. -$email_admin = $dsondage->mail_admin; -$poll_title = $dsondage->titre; +$email_admin = $poll->admin_mail; +$poll_title = $poll->title; $smtp_allowed = $config['use_smtp']; function send_mail_admin() { global $email_admin; @@ -86,7 +82,7 @@ function send_mail_admin() { global $numsondageadmin; global $smtp_allowed; if($smtp_allowed==true){ - if(!isset($_SESSION["mail_admin_sent"])) { + if(!isset($_SESSION['mail_admin_sent'])) { Utils::sendEmail( $email_admin, _("[ADMINISTRATOR] New settings for your poll") . ' ' . stripslashes( $poll_title ), _("You have changed the settings of your poll. \nYou can modify this poll with this link") . @@ -117,15 +113,15 @@ if (isset($_POST["boutonnouveautitre"])) { } // si le bouton est activé, quelque soit la valeur du champ textarea -if (isset($_POST["boutonnouveauxcommentaires"])) { - if (Utils::issetAndNoEmpty('nouveautitre') === false) { +if (isset($_POST['boutonnouveauxcommentaires'])) { + if (empty($_POST['nouveautitre'])) { $err |= COMMENT_EMPTY; } else { $commentaires = htmlentities(html_entity_decode($_POST['nouveauxcommentaires'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); //Update SQL database with new description - $sql = 'UPDATE sondage SET commentaires = '.$connect->Param('commentaires').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); + $prepared = $connect->prepare('UPDATE sondage SET commentaires = ? WHERE id_sondage = ?'); + $prepared->execute(array($commentaires, $poll_id)); //Email sent to the admin if ($connect->Execute($sql, array($commentaires, $numsondage))) { @@ -136,22 +132,23 @@ if (isset($_POST["boutonnouveauxcommentaires"])) { //si la valeur de la nouvelle adresse est valide et que le bouton est activé if (isset($_POST["boutonnouvelleadresse"])) { - if (Utils::issetAndNoEmpty('nouvelleadresse') === false || Utils::isValidEmail($_POST["nouvelleadresse"]) === false) { + if (empty($_POST['nouvelleadresse']) || Utils::isValidEmail($_POST["nouvelleadresse"]) === false) { $err |= INVALID_EMAIL; } else { $nouvelleadresse = htmlentities(html_entity_decode($_POST['nouvelleadresse'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); //Update SQL database with new email - $sql = 'UPDATE sondage SET mail_admin = '.$connect->Param('nouvelleadresse').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); + $prepared = $connect->prepare('UPDATE sondage SET mail_admin = ? WHERE id_sondage = ?'); + $executed = $prepared->execute(array($nouvelleadresse, $poll_id)); //Email sent to the admin - if ($connect->Execute($sql, array($nouvelleadresse, $numsondage))) { + if ($executed) { send_mail_admin(); } } } +// TODO OPZ : Revoir ce que fait ce truc exactament //New poll rules if (isset($_POST["btn_poll_rules"])) { echo ''; @@ -164,23 +161,24 @@ if (isset($_POST["btn_poll_rules"])) { } //Update SQL database with new rules - $sql = 'UPDATE sondage SET format = '.$connect->Param('new_poll_rules').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); + $prepared = $connect->prepare('UPDATE sondage SET format = ? WHERE id_sondage = ?'); + $executed = $prepared->execute(array($new_poll_rules, $poll_id)); //Email sent to the admin - if ($connect->Execute($sql, array($new_poll_rules, $numsondage))) { + if ($executed) { send_mail_admin(); } } // reload -$dsujet=$sujets->FetchObject(false); -$dsondage=$sondage->FetchObject(false); +// TODO OPZ Pourquoi recharger +// $dsujet= $sujets->FetchObject(false); +// $dsondage= $sondage->FetchObject(false); -if (isset($_POST["ajoutsujet"])) { - Utils::print_header( _("Add a column") .' - ' . stripslashes( $dsondage->titre )); +if (isset($_POST['ajoutsujet'])) { + Utils::print_header( _('Add a column') .' - ' . stripslashes( $poll->title)); - bandeau_titre(_("Make your polls")); + bandeau_titre(_('Make your polls')); //on recupere les données et les sujets du sondage @@ -254,7 +252,7 @@ if (isset($_POST["suppressionsondage"])) { } // Remove all the comments -if (isset($_POST["removecomments"])) { +if (isset($_POST['removecomments'])) { $sql = 'DELETE FROM comments WHERE id_sondage='.$connect->Param('numsondage'); $sql = $connect->Prepare($sql); $cleaning = $connect->Execute($sql, array($numsondage)); @@ -298,17 +296,17 @@ if (isset($_POST["confirmesuppression"])) { // quand on ajoute un commentaire utilisateur if (isset($_POST['ajoutcomment'])) { - if (Utils::issetAndNoEmpty('commentuser') === false) { + if (empty($_POST['commentuser'])) { $err |= COMMENT_USER_EMPTY; } else { $comment_user = htmlentities(html_entity_decode($_POST["commentuser"], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); } - if(Utils::issetAndNoEmpty('comment') === false) { + if(empty($_POST['comment'])) { $err |= COMMENT_EMPTY; } - if (Utils::issetAndNoEmpty('comment') && !Utils::is_error(COMMENT_EMPTY) && !Utils::is_error(NO_POLL) && !Utils::is_error(COMMENT_USER_EMPTY)) { + if (!empty($_POST['comment']) && !Utils::is_error(COMMENT_EMPTY) && !Utils::is_error(NO_POLL) && !Utils::is_error(COMMENT_USER_EMPTY)) { $comment = htmlentities(html_entity_decode($_POST["comment"], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); // Check for doublons @@ -339,8 +337,8 @@ if (isset($_POST['ajoutcomment'])) { } } -$nbcolonnes = substr_count($dsujet->sujet, ',') + 1; -$nblignes = $user_studs->RecordCount(); +$nbcolonnes = count($sujets); +$nblignes = count($users); //si il n'y a pas suppression alors on peut afficher normalement le tableau @@ -494,12 +492,11 @@ if (isset($_POST["ajoutercolonne"]) && (substr($dsondage->format, 0, 1) == "D")) for ($i = 0; $i < $nblignes; $i++) { if (isset($_POST["effaceligne$i"])) { $compteur=0; - $sql = 'DELETE FROM user_studs WHERE nom = '.$connect->Param('nom').' AND id_users = '.$connect->Param('id_users'); - $sql = $connect->Prepare($sql); + $prepared = $connect->prepare('DELETE FROM user_studs WHERE nom = ? AND id_users = ?'); - while ($data=$user_studs->FetchNextObject(false)) { + foreach ($users as $user) { if ($compteur==$i){ - $connect->Execute($sql, array($data->nom, $data->id_users)); + $prepared->execute(array($user->nom, $user->id_users)); } $compteur++; @@ -508,8 +505,8 @@ for ($i = 0; $i < $nblignes; $i++) { } -//suppression d'un commentaire utilisateur -$sql = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; +// TODO OPZ Revoir toute cette partie suppression d'un commentaire utilisateur +/*$sql = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; $sql = $connect->Prepare($sql); $comment_user = $connect->Execute($sql, array($numsondage)); $i = 0; @@ -522,7 +519,7 @@ while ($dcomment = $comment_user->FetchNextObject(false)) { $i++; } - +*/ //on teste pour voir si une ligne doit etre modifiée $testmodifier = false; @@ -625,8 +622,8 @@ for ($i = 0; $i < $nbcolonnes; $i++) { } -//recuperation des donnes de la base -$sql = 'SELECT * FROM sondage WHERE id_sondage_admin = '.$connect->Param('numsondageadmin'); +// TODO OPZ Déjà fait en début de fichier recuperation des donnes de la base +/*$sql = 'SELECT * FROM sondage WHERE id_sondage_admin = '.$connect->Param('numsondageadmin'); $sql = $connect->Prepare($sql); $sondage = $connect->Execute($sql, array($numsondageadmin)); @@ -652,7 +649,7 @@ if ($sondage !== false) { bandeau_pied(); die(); -} +}*/ // Errors $errors = ''; @@ -670,14 +667,14 @@ if (isset($erreur_ajout_date) && $erreur_ajout_date) { } //Poll title, description and email values -$title = (isset($_POST["boutonnouveautitre"]) && Utils::issetAndNoEmpty('nouveautitre')) ? htmlentities(html_entity_decode($_POST['nouveautitre'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8') : stripslashes( $dsondage->titre ); -$description = (isset($_POST["nouveauxcommentaires"])) ? stripslashes(htmlentities(html_entity_decode($_POST['nouveauxcommentaires'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8')) : stripslashes( $dsondage->commentaires ); -$email_admin = (isset($_POST["boutonnouvelleadresse"]) && Utils::issetAndNoEmpty('nouvelleadresse')) ? htmlentities(html_entity_decode($_POST['nouvelleadresse'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8') : stripslashes( $dsondage->mail_admin ); +$title = (isset($_POST["boutonnouveautitre"]) && !empty($_POST['nouveautitre'])) ? htmlentities(html_entity_decode($_POST['nouveautitre'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8') : stripslashes( $poll->title); +$description = (isset($_POST["nouveauxcommentaires"])) ? stripslashes(htmlentities(html_entity_decode($_POST['nouveauxcommentaires'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8')) : stripslashes( $poll->comment); +$email_admin = (isset($_POST["boutonnouvelleadresse"]) && !empty($_POST['nouvelleadresse'])) ? htmlentities(html_entity_decode($_POST['nouvelleadresse'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8') : stripslashes( $poll->admin_mail ); //Poll format (locked A-/D-, open A/D, editable A+/D+) -$poll_rules = (isset($_POST["poll_rules"]) && Utils::issetAndNoEmpty('btn_poll_rules')) ? $_POST["poll_rules"] : substr($dsondage->format, 1, 1); +$poll_rules = (isset($_POST["poll_rules"]) && !empty($_POST['btn_poll_rules'])) ? $_POST["poll_rules"] : substr($poll->format, 1, 1); $poll_rules_opt1 = '';$poll_rules_opt2 = '';$poll_rules_opt3 = ''; -if($poll_rules == '+') { +if($poll->editable) { $poll_rules_text = ' '. _("Votes are editable"); $poll_rules_opt3 = 'selected'; } elseif($poll_rules == '-') { @@ -721,7 +718,7 @@ echo '
- + @@ -739,7 +736,7 @@ echo '

'. _("Initiator of the poll") .'

-

'.stripslashes($dsondage->nom_admin).'

+

'.stripslashes($poll->admin_name).'

'.$email_admin.'

@@ -769,16 +766,16 @@ echo '

'. _("Expiration's date") .'

-

'.date("d/m/Y",strtotime($dsondage->date_fin)).'

+

'.date("d/m/Y",strtotime($poll->end_date)).'

@@ -805,14 +802,14 @@ echo '
'."\n"; // .jumbotron -//on recupere les données et les sujets du sondage -$dsujet=$sujets->FetchObject(false); -$dsondage=$sondage->FetchObject(false); +// TODO OPZ : Pourquoi ? on recupere les données et les sujets du sondage +/*$dsujet=$sujets->FetchObject(false); +$dsondage=$sondage->FetchObject(false);*/ -//reformatage des données des sujets du sondage -$toutsujet=explode(",",$dsujet->sujet); +// TODO OPZ : Déjà présent sous la bonne forme : reformatage des données des sujets du sondage +/*$toutsujet=explode(",",$dsujet->sujet); $toutsujet=str_replace("°","'",$toutsujet); -$nbcolonnes=substr_count($dsujet->sujet,',')+1; +$nbcolonnes=substr_count($dsujet->sujet,',')+1;*/ // Table headers $thead = ''; @@ -825,7 +822,7 @@ $td_headers = array(); // for a11y, headers="M1 D4 H5" on each td $radio_title = array(); // date for // Dates poll -if (substr($dsondage->format, 0, 1)=="D") { +if (substr($poll->format, 0, 1)=="D") { $tr_months = ''; $tr_days = ''; @@ -834,8 +831,8 @@ if (substr($dsondage->format, 0, 1)=="D") { // Headers $colspan_month = 1; $colspan_day = 1; - - for ($i = 0; $i < count($toutsujet); $i++) { + + for ($i = 0; $i < count($sujets); $i++) { // Current date $current = $toutsujet[$i];//format date@hour. ex : 2020292820@10:00 @@ -897,18 +894,16 @@ if (substr($dsondage->format, 0, 1)=="D") { // Subjects poll } else { - $toutsujet=str_replace("@","
",$toutsujet); - $tr_subjects = ''; - for ($i = 0; isset($toutsujet[$i]); $i++) { + foreach ($sujets as $i=>$sujet) { $td_headers[$i]='';$radio_title[$i]=''; // init before concatenate // Subjects - preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$toutsujet[$i],$md_a_img); // Markdown [![alt](src)](href) - preg_match_all('/!\[(.*?)\]\((.*?)\)/',$toutsujet[$i],$md_img); // Markdown ![alt](src) - preg_match_all('/\[(.*?)\]\((.*?)\)/',$toutsujet[$i],$md_a); // Markdown [text](href) + preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$sujet->sujet,$md_a_img); // Markdown [![alt](src)](href) + preg_match_all('/!\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_img); // Markdown ![alt](src) + preg_match_all('/\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_a); // Markdown [text](href) if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) $th_subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); @@ -926,7 +921,7 @@ if (substr($dsondage->format, 0, 1)=="D") { } else { // text only - $th_subject_text = stripslashes($toutsujet[$i]); + $th_subject_text = stripslashes($sujet->sujet); $th_subject_html = $th_subject_text; } @@ -980,14 +975,13 @@ echo ' $somme[] = 0; $compteur = 0; -while ($data = $user_studs->FetchNextObject(false)) { +foreach($users as $user) { - $ensemblereponses = $data->reponses; + $ensemblereponses = $user->reponses; // Print name - $nombase=str_replace("°","'",$data->nom); echo ' -'.stripslashes($nombase).''."\n"; +'.stripslashes($user->nom).''."\n"; // si la ligne n'est pas a changer, on affiche les données if (!$testligneamodifier) { @@ -1154,9 +1148,6 @@ for ($i = 0; $i < $nbcolonnes; $i++) { } $tr_addition .= ''; -//recuperation des valeurs des sujets et adaptation pour affichage -$toutsujet = explode(",", $dsujet->sujet); - $meilleursujet = str_replace("°", "'", $meilleursujet).''; $vote_str = ($meilleurecolonne > 1) ? $vote_str = _('votes') : _('vote'); @@ -1188,12 +1179,11 @@ if ($compteursujet == 1) { echo '

'."\n"; -// Commments -$sql = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; -$sql = $connect->Prepare($sql); -$comment_user = $connect->Execute($sql, array($numsondage)); -if ($comment_user->RecordCount() != 0) { +// Commments +$comment_user = $connect->allComments($poll_id); + +if (count($comment_user) != 0) { echo '

' . _("Comments of polled people") . '

'."\n"; $i = 0; diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 60f5b62..23a80d5 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -37,5 +37,11 @@ class FramaDB function query($sql) { return $this->pdo->query($sql); } + + function allComments($poll_id) { + $prepared = $this->prepare('SELECT * FROM comments WHERE id_sondage=? ORDER BY id_comment'); + $prepared->execute(array($poll_id)); + return $prepared->fetchAll(); + } } diff --git a/creation_sondage.php b/creation_sondage.php index 77ab9e0..4ca5c8f 100644 --- a/creation_sondage.php +++ b/creation_sondage.php @@ -58,8 +58,19 @@ function ajouter_sondage($title, $comment, $adminName, $adminMail, $format, $edi $prepared = $connect->prepare('INSERT INTO sujet_studs (id_sondage, sujet) VALUES (?, ?)'); foreach ($choices as $choice) { + $joinedSlots = ''; foreach ($choice->getSlots() as $slot) { - $prepared->execute(array($poll_id, $choice->getName().'@'.$slot)); + if ($first) { + $joinedSlots = $slot; + $first = false; + } else { + $joinedSlots .= ',' . $slot; + } + } + if (empty($joinedSlots)) { + $prepared->execute(array($poll_id, $choice->getName())); + } else { + $prepared->execute(array($poll_id, $choice->getName().'@'.$joinedSlots)); } } From 3743ad55f1c13ae697d1f5c8128adfd1fdcf828d Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 7 Dec 2014 23:12:08 +0100 Subject: [PATCH 007/151] Make add vote working --- app/classes/Framadate/FramaDB.php | 48 +++++++++++++- app/classes/Framadate/Utils.php | 26 -------- studs.php | 104 +++++++++++++----------------- 3 files changed, 90 insertions(+), 88 deletions(-) diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 23a80d5..1758c6e 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -37,11 +37,53 @@ class FramaDB function query($sql) { return $this->pdo->query($sql); } - - function allComments($poll_id) { - $prepared = $this->prepare('SELECT * FROM comments WHERE id_sondage=? ORDER BY id_comment'); + + function findPollById($poll_id) + { + + // Open database + if (preg_match(';^[\w\d]{16}$;i', $poll_id)) { + $prepared = $this->prepare('SELECT * FROM sondage WHERE sondage.poll_id = ?'); + + $prepared->execute([$poll_id]); + $poll = $prepared->fetch(); + $prepared->closeCursor(); + + return $poll; + } + + return null; + } + + function allCommentsByPollId($poll_id) { + $prepared = $this->prepare('SELECT * FROM comments WHERE id_sondage = ? ORDER BY id_comment'); $prepared->execute(array($poll_id)); return $prepared->fetchAll(); } + function allUsersByPollId($poll_id) { + $prepared = $this->prepare('SELECT * FROM user_studs WHERE id_sondage = ? ORDER BY id_users'); + $prepared->execute(array($poll_id)); + return $prepared->fetchAll(); + } + + function allSujetsByPollId($poll_id) { + $prepared = $this->prepare('SELECT * FROM sujet_studs WHERE id_sondage = ? ORDER BY sujet'); + $prepared->execute(array($poll_id)); + return $prepared->fetchAll(); + } + + function insertVote($name, $poll_id, $choice) { + $prepared = $this->prepare('INSERT INTO user_studs (nom,id_sondage,reponses) VALUES (?,?,?)'); + $prepared->execute([$name, $poll_id, $choice]); + + $newVote = new \stdClass(); + $newVote->id_sondage = $poll_id; + $newVote->id_users = $this->pdo->lastInsertId(); + $newVote->nom = $name; + $newVote->reponse = $choice; + + return $newVote; + } + } diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index 78da6e3..9534979 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -30,32 +30,6 @@ class Utils return $scheme . '://' . str_replace('/admin','',str_replace('//','/',str_replace('///','/',$server_name))); } - public static function get_sondage_from_id($id) - { - global $connect; - - // Open database - if (preg_match(';^[\w\d]{16}$;i', $id)) { - $sql = 'SELECT sondage.*,sujet_studs.sujet FROM sondage - LEFT OUTER JOIN sujet_studs ON sondage.id_sondage = sujet_studs.id_sondage - WHERE sondage.id_sondage = ' . $connect->Param('id_sondage'); - - $sql = $connect->Prepare($sql); - $sondage = $connect->Execute($sql, [$id]); - - if ($sondage === false) { - return false; - } - - $psondage = $sondage->FetchObject(false); - $psondage->date_fin = strtotime($psondage->date_fin); - - return $psondage; - } - - return false; - } - public static function is_error($cerr) { global $err; diff --git a/studs.php b/studs.php index 6ec461a..bfd06bd 100644 --- a/studs.php +++ b/studs.php @@ -33,22 +33,25 @@ include_once __DIR__ . '/app/inc/init.php'; $numsondage = false; //On récupère le numéro de sondage par le lien web. -if(Utils::issetAndNoEmpty('sondage', $_GET) === true) { +if(!empty($_GET['sondage'])) { $numsondage = $_GET["sondage"]; $_SESSION["numsondage"] = $numsondage; } -if(Utils::issetAndNoEmpty('sondage') === true) { +if(!empty($_POST['sondage'])) { $numsondage = $_POST["sondage"]; $_SESSION["numsondage"] = $numsondage; -} elseif(Utils::issetAndNoEmpty('sondage', $_COOKIE) === true) { +} elseif(!empty($_COOKIE['sondage'])) { $numsondage = $_COOKIE["sondage"]; -} elseif(Utils::issetAndNoEmpty('numsondage', $_SESSION) === true) { +} elseif(!empty($_SESSION['sondage'])) { $numsondage = $_SESSION["numsondage"]; } -$dsondage = ($numsondage != false) ? Utils::get_sondage_from_id($numsondage) : false; -if (!$dsondage || $dsondage->id_sondage == ''){ +$dsondage = $connect->findPollById($numsondage); +if ($dsondage){ + $sujets = $connect->allSujetsByPollId($numsondage); + $users = $connect->allUsersByPollId($numsondage); +} else { Utils::print_header( _("Error!")); bandeau_titre(_("Error!")); @@ -65,7 +68,7 @@ if (!$dsondage || $dsondage->id_sondage == ''){ } //output a CSV and die() -if(Utils::issetAndNoEmpty('export', $_GET) && $dsondage !== false) { +if(!empty($_GET['export']) && $dsondage) { if($_GET['export'] == 'csv') { require_once('exportcsv.php'); } @@ -125,14 +128,12 @@ if(isset($_POST['ajoutcomment'])) { // Action quand on clique le bouton participer -$sql = 'SELECT * FROM user_studs WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_users'; -$sql = $connect->Prepare($sql); -$user_studs = $connect->Execute($sql, array($numsondage)); +$user_studs = $connect->allUsersByPollId($numsondage); -$nbcolonnes = substr_count($dsondage->sujet, ',') + 1; +$nbcolonnes = count($sujets); if (!Utils::is_error(NO_POLL) && (isset($_POST["boutonp"]))) { //Si le nom est bien entré - if (Utils::issetAndNoEmpty('nom') === false) { + if (empty($_POST['nom'])) { $err |= NAME_EMPTY; } @@ -154,7 +155,7 @@ if (!Utils::is_error(NO_POLL) && (isset($_POST["boutonp"]))) { // protection contre les XSS : htmlentities $nom = htmlentities($nom, ENT_QUOTES, 'UTF-8'); - while($user = $user_studs->FetchNextObject(false)) { + foreach ($users as $user) { if ($nom == $user->nom) { $err |= NAME_TAKEN; } @@ -163,20 +164,15 @@ if (!Utils::is_error(NO_POLL) && (isset($_POST["boutonp"]))) { // Ecriture des choix de l'utilisateur dans la base if (!Utils::is_error(NAME_TAKEN) && !Utils::is_error(NAME_EMPTY)) { - $sql = 'INSERT INTO user_studs (nom,id_sondage,reponses) VALUES ('. - $connect->Param('nom').', '. - $connect->Param('numsondage').', '. - $connect->Param('nouveauchoix').')'; - $sql = $connect->Prepare($sql); + // Todo : Il faudrait lever une erreur en cas d'erreur d'insertion + $newVote = $connect->insertVote($nom, $numsondage, $nouveauchoix); + $user_studs[] = $newVote; - // Todo : Il faudrait lever une erreur en cas d'erreur d'insertion - $connect->Execute($sql, array($nom, $numsondage, $nouveauchoix)); - - if ($dsondage->mailsonde || /* compatibility for non boolean DB */ $dsondage->mailsonde=="yes" || $dsondage->mailsonde=="true") { + if ($dsondage->receiveNewVotes || /* compatibility for non boolean DB */ $dsondage->receiveNewVotes==="yes" || $dsondage->receiveNewVotes==="true") { if($config['use_smtp']==true){ - Utils::sendEmail( "$dsondage->mail_admin", - "[".NOMAPPLICATION."] "._("Poll's participation")." : ".html_entity_decode($dsondage->titre, ENT_QUOTES, 'UTF-8')."", - html_entity_decode("\"$nom\" ", ENT_QUOTES, 'UTF-8'). + Utils::sendEmail( $dsondage->admin_mail, + "[".NOMAPPLICATION."] "._("Poll's participation")." : ".html_entity_decode($dsondage->title, ENT_QUOTES, 'UTF-8') . ' ', + html_entity_decode($nom, ENT_QUOTES, 'UTF-8'). ' ' . _("has filled a line.\nYou can find your poll at the link") . " :\n\n". Utils::getUrlSondage($numsondage) . " \n\n" . _("Thanks for your confidence.") . "\n". NOMAPPLICATION ); @@ -186,10 +182,11 @@ if (!Utils::is_error(NO_POLL) && (isset($_POST["boutonp"]))) { } else { $err |= NAME_EMPTY; } + } if($err != 0) { - Utils::print_header(_("Error!").' - '.$dsondage->titre); + Utils::print_header(_("Error!").' - '.$dsondage->title); bandeau_titre(_("Error!")); echo '
    '."\n"; @@ -210,11 +207,11 @@ if($err != 0) { echo '
'; } else { - Utils::print_header(_('Poll').' - '.$dsondage->titre); - bandeau_titre(_('Poll').' - '.$dsondage->titre); + Utils::print_header(_('Poll').' - '.$dsondage->title); + bandeau_titre(_('Poll').' - '.$dsondage->title); } -$title=stripslashes(str_replace("\\","",$dsondage->titre)); +$title=stripslashes(str_replace("\\","",$dsondage->title)); echo '
@@ -232,18 +229,18 @@ echo '

'. _("Initiator of the poll") .'

-

'.stripslashes($dsondage->nom_admin).'

+

'.stripslashes($dsondage->admin_name).'

'."\n"; //affichage de la description du sondage -if ($dsondage->commentaires) { - $commentaires = $dsondage->commentaires; - $commentaires=nl2br(str_replace("\\","",$commentaires)); +if ($dsondage->comment) { + $commentaires = $dsondage->comment; + $commentaires=nl2br(str_replace("\\","",$comment)); echo '

'._("Description") .'


@@ -255,7 +252,7 @@ echo '
'."\n"; // .jumbotron //On récupere les données et les sujets du sondage -$nblignes = $user_studs->RecordCount(); +$nblignes = count($users); //on teste pour voir si une ligne doit etre modifiée $testmodifier = false; @@ -295,21 +292,13 @@ if ($testmodifier) { $connect->Execute($sql, array($nouveauchoix, $data->nom, $data->id_users)); if ($dsondage->mailsonde=="yes") { - Utils::sendEmail( "$dsondage->mail_admin", "[".NOMAPPLICATION."] " . _("Poll's participation") . " : ".html_entity_decode($dsondage->titre, ENT_QUOTES, 'UTF-8'), "\"".html_entity_decode($data->nom, ENT_QUOTES, 'UTF-8')."\""."" . _("has filled a line.\nYou can find your poll at the link") . " :\n\n" . Utils::getUrlSondage($numsondage) . " \n\n" . _("Thanks for your confidence.") . "\n".NOMAPPLICATION ); + Utils::sendEmail( "$dsondage->mail_admin", "[".NOMAPPLICATION."] " . _("Poll's participation") . " : ".html_entity_decode($dsondage->title, ENT_QUOTES, 'UTF-8'), "\"".html_entity_decode($data->nom, ENT_QUOTES, 'UTF-8')."\""."" . _("has filled a line.\nYou can find your poll at the link") . " :\n\n" . Utils::getUrlSondage($numsondage) . " \n\n" . _("Thanks for your confidence.") . "\n".NOMAPPLICATION ); } } $compteur++; } } -//recuperation des utilisateurs du sondage -$sql = 'SELECT * FROM user_studs WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_users'; -$sql = $connect->Prepare($sql); -$user_studs = $connect->Execute($sql, array($numsondage)); - -//reformatage des données des sujets du sondage -$toutsujet = explode(",",$dsondage->sujet); - // Table headers $thead = ''; @@ -385,18 +374,17 @@ if ($dsondage->format=="D"||$dsondage->format=="D+"||$dsondage->format=="D-") { // Subjects poll } else { - $toutsujet=str_replace("@","
",$toutsujet); $tr_subjects = ''; - for ($i = 0; isset($toutsujet[$i]); $i++) { + foreach ($sujets as $i=>$sujet) { $td_headers[$i]='';$radio_title[$i]=''; // init before concatenate // Subjects - preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$toutsujet[$i],$md_a_img); // Markdown [![alt](src)](href) - preg_match_all('/!\[(.*?)\]\((.*?)\)/',$toutsujet[$i],$md_img); // Markdown ![alt](src) - preg_match_all('/\[(.*?)\]\((.*?)\)/',$toutsujet[$i],$md_a); // Markdown [text](href) + preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$sujet->sujet,$md_a_img); // Markdown [![alt](src)](href) + preg_match_all('/!\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_img); // Markdown ![alt](src) + preg_match_all('/\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_a); // Markdown [text](href) if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) $th_subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); @@ -414,7 +402,7 @@ if ($dsondage->format=="D"||$dsondage->format=="D+"||$dsondage->format=="D-") { } else { // text only - $th_subject_text = stripslashes($toutsujet[$i]); + $th_subject_text = stripslashes($sujet->sujet); $th_subject_html = $th_subject_text; } @@ -431,7 +419,7 @@ if ($dsondage->format=="D"||$dsondage->format=="D+"||$dsondage->format=="D-") { // Print headers echo ' -
+ '; if ($dsondage->format=="A-" || $dsondage->format=="D-") { @@ -475,12 +463,12 @@ $user_mod = false; $somme[] = 0; $compteur = 0; -while ($data = $user_studs->FetchNextObject(false)) { +foreach ($users as $user) { - $ensemblereponses = $data->reponses; + $ensemblereponses = $user->reponses; //affichage du nom - $nombase=str_replace("°","'",$data->nom); + $nombase=str_replace("°","'",$user->nom); echo ' '.stripslashes($nombase).''."\n"; @@ -666,11 +654,9 @@ echo '
'; // Comments -$sql = 'select * from comments where id_sondage='.$connect->Param('numsondage').' order by id_comment'; -$sql = $connect->Prepare($sql); -$comment_user=$connect->Execute($sql, array($numsondage)); +$comments = $connect->allCommentsByPollId($numsondage); -if ($comment_user->RecordCount() != 0) { +if (count($comments) != 0) { echo '

' . _("Comments of polled people") . '

'."\n"; while($dcomment = $comment_user->FetchNextObject(false)) { From fcaea63b84fee381723311a85b19f4907f8006ba Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Fri, 12 Dec 2014 13:43:43 +0100 Subject: [PATCH 008/151] A big part of refactoring * Use Smarty to split View and Controller on studs page (work in progress) * Add field "active" to Poll * And some other stuff... --- .gitignore | 4 + adminstuds.php | 131 +++--- app/classes/Framadate/Form.php | 3 +- app/classes/Framadate/FramaDB.php | 10 +- app/classes/Framadate/Utils.php | 10 +- app/inc/init.php | 28 +- app/inc/studs.inc.php | 10 + choix_date.php | 24 +- composer.json | 2 +- creation_sondage.php | 39 +- install.mysql.sql | 1 + old_studs.php | 706 ++++++++++++++++++++++++++++++ studs.php | 703 ++--------------------------- tpl/footer.tpl | 4 + tpl/head.tpl | 29 ++ tpl/header.tpl | 21 + tpl/studs.tpl | 163 +++++++ 17 files changed, 1122 insertions(+), 766 deletions(-) create mode 100644 app/inc/studs.inc.php create mode 100644 old_studs.php create mode 100644 tpl/footer.tpl create mode 100644 tpl/head.tpl create mode 100644 tpl/header.tpl create mode 100644 tpl/studs.tpl diff --git a/.gitignore b/.gitignore index f6e467c..90c4c5b 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,7 @@ framanav nav app/inc/constants.php vendor +.settings/ +.project +cache/ +tpl_c/ diff --git a/adminstuds.php b/adminstuds.php index daee4b7..53a0122 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -29,10 +29,6 @@ if (file_exists('bandeaux_local.php')) { include_once('bandeaux.php'); } -// Initialisation des variables -$numsondageadmin = false; -$sondage = false; - // recuperation du numero de sondage admin (24 car.) dans l'URL if (!empty($_GET['sondage']) && is_string($_GET['sondage']) && strlen($_GET['sondage']) === 24) { $admin_poll_id = $_GET["sondage"]; @@ -45,7 +41,7 @@ if (preg_match(";[\w\d]{24};i", $admin_poll_id)) { $prepared->execute(array($admin_poll_id)); $poll = $prepared->fetch(); $prepared->closeCursor(); - + $prepared = $connect->prepare('SELECT * FROM sujet_studs WHERE id_sondage = ?'); $prepared->execute(array($poll_id)); $sujets = $prepared->fetchAll(); @@ -79,14 +75,14 @@ $smtp_allowed = $config['use_smtp']; function send_mail_admin() { global $email_admin; global $poll_title; - global $numsondageadmin; + global $admin_poll_id; global $smtp_allowed; if($smtp_allowed==true){ if(!isset($_SESSION['mail_admin_sent'])) { Utils::sendEmail( $email_admin, _("[ADMINISTRATOR] New settings for your poll") . ' ' . stripslashes( $poll_title ), _("You have changed the settings of your poll. \nYou can modify this poll with this link") . - " :\n\n" . Utils::getUrlSondage($numsondageadmin, true) . "\n\n" . + " :\n\n" . Utils::getUrlSondage($admin_poll_id, true) . "\n\n" . _("Thanks for your confidence.") . "\n" . NOMAPPLICATION ); $_SESSION["mail_admin_sent"]=true; @@ -106,7 +102,7 @@ if (isset($_POST["boutonnouveautitre"])) { $sql = $connect->Prepare($sql); //Email sent to the admin - if ($connect->Execute($sql, array($nouveautitre, $numsondage))) { + if ($connect->Execute($sql, array($nouveautitre, $poll_id))) { send_mail_admin(); } } @@ -124,7 +120,7 @@ if (isset($_POST['boutonnouveauxcommentaires'])) { $prepared->execute(array($commentaires, $poll_id)); //Email sent to the admin - if ($connect->Execute($sql, array($commentaires, $numsondage))) { + if ($connect->Execute($sql, array($commentaires, $poll_id))) { send_mail_admin(); } } @@ -176,7 +172,7 @@ if (isset($_POST["btn_poll_rules"])) { // $dsondage= $sondage->FetchObject(false); if (isset($_POST['ajoutsujet'])) { - Utils::print_header( _('Add a column') .' - ' . stripslashes( $poll->title)); + Utils::print_header( _('Add a column') .' - ' . stripslashes($poll->title)); bandeau_titre(_('Make your polls')); @@ -185,10 +181,10 @@ if (isset($_POST['ajoutsujet'])) { echo '
- +

' . _("Column's adding") . '

'."\n"; - if (substr($dsondage->format, 0, 1)=="A"){ + if ($poll->format == "A"){ echo '
@@ -197,7 +193,7 @@ if (isset($_POST['ajoutsujet'])) {
'."\n"; } else { - //ajout d'une date avec creneau horaire + // ajout d'une date avec creneau horaire echo '

'. _("You can add a new scheduling date to your poll.").'
'._("If you just want to add a new hour to an existant date, put the same date and choose a new hour.") .'

@@ -233,12 +229,12 @@ if (isset($_POST['ajoutsujet'])) { } if (isset($_POST["suppressionsondage"])) { - Utils::print_header( _("Confirm removal of your poll") .' - ' . stripslashes( $dsondage->titre )); + Utils::print_header( _("Confirm removal of your poll") .' - ' . stripslashes( $dsondage->title )); bandeau_titre(_("Confirm removal of your poll")); echo ' - +

' . _("Confirm removal of your poll") . '

@@ -255,14 +251,14 @@ if (isset($_POST["suppressionsondage"])) { if (isset($_POST['removecomments'])) { $sql = 'DELETE FROM comments WHERE id_sondage='.$connect->Param('numsondage'); $sql = $connect->Prepare($sql); - $cleaning = $connect->Execute($sql, array($numsondage)); + $cleaning = $connect->Execute($sql, array($poll_id)); } // Remove all the votes if (isset($_POST["removevotes"])) { $sql = 'DELETE FROM user_studs WHERE id_sondage='.$connect->Param('numsondage'); $sql = $connect->Prepare($sql); - $cleaning = $connect->Execute($sql, array($numsondage)); + $cleaning = $connect->Execute($sql, array($poll_id)); } //action si bouton confirmation de suppression est activé @@ -270,7 +266,7 @@ if (isset($_POST["confirmesuppression"])) { $nbuser=$user_studs->RecordCount(); $date=date('H:i:s d/m/Y:'); - if (Utils::remove_sondage($connect, $numsondage)) { + if (Utils::remove_sondage($connect, $poll_id)) { // on ecrit dans le fichier de logs la suppression du sondage error_log($date . " SUPPRESSION: $dsondage->id_sondage\t$dsondage->format\t$dsondage->nom_admin\t$dsondage->mail_admin\n", 3, 'admin/logs_studs.txt'); @@ -313,7 +309,7 @@ if (isset($_POST['ajoutcomment'])) { $comment_doublon = false; $req = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; $sql = $connect->Prepare($req); - $comment_user_doublon = $connect->Execute($sql, array($numsondage)); + $comment_user_doublon = $connect->Execute($sql, array($poll_id)); if ($comment_user_doublon->RecordCount() != 0) { while ( $dcomment_user_doublon=$comment_user_doublon->FetchNextObject(false)) { if($dcomment_user_doublon->comment == $comment && $dcomment_user_doublon->usercomment == $comment_user) { @@ -329,7 +325,7 @@ if (isset($_POST['ajoutcomment'])) { $connect->Param('comment_user').')'; $sql = $connect->Prepare($req); - $comments = $connect->Execute($sql, array($numsondage, $comment, $comment_user)); + $comments = $connect->Execute($sql, array($poll_id, $comment, $comment_user)); if ($comments === false) { $err |= COMMENT_INSERT_FAILED; } @@ -345,7 +341,7 @@ $nblignes = count($users); //action si le bouton participer est cliqué if (isset($_POST["boutonp"])) { //si on a un nom dans la case texte - if (Utils::issetAndNoEmpty('nom')){ + if (!empty($_POST['nom'])){ $nouveauchoix = ''; $erreur_prenom = false; @@ -376,14 +372,14 @@ if (isset($_POST["boutonp"])) { $connect->Param('nouveauchoix').')'; $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($nom, $numsondage, $nouveauchoix)); + $connect->Execute($sql, array($nom, $poll_id, $nouveauchoix)); } } } //action quand on ajoute une colonne au format AUTRE -if (isset($_POST["ajoutercolonne"]) && Utils::issetAndNoEmpty('nouvellecolonne') && (substr($dsondage->format, 0, 1) == "A" )) { +if (isset($_POST["ajoutercolonne"]) && !empty($_POST['nouvellecolonne']) && $poll->format == "A") { $nouveauxsujets=$dsujet->sujet; //on rajoute la valeur a la fin de tous les sujets deja entrés @@ -394,24 +390,32 @@ if (isset($_POST["ajoutercolonne"]) && Utils::issetAndNoEmpty('nouvellecolonne') //mise a jour avec les nouveaux sujets dans la base $sql = 'UPDATE sujet_studs SET sujet = '.$connect->Param('nouveauxsujets').' WHERE id_sondage = '.$connect->Param('numsondage'); $sql = $connect->Prepare($sql); - if ($connect->Execute($sql, array($nouveauxsujets, $numsondage))) { + if ($connect->Execute($sql, array($nouveauxsujets, $poll_id))) { send_mail_admin(); } } -//action quand on ajoute une colonne au format DATE -if (isset($_POST["ajoutercolonne"]) && (substr($dsondage->format, 0, 1) == "D")) { - $nouveauxsujets=$dsujet->sujet; +// [begin] action quand on ajoute une colonne au format DATE +if (isset($_POST['ajoutercolonne']) && $dsondage->format == 'D') { - if (isset($_POST["newdate"]) && $_POST["newdate"] != "vide") { - $nouvelledate=mktime(0, 0, 0, substr($_POST["newdate"],3,2), substr($_POST["newdate"],0,2), substr($_POST["newdate"],6,4)); + if (!empty($_POST["newdate"])) { + $new_choice = mktime(0, 0, 0, substr($_POST["newdate"],3,2), substr($_POST["newdate"],0,2), substr($_POST["newdate"],6,4)); - if (isset($_POST["newhour"]) && $_POST["newhour"]!="vide"){ - $nouvelledate.="@"; - $nouvelledate.=$_POST["newhour"]; + if (!empty($_POST["newhour"])){ + $new_choice .= '@' . $_POST["newhour"]; } + + + + + // TODO OPZ Delete the code below + // TODO OPZ Insert new choice + // TODO OPZ Update users votes (add "0" in the right column^^) + + + //on rajoute la valeur dans les valeurs $datesbase = explode(",",$dsujet->sujet); $taillebase = sizeof($datesbase); @@ -444,13 +448,13 @@ if (isset($_POST["ajoutercolonne"]) && (substr($dsondage->format, 0, 1) == "D")) //if (isset($erreur_ajout_date) && !$erreur_ajout_date){ $sql = 'UPDATE sujet_studs SET sujet = '.$connect->Param('dateinsertion').' WHERE id_sondage = '.$connect->Param('numsondage'); $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($dateinsertion, $numsondage)); + $connect->Execute($sql, array($dateinsertion, $poll_id)); if ($nouvelledate > strtotime($dsondage->date_fin)) { $date_fin=$nouvelledate+200000; $sql = 'UPDATE sondage SET date_fin = '.$connect->Param('date_fin').' WHERE id_sondage = '.$connect->Param('numsondage'); $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($date_fin, $numsondage)); + $connect->Execute($sql, array($date_fin, $poll_id)); } //} @@ -486,6 +490,7 @@ if (isset($_POST["ajoutercolonne"]) && (substr($dsondage->format, 0, 1) == "D")) $erreur_ajout_date="yes"; } } +// [end] action quand on ajoute une colonne au format DATE //suppression de ligne dans la base @@ -508,7 +513,7 @@ for ($i = 0; $i < $nblignes; $i++) { // TODO OPZ Revoir toute cette partie suppression d'un commentaire utilisateur /*$sql = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; $sql = $connect->Prepare($sql); -$comment_user = $connect->Execute($sql, array($numsondage)); +$comment_user = $connect->Execute($sql, array($poll_id)); $i = 0; while ($dcomment = $comment_user->FetchNextObject(false)) { if (isset($_POST['suppressioncomment'.$i])) { @@ -571,17 +576,17 @@ if ($testmodifier) { //suppression de colonnes dans la base for ($i = 0; $i < $nbcolonnes; $i++) { if ((isset($_POST["effacecolonne$i"])) && $nbcolonnes > 1){ - $toutsujet = explode(",",$dsujet->sujet); + $sujets = explode(",",$dsujet->sujet); //sort($toutsujet, SORT_NUMERIC); $j = 0; $nouveauxsujets = ''; //parcours de tous les sujets actuels - while (isset($toutsujet[$j])) { + while (isset($sujets[$j])) { //si le sujet n'est pas celui qui a été effacé alors on concatene if ($i != $j) { $nouveauxsujets .= ','; - $nouveauxsujets .= $toutsujet[$j]; + $nouveauxsujets .= $sujets[$j]; } $j++; @@ -617,7 +622,7 @@ for ($i = 0; $i < $nbcolonnes; $i++) { //mise a jour des sujets dans la base $sql = 'UPDATE sujet_studs SET sujet = '.$connect->Param('nouveauxsujets').' WHERE id_sondage = '.$connect->Param('numsondage'); $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($nouveauxsujets, $numsondage)); + $connect->Execute($sql, array($nouveauxsujets, $poll_id)); } } @@ -625,16 +630,16 @@ for ($i = 0; $i < $nbcolonnes; $i++) { // TODO OPZ Déjà fait en début de fichier recuperation des donnes de la base /*$sql = 'SELECT * FROM sondage WHERE id_sondage_admin = '.$connect->Param('numsondageadmin'); $sql = $connect->Prepare($sql); -$sondage = $connect->Execute($sql, array($numsondageadmin)); +$sondage = $connect->Execute($sql, array($admin_poll_id)); if ($sondage !== false) { $sql = 'SELECT * FROM sujet_studs WHERE id_sondage = '.$connect->Param('numsondage'); $sql = $connect->Prepare($sql); - $sujets = $connect->Execute($sql, array($numsondage)); + $sujets = $connect->Execute($sql, array($poll_id)); $sql = 'SELECT * FROM user_studs WHERE id_sondage = '.$connect->Param('numsondage').' order by id_users'; $sql = $connect->Prepare($sql); - $user_studs = $connect->Execute($sql, array($numsondage)); + $user_studs = $connect->Execute($sql, array($poll_id)); } else { Utils::print_header(_("Error!")); @@ -672,7 +677,7 @@ $description = (isset($_POST["nouveauxcommentaires"])) ? stripslashes(htmlentiti $email_admin = (isset($_POST["boutonnouvelleadresse"]) && !empty($_POST['nouvelleadresse'])) ? htmlentities(html_entity_decode($_POST['nouvelleadresse'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8') : stripslashes( $poll->admin_mail ); //Poll format (locked A-/D-, open A/D, editable A+/D+) -$poll_rules = (isset($_POST["poll_rules"]) && !empty($_POST['btn_poll_rules'])) ? $_POST["poll_rules"] : substr($poll->format, 1, 1); +$poll_rules = (isset($_POST["poll_rules"]) && !empty($_POST['btn_poll_rules'])) ? $_POST["poll_rules"] : substr($poll->format, 1, 1); // TODO OPZ Handle comment disabling $poll_rules_opt1 = '';$poll_rules_opt2 = '';$poll_rules_opt3 = ''; if($poll->editable) { $poll_rules_text = ' '. _("Votes are editable"); @@ -699,7 +704,7 @@ if ($errors!='') { } echo ' - +

@@ -770,7 +775,7 @@ echo '
@@ -802,15 +807,6 @@ echo '
'."\n"; // .jumbotron -// TODO OPZ : Pourquoi ? on recupere les données et les sujets du sondage -/*$dsujet=$sujets->FetchObject(false); -$dsondage=$sondage->FetchObject(false);*/ - -// TODO OPZ : Déjà présent sous la bonne forme : reformatage des données des sujets du sondage -/*$toutsujet=explode(",",$dsujet->sujet); -$toutsujet=str_replace("°","'",$toutsujet); -$nbcolonnes=substr_count($dsujet->sujet,',')+1;*/ - // Table headers $thead = ''; @@ -821,8 +817,8 @@ $border = array(); // bordure pour distinguer les mois $td_headers = array(); // for a11y, headers="M1 D4 H5" on each td $radio_title = array(); // date for -// Dates poll -if (substr($poll->format, 0, 1)=="D") { +// Display dates poll +if ($poll->format == "D") { $tr_months = ''; $tr_days = ''; @@ -831,23 +827,22 @@ if (substr($poll->format, 0, 1)=="D") { // Headers $colspan_month = 1; $colspan_day = 1; - - for ($i = 0; $i < count($sujets); $i++) { + + foreach ($sujets as $i=>$sujet) { // Current date - $current = $toutsujet[$i];//format date@hour. ex : 2020292820@10:00 - $horoCur = explode("@",$current); //horoCur[0] = date, horoCur[1] = hour - if (isset($toutsujet[$i+1])){ - $next = $toutsujet[$i+1]; - $horoNext = explode("@",$next); + $horoCur = explode('@', $sujet->sujet); //horoCur[0] = date, horoCur[1] = hour + if (isset($sujets[$i+1])){ + $next = $sujets[$i+1]->sujet; + $horoNext = explode('@', $next); } $border[$i] = false; - $radio_title[$i] = strftime($date_format['txt_short'],$horoCur[0]); + $radio_title[$i] = strftime($date_format['txt_short'], $horoCur[0]); // Months $td_headers[$i] = 'M'.($i+1-$colspan_month); - if (isset($toutsujet[$i+1]) && strftime("%B", $horoCur[0]) == strftime("%B", $horoNext[0]) && strftime("%Y", $horoCur[0]) == strftime("%Y", $horoNext[0])){ + if (isset($sujets[$i+1]) && strftime("%B", $horoCur[0]) == strftime("%B", $horoNext[0]) && strftime("%Y", $horoCur[0]) == strftime("%Y", $horoNext[0])){ $colspan_month++; } else { $border[$i] = true; @@ -858,7 +853,7 @@ if (substr($poll->format, 0, 1)=="D") { // Days $td_headers[$i] .= ' D'.($i+1-$colspan_day); - if (isset($toutsujet[$i+1]) && strftime($date_format['txt_day'],$horoCur[0])==strftime($date_format['txt_day'],$horoNext[0]) && strftime("%B",$horoCur[0])==strftime("%B",$horoNext[0])){ + if (isset($sujets[$i+1]) && strftime($date_format['txt_day'],$horoCur[0])==strftime($date_format['txt_day'],$horoNext[0]) && strftime("%B",$horoCur[0])==strftime("%B",$horoNext[0])){ $colspan_day++; } else { $rbd = ($border[$i]) ? ' rbd' : ''; @@ -877,7 +872,7 @@ if (substr($poll->format, 0, 1)=="D") { } // Remove col - $tr_add_remove_col .= (count($toutsujet) > 2 ) ? '' : ''; + $tr_add_remove_col .= (count($sujets) > 2 ) ? '' : ''; } @@ -943,7 +938,7 @@ if (substr($poll->format, 0, 1)=="D") { // Print headers echo ' -
+

' . _('As poll administrator, you can change all the lines of this poll with this button ').'' . _('Edit') . ', diff --git a/app/classes/Framadate/Form.php b/app/classes/Framadate/Form.php index 79d1c68..4674afa 100644 --- a/app/classes/Framadate/Form.php +++ b/app/classes/Framadate/Form.php @@ -16,7 +16,7 @@ class Form * Tells if users can modify their choices. */ public $editable; - + /** * If true, notify poll administrator when new vote is made. */ @@ -28,6 +28,7 @@ class Form private $choices; public function __construct(){ + $this->editable = true; $this->clearChoices(); } diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 1758c6e..97b618e 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -61,27 +61,27 @@ class FramaDB return $prepared->fetchAll(); } - function allUsersByPollId($poll_id) { + function allUserVotesByPollId($poll_id) { $prepared = $this->prepare('SELECT * FROM user_studs WHERE id_sondage = ? ORDER BY id_users'); $prepared->execute(array($poll_id)); return $prepared->fetchAll(); } - function allSujetsByPollId($poll_id) { + function allSlotsByPollId($poll_id) { $prepared = $this->prepare('SELECT * FROM sujet_studs WHERE id_sondage = ? ORDER BY sujet'); $prepared->execute(array($poll_id)); return $prepared->fetchAll(); } - function insertVote($name, $poll_id, $choice) { + function insertVote($name, $poll_id, $votes) { $prepared = $this->prepare('INSERT INTO user_studs (nom,id_sondage,reponses) VALUES (?,?,?)'); - $prepared->execute([$name, $poll_id, $choice]); + $prepared->execute([$name, $poll_id, $votes]); $newVote = new \stdClass(); $newVote->id_sondage = $poll_id; $newVote->id_users = $this->pdo->lastInsertId(); $newVote->nom = $name; - $newVote->reponse = $choice; + $newVote->reponse = $votes; return $newVote; } diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index 9534979..047e2e1 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -189,9 +189,9 @@ class Utils } } else { if ($admin === true) { - $url = str_replace('/admin', '', self::get_server_name()) . 'adminstuds.php?sondage=' . $id; + $url = str_replace('/admin', '', self::get_server_name()) . 'adminstuds.php?poll=' . $id; } else { - $url = str_replace('/admin', '', self::get_server_name()) . 'studs.php?sondage=' . $id; + $url = str_replace('/admin', '', self::get_server_name()) . 'studs.php?poll=' . $id; } } @@ -216,12 +216,12 @@ class Utils $prepared = $connect->prepare('DELETE FROM sondage WHERE poll_id = ?'); $prepared->execute(array($poll_id)); - + } public static function cleaningOldPolls($log_txt) { global $connect; - + $resultSet = $connect->query('SELECT poll_id, format, admin_name FROM sondage WHERE end_date < NOW() LIMIT 20'); $toClean = $resultSet->fetchAll(\PDO::FETCH_CLASS); @@ -233,7 +233,7 @@ class Utils } $connect->commit(); } - + public static function debug($object) { echo '

';
diff --git a/app/inc/init.php b/app/inc/init.php
index 4068df0..e3adbfe 100644
--- a/app/inc/init.php
+++ b/app/inc/init.php
@@ -20,18 +20,40 @@
 if (ini_get('date.timezone') == '') {
     date_default_timezone_set('Europe/Paris');
 }
+include_once __DIR__ . '/constants.php';
+include_once __DIR__ . '/i18n.php';
+include_once __DIR__ . '/studs.inc.php';
+
 // Autoloading of dependencies with Composer
 require_once __DIR__ . '/../../vendor/autoload.php';
 
-include_once __DIR__ . '/constants.php';
-include_once __DIR__ . '/i18n.php';
+// Smarty
+require_once __DIR__ . '/../../vendor/smarty/smarty/libs/Smarty.class.php';
+$smarty = new \Smarty();
+$smarty->template_dir = 'tpl/';
+$smarty->compile_dir = 'tpl_c/';
+$smarty->cache_dir = 'cache/';
+$smarty->caching = false;
+
+$smarty->assign('APPLICATION_NAME', NOMAPPLICATION);
+$smarty->assign('SERVER_URL', \Framadate\Utils::get_server_name());
+$smarty->assign('TITLE_IMAGE', IMAGE_TITRE);
+$smarty->assign('use_nav_js', file_exists($_SERVER['DOCUMENT_ROOT'] . '/nav/nav.js'));
+$smarty->assign('lang', $lang);
+$smarty->assign('langs', $ALLOWED_LANGUAGES);
+$smarty->assign('day_format', $date_format['txt_day']);
+
+function smarty_modifier_poll_url($poll_id, $admin=false){return \Framadate\Utils::getUrlSondage($poll_id, $admin);}
+//$smarty->registerPlugin('modifier', 'poll_url', 'sqqmarty_modifier_poll_url');
+// End- Smarty
+
 
 use Framadate\FramaDB;
 use Framadate\Form;
 use Framadate\Choice;
 use Framadate\Utils;
 
-if (session_id() == "") {
+if (session_id() == '') {
     session_start();
 }
 
diff --git a/app/inc/studs.inc.php b/app/inc/studs.inc.php
new file mode 100644
index 0000000..24f81a3
--- /dev/null
+++ b/app/inc/studs.inc.php
@@ -0,0 +1,10 @@
+sujet, ',')+1;
+    }
+    return $nb;
+}
\ No newline at end of file
diff --git a/choix_date.php b/choix_date.php
index 99f5a5b..5a4e06c 100644
--- a/choix_date.php
+++ b/choix_date.php
@@ -39,13 +39,13 @@ if (!isset($_SESSION['form']->titre) || !isset($_SESSION['form']->nom) || (($con
         

' . _("You haven't filled the first section of the poll creation.") . ' !

' . _("Back to the homepage of ") . ' ' . '' . NOMAPPLICATION . '.

'; - + bandeau_pied(); } else { // Step 4 : Data prepare before insert in DB - if (Utils::issetAndNoEmpty('confirmation')) { + if (!empty($_POST['confirmation'])) { // Define expiration date if (!empty($_POST['champdatefin'])) @@ -59,14 +59,14 @@ if (!isset($_SESSION['form']->titre) || !isset($_SESSION['form']->nom) || (($con $_SESSION['form']->champdatefin=$time; } } - } - + } + if(empty($_SESSION['form']->champdatefin)) { // By default, expiration date is 6 months after last day $_SESSION['form']->champdatefin=end($temp_results)+(86400 * $config['default_poll_duration']); } - + // Insert poll in database $admin_poll_id = ajouter_sondage( $_SESSION['form']->titre, @@ -79,27 +79,27 @@ if (!isset($_SESSION['form']->titre) || !isset($_SESSION['form']->nom) || (($con $_SESSION['form']->receiveNewVotes, $_SESSION['form']->getChoices() ); - + // Clean Form data in $_SESSION unset($_SESSION['form']); // Delete old polls Utils::cleaningOldPolls($connect, 'admin/logs_studs.txt'); - + // Redirect to poll administration header('Location:' . Utils::getUrlSondage($admin_poll_id, true)); exit; } else { - - if (Utils::issetAndNoEmpty('days')) { - + + if (!empty($_POST['days'])) { + // Clear previous choices $_SESSION['form']->clearChoices(); for ($i = 0; $i < count($_POST['days']); $i++) { $day = $_POST['days'][$i]; - + if (!empty($day)) { // Add choice to Form data $time = mktime(0, 0, 0, substr($_POST["days"][$i],3,2),substr($_POST["days"][$i],0,2),substr($_POST["days"][$i],6,4)); @@ -121,7 +121,7 @@ if (!isset($_SESSION['form']->titre) || !isset($_SESSION['form']->nom) || (($con $_SESSION['form']->formatsondage = 'D'; // Step 3/4 : Confirm poll creation - if (Utils::issetAndNoEmpty('choixheures') && !isset($_SESSION['form']->totalchoixjour)) { + if (!empty($_POST['choixheures']) && !isset($_SESSION['form']->totalchoixjour)) { Utils::print_header ( _("Removal date and confirmation (3 on 3)") ); bandeau_titre(_("Removal date and confirmation (3 on 3)")); diff --git a/composer.json b/composer.json index ab0c2e6..199030d 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "require": { - "adodb/adodb-php": "5.19" + "smarty/smarty": "3.1.21" }, "autoload": { diff --git a/creation_sondage.php b/creation_sondage.php index 4ca5c8f..6705af1 100644 --- a/creation_sondage.php +++ b/creation_sondage.php @@ -41,12 +41,12 @@ function random($car) function ajouter_sondage($title, $comment, $adminName, $adminMail, $format, $editable, $endDate, $receiveNewVotes, $choices) { global $connect; - global $config; - + global $config; + // Generate poll ids $poll_id = random(16); $admin_poll_id = $poll_id.random(8); - + // Insert poll + slots $connect->beginTransaction(); @@ -58,20 +58,33 @@ function ajouter_sondage($title, $comment, $adminName, $adminMail, $format, $edi $prepared = $connect->prepare('INSERT INTO sujet_studs (id_sondage, sujet) VALUES (?, ?)'); foreach ($choices as $choice) { + + // We prepared the slots (joined by comas) $joinedSlots = ''; + $first = true; foreach ($choice->getSlots() as $slot) { - if ($first) { - $joinedSlots = $slot; - $first = false; + + // We prepared the slots (joined by comas) + $joinedSlots = ''; + $first = true; + foreach ($choice->getSlots() as $slot) { + if ($first) { + $joinedSlots = $slot; + $first = false; + } else { + $joinedSlots .= ',' . $slot; + } + } + + // We execute the insertion + if (empty($joinedSlots)) { + $prepared->execute(array($poll_id, $choice->getName())); } else { - $joinedSlots .= ',' . $slot; + $prepared->execute(array($poll_id, $choice->getName().'@'.$joinedSlots)); } + } - if (empty($joinedSlots)) { - $prepared->execute(array($poll_id, $choice->getName())); - } else { - $prepared->execute(array($poll_id, $choice->getName().'@'.$joinedSlots)); - } + } $connect->commit(); @@ -94,7 +107,7 @@ function ajouter_sondage($title, $comment, $adminName, $adminMail, $format, $edi Utils::sendEmail( $adminMail, "[".NOMAPPLICATION."][" . _("For sending to the polled users") . "] " . _("Poll") . " : ".stripslashes(htmlspecialchars_decode($title,ENT_QUOTES)), $message, $_SESSION['adresse'] ); } } - + error_log(date('H:i:s d/m/Y:') . ' CREATION: '.$poll_id."\t".$format."\t".$adminName."\t".$adminMail."\n", 3, 'admin/logs_studs.txt'); return $admin_poll_id; diff --git a/install.mysql.sql b/install.mysql.sql index 3980fd7..3d47c64 100644 --- a/install.mysql.sql +++ b/install.mysql.sql @@ -34,6 +34,7 @@ CREATE TABLE IF NOT EXISTS `sondage` ( `format` varchar(1) DEFAULT NULL, `editable` tinyint(1) DEFAULT '0', `receiveNewVotes` tinyint(1) DEFAULT '0', + `active` tinyint(1) DEFAULT '1', `statut` int(11) NOT NULL DEFAULT '1' COMMENT '1 = actif ; 0 = inactif ; ', UNIQUE KEY `poll_id` (`poll_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/old_studs.php b/old_studs.php new file mode 100644 index 0000000..96f880f --- /dev/null +++ b/old_studs.php @@ -0,0 +1,706 @@ +findPollById($numsondage); +if ($dsondage){ + $sujets = $connect->allSujetsByPollId($numsondage); + $users = $connect->allUsersByPollId($numsondage); +} else { + Utils::print_header( _("Error!")); + + bandeau_titre(_("Error!")); + + echo ' +
+

' . _("This poll doesn't exist !") . '

+

' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

+
'."\n"; + + bandeau_pied(); + + die(); +} + +//output a CSV and die() +if(!empty($_GET['export']) && $dsondage) { + if($_GET['export'] == 'csv') { + require_once('exportcsv.php'); + } + + die(); +} + +// quand on ajoute un commentaire utilisateur +if(isset($_POST['ajoutcomment'])) { + if (isset($_SESSION['nom']) && Utils::issetAndNoEmpty('commentuser') === false) { + // Si le nom vient de la session, on le de-htmlentities + $comment_user = html_entity_decode($_SESSION['nom'], ENT_QUOTES, 'UTF-8'); + } elseif(Utils::issetAndNoEmpty('commentuser')) { + $comment_user = $_POST["commentuser"]; + } elseif(isset($_POST["commentuser"])) { + $err |= COMMENT_USER_EMPTY; + } else { + $comment_user = _('anonyme'); + } + + if(Utils::issetAndNoEmpty('comment') === false) { + $err |= COMMENT_EMPTY; + } + + if (isset($_POST["comment"]) && !Utils::is_error(COMMENT_EMPTY) && !Utils::is_error(NO_POLL) && !Utils::is_error(COMMENT_USER_EMPTY)) { + // protection contre les XSS : htmlentities + $comment = htmlentities($_POST['comment'], ENT_QUOTES, 'UTF-8'); + $comment_user = htmlentities($comment_user, ENT_QUOTES, 'UTF-8'); + + // Check for doublons + $comment_doublon = false; + $req = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; + $sql = $connect->Prepare($req); + $comment_user_doublon = $connect->Execute($sql, array($numsondage)); + if ($comment_user_doublon->RecordCount() != 0) { + while ( $dcomment_user_doublon=$comment_user_doublon->FetchNextObject(false)) { + if($dcomment_user_doublon->comment == $comment && $dcomment_user_doublon->usercomment == $comment_user) { + $comment_doublon = true; + }; + } + } + + if(!$comment_doublon) { + $req = 'INSERT INTO comments (id_sondage, comment, usercomment) VALUES ('. + $connect->Param('id_sondage').','. + $connect->Param('comment').','. + $connect->Param('comment_user').')'; + $sql = $connect->Prepare($req); + + $comments = $connect->Execute($sql, array($numsondage, $comment, $comment_user)); + if ($comments === false) { + $err |= COMMENT_INSERT_FAILED; + } + } + } +} + + +// Action quand on clique le bouton participer +$user_studs = $connect->allUsersByPollId($numsondage); + +$nbcolonnes = countStuds($sujets); +if (!Utils::is_error(NO_POLL) && (isset($_POST["boutonp"]))) { + //Si le nom est bien entré + if (empty($_POST['nom'])) { + $err |= NAME_EMPTY; + } + + if(!Utils::is_error(NAME_EMPTY) && (! ( USE_REMOTE_USER && isset($_SERVER['REMOTE_USER']) ) || $_POST["nom"] == $_SESSION["nom"])) { + $nouveauchoix = ''; + for ($i=0;$i<$nbcolonnes;$i++) { + // radio checked 1 = Yes, 2 = Ifneedbe, 0 = No + if (isset($_POST["choix$i"])) { + switch ($_POST["choix$i"]) { + case 1: $nouveauchoix .= "1";break; + case 2: $nouveauchoix .= "2";break; + default: $nouveauchoix .= "0";break; + } + } + } + + $nom=substr($_POST["nom"],0,64); + + // protection contre les XSS : htmlentities + $nom = htmlentities($nom, ENT_QUOTES, 'UTF-8'); + + foreach ($users as $user) { + if ($nom == $user->nom) { + $err |= NAME_TAKEN; + } + } + + // Ecriture des choix de l'utilisateur dans la base + if (!Utils::is_error(NAME_TAKEN) && !Utils::is_error(NAME_EMPTY)) { + + // Todo : Il faudrait lever une erreur en cas d'erreur d'insertion + $newVote = $connect->insertVote($nom, $numsondage, $nouveauchoix); + $user_studs[] = $newVote; + + if ($dsondage->receiveNewVotes || /* compatibility for non boolean DB */ $dsondage->receiveNewVotes==="yes" || $dsondage->receiveNewVotes==="true") { + if($config['use_smtp']==true){ + Utils::sendEmail( $dsondage->admin_mail, + "[".NOMAPPLICATION."] "._("Poll's participation")." : ".html_entity_decode($dsondage->title, ENT_QUOTES, 'UTF-8') . ' ', + html_entity_decode($nom, ENT_QUOTES, 'UTF-8'). ' ' . + _("has filled a line.\nYou can find your poll at the link") . " :\n\n". + Utils::getUrlSondage($numsondage) . " \n\n" . + _("Thanks for your confidence.") . "\n". NOMAPPLICATION ); + } + } + } + } else { + $err |= NAME_EMPTY; + } + +} + +if($err != 0) { + Utils::print_header(_("Error!").' - '.$dsondage->title); + bandeau_titre(_("Error!")); + + echo '
    '."\n"; + + if(Utils::is_error(NAME_EMPTY)) { + echo '
  • ' . _("Enter a name") . "
  • \n"; + } + if(Utils::is_error(NAME_TAKEN)) { + echo '
  • ' . _("The name you've chosen already exist in this poll!") . "
  • \n"; + } + if(Utils::is_error(COMMENT_EMPTY) || Utils::is_error(COMMENT_USER_EMPTY)) { + echo '
  • ' . _("Enter a name and a comment!") . "
  • \n"; + } + if(Utils::is_error(COMMENT_INSERT_FAILED) ) { + echo '
  • ' . _("Failed to insert the comment!") . "
  • \n"; + } + + echo '
'; + +} else { + Utils::print_header(_('Poll').' - '.$dsondage->title); + bandeau_titre(_('Poll').' - '.$dsondage->title); +} + +$title=stripslashes(str_replace("\\","",$dsondage->title)); +echo ' +
+
+
+

'.$title.'

+
+
+
+ + +
+
+
+
+
+
+

'. _("Initiator of the poll") .'

+

'.stripslashes($dsondage->admin_name).'

+
+ +
'."\n"; + +//affichage de la description du sondage +if ($dsondage->comment) { + $commentaires = $dsondage->comment; + $commentaires=nl2br(str_replace("\\","",$comment)); + echo ' +
+

'._("Description") .'


+

'. $commentaires .'

+
'; +} +echo ' +
+
'."\n"; // .jumbotron + +//On récupere les données et les sujets du sondage +$nblignes = count($users); + +//on teste pour voir si une ligne doit etre modifiée +$testmodifier = false; +$ligneamodifier = -1; +for ($i=0;$i<$nblignes;$i++) { + if (isset($_POST["modifierligne$i"])) { + $ligneamodifier = $i; + } + + //test pour voir si une ligne est a modifier + if (isset($_POST['validermodifier'.$i])) { + $modifier = $i; + $testmodifier = true; + } +} + +//si le test est valide alors on affiche des checkbox pour entrer de nouvelles valeurs +if ($testmodifier) { + $nouveauchoix = ''; + for ($i=0;$i<$nbcolonnes;$i++) { + // radio checked 1 = Yes, 2 = Ifneedbe, 0 = No + if (isset($_POST["choix$i"])) { + switch ($_POST["choix$i"]) { + case 1: $nouveauchoix .= "1";break; + case 2: $nouveauchoix .= "2";break; + default: $nouveauchoix .= "0";break; + } + } + } + + $compteur=0; + while ($data = $user_studs->FetchNextObject(false) ) { + //mise a jour des données de l'utilisateur dans la base SQL + if ($compteur == $modifier) { + $sql = 'UPDATE user_studs SET reponses='.$connect->Param('nouveauchoix').' WHERE nom='.$connect->Param('nom').' AND id_users='.$connect->Param('id_users'); + $sql = $connect->Prepare($sql); + $connect->Execute($sql, array($nouveauchoix, $data->nom, $data->id_users)); + + if ($dsondage->mailsonde=="yes") { + Utils::sendEmail( "$dsondage->mail_admin", "[".NOMAPPLICATION."] " . _("Poll's participation") . " : ".html_entity_decode($dsondage->title, ENT_QUOTES, 'UTF-8'), "\"".html_entity_decode($data->nom, ENT_QUOTES, 'UTF-8')."\""."" . _("has filled a line.\nYou can find your poll at the link") . " :\n\n" . Utils::getUrlSondage($numsondage) . " \n\n" . _("Thanks for your confidence.") . "\n".NOMAPPLICATION ); + } + } + $compteur++; + } +} + +// Table headers +$thead = ''; + +// Button in the first td to avoid remove col on "Return" keypress) +$border = array(); // bordure pour distinguer les mois +$td_headers = array(); // for a11y, headers="M1 D4 H5" on each td +$radio_title = array(); // date for + +// Dates poll +if ($dsondage->format === 'D') { + + $tr_months = ''; + $tr_days = ''; + $tr_hours = ''; + + // Headers + $colspan_month = 0; + + $col_number = 0; + foreach ($sujets as $i=>$sujet) { + + // Current date + $horoCur = explode("@", $sujet->sujet); //horoCur[0] = date, horoCur[1] = hour,hour,hour + if (isset($sujets[$i+1])){ + $next = $sujets[$i+1]; + $horoNext = explode("@", $next->sujet); + } else { + unset($next); + } + + + $border[$col_number] = false; + $current_radio_title = strftime($date_format['txt_short'], $horoCur[0]); + + // Months + $current_td_headers = 'M'.($i+1-$colspan_month); + + $currentYearMonth = strftime("%B%Y", $horoCur[0]); + $nextYearMonth = strftime("%B%Y", $horoNext[0]); + if (isset($next) && $currentYearMonth == $nextYearMonth) { + $colspan_month += substr_count($horoCur[1], ',') + 1; + } else { + $border[$i] = true; + $colspan_month += substr_count($horoCur[1], ',') + 1; + $tr_months .= ''.strftime("%B",$horoCur[0]).' '.strftime("%Y", $horoCur[0]).''; + $colspan_month=0; + } + + // Days + + $colspan_day = substr_count($horoCur[1], ',') + 1; + $current_td_headers .= ' D'.($col_number+1-$colspan_day); + $tr_days .= ''.strftime($date_format['txt_day'],$horoCur[0]).''; + + // Hours + if (!empty($horoCur[1])) { + $hours = explode(',', $horoCur[1]); + foreach($hours as $hour) { + if (end($hours) == $hour) { + $border[$col_number] = false; + } else { + $border[$col_number] = true; + } + + $rbd = ($border[$col_number]) ? ' rbd' : ''; + + $tr_hours .= ''.$hour.''; + $radio_title[$col_number] = $current_radio_title . ' - '.$hour; + $td_headers[$col_number] = $current_td_headers . ' H'.$col_number; + $col_number++; + } + } else { + $tr_hours .= ''; + } + } + + $border[count($border)-1] = false; // suppression de la bordure droite du dernier mois + + $tr_months .= ''; + $tr_days .= ''; + $tr_hours .= ''; + + $thead = "\n".$tr_months."\n".$tr_days."\n".$tr_hours."\n"; + +// Subjects poll +} else { + + $tr_subjects = ''; + + foreach ($sujets as $i=>$sujet) { + + $td_headers[$i]='';$radio_title[$i]=''; // init before concatenate + + // Subjects + preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$sujet->sujet,$md_a_img); // Markdown [![alt](src)](href) + preg_match_all('/!\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_img); // Markdown ![alt](src) + preg_match_all('/\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_a); // Markdown [text](href) + if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) + + $th_subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); + $th_subject_html = ''.$th_subject_text.''; + + } elseif (isset($md_img[2][0]) && $md_img[2][0]!='') { // ![alt](src) + + $th_subject_text = (isset($md_img[1][0]) && $md_img[1][0]!='') ? stripslashes($md_img[1][0]) : _("Choice") .' '.($i+1); + $th_subject_html = ''.$th_subject_text.''; + + } elseif (isset($md_a[2][0]) && $md_a[2][0]!='') { // [text](href) + + $th_subject_text = (isset($md_a[1][0]) && $md_a[1][0]!='') ? stripslashes($md_a[1][0]) : _("Choice") .' '.($i+1); + $th_subject_html = ''.$th_subject_text.''; + + } else { // text only + + $th_subject_text = stripslashes($sujet->sujet); + $th_subject_html = $th_subject_text; + + } + $tr_subjects .= ''.$th_subject_html.''; + + $border[$i] = false; + $td_headers[$i] .= 'S'.$i; + $radio_title[$i] .= $th_subject_text; + + } + + $thead = $tr_subjects.''; +} + +// Print headers +echo ' + + +'; +if ($dsondage->format=="A-" || $dsondage->format=="D-") { + echo ' +
+

' . _("The administrator locked this poll, votes and comments are frozen, it's not possible to participate anymore.") . '

+ +
'; +} else { + echo ' +
+

' . _("If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line.") . '

+ +
'; +} +echo' + + +

'._('Votes of the poll ').'

+
+ + + '. $thead . ' + '; + +// Print poll results + +//Usager pré-authentifié dans la liste? +$user_mod = false; + +//affichage des resultats actuels +$somme[] = 0; +$compteur = 0; + +foreach ($users as $user) { + + $ensemblereponses = $user->reponses; + + //affichage du nom + $nombase=str_replace("°","'",$user->nom); + echo ' +'."\n"; + + // ligne d'un usager pré-authentifié + $mod_ok = !( USE_REMOTE_USER && isset($_SERVER['REMOTE_USER']) ) || ($nombase == $_SESSION['nom']); + $user_mod |= $mod_ok; + + // pour chaque colonne + for ($k=0; $k < $nbcolonnes; $k++) { + // on remplace les choix de l'utilisateur par une ligne de checkbox pour recuperer de nouvelles valeurs + if ($compteur == $ligneamodifier) { + + $car = substr($ensemblereponses, $k , 1); + + // variable pour afficher la valeur cochée + $car_html[0]='value="0"';$car_html[1]='value="1"';$car_html[2]='value="2"'; + switch ($car) { + case "1": $car_html[1]='value="1" checked';break; + case "2": $car_html[2]='value="2" checked';break; + default: $car_html[0]='value="0" checked';break; + } + + echo ' + '."\n"; + + } else { + $rbd = ($border[$k]) ? ' rbd' : ''; + $car = substr($ensemblereponses, $k, 1); + switch ($car) { + case "1": echo ''."\n"; + if (isset($somme[$k]) === false) { + $somme[$k] = 0; + } + $somme[$k]++; break; + case "2": echo ''."\n"; break; + default: echo ''."\n"; + } + } + } + + //a la fin de chaque ligne se trouve les boutons modifier + if ($compteur != $ligneamodifier && ($dsondage->format=="A+"||$dsondage->format=="D+") && $mod_ok) { + echo ' + '."\n"; + } + + //demande de confirmation pour modification de ligne + for ($i=0;$i<$nblignes;$i++) { + if (isset($_POST["modifierligne$i"])) { + if ($compteur == $i) { + echo ''."\n"; + } + } + } + + $compteur++; + echo ''."\n"; +} + +// affichage de la ligne pour un nouvel utilisateur +if (( !(USE_REMOTE_USER && isset($_SERVER['REMOTE_USER'])) || !$user_mod) && $ligneamodifier==-1 && ($dsondage->format!="A-" && $dsondage->format!="D-")) { + //affichage de la case vide de texte pour un nouvel utilisateur + echo ' +'."\n"; + + //une ligne de checkbox pour le choix du nouvel utilisateur + for ($i = 0; $i < $nbcolonnes; $i++) { + echo ' + '."\n"; + } + + // Affichage du bouton de formulaire pour inscrire un nouvel utilisateur dans la base + echo ' +'."\n"; + +} + +// Addition and Best choice +//affichage de la ligne contenant les sommes de chaque colonne +$tr_addition = ''; +$meilleurecolonne = max($somme); +$compteursujet = 0; +$meilleursujet = '
    '; +for ($i = 0; $i < $nbcolonnes; $i++) { + if (isset($somme[$i]) && $somme[$i] > 0 ) { + if (in_array($i, array_keys($somme, max($somme)))){ + + $tr_addition .= '
'; + + $meilleursujet.= '
  • '.$radio_title[$i].'
  • '; + $compteursujet++; + + } else { + $tr_addition .= ''; + } + } else { + $tr_addition .= ''; + } +} +$tr_addition .= ''; + +$meilleursujet = str_replace("°", "'", $meilleursujet).''; +$vote_str = ($meilleurecolonne > 1) ? $vote_str = _('votes') : _('vote'); + +// Print Addition and Best choice +echo $tr_addition.' + +
    '._('Votes of the poll ').$title.'
    '.stripslashes($nombase).' +
      +
    • + + +
    • +
    • + + +
    • +
    • + + +
    • +
    +
    ' . _('Yes') . '() ' . _('Yes') . _(', ifneedbe') . '' . _('No') . ' + +
    +
    + + +
    +
    +
      +
    • + + +
    • +
    • + + +
    • +
    • + + +
    • +
    +
    '. _("Addition") .''.$somme[$i].''.$somme[$i].'
    +
    +
    '."\n"; + +if ($compteursujet == 1) { + echo ' +

    ' . _("Best choice") . '

    +
    +

    ' . _("The best choice at this time is:") . '

    + ' . $meilleursujet . ' +

    ' . _("with") . ' ' . $meilleurecolonne . ' ' . $vote_str . '.

    +
    '."\n"; +} elseif ($compteursujet > 1) { + echo ' +

    ' . _("Best choices") . '

    +
    +

    ' . _("The bests choices at this time are:") . '

    + ' . $meilleursujet . ' +

    ' . _("with") . ' ' . $meilleurecolonne . ' ' . $vote_str . '.

    +
    '."\n"; +} + +echo ' +
    +
    '; + +// Comments +$comments = $connect->allCommentsByPollId($numsondage); + +if (count($comments) != 0) { + echo '

    ' . _("Comments of polled people") . '

    '."\n"; + + while($dcomment = $comment_user->FetchNextObject(false)) { + echo ' +
    + '.stripslashes($dcomment->usercomment). ' : + ' . stripslashes(nl2br($dcomment->comment)) . ' +
    '; + } + + echo '
    '; +} + +if ($dsondage->format!="A-" && $dsondage->format!="D-") { +echo ' +
    +
    +
    ' . _("Add a comment in the poll") . ' +
    +

    +
    +
    +


    +

    +
    +

    +
    +
    +
    +
    '; +} + +echo ' +
    '; + +bandeau_pied(); diff --git a/studs.php b/studs.php index bfd06bd..dc6c9d0 100644 --- a/studs.php +++ b/studs.php @@ -18,678 +18,65 @@ */ namespace Framadate; -session_start(); - -if (file_exists('bandeaux_local.php')) { - include_once('bandeaux_local.php'); -} else { - include_once('bandeaux.php'); -} - include_once __DIR__ . '/app/inc/init.php'; -// Le fichier studs.php sert a afficher les résultats d'un sondage à un simple utilisateur. -// C'est également l'interface pour ajouter une valeur à un sondage deja créé. -$numsondage = false; +/* Functions */ +/* --------- */ -//On récupère le numéro de sondage par le lien web. -if(!empty($_GET['sondage'])) { - $numsondage = $_GET["sondage"]; - $_SESSION["numsondage"] = $numsondage; +function split_slots($slots) { + $splitted = array(); + foreach ($slots as $slot) { + $ex = explode('@', $slot->sujet); + $obj = new \stdClass(); + $obj->day = $ex[0]; + $obj->moments = explode(',', $ex[1]); + + $splitted[] = $obj; + } + return $splitted; } -if(!empty($_POST['sondage'])) { - $numsondage = $_POST["sondage"]; - $_SESSION["numsondage"] = $numsondage; -} elseif(!empty($_COOKIE['sondage'])) { - $numsondage = $_COOKIE["sondage"]; -} elseif(!empty($_SESSION['sondage'])) { - $numsondage = $_SESSION["numsondage"]; +function split_votes($votes) { + $splitted = array(); + foreach ($votes as $vote) { + $obj = new \stdClass(); + $obj->id = $vote->id_users; + $obj->name = $vote->nom; + $obj->choices = str_split($vote->reponses); + + $splitted[] = $obj; + } + return $splitted; } -$dsondage = $connect->findPollById($numsondage); -if ($dsondage){ - $sujets = $connect->allSujetsByPollId($numsondage); - $users = $connect->allUsersByPollId($numsondage); -} else { - Utils::print_header( _("Error!")); +/* PAGE */ +/* ---- */ - bandeau_titre(_("Error!")); - - echo ' -
    -

    ' . _("This poll doesn't exist !") . '

    -

    ' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

    -
    '."\n"; - - bandeau_pied(); - - die(); -} - -//output a CSV and die() -if(!empty($_GET['export']) && $dsondage) { - if($_GET['export'] == 'csv') { - require_once('exportcsv.php'); - } - - die(); -} - -// quand on ajoute un commentaire utilisateur -if(isset($_POST['ajoutcomment'])) { - if (isset($_SESSION['nom']) && Utils::issetAndNoEmpty('commentuser') === false) { - // Si le nom vient de la session, on le de-htmlentities - $comment_user = html_entity_decode($_SESSION['nom'], ENT_QUOTES, 'UTF-8'); - } elseif(Utils::issetAndNoEmpty('commentuser')) { - $comment_user = $_POST["commentuser"]; - } elseif(isset($_POST["commentuser"])) { - $err |= COMMENT_USER_EMPTY; - } else { - $comment_user = _('anonyme'); - } - - if(Utils::issetAndNoEmpty('comment') === false) { - $err |= COMMENT_EMPTY; - } - - if (isset($_POST["comment"]) && !Utils::is_error(COMMENT_EMPTY) && !Utils::is_error(NO_POLL) && !Utils::is_error(COMMENT_USER_EMPTY)) { - // protection contre les XSS : htmlentities - $comment = htmlentities($_POST['comment'], ENT_QUOTES, 'UTF-8'); - $comment_user = htmlentities($comment_user, ENT_QUOTES, 'UTF-8'); - - // Check for doublons - $comment_doublon = false; - $req = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; - $sql = $connect->Prepare($req); - $comment_user_doublon = $connect->Execute($sql, array($numsondage)); - if ($comment_user_doublon->RecordCount() != 0) { - while ( $dcomment_user_doublon=$comment_user_doublon->FetchNextObject(false)) { - if($dcomment_user_doublon->comment == $comment && $dcomment_user_doublon->usercomment == $comment_user) { - $comment_doublon = true; - }; - } - } - - if(!$comment_doublon) { - $req = 'INSERT INTO comments (id_sondage, comment, usercomment) VALUES ('. - $connect->Param('id_sondage').','. - $connect->Param('comment').','. - $connect->Param('comment_user').')'; - $sql = $connect->Prepare($req); - - $comments = $connect->Execute($sql, array($numsondage, $comment, $comment_user)); - if ($comments === false) { - $err |= COMMENT_INSERT_FAILED; - } - } - } +if(!empty($_GET['poll'])) { + $poll_id = $_GET['poll']; } -// Action quand on clique le bouton participer -$user_studs = $connect->allUsersByPollId($numsondage); - -$nbcolonnes = count($sujets); -if (!Utils::is_error(NO_POLL) && (isset($_POST["boutonp"]))) { - //Si le nom est bien entré - if (empty($_POST['nom'])) { - $err |= NAME_EMPTY; - } - - if(!Utils::is_error(NAME_EMPTY) && (! ( USE_REMOTE_USER && isset($_SERVER['REMOTE_USER']) ) || $_POST["nom"] == $_SESSION["nom"])) { - $nouveauchoix = ''; - for ($i=0;$i<$nbcolonnes;$i++) { - // radio checked 1 = Yes, 2 = Ifneedbe, 0 = No - if (isset($_POST["choix$i"])) { - switch ($_POST["choix$i"]) { - case 1: $nouveauchoix .= "1";break; - case 2: $nouveauchoix .= "2";break; - default: $nouveauchoix .= "0";break; - } - } - } - - $nom=substr($_POST["nom"],0,64); - - // protection contre les XSS : htmlentities - $nom = htmlentities($nom, ENT_QUOTES, 'UTF-8'); - - foreach ($users as $user) { - if ($nom == $user->nom) { - $err |= NAME_TAKEN; - } - } - - // Ecriture des choix de l'utilisateur dans la base - if (!Utils::is_error(NAME_TAKEN) && !Utils::is_error(NAME_EMPTY)) { - - // Todo : Il faudrait lever une erreur en cas d'erreur d'insertion - $newVote = $connect->insertVote($nom, $numsondage, $nouveauchoix); - $user_studs[] = $newVote; - - if ($dsondage->receiveNewVotes || /* compatibility for non boolean DB */ $dsondage->receiveNewVotes==="yes" || $dsondage->receiveNewVotes==="true") { - if($config['use_smtp']==true){ - Utils::sendEmail( $dsondage->admin_mail, - "[".NOMAPPLICATION."] "._("Poll's participation")." : ".html_entity_decode($dsondage->title, ENT_QUOTES, 'UTF-8') . ' ', - html_entity_decode($nom, ENT_QUOTES, 'UTF-8'). ' ' . - _("has filled a line.\nYou can find your poll at the link") . " :\n\n". - Utils::getUrlSondage($numsondage) . " \n\n" . - _("Thanks for your confidence.") . "\n". NOMAPPLICATION ); - } - } - } - } else { - $err |= NAME_EMPTY; - } +$poll = $connect->findPollById($poll_id); +if (!$poll) { + $smarty->assign('error', 'This poll doesn\'t exist'); + $smarty->display('error.tpl'); + exit; } -if($err != 0) { - Utils::print_header(_("Error!").' - '.$dsondage->title); - bandeau_titre(_("Error!")); +// Retrieve data +$slots = $connect->allSlotsByPollId($poll_id); +$votes = $connect->allUserVotesByPollId($poll_id); - echo '
      '."\n"; +// Assign data to template +$smarty->assign('poll_id', $poll_id); +$smarty->assign('poll', $poll); +$smarty->assign('title', _('Poll') . ' - ' . $poll->title); +$smarty->assign('slots', split_slots($slots)); +$smarty->assign('votes', split_votes($votes)); +$smarty->assign('editingVoteId', 0); // TODO Replace by the right ID - if(Utils::is_error(NAME_EMPTY)) { - echo '
    • ' . _("Enter a name") . "
    • \n"; - } - if(Utils::is_error(NAME_TAKEN)) { - echo '
    • ' . _("The name you've chosen already exist in this poll!") . "
    • \n"; - } - if(Utils::is_error(COMMENT_EMPTY) || Utils::is_error(COMMENT_USER_EMPTY)) { - echo '
    • ' . _("Enter a name and a comment!") . "
    • \n"; - } - if(Utils::is_error(COMMENT_INSERT_FAILED) ) { - echo '
    • ' . _("Failed to insert the comment!") . "
    • \n"; - } +//Utils::debug(split_votes($votes));exit; - echo '
    '; - -} else { - Utils::print_header(_('Poll').' - '.$dsondage->title); - bandeau_titre(_('Poll').' - '.$dsondage->title); -} - -$title=stripslashes(str_replace("\\","",$dsondage->title)); -echo ' -
    -
    -
    -

    '.$title.'

    -
    -
    -
    - - -
    -
    -
    -
    -
    -
    -

    '. _("Initiator of the poll") .'

    -

    '.stripslashes($dsondage->admin_name).'

    -
    - -
    '."\n"; - -//affichage de la description du sondage -if ($dsondage->comment) { - $commentaires = $dsondage->comment; - $commentaires=nl2br(str_replace("\\","",$comment)); - echo ' -
    -

    '._("Description") .'


    -

    '. $commentaires .'

    -
    '; -} -echo ' -
    -
    '."\n"; // .jumbotron - -//On récupere les données et les sujets du sondage -$nblignes = count($users); - -//on teste pour voir si une ligne doit etre modifiée -$testmodifier = false; -$ligneamodifier = -1; -for ($i=0;$i<$nblignes;$i++) { - if (isset($_POST["modifierligne$i"])) { - $ligneamodifier = $i; - } - - //test pour voir si une ligne est a modifier - if (isset($_POST['validermodifier'.$i])) { - $modifier = $i; - $testmodifier = true; - } -} - -//si le test est valide alors on affiche des checkbox pour entrer de nouvelles valeurs -if ($testmodifier) { - $nouveauchoix = ''; - for ($i=0;$i<$nbcolonnes;$i++) { - // radio checked 1 = Yes, 2 = Ifneedbe, 0 = No - if (isset($_POST["choix$i"])) { - switch ($_POST["choix$i"]) { - case 1: $nouveauchoix .= "1";break; - case 2: $nouveauchoix .= "2";break; - default: $nouveauchoix .= "0";break; - } - } - } - - $compteur=0; - while ($data = $user_studs->FetchNextObject(false) ) { - //mise a jour des données de l'utilisateur dans la base SQL - if ($compteur == $modifier) { - $sql = 'UPDATE user_studs SET reponses='.$connect->Param('nouveauchoix').' WHERE nom='.$connect->Param('nom').' AND id_users='.$connect->Param('id_users'); - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($nouveauchoix, $data->nom, $data->id_users)); - - if ($dsondage->mailsonde=="yes") { - Utils::sendEmail( "$dsondage->mail_admin", "[".NOMAPPLICATION."] " . _("Poll's participation") . " : ".html_entity_decode($dsondage->title, ENT_QUOTES, 'UTF-8'), "\"".html_entity_decode($data->nom, ENT_QUOTES, 'UTF-8')."\""."" . _("has filled a line.\nYou can find your poll at the link") . " :\n\n" . Utils::getUrlSondage($numsondage) . " \n\n" . _("Thanks for your confidence.") . "\n".NOMAPPLICATION ); - } - } - $compteur++; - } -} - -// Table headers -$thead = ''; - -// Button in the first td to avoid remove col on "Return" keypress) -$border = array(); // bordure pour distinguer les mois -$td_headers = array(); // for a11y, headers="M1 D4 H5" on each td -$radio_title = array(); // date for - -// Dates poll -if ($dsondage->format=="D"||$dsondage->format=="D+"||$dsondage->format=="D-") { - - $tr_months = ''; - $tr_days = ''; - $tr_hours = ''; - - // Headers - $colspan_month = 1; - $colspan_day = 1; - - for ($i = 0; $i < count($toutsujet); $i++) { - - // Current date - $current = $toutsujet[$i]; - $horoCur = explode("@",$current); //horoCur[0] = date, horoCur[1] = hour - if (isset($toutsujet[$i+1])){ - $next = $toutsujet[$i+1]; - $horoNext = explode("@",$next); - } - - $border[$i] = false; - $radio_title[$i] = strftime($date_format['txt_short'],$horoCur[0]); - - // Months - $td_headers[$i] = 'M'.($i+1-$colspan_month); - - if (isset($toutsujet[$i+1]) && strftime("%B", $horoCur[0]) == strftime("%B", $horoNext[0]) && strftime("%Y", $horoCur[0]) == strftime("%Y", $horoNext[0])){ - $colspan_month++; - } else { - $border[$i] = true; - $tr_months .= ''.strftime("%B",$horoCur[0]).' '.strftime("%Y", $horoCur[0]).''; - $colspan_month=1; - } - - // Days - $td_headers[$i] .= ' D'.($i+1-$colspan_day); - - if (isset($toutsujet[$i+1]) && strftime($date_format['txt_day'],$horoCur[0])==strftime($date_format['txt_day'],$horoNext[0])&&strftime("%B",$horoCur[0])==strftime("%B",$horoNext[0])){ - $colspan_day++; - } else { - $rbd = ($border[$i]) ? ' rbd' : ''; - $tr_days .= ''.strftime($date_format['txt_day'],$horoCur[0]).''; - $colspan_day=1; - } - - // Hours - $rbd = ($border[$i]) ? ' rbd' : ''; - if ($horoCur[1] !== "") { - $tr_hours .= ''.$horoCur[1].''; - $radio_title[$i] .= ' - '.$horoCur[1]; - $td_headers[$i] .= ' H'.$i; - } else { - $tr_hours .= ''; - } - } - - $border[count($border)-1] = false; // suppression de la bordure droite du dernier mois - - $tr_months .= ''; - $tr_days .= ''; - $tr_hours .= ''; - - $thead = "\n".$tr_months."\n".$tr_days."\n".$tr_hours."\n"; - -// Subjects poll -} else { - - $tr_subjects = ''; - - foreach ($sujets as $i=>$sujet) { - - $td_headers[$i]='';$radio_title[$i]=''; // init before concatenate - - // Subjects - preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$sujet->sujet,$md_a_img); // Markdown [![alt](src)](href) - preg_match_all('/!\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_img); // Markdown ![alt](src) - preg_match_all('/\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_a); // Markdown [text](href) - if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) - - $th_subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); - $th_subject_html = ''.$th_subject_text.''; - - } elseif (isset($md_img[2][0]) && $md_img[2][0]!='') { // ![alt](src) - - $th_subject_text = (isset($md_img[1][0]) && $md_img[1][0]!='') ? stripslashes($md_img[1][0]) : _("Choice") .' '.($i+1); - $th_subject_html = ''.$th_subject_text.''; - - } elseif (isset($md_a[2][0]) && $md_a[2][0]!='') { // [text](href) - - $th_subject_text = (isset($md_a[1][0]) && $md_a[1][0]!='') ? stripslashes($md_a[1][0]) : _("Choice") .' '.($i+1); - $th_subject_html = ''.$th_subject_text.''; - - } else { // text only - - $th_subject_text = stripslashes($sujet->sujet); - $th_subject_html = $th_subject_text; - - } - $tr_subjects .= ''.$th_subject_html.''; - - $border[$i] = false; - $td_headers[$i] .= 'S'.$i; - $radio_title[$i] .= $th_subject_text; - - } - - $thead = $tr_subjects.''; -} - -// Print headers -echo ' -
    - -'; -if ($dsondage->format=="A-" || $dsondage->format=="D-") { - echo ' -
    -

    ' . _("The administrator locked this poll, votes and comments are frozen, it's not possible to participate anymore.") . '

    - -
    '; -} else { - echo ' -
    -

    ' . _("If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line.") . '

    - -
    '; -} -echo' - - -

    '._('Votes of the poll ').'

    -
    - - - '. $thead . ' - '; - -// Print poll results - -//Usager pré-authentifié dans la liste? -$user_mod = false; - -//affichage des resultats actuels -$somme[] = 0; -$compteur = 0; - -foreach ($users as $user) { - - $ensemblereponses = $user->reponses; - - //affichage du nom - $nombase=str_replace("°","'",$user->nom); - echo ' -'."\n"; - - // ligne d'un usager pré-authentifié - $mod_ok = !( USE_REMOTE_USER && isset($_SERVER['REMOTE_USER']) ) || ($nombase == $_SESSION['nom']); - $user_mod |= $mod_ok; - - // pour chaque colonne - for ($k=0; $k < $nbcolonnes; $k++) { - // on remplace les choix de l'utilisateur par une ligne de checkbox pour recuperer de nouvelles valeurs - if ($compteur == $ligneamodifier) { - - $car = substr($ensemblereponses, $k , 1); - - // variable pour afficher la valeur cochée - $car_html[0]='value="0"';$car_html[1]='value="1"';$car_html[2]='value="2"'; - switch ($car) { - case "1": $car_html[1]='value="1" checked';break; - case "2": $car_html[2]='value="2" checked';break; - default: $car_html[0]='value="0" checked';break; - } - - echo ' - '."\n"; - - } else { - $rbd = ($border[$k]) ? ' rbd' : ''; - $car = substr($ensemblereponses, $k, 1); - switch ($car) { - case "1": echo ''."\n"; - if (isset($somme[$k]) === false) { - $somme[$k] = 0; - } - $somme[$k]++; break; - case "2": echo ''."\n"; break; - default: echo ''."\n"; - } - } - } - - //a la fin de chaque ligne se trouve les boutons modifier - if ($compteur != $ligneamodifier && ($dsondage->format=="A+"||$dsondage->format=="D+") && $mod_ok) { - echo ' - '."\n"; - } - - //demande de confirmation pour modification de ligne - for ($i=0;$i<$nblignes;$i++) { - if (isset($_POST["modifierligne$i"])) { - if ($compteur == $i) { - echo ''."\n"; - } - } - } - - $compteur++; - echo ''."\n"; -} - -// affichage de la ligne pour un nouvel utilisateur -if (( !(USE_REMOTE_USER && isset($_SERVER['REMOTE_USER'])) || !$user_mod) && $ligneamodifier==-1 && ($dsondage->format!="A-" && $dsondage->format!="D-")) { - //affichage de la case vide de texte pour un nouvel utilisateur - echo ' -'."\n"; - - //une ligne de checkbox pour le choix du nouvel utilisateur - for ($i = 0; $i < $nbcolonnes; $i++) { - echo ' - '."\n"; - } - - // Affichage du bouton de formulaire pour inscrire un nouvel utilisateur dans la base - echo ' -'."\n"; - -} - -// Addition and Best choice -//affichage de la ligne contenant les sommes de chaque colonne -$tr_addition = ''; -$meilleurecolonne = max($somme); -$compteursujet = 0; -$meilleursujet = '
      '; -for ($i = 0; $i < $nbcolonnes; $i++) { - if (isset($somme[$i]) && $somme[$i] > 0 ) { - if (in_array($i, array_keys($somme, max($somme)))){ - - $tr_addition .= '
    '; - - $meilleursujet.= '
  • '.$radio_title[$i].'
  • '; - $compteursujet++; - - } else { - $tr_addition .= ''; - } - } else { - $tr_addition .= ''; - } -} -$tr_addition .= ''; - -$meilleursujet = str_replace("°", "'", $meilleursujet).''; -$vote_str = ($meilleurecolonne > 1) ? $vote_str = _('votes') : _('vote'); - -// Print Addition and Best choice -echo $tr_addition.' - -
    '._('Votes of the poll ').$title.'
    '.stripslashes($nombase).' -
      -
    • - - -
    • -
    • - - -
    • -
    • - - -
    • -
    -
    ' . _('Yes') . '() ' . _('Yes') . _(', ifneedbe') . '' . _('No') . ' - -
    -
    - - -
    -
    -
      -
    • - - -
    • -
    • - - -
    • -
    • - - -
    • -
    -
    '. _("Addition") .''.$somme[$i].''.$somme[$i].'
    -
    -
    '."\n"; - -if ($compteursujet == 1) { - echo ' -

    ' . _("Best choice") . '

    -
    -

    ' . _("The best choice at this time is:") . '

    - ' . $meilleursujet . ' -

    ' . _("with") . ' ' . $meilleurecolonne . ' ' . $vote_str . '.

    -
    '."\n"; -} elseif ($compteursujet > 1) { - echo ' -

    ' . _("Best choices") . '

    -
    -

    ' . _("The bests choices at this time are:") . '

    - ' . $meilleursujet . ' -

    ' . _("with") . ' ' . $meilleurecolonne . ' ' . $vote_str . '.

    -
    '."\n"; -} - -echo ' -
    -
    '; - -// Comments -$comments = $connect->allCommentsByPollId($numsondage); - -if (count($comments) != 0) { - echo '

    ' . _("Comments of polled people") . '

    '."\n"; - - while($dcomment = $comment_user->FetchNextObject(false)) { - echo ' -
    - '.stripslashes($dcomment->usercomment). ' : - ' . stripslashes(nl2br($dcomment->comment)) . ' -
    '; - } - - echo '
    '; -} - -if ($dsondage->format!="A-" && $dsondage->format!="D-") { -echo ' -
    -
    -
    ' . _("Add a comment in the poll") . ' -
    -

    -
    -
    -


    -

    -
    -

    -
    -
    -
    -
    '; -} - -echo ' -
    '; - -bandeau_pied(); +$smarty->display('studs.tpl'); diff --git a/tpl/footer.tpl b/tpl/footer.tpl new file mode 100644 index 0000000..af3f5eb --- /dev/null +++ b/tpl/footer.tpl @@ -0,0 +1,4 @@ +
    + + + \ No newline at end of file diff --git a/tpl/head.tpl b/tpl/head.tpl new file mode 100644 index 0000000..6267892 --- /dev/null +++ b/tpl/head.tpl @@ -0,0 +1,29 @@ + + + + + + {if !empty($title)} + {$title} - {$APPLICATION_NAME} + {else} + {$APPLICATION_NAME} + {/if} + + + + + + + + + + + + + {if !empty($nav_js)} + + {/if} + + + +
    \ No newline at end of file diff --git a/tpl/header.tpl b/tpl/header.tpl new file mode 100644 index 0000000..58195c5 --- /dev/null +++ b/tpl/header.tpl @@ -0,0 +1,21 @@ +
    + {if count($langs)>1} +
    +
    + + + + +
    +
    + {/if} + +

    {$APPLICATION_NAME}

    + {if !empty($title)}

    {$title}

    {/if} + +
    +
    \ No newline at end of file diff --git a/tpl/studs.tpl b/tpl/studs.tpl new file mode 100644 index 0000000..9be2368 --- /dev/null +++ b/tpl/studs.tpl @@ -0,0 +1,163 @@ +{include file='head.tpl'} +{include file='header.tpl'} + + {* Global informations about the current poll *} + +
    +
    +
    +

    {$poll->title}

    +
    +
    +
    + + +
    +
    +
    +
    +
    +
    +

    {_("Initiator of the poll")}

    +

    {$poll->admin_name}

    +
    + +
    + + {if !empty($poll->comment)} +
    +

    {_("Description")}


    +

    {$poll->comment}

    +
    + {/if} +
    +
    + + {* Information about voting *} + + {if $poll->active} +
    +

    {_("If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line.")}

    + +
    + {else} +
    +

    {_("The administrator locked this poll, votes and comments are frozen, it's not possible to participate anymore.")}

    + +
    + {/if} + + {* Scroll left and right *} + + + + {* Vote table *} + +

    {_('Votes of the poll')}

    +
    + + + + + + {foreach $slots as $id=>$slot} + + {/foreach} + + + + + {foreach $slots as $id=>$slot} + + {/foreach} + + + + + {foreach $slots as $slot} + {foreach $slot->moments as $id=>$moment} + + {/foreach} + {/foreach} + + + + + {foreach $votes as $vote} + + + + {if $editingVoteId == $vote->id} + {foreach $vote->choices as $k=>$choice} + {* Edited line *} + + + + {/foreach} + {else} + {foreach $vote->choices as $k=>$choice} + {* Voted line *} + + {if $choice==1} + + {else if $choice==2} + + {else} + + {/if} + + {/foreach} + + {if $poll->active && $poll->editable} + + {else} + + {/if} + {/if} + + {/foreach} + +
    {_('Votes of the poll')} {$poll->title}
    {$slot->day|date_format:'%B %Y'}
    {$slot->day|date_format:$day_format}
    {$moment}
    {$vote->name} +
      +
    • + + +
    • +
    • + + +
    • +
    • + + +
    • +
    +
    {_('Yes')}(){_('Ifneedbe')}{_('No')} +
    + + +
    +
    +
    + +{include file='footer.tpl'} \ No newline at end of file From fafa5393edba275a7a7938048fdc918142e60fbf Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Fri, 12 Dec 2014 13:51:13 +0100 Subject: [PATCH 009/151] studs.tpl : Add a Form convering the whole page --- tpl/studs.tpl | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 9be2368..447cbbe 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -1,6 +1,8 @@ {include file='head.tpl'} {include file='header.tpl'} +
    + {* Global informations about the current poll *}
    @@ -143,12 +145,10 @@ {if $poll->active && $poll->editable} - - - - + + {else} @@ -159,5 +159,5 @@
    - + {include file='footer.tpl'} \ No newline at end of file From ea105960b4f9899290741e2a60ed5c49ea0b6c5d Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 14 Dec 2014 00:16:49 +0100 Subject: [PATCH 010/151] Add line to add vote + Add line to show best choices --- app/inc/init.php | 2 +- studs.php | 19 +++++++++- tpl/studs.tpl | 96 ++++++++++++++++++++++++++++++++++++++++-------- 3 files changed, 99 insertions(+), 18 deletions(-) diff --git a/app/inc/init.php b/app/inc/init.php index e3adbfe..dc8fa8c 100644 --- a/app/inc/init.php +++ b/app/inc/init.php @@ -41,7 +41,7 @@ $smarty->assign('TITLE_IMAGE', IMAGE_TITRE); $smarty->assign('use_nav_js', file_exists($_SERVER['DOCUMENT_ROOT'] . '/nav/nav.js')); $smarty->assign('lang', $lang); $smarty->assign('langs', $ALLOWED_LANGUAGES); -$smarty->assign('day_format', $date_format['txt_day']); +$smarty->assign('date_format', $date_format); function smarty_modifier_poll_url($poll_id, $admin=false){return \Framadate\Utils::getUrlSondage($poll_id, $admin);} //$smarty->registerPlugin('modifier', 'poll_url', 'sqqmarty_modifier_poll_url'); diff --git a/studs.php b/studs.php index dc6c9d0..87f8a46 100644 --- a/studs.php +++ b/studs.php @@ -49,6 +49,22 @@ function split_votes($votes) { return $splitted; } +function computeBestMoments($votes) { + $result = []; + foreach ($votes as $vote) { + $choices = str_split($vote->reponses); + foreach ($choices as $i=>$choice) { + if (empty($result[$i])) { + $result[$i] = 0; + } + if ($choice == 2) { + $result[$i]++; + } + } + } + return $result; +} + /* PAGE */ /* ---- */ @@ -75,8 +91,9 @@ $smarty->assign('poll', $poll); $smarty->assign('title', _('Poll') . ' - ' . $poll->title); $smarty->assign('slots', split_slots($slots)); $smarty->assign('votes', split_votes($votes)); +$smarty->assign('best_moments', computeBestMoments($votes)); $smarty->assign('editingVoteId', 0); // TODO Replace by the right ID -//Utils::debug(split_votes($votes));exit; +//Utils::debug(computeBestMoments($votes));exit; $smarty->display('studs.tpl'); diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 447cbbe..67d3a18 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -76,21 +76,27 @@ {foreach $slots as $id=>$slot} {$slot->day|date_format:'%B %Y'} + {for $foo=0 to ($slot->moments|count)-1} + {append var='headersM' value=$id} + {/for} {/foreach} {foreach $slots as $id=>$slot} - {$slot->day|date_format:$day_format} + {$slot->day|date_format:$date_format.txt_day} {/foreach} + {$headersDCount=0} {foreach $slots as $slot} {foreach $slot->moments as $id=>$moment} - {$moment} + {$moment} + {append var='headersD' value=$headersDCount} + {$headersDCount = $headersDCount+1} {/foreach} {/foreach} @@ -99,29 +105,30 @@ {foreach $votes as $vote} + {* Edited line *} + {$vote->name} {if $editingVoteId == $vote->id} {foreach $vote->choices as $k=>$choice} - {* Edited line *} - +
    • - -
    • - -
    • - -
    • @@ -130,15 +137,17 @@ {/foreach} {else} - {foreach $vote->choices as $k=>$choice} + {* Voted line *} - {if $choice==1} - {_('Yes')} - {else if $choice==2} - (){_('Ifneedbe')} + {foreach $vote->choices as $k=>$choice} + + {if $choice==2} + {_('Yes')} + {else if $choice==1} + (){_('Ifneedbe')} {else} - {_('No')} + {_('No')} {/if} {/foreach} @@ -156,6 +165,61 @@ {/if} {/foreach} + + {* Line to add a new vote *} + + {if $poll->active && $editingVoteId == 0} + + +
      + + +
      + + {$i = 0} + {foreach $slots as $slot} + {foreach $slot->moments as $moment} + +
        +
      • + + +
      • +
      • + + +
      • +
      • + + +
      • +
      + + {$i = $i+1} + {/foreach} + {/foreach} + + + {/if} + + {* Line displaying best moments *} + + {_("Addition")} + {$max = max($best_moments)} + {foreach $best_moments as $best_moment} + {if $max == $best_moment} + {$max} + {else} + + {/if} + {/foreach} +
    From 083c9eef2f6c2d27dc348499ac278b3fa98d6cff Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Mon, 15 Dec 2014 13:27:04 +0100 Subject: [PATCH 011/151] Add the display of Best Choices listing --- tpl/studs.tpl | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 67d3a18..5024b36 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -209,19 +209,53 @@ {/if} {* Line displaying best moments *} + {$count_bests = 0} {_("Addition")} {$max = max($best_moments)} {foreach $best_moments as $best_moment} {if $max == $best_moment} - {$max} + {$count_bests = $count_bests +1} + {$max} {else} - + {/if} {/foreach} + + {* Best votes listing *} + + {$max = max($best_moments)} + {if $max > 0} +
    + {if $count_bests == 1} +

    {_("Best choice")}

    +
    +

    {_("The best choice at this time is:")}

    + {elseif $count_bests > 1} +

    {_("Best choices")}

    +
    +

    {_("The bests choices at this time are:")}

    + {/if} + + + {$i = 0} +
      + {foreach $slots as $slot} + {foreach $slot->moments as $moment} + {if $best_moments[$i] == $max} +
    • {$slot->day|date_format:$date_format.txt_full} - {$moment}
    • + {/if} + {$i = $i+1} + {/foreach} + {/foreach} +
    +

    {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

    +
    +
    + {/if} {include file='footer.tpl'} \ No newline at end of file From 448a7c2d38af981338f38e41a52e38df06ceef89 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Mon, 15 Dec 2014 13:29:27 +0100 Subject: [PATCH 012/151] Clean tpl indentation --- tpl/studs.tpl | 446 +++++++++++++++++++++++++------------------------- 1 file changed, 223 insertions(+), 223 deletions(-) diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 5024b36..79424f7 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -3,8 +3,8 @@
    - {* Global informations about the current poll *} - + {* Global informations about the current poll *} +
    @@ -29,233 +29,233 @@
    - {if !empty($poll->comment)} + {if !empty($poll->comment)}

    {_("Description")}


    {$poll->comment}

    - {/if} + {/if}
    - {* Information about voting *} - - {if $poll->active} -
    -

    {_("If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line.")}

    - -
    - {else} -
    -

    {_("The administrator locked this poll, votes and comments are frozen, it's not possible to participate anymore.")}

    - -
    - {/if} - - {* Scroll left and right *} - - - - {* Vote table *} - -

    {_('Votes of the poll')}

    -
    - - - - - - {foreach $slots as $id=>$slot} - - {for $foo=0 to ($slot->moments|count)-1} - {append var='headersM' value=$id} - {/for} - {/foreach} - - - - - {foreach $slots as $id=>$slot} - - {/foreach} - - - - - {$headersDCount=0} - {foreach $slots as $slot} - {foreach $slot->moments as $id=>$moment} - - {append var='headersD' value=$headersDCount} - {$headersDCount = $headersDCount+1} - {/foreach} - {/foreach} - - - - - {foreach $votes as $vote} - - {* Edited line *} - - - - {if $editingVoteId == $vote->id} - {foreach $vote->choices as $k=>$choice} - - - - {/foreach} - {else} - - {* Voted line *} - - {foreach $vote->choices as $k=>$choice} - - {if $choice==2} - - {else if $choice==1} - - {else} - - {/if} - - {/foreach} - - {if $poll->active && $poll->editable} - - {else} - - {/if} - {/if} - - {/foreach} - - {* Line to add a new vote *} - - {if $poll->active && $editingVoteId == 0} - - - {$i = 0} - {foreach $slots as $slot} - {foreach $slot->moments as $moment} - - {$i = $i+1} - {/foreach} - {/foreach} - - - {/if} - - {* Line displaying best moments *} - {$count_bests = 0} - - - {$max = max($best_moments)} - {foreach $best_moments as $best_moment} - {if $max == $best_moment} - {$count_bests = $count_bests +1} - - {else} - - {/if} - {/foreach} - - -
    {_('Votes of the poll')} {$poll->title}
    {$slot->day|date_format:'%B %Y'}
    {$slot->day|date_format:$date_format.txt_day}
    {$moment}
    {$vote->name} -
      -
    • - - -
    • -
    • - - -
    • -
    • - - -
    • -
    -
    {_('Yes')}(){_('Ifneedbe')}{_('No')} - - -
    -
    - - -
    -
    -
      -
    • - - -
    • -
    • - - -
    • -
    • - - -
    • -
    -
    {_("Addition")}{$max}
    -
    - - {* Best votes listing *} - - {$max = max($best_moments)} - {if $max > 0} -
    - {if $count_bests == 1} -

    {_("Best choice")}

    -
    -

    {_("The best choice at this time is:")}

    - {elseif $count_bests > 1} -

    {_("Best choices")}

    -
    -

    {_("The bests choices at this time are:")}

    - {/if} - - - {$i = 0} -
      - {foreach $slots as $slot} - {foreach $slot->moments as $moment} - {if $best_moments[$i] == $max} -
    • {$slot->day|date_format:$date_format.txt_full} - {$moment}
    • - {/if} - {$i = $i+1} - {/foreach} - {/foreach} -
    -

    {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

    -
    -
    - {/if} + {* Information about voting *} + + {if $poll->active} +
    +

    {_("If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line.")}

    + +
    + {else} +
    +

    {_("The administrator locked this poll, votes and comments are frozen, it's not possible to participate anymore.")}

    + +
    + {/if} + + {* Scroll left and right *} + + + + {* Vote table *} + +

    {_('Votes of the poll')}

    +
    + + + + + + {foreach $slots as $id=>$slot} + + {for $foo=0 to ($slot->moments|count)-1} + {append var='headersM' value=$id} + {/for} + {/foreach} + + + + + {foreach $slots as $id=>$slot} + + {/foreach} + + + + + {$headersDCount=0} + {foreach $slots as $slot} + {foreach $slot->moments as $id=>$moment} + + {append var='headersD' value=$headersDCount} + {$headersDCount = $headersDCount+1} + {/foreach} + {/foreach} + + + + + {foreach $votes as $vote} + + {* Edited line *} + + + + {if $editingVoteId == $vote->id} + {foreach $vote->choices as $k=>$choice} + + + + {/foreach} + {else} + + {* Voted line *} + + {foreach $vote->choices as $k=>$choice} + + {if $choice==2} + + {else if $choice==1} + + {else} + + {/if} + + {/foreach} + + {if $poll->active && $poll->editable} + + {else} + + {/if} + {/if} + + {/foreach} + + {* Line to add a new vote *} + + {if $poll->active && $editingVoteId == 0} + + + {$i = 0} + {foreach $slots as $slot} + {foreach $slot->moments as $moment} + + {$i = $i+1} + {/foreach} + {/foreach} + + + {/if} + + {* Line displaying best moments *} + {$count_bests = 0} + + + {$max = max($best_moments)} + {foreach $best_moments as $best_moment} + {if $max == $best_moment} + {$count_bests = $count_bests +1} + + {else} + + {/if} + {/foreach} + + +
    {_('Votes of the poll')} {$poll->title}
    {$slot->day|date_format:'%B %Y'}
    {$slot->day|date_format:$date_format.txt_day}
    {$moment}
    {$vote->name} +
      +
    • + + +
    • +
    • + + +
    • +
    • + + +
    • +
    +
    {_('Yes')}(){_('Ifneedbe')}{_('No')} + + +
    +
    + + +
    +
    +
      +
    • + + +
    • +
    • + + +
    • +
    • + + +
    • +
    +
    {_("Addition")}{$max}
    +
    + + {* Best votes listing *} + + {$max = max($best_moments)} + {if $max > 0} +
    + {if $count_bests == 1} +

    {_("Best choice")}

    +
    +

    {_("The best choice at this time is:")}

    + {elseif $count_bests > 1} +

    {_("Best choices")}

    +
    +

    {_("The bests choices at this time are:")}

    + {/if} + + + {$i = 0} +
      + {foreach $slots as $slot} + {foreach $slot->moments as $moment} + {if $best_moments[$i] == $max} +
    • {$slot->day|date_format:$date_format.txt_full} - {$moment}
    • + {/if} + {$i = $i+1} + {/foreach} + {/foreach} +
    +

    {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

    +
    +
    + {/if} {include file='footer.tpl'} \ No newline at end of file From ecfcae580be9aaa5dec0e18d5df612deb2ca5a21 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Mon, 15 Dec 2014 13:33:39 +0100 Subject: [PATCH 013/151] Define base template : page.tpl --- tpl/page.tpl | 6 ++++++ tpl/studs.tpl | 6 +++--- 2 files changed, 9 insertions(+), 3 deletions(-) create mode 100644 tpl/page.tpl diff --git a/tpl/page.tpl b/tpl/page.tpl new file mode 100644 index 0000000..025864a --- /dev/null +++ b/tpl/page.tpl @@ -0,0 +1,6 @@ +{include file='head.tpl'} +{include file='header.tpl'} + +{block name=main}{/block} + +{include file='footer.tpl'} \ No newline at end of file diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 79424f7..18b8f44 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -1,6 +1,6 @@ -{include file='head.tpl'} -{include file='header.tpl'} +{extends file='page.tpl'} +{block name=main}
    {* Global informations about the current poll *} @@ -258,4 +258,4 @@
    {/if} -{include file='footer.tpl'} \ No newline at end of file +{/block} \ No newline at end of file From 497762165fc3d0fedb3451b60102974eb4e9bbb4 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Mon, 15 Dec 2014 13:36:26 +0100 Subject: [PATCH 014/151] studs.tpl: Remove 4 spaces to global indentation --- tpl/studs.tpl | 445 +++++++++++++++++++++++++------------------------- 1 file changed, 223 insertions(+), 222 deletions(-) diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 18b8f44..c4167e9 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -3,259 +3,260 @@ {block name=main}
    - {* Global informations about the current poll *} + {* Global informations about the current poll *} -
    -
    -
    -

    {$poll->title}

    -
    -
    -
    - - -
    +
    +
    +
    +

    {$poll->title}

    +
    +
    +
    + +
    -
    -
    -
    -

    {_("Initiator of the poll")}

    -

    {$poll->admin_name}

    -
    - +
    +
    +
    +
    +

    {_("Initiator of the poll")}

    +

    {$poll->admin_name}

    - - {if !empty($poll->comment)} -
    -

    {_("Description")}


    -

    {$poll->comment}

    + - {/if}
    -
    - {* Information about voting *} - - {if $poll->active} -
    -

    {_("If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line.")}

    - -
    - {else} -
    -

    {_("The administrator locked this poll, votes and comments are frozen, it's not possible to participate anymore.")}

    - -
    - {/if} - - {* Scroll left and right *} - - - {* Vote table *} + {* Information about voting *} -

    {_('Votes of the poll')}

    -
    - - - - - - {foreach $slots as $id=>$slot} - - {for $foo=0 to ($slot->moments|count)-1} - {append var='headersM' value=$id} - {/for} + {if $poll->active} +
    +

    {_("If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line.")}

    + +
    + {else} +
    +

    {_("The administrator locked this poll, votes and comments are frozen, it's not possible to participate anymore.")}

    + +
    + {/if} + + {* Scroll left and right *} + + + + {* Vote table *} + +

    {_('Votes of the poll')}

    +
    +
    {_('Votes of the poll')} {$poll->title}
    {$slot->day|date_format:'%B %Y'}
    + + + + + {foreach $slots as $id=>$slot} + + {for $foo=0 to ($slot->moments|count)-1} + {append var='headersM' value=$id} + {/for} + {/foreach} + + + + + {foreach $slots as $id=>$slot} + + {/foreach} + + + + + {$headersDCount=0} + {foreach $slots as $slot} + {foreach $slot->moments as $id=>$moment} + + {append var='headersD' value=$headersDCount} + {$headersDCount = $headersDCount+1} {/foreach} - - - - - {foreach $slots as $id=>$slot} - + {/foreach} + + + + + {foreach $votes as $vote} + + {* Edited line *} + + + + {if $editingVoteId == $vote->id} + {foreach $vote->choices as $k=>$choice} + + + {/foreach} - - - - - {$headersDCount=0} - {foreach $slots as $slot} - {foreach $slot->moments as $id=>$moment} - - {append var='headersD' value=$headersDCount} - {$headersDCount = $headersDCount+1} - {/foreach} - {/foreach} - - - - - {foreach $votes as $vote} - - {* Edited line *} + {else} - + {* Voted line *} - {if $editingVoteId == $vote->id} - {foreach $vote->choices as $k=>$choice} + {foreach $vote->choices as $k=>$choice} - - - {/foreach} - {else} - - {* Voted line *} - - {foreach $vote->choices as $k=>$choice} - - {if $choice==2} - - {else if $choice==1} - - {else} - - {/if} - - {/foreach} - - {if $poll->active && $poll->editable} - + {if $choice==2} + + {else if $choice==1} + {else} - + {/if} - {/if} - - {/foreach} - {* Line to add a new vote *} - - {if $poll->active && $editingVoteId == 0} - - - {$i = 0} - {foreach $slots as $slot} - {foreach $slot->moments as $moment} - - {$i = $i+1} - {/foreach} {/foreach} - - - {/if} - {* Line displaying best moments *} - {$count_bests = 0} - - - {$max = max($best_moments)} - {foreach $best_moments as $best_moment} - {if $max == $best_moment} - {$count_bests = $count_bests +1} - + {if $poll->active && $poll->editable} + {else} {/if} - {/foreach} + {/if} - -
    {_('Votes of the poll')} {$poll->title}
    {$slot->day|date_format:'%B %Y'}
    {$slot->day|date_format:$date_format.txt_day}
    {$moment}
    {$slot->day|date_format:$date_format.txt_day}
    {$vote->name} +
      +
    • + + +
    • +
    • + + +
    • +
    • + + +
    • +
    +
    {$moment}
    {$vote->name} -
      -
    • - - -
    • -
    • - - -
    • -
    • - - -
    • -
    -
    {_('Yes')}(){_('Ifneedbe')}{_('No')} - - - {_('Yes')}(){_('Ifneedbe')}{_('No')}
    -
    - - -
    -
    -
      -
    • - - -
    • -
    • - - -
    • -
    • - - -
    • -
    -
    {_("Addition")}{$max} + + +
    -
    + {/foreach} - {* Best votes listing *} + {* Line to add a new vote *} - {$max = max($best_moments)} - {if $max > 0} -
    - {if $count_bests == 1} -

    {_("Best choice")}

    -
    -

    {_("The best choice at this time is:")}

    - {elseif $count_bests > 1} -

    {_("Best choices")}

    -
    -

    {_("The bests choices at this time are:")}

    + {if $poll->active && $editingVoteId == 0} + + +
    + + +
    + + {$i = 0} + {foreach $slots as $slot} + {foreach $slot->moments as $moment} + +
      +
    • + + +
    • +
    • + + +
    • +
    • + + +
    • +
    + + {$i = $i+1} + {/foreach} + {/foreach} + + {/if} - - {$i = 0} -
      - {foreach $slots as $slot} - {foreach $slot->moments as $moment} - {if $best_moments[$i] == $max} -
    • {$slot->day|date_format:$date_format.txt_full} - {$moment}
    • + {* Line displaying best moments *} + {$count_bests = 0} + + {_("Addition")} + {$max = max($best_moments)} + {foreach $best_moments as $best_moment} + {if $max == $best_moment} + {$count_bests = $count_bests +1} + {$max} + {else} + {/if} - {$i = $i+1} {/foreach} - {/foreach} -
    -

    {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

    -
    -
    + + + +
    + + {* Best votes listing *} + + {$max = max($best_moments)} + {if $max > 0} +
    + {if $count_bests == 1} +

    {_("Best choice")}

    +
    +

    {_("The best choice at this time is:")}

    + {elseif $count_bests > 1} +

    {_("Best choices")}

    +
    +

    {_("The bests choices at this time are:")}

    {/if} + + + {$i = 0} +
      + {foreach $slots as $slot} + {foreach $slot->moments as $moment} + {if $best_moments[$i] == $max} +
    • {$slot->day|date_format:$date_format.txt_full} - {$moment}
    • + {/if} + {$i = $i+1} + {/foreach} + {/foreach} +
    +

    {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

    +
    +
    + {/if} + {/block} \ No newline at end of file From ad5ea9c6ffbd7b3f712459ec5a1058c08c466bbe Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Mon, 15 Dec 2014 13:49:25 +0100 Subject: [PATCH 015/151] Display list of comments + Display form to add a comment --- studs.php | 2 ++ tpl/studs.tpl | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/studs.php b/studs.php index 87f8a46..27f3c86 100644 --- a/studs.php +++ b/studs.php @@ -84,6 +84,7 @@ if (!$poll) { // Retrieve data $slots = $connect->allSlotsByPollId($poll_id); $votes = $connect->allUserVotesByPollId($poll_id); +$comments = $connect->allCommentsByPollId($poll_id); // Assign data to template $smarty->assign('poll_id', $poll_id); @@ -92,6 +93,7 @@ $smarty->assign('title', _('Poll') . ' - ' . $poll->title); $smarty->assign('slots', split_slots($slots)); $smarty->assign('votes', split_votes($votes)); $smarty->assign('best_moments', computeBestMoments($votes)); +$smarty->assign('comments', $comments); $smarty->assign('editingVoteId', 0); // TODO Replace by the right ID //Utils::debug(computeBestMoments($votes));exit; diff --git a/tpl/studs.tpl b/tpl/studs.tpl index c4167e9..9df42d0 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -258,5 +258,39 @@
    {/if} + {* Comments *} + + {if $poll->active} +
    + + {* Comment list *} + + {if $comments|count > 0} + {foreach $comments as $comment} +
    + {$comment->usercomment}  + {nl2br($comment->comment)} +
    + {/foreach} + {/if} + + {* Add comment form *} + +
    +
    +
    {_("Add a comment in the poll")} +
    +

    +
    +
    +


    +

    +
    +

    +
    +
    +
    +
    + {/if} {/block} \ No newline at end of file From 2480d441d426a6d4f568d74775136695b870e206 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Mon, 15 Dec 2014 13:55:46 +0100 Subject: [PATCH 016/151] Remove code in comment --- app/inc/init.php | 1 - 1 file changed, 1 deletion(-) diff --git a/app/inc/init.php b/app/inc/init.php index dc8fa8c..fa402bb 100644 --- a/app/inc/init.php +++ b/app/inc/init.php @@ -44,7 +44,6 @@ $smarty->assign('langs', $ALLOWED_LANGUAGES); $smarty->assign('date_format', $date_format); function smarty_modifier_poll_url($poll_id, $admin=false){return \Framadate\Utils::getUrlSondage($poll_id, $admin);} -//$smarty->registerPlugin('modifier', 'poll_url', 'sqqmarty_modifier_poll_url'); // End- Smarty From d54f2e4759a4983c6c729bbb831cda676e68e67e Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 16 Dec 2014 00:02:01 +0100 Subject: [PATCH 017/151] Improve usage of namespace + Create PollService in /Framadate/Service namespace --- app/classes/Framadate/FramaDB.php | 3 +-- app/inc/init.php | 14 +++++--------- composer.json | 2 +- studs.php | 15 ++++++++++----- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 97b618e..0869fcb 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -38,8 +38,7 @@ class FramaDB return $this->pdo->query($sql); } - function findPollById($poll_id) - { + function findPollById($poll_id) { // Open database if (preg_match(';^[\w\d]{16}$;i', $poll_id)) { diff --git a/app/inc/init.php b/app/inc/init.php index fa402bb..5051953 100644 --- a/app/inc/init.php +++ b/app/inc/init.php @@ -16,6 +16,8 @@ * Auteurs de STUdS (projet initial) : Guilhem BORGHESI (borghesi@unistra.fr) et Raphaël DROZ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ +use Framadate\FramaDB; +use Framadate\Utils; if (ini_get('date.timezone') == '') { date_default_timezone_set('Europe/Paris'); @@ -36,25 +38,19 @@ $smarty->cache_dir = 'cache/'; $smarty->caching = false; $smarty->assign('APPLICATION_NAME', NOMAPPLICATION); -$smarty->assign('SERVER_URL', \Framadate\Utils::get_server_name()); +$smarty->assign('SERVER_URL', Utils::get_server_name()); $smarty->assign('TITLE_IMAGE', IMAGE_TITRE); $smarty->assign('use_nav_js', file_exists($_SERVER['DOCUMENT_ROOT'] . '/nav/nav.js')); $smarty->assign('lang', $lang); $smarty->assign('langs', $ALLOWED_LANGUAGES); $smarty->assign('date_format', $date_format); -function smarty_modifier_poll_url($poll_id, $admin=false){return \Framadate\Utils::getUrlSondage($poll_id, $admin);} +function smarty_modifier_poll_url($poll_id, $admin=false){return Utils::getUrlSondage($poll_id, $admin);} // End- Smarty - -use Framadate\FramaDB; -use Framadate\Form; -use Framadate\Choice; -use Framadate\Utils; - if (session_id() == '') { session_start(); } -$connect = new Framadate\FramaDB(DB_CONNECTION_STRING, DB_USER, DB_PASSWORD); +$connect = new FramaDB(DB_CONNECTION_STRING, DB_USER, DB_PASSWORD); $err = 0; diff --git a/composer.json b/composer.json index 199030d..743bc6d 100644 --- a/composer.json +++ b/composer.json @@ -4,6 +4,6 @@ }, "autoload": { - "psr-0": {"Framadate": "app/classes/"} + "psr-4": {"Framadate\\": "app/classes/Framadate/"} } } diff --git a/studs.php b/studs.php index 27f3c86..185c91b 100644 --- a/studs.php +++ b/studs.php @@ -16,7 +16,7 @@ * Auteurs de STUdS (projet initial) : Guilhem BORGHESI (borghesi@unistra.fr) et Raphaël DROZ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ -namespace Framadate; +use Framadate\Services\PollService; include_once __DIR__ . '/app/inc/init.php'; @@ -65,6 +65,11 @@ function computeBestMoments($votes) { return $result; } +/* Services */ +/*----------*/ + +$pollService = new PollService($connect); + /* PAGE */ /* ---- */ @@ -73,7 +78,7 @@ if(!empty($_GET['poll'])) { } -$poll = $connect->findPollById($poll_id); +$poll = $pollService->findById($poll_id); if (!$poll) { $smarty->assign('error', 'This poll doesn\'t exist'); @@ -82,9 +87,9 @@ if (!$poll) { } // Retrieve data -$slots = $connect->allSlotsByPollId($poll_id); -$votes = $connect->allUserVotesByPollId($poll_id); -$comments = $connect->allCommentsByPollId($poll_id); +$slots = $pollService->allSlotsByPollId($poll_id); +$votes = $pollService->allUserVotesByPollId($poll_id); +$comments = $pollService->allCommentsByPollId($poll_id); // Assign data to template $smarty->assign('poll_id', $poll_id); From db915b0bf18aee96167cfac175aa26df70eab739 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 16 Dec 2014 00:02:34 +0100 Subject: [PATCH 018/151] Replace button to CSV export by a link --- tpl/studs.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 9df42d0..a26d97e 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -13,7 +13,7 @@
    - + {_('Export to CSV')}
    From e941cf182216501191e12c5376362ed5fb40b430 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 16 Dec 2014 00:45:16 +0100 Subject: [PATCH 019/151] Add availability to edit a vote --- app/classes/Framadate/FramaDB.php | 5 ++++ studs.php | 38 +++++++++++++++++++++++++++++-- tpl/studs.tpl | 11 ++++----- 3 files changed, 46 insertions(+), 8 deletions(-) diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 0869fcb..12fc08e 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -85,4 +85,9 @@ class FramaDB return $newVote; } + function updateVote($poll_id, $vote_id, $choices) { + $prepared = $this->prepare('UPDATE user_studs SET reponses = ? WHERE id_sondage = ? AND id_users = ?'); + return $prepared->execute([$choices, $poll_id, $vote_id]); + } + } diff --git a/studs.php b/studs.php index 185c91b..f638ac5 100644 --- a/studs.php +++ b/studs.php @@ -17,6 +17,7 @@ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ use Framadate\Services\PollService; +use Framadate\Utils; include_once __DIR__ . '/app/inc/init.php'; @@ -74,7 +75,7 @@ $pollService = new PollService($connect); /* ---- */ if(!empty($_GET['poll'])) { - $poll_id = $_GET['poll']; + $poll_id = filter_input(INPUT_GET, 'poll', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9]+$/']]); } @@ -86,11 +87,44 @@ if (!$poll) { exit; } +// A vote is going to be edited +if (!empty($_POST['edit_vote'])) { + // TODO Try what does filter_input with a wrong value + $editingVoteId = filter_input(INPUT_POST, 'edit_vote', FILTER_VALIDATE_INT); +} else { + $editingVoteId = 0; +} + + +if (!empty($_POST['save'])) { // Save edition of an old vote + $editedVote = filter_input(INPUT_POST, 'save', FILTER_VALIDATE_INT); + $newChoices = []; + + // TODO Do this verification into a Service (maybe called 'InputService') + foreach($_POST['choices'] as $id=>$choice) { + $choice = filter_var($choice, FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[012]$/']]); + if ($choice !== false) { + $newChoices[$id] = $choice; + } + } + + if (count($newChoices) == count($_POST['choices'])) { + $result = $pollService->updatePoll($poll_id, $editedVote, $newChoices); + if ($result) { + $message = ['type'=>'success', 'message'=>_('Update vote successfully!')]; + } else { + $message = ['type'=>'success', 'message'=>_('Update vote successfully!')]; + } + } +} elseif (isset($_POST[''])) { // Add a new vote +} + // Retrieve data $slots = $pollService->allSlotsByPollId($poll_id); $votes = $pollService->allUserVotesByPollId($poll_id); $comments = $pollService->allCommentsByPollId($poll_id); + // Assign data to template $smarty->assign('poll_id', $poll_id); $smarty->assign('poll', $poll); @@ -99,7 +133,7 @@ $smarty->assign('slots', split_slots($slots)); $smarty->assign('votes', split_votes($votes)); $smarty->assign('best_moments', computeBestMoments($votes)); $smarty->assign('comments', $comments); -$smarty->assign('editingVoteId', 0); // TODO Replace by the right ID +$smarty->assign('editingVoteId', $editingVoteId); //Utils::debug(computeBestMoments($votes));exit; diff --git a/tpl/studs.tpl b/tpl/studs.tpl index a26d97e..57d2f86 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -115,27 +115,27 @@
    • - +
    • - +
    • - +
    - {/foreach} + {else} {* Voted line *} @@ -154,8 +154,7 @@ {if $poll->active && $poll->editable} - - From 80b06d65cdf811cfb59c340db9f021e78ac59cec Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 17 Dec 2014 13:17:08 +0100 Subject: [PATCH 020/151] Some work on vote saving --- .gitignore | 10 +- app/classes/Framadate/FramaDB.php | 24 ++--- app/classes/Framadate/Message.php | 15 +++ .../Framadate/Services/InputService.php | 28 +++++ .../Framadate/Services/PollService.php | 83 +++++++++++++++ app/inc/init.php | 1 - app/inc/studs.inc.php | 10 -- studs.php | 100 +++++++----------- tpl/footer.tpl | 2 +- tpl/studs.tpl | 16 +-- 10 files changed, 193 insertions(+), 96 deletions(-) create mode 100644 app/classes/Framadate/Message.php create mode 100644 app/classes/Framadate/Services/InputService.php create mode 100644 app/classes/Framadate/Services/PollService.php delete mode 100644 app/inc/studs.inc.php diff --git a/.gitignore b/.gitignore index 90c4c5b..9181863 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ .htaccess -admin/.htaccess -admin/.htpasswd +.htpasswd admin/logs_studs.txt composer.lock composer.phar @@ -8,7 +7,10 @@ framanav nav app/inc/constants.php vendor -.settings/ -.project cache/ tpl_c/ + +.settings/ +.project +.idea/ +*.iml diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 12fc08e..184f7b6 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -39,19 +39,13 @@ class FramaDB } function findPollById($poll_id) { + $prepared = $this->prepare('SELECT * FROM sondage WHERE sondage.poll_id = ?'); - // Open database - if (preg_match(';^[\w\d]{16}$;i', $poll_id)) { - $prepared = $this->prepare('SELECT * FROM sondage WHERE sondage.poll_id = ?'); + $prepared->execute([$poll_id]); + $poll = $prepared->fetch(); + $prepared->closeCursor(); - $prepared->execute([$poll_id]); - $poll = $prepared->fetch(); - $prepared->closeCursor(); - - return $poll; - } - - return null; + return $poll; } function allCommentsByPollId($poll_id) { @@ -72,15 +66,15 @@ class FramaDB return $prepared->fetchAll(); } - function insertVote($name, $poll_id, $votes) { - $prepared = $this->prepare('INSERT INTO user_studs (nom,id_sondage,reponses) VALUES (?,?,?)'); - $prepared->execute([$name, $poll_id, $votes]); + function insertVote($poll_id, $name, $choices) { + $prepared = $this->prepare('INSERT INTO user_studs (id_sondage,nom,reponses) VALUES (?,?,?)'); + $prepared->execute([$poll_id, $name, $choices]); $newVote = new \stdClass(); $newVote->id_sondage = $poll_id; $newVote->id_users = $this->pdo->lastInsertId(); $newVote->nom = $name; - $newVote->reponse = $votes; + $newVote->reponse = $choices; return $newVote; } diff --git a/app/classes/Framadate/Message.php b/app/classes/Framadate/Message.php new file mode 100644 index 0000000..b14c376 --- /dev/null +++ b/app/classes/Framadate/Message.php @@ -0,0 +1,15 @@ +type = $type; + $this->message = $message; + } + +} + \ No newline at end of file diff --git a/app/classes/Framadate/Services/InputService.php b/app/classes/Framadate/Services/InputService.php new file mode 100644 index 0000000..49a7c39 --- /dev/null +++ b/app/classes/Framadate/Services/InputService.php @@ -0,0 +1,28 @@ +$item) { + $item = filter_var($item, $type, $options); + if ($item !== false) { + $newArr[$id] = $item; + } + } + + return $newArr; + } + +} \ No newline at end of file diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php new file mode 100644 index 0000000..51fa3e7 --- /dev/null +++ b/app/classes/Framadate/Services/PollService.php @@ -0,0 +1,83 @@ +connect = $connect; + } + + function findById($poll_id) { + if (preg_match('/^[\w\d]{16}$/i', $poll_id)) { + return $this->connect->findPollById($poll_id); + } + + return null; + } + + function allCommentsByPollId($poll_id) { + return $this->connect->allCommentsByPollId($poll_id); + } + + function allUserVotesByPollId($poll_id) { + return $this->connect->allUserVotesByPollId($poll_id); + } + + function allSlotsByPollId($poll_id) { + return $this->connect->allSlotsByPollId($poll_id); + } + + public function updateVote($poll_id, $vote_id, $choices) { + $choices = implode($choices); + return $this->connect->updateVote($poll_id, $vote_id, $choices); + } + + function addVote($poll_id, $name, $choices) { + $choices = implode($choices); + return $this->connect->insertVote($poll_id, $name, $choices); + } + + function computeBestMoments($votes) { + $result = []; + foreach ($votes as $vote) { + $choices = str_split($vote->reponses); + foreach ($choices as $i=>$choice) { + if (empty($result[$i])) { + $result[$i] = 0; + } + if ($choice == 2) { + $result[$i]++; + } + } + } + return $result; + } + + function splitSlots($slots) { + $splitted = array(); + foreach ($slots as $slot) { + $ex = explode('@', $slot->sujet); + $obj = new \stdClass(); + $obj->day = $ex[0]; + $obj->moments = explode(',', $ex[1]); + + $splitted[] = $obj; + } + return $splitted; + } + + function splitVotes($votes) { + $splitted = array(); + foreach ($votes as $vote) { + $obj = new \stdClass(); + $obj->id = $vote->id_users; + $obj->name = $vote->nom; + $obj->choices = str_split($vote->reponses); + + $splitted[] = $obj; + } + return $splitted; + } +} diff --git a/app/inc/init.php b/app/inc/init.php index 5051953..2989a0e 100644 --- a/app/inc/init.php +++ b/app/inc/init.php @@ -24,7 +24,6 @@ if (ini_get('date.timezone') == '') { } include_once __DIR__ . '/constants.php'; include_once __DIR__ . '/i18n.php'; -include_once __DIR__ . '/studs.inc.php'; // Autoloading of dependencies with Composer require_once __DIR__ . '/../../vendor/autoload.php'; diff --git a/app/inc/studs.inc.php b/app/inc/studs.inc.php deleted file mode 100644 index 24f81a3..0000000 --- a/app/inc/studs.inc.php +++ /dev/null @@ -1,10 +0,0 @@ -sujet, ',')+1; - } - return $nb; -} \ No newline at end of file diff --git a/studs.php b/studs.php index f638ac5..8f61806 100644 --- a/studs.php +++ b/studs.php @@ -17,59 +17,21 @@ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ use Framadate\Services\PollService; +use Framadate\Services\InputService; use Framadate\Utils; +use Framadate\Message; include_once __DIR__ . '/app/inc/init.php'; -/* Functions */ +/* Variables */ /* --------- */ - -function split_slots($slots) { - $splitted = array(); - foreach ($slots as $slot) { - $ex = explode('@', $slot->sujet); - $obj = new \stdClass(); - $obj->day = $ex[0]; - $obj->moments = explode(',', $ex[1]); - - $splitted[] = $obj; - } - return $splitted; -} - -function split_votes($votes) { - $splitted = array(); - foreach ($votes as $vote) { - $obj = new \stdClass(); - $obj->id = $vote->id_users; - $obj->name = $vote->nom; - $obj->choices = str_split($vote->reponses); - - $splitted[] = $obj; - } - return $splitted; -} - -function computeBestMoments($votes) { - $result = []; - foreach ($votes as $vote) { - $choices = str_split($vote->reponses); - foreach ($choices as $i=>$choice) { - if (empty($result[$i])) { - $result[$i] = 0; - } - if ($choice == 2) { - $result[$i]++; - } - } - } - return $result; -} +$message = null; /* Services */ /*----------*/ $pollService = new PollService($connect); +$inputService = new InputService(); /* PAGE */ /* ---- */ @@ -78,7 +40,6 @@ if(!empty($_GET['poll'])) { $poll_id = filter_input(INPUT_GET, 'poll', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9]+$/']]); } - $poll = $pollService->findById($poll_id); if (!$poll) { @@ -96,27 +57,47 @@ if (!empty($_POST['edit_vote'])) { } +// Something to save (edit or add) if (!empty($_POST['save'])) { // Save edition of an old vote $editedVote = filter_input(INPUT_POST, 'save', FILTER_VALIDATE_INT); - $newChoices = []; + $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[012]$/']]); - // TODO Do this verification into a Service (maybe called 'InputService') - foreach($_POST['choices'] as $id=>$choice) { - $choice = filter_var($choice, FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[012]$/']]); - if ($choice !== false) { - $newChoices[$id] = $choice; - } + if (empty($name)) { + $message = new Message('danger', _('Name is incorrect.')); + } + if (count($choices) != count($_POST['choices'])) { + $message = new Message('danger', _('There is a problem with your choices.')); } - if (count($newChoices) == count($_POST['choices'])) { - $result = $pollService->updatePoll($poll_id, $editedVote, $newChoices); + if ($message == null) { + // Update vote + $result = $pollService->updateVote($poll_id, $editedVote, $choices); if ($result) { - $message = ['type'=>'success', 'message'=>_('Update vote successfully!')]; + $message = new Message('success', _('Update vote successfully!')); } else { - $message = ['type'=>'success', 'message'=>_('Update vote successfully!')]; + $message = new Message('danger', _('Update vote failed!')); + } + } +} elseif (isset($_POST['save'])) { // Add a new vote + $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9_ -]+$/i']]); + $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[012]$/']]); + + if (empty($name)) { + $message = new Message('danger', _('Name is incorrect.')); + } + if (count($choices) != count($_POST['choices'])) { + $message = new Message('danger', _('There is a problem with your choices.')); + } + + if ($message == null) { + // Add vote + $result = $pollService->addVote($poll_id, $name, $choices); + if ($result) { + $message = new Message('success', _('Update vote successfully!')); + } else { + $message = new Message('danger', _('Update vote failed!')); } } -} elseif (isset($_POST[''])) { // Add a new vote } // Retrieve data @@ -129,11 +110,12 @@ $comments = $pollService->allCommentsByPollId($poll_id); $smarty->assign('poll_id', $poll_id); $smarty->assign('poll', $poll); $smarty->assign('title', _('Poll') . ' - ' . $poll->title); -$smarty->assign('slots', split_slots($slots)); -$smarty->assign('votes', split_votes($votes)); -$smarty->assign('best_moments', computeBestMoments($votes)); +$smarty->assign('slots', $pollService->splitSlots($slots)); +$smarty->assign('votes', $pollService->splitVotes($votes)); +$smarty->assign('best_moments', $pollService->computeBestMoments($votes)); $smarty->assign('comments', $comments); $smarty->assign('editingVoteId', $editingVoteId); +$smarty->assign('message', $message); //Utils::debug(computeBestMoments($votes));exit; diff --git a/tpl/footer.tpl b/tpl/footer.tpl index af3f5eb..0313ca5 100644 --- a/tpl/footer.tpl +++ b/tpl/footer.tpl @@ -1,4 +1,4 @@ - +
    \ No newline at end of file diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 57d2f86..1bc08ff 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -5,6 +5,10 @@ {* Global informations about the current poll *} + {if !empty($message)} + + {/if} +
    @@ -12,7 +16,7 @@
    - + {_('Export to CSV')}
    @@ -172,7 +176,7 @@
    - +
    {$i = 0} @@ -181,19 +185,19 @@
    • - +
    • - +
    • - + @@ -203,7 +207,7 @@ {$i = $i+1} {/foreach} {/foreach} - + {/if} From 37735e8298ea76fe0d470a625a21f3f3c4ec9d4d Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 17 Dec 2014 13:18:59 +0100 Subject: [PATCH 021/151] Fix radio button 'no' --- tpl/studs.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 1bc08ff..abf2c36 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -197,7 +197,7 @@
    • - + From 8604cacc620363be49775a9f6ec7fc6b6ded6e3d Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 17 Dec 2014 13:22:09 +0100 Subject: [PATCH 022/151] studs.php: Move global form just around votes table --- tpl/studs.tpl | 232 +++++++++++++++++++++++++------------------------- 1 file changed, 116 insertions(+), 116 deletions(-) diff --git a/tpl/studs.tpl b/tpl/studs.tpl index abf2c36..729ea90 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -1,78 +1,78 @@ {extends file='page.tpl'} {block name=main} -
      - {* Global informations about the current poll *} +{* Global informations about the current poll *} - {if !empty($message)} - - {/if} +{if !empty($message)} + +{/if} -
      -
      -
      -

      {$poll->title}

      -
      -
      -
      - - {_('Export to CSV')} -
      +
      +
      +
      +

      {$poll->title}

      +
      +
      +
      + + {_('Export to CSV')}
      -
      -
      -
      -

      {_("Initiator of the poll")}

      -

      {$poll->admin_name}

      -
      - +
      +
      +
      +
      +

      {_("Initiator of the poll")}

      +

      {$poll->admin_name}

      - - {if !empty($poll->comment)} -
      -

      {_("Description")}


      -

      {$poll->comment}

      + - {/if}
      -
      - {* Information about voting *} - - {if $poll->active} -
      -

      {_("If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line.")}

      - -
      - {else} -
      -

      {_("The administrator locked this poll, votes and comments are frozen, it's not possible to participate anymore.")}

      - -
      - {/if} - - {* Scroll left and right *} - - - {* Vote table *} +{* Information about voting *} -

      {_('Votes of the poll')}

      -
      +{if $poll->active} +
      +

      {_("If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line.")}

      + +
      +{else} +
      +

      {_("The administrator locked this poll, votes and comments are frozen, it's not possible to participate anymore.")}

      + +
      +{/if} + +{* Scroll left and right *} + + + +{* Vote table *} + +

      {_('Votes of the poll')}

      +
      + @@ -227,73 +227,73 @@
      {_('Votes of the poll')} {$poll->title}
      -
      + +
      - {* Best votes listing *} +{* Best votes listing *} - {$max = max($best_moments)} - {if $max > 0} -
      - {if $count_bests == 1} -

      {_("Best choice")}

      -
      -

      {_("The best choice at this time is:")}

      - {elseif $count_bests > 1} -

      {_("Best choices")}

      -
      -

      {_("The bests choices at this time are:")}

      - {/if} +{$max = max($best_moments)} +{if $max > 0} +
      + {if $count_bests == 1} +

      {_("Best choice")}

      +
      +

      {_("The best choice at this time is:")}

      + {elseif $count_bests > 1} +

      {_("Best choices")}

      +
      +

      {_("The bests choices at this time are:")}

      + {/if} - {$i = 0} -
        - {foreach $slots as $slot} - {foreach $slot->moments as $moment} - {if $best_moments[$i] == $max} -
      • {$slot->day|date_format:$date_format.txt_full} - {$moment}
      • - {/if} - {$i = $i+1} - {/foreach} + {$i = 0} +
          + {foreach $slots as $slot} + {foreach $slot->moments as $moment} + {if $best_moments[$i] == $max} +
        • {$slot->day|date_format:$date_format.txt_full} - {$moment}
        • + {/if} + {$i = $i+1} {/foreach} -
        -

        {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

        -
      + {/foreach} +
    +

    {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

    +
    +{/if} + +{* Comments *} + +{if $poll->active} + + + {* Comment list *} + + {if $comments|count > 0} + {foreach $comments as $comment} +
    + {$comment->usercomment}  + {nl2br($comment->comment)} +
    + {/foreach} {/if} - {* Comments *} + {* Add comment form *} - {if $poll->active} -
    - - {* Comment list *} - - {if $comments|count > 0} - {foreach $comments as $comment} -
    - {$comment->usercomment}  - {nl2br($comment->comment)} +
    +
    +
    {_("Add a comment in the poll")} +
    +

    - {/foreach} - {/if} - - {* Add comment form *} - -
    -
    -
    {_("Add a comment in the poll")} -
    -

    -
    -
    -


    -

    -
    -

    -
    +
    +


    +

    -
    +

    +
    - {/if} - +
    +
    +{/if} {/block} \ No newline at end of file From 7837c01ba040404a41fc24a484dc63bdc7f037b5 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 17 Dec 2014 13:23:32 +0100 Subject: [PATCH 023/151] Fix form control when editing vote --- studs.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/studs.php b/studs.php index 8f61806..042d4ab 100644 --- a/studs.php +++ b/studs.php @@ -62,8 +62,8 @@ if (!empty($_POST['save'])) { // Save edition of an old vote $editedVote = filter_input(INPUT_POST, 'save', FILTER_VALIDATE_INT); $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[012]$/']]); - if (empty($name)) { - $message = new Message('danger', _('Name is incorrect.')); + if (empty($editedVote)) { + $message = new Message('danger', _('Something is going wrong...')); } if (count($choices) != count($_POST['choices'])) { $message = new Message('danger', _('There is a problem with your choices.')); From fcc478bb9306eea805173fce705cb445f910aa7e Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 17 Dec 2014 13:39:12 +0100 Subject: [PATCH 024/151] Add headers to th cells when editing vote --- studs.php | 6 ++++++ tpl/studs.tpl | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/studs.php b/studs.php index 042d4ab..f2850be 100644 --- a/studs.php +++ b/studs.php @@ -48,7 +48,10 @@ if (!$poll) { exit; } +// ------------------------------- // A vote is going to be edited +// ------------------------------- + if (!empty($_POST['edit_vote'])) { // TODO Try what does filter_input with a wrong value $editingVoteId = filter_input(INPUT_POST, 'edit_vote', FILTER_VALIDATE_INT); @@ -57,7 +60,10 @@ if (!empty($_POST['edit_vote'])) { } +// ------------------------------- // Something to save (edit or add) +// ------------------------------- + if (!empty($_POST['save'])) { // Save edition of an old vote $editedVote = filter_input(INPUT_POST, 'save', FILTER_VALIDATE_INT); $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[012]$/']]); diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 729ea90..ef76135 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -116,7 +116,7 @@ {if $editingVoteId == $vote->id} {foreach $vote->choices as $k=>$choice} - +
    • @@ -207,7 +207,7 @@ {$i = $i+1} {/foreach} {/foreach} - + {/if} From ab5f9e013a58e695c3472cc4b1621c849e89b258 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 17 Dec 2014 13:47:14 +0100 Subject: [PATCH 025/151] Implement comments functionnality --- app/classes/Framadate/FramaDB.php | 5 +++ .../Framadate/Services/PollService.php | 4 +++ studs.php | 35 ++++++++++++++++--- tpl/studs.tpl | 29 ++++++++------- 4 files changed, 56 insertions(+), 17 deletions(-) diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 184f7b6..7e1d8e5 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -84,4 +84,9 @@ class FramaDB return $prepared->execute([$choices, $poll_id, $vote_id]); } + function insertComment($poll_id, $name, $comment) { + $prepared = $this->prepare('INSERT INTO comments (id_sondage, usercomment, comment) VALUES (?,?,?)'); + return $prepared->execute([$poll_id, $name, $comment]); + } + } diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 51fa3e7..d37272f 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -39,6 +39,10 @@ class PollService { return $this->connect->insertVote($poll_id, $name, $choices); } + function addComment($poll_id, $name, $comment) { + return $this->connect->insertComment($poll_id, $name, $comment); + } + function computeBestMoments($votes) { $result = []; foreach ($votes as $vote) { diff --git a/studs.php b/studs.php index f2850be..400cd7a 100644 --- a/studs.php +++ b/studs.php @@ -18,13 +18,14 @@ */ use Framadate\Services\PollService; use Framadate\Services\InputService; -use Framadate\Utils; use Framadate\Message; +use Framadate\Utils; include_once __DIR__ . '/app/inc/init.php'; /* Variables */ /* --------- */ +$poll_id = null; $message = null; /* Services */ @@ -79,9 +80,9 @@ if (!empty($_POST['save'])) { // Save edition of an old vote // Update vote $result = $pollService->updateVote($poll_id, $editedVote, $choices); if ($result) { - $message = new Message('success', _('Update vote successfully!')); + $message = new Message('success', _('Update vote successfully.')); } else { - $message = new Message('danger', _('Update vote failed!')); + $message = new Message('danger', _('Update vote failed.')); } } } elseif (isset($_POST['save'])) { // Add a new vote @@ -99,13 +100,37 @@ if (!empty($_POST['save'])) { // Save edition of an old vote // Add vote $result = $pollService->addVote($poll_id, $name, $choices); if ($result) { - $message = new Message('success', _('Update vote successfully!')); + $message = new Message('success', _('Update vote successfully.')); } else { - $message = new Message('danger', _('Update vote failed!')); + $message = new Message('danger', _('Update vote failed.')); } } } +// ------------------------------- +// Add a comment +// ------------------------------- + +if (isset($_POST['add_comment'])) { + $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9_ -]+$/i']]); + $comment = filter_input(INPUT_POST, 'comment', FILTER_DEFAULT); + + if (empty($name)) { + $message = new Message('danger', _('Name is incorrect.')); + } + + if ($message == null) { + // Add comment + $result = $pollService->addComment($poll_id, $name, $comment); + if ($result) { + $message = new Message('success', _('Comment added.')); + } else { + $message = new Message('danger', _('Comment failed.')); + } + } + +} + // Retrieve data $slots = $pollService->allSlotsByPollId($poll_id); $votes = $pollService->allUserVotesByPollId($poll_id); diff --git a/tpl/studs.tpl b/tpl/studs.tpl index ef76135..dc7f0dc 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -281,19 +281,24 @@ {* Add comment form *}
      -
      -
      {_("Add a comment in the poll")} -
      -

      +
      +
      +
      {_("Add a comment to the poll")} +
      + + +
      +
      + + +
      +
      + +
      +
      -
      -


      -

      -
      -

      -
      -
      -
      +
      +
      {/if} {/block} \ No newline at end of file From 9284a5d62b95503d7f60d713ad3abf0fb853b54a Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 17 Dec 2014 13:48:03 +0100 Subject: [PATCH 026/151] Add licence informations on classes --- app/classes/Framadate/Choice.php | 17 +++++++++++++++++ app/classes/Framadate/Form.php | 17 +++++++++++++++++ app/classes/Framadate/FramaDB.php | 17 +++++++++++++++++ app/classes/Framadate/Message.php | 17 +++++++++++++++++ app/classes/Framadate/Services/InputService.php | 17 +++++++++++++++++ app/classes/Framadate/Services/PollService.php | 17 +++++++++++++++++ 6 files changed, 102 insertions(+) diff --git a/app/classes/Framadate/Choice.php b/app/classes/Framadate/Choice.php index 6375945..aab438c 100644 --- a/app/classes/Framadate/Choice.php +++ b/app/classes/Framadate/Choice.php @@ -1,4 +1,21 @@ Date: Wed, 17 Dec 2014 13:52:52 +0100 Subject: [PATCH 027/151] Remove old code + Add doc --- app/classes/Framadate/Utils.php | 36 +++++++++------------------------ studs.php | 2 -- 2 files changed, 9 insertions(+), 29 deletions(-) diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index 047e2e1..cb8a078 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -82,17 +82,6 @@ class Utils } - public static function check_table_sondage() - { - global $connect; - - if (in_array('sondage', $connect->MetaTables('TABLES'))) { - return true; - } - - return false; - } - /** * Check if an email address is valid using PHP filters * @@ -157,22 +146,6 @@ class Utils mail($to, $subject, $body, $headers, $param); } - /** - * Fonction vérifiant l'existance et la valeur non vide d'une clé d'un tableau - * @deprecated - * @param string $name La clé à tester - * @param array $tableau Le tableau où rechercher la clé ($_POST par défaut) - * @return bool Vrai si la clé existe et renvoie une valeur non vide - */ - /*public static function issetAndNoEmpty($name, $tableau = null) - { - if (is_null($tableau)) { - $tableau = $_POST; - } - - return isset($tableau[$name]) && ! empty($tableau[$name]); - }*/ - /** * Fonction permettant de générer les URL pour les sondage * @param string $id L'identifiant du sondage @@ -200,6 +173,7 @@ class Utils /** * Completly delete data about the given poll + * TODO Move this function to FramaDB */ public static function removeSondage($poll_id) { @@ -219,6 +193,10 @@ class Utils } + /** + * Clean old poll (end_date < now). + * TODO Move this function to FramaDB + */ public static function cleaningOldPolls($log_txt) { global $connect; @@ -234,6 +212,10 @@ class Utils $connect->commit(); } + /** + * This method pretty prints an object to the page framed by pre tags. + * @param Object $object The object to print. + */ public static function debug($object) { echo '
      ';
      diff --git a/studs.php b/studs.php
      index 400cd7a..3fba002 100644
      --- a/studs.php
      +++ b/studs.php
      @@ -148,6 +148,4 @@ $smarty->assign('comments', $comments);
       $smarty->assign('editingVoteId', $editingVoteId);
       $smarty->assign('message', $message);
       
      -//Utils::debug(computeBestMoments($votes));exit;
      -
       $smarty->display('studs.tpl');
      
      From 7c5ba2eb17bcc421ac981ff7bd78b573e60bd7a6 Mon Sep 17 00:00:00 2001
      From: Olivier PEREZ 
      Date: Wed, 17 Dec 2014 23:12:05 +0100
      Subject: [PATCH 028/151] Split parts of studs.tpl into severals sub-templates.
      
      ---
       app/inc/i18n.php        |   2 +-
       tpl/part/comments.tpl   |  36 ++++++
       tpl/part/poll_info.tpl  |  32 +++++
       tpl/part/vote_table.tpl | 192 ++++++++++++++++++++++++++++
       tpl/studs.tpl           | 270 ++--------------------------------------
       5 files changed, 268 insertions(+), 264 deletions(-)
       create mode 100644 tpl/part/comments.tpl
       create mode 100644 tpl/part/poll_info.tpl
       create mode 100644 tpl/part/vote_table.tpl
      
      diff --git a/app/inc/i18n.php b/app/inc/i18n.php
      index 31c6f2d..5040073 100644
      --- a/app/inc/i18n.php
      +++ b/app/inc/i18n.php
      @@ -50,7 +50,7 @@ if (strtoupper(substr(PHP_OS,0,3))=='WIN'){
       putenv('LANGUAGE=');//sert à quoi?
       setlocale(LC_ALL, $locale);
       setlocale(LC_TIME, $locale);
      -setlocale(LC_MESSAGES, $locale);
      +//setlocale(LC_MESSAGES, $locale);
       
       $domain = 'Studs';
       bindtextdomain($domain, 'locale');
      diff --git a/tpl/part/comments.tpl b/tpl/part/comments.tpl
      new file mode 100644
      index 0000000..4e9f09c
      --- /dev/null
      +++ b/tpl/part/comments.tpl
      @@ -0,0 +1,36 @@
      +
      +
      +{* Comment list *}
      +
      +{if $comments|count > 0}
      +    {foreach $comments as $comment}
      +        
      + {$comment->usercomment}  + {nl2br($comment->comment)} +
      + {/foreach} +{/if} + +{* Add comment form *} +{if $active} +
      +
      +
      +
      {_("Add a comment to the poll")} +
      + + +
      +
      + + +
      +
      + +
      +
      +
      +
      +
      +
      +{/if} \ No newline at end of file diff --git a/tpl/part/poll_info.tpl b/tpl/part/poll_info.tpl new file mode 100644 index 0000000..d0108e1 --- /dev/null +++ b/tpl/part/poll_info.tpl @@ -0,0 +1,32 @@ +
      +
      +
      +

      {$poll->title}

      +
      +
      +
      + + {_('Export to CSV')} +
      +
      +
      +
      +
      +
      +

      {_("Initiator of the poll")}

      +

      {$poll->admin_name}

      +
      + +
      + + {if !empty($poll->comment)} +
      +

      {_("Description")}


      +

      {$poll->comment}

      +
      + {/if} +
      +
      \ No newline at end of file diff --git a/tpl/part/vote_table.tpl b/tpl/part/vote_table.tpl new file mode 100644 index 0000000..b9f9186 --- /dev/null +++ b/tpl/part/vote_table.tpl @@ -0,0 +1,192 @@ +

      {_('Votes of the poll')}

      + +
      +
      + + + + + + {foreach $slots as $id=>$slot} + + {for $foo=0 to ($slot->moments|count)-1} + {append var='headersM' value=$id} + {/for} + {/foreach} + + + + + {foreach $slots as $id=>$slot} + + {/foreach} + + + + + {$headersDCount=0} + {foreach $slots as $slot} + {foreach $slot->moments as $id=>$moment} + + {append var='headersD' value=$headersDCount} + {$headersDCount = $headersDCount+1} + {/foreach} + {/foreach} + + + + + {foreach $votes as $vote} + + {* Edited line *} + + + + {if $editingVoteId == $vote->id} + {foreach $vote->choices as $k=>$choice} + + + {/foreach} + + {else} + + {* Voted line *} + + {foreach $vote->choices as $k=>$choice} + + {if $choice==2} + + {elseif $choice==1} + + {else} + + {/if} + + {/foreach} + + {if $active && $poll->editable} + + {else} + + {/if} + {/if} + + {/foreach} + + {* Line to add a new vote *} + + {if $active && $editingVoteId == 0} + + + {$i = 0} + {foreach $slots as $slot} + {foreach $slot->moments as $moment} + + {$i = $i+1} + {/foreach} + {/foreach} + + + {/if} + + {* Line displaying best moments *} + {$count_bests = 0} + + + {$max = max($best_moments)} + {foreach $best_moments as $best_moment} + {if $max == $best_moment} + {$count_bests = $count_bests +1} + + {else} + + {/if} + {/foreach} + + +
      {_('Votes of the poll')} {$poll->title}
      {$slot->day|date_format:'%B %Y'}
      {$slot->day|date_format:$date_format.txt_day}
      {$moment}
      {$vote->name} +
        +
      • + + +
      • +
      • + + +
      • +
      • + + +
      • +
      +
      {_('Yes')}(){_('Ifneedbe')}{_('No')} + +
      +
      + + +
      +
      +
        +
      • + + +
      • +
      • + + +
      • +
      • + + +
      • +
      +
      {_("Addition")}{$max}
      +
      +
      + +{* Best votes listing *} + +{$max = max($best_moments)} +{if $max > 0} +
      + {if $count_bests == 1} +

      {_("Best choice")}

      +
      +

      {_("The best choice at this time is:")}

      + {elseif $count_bests > 1} +

      {_("Best choices")}

      +
      +

      {_("The bests choices at this time are:")}

      + {/if} + + + {$i = 0} +
        + {foreach $slots as $slot} + {foreach $slot->moments as $moment} + {if $best_moments[$i] == $max} +
      • {$slot->day|date_format:$date_format.txt_full} - {$moment}
      • + {/if} + {$i = $i+1} + {/foreach} + {/foreach} +
      +

      {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

      +
      +
      +{/if} \ No newline at end of file diff --git a/tpl/studs.tpl b/tpl/studs.tpl index dc7f0dc..4cba8d6 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -2,44 +2,13 @@ {block name=main} + {if !empty($message)} + + {/if} + {* Global informations about the current poll *} -{if !empty($message)} - -{/if} - -
      -
      -
      -

      {$poll->title}

      -
      -
      -
      - - {_('Export to CSV')} -
      -
      -
      -
      -
      -
      -

      {_("Initiator of the poll")}

      -

      {$poll->admin_name}

      -
      - -
      - - {if !empty($poll->comment)} -
      -

      {_("Description")}


      -

      {$poll->comment}

      -
      - {/if} -
      -
      +{include 'part/poll_info.tpl'} {* Information about voting *} @@ -70,235 +39,10 @@ {* Vote table *} -

      {_('Votes of the poll')}

      -
      -
      - - - - - - {foreach $slots as $id=>$slot} - - {for $foo=0 to ($slot->moments|count)-1} - {append var='headersM' value=$id} - {/for} - {/foreach} - - - - - {foreach $slots as $id=>$slot} - - {/foreach} - - - - - {$headersDCount=0} - {foreach $slots as $slot} - {foreach $slot->moments as $id=>$moment} - - {append var='headersD' value=$headersDCount} - {$headersDCount = $headersDCount+1} - {/foreach} - {/foreach} - - - - - {foreach $votes as $vote} - - {* Edited line *} - - - - {if $editingVoteId == $vote->id} - {foreach $vote->choices as $k=>$choice} - - - {/foreach} - - {else} - - {* Voted line *} - - {foreach $vote->choices as $k=>$choice} - - {if $choice==2} - - {else if $choice==1} - - {else} - - {/if} - - {/foreach} - - {if $poll->active && $poll->editable} - - {else} - - {/if} - {/if} - - {/foreach} - - {* Line to add a new vote *} - - {if $poll->active && $editingVoteId == 0} - - - {$i = 0} - {foreach $slots as $slot} - {foreach $slot->moments as $moment} - - {$i = $i+1} - {/foreach} - {/foreach} - - - {/if} - - {* Line displaying best moments *} - {$count_bests = 0} - - - {$max = max($best_moments)} - {foreach $best_moments as $best_moment} - {if $max == $best_moment} - {$count_bests = $count_bests +1} - - {else} - - {/if} - {/foreach} - - -
      {_('Votes of the poll')} {$poll->title}
      {$slot->day|date_format:'%B %Y'}
      {$slot->day|date_format:$date_format.txt_day}
      {$moment}
      {$vote->name} -
        -
      • - - -
      • -
      • - - -
      • -
      • - - -
      • -
      -
      {_('Yes')}(){_('Ifneedbe')}{_('No')} - -
      -
      - - -
      -
      -
        -
      • - - -
      • -
      • - - -
      • -
      • - - -
      • -
      -
      {_("Addition")}{$max}
      -
      -
      - -{* Best votes listing *} - -{$max = max($best_moments)} -{if $max > 0} -
      - {if $count_bests == 1} -

      {_("Best choice")}

      -
      -

      {_("The best choice at this time is:")}

      - {elseif $count_bests > 1} -

      {_("Best choices")}

      -
      -

      {_("The bests choices at this time are:")}

      - {/if} - - - {$i = 0} -
        - {foreach $slots as $slot} - {foreach $slot->moments as $moment} - {if $best_moments[$i] == $max} -
      • {$slot->day|date_format:$date_format.txt_full} - {$moment}
      • - {/if} - {$i = $i+1} - {/foreach} - {/foreach} -
      -

      {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

      -
      -
      -{/if} +{include 'part/vote_table.tpl' active=$poll->active} {* Comments *} -{if $poll->active} - +{include 'part/comments.tpl' active=$poll->active comments=$comments} - {* Comment list *} - - {if $comments|count > 0} - {foreach $comments as $comment} -
      - {$comment->usercomment}  - {nl2br($comment->comment)} -
      - {/foreach} - {/if} - - {* Add comment form *} - -
      -
      -
      -
      {_("Add a comment to the poll")} -
      - - -
      -
      - - -
      -
      - -
      -
      -
      -
      -
      -
      -{/if} {/block} \ No newline at end of file From 844315ada4ae8b624666bbdd8e28a4336278c770 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 17 Dec 2014 23:20:12 +0100 Subject: [PATCH 029/151] Recreate adminstuds.php with Smarty style (Work in progress) --- adminstuds.php | 1231 ++------------------------------------------ old_adminstuds.php | 1214 +++++++++++++++++++++++++++++++++++++++++++ studs.php | 4 +- 3 files changed, 1260 insertions(+), 1189 deletions(-) create mode 100644 old_adminstuds.php diff --git a/adminstuds.php b/adminstuds.php index 53a0122..ec82d51 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -16,1199 +16,56 @@ * Auteurs de STUdS (projet initial) : Guilhem BORGHESI (borghesi@unistra.fr) et Raphaël DROZ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ -namespace Framadate; +use Framadate\Services\PollService; +use Framadate\Services\InputService; +use Framadate\Message; +use Framadate\Utils; -session_start(); - -//setlocale(LC_TIME, "fr_FR"); include_once __DIR__ . '/app/inc/init.php'; -if (file_exists('bandeaux_local.php')) { - include_once('bandeaux_local.php'); -} else { - include_once('bandeaux.php'); -} +/* Variables */ +/* --------- */ +$admin_poll_id = null; +$poll_id = null; +$poll = null; +$message = null; -// recuperation du numero de sondage admin (24 car.) dans l'URL -if (!empty($_GET['sondage']) && is_string($_GET['sondage']) && strlen($_GET['sondage']) === 24) { - $admin_poll_id = $_GET["sondage"]; - // on découpe le résultat pour avoir le numéro de sondage (16 car.) +/* Services */ +/*----------*/ + +$pollService = new PollService($connect); +$inputService = new InputService(); + +/* PAGE */ +/* ---- */ + +if(!empty($_GET['poll']) && strlen($_GET['poll']) === 24) { + $admin_poll_id = filter_input(INPUT_GET, 'poll', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9]+$/']]); $poll_id = substr($admin_poll_id, 0, 16); + $poll = $pollService->findById($poll_id); } -if (preg_match(";[\w\d]{24};i", $admin_poll_id)) { - $prepared = $connect->prepare('SELECT * FROM sondage WHERE admin_poll_id = ?'); - $prepared->execute(array($admin_poll_id)); - $poll = $prepared->fetch(); - $prepared->closeCursor(); - - $prepared = $connect->prepare('SELECT * FROM sujet_studs WHERE id_sondage = ?'); - $prepared->execute(array($poll_id)); - $sujets = $prepared->fetchAll(); - - $prepared = $connect->prepare('SELECT * FROM user_studs WHERE id_sondage = ? order by id_users'); - $prepared->execute(array($poll_id)); - $users = $prepared->fetchAll(); +if (!$poll) { + $smarty->assign('error', 'This poll doesn\'t exist'); + $smarty->display('error.tpl'); + exit; } -//verification de l'existence du sondage, s'il n'existe pas on met une page d'erreur -if (!$poll || !$sujets) { - Utils::print_header( _('Error!')); - - bandeau_titre(_('Error!')); - - echo ' -
      -

      ' . _('This poll doesn\'t exist !') . '

      -

      ' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

      -
      '."\n"; - - bandeau_pied(); - - die(); -} - -// Send email (only once during the session) to alert admin of the change he made. ==> two modifications (comment, title, description, ...) on differents polls in the same session will generate only one mail. -$email_admin = $poll->admin_mail; -$poll_title = $poll->title; -$smtp_allowed = $config['use_smtp']; -function send_mail_admin() { - global $email_admin; - global $poll_title; - global $admin_poll_id; - global $smtp_allowed; - if($smtp_allowed==true){ - if(!isset($_SESSION['mail_admin_sent'])) { - Utils::sendEmail( $email_admin, - _("[ADMINISTRATOR] New settings for your poll") . ' ' . stripslashes( $poll_title ), - _("You have changed the settings of your poll. \nYou can modify this poll with this link") . - " :\n\n" . Utils::getUrlSondage($admin_poll_id, true) . "\n\n" . - _("Thanks for your confidence.") . "\n" . NOMAPPLICATION - ); - $_SESSION["mail_admin_sent"]=true; - } - } - -} - -//si la valeur du nouveau titre est valide et que le bouton est activé -if (isset($_POST["boutonnouveautitre"])) { - if (Utils::issetAndNoEmpty('nouveautitre') === false) { - $err |= TITLE_EMPTY; - } else { - //Update SQL database with new title - $nouveautitre = htmlentities(html_entity_decode($_POST['nouveautitre'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - $sql = 'UPDATE sondage SET titre = '.$connect->Param('nouveautitre').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - - //Email sent to the admin - if ($connect->Execute($sql, array($nouveautitre, $poll_id))) { - send_mail_admin(); - } - } -} - -// si le bouton est activé, quelque soit la valeur du champ textarea -if (isset($_POST['boutonnouveauxcommentaires'])) { - if (empty($_POST['nouveautitre'])) { - $err |= COMMENT_EMPTY; - } else { - $commentaires = htmlentities(html_entity_decode($_POST['nouveauxcommentaires'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - - //Update SQL database with new description - $prepared = $connect->prepare('UPDATE sondage SET commentaires = ? WHERE id_sondage = ?'); - $prepared->execute(array($commentaires, $poll_id)); - - //Email sent to the admin - if ($connect->Execute($sql, array($commentaires, $poll_id))) { - send_mail_admin(); - } - } -} - -//si la valeur de la nouvelle adresse est valide et que le bouton est activé -if (isset($_POST["boutonnouvelleadresse"])) { - if (empty($_POST['nouvelleadresse']) || Utils::isValidEmail($_POST["nouvelleadresse"]) === false) { - $err |= INVALID_EMAIL; - } else { - $nouvelleadresse = htmlentities(html_entity_decode($_POST['nouvelleadresse'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - - //Update SQL database with new email - $prepared = $connect->prepare('UPDATE sondage SET mail_admin = ? WHERE id_sondage = ?'); - $executed = $prepared->execute(array($nouvelleadresse, $poll_id)); - - //Email sent to the admin - if ($executed) { - send_mail_admin(); - } - } -} - -// TODO OPZ : Revoir ce que fait ce truc exactament -//New poll rules -if (isset($_POST["btn_poll_rules"])) { - echo ''; - if($_POST['poll_rules'] == '+') { - $new_poll_rules = substr($dsondage->format, 0, 1).'+'; - } elseif($_POST['poll_rules'] == '-') { - $new_poll_rules = substr($dsondage->format, 0, 1).'-'; - } else { - $new_poll_rules = substr($dsondage->format, 0, 1); - } - - //Update SQL database with new rules - $prepared = $connect->prepare('UPDATE sondage SET format = ? WHERE id_sondage = ?'); - $executed = $prepared->execute(array($new_poll_rules, $poll_id)); - - //Email sent to the admin - if ($executed) { - send_mail_admin(); - } -} - -// reload -// TODO OPZ Pourquoi recharger -// $dsujet= $sujets->FetchObject(false); -// $dsondage= $sondage->FetchObject(false); - -if (isset($_POST['ajoutsujet'])) { - Utils::print_header( _('Add a column') .' - ' . stripslashes($poll->title)); - - bandeau_titre(_('Make your polls')); - - //on recupere les données et les sujets du sondage - - echo ' -
      -
      -
      -

      ' . _("Column's adding") . '

      '."\n"; - - if ($poll->format == "A"){ - echo ' -
      - -
      - -
      -
      '."\n"; - } else { - // ajout d'une date avec creneau horaire - echo ' -

      '. _("You can add a new scheduling date to your poll.").'
      '._("If you just want to add a new hour to an existant date, put the same date and choose a new hour.") .'

      - -
      - -
      -
      - - -
      - '. _("(dd/mm/yyyy)") .' -
      -
      -
      - -
      - -
      -
      '; - } - echo ' -

      - - -

      -
      -
      -
      '; - - bandeau_pied(); - - die(); -} - -if (isset($_POST["suppressionsondage"])) { - Utils::print_header( _("Confirm removal of your poll") .' - ' . stripslashes( $dsondage->title )); - - bandeau_titre(_("Confirm removal of your poll")); - - echo ' -
      -
      -

      ' . _("Confirm removal of your poll") . '

      -

      -

      -
      -
      '; - - bandeau_pied(); - - die(); -} - -// Remove all the comments -if (isset($_POST['removecomments'])) { - $sql = 'DELETE FROM comments WHERE id_sondage='.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $cleaning = $connect->Execute($sql, array($poll_id)); -} - -// Remove all the votes -if (isset($_POST["removevotes"])) { - $sql = 'DELETE FROM user_studs WHERE id_sondage='.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $cleaning = $connect->Execute($sql, array($poll_id)); -} - -//action si bouton confirmation de suppression est activé -if (isset($_POST["confirmesuppression"])) { - $nbuser=$user_studs->RecordCount(); - $date=date('H:i:s d/m/Y:'); - - if (Utils::remove_sondage($connect, $poll_id)) { - // on ecrit dans le fichier de logs la suppression du sondage - error_log($date . " SUPPRESSION: $dsondage->id_sondage\t$dsondage->format\t$dsondage->nom_admin\t$dsondage->mail_admin\n", 3, 'admin/logs_studs.txt'); - - // Email sent - send_mail_admin(); - //affichage de l'ecran de confirmation de suppression de sondage - Utils::print_header(_("Your poll has been removed!")); - - bandeau_titre(_("Make your polls")); - - echo ' -
      -

      ' . _("Your poll has been removed!") . '

      -

      ' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

      -
      - '."\n"; - - bandeau_pied(); - - die(); - } -} - -// quand on ajoute un commentaire utilisateur -if (isset($_POST['ajoutcomment'])) { - if (empty($_POST['commentuser'])) { - $err |= COMMENT_USER_EMPTY; - } else { - $comment_user = htmlentities(html_entity_decode($_POST["commentuser"], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - } - - if(empty($_POST['comment'])) { - $err |= COMMENT_EMPTY; - } - - if (!empty($_POST['comment']) && !Utils::is_error(COMMENT_EMPTY) && !Utils::is_error(NO_POLL) && !Utils::is_error(COMMENT_USER_EMPTY)) { - $comment = htmlentities(html_entity_decode($_POST["comment"], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - - // Check for doublons - $comment_doublon = false; - $req = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; - $sql = $connect->Prepare($req); - $comment_user_doublon = $connect->Execute($sql, array($poll_id)); - if ($comment_user_doublon->RecordCount() != 0) { - while ( $dcomment_user_doublon=$comment_user_doublon->FetchNextObject(false)) { - if($dcomment_user_doublon->comment == $comment && $dcomment_user_doublon->usercomment == $comment_user) { - $comment_doublon = true; - }; - } - } - - if(!$comment_doublon) { - $req = 'INSERT INTO comments (id_sondage, comment, usercomment) VALUES ('. - $connect->Param('id_sondage').','. - $connect->Param('comment').','. - $connect->Param('comment_user').')'; - $sql = $connect->Prepare($req); - - $comments = $connect->Execute($sql, array($poll_id, $comment, $comment_user)); - if ($comments === false) { - $err |= COMMENT_INSERT_FAILED; - } - } - } -} - -$nbcolonnes = count($sujets); -$nblignes = count($users); - -//si il n'y a pas suppression alors on peut afficher normalement le tableau - -//action si le bouton participer est cliqué -if (isset($_POST["boutonp"])) { - //si on a un nom dans la case texte - if (!empty($_POST['nom'])){ - $nouveauchoix = ''; - $erreur_prenom = false; - - for ($i=0;$i<$nbcolonnes;$i++){ - // radio checked 1 = Yes, 2 = Ifneedbe, 0 = No - if (isset($_POST["choix$i"])) { - switch ($_POST["choix$i"]) { - case 1: $nouveauchoix .= "1";break; - case 2: $nouveauchoix .= "2";break; - default: $nouveauchoix .= "0";break; - } - } - } - - $nom = htmlentities(html_entity_decode($_POST["nom"], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - - while($user = $user_studs->FetchNextObject(false)) { - if ($nom == $user->nom){ - $erreur_prenom="yes"; - } - } - - // Ecriture des choix de l'utilisateur dans la base - if (!$erreur_prenom) { - $sql = 'INSERT INTO user_studs (nom, id_sondage, reponses) VALUES ('. - $connect->Param('nom').','. - $connect->Param('numsondage').','. - $connect->Param('nouveauchoix').')'; - - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($nom, $poll_id, $nouveauchoix)); - } - } -} - - -//action quand on ajoute une colonne au format AUTRE -if (isset($_POST["ajoutercolonne"]) && !empty($_POST['nouvellecolonne']) && $poll->format == "A") { - $nouveauxsujets=$dsujet->sujet; - - //on rajoute la valeur a la fin de tous les sujets deja entrés - $nouveauxsujets.=","; - $nouveauxsujets.=str_replace(","," ",$_POST["nouvellecolonne"]); - $nouveauxsujets = htmlentities(html_entity_decode($nouveauxsujets, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - - //mise a jour avec les nouveaux sujets dans la base - $sql = 'UPDATE sujet_studs SET sujet = '.$connect->Param('nouveauxsujets').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - if ($connect->Execute($sql, array($nouveauxsujets, $poll_id))) { - send_mail_admin(); - } -} - - -// [begin] action quand on ajoute une colonne au format DATE -if (isset($_POST['ajoutercolonne']) && $dsondage->format == 'D') { - - if (!empty($_POST["newdate"])) { - $new_choice = mktime(0, 0, 0, substr($_POST["newdate"],3,2), substr($_POST["newdate"],0,2), substr($_POST["newdate"],6,4)); - - if (!empty($_POST["newhour"])){ - $new_choice .= '@' . $_POST["newhour"]; - } - - - - - - // TODO OPZ Delete the code below - // TODO OPZ Insert new choice - // TODO OPZ Update users votes (add "0" in the right column^^) - - - - //on rajoute la valeur dans les valeurs - $datesbase = explode(",",$dsujet->sujet); - $taillebase = sizeof($datesbase); - - //recherche de l'endroit de l'insertion de la nouvelle date dans les dates deja entrées dans le tableau - if ($nouvelledate < $datesbase[0]) { - $cleinsertion = 0; - } elseif ($nouvelledate > $datesbase[$taillebase-1]) { - $cleinsertion = count($datesbase); - } else { - for ($i = 0; $i < count($datesbase); $i++) { - $j = $i + 1; - if ($nouvelledate > $datesbase[$i] && $nouvelledate < $datesbase[$j]) { - $cleinsertion = $j; - } - } - } - - array_splice($datesbase, $cleinsertion, 0, $nouvelledate); - $cle = array_search($nouvelledate, $datesbase); - $dateinsertion = ''; - for ($i = 0; $i < count($datesbase); $i++) { - $dateinsertion.=","; - $dateinsertion.=$datesbase[$i]; - } - - $dateinsertion = substr("$dateinsertion", 1); - - //mise a jour avec les nouveaux sujets dans la base - //if (isset($erreur_ajout_date) && !$erreur_ajout_date){ - $sql = 'UPDATE sujet_studs SET sujet = '.$connect->Param('dateinsertion').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($dateinsertion, $poll_id)); - - if ($nouvelledate > strtotime($dsondage->date_fin)) { - $date_fin=$nouvelledate+200000; - $sql = 'UPDATE sondage SET date_fin = '.$connect->Param('date_fin').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($date_fin, $poll_id)); - } - //} - - //mise a jour des reponses actuelles correspondant au sujet ajouté - $sql = 'UPDATE user_studs SET reponses = '.$connect->Param('reponses').' WHERE nom = '.$connect->Param('nom').' AND id_users='.$connect->Param('id_users'); - $sql = $connect->Prepare($sql); - while ($data = $user_studs->FetchNextObject(false)) { - $ensemblereponses=$data->reponses; - $newcar = ''; - - //parcours de toutes les réponses actuelles - for ($j = 0; $j < $nbcolonnes; $j++) { - $car=substr($ensemblereponses,$j,1); - - //si les reponses ne concerne pas la colonne ajoutée, on concatene - if ($j==$cle) { - $newcar.="0"; - } - - $newcar.=$car; - } - - //mise a jour des reponses utilisateurs dans la base - if (isset($erreur_ajout_date) && !$erreur_ajout_date){ - $connect->Execute($sql, array($newcar, $data->nom, $data->id_users)); - } - } - - //Email sent to the admin - send_mail_admin(); - - } else { - $erreur_ajout_date="yes"; - } -} -// [end] action quand on ajoute une colonne au format DATE - - -//suppression de ligne dans la base -for ($i = 0; $i < $nblignes; $i++) { - if (isset($_POST["effaceligne$i"])) { - $compteur=0; - $prepared = $connect->prepare('DELETE FROM user_studs WHERE nom = ? AND id_users = ?'); - - foreach ($users as $user) { - if ($compteur==$i){ - $prepared->execute(array($user->nom, $user->id_users)); - } - - $compteur++; - } - } -} - - -// TODO OPZ Revoir toute cette partie suppression d'un commentaire utilisateur -/*$sql = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; -$sql = $connect->Prepare($sql); -$comment_user = $connect->Execute($sql, array($poll_id)); -$i = 0; -while ($dcomment = $comment_user->FetchNextObject(false)) { - if (isset($_POST['suppressioncomment'.$i])) { - $sql = 'DELETE FROM comments WHERE id_comment = '.$connect->Param('id_comment'); - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($dcomment->id_comment)); - } - - $i++; -} -*/ - -//on teste pour voir si une ligne doit etre modifiée -$testmodifier = false; -$testligneamodifier = false; - -for ($i = 0; $i < $nblignes; $i++) { - if (isset($_POST["modifierligne$i"])) { - $ligneamodifier=$i; - $testligneamodifier="true"; - } - - //test pour voir si une ligne est a modifier - if (isset($_POST["validermodifier$i"])) { - $modifier=$i; - $testmodifier="true"; - } -} - - -//si le test est valide alors on affiche des checkbox pour entrer de nouvelles valeurs -if ($testmodifier) { - $nouveauchoix = ''; - for ($i = 0; $i < $nbcolonnes; $i++) { - // radio checked 1 = Yes, 2 = Ifneedbe, 0 = No - if (isset($_POST["choix$i"])) { - switch ($_POST["choix$i"]) { - case 1: $nouveauchoix .= "1";break; - case 2: $nouveauchoix .= "2";break; - default: $nouveauchoix .= "0";break; - } - } - } - - $compteur=0; - - while ($data=$user_studs->FetchNextObject(false)) { - //mise a jour des données de l'utilisateur dans la base SQL - if ($compteur==$modifier) { - $sql = 'UPDATE user_studs SET reponses = '.$connect->Param('reponses').' WHERE nom = '.$connect->Param('nom').' AND id_users = '.$connect->Param('id_users'); - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($nouveauchoix, $data->nom, $data->id_users)); - } - - $compteur++; - } -} - - -//suppression de colonnes dans la base -for ($i = 0; $i < $nbcolonnes; $i++) { - if ((isset($_POST["effacecolonne$i"])) && $nbcolonnes > 1){ - $sujets = explode(",",$dsujet->sujet); - //sort($toutsujet, SORT_NUMERIC); - $j = 0; - $nouveauxsujets = ''; - - //parcours de tous les sujets actuels - while (isset($sujets[$j])) { - //si le sujet n'est pas celui qui a été effacé alors on concatene - if ($i != $j) { - $nouveauxsujets .= ','; - $nouveauxsujets .= $sujets[$j]; - } - - $j++; - } - - //on enleve la virgule au début - $nouveauxsujets = substr("$nouveauxsujets", 1); - - //nettoyage des reponses actuelles correspondant au sujet effacé - $compteur = 0; - $sql = 'UPDATE user_studs SET reponses = '.$connect->Param('reponses').' WHERE nom = '.$connect->Param('nom').' AND id_users = '.$connect->Param('id_users'); - $sql = $connect->Prepare($sql); - - while ($data = $user_studs->FetchNextObject(false)) { - $newcar = ''; - $ensemblereponses = $data->reponses; - - //parcours de toutes les réponses actuelles - for ($j = 0; $j < $nbcolonnes; $j++) { - $car=substr($ensemblereponses, $j, 1); - //si les reponses ne concerne pas la colonne effacée, on concatene - if ($i != $j) { - $newcar .= $car; - } - } - - $compteur++; - - //mise a jour des reponses utilisateurs dans la base - $connect->Execute($sql, array($newcar, $data->nom, $data->id_users)); - } - - //mise a jour des sujets dans la base - $sql = 'UPDATE sujet_studs SET sujet = '.$connect->Param('nouveauxsujets').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($nouveauxsujets, $poll_id)); - } -} - - -// TODO OPZ Déjà fait en début de fichier recuperation des donnes de la base -/*$sql = 'SELECT * FROM sondage WHERE id_sondage_admin = '.$connect->Param('numsondageadmin'); -$sql = $connect->Prepare($sql); -$sondage = $connect->Execute($sql, array($admin_poll_id)); - -if ($sondage !== false) { - $sql = 'SELECT * FROM sujet_studs WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $sujets = $connect->Execute($sql, array($poll_id)); - - $sql = 'SELECT * FROM user_studs WHERE id_sondage = '.$connect->Param('numsondage').' order by id_users'; - $sql = $connect->Prepare($sql); - $user_studs = $connect->Execute($sql, array($poll_id)); -} else { - - Utils::print_header(_("Error!")); - bandeau_titre(_("Error!")); - - echo ' -
      -

      ' . _("This poll doesn't exist !") . '

      -

      ' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

      -
      '."\n"; - - bandeau_pied(); - - die(); -}*/ - -// Errors -$errors = ''; -if ((isset($_POST["boutonp"])) && $_POST["nom"] == "") { - $errors .= '
    • ' . _("Enter a name") . '
    • '; -} -if (isset($erreur_prenom) && $erreur_prenom) { - $errors .= '
    • ' . _("The name you've chosen already exist in this poll!") . '
    • '; -} -if (isset($erreur_injection) && $erreur_injection) { - $errors .= '
    • ' . _("Characters \" ' < et > are not permitted") . '
    • '; -} -if (isset($erreur_ajout_date) && $erreur_ajout_date) { - $errors .= '
    • ' . _("The date is not correct !") . '
    • '; -} - -//Poll title, description and email values -$title = (isset($_POST["boutonnouveautitre"]) && !empty($_POST['nouveautitre'])) ? htmlentities(html_entity_decode($_POST['nouveautitre'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8') : stripslashes( $poll->title); -$description = (isset($_POST["nouveauxcommentaires"])) ? stripslashes(htmlentities(html_entity_decode($_POST['nouveauxcommentaires'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8')) : stripslashes( $poll->comment); -$email_admin = (isset($_POST["boutonnouvelleadresse"]) && !empty($_POST['nouvelleadresse'])) ? htmlentities(html_entity_decode($_POST['nouvelleadresse'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8') : stripslashes( $poll->admin_mail ); - -//Poll format (locked A-/D-, open A/D, editable A+/D+) -$poll_rules = (isset($_POST["poll_rules"]) && !empty($_POST['btn_poll_rules'])) ? $_POST["poll_rules"] : substr($poll->format, 1, 1); // TODO OPZ Handle comment disabling -$poll_rules_opt1 = '';$poll_rules_opt2 = '';$poll_rules_opt3 = ''; -if($poll->editable) { - $poll_rules_text = ' '. _("Votes are editable"); - $poll_rules_opt3 = 'selected'; -} elseif($poll_rules == '-') { - $poll_rules_text = ' '. _("Votes and comments are locked"); - $poll_rules_opt1 = 'selected'; -} else { - $poll_rules_text = ' '. _("Votes and comments are open"); - $poll_rules_opt2 = 'selected'; -} - -if ($errors!='') { - Utils::print_header(_("Error!")); - bandeau_titre(_("Error!")); - - echo '
        '.$errors.'
      '."\n"; - -} else { - Utils::print_header(_('Poll administration').' - '.$title); - bandeau_titre(_('Poll administration').' - '.$title); - - // session_unset(); -} - -echo ' -
      -
      -
      -
      -

      '.$title.'

      - -
      -
      -
      - - - - -
      -
      -
      -
      -
      -
      -
      -

      '. _("Initiator of the poll") .'

      -

      '.stripslashes($poll->admin_name).'

      -
      -
      -

      '.$email_admin.'

      - -
      -
      -
      -
      -

      '._("Description") .'


      -

      '.$description.'

      - -
      -
      -
      - - -
      -

      '. _("Expiration's date") .'

      -

      '.date("d/m/Y",strtotime($poll->end_date)).'

      -
      -
      -
      -
      -
      -

      '.$poll_rules_text.'

      - -
      -
      -
      -
      -
      '."\n"; // .jumbotron - -// Table headers -$thead = ''; - -// Button in the first td to avoid remove col on "Return" keypress) -$tr_add_remove_col = ''; - -$border = array(); // bordure pour distinguer les mois -$td_headers = array(); // for a11y, headers="M1 D4 H5" on each td -$radio_title = array(); // date for - -// Display dates poll -if ($poll->format == "D") { - - $tr_months = ''; - $tr_days = ''; - $tr_hours = ''; - - // Headers - $colspan_month = 1; - $colspan_day = 1; - - foreach ($sujets as $i=>$sujet) { - - // Current date - $horoCur = explode('@', $sujet->sujet); //horoCur[0] = date, horoCur[1] = hour - if (isset($sujets[$i+1])){ - $next = $sujets[$i+1]->sujet; - $horoNext = explode('@', $next); - } - $border[$i] = false; - $radio_title[$i] = strftime($date_format['txt_short'], $horoCur[0]); - - // Months - $td_headers[$i] = 'M'.($i+1-$colspan_month); - - if (isset($sujets[$i+1]) && strftime("%B", $horoCur[0]) == strftime("%B", $horoNext[0]) && strftime("%Y", $horoCur[0]) == strftime("%Y", $horoNext[0])){ - $colspan_month++; - } else { - $border[$i] = true; - $tr_months .= ''.strftime("%B",$horoCur[0]).' '.strftime("%Y", $horoCur[0]).''; - $colspan_month=1; - } - - // Days - $td_headers[$i] .= ' D'.($i+1-$colspan_day); - - if (isset($sujets[$i+1]) && strftime($date_format['txt_day'],$horoCur[0])==strftime($date_format['txt_day'],$horoNext[0]) && strftime("%B",$horoCur[0])==strftime("%B",$horoNext[0])){ - $colspan_day++; - } else { - $rbd = ($border[$i]) ? ' rbd' : ''; - $tr_days .= ''.strftime($date_format['txt_day'],$horoCur[0]).''; - $colspan_day=1; - } - - // Hours - $rbd = ($border[$i]) ? ' rbd' : ''; - if ($horoCur[1] !== "") { - $tr_hours .= ''.$horoCur[1].''; - $radio_title[$i] .= ' - '.$horoCur[1]; - $td_headers[$i] .= ' H'.$i; - } else { - $tr_hours .= ''; - } - - // Remove col - $tr_add_remove_col .= (count($sujets) > 2 ) ? '' : ''; - - } - - $border[count($border)-1] = false; // suppression de la bordure droite du dernier mois - - $tr_months .= ''; - $tr_days .= ''; - $tr_hours .= ''; - - // Add col - $tr_add_remove_col .= ''; - - $thead = "\n".$tr_add_remove_col."\n".$tr_months."\n".$tr_days."\n".$tr_hours."\n"; - -// Subjects poll -} else { - $tr_subjects = ''; - - foreach ($sujets as $i=>$sujet) { - - $td_headers[$i]='';$radio_title[$i]=''; // init before concatenate - - // Subjects - preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$sujet->sujet,$md_a_img); // Markdown [![alt](src)](href) - preg_match_all('/!\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_img); // Markdown ![alt](src) - preg_match_all('/\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_a); // Markdown [text](href) - if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) - - $th_subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); - $th_subject_html = ''.$th_subject_text.''; - - } elseif (isset($md_img[2][0]) && $md_img[2][0]!='') { // ![alt](src) - - $th_subject_text = (isset($md_img[1][0]) && $md_img[1][0]!='') ? stripslashes($md_img[1][0]) : _("Choice") .' '.($i+1); - $th_subject_html = ''.$th_subject_text.''; - - } elseif (isset($md_a[2][0]) && $md_a[2][0]!='') { // [text](href) - - $th_subject_text = (isset($md_a[1][0]) && $md_a[1][0]!='') ? stripslashes($md_a[1][0]) : _("Choice") .' '.($i+1); - $th_subject_html = ''.$th_subject_text.''; - - } else { // text only - - $th_subject_text = stripslashes($sujet->sujet); - $th_subject_html = $th_subject_text; - - } - $tr_subjects .= ''.$th_subject_html.''; - - $border[$i] = false; - $td_headers[$i] .= 'S'.$i; - $radio_title[$i] .= $th_subject_text; - - // Remove col - $tr_add_remove_col .= ''; - } - - // Add col - $tr_add_remove_col .= ''; - - $thead = $tr_add_remove_col.$tr_subjects.''; -} - -// Print headers -echo ' -
      - -
      -

      ' . _('As poll administrator, you can change all the lines of this poll with this button ').'' . _('Edit') . ', - ' . _(' remove a column or a line with ') . '' . _('Remove') . ' - ' . _('and add a new column with '). ''. _('Add a column') . '

      -

      ' . _('Finally, you can change the informations of this poll like the title, the comments or your email address.') . '

      - -
      - - - -

      '._('Votes of the poll ').'

      -
      - - - '. $thead . ' - '; - -// Print poll results -$somme[] = 0; -$compteur = 0; - -foreach($users as $user) { - - $ensemblereponses = $user->reponses; - - // Print name - echo ' -'."\n"; - - // si la ligne n'est pas a changer, on affiche les données - if (!$testligneamodifier) { - for ($k = 0; $k < $nbcolonnes; $k++) { - $rbd = ($border[$k]) ? ' rbd' : ''; - $car = substr($ensemblereponses, $k, 1); - switch ($car) { - case "1": echo ''."\n"; - if (isset($somme[$k]) === false) { - $somme[$k] = 0; - } - $somme[$k]++; break; - case "2": echo ''."\n"; break; - default: echo ''."\n";break; - } - } - } else { // sinon on remplace les choix de l'utilisateur par une ligne de radio pour recuperer de nouvelles valeurs - // si c'est bien la ligne a modifier on met les radios - if ($compteur == "$ligneamodifier") { - for ($j = 0; $j < $nbcolonnes; $j++) { - - $car = substr($ensemblereponses, $j, 1); - - // variable pour afficher la valeur cochée - $car_html[0]='value="0"';$car_html[1]='value="1"';$car_html[2]='value="2"'; - switch ($car) { - case "1": $car_html[1]='value="1" checked';break; - case "2": $car_html[2]='value="2" checked';break; - default: $car_html[0]='value="0" checked';break; - } - - echo ' - '."\n"; - - } - } else { //sinon on affiche les lignes normales - for ($k = 0; $k < $nbcolonnes; $k++) { - $rbd = ($border[$k]) ? ' rbd' : ''; - $car = substr($ensemblereponses, $k, 1); - switch ($car) { - case "1": echo ''."\n"; - if (isset($somme[$k]) === false) { - $somme[$k] = 0; - } - $somme[$k]++; break; - case "2": echo ''."\n"; break; - default: echo ''."\n";break; - } - } - } - } - - //a la fin de chaque ligne se trouve les boutons modifier - if (!$testligneamodifier=="true") { - echo ' - '."\n"; - } - - //demande de confirmation pour modification de ligne - for ($i = 0; $i < $nblignes; $i++) { - if (isset($_POST["modifierligne$i"])) { - if ($compteur == $i) { - echo ''."\n"; - } - } - } - - $compteur++; - echo ''."\n"; -} - -if (!$testligneamodifier=="true") { - //affichage de la case vide de texte pour un nouvel utilisateur - echo ' -'."\n"; - - //une ligne de checkbox pour le choix du nouvel utilisateur - for ($i = 0; $i < $nbcolonnes; $i++) { - echo ' - '."\n"; - } - - // Affichage du bouton de formulaire pour inscrire un nouvel utilisateur dans la base - echo ' -'."\n"; - -} - -// Addition and Best choice -//affichage de la ligne contenant les sommes de chaque colonne -$tr_addition = ''; -$meilleurecolonne = max($somme); -$compteursujet = 0; -$meilleursujet = '
        '; -for ($i = 0; $i < $nbcolonnes; $i++) { - if (isset($somme[$i]) && $somme[$i] > 0 ) { - if (in_array($i, array_keys($somme, max($somme)))){ - - $tr_addition .= '
      '; - - $meilleursujet.= '
    • '.$radio_title[$i].'
    • '; - $compteursujet++; - - } else { - $tr_addition .= ''; - } - } else { - $tr_addition .= ''; - } -} -$tr_addition .= ''; - -$meilleursujet = str_replace("°", "'", $meilleursujet).''; -$vote_str = ($meilleurecolonne > 1) ? $vote_str = _('votes') : _('vote'); - -// Print Addition and Best choice -echo $tr_addition.' - -
      '._('Votes of the poll ').$title.'
      '.stripslashes($user->nom).' ' . _('Yes') . '() ' . _('Yes') . _(', ifneedbe') . '' . _('No') . ' -
        -
      • - - -
      • -
      • - - -
      • -
      • - - -
      • -
      -
      ' . _('Yes') . '() ' . _('Yes') . _(', ifneedbe') . '' . _('No') . ' - - -
      -
      - - -
      -
      -
        -
      • - - -
      • -
      • - - -
      • -
      • - - -
      • -
      -
      '. _("Addition") .''.$somme[$i].''.$somme[$i].'
      -
      -
      '."\n"; - -if ($compteursujet == 1) { - echo ' -

      ' . _("Best choice") . '

      -
      -

      ' . _("The best choice at this time is:") . '

      - ' . $meilleursujet . ' -

      ' . _("with") . ' ' . $meilleurecolonne . ' ' . $vote_str . '.

      -
      '."\n"; -} elseif ($compteursujet > 1) { - echo ' -

      ' . _("Best choices") . '

      -
      -

      ' . _("The bests choices at this time are:") . '

      - ' . $meilleursujet . ' -

      ' . _("with") . ' ' . $meilleurecolonne . ' ' . $vote_str . '.

      -
      '."\n"; -} - -echo ' -
      -
      '."\n"; - -// Commments -$comment_user = $connect->allComments($poll_id); - -if (count($comment_user) != 0) { - echo '

      ' . _("Comments of polled people") . '

      '."\n"; - - $i = 0; - while ( $dcomment=$comment_user->FetchNextObject(false)) { - echo ' -
      - - '.stripslashes($dcomment->usercomment). ' : - ' . stripslashes(nl2br($dcomment->comment)) . ' -
      '; - $i++; - } - echo '
      '; -} -echo ' -
      -
      -
      ' . _("Add a comment in the poll") . ' -
      -

      -
      -
      -


      -

      -
      -

      -
      -
      -
      -
      -
      '; - -bandeau_pied(); +// Retrieve data +$slots = $pollService->allSlotsByPollId($poll_id); +$votes = $pollService->allUserVotesByPollId($poll_id); +$comments = $pollService->allCommentsByPollId($poll_id); + + +// Assign data to template +$smarty->assign('poll_id', $admin_poll_id); +$smarty->assign('poll', $poll); +$smarty->assign('title', _('Poll') . ' - ' . $poll->title); +$smarty->assign('slots', $pollService->splitSlots($slots)); +$smarty->assign('votes', $pollService->splitVotes($votes)); +$smarty->assign('best_moments', $pollService->computeBestMoments($votes)); +$smarty->assign('comments', $comments); +$smarty->assign('editingVoteId', $editingVoteId); +$smarty->assign('message', $message); + +$smarty->display('studs.tpl'); \ No newline at end of file diff --git a/old_adminstuds.php b/old_adminstuds.php new file mode 100644 index 0000000..53a0122 --- /dev/null +++ b/old_adminstuds.php @@ -0,0 +1,1214 @@ +prepare('SELECT * FROM sondage WHERE admin_poll_id = ?'); + $prepared->execute(array($admin_poll_id)); + $poll = $prepared->fetch(); + $prepared->closeCursor(); + + $prepared = $connect->prepare('SELECT * FROM sujet_studs WHERE id_sondage = ?'); + $prepared->execute(array($poll_id)); + $sujets = $prepared->fetchAll(); + + $prepared = $connect->prepare('SELECT * FROM user_studs WHERE id_sondage = ? order by id_users'); + $prepared->execute(array($poll_id)); + $users = $prepared->fetchAll(); +} + +//verification de l'existence du sondage, s'il n'existe pas on met une page d'erreur +if (!$poll || !$sujets) { + Utils::print_header( _('Error!')); + + bandeau_titre(_('Error!')); + + echo ' +
      +

      ' . _('This poll doesn\'t exist !') . '

      +

      ' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

      +
      '."\n"; + + bandeau_pied(); + + die(); +} + +// Send email (only once during the session) to alert admin of the change he made. ==> two modifications (comment, title, description, ...) on differents polls in the same session will generate only one mail. +$email_admin = $poll->admin_mail; +$poll_title = $poll->title; +$smtp_allowed = $config['use_smtp']; +function send_mail_admin() { + global $email_admin; + global $poll_title; + global $admin_poll_id; + global $smtp_allowed; + if($smtp_allowed==true){ + if(!isset($_SESSION['mail_admin_sent'])) { + Utils::sendEmail( $email_admin, + _("[ADMINISTRATOR] New settings for your poll") . ' ' . stripslashes( $poll_title ), + _("You have changed the settings of your poll. \nYou can modify this poll with this link") . + " :\n\n" . Utils::getUrlSondage($admin_poll_id, true) . "\n\n" . + _("Thanks for your confidence.") . "\n" . NOMAPPLICATION + ); + $_SESSION["mail_admin_sent"]=true; + } + } + +} + +//si la valeur du nouveau titre est valide et que le bouton est activé +if (isset($_POST["boutonnouveautitre"])) { + if (Utils::issetAndNoEmpty('nouveautitre') === false) { + $err |= TITLE_EMPTY; + } else { + //Update SQL database with new title + $nouveautitre = htmlentities(html_entity_decode($_POST['nouveautitre'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); + $sql = 'UPDATE sondage SET titre = '.$connect->Param('nouveautitre').' WHERE id_sondage = '.$connect->Param('numsondage'); + $sql = $connect->Prepare($sql); + + //Email sent to the admin + if ($connect->Execute($sql, array($nouveautitre, $poll_id))) { + send_mail_admin(); + } + } +} + +// si le bouton est activé, quelque soit la valeur du champ textarea +if (isset($_POST['boutonnouveauxcommentaires'])) { + if (empty($_POST['nouveautitre'])) { + $err |= COMMENT_EMPTY; + } else { + $commentaires = htmlentities(html_entity_decode($_POST['nouveauxcommentaires'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); + + //Update SQL database with new description + $prepared = $connect->prepare('UPDATE sondage SET commentaires = ? WHERE id_sondage = ?'); + $prepared->execute(array($commentaires, $poll_id)); + + //Email sent to the admin + if ($connect->Execute($sql, array($commentaires, $poll_id))) { + send_mail_admin(); + } + } +} + +//si la valeur de la nouvelle adresse est valide et que le bouton est activé +if (isset($_POST["boutonnouvelleadresse"])) { + if (empty($_POST['nouvelleadresse']) || Utils::isValidEmail($_POST["nouvelleadresse"]) === false) { + $err |= INVALID_EMAIL; + } else { + $nouvelleadresse = htmlentities(html_entity_decode($_POST['nouvelleadresse'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); + + //Update SQL database with new email + $prepared = $connect->prepare('UPDATE sondage SET mail_admin = ? WHERE id_sondage = ?'); + $executed = $prepared->execute(array($nouvelleadresse, $poll_id)); + + //Email sent to the admin + if ($executed) { + send_mail_admin(); + } + } +} + +// TODO OPZ : Revoir ce que fait ce truc exactament +//New poll rules +if (isset($_POST["btn_poll_rules"])) { + echo ''; + if($_POST['poll_rules'] == '+') { + $new_poll_rules = substr($dsondage->format, 0, 1).'+'; + } elseif($_POST['poll_rules'] == '-') { + $new_poll_rules = substr($dsondage->format, 0, 1).'-'; + } else { + $new_poll_rules = substr($dsondage->format, 0, 1); + } + + //Update SQL database with new rules + $prepared = $connect->prepare('UPDATE sondage SET format = ? WHERE id_sondage = ?'); + $executed = $prepared->execute(array($new_poll_rules, $poll_id)); + + //Email sent to the admin + if ($executed) { + send_mail_admin(); + } +} + +// reload +// TODO OPZ Pourquoi recharger +// $dsujet= $sujets->FetchObject(false); +// $dsondage= $sondage->FetchObject(false); + +if (isset($_POST['ajoutsujet'])) { + Utils::print_header( _('Add a column') .' - ' . stripslashes($poll->title)); + + bandeau_titre(_('Make your polls')); + + //on recupere les données et les sujets du sondage + + echo ' +
      +
      +
      +

      ' . _("Column's adding") . '

      '."\n"; + + if ($poll->format == "A"){ + echo ' +
      + +
      + +
      +
      '."\n"; + } else { + // ajout d'une date avec creneau horaire + echo ' +

      '. _("You can add a new scheduling date to your poll.").'
      '._("If you just want to add a new hour to an existant date, put the same date and choose a new hour.") .'

      + +
      + +
      +
      + + +
      + '. _("(dd/mm/yyyy)") .' +
      +
      +
      + +
      + +
      +
      '; + } + echo ' +

      + + +

      +
      +
      +
      '; + + bandeau_pied(); + + die(); +} + +if (isset($_POST["suppressionsondage"])) { + Utils::print_header( _("Confirm removal of your poll") .' - ' . stripslashes( $dsondage->title )); + + bandeau_titre(_("Confirm removal of your poll")); + + echo ' +
      +
      +

      ' . _("Confirm removal of your poll") . '

      +

      +

      +
      +
      '; + + bandeau_pied(); + + die(); +} + +// Remove all the comments +if (isset($_POST['removecomments'])) { + $sql = 'DELETE FROM comments WHERE id_sondage='.$connect->Param('numsondage'); + $sql = $connect->Prepare($sql); + $cleaning = $connect->Execute($sql, array($poll_id)); +} + +// Remove all the votes +if (isset($_POST["removevotes"])) { + $sql = 'DELETE FROM user_studs WHERE id_sondage='.$connect->Param('numsondage'); + $sql = $connect->Prepare($sql); + $cleaning = $connect->Execute($sql, array($poll_id)); +} + +//action si bouton confirmation de suppression est activé +if (isset($_POST["confirmesuppression"])) { + $nbuser=$user_studs->RecordCount(); + $date=date('H:i:s d/m/Y:'); + + if (Utils::remove_sondage($connect, $poll_id)) { + // on ecrit dans le fichier de logs la suppression du sondage + error_log($date . " SUPPRESSION: $dsondage->id_sondage\t$dsondage->format\t$dsondage->nom_admin\t$dsondage->mail_admin\n", 3, 'admin/logs_studs.txt'); + + // Email sent + send_mail_admin(); + //affichage de l'ecran de confirmation de suppression de sondage + Utils::print_header(_("Your poll has been removed!")); + + bandeau_titre(_("Make your polls")); + + echo ' +
      +

      ' . _("Your poll has been removed!") . '

      +

      ' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

      +
      + '."\n"; + + bandeau_pied(); + + die(); + } +} + +// quand on ajoute un commentaire utilisateur +if (isset($_POST['ajoutcomment'])) { + if (empty($_POST['commentuser'])) { + $err |= COMMENT_USER_EMPTY; + } else { + $comment_user = htmlentities(html_entity_decode($_POST["commentuser"], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); + } + + if(empty($_POST['comment'])) { + $err |= COMMENT_EMPTY; + } + + if (!empty($_POST['comment']) && !Utils::is_error(COMMENT_EMPTY) && !Utils::is_error(NO_POLL) && !Utils::is_error(COMMENT_USER_EMPTY)) { + $comment = htmlentities(html_entity_decode($_POST["comment"], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); + + // Check for doublons + $comment_doublon = false; + $req = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; + $sql = $connect->Prepare($req); + $comment_user_doublon = $connect->Execute($sql, array($poll_id)); + if ($comment_user_doublon->RecordCount() != 0) { + while ( $dcomment_user_doublon=$comment_user_doublon->FetchNextObject(false)) { + if($dcomment_user_doublon->comment == $comment && $dcomment_user_doublon->usercomment == $comment_user) { + $comment_doublon = true; + }; + } + } + + if(!$comment_doublon) { + $req = 'INSERT INTO comments (id_sondage, comment, usercomment) VALUES ('. + $connect->Param('id_sondage').','. + $connect->Param('comment').','. + $connect->Param('comment_user').')'; + $sql = $connect->Prepare($req); + + $comments = $connect->Execute($sql, array($poll_id, $comment, $comment_user)); + if ($comments === false) { + $err |= COMMENT_INSERT_FAILED; + } + } + } +} + +$nbcolonnes = count($sujets); +$nblignes = count($users); + +//si il n'y a pas suppression alors on peut afficher normalement le tableau + +//action si le bouton participer est cliqué +if (isset($_POST["boutonp"])) { + //si on a un nom dans la case texte + if (!empty($_POST['nom'])){ + $nouveauchoix = ''; + $erreur_prenom = false; + + for ($i=0;$i<$nbcolonnes;$i++){ + // radio checked 1 = Yes, 2 = Ifneedbe, 0 = No + if (isset($_POST["choix$i"])) { + switch ($_POST["choix$i"]) { + case 1: $nouveauchoix .= "1";break; + case 2: $nouveauchoix .= "2";break; + default: $nouveauchoix .= "0";break; + } + } + } + + $nom = htmlentities(html_entity_decode($_POST["nom"], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); + + while($user = $user_studs->FetchNextObject(false)) { + if ($nom == $user->nom){ + $erreur_prenom="yes"; + } + } + + // Ecriture des choix de l'utilisateur dans la base + if (!$erreur_prenom) { + $sql = 'INSERT INTO user_studs (nom, id_sondage, reponses) VALUES ('. + $connect->Param('nom').','. + $connect->Param('numsondage').','. + $connect->Param('nouveauchoix').')'; + + $sql = $connect->Prepare($sql); + $connect->Execute($sql, array($nom, $poll_id, $nouveauchoix)); + } + } +} + + +//action quand on ajoute une colonne au format AUTRE +if (isset($_POST["ajoutercolonne"]) && !empty($_POST['nouvellecolonne']) && $poll->format == "A") { + $nouveauxsujets=$dsujet->sujet; + + //on rajoute la valeur a la fin de tous les sujets deja entrés + $nouveauxsujets.=","; + $nouveauxsujets.=str_replace(","," ",$_POST["nouvellecolonne"]); + $nouveauxsujets = htmlentities(html_entity_decode($nouveauxsujets, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); + + //mise a jour avec les nouveaux sujets dans la base + $sql = 'UPDATE sujet_studs SET sujet = '.$connect->Param('nouveauxsujets').' WHERE id_sondage = '.$connect->Param('numsondage'); + $sql = $connect->Prepare($sql); + if ($connect->Execute($sql, array($nouveauxsujets, $poll_id))) { + send_mail_admin(); + } +} + + +// [begin] action quand on ajoute une colonne au format DATE +if (isset($_POST['ajoutercolonne']) && $dsondage->format == 'D') { + + if (!empty($_POST["newdate"])) { + $new_choice = mktime(0, 0, 0, substr($_POST["newdate"],3,2), substr($_POST["newdate"],0,2), substr($_POST["newdate"],6,4)); + + if (!empty($_POST["newhour"])){ + $new_choice .= '@' . $_POST["newhour"]; + } + + + + + + // TODO OPZ Delete the code below + // TODO OPZ Insert new choice + // TODO OPZ Update users votes (add "0" in the right column^^) + + + + //on rajoute la valeur dans les valeurs + $datesbase = explode(",",$dsujet->sujet); + $taillebase = sizeof($datesbase); + + //recherche de l'endroit de l'insertion de la nouvelle date dans les dates deja entrées dans le tableau + if ($nouvelledate < $datesbase[0]) { + $cleinsertion = 0; + } elseif ($nouvelledate > $datesbase[$taillebase-1]) { + $cleinsertion = count($datesbase); + } else { + for ($i = 0; $i < count($datesbase); $i++) { + $j = $i + 1; + if ($nouvelledate > $datesbase[$i] && $nouvelledate < $datesbase[$j]) { + $cleinsertion = $j; + } + } + } + + array_splice($datesbase, $cleinsertion, 0, $nouvelledate); + $cle = array_search($nouvelledate, $datesbase); + $dateinsertion = ''; + for ($i = 0; $i < count($datesbase); $i++) { + $dateinsertion.=","; + $dateinsertion.=$datesbase[$i]; + } + + $dateinsertion = substr("$dateinsertion", 1); + + //mise a jour avec les nouveaux sujets dans la base + //if (isset($erreur_ajout_date) && !$erreur_ajout_date){ + $sql = 'UPDATE sujet_studs SET sujet = '.$connect->Param('dateinsertion').' WHERE id_sondage = '.$connect->Param('numsondage'); + $sql = $connect->Prepare($sql); + $connect->Execute($sql, array($dateinsertion, $poll_id)); + + if ($nouvelledate > strtotime($dsondage->date_fin)) { + $date_fin=$nouvelledate+200000; + $sql = 'UPDATE sondage SET date_fin = '.$connect->Param('date_fin').' WHERE id_sondage = '.$connect->Param('numsondage'); + $sql = $connect->Prepare($sql); + $connect->Execute($sql, array($date_fin, $poll_id)); + } + //} + + //mise a jour des reponses actuelles correspondant au sujet ajouté + $sql = 'UPDATE user_studs SET reponses = '.$connect->Param('reponses').' WHERE nom = '.$connect->Param('nom').' AND id_users='.$connect->Param('id_users'); + $sql = $connect->Prepare($sql); + while ($data = $user_studs->FetchNextObject(false)) { + $ensemblereponses=$data->reponses; + $newcar = ''; + + //parcours de toutes les réponses actuelles + for ($j = 0; $j < $nbcolonnes; $j++) { + $car=substr($ensemblereponses,$j,1); + + //si les reponses ne concerne pas la colonne ajoutée, on concatene + if ($j==$cle) { + $newcar.="0"; + } + + $newcar.=$car; + } + + //mise a jour des reponses utilisateurs dans la base + if (isset($erreur_ajout_date) && !$erreur_ajout_date){ + $connect->Execute($sql, array($newcar, $data->nom, $data->id_users)); + } + } + + //Email sent to the admin + send_mail_admin(); + + } else { + $erreur_ajout_date="yes"; + } +} +// [end] action quand on ajoute une colonne au format DATE + + +//suppression de ligne dans la base +for ($i = 0; $i < $nblignes; $i++) { + if (isset($_POST["effaceligne$i"])) { + $compteur=0; + $prepared = $connect->prepare('DELETE FROM user_studs WHERE nom = ? AND id_users = ?'); + + foreach ($users as $user) { + if ($compteur==$i){ + $prepared->execute(array($user->nom, $user->id_users)); + } + + $compteur++; + } + } +} + + +// TODO OPZ Revoir toute cette partie suppression d'un commentaire utilisateur +/*$sql = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; +$sql = $connect->Prepare($sql); +$comment_user = $connect->Execute($sql, array($poll_id)); +$i = 0; +while ($dcomment = $comment_user->FetchNextObject(false)) { + if (isset($_POST['suppressioncomment'.$i])) { + $sql = 'DELETE FROM comments WHERE id_comment = '.$connect->Param('id_comment'); + $sql = $connect->Prepare($sql); + $connect->Execute($sql, array($dcomment->id_comment)); + } + + $i++; +} +*/ + +//on teste pour voir si une ligne doit etre modifiée +$testmodifier = false; +$testligneamodifier = false; + +for ($i = 0; $i < $nblignes; $i++) { + if (isset($_POST["modifierligne$i"])) { + $ligneamodifier=$i; + $testligneamodifier="true"; + } + + //test pour voir si une ligne est a modifier + if (isset($_POST["validermodifier$i"])) { + $modifier=$i; + $testmodifier="true"; + } +} + + +//si le test est valide alors on affiche des checkbox pour entrer de nouvelles valeurs +if ($testmodifier) { + $nouveauchoix = ''; + for ($i = 0; $i < $nbcolonnes; $i++) { + // radio checked 1 = Yes, 2 = Ifneedbe, 0 = No + if (isset($_POST["choix$i"])) { + switch ($_POST["choix$i"]) { + case 1: $nouveauchoix .= "1";break; + case 2: $nouveauchoix .= "2";break; + default: $nouveauchoix .= "0";break; + } + } + } + + $compteur=0; + + while ($data=$user_studs->FetchNextObject(false)) { + //mise a jour des données de l'utilisateur dans la base SQL + if ($compteur==$modifier) { + $sql = 'UPDATE user_studs SET reponses = '.$connect->Param('reponses').' WHERE nom = '.$connect->Param('nom').' AND id_users = '.$connect->Param('id_users'); + $sql = $connect->Prepare($sql); + $connect->Execute($sql, array($nouveauchoix, $data->nom, $data->id_users)); + } + + $compteur++; + } +} + + +//suppression de colonnes dans la base +for ($i = 0; $i < $nbcolonnes; $i++) { + if ((isset($_POST["effacecolonne$i"])) && $nbcolonnes > 1){ + $sujets = explode(",",$dsujet->sujet); + //sort($toutsujet, SORT_NUMERIC); + $j = 0; + $nouveauxsujets = ''; + + //parcours de tous les sujets actuels + while (isset($sujets[$j])) { + //si le sujet n'est pas celui qui a été effacé alors on concatene + if ($i != $j) { + $nouveauxsujets .= ','; + $nouveauxsujets .= $sujets[$j]; + } + + $j++; + } + + //on enleve la virgule au début + $nouveauxsujets = substr("$nouveauxsujets", 1); + + //nettoyage des reponses actuelles correspondant au sujet effacé + $compteur = 0; + $sql = 'UPDATE user_studs SET reponses = '.$connect->Param('reponses').' WHERE nom = '.$connect->Param('nom').' AND id_users = '.$connect->Param('id_users'); + $sql = $connect->Prepare($sql); + + while ($data = $user_studs->FetchNextObject(false)) { + $newcar = ''; + $ensemblereponses = $data->reponses; + + //parcours de toutes les réponses actuelles + for ($j = 0; $j < $nbcolonnes; $j++) { + $car=substr($ensemblereponses, $j, 1); + //si les reponses ne concerne pas la colonne effacée, on concatene + if ($i != $j) { + $newcar .= $car; + } + } + + $compteur++; + + //mise a jour des reponses utilisateurs dans la base + $connect->Execute($sql, array($newcar, $data->nom, $data->id_users)); + } + + //mise a jour des sujets dans la base + $sql = 'UPDATE sujet_studs SET sujet = '.$connect->Param('nouveauxsujets').' WHERE id_sondage = '.$connect->Param('numsondage'); + $sql = $connect->Prepare($sql); + $connect->Execute($sql, array($nouveauxsujets, $poll_id)); + } +} + + +// TODO OPZ Déjà fait en début de fichier recuperation des donnes de la base +/*$sql = 'SELECT * FROM sondage WHERE id_sondage_admin = '.$connect->Param('numsondageadmin'); +$sql = $connect->Prepare($sql); +$sondage = $connect->Execute($sql, array($admin_poll_id)); + +if ($sondage !== false) { + $sql = 'SELECT * FROM sujet_studs WHERE id_sondage = '.$connect->Param('numsondage'); + $sql = $connect->Prepare($sql); + $sujets = $connect->Execute($sql, array($poll_id)); + + $sql = 'SELECT * FROM user_studs WHERE id_sondage = '.$connect->Param('numsondage').' order by id_users'; + $sql = $connect->Prepare($sql); + $user_studs = $connect->Execute($sql, array($poll_id)); +} else { + + Utils::print_header(_("Error!")); + bandeau_titre(_("Error!")); + + echo ' +
      +

      ' . _("This poll doesn't exist !") . '

      +

      ' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

      +
      '."\n"; + + bandeau_pied(); + + die(); +}*/ + +// Errors +$errors = ''; +if ((isset($_POST["boutonp"])) && $_POST["nom"] == "") { + $errors .= '
    • ' . _("Enter a name") . '
    • '; +} +if (isset($erreur_prenom) && $erreur_prenom) { + $errors .= '
    • ' . _("The name you've chosen already exist in this poll!") . '
    • '; +} +if (isset($erreur_injection) && $erreur_injection) { + $errors .= '
    • ' . _("Characters \" ' < et > are not permitted") . '
    • '; +} +if (isset($erreur_ajout_date) && $erreur_ajout_date) { + $errors .= '
    • ' . _("The date is not correct !") . '
    • '; +} + +//Poll title, description and email values +$title = (isset($_POST["boutonnouveautitre"]) && !empty($_POST['nouveautitre'])) ? htmlentities(html_entity_decode($_POST['nouveautitre'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8') : stripslashes( $poll->title); +$description = (isset($_POST["nouveauxcommentaires"])) ? stripslashes(htmlentities(html_entity_decode($_POST['nouveauxcommentaires'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8')) : stripslashes( $poll->comment); +$email_admin = (isset($_POST["boutonnouvelleadresse"]) && !empty($_POST['nouvelleadresse'])) ? htmlentities(html_entity_decode($_POST['nouvelleadresse'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8') : stripslashes( $poll->admin_mail ); + +//Poll format (locked A-/D-, open A/D, editable A+/D+) +$poll_rules = (isset($_POST["poll_rules"]) && !empty($_POST['btn_poll_rules'])) ? $_POST["poll_rules"] : substr($poll->format, 1, 1); // TODO OPZ Handle comment disabling +$poll_rules_opt1 = '';$poll_rules_opt2 = '';$poll_rules_opt3 = ''; +if($poll->editable) { + $poll_rules_text = ' '. _("Votes are editable"); + $poll_rules_opt3 = 'selected'; +} elseif($poll_rules == '-') { + $poll_rules_text = ' '. _("Votes and comments are locked"); + $poll_rules_opt1 = 'selected'; +} else { + $poll_rules_text = ' '. _("Votes and comments are open"); + $poll_rules_opt2 = 'selected'; +} + +if ($errors!='') { + Utils::print_header(_("Error!")); + bandeau_titre(_("Error!")); + + echo '
        '.$errors.'
      '."\n"; + +} else { + Utils::print_header(_('Poll administration').' - '.$title); + bandeau_titre(_('Poll administration').' - '.$title); + + // session_unset(); +} + +echo ' +
      +
      +
      +
      +

      '.$title.'

      + +
      +
      +
      + + + + +
      +
      +
      +
      +
      +
      +
      +

      '. _("Initiator of the poll") .'

      +

      '.stripslashes($poll->admin_name).'

      +
      +
      +

      '.$email_admin.'

      + +
      +
      +
      +
      +

      '._("Description") .'


      +

      '.$description.'

      + +
      +
      +
      + + +
      +

      '. _("Expiration's date") .'

      +

      '.date("d/m/Y",strtotime($poll->end_date)).'

      +
      +
      +
      +
      +
      +

      '.$poll_rules_text.'

      + +
      +
      +
      +
      +
      '."\n"; // .jumbotron + +// Table headers +$thead = ''; + +// Button in the first td to avoid remove col on "Return" keypress) +$tr_add_remove_col = ''; + +$border = array(); // bordure pour distinguer les mois +$td_headers = array(); // for a11y, headers="M1 D4 H5" on each td +$radio_title = array(); // date for + +// Display dates poll +if ($poll->format == "D") { + + $tr_months = ''; + $tr_days = ''; + $tr_hours = ''; + + // Headers + $colspan_month = 1; + $colspan_day = 1; + + foreach ($sujets as $i=>$sujet) { + + // Current date + $horoCur = explode('@', $sujet->sujet); //horoCur[0] = date, horoCur[1] = hour + if (isset($sujets[$i+1])){ + $next = $sujets[$i+1]->sujet; + $horoNext = explode('@', $next); + } + $border[$i] = false; + $radio_title[$i] = strftime($date_format['txt_short'], $horoCur[0]); + + // Months + $td_headers[$i] = 'M'.($i+1-$colspan_month); + + if (isset($sujets[$i+1]) && strftime("%B", $horoCur[0]) == strftime("%B", $horoNext[0]) && strftime("%Y", $horoCur[0]) == strftime("%Y", $horoNext[0])){ + $colspan_month++; + } else { + $border[$i] = true; + $tr_months .= ''.strftime("%B",$horoCur[0]).' '.strftime("%Y", $horoCur[0]).''; + $colspan_month=1; + } + + // Days + $td_headers[$i] .= ' D'.($i+1-$colspan_day); + + if (isset($sujets[$i+1]) && strftime($date_format['txt_day'],$horoCur[0])==strftime($date_format['txt_day'],$horoNext[0]) && strftime("%B",$horoCur[0])==strftime("%B",$horoNext[0])){ + $colspan_day++; + } else { + $rbd = ($border[$i]) ? ' rbd' : ''; + $tr_days .= ''.strftime($date_format['txt_day'],$horoCur[0]).''; + $colspan_day=1; + } + + // Hours + $rbd = ($border[$i]) ? ' rbd' : ''; + if ($horoCur[1] !== "") { + $tr_hours .= ''.$horoCur[1].''; + $radio_title[$i] .= ' - '.$horoCur[1]; + $td_headers[$i] .= ' H'.$i; + } else { + $tr_hours .= ''; + } + + // Remove col + $tr_add_remove_col .= (count($sujets) > 2 ) ? '' : ''; + + } + + $border[count($border)-1] = false; // suppression de la bordure droite du dernier mois + + $tr_months .= ''; + $tr_days .= ''; + $tr_hours .= ''; + + // Add col + $tr_add_remove_col .= ''; + + $thead = "\n".$tr_add_remove_col."\n".$tr_months."\n".$tr_days."\n".$tr_hours."\n"; + +// Subjects poll +} else { + $tr_subjects = ''; + + foreach ($sujets as $i=>$sujet) { + + $td_headers[$i]='';$radio_title[$i]=''; // init before concatenate + + // Subjects + preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$sujet->sujet,$md_a_img); // Markdown [![alt](src)](href) + preg_match_all('/!\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_img); // Markdown ![alt](src) + preg_match_all('/\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_a); // Markdown [text](href) + if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) + + $th_subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); + $th_subject_html = ''.$th_subject_text.''; + + } elseif (isset($md_img[2][0]) && $md_img[2][0]!='') { // ![alt](src) + + $th_subject_text = (isset($md_img[1][0]) && $md_img[1][0]!='') ? stripslashes($md_img[1][0]) : _("Choice") .' '.($i+1); + $th_subject_html = ''.$th_subject_text.''; + + } elseif (isset($md_a[2][0]) && $md_a[2][0]!='') { // [text](href) + + $th_subject_text = (isset($md_a[1][0]) && $md_a[1][0]!='') ? stripslashes($md_a[1][0]) : _("Choice") .' '.($i+1); + $th_subject_html = ''.$th_subject_text.''; + + } else { // text only + + $th_subject_text = stripslashes($sujet->sujet); + $th_subject_html = $th_subject_text; + + } + $tr_subjects .= ''.$th_subject_html.''; + + $border[$i] = false; + $td_headers[$i] .= 'S'.$i; + $radio_title[$i] .= $th_subject_text; + + // Remove col + $tr_add_remove_col .= ''; + } + + // Add col + $tr_add_remove_col .= ''; + + $thead = $tr_add_remove_col.$tr_subjects.''; +} + +// Print headers +echo ' +
      + +
      +

      ' . _('As poll administrator, you can change all the lines of this poll with this button ').'' . _('Edit') . ', + ' . _(' remove a column or a line with ') . '' . _('Remove') . ' + ' . _('and add a new column with '). ''. _('Add a column') . '

      +

      ' . _('Finally, you can change the informations of this poll like the title, the comments or your email address.') . '

      + +
      + + + +

      '._('Votes of the poll ').'

      +
      + + + '. $thead . ' + '; + +// Print poll results +$somme[] = 0; +$compteur = 0; + +foreach($users as $user) { + + $ensemblereponses = $user->reponses; + + // Print name + echo ' +'."\n"; + + // si la ligne n'est pas a changer, on affiche les données + if (!$testligneamodifier) { + for ($k = 0; $k < $nbcolonnes; $k++) { + $rbd = ($border[$k]) ? ' rbd' : ''; + $car = substr($ensemblereponses, $k, 1); + switch ($car) { + case "1": echo ''."\n"; + if (isset($somme[$k]) === false) { + $somme[$k] = 0; + } + $somme[$k]++; break; + case "2": echo ''."\n"; break; + default: echo ''."\n";break; + } + } + } else { // sinon on remplace les choix de l'utilisateur par une ligne de radio pour recuperer de nouvelles valeurs + // si c'est bien la ligne a modifier on met les radios + if ($compteur == "$ligneamodifier") { + for ($j = 0; $j < $nbcolonnes; $j++) { + + $car = substr($ensemblereponses, $j, 1); + + // variable pour afficher la valeur cochée + $car_html[0]='value="0"';$car_html[1]='value="1"';$car_html[2]='value="2"'; + switch ($car) { + case "1": $car_html[1]='value="1" checked';break; + case "2": $car_html[2]='value="2" checked';break; + default: $car_html[0]='value="0" checked';break; + } + + echo ' + '."\n"; + + } + } else { //sinon on affiche les lignes normales + for ($k = 0; $k < $nbcolonnes; $k++) { + $rbd = ($border[$k]) ? ' rbd' : ''; + $car = substr($ensemblereponses, $k, 1); + switch ($car) { + case "1": echo ''."\n"; + if (isset($somme[$k]) === false) { + $somme[$k] = 0; + } + $somme[$k]++; break; + case "2": echo ''."\n"; break; + default: echo ''."\n";break; + } + } + } + } + + //a la fin de chaque ligne se trouve les boutons modifier + if (!$testligneamodifier=="true") { + echo ' + '."\n"; + } + + //demande de confirmation pour modification de ligne + for ($i = 0; $i < $nblignes; $i++) { + if (isset($_POST["modifierligne$i"])) { + if ($compteur == $i) { + echo ''."\n"; + } + } + } + + $compteur++; + echo ''."\n"; +} + +if (!$testligneamodifier=="true") { + //affichage de la case vide de texte pour un nouvel utilisateur + echo ' +'."\n"; + + //une ligne de checkbox pour le choix du nouvel utilisateur + for ($i = 0; $i < $nbcolonnes; $i++) { + echo ' + '."\n"; + } + + // Affichage du bouton de formulaire pour inscrire un nouvel utilisateur dans la base + echo ' +'."\n"; + +} + +// Addition and Best choice +//affichage de la ligne contenant les sommes de chaque colonne +$tr_addition = ''; +$meilleurecolonne = max($somme); +$compteursujet = 0; +$meilleursujet = '
        '; +for ($i = 0; $i < $nbcolonnes; $i++) { + if (isset($somme[$i]) && $somme[$i] > 0 ) { + if (in_array($i, array_keys($somme, max($somme)))){ + + $tr_addition .= '
      '; + + $meilleursujet.= '
    • '.$radio_title[$i].'
    • '; + $compteursujet++; + + } else { + $tr_addition .= ''; + } + } else { + $tr_addition .= ''; + } +} +$tr_addition .= ''; + +$meilleursujet = str_replace("°", "'", $meilleursujet).''; +$vote_str = ($meilleurecolonne > 1) ? $vote_str = _('votes') : _('vote'); + +// Print Addition and Best choice +echo $tr_addition.' + +
      '._('Votes of the poll ').$title.'
      '.stripslashes($user->nom).' ' . _('Yes') . '() ' . _('Yes') . _(', ifneedbe') . '' . _('No') . ' +
        +
      • + + +
      • +
      • + + +
      • +
      • + + +
      • +
      +
      ' . _('Yes') . '() ' . _('Yes') . _(', ifneedbe') . '' . _('No') . ' + + +
      +
      + + +
      +
      +
        +
      • + + +
      • +
      • + + +
      • +
      • + + +
      • +
      +
      '. _("Addition") .''.$somme[$i].''.$somme[$i].'
      +
      +
      '."\n"; + +if ($compteursujet == 1) { + echo ' +

      ' . _("Best choice") . '

      +
      +

      ' . _("The best choice at this time is:") . '

      + ' . $meilleursujet . ' +

      ' . _("with") . ' ' . $meilleurecolonne . ' ' . $vote_str . '.

      +
      '."\n"; +} elseif ($compteursujet > 1) { + echo ' +

      ' . _("Best choices") . '

      +
      +

      ' . _("The bests choices at this time are:") . '

      + ' . $meilleursujet . ' +

      ' . _("with") . ' ' . $meilleurecolonne . ' ' . $vote_str . '.

      +
      '."\n"; +} + +echo ' +
      +
      '."\n"; + +// Commments +$comment_user = $connect->allComments($poll_id); + +if (count($comment_user) != 0) { + echo '

      ' . _("Comments of polled people") . '

      '."\n"; + + $i = 0; + while ( $dcomment=$comment_user->FetchNextObject(false)) { + echo ' +
      + + '.stripslashes($dcomment->usercomment). ' : + ' . stripslashes(nl2br($dcomment->comment)) . ' +
      '; + $i++; + } + echo '
      '; +} +echo ' +
      +
      +
      ' . _("Add a comment in the poll") . ' +
      +

      +
      +
      +


      +

      +
      +

      +
      +
      +
      +
      +
      '; + +bandeau_pied(); diff --git a/studs.php b/studs.php index 3fba002..6f6a2e8 100644 --- a/studs.php +++ b/studs.php @@ -26,6 +26,7 @@ include_once __DIR__ . '/app/inc/init.php'; /* Variables */ /* --------- */ $poll_id = null; +$poll = null; $message = null; /* Services */ @@ -39,10 +40,9 @@ $inputService = new InputService(); if(!empty($_GET['poll'])) { $poll_id = filter_input(INPUT_GET, 'poll', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9]+$/']]); + $poll = $pollService->findById($poll_id); } -$poll = $pollService->findById($poll_id); - if (!$poll) { $smarty->assign('error', 'This poll doesn\'t exist'); $smarty->display('error.tpl'); From 410d2127ce3ec0412e8d4bd92429cc0afbe4098d Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 17 Dec 2014 23:43:06 +0100 Subject: [PATCH 030/151] admin: Add some work to poll information pane. --- adminstuds.php | 5 ++++- app/inc/i18n.php | 1 + css/frama.css | 2 +- studs.php | 6 ++++-- tpl/part/poll_info.tpl | 48 ++++++++++++++++++++++++++++++------------ 5 files changed, 45 insertions(+), 17 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index ec82d51..11eb8eb 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -29,6 +29,7 @@ $admin_poll_id = null; $poll_id = null; $poll = null; $message = null; +$editingVoteId = 0; /* Services */ /*----------*/ @@ -58,7 +59,8 @@ $comments = $pollService->allCommentsByPollId($poll_id); // Assign data to template -$smarty->assign('poll_id', $admin_poll_id); +$smarty->assign('poll_id', $poll_id); +$smarty->assign('admin_poll_id', $admin_poll_id); $smarty->assign('poll', $poll); $smarty->assign('title', _('Poll') . ' - ' . $poll->title); $smarty->assign('slots', $pollService->splitSlots($slots)); @@ -67,5 +69,6 @@ $smarty->assign('best_moments', $pollService->computeBestMoments($votes)); $smarty->assign('comments', $comments); $smarty->assign('editingVoteId', $editingVoteId); $smarty->assign('message', $message); +$smarty->assign('admin', true); $smarty->display('studs.tpl'); \ No newline at end of file diff --git a/app/inc/i18n.php b/app/inc/i18n.php index 5040073..829206c 100644 --- a/app/inc/i18n.php +++ b/app/inc/i18n.php @@ -69,6 +69,7 @@ $lang = ($_SESSION['langue']!='') ? strtolower($_SESSION['langue']) : 'fr'; $date_format['txt_full'] = _("%A, den %e. %B %Y"); //summary in choix_date.php and removal date in choix_(date|autre).php $date_format['txt_short'] = "%A %e %B %Y"; // radio title $date_format['txt_day'] = "%a %e"; +$date_format['txt_date'] = _("%Y-%m-%d"); if (strtoupper(substr(PHP_OS,0,3))=='WIN'){ //%e can't be used on Windows platform, use %#d instead foreach($date_format as $k => $v) { $date_format[$k] = preg_replace('#(?updateVote($poll_id, $editedVote, $choices); if ($result) { $message = new Message('success', _('Update vote successfully.')); + // TODO Send mail to notify the poll admin } else { $message = new Message('danger', _('Update vote failed.')); } @@ -101,6 +101,7 @@ if (!empty($_POST['save'])) { // Save edition of an old vote $result = $pollService->addVote($poll_id, $name, $choices); if ($result) { $message = new Message('success', _('Update vote successfully.')); + // TODO Send mail to notify the poll admin } else { $message = new Message('danger', _('Update vote failed.')); } @@ -147,5 +148,6 @@ $smarty->assign('best_moments', $pollService->computeBestMoments($votes)); $smarty->assign('comments', $comments); $smarty->assign('editingVoteId', $editingVoteId); $smarty->assign('message', $message); +$smarty->assign('admin', false); $smarty->display('studs.tpl'); diff --git a/tpl/part/poll_info.tpl b/tpl/part/poll_info.tpl index d0108e1..997b42a 100644 --- a/tpl/part/poll_info.tpl +++ b/tpl/part/poll_info.tpl @@ -1,27 +1,32 @@ -
      +{* TODO Add a form maybe *} +

      {$poll->title}

      - - {_('Export to CSV')} + + {_('Export to CSV')} + {if $admin|default:false} + + + {/if}
      -
      -
      -

      {_("Initiator of the poll")}

      -

      {$poll->admin_name}

      -
      - +
      +

      {_("Initiator of the poll")}

      +

      {$poll->admin_name}

      - {if !empty($poll->comment)}

      {_("Description")}


      @@ -29,4 +34,21 @@
      {/if}
      + +
      + + {if $admin} + +
      +

      {_("Expiration's date")}

      +

      {$poll->end_date|date_format:$date_format['txt_date']}

      +
      + {/if} +
      \ No newline at end of file From 94380c61825ca7e420651bcd72dbed92de172a03 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 18 Dec 2014 12:47:51 +0100 Subject: [PATCH 031/151] UI : Add availability to edit poll title --- tpl/part/poll_info.tpl | 105 +++++++++++++++++++++++------------------ tpl/studs.tpl | 2 +- 2 files changed, 61 insertions(+), 46 deletions(-) diff --git a/tpl/part/poll_info.tpl b/tpl/part/poll_info.tpl index 997b42a..2b7ccdf 100644 --- a/tpl/part/poll_info.tpl +++ b/tpl/part/poll_info.tpl @@ -1,54 +1,69 @@ {* TODO Add a form maybe *} -
      -
      -
      -

      {$poll->title}

      -
      -
      -
      - - {_('Export to CSV')} - {if $admin|default:false} - - +{$admin = $admin|default:false} +
      +
      +
      +
      +

      {$poll->title}{if $admin} {/if}

      + {if $admin} + {/if}
      -
      -
      -
      -
      -

      {_("Initiator of the poll")}

      -

      {$poll->admin_name}

      -
      - {if !empty($poll->comment)} -
      -

      {_("Description")}


      -

      {$poll->comment}

      +
      +
      + + {_('Export to CSV')} + {if $admin} + + + {/if} +
      - {/if} -
      - -
      - - {if $admin} +
      - - +

      {_("Initiator of the poll")}

      +

      {$poll->admin_name}

      -
      -

      {_("Expiration's date")}

      -

      {$poll->end_date|date_format:$date_format['txt_date']}

      + {if !empty($poll->comment)} +
      +

      {_("Description")}


      +

      {$poll->comment}

      +
      + {/if} +
      + +
      + - {/if} + {if $admin} + +
      +

      {_("Expiration's date")}

      +

      {$poll->end_date|date_format:$date_format['txt_date']}

      +
      + {/if} +
      -
      \ No newline at end of file + diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 4cba8d6..879cbbd 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -8,7 +8,7 @@ {* Global informations about the current poll *} -{include 'part/poll_info.tpl'} +{include 'part/poll_info.tpl' admin=$admin} {* Information about voting *} From cf207052f52cf0d72fa9470e58f59633101db6fd Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 18 Dec 2014 13:08:30 +0100 Subject: [PATCH 032/151] UI : Add availability to edit poll description + admin mail --- tpl/part/poll_info.tpl | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/tpl/part/poll_info.tpl b/tpl/part/poll_info.tpl index 2b7ccdf..429c6f3 100644 --- a/tpl/part/poll_info.tpl +++ b/tpl/part/poll_info.tpl @@ -1,9 +1,10 @@ {* TODO Add a form maybe *} {$admin = $admin|default:false} -
      + +{if $admin}{/if}
      -
      +

      {$poll->title}{if $admin} {/if}

      {if $admin}
      - +{if $admin}{/if} From 04a60e5c578eff0a74151ca47eebef9cb7d01541 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 18 Dec 2014 13:12:28 +0100 Subject: [PATCH 033/151] Add shadow under the text on submit button --- css/frama.css | 1 + 1 file changed, 1 insertion(+) diff --git a/css/frama.css b/css/frama.css index be2db00..bf0a0cb 100644 --- a/css/frama.css +++ b/css/frama.css @@ -210,6 +210,7 @@ fieldset[disabled] .btn-primary.active { color: #fff; background-color: #849551; border-color: #748544; + text-shadow: 0px 0px 3px rgba(0, 0, 0, 0.7); } .btn-success:hover, .btn-success:focus, From 716efd6d58ac3a646f796ed0869300fb693dfac5 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 18 Dec 2014 13:23:47 +0100 Subject: [PATCH 034/151] UI : Add availability to edit poll status --- tpl/part/poll_info.tpl | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/tpl/part/poll_info.tpl b/tpl/part/poll_info.tpl index 429c6f3..6ba1b95 100644 --- a/tpl/part/poll_info.tpl +++ b/tpl/part/poll_info.tpl @@ -87,5 +87,43 @@
      {/if}
      + {if admin} +
      +
      +
      + {if $poll->active} + {if $poll->editable} + {$rule_id = 2} + {$rule_icon = ''} + {$rule_txt = _('Votes are editable')} + {else} + {$rule_id = 1} + {$rule_icon = ''} + {$rule_txt = _('Votes and comments are open')} + {/if} + {else} + {$rule_id = 0} + {$rule_icon = ''} + {$rule_txt = _('Votes and comments are locked')} + {/if} +

      {$rule_icon} {$rule_txt}

      + +
      +
      +
      + {/if}
      {if $admin}{/if} From 8e15a008fea4fc2a324d7f4635325cb1c82906e8 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 18 Dec 2014 13:57:25 +0100 Subject: [PATCH 035/151] adminstuds.php: Realize the update of poll in database --- adminstuds.php | 59 ++++++++++++++++++- app/classes/Framadate/FramaDB.php | 6 ++ .../Framadate/Services/InputService.php | 6 +- .../Framadate/Services/PollService.php | 4 ++ 4 files changed, 72 insertions(+), 3 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index 11eb8eb..f0bc76c 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -40,8 +40,8 @@ $inputService = new InputService(); /* PAGE */ /* ---- */ -if(!empty($_GET['poll']) && strlen($_GET['poll']) === 24) { - $admin_poll_id = filter_input(INPUT_GET, 'poll', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9]+$/']]); +if (!empty($_GET['poll']) && strlen($_GET['poll']) === 24) { + $admin_poll_id = filter_input(INPUT_GET, 'poll', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^[a-z0-9]+$/']]); $poll_id = substr($admin_poll_id, 0, 16); $poll = $pollService->findById($poll_id); } @@ -52,6 +52,61 @@ if (!$poll) { exit; } +// ------------------------------- +// Update poll info +// ------------------------------- +if (isset($_POST['update_poll_info'])) { + $updated = false; + $field = $inputService->filterAllowedValues($_POST['update_poll_info'], ['title', 'admin_mail', 'comment', 'rules']); + + // Update the right poll field + if ($field == 'title') { + $title = $filter_input(INPUT_POST, 'title', FILTER_DEFAULT); + if ($title) { + $poll->title = $title; + $updated = true; + } + } elseif ($field == 'admin_mail') { + $admin_mail = filter_input(INPUT_POST, 'admin_mail', FILTER_VALIDATE_EMAIL); + if ($admin_mail) { + $poll->admin_mail = $admin_mail; + $updated = true; + } + } elseif ($field == 'comment') { + $comment = filter_input(INPUT_POST, 'comment', FILTER_DEFAULT); + if ($comment) { + $poll->comment = $comment; + $updated = true; + } + } elseif ($field == 'rules') { + $rules = filter_input(INPUT_POST, 'rules', FILTER_DEFAULT); + switch ($rules) { + case 0: + $poll->active = false; + $poll->editable = false; + $updated = true; + break; + case 1: + $poll->active = true; + $poll->editable = false; + $updated = true; + break; + case 2: + $poll->active = true; + $poll->editable = true; + $updated = true; + break; + } + } + + // Update poll in database + if ($updated && $pollService->updatePoll($poll)) { + $message = new Message('success', _('Poll saved.')); + } else { + $message = new Message('danger', _('Failed to save poll.')); + } +} + // Retrieve data $slots = $pollService->allSlotsByPollId($poll_id); $votes = $pollService->allUserVotesByPollId($poll_id); diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index fcaa4a5..8978772 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -65,6 +65,12 @@ class FramaDB return $poll; } + function updatePoll($poll) { + $prepared = $this->prepare('UPDATE sondage SET title=?, admin_mail=?, comment=?, active=?, editable=? WHERE sondage.poll_id = ?'); + + return $prepared->execute([$poll->title, $poll->admin_mail, $poll->comment, $poll->active, $poll->editable, $poll->poll_id]); + } + function allCommentsByPollId($poll_id) { $prepared = $this->prepare('SELECT * FROM comments WHERE id_sondage = ? ORDER BY id_comment'); $prepared->execute(array($poll_id)); diff --git a/app/classes/Framadate/Services/InputService.php b/app/classes/Framadate/Services/InputService.php index d48f4f0..d985bb5 100644 --- a/app/classes/Framadate/Services/InputService.php +++ b/app/classes/Framadate/Services/InputService.php @@ -29,7 +29,7 @@ class InputService { * This method filter an array calling "filter_var" on each items. * Only items validated are added at their own indexes, the others are not returned. */ - function filterArray($arr, $type, $options) { + function filterArray(array $arr, $type, $options) { $newArr = []; foreach($arr as $id=>$item) { @@ -42,4 +42,8 @@ class InputService { return $newArr; } + function filterAllowedValues($value, array $allowedValues) { + return in_array($value, $allowedValues, true) ? $value : null; + } + } \ No newline at end of file diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 33959f0..9256b27 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -34,6 +34,10 @@ class PollService { return null; } + function updatePoll($poll) { + return $this->connect->updatePoll($poll); + } + function allCommentsByPollId($poll_id) { return $this->connect->allCommentsByPollId($poll_id); } From 446bbece5800282918646b7125603b190088a192 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 18 Dec 2014 23:57:00 +0100 Subject: [PATCH 036/151] Add a missing $ --- tpl/part/poll_info.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tpl/part/poll_info.tpl b/tpl/part/poll_info.tpl index 6ba1b95..a8b8c8d 100644 --- a/tpl/part/poll_info.tpl +++ b/tpl/part/poll_info.tpl @@ -87,7 +87,7 @@
      {/if}
      - {if admin} + {if $admin}
      From 187c84074e91992f2b1d1678cf5a6c5f8f0c7f93 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 18 Dec 2014 23:57:38 +0100 Subject: [PATCH 037/151] Display a different hint pane on admin page. --- tpl/part/poll_hint.tpl | 11 +++++++++++ tpl/part/poll_hint_admin.tpl | 7 +++++++ tpl/studs.tpl | 12 +++--------- 3 files changed, 21 insertions(+), 9 deletions(-) create mode 100644 tpl/part/poll_hint.tpl create mode 100644 tpl/part/poll_hint_admin.tpl diff --git a/tpl/part/poll_hint.tpl b/tpl/part/poll_hint.tpl new file mode 100644 index 0000000..341a9f1 --- /dev/null +++ b/tpl/part/poll_hint.tpl @@ -0,0 +1,11 @@ +{if $active} +
      +

      {_("If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line.")}

      + +
      +{else} +
      +

      {_("The administrator locked this poll, votes and comments are frozen, it's not possible to participate anymore.")}

      + +
      +{/if} \ No newline at end of file diff --git a/tpl/part/poll_hint_admin.tpl b/tpl/part/poll_hint_admin.tpl new file mode 100644 index 0000000..7a21be1 --- /dev/null +++ b/tpl/part/poll_hint_admin.tpl @@ -0,0 +1,7 @@ +
      +

      {_('As poll administrator, you can change all the lines of this poll with this button')} {_('Edit')}, + {_(' remove a column or a line with')} {_('Remove')} + {_('and add a new column with')} {_('Add a column')}.

      +

      {_('Finally, you can change the informations of this poll like the title, the comments or your email address.')}

      + +
      \ No newline at end of file diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 879cbbd..de89e8a 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -12,16 +12,10 @@ {* Information about voting *} -{if $poll->active} -
      -

      {_("If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line.")}

      - -
      +{if $admin} + {include 'part/poll_hint_admin.tpl'} {else} -
      -

      {_("The administrator locked this poll, votes and comments are frozen, it's not possible to participate anymore.")}

      - -
      + {include 'part/poll_hint.tpl' active=$poll->active} {/if} {* Scroll left and right *} From 178208380f93692e6d2fa8be8c55dc7f542ade90 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Fri, 19 Dec 2014 00:12:19 +0100 Subject: [PATCH 038/151] Change color of text-danger. --- css/frama.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/css/frama.css b/css/frama.css index bf0a0cb..0c0a6c9 100644 --- a/css/frama.css +++ b/css/frama.css @@ -47,7 +47,7 @@ a.text-info:focus { .text-warning, .text-warning a, a.text-warning { - color: #8A6E3B; + color: #C05827; } .text-warning a:hover, .text-warning a:focus, From 1b01bcc6b6bd08686a08b3c85fb30bcd86fc54dc Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Fri, 19 Dec 2014 00:13:21 +0100 Subject: [PATCH 039/151] admin: Add availability to delete comments one by one. --- adminstuds.php | 14 ++++ app/classes/Framadate/FramaDB.php | 5 ++ .../Framadate/Services/PollService.php | 4 ++ tpl/part/comments.tpl | 68 ++++++++++--------- 4 files changed, 59 insertions(+), 32 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index f0bc76c..676922d 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -55,6 +55,7 @@ if (!$poll) { // ------------------------------- // Update poll info // ------------------------------- + if (isset($_POST['update_poll_info'])) { $updated = false; $field = $inputService->filterAllowedValues($_POST['update_poll_info'], ['title', 'admin_mail', 'comment', 'rules']); @@ -107,6 +108,19 @@ if (isset($_POST['update_poll_info'])) { } } +// ------------------------------- +// Delete a comment +// ------------------------------- +if (!empty($_POST['delete_comment'])) { + $comment_id = filter_input(INPUT_POST, 'delete_comment', FILTER_VALIDATE_INT); + + if ($pollService->deleteComment($poll_id, $comment_id)) { + $message = new Message('success', _('Comment deleted.')); + } else { + $message = new Message('danger', _('Failed to delete the comment.')); + } +} + // Retrieve data $slots = $pollService->allSlotsByPollId($poll_id); $votes = $pollService->allUserVotesByPollId($poll_id); diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 8978772..f20f80e 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -112,4 +112,9 @@ class FramaDB return $prepared->execute([$poll_id, $name, $comment]); } + function deleteComment($poll_id, $comment_id) { + $prepared = $this->prepare('DELETE FROM comments WHERE id_sondage = ? AND id_comment = ?'); + return $prepared->execute([$poll_id, $comment_id]); + } + } diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 9256b27..d1fb923 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -64,6 +64,10 @@ class PollService { return $this->connect->insertComment($poll_id, $name, $comment); } + function deleteComment($poll_id, $comment_id) { + return $this->connect->deleteComment($poll_id, $comment_id); + } + function computeBestMoments($votes) { $result = []; foreach ($votes as $vote) { diff --git a/tpl/part/comments.tpl b/tpl/part/comments.tpl index 4e9f09c..a9bb572 100644 --- a/tpl/part/comments.tpl +++ b/tpl/part/comments.tpl @@ -1,36 +1,40 @@ +
      -{* Comment list *} + {* Comment list *} -{if $comments|count > 0} - {foreach $comments as $comment} -
      - {$comment->usercomment}  - {nl2br($comment->comment)} + {if $comments|count > 0} +

      {_("Comments of polled people")}

      + {foreach $comments as $comment} +
      + {if $admin} + + {/if} + {$comment->usercomment}  + {nl2br($comment->comment)} +
      + {/foreach} + {/if} + + {* Add comment form *} + {if $active} +
      +
      +
      {_("Add a comment to the poll")} +
      + + +
      +
      + + +
      +
      + +
      +
      +
      +
      - {/foreach} -{/if} - -{* Add comment form *} -{if $active} -
      - -
      -
      {_("Add a comment to the poll")} -
      - - -
      -
      - - -
      -
      - -
      -
      -
      -
      - -
      -{/if} \ No newline at end of file + {/if} + \ No newline at end of file From 14727bd94c367646472797a9cd5908c18734c5b9 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Fri, 19 Dec 2014 00:27:30 +0100 Subject: [PATCH 040/151] admin: Add availability to delete all votes of a poll. --- adminstuds.php | 8 ++++++++ app/classes/Framadate/FramaDB.php | 14 ++++++++++++++ app/classes/Framadate/Services/PollService.php | 4 ++++ 3 files changed, 26 insertions(+) diff --git a/adminstuds.php b/adminstuds.php index 676922d..6da08c6 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -52,6 +52,13 @@ if (!$poll) { exit; } +// ------------------------------- +// Remove all votes +// ------------------------------- +if (isset($_POST['remove_all_votes'])) { + $pollService->cleanVotes($admin_poll_id, $poll_id); +} + // ------------------------------- // Update poll info // ------------------------------- @@ -111,6 +118,7 @@ if (isset($_POST['update_poll_info'])) { // ------------------------------- // Delete a comment // ------------------------------- + if (!empty($_POST['delete_comment'])) { $comment_id = filter_input(INPUT_POST, 'delete_comment', FILTER_VALIDATE_INT); diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index f20f80e..2359bc1 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -102,6 +102,20 @@ class FramaDB return $newVote; } + function deleteVotesByAdminPollId($admin_poll_id, $poll_id) { + $prepared = $this->prepare('SELECT 1 FROM sondage WHERE admin_poll_id = ? AND poll_id = ?'); + $prepared->execute([$admin_poll_id, $poll_id]); + $count = $prepared->rowCount(); + $prepared->closeCursor(); + + if ($count === 1) { + $prepared = $this->prepare('DELETE FROM user_studs WHERE id_sondage = ?'); + return $prepared->execute([$poll_id]); + } else { + return null; + } + } + function updateVote($poll_id, $vote_id, $choices) { $prepared = $this->prepare('UPDATE user_studs SET reponses = ? WHERE id_sondage = ? AND id_users = ?'); return $prepared->execute([$choices, $poll_id, $vote_id]); diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index d1fb923..34d93e1 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -60,6 +60,10 @@ class PollService { return $this->connect->insertVote($poll_id, $name, $choices); } + function cleanVotes($admin_poll_id, $poll_id) { + $this->connect->deleteVotesByAdminPollId($admin_poll_id, $poll_id); + } + function addComment($poll_id, $name, $comment) { return $this->connect->insertComment($poll_id, $name, $comment); } From 3d18c208ca260de2b1073f876ee035337af00543 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Fri, 19 Dec 2014 00:28:20 +0100 Subject: [PATCH 041/151] Check the number and the max of votes before displaying the best moments. --- tpl/part/vote_table.tpl | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/tpl/part/vote_table.tpl b/tpl/part/vote_table.tpl index b9f9186..75408dd 100644 --- a/tpl/part/vote_table.tpl +++ b/tpl/part/vote_table.tpl @@ -1,3 +1,7 @@ +{if !is_array($best_moments) || empty($best_moments)} + {$best_moments = [0]} +{/if} +

      {_('Votes of the poll')}

      @@ -142,18 +146,20 @@ {* Line displaying best moments *} {$count_bests = 0} - - {_("Addition")} - {$max = max($best_moments)} - {foreach $best_moments as $best_moment} - {if $max == $best_moment} - {$count_bests = $count_bests +1} - {$max} - {else} - - {/if} - {/foreach} - + {$max = max($best_moments)} + {if $max > 0} + + {_("Addition")} + {foreach $best_moments as $best_moment} + {if $max == $best_moment} + {$count_bests = $count_bests +1} + {$max} + {else} + + {/if} + {/foreach} + + {/if} From 07d5a336fbe1e40e0b1c2539a347591a28660148 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Fri, 19 Dec 2014 00:36:09 +0100 Subject: [PATCH 042/151] Add availability to delete all comments of one poll. + Simplify call to remove all votes of one poll --- adminstuds.php | 9 +++++- app/classes/Framadate/FramaDB.php | 30 ++++++++++++------- .../Framadate/Services/PollService.php | 8 +++-- 3 files changed, 33 insertions(+), 14 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index 6da08c6..689d51b 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -56,7 +56,14 @@ if (!$poll) { // Remove all votes // ------------------------------- if (isset($_POST['remove_all_votes'])) { - $pollService->cleanVotes($admin_poll_id, $poll_id); + $pollService->cleanVotes($poll_id); +} + +// ------------------------------- +// Remove all comments +// ------------------------------- +if (isset($_POST['remove_all_comments'])) { + $pollService->cleanComments($poll_id); } // ------------------------------- diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 2359bc1..33f97b9 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -102,18 +102,26 @@ class FramaDB return $newVote; } - function deleteVotesByAdminPollId($admin_poll_id, $poll_id) { - $prepared = $this->prepare('SELECT 1 FROM sondage WHERE admin_poll_id = ? AND poll_id = ?'); - $prepared->execute([$admin_poll_id, $poll_id]); - $count = $prepared->rowCount(); - $prepared->closeCursor(); + /** + * Delete all votes of a given poll. + * + * @param $poll_id int The ID of the given poll. + * @return bool|null true if action succeeded. + */ + function deleteVotesByAdminPollId($poll_id) { + $prepared = $this->prepare('DELETE FROM user_studs WHERE id_sondage = ?'); + return $prepared->execute([$poll_id]); + } - if ($count === 1) { - $prepared = $this->prepare('DELETE FROM user_studs WHERE id_sondage = ?'); - return $prepared->execute([$poll_id]); - } else { - return null; - } + /** + * Delete all comments of a given poll. + * + * @param $poll_id int The ID of the given poll. + * @return bool|null true if action succeeded. + */ + function deleteCommentssByAdminPollId($poll_id) { + $prepared = $this->prepare('DELETE FROM comments WHERE id_sondage = ?'); + return $prepared->execute([$poll_id]); } function updateVote($poll_id, $vote_id, $choices) { diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 34d93e1..ca73c9c 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -60,8 +60,8 @@ class PollService { return $this->connect->insertVote($poll_id, $name, $choices); } - function cleanVotes($admin_poll_id, $poll_id) { - $this->connect->deleteVotesByAdminPollId($admin_poll_id, $poll_id); + function cleanVotes($poll_id) { + $this->connect->deleteVotesByAdminPollId($poll_id); } function addComment($poll_id, $name, $comment) { @@ -72,6 +72,10 @@ class PollService { return $this->connect->deleteComment($poll_id, $comment_id); } + function cleanComments($poll_id) { + $this->connect->deleteCommentssByAdminPollId($poll_id); + } + function computeBestMoments($votes) { $result = []; foreach ($votes as $vote) { From 3829402a693c49153f1677e6729a234015e28230 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Fri, 19 Dec 2014 00:47:56 +0100 Subject: [PATCH 043/151] Display a confirmation page before delete the poll (confirmation does nothing for now) --- adminstuds.php | 15 +++++++++++++++ tpl/confirm/delete_poll.tpl | 11 +++++++++++ 2 files changed, 26 insertions(+) create mode 100644 tpl/confirm/delete_poll.tpl diff --git a/adminstuds.php b/adminstuds.php index 689d51b..8435200 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -136,6 +136,21 @@ if (!empty($_POST['delete_comment'])) { } } + +// ------------------------------- +// Delete the entire poll +// ------------------------------- + +if (isset($_POST['delete_poll'])) { + $smarty->assign('poll_id', $poll_id); + $smarty->assign('admin_poll_id', $admin_poll_id); + $smarty->display('confirm/delete_poll.tpl'); + exit; +} +if (isset($_POST['confirm_delete_poll'])) { + // TODO +} + // Retrieve data $slots = $pollService->allSlotsByPollId($poll_id); $votes = $pollService->allUserVotesByPollId($poll_id); diff --git a/tpl/confirm/delete_poll.tpl b/tpl/confirm/delete_poll.tpl new file mode 100644 index 0000000..89e33bb --- /dev/null +++ b/tpl/confirm/delete_poll.tpl @@ -0,0 +1,11 @@ +{extends file='page.tpl'} + +{block name=main} +
      +
      +

      {_("Confirm removal of your poll")}

      +

      +

      +
      +
      +{/block} \ No newline at end of file From 94a125ca2bf6433321d861ea37a96a774fafbc15 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Fri, 19 Dec 2014 00:59:27 +0100 Subject: [PATCH 044/151] Display confirmation page before to delete all comments of one poll. --- adminstuds.php | 39 ++++++++++++------- .../Framadate/Services/PollService.php | 16 +++++++- tpl/confirm/delete_comment.tpl | 11 ++++++ 3 files changed, 50 insertions(+), 16 deletions(-) create mode 100644 tpl/confirm/delete_comment.tpl diff --git a/adminstuds.php b/adminstuds.php index 8435200..84b8485 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -52,20 +52,6 @@ if (!$poll) { exit; } -// ------------------------------- -// Remove all votes -// ------------------------------- -if (isset($_POST['remove_all_votes'])) { - $pollService->cleanVotes($poll_id); -} - -// ------------------------------- -// Remove all comments -// ------------------------------- -if (isset($_POST['remove_all_comments'])) { - $pollService->cleanComments($poll_id); -} - // ------------------------------- // Update poll info // ------------------------------- @@ -136,6 +122,30 @@ if (!empty($_POST['delete_comment'])) { } } +// ------------------------------- +// Remove all votes +// ------------------------------- +if (isset($_POST['remove_all_votes'])) { + $pollService->cleanVotes($poll_id); +} + +// ------------------------------- +// Remove all comments +// ------------------------------- +if (isset($_POST['remove_all_comments'])) { + $smarty->assign('poll_id', $poll_id); + $smarty->assign('admin_poll_id', $admin_poll_id); + $smarty->assign('title', _('Poll') . ' - ' . $poll->title); + $smarty->display('confirm/delete_comment.tpl'); + exit; +} +if (isset($_POST['confirm_remove_all_comments'])) { + if ($pollService->cleanComments($poll_id)) { + $message = new Message('success', _('All comments deleted.')); + } else { + $message = new Message('danger', _('Failed to delete all comments.')); + } +} // ------------------------------- // Delete the entire poll @@ -144,6 +154,7 @@ if (!empty($_POST['delete_comment'])) { if (isset($_POST['delete_poll'])) { $smarty->assign('poll_id', $poll_id); $smarty->assign('admin_poll_id', $admin_poll_id); + $smarty->assign('title', _('Poll') . ' - ' . $poll->title); $smarty->display('confirm/delete_poll.tpl'); exit; } diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index ca73c9c..cf97b41 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -60,8 +60,14 @@ class PollService { return $this->connect->insertVote($poll_id, $name, $choices); } + /** + * Remove all votes of a poll. + * + * @param $poll_id int The ID a the poll + * @return bool|null true is action succeeded + */ function cleanVotes($poll_id) { - $this->connect->deleteVotesByAdminPollId($poll_id); + return $this->connect->deleteVotesByAdminPollId($poll_id); } function addComment($poll_id, $name, $comment) { @@ -72,8 +78,14 @@ class PollService { return $this->connect->deleteComment($poll_id, $comment_id); } + /** + * Remove all comments of a poll. + * + * @param $poll_id int The ID a the poll + * @return bool|null true is action succeeded + */ function cleanComments($poll_id) { - $this->connect->deleteCommentssByAdminPollId($poll_id); + return $this->connect->deleteCommentssByAdminPollId($poll_id); } function computeBestMoments($votes) { diff --git a/tpl/confirm/delete_comment.tpl b/tpl/confirm/delete_comment.tpl new file mode 100644 index 0000000..739be74 --- /dev/null +++ b/tpl/confirm/delete_comment.tpl @@ -0,0 +1,11 @@ +{extends file='page.tpl'} + +{block name=main} +
      +
      +

      {_("Confirm removal of all comments of the poll")}

      +

      +

      +
      +
      +{/block} \ No newline at end of file From 8d46ec6c33471676c6451311611a86054cc6c5bf Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sat, 20 Dec 2014 23:59:44 +0100 Subject: [PATCH 045/151] Move all admin method from PollService to AdminPollService --- adminstuds.php | 10 +++-- .../Framadate/Services/AdminPollService.php | 45 +++++++++++++++++++ .../Framadate/Services/PollService.php | 28 ------------ 3 files changed, 51 insertions(+), 32 deletions(-) create mode 100644 app/classes/Framadate/Services/AdminPollService.php diff --git a/adminstuds.php b/adminstuds.php index 84b8485..0aad6ed 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -17,6 +17,7 @@ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ use Framadate\Services\PollService; +use Framadate\Services\AdminPollService; use Framadate\Services\InputService; use Framadate\Message; use Framadate\Utils; @@ -35,6 +36,7 @@ $editingVoteId = 0; /*----------*/ $pollService = new PollService($connect); +$adminPollService = new AdminPollService($connect); $inputService = new InputService(); /* PAGE */ @@ -101,7 +103,7 @@ if (isset($_POST['update_poll_info'])) { } // Update poll in database - if ($updated && $pollService->updatePoll($poll)) { + if ($updated && $adminPollService->updatePoll($poll)) { $message = new Message('success', _('Poll saved.')); } else { $message = new Message('danger', _('Failed to save poll.')); @@ -115,7 +117,7 @@ if (isset($_POST['update_poll_info'])) { if (!empty($_POST['delete_comment'])) { $comment_id = filter_input(INPUT_POST, 'delete_comment', FILTER_VALIDATE_INT); - if ($pollService->deleteComment($poll_id, $comment_id)) { + if ($adminPollService->deleteComment($poll_id, $comment_id)) { $message = new Message('success', _('Comment deleted.')); } else { $message = new Message('danger', _('Failed to delete the comment.')); @@ -126,7 +128,7 @@ if (!empty($_POST['delete_comment'])) { // Remove all votes // ------------------------------- if (isset($_POST['remove_all_votes'])) { - $pollService->cleanVotes($poll_id); + $adminPollService->cleanVotes($poll_id); } // ------------------------------- @@ -140,7 +142,7 @@ if (isset($_POST['remove_all_comments'])) { exit; } if (isset($_POST['confirm_remove_all_comments'])) { - if ($pollService->cleanComments($poll_id)) { + if ($adminPollService->cleanComments($poll_id)) { $message = new Message('success', _('All comments deleted.')); } else { $message = new Message('danger', _('Failed to delete all comments.')); diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php new file mode 100644 index 0000000..bf49ce9 --- /dev/null +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -0,0 +1,45 @@ +connect = $connect; + } + + function updatePoll($poll) { + return $this->connect->updatePoll($poll); + } + + function deleteComment($poll_id, $comment_id) { + return $this->connect->deleteComment($poll_id, $comment_id); + } + + /** + * Remove all comments of a poll. + * + * @param $poll_id int The ID a the poll + * @return bool|null true is action succeeded + */ + function cleanComments($poll_id) { + return $this->connect->deleteCommentssByAdminPollId($poll_id); + } + + /** + * Remove all votes of a poll. + * + * @param $poll_id int The ID a the poll + * @return bool|null true is action succeeded + */ + function cleanVotes($poll_id) { + return $this->connect->deleteVotesByAdminPollId($poll_id); + } + +} + \ No newline at end of file diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index cf97b41..33959f0 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -34,10 +34,6 @@ class PollService { return null; } - function updatePoll($poll) { - return $this->connect->updatePoll($poll); - } - function allCommentsByPollId($poll_id) { return $this->connect->allCommentsByPollId($poll_id); } @@ -60,34 +56,10 @@ class PollService { return $this->connect->insertVote($poll_id, $name, $choices); } - /** - * Remove all votes of a poll. - * - * @param $poll_id int The ID a the poll - * @return bool|null true is action succeeded - */ - function cleanVotes($poll_id) { - return $this->connect->deleteVotesByAdminPollId($poll_id); - } - function addComment($poll_id, $name, $comment) { return $this->connect->insertComment($poll_id, $name, $comment); } - function deleteComment($poll_id, $comment_id) { - return $this->connect->deleteComment($poll_id, $comment_id); - } - - /** - * Remove all comments of a poll. - * - * @param $poll_id int The ID a the poll - * @return bool|null true is action succeeded - */ - function cleanComments($poll_id) { - return $this->connect->deleteCommentssByAdminPollId($poll_id); - } - function computeBestMoments($votes) { $result = []; foreach ($votes as $vote) { From 45716d15c1aef18fa036eec7bd8678de5fd65081 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 21 Dec 2014 00:04:23 +0100 Subject: [PATCH 046/151] Display confirmation page before to delete all votes of one poll. --- adminstuds.php | 7 +++++++ tpl/confirm/delete_votes.tpl | 11 +++++++++++ 2 files changed, 18 insertions(+) create mode 100644 tpl/confirm/delete_votes.tpl diff --git a/adminstuds.php b/adminstuds.php index 0aad6ed..0fbbef1 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -128,6 +128,13 @@ if (!empty($_POST['delete_comment'])) { // Remove all votes // ------------------------------- if (isset($_POST['remove_all_votes'])) { + $smarty->assign('poll_id', $poll_id); + $smarty->assign('admin_poll_id', $admin_poll_id); + $smarty->assign('title', _('Poll') . ' - ' . $poll->title); + $smarty->display('confirm/delete_votes.tpl'); + exit; +} +if (isset($_POST['confirm_remove_all_votes'])) { $adminPollService->cleanVotes($poll_id); } diff --git a/tpl/confirm/delete_votes.tpl b/tpl/confirm/delete_votes.tpl new file mode 100644 index 0000000..28490b0 --- /dev/null +++ b/tpl/confirm/delete_votes.tpl @@ -0,0 +1,11 @@ +{extends file='page.tpl'} + +{block name=main} +
      +
      +

      {_("Confirm removal of all votes of the poll")}

      +

      +

      +
      +
      +{/block} \ No newline at end of file From 26b0c081286aa7c5240dc1001f4f29906458f5cc Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 21 Dec 2014 00:04:41 +0100 Subject: [PATCH 047/151] Fix filter_input call --- adminstuds.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminstuds.php b/adminstuds.php index 0fbbef1..9297237 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -64,7 +64,7 @@ if (isset($_POST['update_poll_info'])) { // Update the right poll field if ($field == 'title') { - $title = $filter_input(INPUT_POST, 'title', FILTER_DEFAULT); + $title = filter_input(INPUT_POST, 'title', FILTER_DEFAULT); if ($title) { $poll->title = $title; $updated = true; From ce548da367b3f7c286f629346386b522e995ba8e Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 21 Dec 2014 00:05:52 +0100 Subject: [PATCH 048/151] Rename delete_comment.tpl to delete_comments.tpl --- adminstuds.php | 2 +- tpl/confirm/{delete_comment.tpl => delete_comments.tpl} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename tpl/confirm/{delete_comment.tpl => delete_comments.tpl} (100%) diff --git a/adminstuds.php b/adminstuds.php index 9297237..999d978 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -145,7 +145,7 @@ if (isset($_POST['remove_all_comments'])) { $smarty->assign('poll_id', $poll_id); $smarty->assign('admin_poll_id', $admin_poll_id); $smarty->assign('title', _('Poll') . ' - ' . $poll->title); - $smarty->display('confirm/delete_comment.tpl'); + $smarty->display('confirm/delete_comments.tpl'); exit; } if (isset($_POST['confirm_remove_all_comments'])) { diff --git a/tpl/confirm/delete_comment.tpl b/tpl/confirm/delete_comments.tpl similarity index 100% rename from tpl/confirm/delete_comment.tpl rename to tpl/confirm/delete_comments.tpl From b8d0110263c16e6085297b58518e6618e5d470f6 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 21 Dec 2014 00:14:56 +0100 Subject: [PATCH 049/151] Remove code from old_adminstuds that is already refactored. --- adminstuds.php | 4 + .../Framadate/Services/PollService.php | 1 + old_adminstuds.php | 238 ------------------ 3 files changed, 5 insertions(+), 238 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index 999d978..72120d5 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -110,6 +110,10 @@ if (isset($_POST['update_poll_info'])) { } } +// TODO Handle Add/Edit vote form + +// TODO Handle Add comment form + // ------------------------------- // Delete a comment // ------------------------------- diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 33959f0..bd7c6c7 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -57,6 +57,7 @@ class PollService { } function addComment($poll_id, $name, $comment) { + // TODO Check if there is no duplicate before to add a new comment return $this->connect->insertComment($poll_id, $name, $comment); } diff --git a/old_adminstuds.php b/old_adminstuds.php index 53a0122..7a734d2 100644 --- a/old_adminstuds.php +++ b/old_adminstuds.php @@ -18,56 +18,6 @@ */ namespace Framadate; -session_start(); - -//setlocale(LC_TIME, "fr_FR"); -include_once __DIR__ . '/app/inc/init.php'; - -if (file_exists('bandeaux_local.php')) { - include_once('bandeaux_local.php'); -} else { - include_once('bandeaux.php'); -} - -// recuperation du numero de sondage admin (24 car.) dans l'URL -if (!empty($_GET['sondage']) && is_string($_GET['sondage']) && strlen($_GET['sondage']) === 24) { - $admin_poll_id = $_GET["sondage"]; - // on découpe le résultat pour avoir le numéro de sondage (16 car.) - $poll_id = substr($admin_poll_id, 0, 16); -} - -if (preg_match(";[\w\d]{24};i", $admin_poll_id)) { - $prepared = $connect->prepare('SELECT * FROM sondage WHERE admin_poll_id = ?'); - $prepared->execute(array($admin_poll_id)); - $poll = $prepared->fetch(); - $prepared->closeCursor(); - - $prepared = $connect->prepare('SELECT * FROM sujet_studs WHERE id_sondage = ?'); - $prepared->execute(array($poll_id)); - $sujets = $prepared->fetchAll(); - - $prepared = $connect->prepare('SELECT * FROM user_studs WHERE id_sondage = ? order by id_users'); - $prepared->execute(array($poll_id)); - $users = $prepared->fetchAll(); -} - -//verification de l'existence du sondage, s'il n'existe pas on met une page d'erreur -if (!$poll || !$sujets) { - Utils::print_header( _('Error!')); - - bandeau_titre(_('Error!')); - - echo ' -
      -

      ' . _('This poll doesn\'t exist !') . '

      -

      ' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

      -
      '."\n"; - - bandeau_pied(); - - die(); -} - // Send email (only once during the session) to alert admin of the change he made. ==> two modifications (comment, title, description, ...) on differents polls in the same session will generate only one mail. $email_admin = $poll->admin_mail; $poll_title = $poll->title; @@ -91,80 +41,6 @@ function send_mail_admin() { } -//si la valeur du nouveau titre est valide et que le bouton est activé -if (isset($_POST["boutonnouveautitre"])) { - if (Utils::issetAndNoEmpty('nouveautitre') === false) { - $err |= TITLE_EMPTY; - } else { - //Update SQL database with new title - $nouveautitre = htmlentities(html_entity_decode($_POST['nouveautitre'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - $sql = 'UPDATE sondage SET titre = '.$connect->Param('nouveautitre').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - - //Email sent to the admin - if ($connect->Execute($sql, array($nouveautitre, $poll_id))) { - send_mail_admin(); - } - } -} - -// si le bouton est activé, quelque soit la valeur du champ textarea -if (isset($_POST['boutonnouveauxcommentaires'])) { - if (empty($_POST['nouveautitre'])) { - $err |= COMMENT_EMPTY; - } else { - $commentaires = htmlentities(html_entity_decode($_POST['nouveauxcommentaires'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - - //Update SQL database with new description - $prepared = $connect->prepare('UPDATE sondage SET commentaires = ? WHERE id_sondage = ?'); - $prepared->execute(array($commentaires, $poll_id)); - - //Email sent to the admin - if ($connect->Execute($sql, array($commentaires, $poll_id))) { - send_mail_admin(); - } - } -} - -//si la valeur de la nouvelle adresse est valide et que le bouton est activé -if (isset($_POST["boutonnouvelleadresse"])) { - if (empty($_POST['nouvelleadresse']) || Utils::isValidEmail($_POST["nouvelleadresse"]) === false) { - $err |= INVALID_EMAIL; - } else { - $nouvelleadresse = htmlentities(html_entity_decode($_POST['nouvelleadresse'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - - //Update SQL database with new email - $prepared = $connect->prepare('UPDATE sondage SET mail_admin = ? WHERE id_sondage = ?'); - $executed = $prepared->execute(array($nouvelleadresse, $poll_id)); - - //Email sent to the admin - if ($executed) { - send_mail_admin(); - } - } -} - -// TODO OPZ : Revoir ce que fait ce truc exactament -//New poll rules -if (isset($_POST["btn_poll_rules"])) { - echo ''; - if($_POST['poll_rules'] == '+') { - $new_poll_rules = substr($dsondage->format, 0, 1).'+'; - } elseif($_POST['poll_rules'] == '-') { - $new_poll_rules = substr($dsondage->format, 0, 1).'-'; - } else { - $new_poll_rules = substr($dsondage->format, 0, 1); - } - - //Update SQL database with new rules - $prepared = $connect->prepare('UPDATE sondage SET format = ? WHERE id_sondage = ?'); - $executed = $prepared->execute(array($new_poll_rules, $poll_id)); - - //Email sent to the admin - if ($executed) { - send_mail_admin(); - } -} // reload // TODO OPZ Pourquoi recharger @@ -228,39 +104,6 @@ if (isset($_POST['ajoutsujet'])) { die(); } -if (isset($_POST["suppressionsondage"])) { - Utils::print_header( _("Confirm removal of your poll") .' - ' . stripslashes( $dsondage->title )); - - bandeau_titre(_("Confirm removal of your poll")); - - echo ' -
      -
      -

      ' . _("Confirm removal of your poll") . '

      -

      -

      -
      -
      '; - - bandeau_pied(); - - die(); -} - -// Remove all the comments -if (isset($_POST['removecomments'])) { - $sql = 'DELETE FROM comments WHERE id_sondage='.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $cleaning = $connect->Execute($sql, array($poll_id)); -} - -// Remove all the votes -if (isset($_POST["removevotes"])) { - $sql = 'DELETE FROM user_studs WHERE id_sondage='.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $cleaning = $connect->Execute($sql, array($poll_id)); -} - //action si bouton confirmation de suppression est activé if (isset($_POST["confirmesuppression"])) { $nbuser=$user_studs->RecordCount(); @@ -290,92 +133,11 @@ if (isset($_POST["confirmesuppression"])) { } } -// quand on ajoute un commentaire utilisateur -if (isset($_POST['ajoutcomment'])) { - if (empty($_POST['commentuser'])) { - $err |= COMMENT_USER_EMPTY; - } else { - $comment_user = htmlentities(html_entity_decode($_POST["commentuser"], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - } - - if(empty($_POST['comment'])) { - $err |= COMMENT_EMPTY; - } - - if (!empty($_POST['comment']) && !Utils::is_error(COMMENT_EMPTY) && !Utils::is_error(NO_POLL) && !Utils::is_error(COMMENT_USER_EMPTY)) { - $comment = htmlentities(html_entity_decode($_POST["comment"], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - - // Check for doublons - $comment_doublon = false; - $req = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; - $sql = $connect->Prepare($req); - $comment_user_doublon = $connect->Execute($sql, array($poll_id)); - if ($comment_user_doublon->RecordCount() != 0) { - while ( $dcomment_user_doublon=$comment_user_doublon->FetchNextObject(false)) { - if($dcomment_user_doublon->comment == $comment && $dcomment_user_doublon->usercomment == $comment_user) { - $comment_doublon = true; - }; - } - } - - if(!$comment_doublon) { - $req = 'INSERT INTO comments (id_sondage, comment, usercomment) VALUES ('. - $connect->Param('id_sondage').','. - $connect->Param('comment').','. - $connect->Param('comment_user').')'; - $sql = $connect->Prepare($req); - - $comments = $connect->Execute($sql, array($poll_id, $comment, $comment_user)); - if ($comments === false) { - $err |= COMMENT_INSERT_FAILED; - } - } - } -} - $nbcolonnes = count($sujets); $nblignes = count($users); //si il n'y a pas suppression alors on peut afficher normalement le tableau -//action si le bouton participer est cliqué -if (isset($_POST["boutonp"])) { - //si on a un nom dans la case texte - if (!empty($_POST['nom'])){ - $nouveauchoix = ''; - $erreur_prenom = false; - - for ($i=0;$i<$nbcolonnes;$i++){ - // radio checked 1 = Yes, 2 = Ifneedbe, 0 = No - if (isset($_POST["choix$i"])) { - switch ($_POST["choix$i"]) { - case 1: $nouveauchoix .= "1";break; - case 2: $nouveauchoix .= "2";break; - default: $nouveauchoix .= "0";break; - } - } - } - - $nom = htmlentities(html_entity_decode($_POST["nom"], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - - while($user = $user_studs->FetchNextObject(false)) { - if ($nom == $user->nom){ - $erreur_prenom="yes"; - } - } - - // Ecriture des choix de l'utilisateur dans la base - if (!$erreur_prenom) { - $sql = 'INSERT INTO user_studs (nom, id_sondage, reponses) VALUES ('. - $connect->Param('nom').','. - $connect->Param('numsondage').','. - $connect->Param('nouveauchoix').')'; - - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($nom, $poll_id, $nouveauchoix)); - } - } -} //action quand on ajoute une colonne au format AUTRE From 1a062a2a6919c079aeb049c913e91bc286c7b651 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 21 Dec 2014 00:25:00 +0100 Subject: [PATCH 050/151] admin: Add availability to delete a vote. --- adminstuds.php | 28 +++++++++++++------ app/classes/Framadate/FramaDB.php | 7 ++++- .../Framadate/Services/AdminPollService.php | 22 +++++++++++++-- tpl/part/vote_table.tpl | 7 ++++- 4 files changed, 52 insertions(+), 12 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index 72120d5..f468032 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -115,16 +115,14 @@ if (isset($_POST['update_poll_info'])) { // TODO Handle Add comment form // ------------------------------- -// Delete a comment +// Delete a votes // ------------------------------- - -if (!empty($_POST['delete_comment'])) { - $comment_id = filter_input(INPUT_POST, 'delete_comment', FILTER_VALIDATE_INT); - - if ($adminPollService->deleteComment($poll_id, $comment_id)) { - $message = new Message('success', _('Comment deleted.')); +if (!empty($_POST['delete_vote'])) { + $vote_id = filter_input(INPUT_POST, 'delete_vote', FILTER_VALIDATE_INT); + if ($adminPollService->deleteVote($poll_id, $vote_id)) { + $message = new Message('success', _('Vote delete.')); } else { - $message = new Message('danger', _('Failed to delete the comment.')); + $message = new Message('danger', _('Failed to delete the vote.')); } } @@ -142,6 +140,20 @@ if (isset($_POST['confirm_remove_all_votes'])) { $adminPollService->cleanVotes($poll_id); } +// ------------------------------- +// Delete a comment +// ------------------------------- + +if (!empty($_POST['delete_comment'])) { + $comment_id = filter_input(INPUT_POST, 'delete_comment', FILTER_VALIDATE_INT); + + if ($adminPollService->deleteComment($poll_id, $comment_id)) { + $message = new Message('success', _('Comment deleted.')); + } else { + $message = new Message('danger', _('Failed to delete the comment.')); + } +} + // ------------------------------- // Remove all comments // ------------------------------- diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 33f97b9..102ccfb 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -102,6 +102,11 @@ class FramaDB return $newVote; } + function deleteVote($poll_id, $vote_id) { + $prepared = $this->prepare('DELETE FROM user_studs WHERE id_sondage = ? AND id_users = ?'); + return $prepared->execute([$poll_id, $vote_id]); + } + /** * Delete all votes of a given poll. * @@ -119,7 +124,7 @@ class FramaDB * @param $poll_id int The ID of the given poll. * @return bool|null true if action succeeded. */ - function deleteCommentssByAdminPollId($poll_id) { + function deleteCommentsByAdminPollId($poll_id) { $prepared = $this->prepare('DELETE FROM comments WHERE id_sondage = ?'); return $prepared->execute([$poll_id]); } diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php index bf49ce9..eee80a9 100644 --- a/app/classes/Framadate/Services/AdminPollService.php +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -17,6 +17,13 @@ class AdminPollService { return $this->connect->updatePoll($poll); } + /** + * Delete a comment from a poll. + * + * @param $poll_id int The ID of the poll + * @param $comment_id int The ID of the comment + * @return mixed true is action succeeded + */ function deleteComment($poll_id, $comment_id) { return $this->connect->deleteComment($poll_id, $comment_id); } @@ -28,13 +35,24 @@ class AdminPollService { * @return bool|null true is action succeeded */ function cleanComments($poll_id) { - return $this->connect->deleteCommentssByAdminPollId($poll_id); + return $this->connect->deleteCommentsByAdminPollId($poll_id); + } + + /** + * Delete a vote from a poll. + * + * @param $poll_id int The ID of the poll + * @param $vote_id int The ID of the vote + * @return mixed true is action succeeded + */ + function deleteVote($poll_id, $vote_id) { + return $this->connect->deleteVote($poll_id, $vote_id); } /** * Remove all votes of a poll. * - * @param $poll_id int The ID a the poll + * @param $poll_id int The ID of the poll * @return bool|null true is action succeeded */ function cleanVotes($poll_id) { diff --git a/tpl/part/vote_table.tpl b/tpl/part/vote_table.tpl index 75408dd..37829f8 100644 --- a/tpl/part/vote_table.tpl +++ b/tpl/part/vote_table.tpl @@ -5,7 +5,7 @@

      {_('Votes of the poll')}

      -
      + @@ -94,6 +94,11 @@ + {if $admin} + + {/if} {else} From ff61cf6b915da3d82a9d17d8b339f9a0c1ef7cc6 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 21 Dec 2014 00:29:51 +0100 Subject: [PATCH 051/151] admin: Copy fonctionnalities from studs.php --- adminstuds.php | 81 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 79 insertions(+), 2 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index f468032..f3f123d 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -110,9 +110,62 @@ if (isset($_POST['update_poll_info'])) { } } -// TODO Handle Add/Edit vote form +// ------------------------------- +// A vote is going to be edited +// ------------------------------- -// TODO Handle Add comment form +if (!empty($_POST['edit_vote'])) { + // TODO Try what does filter_input with a wrong value + $editingVoteId = filter_input(INPUT_POST, 'edit_vote', FILTER_VALIDATE_INT); +} + +// ------------------------------- +// Something to save (edit or add) +// ------------------------------- + +if (!empty($_POST['save'])) { // Save edition of an old vote + $editedVote = filter_input(INPUT_POST, 'save', FILTER_VALIDATE_INT); + $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[012]$/']]); + + if (empty($editedVote)) { + $message = new Message('danger', _('Something is going wrong...')); + } + if (count($choices) != count($_POST['choices'])) { + $message = new Message('danger', _('There is a problem with your choices.')); + } + + if ($message == null) { + // Update vote + $result = $pollService->updateVote($poll_id, $editedVote, $choices); + if ($result) { + $message = new Message('success', _('Update vote successfully.')); + // TODO Send mail to notify the poll admin + } else { + $message = new Message('danger', _('Update vote failed.')); + } + } +} elseif (isset($_POST['save'])) { // Add a new vote + $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9_ -]+$/i']]); + $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[012]$/']]); + + if (empty($name)) { + $message = new Message('danger', _('Name is incorrect.')); + } + if (count($choices) != count($_POST['choices'])) { + $message = new Message('danger', _('There is a problem with your choices.')); + } + + if ($message == null) { + // Add vote + $result = $pollService->addVote($poll_id, $name, $choices); + if ($result) { + $message = new Message('success', _('Update vote successfully.')); + // TODO Send mail to notify the poll admin + } else { + $message = new Message('danger', _('Update vote failed.')); + } + } +} // ------------------------------- // Delete a votes @@ -140,6 +193,30 @@ if (isset($_POST['confirm_remove_all_votes'])) { $adminPollService->cleanVotes($poll_id); } +// ------------------------------- +// Add a comment +// ------------------------------- + +if (isset($_POST['add_comment'])) { + $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9_ -]+$/i']]); + $comment = filter_input(INPUT_POST, 'comment', FILTER_DEFAULT); + + if (empty($name)) { + $message = new Message('danger', _('Name is incorrect.')); + } + + if ($message == null) { + // Add comment + $result = $pollService->addComment($poll_id, $name, $comment); + if ($result) { + $message = new Message('success', _('Comment added.')); + } else { + $message = new Message('danger', _('Comment failed.')); + } + } + +} + // ------------------------------- // Delete a comment // ------------------------------- From 316675241045119d3a7e044d555a63d499b3ad2c Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 21 Dec 2014 00:45:39 +0100 Subject: [PATCH 052/151] admin: Display buttons to add or remove choice. --- old_adminstuds.php | 529 ---------------------------------------- tpl/part/vote_table.tpl | 17 ++ 2 files changed, 17 insertions(+), 529 deletions(-) diff --git a/old_adminstuds.php b/old_adminstuds.php index 7a734d2..945be49 100644 --- a/old_adminstuds.php +++ b/old_adminstuds.php @@ -255,85 +255,10 @@ if (isset($_POST['ajoutercolonne']) && $dsondage->format == 'D') { // [end] action quand on ajoute une colonne au format DATE -//suppression de ligne dans la base -for ($i = 0; $i < $nblignes; $i++) { - if (isset($_POST["effaceligne$i"])) { - $compteur=0; - $prepared = $connect->prepare('DELETE FROM user_studs WHERE nom = ? AND id_users = ?'); - - foreach ($users as $user) { - if ($compteur==$i){ - $prepared->execute(array($user->nom, $user->id_users)); - } - - $compteur++; - } - } -} - - -// TODO OPZ Revoir toute cette partie suppression d'un commentaire utilisateur -/*$sql = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; -$sql = $connect->Prepare($sql); -$comment_user = $connect->Execute($sql, array($poll_id)); -$i = 0; -while ($dcomment = $comment_user->FetchNextObject(false)) { - if (isset($_POST['suppressioncomment'.$i])) { - $sql = 'DELETE FROM comments WHERE id_comment = '.$connect->Param('id_comment'); - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($dcomment->id_comment)); - } - - $i++; -} -*/ - //on teste pour voir si une ligne doit etre modifiée $testmodifier = false; $testligneamodifier = false; -for ($i = 0; $i < $nblignes; $i++) { - if (isset($_POST["modifierligne$i"])) { - $ligneamodifier=$i; - $testligneamodifier="true"; - } - - //test pour voir si une ligne est a modifier - if (isset($_POST["validermodifier$i"])) { - $modifier=$i; - $testmodifier="true"; - } -} - - -//si le test est valide alors on affiche des checkbox pour entrer de nouvelles valeurs -if ($testmodifier) { - $nouveauchoix = ''; - for ($i = 0; $i < $nbcolonnes; $i++) { - // radio checked 1 = Yes, 2 = Ifneedbe, 0 = No - if (isset($_POST["choix$i"])) { - switch ($_POST["choix$i"]) { - case 1: $nouveauchoix .= "1";break; - case 2: $nouveauchoix .= "2";break; - default: $nouveauchoix .= "0";break; - } - } - } - - $compteur=0; - - while ($data=$user_studs->FetchNextObject(false)) { - //mise a jour des données de l'utilisateur dans la base SQL - if ($compteur==$modifier) { - $sql = 'UPDATE user_studs SET reponses = '.$connect->Param('reponses').' WHERE nom = '.$connect->Param('nom').' AND id_users = '.$connect->Param('id_users'); - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($nouveauchoix, $data->nom, $data->id_users)); - } - - $compteur++; - } -} - //suppression de colonnes dans la base for ($i = 0; $i < $nbcolonnes; $i++) { @@ -389,185 +314,6 @@ for ($i = 0; $i < $nbcolonnes; $i++) { } -// TODO OPZ Déjà fait en début de fichier recuperation des donnes de la base -/*$sql = 'SELECT * FROM sondage WHERE id_sondage_admin = '.$connect->Param('numsondageadmin'); -$sql = $connect->Prepare($sql); -$sondage = $connect->Execute($sql, array($admin_poll_id)); - -if ($sondage !== false) { - $sql = 'SELECT * FROM sujet_studs WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $sujets = $connect->Execute($sql, array($poll_id)); - - $sql = 'SELECT * FROM user_studs WHERE id_sondage = '.$connect->Param('numsondage').' order by id_users'; - $sql = $connect->Prepare($sql); - $user_studs = $connect->Execute($sql, array($poll_id)); -} else { - - Utils::print_header(_("Error!")); - bandeau_titre(_("Error!")); - - echo ' -
      -

      ' . _("This poll doesn't exist !") . '

      -

      ' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

      -
      '."\n"; - - bandeau_pied(); - - die(); -}*/ - -// Errors -$errors = ''; -if ((isset($_POST["boutonp"])) && $_POST["nom"] == "") { - $errors .= '
    • ' . _("Enter a name") . '
    • '; -} -if (isset($erreur_prenom) && $erreur_prenom) { - $errors .= '
    • ' . _("The name you've chosen already exist in this poll!") . '
    • '; -} -if (isset($erreur_injection) && $erreur_injection) { - $errors .= '
    • ' . _("Characters \" ' < et > are not permitted") . '
    • '; -} -if (isset($erreur_ajout_date) && $erreur_ajout_date) { - $errors .= '
    • ' . _("The date is not correct !") . '
    • '; -} - -//Poll title, description and email values -$title = (isset($_POST["boutonnouveautitre"]) && !empty($_POST['nouveautitre'])) ? htmlentities(html_entity_decode($_POST['nouveautitre'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8') : stripslashes( $poll->title); -$description = (isset($_POST["nouveauxcommentaires"])) ? stripslashes(htmlentities(html_entity_decode($_POST['nouveauxcommentaires'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8')) : stripslashes( $poll->comment); -$email_admin = (isset($_POST["boutonnouvelleadresse"]) && !empty($_POST['nouvelleadresse'])) ? htmlentities(html_entity_decode($_POST['nouvelleadresse'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8') : stripslashes( $poll->admin_mail ); - -//Poll format (locked A-/D-, open A/D, editable A+/D+) -$poll_rules = (isset($_POST["poll_rules"]) && !empty($_POST['btn_poll_rules'])) ? $_POST["poll_rules"] : substr($poll->format, 1, 1); // TODO OPZ Handle comment disabling -$poll_rules_opt1 = '';$poll_rules_opt2 = '';$poll_rules_opt3 = ''; -if($poll->editable) { - $poll_rules_text = ' '. _("Votes are editable"); - $poll_rules_opt3 = 'selected'; -} elseif($poll_rules == '-') { - $poll_rules_text = ' '. _("Votes and comments are locked"); - $poll_rules_opt1 = 'selected'; -} else { - $poll_rules_text = ' '. _("Votes and comments are open"); - $poll_rules_opt2 = 'selected'; -} - -if ($errors!='') { - Utils::print_header(_("Error!")); - bandeau_titre(_("Error!")); - - echo '
        '.$errors.'
      '."\n"; - -} else { - Utils::print_header(_('Poll administration').' - '.$title); - bandeau_titre(_('Poll administration').' - '.$title); - - // session_unset(); -} - -echo ' - -
      -
      -
      -

      '.$title.'

      - -
      -
      -
      - - - - -
      -
      -
      -
      -
      -
      -
      -

      '. _("Initiator of the poll") .'

      -

      '.stripslashes($poll->admin_name).'

      -
      -
      -

      '.$email_admin.'

      - -
      -
      -
      -
      -

      '._("Description") .'


      -

      '.$description.'

      - -
      -
      -
      - - -
      -

      '. _("Expiration's date") .'

      -

      '.date("d/m/Y",strtotime($poll->end_date)).'

      -
      -
      -
      -
      -
      -

      '.$poll_rules_text.'

      - -
      -
      -
      -
      - '."\n"; // .jumbotron // Table headers $thead = '
      '; @@ -699,278 +445,3 @@ if ($poll->format == "D") { } // Print headers -echo ' - - -
      -

      ' . _('As poll administrator, you can change all the lines of this poll with this button ').'' . _('Edit') . ', - ' . _(' remove a column or a line with ') . '' . _('Remove') . ' - ' . _('and add a new column with '). ''. _('Add a column') . '

      -

      ' . _('Finally, you can change the informations of this poll like the title, the comments or your email address.') . '

      - -
      - - - -

      '._('Votes of the poll ').'

      -
      -
      {_('Votes of the poll')} {$poll->title}
      - - '. $thead . ' - '; - -// Print poll results -$somme[] = 0; -$compteur = 0; - -foreach($users as $user) { - - $ensemblereponses = $user->reponses; - - // Print name - echo ' -'."\n"; - - // si la ligne n'est pas a changer, on affiche les données - if (!$testligneamodifier) { - for ($k = 0; $k < $nbcolonnes; $k++) { - $rbd = ($border[$k]) ? ' rbd' : ''; - $car = substr($ensemblereponses, $k, 1); - switch ($car) { - case "1": echo ''."\n"; - if (isset($somme[$k]) === false) { - $somme[$k] = 0; - } - $somme[$k]++; break; - case "2": echo ''."\n"; break; - default: echo ''."\n";break; - } - } - } else { // sinon on remplace les choix de l'utilisateur par une ligne de radio pour recuperer de nouvelles valeurs - // si c'est bien la ligne a modifier on met les radios - if ($compteur == "$ligneamodifier") { - for ($j = 0; $j < $nbcolonnes; $j++) { - - $car = substr($ensemblereponses, $j, 1); - - // variable pour afficher la valeur cochée - $car_html[0]='value="0"';$car_html[1]='value="1"';$car_html[2]='value="2"'; - switch ($car) { - case "1": $car_html[1]='value="1" checked';break; - case "2": $car_html[2]='value="2" checked';break; - default: $car_html[0]='value="0" checked';break; - } - - echo ' - '."\n"; - - } - } else { //sinon on affiche les lignes normales - for ($k = 0; $k < $nbcolonnes; $k++) { - $rbd = ($border[$k]) ? ' rbd' : ''; - $car = substr($ensemblereponses, $k, 1); - switch ($car) { - case "1": echo ''."\n"; - if (isset($somme[$k]) === false) { - $somme[$k] = 0; - } - $somme[$k]++; break; - case "2": echo ''."\n"; break; - default: echo ''."\n";break; - } - } - } - } - - //a la fin de chaque ligne se trouve les boutons modifier - if (!$testligneamodifier=="true") { - echo ' - '."\n"; - } - - //demande de confirmation pour modification de ligne - for ($i = 0; $i < $nblignes; $i++) { - if (isset($_POST["modifierligne$i"])) { - if ($compteur == $i) { - echo ''."\n"; - } - } - } - - $compteur++; - echo ''."\n"; -} - -if (!$testligneamodifier=="true") { - //affichage de la case vide de texte pour un nouvel utilisateur - echo ' -'."\n"; - - //une ligne de checkbox pour le choix du nouvel utilisateur - for ($i = 0; $i < $nbcolonnes; $i++) { - echo ' - '."\n"; - } - - // Affichage du bouton de formulaire pour inscrire un nouvel utilisateur dans la base - echo ' -'."\n"; - -} - -// Addition and Best choice -//affichage de la ligne contenant les sommes de chaque colonne -$tr_addition = ''; -$meilleurecolonne = max($somme); -$compteursujet = 0; -$meilleursujet = '
        '; -for ($i = 0; $i < $nbcolonnes; $i++) { - if (isset($somme[$i]) && $somme[$i] > 0 ) { - if (in_array($i, array_keys($somme, max($somme)))){ - - $tr_addition .= '
      '; - - $meilleursujet.= '
    • '.$radio_title[$i].'
    • '; - $compteursujet++; - - } else { - $tr_addition .= ''; - } - } else { - $tr_addition .= ''; - } -} -$tr_addition .= ''; - -$meilleursujet = str_replace("°", "'", $meilleursujet).''; -$vote_str = ($meilleurecolonne > 1) ? $vote_str = _('votes') : _('vote'); - -// Print Addition and Best choice -echo $tr_addition.' - -
      '._('Votes of the poll ').$title.'
      '.stripslashes($user->nom).' ' . _('Yes') . '() ' . _('Yes') . _(', ifneedbe') . '' . _('No') . ' -
        -
      • - - -
      • -
      • - - -
      • -
      • - - -
      • -
      -
      ' . _('Yes') . '() ' . _('Yes') . _(', ifneedbe') . '' . _('No') . ' - - -
      -
      - - -
      -
      -
        -
      • - - -
      • -
      • - - -
      • -
      • - - -
      • -
      -
      '. _("Addition") .''.$somme[$i].''.$somme[$i].'
      -
      -
      '."\n"; - -if ($compteursujet == 1) { - echo ' -

      ' . _("Best choice") . '

      -
      -

      ' . _("The best choice at this time is:") . '

      - ' . $meilleursujet . ' -

      ' . _("with") . ' ' . $meilleurecolonne . ' ' . $vote_str . '.

      -
      '."\n"; -} elseif ($compteursujet > 1) { - echo ' -

      ' . _("Best choices") . '

      -
      -

      ' . _("The bests choices at this time are:") . '

      - ' . $meilleursujet . ' -

      ' . _("with") . ' ' . $meilleurecolonne . ' ' . $vote_str . '.

      -
      '."\n"; -} - -echo ' -
      -
      '."\n"; - -// Commments -$comment_user = $connect->allComments($poll_id); - -if (count($comment_user) != 0) { - echo '

      ' . _("Comments of polled people") . '

      '."\n"; - - $i = 0; - while ( $dcomment=$comment_user->FetchNextObject(false)) { - echo ' -
      - - '.stripslashes($dcomment->usercomment). ' : - ' . stripslashes(nl2br($dcomment->comment)) . ' -
      '; - $i++; - } - echo '
      '; -} -echo ' -
      -
      -
      ' . _("Add a comment in the poll") . ' -
      -

      -
      -
      -


      -

      -
      -

      -
      -
      -
      -
      -'; - -bandeau_pied(); diff --git a/tpl/part/vote_table.tpl b/tpl/part/vote_table.tpl index 37829f8..daf8d40 100644 --- a/tpl/part/vote_table.tpl +++ b/tpl/part/vote_table.tpl @@ -9,6 +9,23 @@ + {if $admin} + + + {$headersDCount=0} + {foreach $slots as $slot} + {foreach $slot->moments as $id=>$moment} + + {$headersDCount = $headersDCount+1} + {/foreach} + {/foreach} + + + {/if} {foreach $slots as $id=>$slot} From dec9e24530d464bac03022bc647cc31d550b0b9c Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 21 Dec 2014 23:48:22 +0100 Subject: [PATCH 053/151] admin: Implement the removal of a slot. --- adminstuds.php | 20 +++++++- app/classes/Framadate/FramaDB.php | 47 +++++++++++++++--- .../Framadate/Services/AdminPollService.php | 49 ++++++++++++++++++- studs.php | 1 - 4 files changed, 106 insertions(+), 11 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index f3f123d..66af6db 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -36,7 +36,7 @@ $editingVoteId = 0; /*----------*/ $pollService = new PollService($connect); -$adminPollService = new AdminPollService($connect); +$adminPollService = new AdminPollService($connect, $pollService); $inputService = new InputService(); /* PAGE */ @@ -115,7 +115,6 @@ if (isset($_POST['update_poll_info'])) { // ------------------------------- if (!empty($_POST['edit_vote'])) { - // TODO Try what does filter_input with a wrong value $editingVoteId = filter_input(INPUT_POST, 'edit_vote', FILTER_VALIDATE_INT); } @@ -170,6 +169,7 @@ if (!empty($_POST['save'])) { // Save edition of an old vote // ------------------------------- // Delete a votes // ------------------------------- + if (!empty($_POST['delete_vote'])) { $vote_id = filter_input(INPUT_POST, 'delete_vote', FILTER_VALIDATE_INT); if ($adminPollService->deleteVote($poll_id, $vote_id)) { @@ -182,6 +182,7 @@ if (!empty($_POST['delete_vote'])) { // ------------------------------- // Remove all votes // ------------------------------- + if (isset($_POST['remove_all_votes'])) { $smarty->assign('poll_id', $poll_id); $smarty->assign('admin_poll_id', $admin_poll_id); @@ -234,6 +235,7 @@ if (!empty($_POST['delete_comment'])) { // ------------------------------- // Remove all comments // ------------------------------- + if (isset($_POST['remove_all_comments'])) { $smarty->assign('poll_id', $poll_id); $smarty->assign('admin_poll_id', $admin_poll_id); @@ -264,6 +266,20 @@ if (isset($_POST['confirm_delete_poll'])) { // TODO } +// ------------------------------- +// Delete a slot +// ------------------------------- + +if (!empty($_POST['delete_column'])) { + $column = filter_input(INPUT_POST, 'delete_column', FILTER_DEFAULT); + + if ($adminPollService->deleteSlot($poll_id, $column)) { + $message = new Message('success', _('Column deleted.')); + } else { + $message = new Message('danger', _('Failed to delete the column.')); + } +} + // Retrieve data $slots = $pollService->allSlotsByPollId($poll_id); $votes = $pollService->allUserVotesByPollId($poll_id); diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 102ccfb..0bbb036 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -18,23 +18,20 @@ */ namespace Framadate; -class FramaDB -{ +class FramaDB { /** * PDO Object, connection to database. */ private $pdo = null; - function __construct($connection_string, $user, $password) - { + function __construct($connection_string, $user, $password) { $this->pdo = new \PDO($connection_string, $user, $password); $this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ); $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); } - function areTablesCreated() - { - $result= $this->pdo->query('SHOW TABLES'); + function areTablesCreated() { + $result = $this->pdo->query('SHOW TABLES'); $schemas = $result->fetchAll(\PDO::FETCH_COLUMN); return !empty(array_diff($schemas, ['comments', 'sondage', 'sujet_studs', 'user_studs'])); } @@ -118,6 +115,42 @@ class FramaDB return $prepared->execute([$poll_id]); } + /** + * Delete all votes made on given moment index. + * + * @param $poll_id int The ID of the poll + * @param $index int The index of the vote into the poll + * @return bool|null true if action succeeded. + */ + function deleteVotesByIndex($poll_id, $index) { + $prepared = $this->prepare('UPDATE user_studs SET reponses = CONCAT(SUBSTR(reponses, 1, ?), SUBSTR(reponses, ?)) WHERE id_sondage = ?'); + return $prepared->execute([$index, $index + 2, $poll_id]); + } + + /** + * Update a slot into a poll. + * + * @param $poll_id int The ID of the poll + * @param $datetime int The datetime of the slot to update + * @param $newValue mixed The new value of the entire slot + * @return bool|null true if action succeeded. + */ + function updateSlot($poll_id, $datetime, $newValue) { + $prepared = $this->prepare('UPDATE sujet_studs SET sujet = ? WHERE id_sondage = ? AND SUBSTRING_INDEX(sujet, \'@\', 1) = ?'); + return $prepared->execute([$newValue, $poll_id, $datetime]); + } + + /** + * Delete a entire slot from a poll. + * + * @param $poll_id int The ID of the poll + * @param $datetime mixed The datetime of the slot + */ + function deleteSlot($poll_id, $datetime) { + $prepared = $this->prepare('DELETE FROM sujet_studs WHERE id_sondage = ? AND SUBSTRING_INDEX(sujet, \'@\', 1) = ?'); + $prepared->execute([$poll_id, $datetime]); + } + /** * Delete all comments of a given poll. * diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php index eee80a9..450ed78 100644 --- a/app/classes/Framadate/Services/AdminPollService.php +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -8,9 +8,11 @@ namespace Framadate\Services; class AdminPollService { private $connect; + private $pollService; - function __construct($connect) { + function __construct($connect, $pollService) { $this->connect = $connect; + $this->pollService = $pollService; } function updatePoll($poll) { @@ -59,5 +61,50 @@ class AdminPollService { return $this->connect->deleteVotesByAdminPollId($poll_id); } + /** + * Delete a slot from a poll. + * + * @param $poll_id int The ID of the poll + * @param $slot string The name of the slot + */ + public function deleteSlot($poll_id, $slot) { + $ex = explode('@', $slot); + $datetime = $ex[0]; + $moment = $ex[1]; + + $slots = $this->pollService->allSlotsByPollId($poll_id); + + $index = 0; + $indexToDelete = -1; + $newMoments = []; + + // Search the index of the slot to delete + foreach ($slots as $aSlot) { + $ex = explode('@', $aSlot->sujet); + $moments = explode(',', $ex[1]); + + foreach ($moments as $rowMoment) { + if ($datetime == $ex[0]) { + if ($moment == $rowMoment) { + $indexToDelete = $index; + } else { + $newMoments[] = $rowMoment; + } + } + $index++; + } + } + + // Remove votes + $this->connect->beginTransaction(); + $this->connect->deleteVotesByIndex($poll_id, $indexToDelete); + if (count($newMoments) > 0) { + $this->connect->updateSlot($poll_id, $datetime, $datetime . '@' . implode(',', $newMoments)); + } else { + $this->connect->deleteSlot($poll_id, $datetime); + } + $this->connect->commit(); + } + } \ No newline at end of file diff --git a/studs.php b/studs.php index bf6db02..08a0206 100644 --- a/studs.php +++ b/studs.php @@ -55,7 +55,6 @@ if (!$poll) { // ------------------------------- if (!empty($_POST['edit_vote'])) { - // TODO Try what does filter_input with a wrong value $editingVoteId = filter_input(INPUT_POST, 'edit_vote', FILTER_VALIDATE_INT); } From 21ce86e2b73603503d8cfbe14c67f9d1e8b2839e Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Mon, 22 Dec 2014 09:53:18 +0100 Subject: [PATCH 054/151] WIP --- INSTALL | 186 ----------------------------------------------- adminstuds.php | 12 +++ tpl/add_slot.tpl | 31 ++++++++ 3 files changed, 43 insertions(+), 186 deletions(-) delete mode 100644 INSTALL create mode 100644 tpl/add_slot.tpl diff --git a/INSTALL b/INSTALL deleted file mode 100644 index e8d32d6..0000000 --- a/INSTALL +++ /dev/null @@ -1,186 +0,0 @@ -========================================================================== - -Université de Strasbourg - Direction Informatique -Auteur : Guilhem BORGHESI -Création : Février 2008 - -borghesi@unistra.fr - -Ce logiciel est régi par la licence CeCILL-B soumise au droit français et -respectant les principes de diffusion des logiciels libres. Vous pouvez -utiliser, modifier et/ou redistribuer ce programme sous les conditions -de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA -sur le site "http://www.cecill.info". - -Le fait que vous puissiez accéder à cet en-tête signifie que vous avez -pris connaissance de la licence CeCILL-B, et que vous en avez accepté les -termes. Vous pouvez trouver une copie de la licence dans le fichier LICENCE. - -========================================================================== - -Université de Strasbourg - Direction Informatique -Author : Guilhem BORGHESI -Creation : Feb 2008 - -borghesi@unistra.fr - -This software is governed by the CeCILL-B license under French law and -abiding by the rules of distribution of free software. You can use, -modify and/ or redistribute the software under the terms of the CeCILL-B -license as circulated by CEA, CNRS and INRIA at the following URL -"http://www.cecill.info". - -The fact that you are presently reading this means that you have had -knowledge of the CeCILL-B license and that you accept its terms. You can -find a copy of this license in the file LICENSE. - -========================================================================== - - -Paramètres -========== - -Le fichier app/inc/constants.php.template contient le paramétrage par défaut de -l'application Framadate. Pour personnaliser votre installation, copiez -ce fichier sous le nom app/inc/constants.php et modifiez ce dernier. - -Configuration du fichier php.ini -================================ - -Pour que les quotes simples soient acceptées dans la partie "Création de sondage", il faut que la variable magic_quotes_gpc soit activée ("On") dans le fichier php.ini. - - -Base de données -=============== - -STUdS fonctionne indépendemment de la base SQL utilisée, sous réserve que -le serveur dispose de l'extension ADOdb (http://sourceforge.net/projects/adodb) - -Cependant la base de donnée doit être créée au préalable. -Deux scripts le faisant sont fournis : -install.sql: pour postgresql -install.mysql.sql: pour mysql - -Pour postgresql : -Après avoir renseigné les paramètres de la base de données, créez la -base et pré-chargez les données par défaut. Ceci ressemble à : - -% su - pgsql -% createdb studs -% psql -d studs -f install.sql - -Attention : Si vous créez la base de données avec l'utilisateur "pgsql", il vous faudra faire un "grant all on to studs" pour donner les droits à l'utilisateur studs de lire et modifier la base. Les tables de l'applications sont décrites plus loin dans ce fichier dans la partie "Tables de la base de données". - - -Accès à la page administrateur -============================== - -Le répertoire admin/ contient un fichier .htaccess pour Apache, qui restreint l'accès -à la page d'administration de l'application. -Modifiez le contenu de ce fichier .htaccess pour l'adapter au chemin du fichier .htpasswd -sur votre serveur. -Le fichier .htpasswd à besoin d'être créé par vos soins en utilisant par exemple la commande -suivante : -htpasswd -mnb - -Un fichier admin/logs_studs.txt doit être créé et accessible en écriture -par votre serveur Web. Quelque chose comme : - -% touch admin/logs_studs.txt -% chmod 700 admin/logs_studs.txt -% chown www-data admin/logs_studs.txt - -devrait convenir. - -Maintenance -=========== -Studs dispose d'une possibilité de mise en maintenance par le biais -d'un fichier .htaccess. -La section relative à Studs, dans la configuration d'Apache -doit au moins contenir : -AllowOverride AuthConfig Options -Le fichier .htaccess correspondant doit être modifier pour y configurer -l'adresse IP depuis laquelle s'effectue la maintenance. -N'oubliez pas de le recommenter en intégralité une fois la maintenance effectuée. - -Tables de la base de données -============================ - -Voici la structure des tables de l'application. La base se compose de trois tables : - -- sondage : Le contenu de chacun des sondages, -- sujet_studs : les sujets ou dates de tous les sondages, -- user_studs : les identifiants des sondés de tous les sondages. - -Chacune des tables contient les champs suivants : - -SONDAGE - - Nom du champ format description - - id_sondage (clé primaire) alpha-numérique numéro du sondage aléatoire - commentaires text commentaires liés au sondage - mail_admin text adresse de l'auteur du sondage - nom_admin text nom de l'auteur du sondage - titre text titre du sondage - id_sondage_admin alpha-numérique numéro du sondage pour le lien d'administration - date_fin alpha-numérique date de fin su sondage au format SQL - format text format du sondage : D/D+ pour Date, A/A+ pour Autre - mailsonde text envoi de mail a l'auteur du sondage a chaque participation ("yes" ou vide) - -SUJET_STUDS - - Nom du champ format description - - id_sondage (clé primaire) alpha-numérique numéro du sondage aléatoire - sujet text tous les sujets du sondage - -USER_STUDS - - Nom du champ format description - - user text nom du participant - id_sondage (clé primaire) alpha-numérique numéro du sondage aléatoire - reponses text reponses a chacun des sujets proposés au vote (0 pour non, 1 pour OK) - id_users alpha-numérique numéro d'utilisateur par ordre croissant de participation pour garder l'ordre de participation - -COMMENTS - Nom du champ format description - - id_sondage (clé primaire) alpha-numérique numéro du sondage aléatoire - comment text commentaires d'un participant - usercomment text nom de l'utilisateur qui laisse le commentaire - id_comment alpha-numérique numéro de commentaire par ordre croissant de participation pour garder l'ordre de remplissage - - -Traductions -=========== - -Pour pouvoir bénéficier de toutes les traductions en FR, EN, DE et ES -il faut avoir installé les locales fr_FR, de_DE, en_US et es_ES sur le -serveur qui héberge l'application ainsi que disposer de l'extension PHP Gettext. - -Export -====== - -Pour pouvoir bénéficier de l'export au format PDF, l'extension PHP PEAR -FPDF (php-fpdf) doit être installée. - -Synthèses des librairies utilisées -================================== - -ADOdb -http://sourceforge.net/projects/adodb -paquet: php5-adodb - -fpdf -http://www.fpdf.org -paquet: php-fpdf - -gettext -https://launchpad.net/php-gettext -paquet: php-gettext - -Sous GNU/Linux, -disposer des locales utf-8 suivantes pour la glibc: -FR, EN, ES, DE (/etc/locales.gen) diff --git a/adminstuds.php b/adminstuds.php index 66af6db..66100cd 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -280,6 +280,18 @@ if (!empty($_POST['delete_column'])) { } } +// ------------------------------- +// Delete a slot +// ------------------------------- + +if (isset($_POST['add_slot'])) { + $smarty->assign('poll_id', $poll_id); + $smarty->assign('admin_poll_id', $admin_poll_id); + $smarty->assign('title', _('Poll') . ' - ' . $poll->title); + $smarty->display('add_slot.tpl'); + exit; +} + // Retrieve data $slots = $pollService->allSlotsByPollId($poll_id); $votes = $pollService->allUserVotesByPollId($poll_id); diff --git a/tpl/add_slot.tpl b/tpl/add_slot.tpl new file mode 100644 index 0000000..b8f15fc --- /dev/null +++ b/tpl/add_slot.tpl @@ -0,0 +1,31 @@ +{extends file='page.tpl'} + +{block name=main} +
      +
      +

      {_("Column's adding")}

      + +
      + +
      +
      + + +
      + {_("(dd/mm/yyyy)")} +
      +
      +
      + +
      + +
      +
      +
      + + +
      +
      +
      + +{/block} \ No newline at end of file From 94e87a318281484ad70ca9bdf3ab61877b4d5a8a Mon Sep 17 00:00:00 2001 From: "Olivier Perez [a570709]" Date: Mon, 22 Dec 2014 14:18:33 +0100 Subject: [PATCH 055/151] WIP> admin: Add availability to add a slot to a poll --- adminstuds.php | 10 ++++++ app/classes/Framadate/FramaDB.php | 31 ++++++++++++++++++- .../Framadate/Services/AdminPollService.php | 25 +++++++++++++++ tpl/add_slot.tpl | 7 ++--- 4 files changed, 68 insertions(+), 5 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index 66100cd..948499e 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -291,6 +291,16 @@ if (isset($_POST['add_slot'])) { $smarty->display('add_slot.tpl'); exit; } +if (isset($_POST['confirm_add_slot'])) { + $newdate = filter_input(INPUT_POST, 'newdate', FILTER_DEFAULT); + $newmoment = filter_input(INPUT_POST, 'newmoment', FILTER_DEFAULT); + + if ($adminPollService->addSlot($poll_id, $newdate, $newmoment)) { + $message = new Message('success', _('Column added.')); + } else { + $message = new Message('danger', _('Failed to add the column.')); + } +} // Retrieve data $slots = $pollService->allSlotsByPollId($poll_id); diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 0bbb036..2e03d57 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -33,7 +33,7 @@ class FramaDB { function areTablesCreated() { $result = $this->pdo->query('SHOW TABLES'); $schemas = $result->fetchAll(\PDO::FETCH_COLUMN); - return !empty(array_diff($schemas, ['comments', 'sondage', 'sujet_studs', 'user_studs'])); + return 0 != count(array_diff($schemas, ['comments', 'sondage', 'sujet_studs', 'user_studs'])); } function prepare($sql) { @@ -127,6 +127,35 @@ class FramaDB { return $prepared->execute([$index, $index + 2, $poll_id]); } + /** + * Find the slot into poll for a given datetime. + * + * @param $poll_id int The ID of the poll + * @param $datetime int The datetime of the slot + * @return mixed Object The slot found, or null + */ + function findSlotByPollIdAndDatetime($poll_id, $datetime) { + $prepared = $this->prepare('SELECT * FROM sujet_studs WHERE id_sondage = ? AND SUBSTRING_INDEX(sujet, \'@\', 1) = ?'); + + $prepared->execute([$poll_id, $datetime]); + $slot = $prepared->fetch(); + $prepared->closeCursor(); + + return $slot; + } + + /** + * Insert a new slot into a given poll. + * + * @param $poll_id int The ID of the poll + * @param $slot mixed The value of the slot + * @return bool true if action succeeded + */ + function insertSlot($poll_id, $slot) { + $prepared = $this->prepare('INSERT INTO sujet_studs (id_sondage, sujet) VALUES (?,?)'); + return $prepared->execute([$poll_id, $slot]); + } + /** * Update a slot into a poll. * diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php index 450ed78..b6bca39 100644 --- a/app/classes/Framadate/Services/AdminPollService.php +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -106,5 +106,30 @@ class AdminPollService { $this->connect->commit(); } + public function addSlot($poll_id, $newdate, $newmoment) { + $ex = explode('/', $newdate); + $datetime = mktime(0,0,0, $ex[1], $ex[0], $ex[2]); + + $slot = $this->connect->findSlotByPollIdAndDatetime($poll_id, $datetime); + + if ($slot != null) { + // Update found slot + $moments = explode('@', $slot->sujet)[1]; + foreach ($moments as $moment) { + if ($moment == $newmoment) { + return false; + } + } + // TODO Implements + + } else { + // TODO Found index of insertion, in order to update user votes + $this->connect->insertSlot($poll_id, $datetime . '@' . $newmoment); + } + + return true; + + } + } \ No newline at end of file diff --git a/tpl/add_slot.tpl b/tpl/add_slot.tpl index b8f15fc..9837817 100644 --- a/tpl/add_slot.tpl +++ b/tpl/add_slot.tpl @@ -16,16 +16,15 @@
      - +
      - +
      -
      +
      -
      {/block} \ No newline at end of file From 288ddd2efc765d91389951fe0286caaa0d29f1a0 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 23 Dec 2014 00:30:05 +0100 Subject: [PATCH 056/151] admin: Add availability to add a slot to a poll --- app/classes/Framadate/FramaDB.php | 19 ++- .../Framadate/Services/AdminPollService.php | 112 +++++++++++++++--- app/classes/Framadate/Utils.php | 2 +- 3 files changed, 117 insertions(+), 16 deletions(-) diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 2e03d57..aab3fc1 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -48,6 +48,18 @@ class FramaDB { $this->pdo->commit(); } + function rollback() { + $this->pdo->rollback(); + } + + function errorCode() { + return $this->pdo->errorCode(); + } + + function errorInfo() { + return $this->pdo->errorInfo(); + } + function query($sql) { return $this->pdo->query($sql); } @@ -63,7 +75,7 @@ class FramaDB { } function updatePoll($poll) { - $prepared = $this->prepare('UPDATE sondage SET title=?, admin_mail=?, comment=?, active=?, editable=? WHERE sondage.poll_id = ?'); + $prepared = $this->prepare('UPDATE sondage SET title=?, admin_mail=?, comment=?, active=?, editable=? WHERE poll_id = ?'); return $prepared->execute([$poll->title, $poll->admin_mail, $poll->comment, $poll->active, $poll->editable, $poll->poll_id]); } @@ -86,6 +98,11 @@ class FramaDB { return $prepared->fetchAll(); } + function insertDefaultVote($poll_id, $insert_position) { + $prepared = $this->prepare('UPDATE user_studs SET reponses = CONCAT(SUBSTRING(reponses, 1, ?), "0", SUBSTRING(reponses, ?)) WHERE id_sondage = ?'); + return $prepared->execute([$insert_position, $insert_position + 1, $poll_id]); + } + function insertVote($poll_id, $name, $choices) { $prepared = $this->prepare('INSERT INTO user_studs (id_sondage,nom,reponses) VALUES (?,?,?)'); $prepared->execute([$poll_id, $name, $choices]); diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php index b6bca39..ce4deb6 100644 --- a/app/classes/Framadate/Services/AdminPollService.php +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -1,8 +1,11 @@ connect->commit(); } - public function addSlot($poll_id, $newdate, $newmoment) { - $ex = explode('/', $newdate); - $datetime = mktime(0,0,0, $ex[1], $ex[0], $ex[2]); + /** + * Add a new slot to the poll. And insert default values for user's votes. + *
        + *
      • Create a new slot if no one exists for the given date
      • + *
      • Create a new moment if a slot already exists for the given date
      • + *
      + * + * @param $poll_id int The ID of the poll + * @param $new_date string The date (format: d/m/Y) + * @param $new_moment string The moment's name + * @return bool true if added + */ + public function addSlot($poll_id, $new_date, $new_moment) { + $ex = explode('/', $new_date); + $datetime = mktime(0, 0, 0, $ex[1], $ex[0], $ex[2]); - $slot = $this->connect->findSlotByPollIdAndDatetime($poll_id, $datetime); + $slots = $this->connect->allSlotsByPollId($poll_id); + $result = $this->findInsertPosition($slots, $datetime, $new_moment); - if ($slot != null) { - // Update found slot - $moments = explode('@', $slot->sujet)[1]; - foreach ($moments as $moment) { - if ($moment == $newmoment) { - return false; - } + // Begin transaction + $this->connect->beginTransaction(); + + if ($result == null) { + // The moment already exists + return false; + } elseif ($result->slot != null) { + $slot = $result->slot; + + $joined_moments = explode('@', $slot->sujet)[1]; + $moments = explode(',', $joined_moments); + + // Check if moment already exists (maybe not necessary) + if (in_array($new_moment, $moments)) { + return false; } - // TODO Implements + + // Update found slot + $moments[] = $new_moment; + sort($moments); + $this->connect->updateSlot($poll_id, $datetime, $datetime . '@' . implode(',', $moments)); } else { - // TODO Found index of insertion, in order to update user votes - $this->connect->insertSlot($poll_id, $datetime . '@' . $newmoment); + $this->connect->insertSlot($poll_id, $datetime . '@' . $new_moment); } + $this->connect->insertDefaultVote($poll_id, $result->insert); + + // Commit transaction + $this->connect->commit(); + return true; } + /** + * This method find where to insert a datatime+moment into a list of slots.
      + * Return the {insert:X}, where X is the index of the moment into the whole poll (ex: X=0 => Insert to the first column). + * Return {slot:Y}, where Y is not null if there is a slot existing for the given datetime. + * + * @param $slots array All the slots of the poll + * @param $datetime int The datetime of the new slot + * @param $moment string The moment's name + * @return null|\stdClass An object like this one: {insert:X, slot:Y} where Y can be null. + */ + private function findInsertPosition($slots, $datetime, $moment) { + $result = new \stdClass(); + $result->slot = null; + $result->insert = -1; + + $i = 0; + + foreach ($slots as $slot) { + $ex = explode('@', $slot->sujet); + $rowDatetime = $ex[0]; + $moments = explode(',', $ex[1]); + + if ($datetime == $rowDatetime) { + $result->slot = $slot; + + foreach ($moments as $rowMoment) { + $strcmp = strcmp($moment, $rowMoment); + if ($strcmp < 0) { + // Here we have to insert at First place or middle of the slot + break(2); + } elseif ($strcmp == 0) { + // Here we dont have to insert at all + return null; + } + $i++; + } + + // Here we have to insert at the end of a slot + $result->insert = $i; + break; + } elseif ($datetime < $rowDatetime) { + // Here we have to insert a new slot + break; + } else { + $i += count($moments); + } + } + $result->insert = $i; + + return $result; + } + } \ No newline at end of file diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index cb8a078..0226eb7 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -214,7 +214,7 @@ class Utils /** * This method pretty prints an object to the page framed by pre tags. - * @param Object $object The object to print. + * @param mixed $object The object to print. */ public static function debug($object) { From d942f82b0ab0d2f02dc4d5f510d0485585b630dc Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 23 Dec 2014 00:31:13 +0100 Subject: [PATCH 057/151] admin: No need to send a mail to the admin when modifying on the admin page --- adminstuds.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index 948499e..f8b0d43 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -138,7 +138,6 @@ if (!empty($_POST['save'])) { // Save edition of an old vote $result = $pollService->updateVote($poll_id, $editedVote, $choices); if ($result) { $message = new Message('success', _('Update vote successfully.')); - // TODO Send mail to notify the poll admin } else { $message = new Message('danger', _('Update vote failed.')); } @@ -159,7 +158,6 @@ if (!empty($_POST['save'])) { // Save edition of an old vote $result = $pollService->addVote($poll_id, $name, $choices); if ($result) { $message = new Message('success', _('Update vote successfully.')); - // TODO Send mail to notify the poll admin } else { $message = new Message('danger', _('Update vote failed.')); } From 8109b11b70dae2d3ee773065a95213bb0bee4081 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 23 Dec 2014 00:58:00 +0100 Subject: [PATCH 058/151] Move mail sending to class \Framadate\Service\MailService --- .../Framadate/Services/MailService.php | 49 +++++++++++++++++++ app/classes/Framadate/Utils.php | 15 +++--- studs.php | 31 +++++++++++- 3 files changed, 87 insertions(+), 8 deletions(-) create mode 100644 app/classes/Framadate/Services/MailService.php diff --git a/app/classes/Framadate/Services/MailService.php b/app/classes/Framadate/Services/MailService.php new file mode 100644 index 0000000..233d767 --- /dev/null +++ b/app/classes/Framadate/Services/MailService.php @@ -0,0 +1,49 @@ +smtp_allowed = $smtp_allowed; + } + + public function isValidEmail($email) { + return filter_var($email, FILTER_VALIDATE_EMAIL); + } + + function send($to, $subject, $body, $param = '') { + if($this->smtp_allowed == true) { + mb_internal_encoding('UTF-8'); + + $subject = mb_encode_mimeheader(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'), 'UTF-8', 'B', "\n", 9); + + $encoded_app = mb_encode_mimeheader(NOMAPPLICATION, 'UTF-8', 'B', "\n", 6); + $size_encoded_app = (6 + strlen($encoded_app)) % 75; + $size_admin_email = strlen(ADRESSEMAILADMIN); + + if (($size_encoded_app + $size_admin_email + 9) > 74) { + $folding = "\n"; + } else { + $folding = ''; + }; + + $from = sprintf("From: %s%s <%s>\n", $encoded_app, $folding, ADRESSEMAILADMIN); + + $headers = $from; + $headers .= 'Reply-To: ' . ADRESSEMAILREPONSEAUTO . "\n"; + $headers .= "MIME-Version: 1.0\n"; + $headers .= "Content-Type: text/plain; charset=UTF-8\n"; + $headers .= "Content-Transfer-Encoding: 8bit\n"; + $headers .= "Auto-Submitted:auto-generated\n"; + $headers .= 'Return-Path: <>'; + + $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8') . _('\n--\n\n« La route est longue, mais la voie est libre… »\nFramasoft ne vit que par vos dons (déductibles des impôts).\nMerci d\'avance pour votre soutien http://soutenir.framasoft.org.'); + + mail($to, $subject, $body, $headers, $param); + } + } + +} + \ No newline at end of file diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index 0226eb7..a07719d 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -45,6 +45,10 @@ class Utils return (USE_REMOTE_USER && isset($_SERVER['REMOTE_USER'])) || isset($_SESSION['nom']); } + /** + * @param string $title + * @deprecated + */ public static function print_header($title = '') { global $lang; @@ -87,6 +91,7 @@ class Utils * * @param string $email Email address to check * @return bool True if valid. False if not valid. + * @deprecated */ public static function isValidEmail($email) { @@ -96,7 +101,7 @@ class Utils /** * Envoi un courrier avec un codage correct de To et Subject * Les en-têtes complémentaires ne sont pas gérés - * + * @deprecated */ public static function sendEmail( $to, $subject, $body, $headers='', $param='') { @@ -175,8 +180,7 @@ class Utils * Completly delete data about the given poll * TODO Move this function to FramaDB */ - public static function removeSondage($poll_id) - { + public static function removeSondage($poll_id) { global $connect; $prepared = $connect->prepare('DELETE FROM sujet_studs WHERE id_sondage = ?'); @@ -195,7 +199,7 @@ class Utils /** * Clean old poll (end_date < now). - * TODO Move this function to FramaDB + * TODO Move this function to PurgePollService */ public static function cleaningOldPolls($log_txt) { global $connect; @@ -216,8 +220,7 @@ class Utils * This method pretty prints an object to the page framed by pre tags. * @param mixed $object The object to print. */ - public static function debug($object) - { + public static function debug($object) { echo '
      ';
               print_r($object);
               echo '
      '; diff --git a/studs.php b/studs.php index 08a0206..437e462 100644 --- a/studs.php +++ b/studs.php @@ -18,6 +18,7 @@ */ use Framadate\Services\PollService; use Framadate\Services\InputService; +use Framadate\Services\MailService; use Framadate\Message; use Framadate\Utils; @@ -25,6 +26,7 @@ include_once __DIR__ . '/app/inc/init.php'; /* Variables */ /* --------- */ + $poll_id = null; $poll = null; $message = null; @@ -35,6 +37,31 @@ $editingVoteId = 0; $pollService = new PollService($connect); $inputService = new InputService(); +$mailService = new MailService($config['use_smtp']); + +/* Functions */ +/*-----------*/ + +/** + * Send a notification to the poll admin to notify him about an update. + * + * @param $poll Object The poll + * @param $mailService MailService The mail service + */ +function sendUpdateNotification($poll, $mailService) { + if ($poll->receiveNewVotes && !isset($_SESSION['mail_sent'][$poll->poll_id])) { + + $subject = '[' . NOMAPPLICATION . '] ' . _('Poll\'s participation') . ' : ' . html_entity_decode($poll->title, ENT_QUOTES, 'UTF-8'); + $message = html_entity_decode('"$nom" ', ENT_QUOTES, 'UTF-8') . + _('has filled a line.\nYou can find your poll at the link') . " :\n\n" . + Utils::getUrlSondage($poll->admin_poll_id, true) . " \n\n" . + _('Thanks for your confidence.') . "\n" . NOMAPPLICATION; + + $mailService->send($poll->admin_mail, $subject, $message); + + $_SESSION["mail_sent"][$poll->poll_id] = true; + } +} /* PAGE */ /* ---- */ @@ -79,7 +106,7 @@ if (!empty($_POST['save'])) { // Save edition of an old vote $result = $pollService->updateVote($poll_id, $editedVote, $choices); if ($result) { $message = new Message('success', _('Update vote successfully.')); - // TODO Send mail to notify the poll admin + sendUpdateNotification($poll, $mailService); } else { $message = new Message('danger', _('Update vote failed.')); } @@ -100,7 +127,7 @@ if (!empty($_POST['save'])) { // Save edition of an old vote $result = $pollService->addVote($poll_id, $name, $choices); if ($result) { $message = new Message('success', _('Update vote successfully.')); - // TODO Send mail to notify the poll admin + sendUpdateNotification($poll, $mailService); } else { $message = new Message('danger', _('Update vote failed.')); } From d4d483edfd02d942b87b85e6a6d102bb5d3616f1 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 23 Dec 2014 00:59:56 +0100 Subject: [PATCH 059/151] Messages displayed on the top of pages are now dismissable. --- tpl/studs.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tpl/studs.tpl b/tpl/studs.tpl index de89e8a..5eeb84c 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -3,7 +3,7 @@ {block name=main} {if !empty($message)} - + {/if} {* Global informations about the current poll *} From f50b244568872f14814c876edac8a8ae5785519f Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 23 Dec 2014 01:01:09 +0100 Subject: [PATCH 060/151] Return true when deleting a slot. --- app/classes/Framadate/Services/AdminPollService.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php index ce4deb6..9d9c106 100644 --- a/app/classes/Framadate/Services/AdminPollService.php +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -107,6 +107,8 @@ class AdminPollService { $this->connect->deleteSlot($poll_id, $datetime); } $this->connect->commit(); + + return true; } /** From 70ad15aa9739cbb896912d90ba8dd8f69dc284f9 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 23 Dec 2014 09:29:30 +0100 Subject: [PATCH 061/151] Add 'id' column to sujet_studs table. --- install.mysql.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/install.mysql.sql b/install.mysql.sql index 3d47c64..69b36b2 100644 --- a/install.mysql.sql +++ b/install.mysql.sql @@ -46,6 +46,7 @@ CREATE TABLE IF NOT EXISTS `sondage` ( -- CREATE TABLE IF NOT EXISTS `sujet_studs` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `id_sondage` char(16) NOT NULL, `sujet` text, KEY `id_sondage` (`id_sondage`) From 4818d7977a25e10c82a4f27f67bab8f5b775a5c4 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 23 Dec 2014 09:33:00 +0100 Subject: [PATCH 062/151] Update constants.php.template --- app/inc/constants.php.template | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/app/inc/constants.php.template b/app/inc/constants.php.template index c9e31de..6afeb02 100644 --- a/app/inc/constants.php.template +++ b/app/inc/constants.php.template @@ -32,20 +32,14 @@ const ADRESSEMAILADMIN = ''; // Email for automatic responses (you should set it to "no-reply") const ADRESSEMAILREPONSEAUTO = ''; -// Database name -const BASE = ''; - // Database user -const USERBASE = ''; +const DB_USER= ''; // Database password -const USERPASSWD = ''; +const DB_PASSWORD = ''; // Database server name, leave empty to use a socket -const SERVEURBASE = ''; - -// Database type (pdo, mysql, postgres…) http://phplens.com/lens/adodb/docs-adodb.htm#drivers -const BASE_TYPE = ''; +const DB_CONNECTION_STRING = 'mysql:host=;dbname=;port='; // Default Language using POSIX variant of BC P47 standard (choose in $ALLOWED_LANGUAGES) const LANGUE = 'fr_FR'; @@ -93,8 +87,8 @@ $config = [ 'show_the_software' => true, // display technical information about the software 'show_cultivate_your_garden' => true, // display "developpement and administration" information /* choix_autre.php / choix_date.php */ - 'default_poll_duration' => 180, // default values for the new poll duration (number of days). + 'default_poll_duration' => 180, // default values for the new poll duration (number of days). /* choix_autre.php */ - 'user_can_add_img_or_link' => true, // user can add link or URL when creating his poll. + 'user_can_add_img_or_link' => true, // user can add link or URL when creating his poll. ]; From b5fc415edccfa2797344d6737bba95709a467dc2 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 23 Dec 2014 09:48:58 +0100 Subject: [PATCH 063/151] admin: Add availability to delete a poll --- adminstuds.php | 22 +- app/classes/Framadate/FramaDB.php | 14 +- .../Framadate/Services/AdminPollService.php | 20 +- old_adminstuds.php | 318 +----------------- tpl/poll_deleted.tpl | 8 + 5 files changed, 59 insertions(+), 323 deletions(-) create mode 100644 tpl/poll_deleted.tpl diff --git a/adminstuds.php b/adminstuds.php index f8b0d43..a26a08c 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -189,7 +189,12 @@ if (isset($_POST['remove_all_votes'])) { exit; } if (isset($_POST['confirm_remove_all_votes'])) { - $adminPollService->cleanVotes($poll_id); + // TODO Add log + if ($adminPollService->cleanVotes($poll_id)) { + $message = new Message('success', _('All votes deleted.')); + } else { + $message = new Message('danger', _('Failed to delete all votes.')); + } } // ------------------------------- @@ -242,6 +247,7 @@ if (isset($_POST['remove_all_comments'])) { exit; } if (isset($_POST['confirm_remove_all_comments'])) { + // TODO Add log if ($adminPollService->cleanComments($poll_id)) { $message = new Message('success', _('All comments deleted.')); } else { @@ -261,7 +267,18 @@ if (isset($_POST['delete_poll'])) { exit; } if (isset($_POST['confirm_delete_poll'])) { - // TODO + // TODO Add log + if ($adminPollService->deleteEntirePoll($poll_id)) { + $message = new Message('success', _('Poll fully deleted.')); + } else { + $message = new Message('danger', _('Failed to delete the poll.')); + } + $smarty->assign('poll_id', $poll_id); + $smarty->assign('admin_poll_id', $admin_poll_id); + $smarty->assign('title', _('Poll') . ' - ' . $poll->title); + $smarty->assign('message', $message); + $smarty->display('poll_deleted.tpl'); + exit; } // ------------------------------- @@ -269,6 +286,7 @@ if (isset($_POST['confirm_delete_poll'])) { // ------------------------------- if (!empty($_POST['delete_column'])) { + // TODO Add log $column = filter_input(INPUT_POST, 'delete_column', FILTER_DEFAULT); if ($adminPollService->deleteSlot($poll_id, $column)) { diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index aab3fc1..b6864ab 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -127,7 +127,7 @@ class FramaDB { * @param $poll_id int The ID of the given poll. * @return bool|null true if action succeeded. */ - function deleteVotesByAdminPollId($poll_id) { + function deleteVotesByPollId($poll_id) { $prepared = $this->prepare('DELETE FROM user_studs WHERE id_sondage = ?'); return $prepared->execute([$poll_id]); } @@ -197,13 +197,18 @@ class FramaDB { $prepared->execute([$poll_id, $datetime]); } + function deleteSlotsByPollId($poll_id) { + $prepared = $this->prepare('DELETE FROM sujet_studs WHERE id_sondage = ?'); + $prepared->execute([$poll_id]); + } + /** * Delete all comments of a given poll. * * @param $poll_id int The ID of the given poll. * @return bool|null true if action succeeded. */ - function deleteCommentsByAdminPollId($poll_id) { + function deleteCommentsByPollId($poll_id) { $prepared = $this->prepare('DELETE FROM comments WHERE id_sondage = ?'); return $prepared->execute([$poll_id]); } @@ -223,4 +228,9 @@ class FramaDB { return $prepared->execute([$poll_id, $comment_id]); } + function deleteByPollId($poll_id) { + $prepared = $this->prepare('DELETE FROM sondage WHERE poll_id = ?'); + $prepared->execute([$poll_id]); + } + } diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php index 9d9c106..4559ce6 100644 --- a/app/classes/Framadate/Services/AdminPollService.php +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -40,7 +40,7 @@ class AdminPollService { * @return bool|null true is action succeeded */ function cleanComments($poll_id) { - return $this->connect->deleteCommentsByAdminPollId($poll_id); + return $this->connect->deleteCommentsByPollId($poll_id); } /** @@ -61,7 +61,22 @@ class AdminPollService { * @return bool|null true is action succeeded */ function cleanVotes($poll_id) { - return $this->connect->deleteVotesByAdminPollId($poll_id); + return $this->connect->deleteVotesByPollId($poll_id); + } + + /** + * Delete the entire given poll. + * + * @param $poll_id int The ID of the poll + * @return bool true is action succeeded + */ + function deleteEntirePoll($poll_id) { + /*$this->connect->deleteVotesByPollId($poll_id); + $this->connect->deleteCommentsByPollId($poll_id); + $this->connect->deleteSlotsByPollId($poll_id); + $this->connect->deleteByPollId($poll_id);*/ + + return true; } /** @@ -69,6 +84,7 @@ class AdminPollService { * * @param $poll_id int The ID of the poll * @param $slot string The name of the slot + * @return bool true if action succeeded */ public function deleteSlot($poll_id, $slot) { $ex = explode('@', $slot); diff --git a/old_adminstuds.php b/old_adminstuds.php index 945be49..46a8b8e 100644 --- a/old_adminstuds.php +++ b/old_adminstuds.php @@ -42,97 +42,6 @@ function send_mail_admin() { } -// reload -// TODO OPZ Pourquoi recharger -// $dsujet= $sujets->FetchObject(false); -// $dsondage= $sondage->FetchObject(false); - -if (isset($_POST['ajoutsujet'])) { - Utils::print_header( _('Add a column') .' - ' . stripslashes($poll->title)); - - bandeau_titre(_('Make your polls')); - - //on recupere les données et les sujets du sondage - - echo ' -
      -
      -
      -

      ' . _("Column's adding") . '

      '."\n"; - - if ($poll->format == "A"){ - echo ' -
      - -
      - -
      -
      '."\n"; - } else { - // ajout d'une date avec creneau horaire - echo ' -

      '. _("You can add a new scheduling date to your poll.").'
      '._("If you just want to add a new hour to an existant date, put the same date and choose a new hour.") .'

      - -
      - -
      -
      - - -
      - '. _("(dd/mm/yyyy)") .' -
      -
      -
      - -
      - -
      -
      '; - } - echo ' -

      - - -

      - -
      -
      '; - - bandeau_pied(); - - die(); -} - -//action si bouton confirmation de suppression est activé -if (isset($_POST["confirmesuppression"])) { - $nbuser=$user_studs->RecordCount(); - $date=date('H:i:s d/m/Y:'); - - if (Utils::remove_sondage($connect, $poll_id)) { - // on ecrit dans le fichier de logs la suppression du sondage - error_log($date . " SUPPRESSION: $dsondage->id_sondage\t$dsondage->format\t$dsondage->nom_admin\t$dsondage->mail_admin\n", 3, 'admin/logs_studs.txt'); - - // Email sent - send_mail_admin(); - //affichage de l'ecran de confirmation de suppression de sondage - Utils::print_header(_("Your poll has been removed!")); - - bandeau_titre(_("Make your polls")); - - echo ' -
      -

      ' . _("Your poll has been removed!") . '

      -

      ' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

      -
      - '."\n"; - - bandeau_pied(); - - die(); - } -} - $nbcolonnes = count($sujets); $nblignes = count($users); @@ -158,165 +67,11 @@ if (isset($_POST["ajoutercolonne"]) && !empty($_POST['nouvellecolonne']) && $pol } -// [begin] action quand on ajoute une colonne au format DATE -if (isset($_POST['ajoutercolonne']) && $dsondage->format == 'D') { - - if (!empty($_POST["newdate"])) { - $new_choice = mktime(0, 0, 0, substr($_POST["newdate"],3,2), substr($_POST["newdate"],0,2), substr($_POST["newdate"],6,4)); - - if (!empty($_POST["newhour"])){ - $new_choice .= '@' . $_POST["newhour"]; - } - - - - - - // TODO OPZ Delete the code below - // TODO OPZ Insert new choice - // TODO OPZ Update users votes (add "0" in the right column^^) - - - - //on rajoute la valeur dans les valeurs - $datesbase = explode(",",$dsujet->sujet); - $taillebase = sizeof($datesbase); - - //recherche de l'endroit de l'insertion de la nouvelle date dans les dates deja entrées dans le tableau - if ($nouvelledate < $datesbase[0]) { - $cleinsertion = 0; - } elseif ($nouvelledate > $datesbase[$taillebase-1]) { - $cleinsertion = count($datesbase); - } else { - for ($i = 0; $i < count($datesbase); $i++) { - $j = $i + 1; - if ($nouvelledate > $datesbase[$i] && $nouvelledate < $datesbase[$j]) { - $cleinsertion = $j; - } - } - } - - array_splice($datesbase, $cleinsertion, 0, $nouvelledate); - $cle = array_search($nouvelledate, $datesbase); - $dateinsertion = ''; - for ($i = 0; $i < count($datesbase); $i++) { - $dateinsertion.=","; - $dateinsertion.=$datesbase[$i]; - } - - $dateinsertion = substr("$dateinsertion", 1); - - //mise a jour avec les nouveaux sujets dans la base - //if (isset($erreur_ajout_date) && !$erreur_ajout_date){ - $sql = 'UPDATE sujet_studs SET sujet = '.$connect->Param('dateinsertion').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($dateinsertion, $poll_id)); - - if ($nouvelledate > strtotime($dsondage->date_fin)) { - $date_fin=$nouvelledate+200000; - $sql = 'UPDATE sondage SET date_fin = '.$connect->Param('date_fin').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($date_fin, $poll_id)); - } - //} - - //mise a jour des reponses actuelles correspondant au sujet ajouté - $sql = 'UPDATE user_studs SET reponses = '.$connect->Param('reponses').' WHERE nom = '.$connect->Param('nom').' AND id_users='.$connect->Param('id_users'); - $sql = $connect->Prepare($sql); - while ($data = $user_studs->FetchNextObject(false)) { - $ensemblereponses=$data->reponses; - $newcar = ''; - - //parcours de toutes les réponses actuelles - for ($j = 0; $j < $nbcolonnes; $j++) { - $car=substr($ensemblereponses,$j,1); - - //si les reponses ne concerne pas la colonne ajoutée, on concatene - if ($j==$cle) { - $newcar.="0"; - } - - $newcar.=$car; - } - - //mise a jour des reponses utilisateurs dans la base - if (isset($erreur_ajout_date) && !$erreur_ajout_date){ - $connect->Execute($sql, array($newcar, $data->nom, $data->id_users)); - } - } - - //Email sent to the admin - send_mail_admin(); - - } else { - $erreur_ajout_date="yes"; - } -} -// [end] action quand on ajoute une colonne au format DATE - - //on teste pour voir si une ligne doit etre modifiée $testmodifier = false; $testligneamodifier = false; -//suppression de colonnes dans la base -for ($i = 0; $i < $nbcolonnes; $i++) { - if ((isset($_POST["effacecolonne$i"])) && $nbcolonnes > 1){ - $sujets = explode(",",$dsujet->sujet); - //sort($toutsujet, SORT_NUMERIC); - $j = 0; - $nouveauxsujets = ''; - - //parcours de tous les sujets actuels - while (isset($sujets[$j])) { - //si le sujet n'est pas celui qui a été effacé alors on concatene - if ($i != $j) { - $nouveauxsujets .= ','; - $nouveauxsujets .= $sujets[$j]; - } - - $j++; - } - - //on enleve la virgule au début - $nouveauxsujets = substr("$nouveauxsujets", 1); - - //nettoyage des reponses actuelles correspondant au sujet effacé - $compteur = 0; - $sql = 'UPDATE user_studs SET reponses = '.$connect->Param('reponses').' WHERE nom = '.$connect->Param('nom').' AND id_users = '.$connect->Param('id_users'); - $sql = $connect->Prepare($sql); - - while ($data = $user_studs->FetchNextObject(false)) { - $newcar = ''; - $ensemblereponses = $data->reponses; - - //parcours de toutes les réponses actuelles - for ($j = 0; $j < $nbcolonnes; $j++) { - $car=substr($ensemblereponses, $j, 1); - //si les reponses ne concerne pas la colonne effacée, on concatene - if ($i != $j) { - $newcar .= $car; - } - } - - $compteur++; - - //mise a jour des reponses utilisateurs dans la base - $connect->Execute($sql, array($newcar, $data->nom, $data->id_users)); - } - - //mise a jour des sujets dans la base - $sql = 'UPDATE sujet_studs SET sujet = '.$connect->Param('nouveauxsujets').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($nouveauxsujets, $poll_id)); - } -} - - - -// Table headers -$thead = '
      '; // Button in the first td to avoid remove col on "Return" keypress) $tr_add_remove_col = ''; @@ -325,78 +80,7 @@ $border = array(); // bordure pour distinguer les mois $td_headers = array(); // for a11y, headers="M1 D4 H5" on each td $radio_title = array(); // date for -// Display dates poll -if ($poll->format == "D") { - - $tr_months = ''; - $tr_days = ''; - $tr_hours = ''; - - // Headers - $colspan_month = 1; - $colspan_day = 1; - - foreach ($sujets as $i=>$sujet) { - - // Current date - $horoCur = explode('@', $sujet->sujet); //horoCur[0] = date, horoCur[1] = hour - if (isset($sujets[$i+1])){ - $next = $sujets[$i+1]->sujet; - $horoNext = explode('@', $next); - } - $border[$i] = false; - $radio_title[$i] = strftime($date_format['txt_short'], $horoCur[0]); - - // Months - $td_headers[$i] = 'M'.($i+1-$colspan_month); - - if (isset($sujets[$i+1]) && strftime("%B", $horoCur[0]) == strftime("%B", $horoNext[0]) && strftime("%Y", $horoCur[0]) == strftime("%Y", $horoNext[0])){ - $colspan_month++; - } else { - $border[$i] = true; - $tr_months .= ''; - $colspan_month=1; - } - - // Days - $td_headers[$i] .= ' D'.($i+1-$colspan_day); - - if (isset($sujets[$i+1]) && strftime($date_format['txt_day'],$horoCur[0])==strftime($date_format['txt_day'],$horoNext[0]) && strftime("%B",$horoCur[0])==strftime("%B",$horoNext[0])){ - $colspan_day++; - } else { - $rbd = ($border[$i]) ? ' rbd' : ''; - $tr_days .= ''; - $colspan_day=1; - } - - // Hours - $rbd = ($border[$i]) ? ' rbd' : ''; - if ($horoCur[1] !== "") { - $tr_hours .= ''; - $radio_title[$i] .= ' - '.$horoCur[1]; - $td_headers[$i] .= ' H'.$i; - } else { - $tr_hours .= ''; - } - - // Remove col - $tr_add_remove_col .= (count($sujets) > 2 ) ? '' : ''; - - } - - $border[count($border)-1] = false; // suppression de la bordure droite du dernier mois - - $tr_months .= ''; - $tr_days .= ''; - $tr_hours .= ''; - - // Add col - $tr_add_remove_col .= ''; - - $thead = "\n".$tr_add_remove_col."\n".$tr_months."\n".$tr_days."\n".$tr_hours."\n"; - -// Subjects poll -} else { +if ($poll->format == "A") { $tr_subjects = ''; foreach ($sujets as $i=>$sujet) { diff --git a/tpl/poll_deleted.tpl b/tpl/poll_deleted.tpl new file mode 100644 index 0000000..b7b0ce3 --- /dev/null +++ b/tpl/poll_deleted.tpl @@ -0,0 +1,8 @@ +{extends file='page.tpl'} + +{block name=main} +
      +

      {_("Your poll has been removed!")}

      +

      {_('Back to the homepage of')} {$APPLICATION_NAME}

      +
      +{/block} \ No newline at end of file From a5d1305535dd0773e62e519f6a9a5f67ed76be75 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 24 Dec 2014 09:40:41 +0100 Subject: [PATCH 064/151] LogService : WIP --- adminstuds.php | 5 +++-- .../Framadate/Services/AdminPollService.php | 6 +++++- app/classes/Framadate/Services/LogService.php | 15 +++++++++++++++ 3 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 app/classes/Framadate/Services/LogService.php diff --git a/adminstuds.php b/adminstuds.php index a26a08c..c14cb3b 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -19,6 +19,7 @@ use Framadate\Services\PollService; use Framadate\Services\AdminPollService; use Framadate\Services\InputService; +use Framadate\Services\LogService; use Framadate\Message; use Framadate\Utils; @@ -35,8 +36,9 @@ $editingVoteId = 0; /* Services */ /*----------*/ +$logService = new LogService(); $pollService = new PollService($connect); -$adminPollService = new AdminPollService($connect, $pollService); +$adminPollService = new AdminPollService($connect, $pollService, $logService); $inputService = new InputService(); /* PAGE */ @@ -267,7 +269,6 @@ if (isset($_POST['delete_poll'])) { exit; } if (isset($_POST['confirm_delete_poll'])) { - // TODO Add log if ($adminPollService->deleteEntirePoll($poll_id)) { $message = new Message('success', _('Poll fully deleted.')); } else { diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php index 4559ce6..5b18816 100644 --- a/app/classes/Framadate/Services/AdminPollService.php +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -12,10 +12,12 @@ class AdminPollService { private $connect; private $pollService; + private $logService; - function __construct($connect, $pollService) { + function __construct($connect, $pollService, $logService) { $this->connect = $connect; $this->pollService = $pollService; + $this->logService = $logService; } function updatePoll($poll) { @@ -71,6 +73,8 @@ class AdminPollService { * @return bool true is action succeeded */ function deleteEntirePoll($poll_id) { + $poll = $this->connect->findPollById($poll_id); + $this->logService->log("DELETE_POLL", "id$poll->poll_id, format:$poll->format, $poll->admin_name, $poll->admin_mail"); /*$this->connect->deleteVotesByPollId($poll_id); $this->connect->deleteCommentsByPollId($poll_id); $this->connect->deleteSlotsByPollId($poll_id); diff --git a/app/classes/Framadate/Services/LogService.php b/app/classes/Framadate/Services/LogService.php new file mode 100644 index 0000000..afceb48 --- /dev/null +++ b/app/classes/Framadate/Services/LogService.php @@ -0,0 +1,15 @@ + Date: Wed, 24 Dec 2014 22:42:50 +0100 Subject: [PATCH 065/151] admin: Add some logging on important actions (delete poll, clean votes, clean comments, drop column) --- adminstuds.php | 5 +---- app/classes/Framadate/Services/AdminPollService.php | 5 ++++- app/classes/Framadate/Services/LogService.php | 9 ++++++++- app/classes/Framadate/Services/PollService.php | 6 ++++++ 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index c14cb3b..20dc5bb 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -36,7 +36,7 @@ $editingVoteId = 0; /* Services */ /*----------*/ -$logService = new LogService(); +$logService = new LogService(LOG_FILE); $pollService = new PollService($connect); $adminPollService = new AdminPollService($connect, $pollService, $logService); $inputService = new InputService(); @@ -191,7 +191,6 @@ if (isset($_POST['remove_all_votes'])) { exit; } if (isset($_POST['confirm_remove_all_votes'])) { - // TODO Add log if ($adminPollService->cleanVotes($poll_id)) { $message = new Message('success', _('All votes deleted.')); } else { @@ -249,7 +248,6 @@ if (isset($_POST['remove_all_comments'])) { exit; } if (isset($_POST['confirm_remove_all_comments'])) { - // TODO Add log if ($adminPollService->cleanComments($poll_id)) { $message = new Message('success', _('All comments deleted.')); } else { @@ -287,7 +285,6 @@ if (isset($_POST['confirm_delete_poll'])) { // ------------------------------- if (!empty($_POST['delete_column'])) { - // TODO Add log $column = filter_input(INPUT_POST, 'delete_column', FILTER_DEFAULT); if ($adminPollService->deleteSlot($poll_id, $column)) { diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php index 5b18816..c506dfc 100644 --- a/app/classes/Framadate/Services/AdminPollService.php +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -42,6 +42,7 @@ class AdminPollService { * @return bool|null true is action succeeded */ function cleanComments($poll_id) { + $this->logService->log("CLEAN_COMMENTS", "id:$poll_id"); return $this->connect->deleteCommentsByPollId($poll_id); } @@ -63,6 +64,7 @@ class AdminPollService { * @return bool|null true is action succeeded */ function cleanVotes($poll_id) { + $this->logService->log("CLEAN_VOTES", "id:$poll_id"); return $this->connect->deleteVotesByPollId($poll_id); } @@ -74,7 +76,7 @@ class AdminPollService { */ function deleteEntirePoll($poll_id) { $poll = $this->connect->findPollById($poll_id); - $this->logService->log("DELETE_POLL", "id$poll->poll_id, format:$poll->format, $poll->admin_name, $poll->admin_mail"); + $this->logService->log("DELETE_POLL", "id:$poll->poll_id, format:$poll->format, admin:$poll->admin_name, mail:$poll->admin_mail"); /*$this->connect->deleteVotesByPollId($poll_id); $this->connect->deleteCommentsByPollId($poll_id); $this->connect->deleteSlotsByPollId($poll_id); @@ -91,6 +93,7 @@ class AdminPollService { * @return bool true if action succeeded */ public function deleteSlot($poll_id, $slot) { + $this->logService->log("DELETE_SLOT", "id:$poll_id, slot:" . json_encode($slot)); $ex = explode('@', $slot); $datetime = $ex[0]; $moment = $ex[1]; diff --git a/app/classes/Framadate/Services/LogService.php b/app/classes/Framadate/Services/LogService.php index afceb48..b717f22 100644 --- a/app/classes/Framadate/Services/LogService.php +++ b/app/classes/Framadate/Services/LogService.php @@ -8,7 +8,14 @@ namespace Framadate\Services; */ class LogService { - function __construct() { + private $output; + + function __construct($output) { + $this->output = $output; + } + + function log($tag, $message) { + error_log('[' . $tag . '] ' . $message, 3, $this->output); } } diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index bd7c6c7..2e62b44 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -26,6 +26,12 @@ class PollService { $this->connect = $connect; } + /** + * Find a poll from its ID. + * + * @param $poll_id int The ID of the poll + * @return \stdClass|null The found poll, or null + */ function findById($poll_id) { if (preg_match('/^[\w\d]{16}$/i', $poll_id)) { return $this->connect->findPollById($poll_id); From 31f62cd62dd768f47535f1d752f29149c0c21222 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 24 Dec 2014 23:38:44 +0100 Subject: [PATCH 066/151] LogService: Add a line break at the en of lines --- app/classes/Framadate/Services/LogService.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/app/classes/Framadate/Services/LogService.php b/app/classes/Framadate/Services/LogService.php index b717f22..a8f27aa 100644 --- a/app/classes/Framadate/Services/LogService.php +++ b/app/classes/Framadate/Services/LogService.php @@ -14,8 +14,14 @@ class LogService { $this->output = $output; } + /** + * Log a message to the log file. + * + * @param $tag string A tag is used to quickly found a message when reading log file + * @param $message string some message + */ function log($tag, $message) { - error_log('[' . $tag . '] ' . $message, 3, $this->output); + error_log('[' . $tag . '] ' . $message . "\n", 3, $this->output); } } From 2f3831d99754764ba22c54fddcc7c744cd5e9e8d Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 24 Dec 2014 23:44:40 +0100 Subject: [PATCH 067/151] Add const LOG_FILE to constants.php.template --- app/inc/constants.php.template | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/inc/constants.php.template b/app/inc/constants.php.template index 6afeb02..af7f289 100644 --- a/app/inc/constants.php.template +++ b/app/inc/constants.php.template @@ -67,6 +67,9 @@ const URL_PROPRE = false; // Use REMOTE_USER data provided by web server const USE_REMOTE_USER = true; +// Path to the log file +const LOG_FILE = 'admin/stdout.log'; + const COMMENT_EMPTY = 0x0000000001; const COMMENT_USER_EMPTY = 0x0000000010; const COMMENT_INSERT_FAILED = 0x0000000100; From 9ed0043569dbad4aa280d75d21cf95d9dd8b10b3 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 25 Dec 2014 00:55:52 +0100 Subject: [PATCH 068/151] Some cleaning in poll creation --- adminstuds.php | 2 +- app/classes/Framadate/Form.php | 12 +- app/classes/Framadate/Services/LogService.php | 2 +- .../Framadate/Services/PollService.php | 79 +++++++++++- bandeaux.php | 2 +- choix_autre.php | 2 - choix_date.php | 58 ++++++--- creation_sondage.php | 114 ------------------ infos_sondage.php | 26 ++-- studs.php | 5 +- 10 files changed, 141 insertions(+), 161 deletions(-) delete mode 100644 creation_sondage.php diff --git a/adminstuds.php b/adminstuds.php index 20dc5bb..05aed7e 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -37,7 +37,7 @@ $editingVoteId = 0; /*----------*/ $logService = new LogService(LOG_FILE); -$pollService = new PollService($connect); +$pollService = new PollService($connect, $logService); $adminPollService = new AdminPollService($connect, $pollService, $logService); $inputService = new InputService(); diff --git a/app/classes/Framadate/Form.php b/app/classes/Framadate/Form.php index 2be9e6c..c002997 100644 --- a/app/classes/Framadate/Form.php +++ b/app/classes/Framadate/Form.php @@ -21,12 +21,12 @@ namespace Framadate; class Form { - public $titre; - public $commentaires; - public $nom; - public $adresse; - public $formatsondage; - public $champdatefin; + public $title; + public $description; + public $admin_name; + public $admin_mail; + public $format; + public $end_date; public $choix_sondage; /** diff --git a/app/classes/Framadate/Services/LogService.php b/app/classes/Framadate/Services/LogService.php index a8f27aa..620ffa9 100644 --- a/app/classes/Framadate/Services/LogService.php +++ b/app/classes/Framadate/Services/LogService.php @@ -21,7 +21,7 @@ class LogService { * @param $message string some message */ function log($tag, $message) { - error_log('[' . $tag . '] ' . $message . "\n", 3, $this->output); + error_log(date('H:i:s d/m/Y:') . '[' . $tag . '] ' . $message . "\n", 3, $this->output); } } diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 2e62b44..25a4b2e 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -18,12 +18,18 @@ */ namespace Framadate\Services; +use Framadate\Form; +use Framadate\FramaDB; +use Framadate\Utils; + class PollService { private $connect; + private $logService; - function __construct($connect) { + function __construct(FramaDB $connect, LogService $logService) { $this->connect = $connect; + $this->logService = $logService; } /** @@ -54,11 +60,13 @@ class PollService { public function updateVote($poll_id, $vote_id, $choices) { $choices = implode($choices); + return $this->connect->updateVote($poll_id, $vote_id, $choices); } function addVote($poll_id, $name, $choices) { $choices = implode($choices); + return $this->connect->insertVote($poll_id, $name, $choices); } @@ -71,7 +79,7 @@ class PollService { $result = []; foreach ($votes as $vote) { $choices = str_split($vote->reponses); - foreach ($choices as $i=>$choice) { + foreach ($choices as $i => $choice) { if (empty($result[$i])) { $result[$i] = 0; } @@ -80,6 +88,7 @@ class PollService { } } } + return $result; } @@ -93,6 +102,7 @@ class PollService { $splitted[] = $obj; } + return $splitted; } @@ -106,6 +116,71 @@ class PollService { $splitted[] = $obj; } + return $splitted; } + + /** + * @param Form $form + * @return string + */ + function createPoll(Form $form) { + + // Generate poll IDs + $poll_id = $this->random(16); + $admin_poll_id = $poll_id . $this->random(8); + + // Insert poll + slots + $this->connect->beginTransaction(); + + $sql = 'INSERT INTO sondage + (poll_id, admin_poll_id, title, comment, admin_name, admin_mail, end_date, format, editable, receiveNewVotes) + VALUES (?,?,?,?,?,?,FROM_UNIXTIME(?),?,?,?)'; + $prepared = $this->connect->prepare($sql); + $prepared->execute(array($poll_id, $admin_poll_id, $form->title, $form->description, $form->admin_name, $form->admin_mail, $form->end_date, $form->format, $form->editable, $form->receiveNewVotes)); + + $prepared = $this->connect->prepare('INSERT INTO sujet_studs (id_sondage, sujet) VALUES (?, ?)'); + + foreach ($form->getChoices() as $choice) { + + // We prepared the slots (joined by comas) + $joinedSlots = ''; + $first = true; + foreach ($choice->getSlots() as $slot) { + if ($first) { + $joinedSlots = $slot; + $first = false; + } else { + $joinedSlots .= ',' . $slot; + } + } + + // We execute the insertion + if (empty($joinedSlots)) { + $prepared->execute(array($poll_id, $choice->getName())); + } else { + $prepared->execute(array($poll_id, $choice->getName() . '@' . $joinedSlots)); + } + + } + + $this->connect->commit(); + + $this->logService->log('CREATE_POLL', ' id:' . $poll_id . ', format:' . $form->format . ', admin:' . $form->admin_name . ', mail:' . $form->admin_mail); + + + return [$poll_id, $admin_poll_id]; + } + + private function random($car) { + // TODO Better random ? + $string = ''; + $chaine = 'abcdefghijklmnopqrstuvwxyz123456789'; + srand((double)microtime() * 1000000); + for ($i = 0; $i < $car; $i++) { + $string .= $chaine[rand() % strlen($chaine)]; + } + + return $string; + } } diff --git a/bandeaux.php b/bandeaux.php index 7f86cde..f931177 100644 --- a/bandeaux.php +++ b/bandeaux.php @@ -16,7 +16,7 @@ * Auteurs de STUdS (projet initial) : Guilhem BORGHESI (borghesi@unistra.fr) et Raphaël DROZ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ -namespace Framadate; +use Framadate\Utils; include_once __DIR__ . '/app/inc/init.php'; diff --git a/choix_autre.php b/choix_autre.php index 7ebca4d..368e6b5 100644 --- a/choix_autre.php +++ b/choix_autre.php @@ -20,8 +20,6 @@ namespace Framadate; include_once __DIR__ . '/app/inc/init.php'; -include_once('creation_sondage.php'); - if (file_exists('bandeaux_local.php')) { include_once('bandeaux_local.php'); } else { diff --git a/choix_date.php b/choix_date.php index 5a4e06c..6bf17e6 100644 --- a/choix_date.php +++ b/choix_date.php @@ -16,11 +16,19 @@ * Auteurs de STUdS (projet initial) : Guilhem BORGHESI (borghesi@unistra.fr) et Raphaël DROZ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ -namespace Framadate; +use Framadate\Services\LogService; +use Framadate\Services\PollService; +use Framadate\Services\MailService; +use Framadate\Utils; +use Framadate\Choice; include_once __DIR__ . '/app/inc/init.php'; -include_once('creation_sondage.php'); +/* Service */ +/*---------*/ +$logService = new LogService(LOG_FILE); +$pollService = new PollService($connect, $logService); +$mailService = new MailService($config['use_smtp']); if (is_readable('bandeaux_local.php')) { include_once('bandeaux_local.php'); @@ -29,7 +37,7 @@ if (is_readable('bandeaux_local.php')) { } // Step 1/4 : error if $_SESSION from info_sondage are not valid -if (!isset($_SESSION['form']->titre) || !isset($_SESSION['form']->nom) || (($config['use_smtp']) ? !isset($_SESSION['form']->adresse) : false)) { +if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || ($config['use_smtp'] && !isset($_SESSION['form']->admin_mail))) { Utils::print_header ( _("Error!") ); bandeau_titre(_("Error!")); @@ -56,34 +64,46 @@ if (!isset($_SESSION['form']->titre) || !isset($_SESSION['form']->nom) || (($con $time = mktime(0,0,0, $registredate[1], $registredate[0], $registredate[2]); if ($time > time() + (24*60*60)) { - $_SESSION['form']->champdatefin=$time; + $_SESSION['form']->end_date=$time; } } } - if(empty($_SESSION['form']->champdatefin)) - { + if(empty($_SESSION['form']->end_date)) { // By default, expiration date is 6 months after last day - $_SESSION['form']->champdatefin=end($temp_results)+(86400 * $config['default_poll_duration']); + $_SESSION['form']->end_date=end($temp_results)+(86400 * $config['default_poll_duration']); } // Insert poll in database - $admin_poll_id = ajouter_sondage( - $_SESSION['form']->titre, - $_SESSION['form']->commentaires, - $_SESSION['form']->nom, - $_SESSION['form']->adresse, - $_SESSION['form']->formatsondage, - $_SESSION['form']->editable, - $_SESSION['form']->champdatefin, - $_SESSION['form']->receiveNewVotes, - $_SESSION['form']->getChoices() - ); + $ids = $pollService->createPoll($_SESSION['form']); + $poll_id = $ids[0]; + $admin_poll_id = $ids[1]; + + + // Send confirmation by mail if enabled + if ($config['use_smtp'] === true) { + $message = _("This is the message you have to send to the people you want to poll. \nNow, you have to send this message to everyone you want to poll."); + $message .= "\n\n"; + $message .= stripslashes(html_entity_decode($_SESSION['form']->admin_name, ENT_QUOTES, "UTF-8")) . ' ' . _("hast just created a poll called") . ' : "' . stripslashes(htmlspecialchars_decode($_SESSION['form']->title, ENT_QUOTES)) . "\".\n"; + $message .= _('Thanks for filling the poll at the link above') . " :\n\n%s\n\n" . _('Thanks for your confidence.') . "\n" . NOMAPPLICATION; + + $message_admin = _("This message should NOT be sent to the polled people. It is private for the poll's creator.\n\nYou can now modify it at the link above"); + $message_admin .= " :\n\n" . "%s \n\n" . _('Thanks for your confidence.') . "\n" . NOMAPPLICATION; + + $message = sprintf($message, Utils::getUrlSondage($poll_id)); + $message_admin = sprintf($message_admin, Utils::getUrlSondage($admin_poll_id, true)); + + if ($mailService->isValidEmail($_SESSION['form']->admin_mail)) { + $mailService->send($_SESSION['form']->admin_mail, '[' . NOMAPPLICATION . '][' . _('Author\'s message') . '] ' . _('Poll') . ' : ' . stripslashes(htmlspecialchars_decode($_SESSION['form']->title, ENT_QUOTES)), $message_admin); + $mailService->send($_SESSION['form']->admin_mail, '[' . NOMAPPLICATION . '][' . _('For sending to the polled users') . '] ' . _('Poll') . ' : ' . stripslashes(htmlspecialchars_decode($_SESSION['form']->title, ENT_QUOTES)), $message); + } + } // Clean Form data in $_SESSION unset($_SESSION['form']); // Delete old polls + // TODO Create a PurgeService Utils::cleaningOldPolls($connect, 'admin/logs_studs.txt'); // Redirect to poll administration @@ -118,7 +138,7 @@ if (!isset($_SESSION['form']->titre) || !isset($_SESSION['form']->nom) || (($con } //le format du sondage est DATE - $_SESSION['form']->formatsondage = 'D'; + $_SESSION['form']->format = 'D'; // Step 3/4 : Confirm poll creation if (!empty($_POST['choixheures']) && !isset($_SESSION['form']->totalchoixjour)) { diff --git a/creation_sondage.php b/creation_sondage.php deleted file mode 100644 index 6705af1..0000000 --- a/creation_sondage.php +++ /dev/null @@ -1,114 +0,0 @@ -beginTransaction(); - - $sql = 'INSERT INTO sondage - (poll_id, admin_poll_id, title, comment, admin_name, admin_mail, end_date, format, editable, receiveNewVotes) - VALUES (?,?,?,?,?,?,FROM_UNIXTIME(?),?,?,?)'; - $prepared = $connect->prepare($sql); - $prepared->execute(array($poll_id, $admin_poll_id, $title, $comment, $adminName, $adminMail, $endDate, $format, $editable, $receiveNewVotes)); - - $prepared = $connect->prepare('INSERT INTO sujet_studs (id_sondage, sujet) VALUES (?, ?)'); - foreach ($choices as $choice) { - - // We prepared the slots (joined by comas) - $joinedSlots = ''; - $first = true; - foreach ($choice->getSlots() as $slot) { - - // We prepared the slots (joined by comas) - $joinedSlots = ''; - $first = true; - foreach ($choice->getSlots() as $slot) { - if ($first) { - $joinedSlots = $slot; - $first = false; - } else { - $joinedSlots .= ',' . $slot; - } - } - - // We execute the insertion - if (empty($joinedSlots)) { - $prepared->execute(array($poll_id, $choice->getName())); - } else { - $prepared->execute(array($poll_id, $choice->getName().'@'.$joinedSlots)); - } - - } - - } - - $connect->commit(); - - // Send confirmation by mail if enabled - if($config['use_smtp'] === true){ - $message = _("This is the message you have to send to the people you want to poll. \nNow, you have to send this message to everyone you want to poll."); - $message .= "\n\n"; - $message .= stripslashes(html_entity_decode($adminName, ENT_QUOTES, "UTF-8"))." " . _("hast just created a poll called") . " : \"".stripslashes(htmlspecialchars_decode($title,ENT_QUOTES))."\".\n"; - $message .= _("Thanks for filling the poll at the link above") . " :\n\n%s\n\n" . _("Thanks for your confidence.") . "\n".NOMAPPLICATION; - - $message_admin = _("This message should NOT be sent to the polled people. It is private for the poll's creator.\n\nYou can now modify it at the link above"); - $message_admin .= " :\n\n"."%s \n\n" . _("Thanks for your confidence.") . "\n".NOMAPPLICATION; - - $message = sprintf($message, Utils::getUrlSondage($poll_id)); - $message_admin = sprintf($message_admin, Utils::getUrlSondage($admin_poll_id, true)); - - if (Utils::isValidEmail($_SESSION['adresse'])) { - Utils::sendEmail( $adminMail, "[".NOMAPPLICATION."][" . _("Author's message") . "] " . _("Poll") . " : ".stripslashes(htmlspecialchars_decode($title,ENT_QUOTES)), $message_admin, $_SESSION['adresse'] ); - Utils::sendEmail( $adminMail, "[".NOMAPPLICATION."][" . _("For sending to the polled users") . "] " . _("Poll") . " : ".stripslashes(htmlspecialchars_decode($title,ENT_QUOTES)), $message, $_SESSION['adresse'] ); - } - } - - error_log(date('H:i:s d/m/Y:') . ' CREATION: '.$poll_id."\t".$format."\t".$adminName."\t".$adminMail."\n", 3, 'admin/logs_studs.txt'); - - return $admin_poll_id; -} diff --git a/infos_sondage.php b/infos_sondage.php index 58e00d8..6d9d24f 100644 --- a/infos_sondage.php +++ b/infos_sondage.php @@ -58,10 +58,10 @@ $erreur_injection_commentaires = false; #tests if (!empty($_POST['poursuivre'])){ - $_SESSION['form']->titre = $titre; - $_SESSION['form']->nom = $nom; - $_SESSION['form']->adresse = $adresse; - $_SESSION['form']->commentaires = $commentaires; + $_SESSION['form']->title = $titre; + $_SESSION['form']->admin_name = $nom; + $_SESSION['form']->admin_mail = $adresse; + $_SESSION['form']->description = $commentaires; $_SESSION['form']->editable = ($editable !== null) ? true : false; $_SESSION['form']->receiveNewVotes = ($receiveNewVotes !== null) ? true : false; @@ -140,7 +140,7 @@ $errors = array( ) ); -if (!$_SESSION['form']->titre && !empty($_POST['poursuivre'])) { +if (!$_SESSION['form']->title && !empty($_POST['poursuivre'])) { $errors['title']['aria'] = 'aria-describeby="poll_title_error" '; $errors['title']['class'] = ' has-error'; $errors['title']['msg'] = '

      ' . _("Enter a title") . '

      '; } elseif ($erreur_injection_titre) { @@ -153,7 +153,7 @@ if ($erreur_injection_commentaires) { $errors['description']['msg'] = '

      ' . _("Characters < > and \" are not permitted") . '

      '; } -if (!$_SESSION['form']->nom && !empty($_POST['poursuivre'])) { +if (!$_SESSION['form']->admin_name && !empty($_POST['poursuivre'])) { $errors['name']['aria'] = 'aria-describeby="poll_name_error" '; $errors['name']['class'] = ' has-error'; $errors['name']['msg'] = '

      ' . _("Enter a name") . '

      '; } elseif ($erreur_injection_nom) { @@ -161,7 +161,7 @@ if (!$_SESSION['form']->nom && !empty($_POST['poursuivre'])) { $errors['name']['msg'] = '

      ' . _("Characters < > and \" are not permitted") . '

      '; } -if (!$_SESSION['form']->adresse && !empty($_POST['poursuivre'])) { +if (!$_SESSION['form']->admin_mail && !empty($_POST['poursuivre'])) { $errors['email']['aria'] = 'aria-describeby="poll_name_error" '; $errors['email']['class'] = ' has-error'; $errors['email']['msg'] = '

      ' . _("Enter an email address") . '

      '; } elseif ($erreur_adresse && !empty($_POST['poursuivre'])) { @@ -175,15 +175,15 @@ if (!$_SESSION['form']->adresse && !empty($_POST['poursuivre'])) { // REMOTE_USER ? if (USE_REMOTE_USER && isset($_SERVER['REMOTE_USER'])) { - $input_name = ''.stripslashes($_SESSION['form']->nom); + $input_name = ''.stripslashes($_SESSION['form']->admin_name); } else { - $input_name = ''; + $input_name = ''; } if (USE_REMOTE_USER && isset($_SERVER['REMOTE_USER'])) { - $input_email = ''.$_SESSION['form']->adresse; + $input_email = ''.$_SESSION['form']->admin_mail; } else { - $input_email = ''; + $input_email = ''; } // Checkbox checked ? @@ -208,14 +208,14 @@ echo '
      - +
      '.$errors['title']['msg'].'
      - +
      '.$errors['description']['msg'].' diff --git a/studs.php b/studs.php index 437e462..a893a27 100644 --- a/studs.php +++ b/studs.php @@ -16,6 +16,7 @@ * Auteurs de STUdS (projet initial) : Guilhem BORGHESI (borghesi@unistra.fr) et Raphaël DROZ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ +use Framadate\Services\LogService; use Framadate\Services\PollService; use Framadate\Services\InputService; use Framadate\Services\MailService; @@ -34,8 +35,8 @@ $editingVoteId = 0; /* Services */ /*----------*/ - -$pollService = new PollService($connect); +$logService = new LogService(LOG_FILE); +$pollService = new PollService($connect, $logService); $inputService = new InputService(); $mailService = new MailService($config['use_smtp']); From 98f14c487ab7e358d517743a28b018737341914e Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 25 Dec 2014 01:11:06 +0100 Subject: [PATCH 069/151] Enable poll deletion + improve random generator --- app/classes/Framadate/Services/AdminPollService.php | 6 ++++-- app/classes/Framadate/Services/PollService.php | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php index c506dfc..4445ef6 100644 --- a/app/classes/Framadate/Services/AdminPollService.php +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -77,10 +77,12 @@ class AdminPollService { function deleteEntirePoll($poll_id) { $poll = $this->connect->findPollById($poll_id); $this->logService->log("DELETE_POLL", "id:$poll->poll_id, format:$poll->format, admin:$poll->admin_name, mail:$poll->admin_mail"); - /*$this->connect->deleteVotesByPollId($poll_id); + + // Delete the entire poll + $this->connect->deleteVotesByPollId($poll_id); $this->connect->deleteCommentsByPollId($poll_id); $this->connect->deleteSlotsByPollId($poll_id); - $this->connect->deleteByPollId($poll_id);*/ + $this->connect->deleteByPollId($poll_id); return true; } diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 25a4b2e..7edcdf0 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -176,9 +176,9 @@ class PollService { // TODO Better random ? $string = ''; $chaine = 'abcdefghijklmnopqrstuvwxyz123456789'; - srand((double)microtime() * 1000000); + mt_srand(); for ($i = 0; $i < $car; $i++) { - $string .= $chaine[rand() % strlen($chaine)]; + $string .= $chaine[mt_rand() % strlen($chaine)]; } return $string; From 9a067e00efe145b94d072ad195de6ee099c723ec Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Fri, 26 Dec 2014 23:32:53 +0100 Subject: [PATCH 070/151] Fix creation of classic polls --- choix_autre.php | 187 ++++++++++++++++++++++++++---------------------- choix_date.php | 63 ++++++++-------- 2 files changed, 134 insertions(+), 116 deletions(-) diff --git a/choix_autre.php b/choix_autre.php index 368e6b5..d66c264 100644 --- a/choix_autre.php +++ b/choix_autre.php @@ -16,10 +16,20 @@ * Auteurs de STUdS (projet initial) : Guilhem BORGHESI (borghesi@unistra.fr) et Raphaël DROZ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ -namespace Framadate; +use Framadate\Services\LogService; +use Framadate\Services\PollService; +use Framadate\Services\MailService; +use Framadate\Utils; +use Framadate\Choice; include_once __DIR__ . '/app/inc/init.php'; +/* Service */ +/*---------*/ +$logService = new LogService(LOG_FILE); +$pollService = new PollService($connect, $logService); +$mailService = new MailService($config['use_smtp']); + if (file_exists('bandeaux_local.php')) { include_once('bandeaux_local.php'); } else { @@ -27,73 +37,82 @@ if (file_exists('bandeaux_local.php')) { } // Step 1/4 : error if $_SESSION from info_sondage are not valid -if (empty($_SESSION['form']->titre) || empty($_SESSION['form']->nom) || (($config['use_smtp']) ? empty($_SESSION['form']->adresse) : false)) { +if (empty($_SESSION['form']->title) || empty($_SESSION['form']->admin_name) || (($config['use_smtp']) ? empty($_SESSION['form']->admin_mail) : false)) { - Utils::print_header ( _("Error!") ); + Utils::print_header(_("Error!")); bandeau_titre(_("Error!")); echo '

      ' . _('You haven\'t filled the first section of the poll creation.') . ' !

      ' . _('Back to the homepage of') . ' ' . NOMAPPLICATION . '

      -
      '."\n"; + ' . "\n"; bandeau_pied(); } else { - + // Step 4 : Data prepare before insert in DB if (isset($_POST['confirmecreation'])) { $registredate = explode('/', $_POST['champdatefin']); if (is_array($registredate) == true && count($registredate) == 3) { - $time = mktime(0,0,0,$registredate[1],$registredate[0],$registredate[2]); - if ($time > time() + (24*60*60)) { + $time = mktime(0, 0, 0, $registredate[1], $registredate[0], $registredate[2]); + if ($time > time() + (24 * 60 * 60)) { $_SESSION['form']->champdatefin = $time; } } // format du sondage AUTRE - $_SESSION['form']->formatsondage = 'A'; - + $_SESSION['form']->format = 'A'; + // Insert poll in database - $admin_poll_id = ajouter_sondage( - $_SESSION['form']->titre, - $_SESSION['form']->commentaires, - $_SESSION['form']->nom, - $_SESSION['form']->adresse, - $_SESSION['form']->formatsondage, - $_SESSION['form']->editable, - $_SESSION['form']->champdatefin, - $_SESSION['form']->receiveNewVotes, - $_SESSION['form']->getChoices() - ); - + $ids = $pollService->createPoll($_SESSION['form']); + $poll_id = $ids[0]; + $admin_poll_id = $ids[1]; + + + // Send confirmation by mail if enabled + if ($config['use_smtp'] === true) { + $message = _("This is the message you have to send to the people you want to poll. \nNow, you have to send this message to everyone you want to poll."); + $message .= "\n\n"; + $message .= stripslashes(html_entity_decode($_SESSION['form']->admin_name, ENT_QUOTES, "UTF-8")) . ' ' . _('hast just created a poll called') . ' : "' . stripslashes(htmlspecialchars_decode($_SESSION['form']->title, ENT_QUOTES)) . "\".\n"; + $message .= _('Thanks for filling the poll at the link above') . " :\n\n%s\n\n" . _('Thanks for your confidence.') . "\n" . NOMAPPLICATION; + + $message_admin = _("This message should NOT be sent to the polled people. It is private for the poll's creator.\n\nYou can now modify it at the link above"); + $message_admin .= " :\n\n" . "%s \n\n" . _('Thanks for your confidence.') . "\n" . NOMAPPLICATION; + + $message = sprintf($message, Utils::getUrlSondage($poll_id)); + $message_admin = sprintf($message_admin, Utils::getUrlSondage($admin_poll_id, true)); + + if ($mailService->isValidEmail($_SESSION['form']->admin_mail)) { + $mailService->send($_SESSION['form']->admin_mail, '[' . NOMAPPLICATION . '][' . _('Author\'s message') . '] ' . _('Poll') . ' : ' . stripslashes(htmlspecialchars_decode($_SESSION['form']->title, ENT_QUOTES)), $message_admin); + $mailService->send($_SESSION['form']->admin_mail, '[' . NOMAPPLICATION . '][' . _('For sending to the polled users') . '] ' . _('Poll') . ' : ' . stripslashes(htmlspecialchars_decode($_SESSION['form']->title, ENT_QUOTES)), $message); + } + } + // Clean Form data in $_SESSION unset($_SESSION['form']); // Delete old polls + // TODO Create a PurgeService Utils::cleaningOldPolls($connect, 'admin/logs_studs.txt'); - + // Redirect to poll administration header('Location:' . Utils::getUrlSondage($admin_poll_id, true)); exit; - } - - // Step 3/4 : Confirm poll creation and choose a removal date + } // Step 3/4 : Confirm poll creation and choose a removal date else if (isset($_POST['fin_sondage_autre'])) { - Utils::print_header ( _('Removal date and confirmation (3 on 3)') ); + Utils::print_header(_('Removal date and confirmation (3 on 3)')); bandeau_titre(_('Removal date and confirmation (3 on 3)')); - + // Store choices in $_SESSION if (isset($_POST['choices'])) { $_SESSION['form']->clearChoices(); - foreach ($_POST['choices'] as $c) - { - if (!empty($c)) - { + foreach ($_POST['choices'] as $c) { + if (!empty($c)) { $choice = new Choice(htmlentities(html_entity_decode($c, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8')); $_SESSION['form']->addChoice($choice); } @@ -101,29 +120,29 @@ if (empty($_SESSION['form']->titre) || empty($_SESSION['form']->nom) || (($confi } // Expiration date is initialised with config parameter. Value will be modified in step 4 if user has defined an other date - $_SESSION['form']->champdatefin = time() + (86400 * $config['default_poll_duration']); //60 sec * 60 min * 24 hours * config + $_SESSION['form']->end_date = time() + (86400 * $config['default_poll_duration']); //60 sec * 60 min * 24 hours * config // Summary $summary = '
        '; foreach ($_SESSION['form']->getChoices() as $choice) { - preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/', $choice->getName(), $md_a_img); // Markdown [![alt](src)](href) - preg_match_all('/!\[(.*?)\]\((.*?)\)/', $choice->getName(), $md_img); // Markdown ![alt](src) - preg_match_all('/\[(.*?)\]\((.*?)\)/', $choice->getName(), $md_a); // Markdown [text](href) - if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) + preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/', $choice->getName(), $md_a_img); // Markdown [![alt](src)](href) + preg_match_all('/!\[(.*?)\]\((.*?)\)/', $choice->getName(), $md_img); // Markdown ![alt](src) + preg_match_all('/\[(.*?)\]\((.*?)\)/', $choice->getName(), $md_a); // Markdown [text](href) + if (isset($md_a_img[2][0]) && $md_a_img[2][0] != '' && isset($md_a_img[3][0]) && $md_a_img[3][0] != '') { // [![alt](src)](href) - $li_subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); - $li_subject_html = ''.$li_subject_text.''; + $li_subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0] != '') ? stripslashes($md_a_img[1][0]) : _('Choice') . ' ' . ($i + 1); + $li_subject_html = '' . $li_subject_text . ''; - } elseif (isset($md_img[2][0]) && $md_img[2][0]!='') { // ![alt](src) + } elseif (isset($md_img[2][0]) && $md_img[2][0] != '') { // ![alt](src) - $li_subject_text = (isset($md_img[1][0]) && $md_img[1][0]!='') ? stripslashes($md_img[1][0]) : _("Choice") .' '.($i+1); - $li_subject_html = ''.$li_subject_text.''; + $li_subject_text = (isset($md_img[1][0]) && $md_img[1][0] != '') ? stripslashes($md_img[1][0]) : _('Choice') . ' ' . ($i + 1); + $li_subject_html = '' . $li_subject_text . ''; - } elseif (isset($md_a[2][0]) && $md_a[2][0]!='') { // [text](href) + } elseif (isset($md_a[2][0]) && $md_a[2][0] != '') { // [text](href) - $li_subject_text = (isset($md_a[1][0]) && $md_a[1][0]!='') ? stripslashes($md_a[1][0]) : _("Choice") .' '.($i+1); - $li_subject_html = ''.$li_subject_text.''; + $li_subject_text = (isset($md_a[1][0]) && $md_a[1][0] != '') ? stripslashes($md_a[1][0]) : _('Choice') . ' ' . ($i + 1); + $li_subject_html = '' . $li_subject_text . ''; } else { // text only @@ -132,54 +151,54 @@ if (empty($_SESSION['form']->titre) || empty($_SESSION['form']->nom) || (($confi } - $summary .= '
      1. '.$li_subject_html.'
      2. '."\n"; + $summary .= '
      3. ' . $li_subject_html . '
      4. ' . "\n"; } $summary .= '
      '; - $end_date_str = utf8_encode(strftime('%d/%M/%Y', $_SESSION['form']->champdatefin));//textual date + $end_date_str = utf8_encode(strftime('%d/%M/%Y', $_SESSION['form']->end_date)); //textual date echo '
      -

      '. _("List of your choices").'

      - '. $summary .' +

      ' . _('List of your choices') . '

      + ' . $summary . '
      -

      ' . _('Your poll will be automatically removed after'). ' ' . $config['default_poll_duration'] . ' ' . _('days') . '.
      ' . _("You can fix another removal date for it.") .'

      +

      ' . _('Your poll will be automatically removed after') . ' ' . $config['default_poll_duration'] . ' ' . _('days') . '.
      ' . _("You can fix another removal date for it.") . '

      - +
      - +
      - '. _("(dd/mm/yyyy)") .' + ' . _("(dd/mm/yyyy)") . '
      -

      '. _("Once you have confirmed the creation of your poll, you will be automatically redirected on the administration page of your poll."). '

      '; - if($config['use_smtp']==true){ +

      ' . _("Once you have confirmed the creation of your poll, you will be automatically redirected on the administration page of your poll.") . '

      '; + if ($config['use_smtp'] == true) { echo ' -

      ' . _("Then, you will receive quickly two emails: one contening the link of your poll for sending it to the voters, the other contening the link to the administration page of your poll.") .'

      '; +

      ' . _("Then, you will receive quickly two emails: one contening the link of your poll for sending it to the voters, the other contening the link to the administration page of your poll.") . '

      '; } echo '

      - - + +

      - '."\n"; + ' . "\n"; bandeau_pied(); - // Step 2/4 : Select choices of the poll + // Step 2/4 : Select choices of the poll } else { - Utils::print_header( _('Poll subjects (2 on 3)')); + Utils::print_header(_('Poll subjects (2 on 3)')); bandeau_titre(_('Poll subjects (2 on 3)')); echo ' @@ -188,12 +207,12 @@ if (empty($_SESSION['form']->titre) || empty($_SESSION['form']->nom) || (($confi
      '; echo '
      -

      '. _("To make a generic poll you need to propose at least two choices between differents subjects.") .'

      -

      '. _("You can add or remove additional choices with the buttons") .' '. _("Remove") .' '. _("Add") .'

      '; - if($config['user_can_add_img_or_link']){ - echo '

      '. _("It's possible to propose links or images by using "). ''. _("the Markdown syntax") .'.

      '; +

      ' . _("To make a generic poll you need to propose at least two choices between differents subjects.") . '

      +

      ' . _("You can add or remove additional choices with the buttons") . ' ' . _("Remove") . ' ' . _("Add") . '

      '; + if ($config['user_can_add_img_or_link']) { + echo '

      ' . _("It's possible to propose links or images by using ") . '' . _("the Markdown syntax") . '.

      '; } - echo '
      '."\n"; + echo '
      ' . "\n"; // Fields choices : 5 by default $choices = $_SESSION['form']->getChoices(); @@ -202,27 +221,27 @@ if (empty($_SESSION['form']->titre) || empty($_SESSION['form']->nom) || (($confi $choice = isset($choices[$i]) ? $choices[$i] : new Choice(); echo '
      - +
      - '; - if($config['user_can_add_img_or_link']){ - echo ' '; - } + '; + if ($config['user_can_add_img_or_link']) { + echo ' '; + } echo '
      -
      '."\n"; + ' . "\n"; } echo '
      - - + +
      - '. _('Back') . ' - + ' . _('Back') . ' +
      @@ -230,32 +249,32 @@ if (empty($_SESSION['form']->titre) || empty($_SESSION['form']->nom) || (($confi - '."\n"; + ' . "\n"; bandeau_pied(); diff --git a/choix_date.php b/choix_date.php index 6bf17e6..5a28339 100644 --- a/choix_date.php +++ b/choix_date.php @@ -44,8 +44,8 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || echo '
      -

      ' . _("You haven't filled the first section of the poll creation.") . ' !

      -

      ' . _("Back to the homepage of ") . ' ' . '' . NOMAPPLICATION . '.

      +

      ' . _('You haven\'t filled the first section of the poll creation.') . ' !

      +

      ' . _('Back to the homepage of ') . ' ' . '' . NOMAPPLICATION . '.

      '; @@ -84,7 +84,7 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || if ($config['use_smtp'] === true) { $message = _("This is the message you have to send to the people you want to poll. \nNow, you have to send this message to everyone you want to poll."); $message .= "\n\n"; - $message .= stripslashes(html_entity_decode($_SESSION['form']->admin_name, ENT_QUOTES, "UTF-8")) . ' ' . _("hast just created a poll called") . ' : "' . stripslashes(htmlspecialchars_decode($_SESSION['form']->title, ENT_QUOTES)) . "\".\n"; + $message .= stripslashes(html_entity_decode($_SESSION['form']->admin_name, ENT_QUOTES, 'UTF-8')) . ' ' . _("hast just created a poll called") . ' : "' . stripslashes(htmlspecialchars_decode($_SESSION['form']->title, ENT_QUOTES)) . "\".\n"; $message .= _('Thanks for filling the poll at the link above') . " :\n\n%s\n\n" . _('Thanks for your confidence.') . "\n" . NOMAPPLICATION; $message_admin = _("This message should NOT be sent to the polled people. It is private for the poll's creator.\n\nYou can now modify it at the link above"); @@ -168,29 +168,28 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) ||
      -

      '. _("Confirm the creation of your poll") .'

      +

      '. _('Confirm the creation of your poll') .'

      -

      '. _("List of your choices").'

      +

      '. _('List of your choices').'

      '. $summary .'
      -

      ' . _("Your poll will be automatically removed "). $config['default_poll_duration'] . ' ' . _("days") . ' ' ._("after the last date of your poll") . '.
      ' . _("You can fix another removal date for it.") .'

      +

      ' . _('Your poll will be automatically removed '). $config['default_poll_duration'] . ' ' . _("days") . ' ' ._('after the last date of your poll') . '.
      ' . _('You can fix another removal date for it.') .'

      - +
      - +
      '. _("(dd/mm/yyyy)") .'
      -

      '. _("Once you have confirmed the creation of your poll, you will be automatically redirected on the administration page of your poll."). '

      '; +

      '. _('Once you have confirmed the creation of your poll, you will be automatically redirected on the administration page of your poll.'). '

      '; if($config['use_smtp']==true){ - echo ' -

      ' . _("Then, you will receive quickly two emails: one contening the link of your poll for sending it to the voters, the other contening the link to the administration page of your poll.") .'

      '; + echo '

      ' . _('Then, you will receive quickly two emails: one contening the link of your poll for sending it to the voters, the other contening the link to the administration page of your poll.') .'

      '; } echo '
      @@ -206,8 +205,8 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || // Step 2/4 : Select dates of the poll } else { - Utils::print_header ( _("Poll dates (2 on 3)") ); - bandeau_titre(_("Poll dates (2 on 3)")); + Utils::print_header ( _('Poll dates (2 on 3)') ); + bandeau_titre(_('Poll dates (2 on 3)')); echo ' @@ -215,34 +214,34 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) ||

      '. _("Choose the dates of your poll") .'

      -

      '. _("To schedule an event you need to propose at least two choices (two hours for one day or two days).").'

      -

      '. _("You can add or remove additionnal days and hours with the buttons") .' '. _("Remove") .' '. _("Add") .'

      -

      '. _("For each selected day, you can choose, or not, meeting hours (e.g.: \"8h\", \"8:30\", \"8h-10h\", \"evening\", etc.)").'

      +

      '. _('To schedule an event you need to propose at least two choices (two hours for one day or two days).').'

      +

      '. _('You can add or remove additionnal days and hours with the buttons') .' '. _('Remove') .' '. _('Add') .'

      +

      '. _('For each selected day, you can choose, or not, meeting hours (e.g.: "8h", "8:30", "8h-10h", "evening", etc.)').'

      '; // Fields days : 3 by default - $nb_days = (isset($_SESSION["totalchoixjour"])) ? count($_SESSION["totalchoixjour"]) : 3; + $nb_days = (isset($_SESSION['totalchoixjour'])) ? count($_SESSION['totalchoixjour']) : 3; for ($i=0;$i<$nb_days;$i++) { - $day_value = isset($_SESSION["totalchoixjour"][$i]) ? strftime( "%d/%m/%Y", $_SESSION["totalchoixjour"][$i]) : ''; + $day_value = isset($_SESSION['totalchoixjour'][$i]) ? strftime('%d/%m/%Y', $_SESSION['totalchoixjour'][$i]) : ''; echo '
      - +
      - +
      - '. _("(dd/mm/yyyy)") .' + '. _('(dd/mm/yyyy)') .'
      '."\n"; // Fields hours : 3 by default - for ($j=0;$j - - + +
      '."\n"; } echo ' @@ -255,24 +254,24 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || } echo '
      - +
      - - + +
      '. _('Back') . ' - +
      From 60ae6bc3644356d5b00ba2a884c3ff1418d881da Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sat, 27 Dec 2014 00:00:14 +0100 Subject: [PATCH 071/151] Display a diffrent table if poll is a classic one --- adminstuds.php | 2 +- studs.php | 2 +- tpl/part/vote_table_classic.tpl | 190 ++++++++++++++++++ .../{vote_table.tpl => vote_table_date.tpl} | 0 tpl/studs.tpl | 6 +- 5 files changed, 197 insertions(+), 3 deletions(-) create mode 100644 tpl/part/vote_table_classic.tpl rename tpl/part/{vote_table.tpl => vote_table_date.tpl} (100%) diff --git a/adminstuds.php b/adminstuds.php index 05aed7e..aae0bbd 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -327,7 +327,7 @@ $smarty->assign('poll_id', $poll_id); $smarty->assign('admin_poll_id', $admin_poll_id); $smarty->assign('poll', $poll); $smarty->assign('title', _('Poll') . ' - ' . $poll->title); -$smarty->assign('slots', $pollService->splitSlots($slots)); +$smarty->assign('slots', $poll->format === 'D' ? $pollService->splitSlots($slots) : $slots); $smarty->assign('votes', $pollService->splitVotes($votes)); $smarty->assign('best_moments', $pollService->computeBestMoments($votes)); $smarty->assign('comments', $comments); diff --git a/studs.php b/studs.php index a893a27..7ff18a5 100644 --- a/studs.php +++ b/studs.php @@ -169,7 +169,7 @@ $comments = $pollService->allCommentsByPollId($poll_id); $smarty->assign('poll_id', $poll_id); $smarty->assign('poll', $poll); $smarty->assign('title', _('Poll') . ' - ' . $poll->title); -$smarty->assign('slots', $pollService->splitSlots($slots)); +$smarty->assign('slots', $poll->format === 'D' ? $pollService->splitSlots($slots) : $slots); $smarty->assign('votes', $pollService->splitVotes($votes)); $smarty->assign('best_moments', $pollService->computeBestMoments($votes)); $smarty->assign('comments', $comments); diff --git a/tpl/part/vote_table_classic.tpl b/tpl/part/vote_table_classic.tpl new file mode 100644 index 0000000..7d7e703 --- /dev/null +++ b/tpl/part/vote_table_classic.tpl @@ -0,0 +1,190 @@ +{if !is_array($best_moments) || empty($best_moments)} + {$best_moments = [0]} +{/if} + +

      {_('Votes of the poll')}

      + +
      + +
      {_('Votes of the poll')} {$poll->title}
      + + + +
      '.strftime("%B",$horoCur[0]).' '.strftime("%Y", $horoCur[0]).''.strftime($date_format['txt_day'],$horoCur[0]).''.$horoCur[1].'
      + + + {if $admin} + + + {foreach $slots as $id=>$slot} + + {/foreach} + + + {/if} + + + {foreach $slots as $id=>$slot} + + {/foreach} + + + + + {foreach $votes as $vote} + + {* Edited line *} + + + + {if $editingVoteId == $vote->id} + {foreach $vote->choices as $id=>$choice} + + + {/foreach} + + {else} + + {* Voted line *} + + {foreach $vote->choices as $choice} + + {if $choice==2} + + {elseif $choice==1} + + {else} + + {/if} + + {/foreach} + + {if $active && $poll->editable} + + {else} + + {/if} + {/if} + + {/foreach} + + {* Line to add a new vote *} + + {if $active && $editingVoteId == 0} + + + {foreach $slots as $id=>$slot} + + {/foreach} + + + {/if} + + {* Line displaying best moments *} + {$count_bests = 0} + {$max = max($best_moments)} + {if $max > 0} + + + {foreach $best_moments as $best_moment} + {if $max == $best_moment} + {$count_bests = $count_bests +1} + + {else} + + {/if} + {/foreach} + + {/if} + +
      {_('Votes of the poll')} {$poll->title}
      + + + +
      {$slot->sujet}
      {$vote->name} +
        +
      • + + +
      • +
      • + + +
      • +
      • + + +
      • +
      +
      {_('Yes')}(){_('Ifneedbe')}{_('No')} + + {if $admin} + + {/if} +
      +
      + + +
      +
      +
        +
      • + + +
      • +
      • + + +
      • +
      • + + +
      • +
      +
      {_("Addition")}{$max}
      + +
      + +{* Best votes listing *} + +{$max = max($best_moments)} +{if $max > 0} +
      + {if $count_bests == 1} +

      {_("Best choice")}

      +
      +

      {_("The best choice at this time is:")}

      + {elseif $count_bests > 1} +

      {_("Best choices")}

      +
      +

      {_("The bests choices at this time are:")}

      + {/if} + + + {$i = 0} +
        + {foreach $slots as $slot} + {foreach $slot->moments as $moment} + {if $best_moments[$i] == $max} +
      • {$slot->sujet}
      • + {/if} + {$i = $i+1} + {/foreach} + {/foreach} +
      +

      {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

      +
      +
      +{/if} \ No newline at end of file diff --git a/tpl/part/vote_table.tpl b/tpl/part/vote_table_date.tpl similarity index 100% rename from tpl/part/vote_table.tpl rename to tpl/part/vote_table_date.tpl diff --git a/tpl/studs.tpl b/tpl/studs.tpl index 5eeb84c..c9ed65e 100644 --- a/tpl/studs.tpl +++ b/tpl/studs.tpl @@ -33,7 +33,11 @@ {* Vote table *} -{include 'part/vote_table.tpl' active=$poll->active} +{if $poll->format === 'D'} + {include 'part/vote_table_date.tpl' active=$poll->active} +{else} + {include 'part/vote_table_classic.tpl' active=$poll->active} +{/if} {* Comments *} From 53048e848865faa7b2b1cd7845bce6b414867725 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sat, 27 Dec 2014 00:19:48 +0100 Subject: [PATCH 072/151] Fix display of best choices on classic polls --- adminstuds.php | 2 +- .../Framadate/Services/PollService.php | 2 +- studs.php | 2 +- tpl/part/vote_table_classic.tpl | 22 +++++++++---------- 4 files changed, 13 insertions(+), 15 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index aae0bbd..d2ad6c5 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -329,7 +329,7 @@ $smarty->assign('poll', $poll); $smarty->assign('title', _('Poll') . ' - ' . $poll->title); $smarty->assign('slots', $poll->format === 'D' ? $pollService->splitSlots($slots) : $slots); $smarty->assign('votes', $pollService->splitVotes($votes)); -$smarty->assign('best_moments', $pollService->computeBestMoments($votes)); +$smarty->assign('best_choices', $pollService->computeBestChoices($votes)); $smarty->assign('comments', $comments); $smarty->assign('editingVoteId', $editingVoteId); $smarty->assign('message', $message); diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 7edcdf0..47407f3 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -75,7 +75,7 @@ class PollService { return $this->connect->insertComment($poll_id, $name, $comment); } - function computeBestMoments($votes) { + function computeBestChoices($votes) { $result = []; foreach ($votes as $vote) { $choices = str_split($vote->reponses); diff --git a/studs.php b/studs.php index 7ff18a5..2fbcbf4 100644 --- a/studs.php +++ b/studs.php @@ -171,7 +171,7 @@ $smarty->assign('poll', $poll); $smarty->assign('title', _('Poll') . ' - ' . $poll->title); $smarty->assign('slots', $poll->format === 'D' ? $pollService->splitSlots($slots) : $slots); $smarty->assign('votes', $pollService->splitVotes($votes)); -$smarty->assign('best_moments', $pollService->computeBestMoments($votes)); +$smarty->assign('best_choices', $pollService->computeBestChoices($votes)); $smarty->assign('comments', $comments); $smarty->assign('editingVoteId', $editingVoteId); $smarty->assign('message', $message); diff --git a/tpl/part/vote_table_classic.tpl b/tpl/part/vote_table_classic.tpl index 7d7e703..961274d 100644 --- a/tpl/part/vote_table_classic.tpl +++ b/tpl/part/vote_table_classic.tpl @@ -1,5 +1,5 @@ -{if !is_array($best_moments) || empty($best_moments)} - {$best_moments = [0]} +{if !is_array($best_choices) || empty($best_choices)} + {$best_choices = [0]} {/if}

      {_('Votes of the poll')}

      @@ -138,12 +138,12 @@ {* Line displaying best moments *} {$count_bests = 0} - {$max = max($best_moments)} + {$max = max($best_choices)} {if $max > 0} {_("Addition")} - {foreach $best_moments as $best_moment} - {if $max == $best_moment} + {foreach $best_choices as $best_choice} + {if $max == $best_choice} {$count_bests = $count_bests +1} {$max} {else} @@ -159,7 +159,7 @@ {* Best votes listing *} -{$max = max($best_moments)} +{$max = max($best_choices)} {if $max > 0}
      {if $count_bests == 1} @@ -176,12 +176,10 @@ {$i = 0}
        {foreach $slots as $slot} - {foreach $slot->moments as $moment} - {if $best_moments[$i] == $max} -
      • {$slot->sujet}
      • - {/if} - {$i = $i+1} - {/foreach} + {if $best_choices[$i] == $max} +
      • {$slot->sujet}
      • + {/if} + {$i = $i+1} {/foreach}

      {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

      From 23ec39adb274e68b5e1a3b6bdde69db8416fa7e0 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 28 Dec 2014 23:43:47 +0100 Subject: [PATCH 073/151] Create PurgeService --- .../Framadate/Services/PurgeService.php | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 app/classes/Framadate/Services/PurgeService.php diff --git a/app/classes/Framadate/Services/PurgeService.php b/app/classes/Framadate/Services/PurgeService.php new file mode 100644 index 0000000..bf7d85b --- /dev/null +++ b/app/classes/Framadate/Services/PurgeService.php @@ -0,0 +1,40 @@ +connect = $connect; + } + + /** + * This methode purges all old polls (the ones with end_date in past). + * + * @return bool true is action succeeded + */ + function purgeOldPolls() { + // TODO Implements + return false; + } + + /** + * This methode delete all data about a poll. + * + * @param $poll_id int The ID of the poll + * @return bool true is action succeeded + */ + function purgePollById($poll_id) { + // TODO Implements + return false; + } + +} + \ No newline at end of file From 10c409e29ecae01238b7032631dbf41e53451370 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Mon, 29 Dec 2014 21:52:44 +0100 Subject: [PATCH 074/151] LogService: Change date format to "Ymd His" --- app/classes/Framadate/Services/LogService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/classes/Framadate/Services/LogService.php b/app/classes/Framadate/Services/LogService.php index 620ffa9..61c5e79 100644 --- a/app/classes/Framadate/Services/LogService.php +++ b/app/classes/Framadate/Services/LogService.php @@ -21,7 +21,7 @@ class LogService { * @param $message string some message */ function log($tag, $message) { - error_log(date('H:i:s d/m/Y:') . '[' . $tag . '] ' . $message . "\n", 3, $this->output); + error_log(date('Ymd His') . ' [' . $tag . '] ' . $message . "\n", 3, $this->output); } } From dcb711dcccbe97d727a5bd62871baab77569f69e Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Mon, 29 Dec 2014 21:54:07 +0100 Subject: [PATCH 075/151] Implements purge methods --- app/classes/Framadate/FramaDB.php | 32 +++++++++++++++++-- .../Framadate/Services/AdminPollService.php | 11 ++++--- .../Framadate/Services/PollService.php | 3 +- .../Framadate/Services/PurgeService.php | 31 +++++++++++++++--- choix_autre.php | 5 +-- choix_date.php | 5 +-- 6 files changed, 69 insertions(+), 18 deletions(-) diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index b6864ab..2982cb9 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -33,6 +33,7 @@ class FramaDB { function areTablesCreated() { $result = $this->pdo->query('SHOW TABLES'); $schemas = $result->fetchAll(\PDO::FETCH_COLUMN); + return 0 != count(array_diff($schemas, ['comments', 'sondage', 'sujet_studs', 'user_studs'])); } @@ -83,23 +84,27 @@ class FramaDB { function allCommentsByPollId($poll_id) { $prepared = $this->prepare('SELECT * FROM comments WHERE id_sondage = ? ORDER BY id_comment'); $prepared->execute(array($poll_id)); + return $prepared->fetchAll(); } function allUserVotesByPollId($poll_id) { $prepared = $this->prepare('SELECT * FROM user_studs WHERE id_sondage = ? ORDER BY id_users'); $prepared->execute(array($poll_id)); + return $prepared->fetchAll(); } function allSlotsByPollId($poll_id) { $prepared = $this->prepare('SELECT * FROM sujet_studs WHERE id_sondage = ? ORDER BY sujet'); $prepared->execute(array($poll_id)); + return $prepared->fetchAll(); } function insertDefaultVote($poll_id, $insert_position) { $prepared = $this->prepare('UPDATE user_studs SET reponses = CONCAT(SUBSTRING(reponses, 1, ?), "0", SUBSTRING(reponses, ?)) WHERE id_sondage = ?'); + return $prepared->execute([$insert_position, $insert_position + 1, $poll_id]); } @@ -118,6 +123,7 @@ class FramaDB { function deleteVote($poll_id, $vote_id) { $prepared = $this->prepare('DELETE FROM user_studs WHERE id_sondage = ? AND id_users = ?'); + return $prepared->execute([$poll_id, $vote_id]); } @@ -129,6 +135,7 @@ class FramaDB { */ function deleteVotesByPollId($poll_id) { $prepared = $this->prepare('DELETE FROM user_studs WHERE id_sondage = ?'); + return $prepared->execute([$poll_id]); } @@ -141,6 +148,7 @@ class FramaDB { */ function deleteVotesByIndex($poll_id, $index) { $prepared = $this->prepare('UPDATE user_studs SET reponses = CONCAT(SUBSTR(reponses, 1, ?), SUBSTR(reponses, ?)) WHERE id_sondage = ?'); + return $prepared->execute([$index, $index + 2, $poll_id]); } @@ -170,6 +178,7 @@ class FramaDB { */ function insertSlot($poll_id, $slot) { $prepared = $this->prepare('INSERT INTO sujet_studs (id_sondage, sujet) VALUES (?,?)'); + return $prepared->execute([$poll_id, $slot]); } @@ -183,6 +192,7 @@ class FramaDB { */ function updateSlot($poll_id, $datetime, $newValue) { $prepared = $this->prepare('UPDATE sujet_studs SET sujet = ? WHERE id_sondage = ? AND SUBSTRING_INDEX(sujet, \'@\', 1) = ?'); + return $prepared->execute([$newValue, $poll_id, $datetime]); } @@ -199,7 +209,7 @@ class FramaDB { function deleteSlotsByPollId($poll_id) { $prepared = $this->prepare('DELETE FROM sujet_studs WHERE id_sondage = ?'); - $prepared->execute([$poll_id]); + return $prepared->execute([$poll_id]); } /** @@ -210,27 +220,43 @@ class FramaDB { */ function deleteCommentsByPollId($poll_id) { $prepared = $this->prepare('DELETE FROM comments WHERE id_sondage = ?'); + return $prepared->execute([$poll_id]); } function updateVote($poll_id, $vote_id, $choices) { $prepared = $this->prepare('UPDATE user_studs SET reponses = ? WHERE id_sondage = ? AND id_users = ?'); + return $prepared->execute([$choices, $poll_id, $vote_id]); } function insertComment($poll_id, $name, $comment) { $prepared = $this->prepare('INSERT INTO comments (id_sondage, usercomment, comment) VALUES (?,?,?)'); + return $prepared->execute([$poll_id, $name, $comment]); } function deleteComment($poll_id, $comment_id) { $prepared = $this->prepare('DELETE FROM comments WHERE id_sondage = ? AND id_comment = ?'); + return $prepared->execute([$poll_id, $comment_id]); } - function deleteByPollId($poll_id) { + function deletePollById($poll_id) { $prepared = $this->prepare('DELETE FROM sondage WHERE poll_id = ?'); - $prepared->execute([$poll_id]); + return $prepared->execute([$poll_id]); + } + + /** + * Find old polls. Limit: 20. + * + * @return array Array of old polls + */ + public function findOldPolls() { + $prepared = $this->prepare('SELECT * FROM sondage WHERE end_date < NOW() LIMIT 20'); + $prepared->execute([]); + + return $prepared->fetchAll(); } } diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php index 4445ef6..b8c7fec 100644 --- a/app/classes/Framadate/Services/AdminPollService.php +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -1,6 +1,7 @@ connect = $connect; $this->pollService = $pollService; $this->logService = $logService; @@ -64,7 +65,7 @@ class AdminPollService { * @return bool|null true is action succeeded */ function cleanVotes($poll_id) { - $this->logService->log("CLEAN_VOTES", "id:$poll_id"); + $this->logService->log('CLEAN_VOTES', 'id:' . $poll_id); return $this->connect->deleteVotesByPollId($poll_id); } @@ -76,13 +77,13 @@ class AdminPollService { */ function deleteEntirePoll($poll_id) { $poll = $this->connect->findPollById($poll_id); - $this->logService->log("DELETE_POLL", "id:$poll->poll_id, format:$poll->format, admin:$poll->admin_name, mail:$poll->admin_mail"); + $this->logService->log('DELETE_POLL', "id:$poll->poll_id, format:$poll->format, admin:$poll->admin_name, mail:$poll->admin_mail"); // Delete the entire poll $this->connect->deleteVotesByPollId($poll_id); $this->connect->deleteCommentsByPollId($poll_id); $this->connect->deleteSlotsByPollId($poll_id); - $this->connect->deleteByPollId($poll_id); + $this->connect->deletePollById($poll_id); return true; } @@ -95,7 +96,7 @@ class AdminPollService { * @return bool true if action succeeded */ public function deleteSlot($poll_id, $slot) { - $this->logService->log("DELETE_SLOT", "id:$poll_id, slot:" . json_encode($slot)); + $this->logService->log('DELETE_SLOT', 'id:' . $poll_id . ', slot:' . json_encode($slot)); $ex = explode('@', $slot); $datetime = $ex[0]; $moment = $ex[1]; diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 47407f3..8ac6fff 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -133,6 +133,7 @@ class PollService { // Insert poll + slots $this->connect->beginTransaction(); + // TODO Extract this to FramaDB (or repository layer) $sql = 'INSERT INTO sondage (poll_id, admin_poll_id, title, comment, admin_name, admin_mail, end_date, format, editable, receiveNewVotes) VALUES (?,?,?,?,?,?,FROM_UNIXTIME(?),?,?,?)'; @@ -166,7 +167,7 @@ class PollService { $this->connect->commit(); - $this->logService->log('CREATE_POLL', ' id:' . $poll_id . ', format:' . $form->format . ', admin:' . $form->admin_name . ', mail:' . $form->admin_mail); + $this->logService->log('CREATE_POLL', 'id:' . $poll_id . 'title: ' . $form->title . ', format:' . $form->format . ', admin:' . $form->admin_name . ', mail:' . $form->admin_mail); return [$poll_id, $admin_poll_id]; diff --git a/app/classes/Framadate/Services/PurgeService.php b/app/classes/Framadate/Services/PurgeService.php index bf7d85b..f1d73d8 100644 --- a/app/classes/Framadate/Services/PurgeService.php +++ b/app/classes/Framadate/Services/PurgeService.php @@ -3,16 +3,18 @@ namespace Framadate\Services; use Framadate\FramaDB; /** - * This service helps to purge old poll. + * This service helps to purge data. * * @package Framadate\Services */ class PurgeService { private $connect; + private $logService; - function __construct(FramaDB $connect) { + function __construct(FramaDB $connect, LogService $logService) { $this->connect = $connect; + $this->logService = $logService; } /** @@ -21,7 +23,21 @@ class PurgeService { * @return bool true is action succeeded */ function purgeOldPolls() { - // TODO Implements + $oldPolls = $this->connect->findOldPolls(); + $count = count($oldPolls); + + if ($count > 0) { + $this->logService->log('EXPIRATION', 'Going to purge ' . $count . ' poll(s)...'); + + foreach ($oldPolls as $poll) { + if ($this->purgePollById($poll->poll_id)) { + $this->logService->log('EXPIRATION_SUCCESS', 'id: ' . $poll->poll_id . ', title:' . $poll->title . ', format: '.$poll->format . ', admin: ' . $poll->admin_name); + } else { + $this->logService->log('EXPIRATION_FAILED', 'id: ' . $poll->poll_id . ', title:' . $poll->title . ', format: '.$poll->format . ', admin: ' . $poll->admin_name); + } + } + } + return false; } @@ -32,8 +48,13 @@ class PurgeService { * @return bool true is action succeeded */ function purgePollById($poll_id) { - // TODO Implements - return false; + $done = false; + $done |= $this->connect->deleteCommentsByPollId($poll_id); + $done |= $this->connect->deleteVotesByPollId($poll_id); + $done |= $this->connect->deleteSlotsByPollId($poll_id); + $done |= $this->connect->deletePollById($poll_id); + + return $done; } } diff --git a/choix_autre.php b/choix_autre.php index d66c264..da3c4bc 100644 --- a/choix_autre.php +++ b/choix_autre.php @@ -19,6 +19,7 @@ use Framadate\Services\LogService; use Framadate\Services\PollService; use Framadate\Services\MailService; +use Framadate\Services\PurgeService; use Framadate\Utils; use Framadate\Choice; @@ -29,6 +30,7 @@ include_once __DIR__ . '/app/inc/init.php'; $logService = new LogService(LOG_FILE); $pollService = new PollService($connect, $logService); $mailService = new MailService($config['use_smtp']); +$purgeService = new PurgeService($connect, $logService); if (file_exists('bandeaux_local.php')) { include_once('bandeaux_local.php'); @@ -95,8 +97,7 @@ if (empty($_SESSION['form']->title) || empty($_SESSION['form']->admin_name) || ( unset($_SESSION['form']); // Delete old polls - // TODO Create a PurgeService - Utils::cleaningOldPolls($connect, 'admin/logs_studs.txt'); + $purgeService->purgeOldPolls(); // Redirect to poll administration header('Location:' . Utils::getUrlSondage($admin_poll_id, true)); diff --git a/choix_date.php b/choix_date.php index 5a28339..623f5a5 100644 --- a/choix_date.php +++ b/choix_date.php @@ -19,6 +19,7 @@ use Framadate\Services\LogService; use Framadate\Services\PollService; use Framadate\Services\MailService; +use Framadate\Services\PurgeService; use Framadate\Utils; use Framadate\Choice; @@ -29,6 +30,7 @@ include_once __DIR__ . '/app/inc/init.php'; $logService = new LogService(LOG_FILE); $pollService = new PollService($connect, $logService); $mailService = new MailService($config['use_smtp']); +$purgeService = new PurgeService($connect, $logService); if (is_readable('bandeaux_local.php')) { include_once('bandeaux_local.php'); @@ -103,8 +105,7 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || unset($_SESSION['form']); // Delete old polls - // TODO Create a PurgeService - Utils::cleaningOldPolls($connect, 'admin/logs_studs.txt'); + $purgeService->purgeOldPolls(); // Redirect to poll administration header('Location:' . Utils::getUrlSondage($admin_poll_id, true)); From 1ca7502216784791a706b84e33d645e78ea9e22d Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 30 Dec 2014 01:41:25 +0100 Subject: [PATCH 076/151] Translate database names (table+columns) to English + Reorganize some columns --- adminstuds.php | 15 +- app/classes/Framadate/FramaDB.php | 69 ++++---- .../Framadate/Services/AdminPollService.php | 29 ++-- .../Framadate/Services/PollService.php | 25 ++- .../Framadate/Services/PurgeService.php | 24 ++- app/classes/Framadate/Utils.php | 53 ------- install.mysql.sql | 150 ++++++++++-------- studs.php | 4 +- tpl/add_slot.tpl | 37 +++-- tpl/part/comments.tpl | 4 +- tpl/part/vote_table_classic.tpl | 12 +- tpl/part/vote_table_date.tpl | 12 +- 12 files changed, 206 insertions(+), 228 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index d2ad6c5..812df0c 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -301,15 +301,24 @@ if (!empty($_POST['delete_column'])) { if (isset($_POST['add_slot'])) { $smarty->assign('poll_id', $poll_id); $smarty->assign('admin_poll_id', $admin_poll_id); + $smarty->assign('format', $poll->format); $smarty->assign('title', _('Poll') . ' - ' . $poll->title); $smarty->display('add_slot.tpl'); exit; } if (isset($_POST['confirm_add_slot'])) { - $newdate = filter_input(INPUT_POST, 'newdate', FILTER_DEFAULT); - $newmoment = filter_input(INPUT_POST, 'newmoment', FILTER_DEFAULT); + if ($poll->format === 'D') { + $newdate = filter_input(INPUT_POST, 'newdate', FILTER_DEFAULT); + $newmoment = filter_input(INPUT_POST, 'newmoment', FILTER_DEFAULT); - if ($adminPollService->addSlot($poll_id, $newdate, $newmoment)) { + $ex = explode('/', $newdate); + $result = $adminPollService->addSlot($poll_id, mktime(0, 0, 0, $ex[1], $ex[0], $ex[2]), $newmoment); + } else { + $newslot = filter_input(INPUT_POST, 'choice', FILTER_DEFAULT); + $result = $adminPollService->addSlot($poll_id,$newslot, null); + } + + if ($result) { $message = new Message('success', _('Column added.')); } else { $message = new Message('danger', _('Failed to add the column.')); diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 2982cb9..fe67833 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -34,7 +34,7 @@ class FramaDB { $result = $this->pdo->query('SHOW TABLES'); $schemas = $result->fetchAll(\PDO::FETCH_COLUMN); - return 0 != count(array_diff($schemas, ['comments', 'sondage', 'sujet_studs', 'user_studs'])); + return 0 != count(array_diff($schemas, ['comment', 'poll', 'slot', 'vote'])); } function prepare($sql) { @@ -66,7 +66,7 @@ class FramaDB { } function findPollById($poll_id) { - $prepared = $this->prepare('SELECT * FROM sondage WHERE sondage.poll_id = ?'); + $prepared = $this->prepare('SELECT * FROM poll WHERE id = ?'); $prepared->execute([$poll_id]); $poll = $prepared->fetch(); @@ -76,53 +76,53 @@ class FramaDB { } function updatePoll($poll) { - $prepared = $this->prepare('UPDATE sondage SET title=?, admin_mail=?, comment=?, active=?, editable=? WHERE poll_id = ?'); + $prepared = $this->prepare('UPDATE poll SET title=?, admin_mail=?, comment=?, active=?, editable=? WHERE id = ?'); - return $prepared->execute([$poll->title, $poll->admin_mail, $poll->comment, $poll->active, $poll->editable, $poll->poll_id]); + return $prepared->execute([$poll->title, $poll->admin_mail, $poll->comment, $poll->active, $poll->editable, $poll->id]); } function allCommentsByPollId($poll_id) { - $prepared = $this->prepare('SELECT * FROM comments WHERE id_sondage = ? ORDER BY id_comment'); + $prepared = $this->prepare('SELECT * FROM comment WHERE poll_id = ? ORDER BY id'); $prepared->execute(array($poll_id)); return $prepared->fetchAll(); } function allUserVotesByPollId($poll_id) { - $prepared = $this->prepare('SELECT * FROM user_studs WHERE id_sondage = ? ORDER BY id_users'); + $prepared = $this->prepare('SELECT * FROM vote WHERE poll_id = ? ORDER BY id'); $prepared->execute(array($poll_id)); return $prepared->fetchAll(); } function allSlotsByPollId($poll_id) { - $prepared = $this->prepare('SELECT * FROM sujet_studs WHERE id_sondage = ? ORDER BY sujet'); + $prepared = $this->prepare('SELECT * FROM slot WHERE poll_id = ? ORDER BY title'); $prepared->execute(array($poll_id)); return $prepared->fetchAll(); } function insertDefaultVote($poll_id, $insert_position) { - $prepared = $this->prepare('UPDATE user_studs SET reponses = CONCAT(SUBSTRING(reponses, 1, ?), "0", SUBSTRING(reponses, ?)) WHERE id_sondage = ?'); + $prepared = $this->prepare('UPDATE vote SET choices = CONCAT(SUBSTRING(choices, 1, ?), "0", SUBSTRING(choices, ?)) WHERE poll_id = ?'); return $prepared->execute([$insert_position, $insert_position + 1, $poll_id]); } function insertVote($poll_id, $name, $choices) { - $prepared = $this->prepare('INSERT INTO user_studs (id_sondage,nom,reponses) VALUES (?,?,?)'); + $prepared = $this->prepare('INSERT INTO vote (poll_id, name, choices) VALUES (?,?,?)'); $prepared->execute([$poll_id, $name, $choices]); $newVote = new \stdClass(); - $newVote->id_sondage = $poll_id; - $newVote->id_users = $this->pdo->lastInsertId(); - $newVote->nom = $name; - $newVote->reponse = $choices; + $newVote->poll_id = $poll_id; + $newVote->id = $this->pdo->lastInsertId(); + $newVote->name = $name; + $newVote->choices = $choices; return $newVote; } function deleteVote($poll_id, $vote_id) { - $prepared = $this->prepare('DELETE FROM user_studs WHERE id_sondage = ? AND id_users = ?'); + $prepared = $this->prepare('DELETE FROM vote WHERE poll_id = ? AND id = ?'); return $prepared->execute([$poll_id, $vote_id]); } @@ -134,7 +134,7 @@ class FramaDB { * @return bool|null true if action succeeded. */ function deleteVotesByPollId($poll_id) { - $prepared = $this->prepare('DELETE FROM user_studs WHERE id_sondage = ?'); + $prepared = $this->prepare('DELETE FROM vote WHERE poll_id = ?'); return $prepared->execute([$poll_id]); } @@ -147,7 +147,7 @@ class FramaDB { * @return bool|null true if action succeeded. */ function deleteVotesByIndex($poll_id, $index) { - $prepared = $this->prepare('UPDATE user_studs SET reponses = CONCAT(SUBSTR(reponses, 1, ?), SUBSTR(reponses, ?)) WHERE id_sondage = ?'); + $prepared = $this->prepare('UPDATE vote SET choices = CONCAT(SUBSTR(choices, 1, ?), SUBSTR(choices, ?)) WHERE poll_id = ?'); return $prepared->execute([$index, $index + 2, $poll_id]); } @@ -160,7 +160,7 @@ class FramaDB { * @return mixed Object The slot found, or null */ function findSlotByPollIdAndDatetime($poll_id, $datetime) { - $prepared = $this->prepare('SELECT * FROM sujet_studs WHERE id_sondage = ? AND SUBSTRING_INDEX(sujet, \'@\', 1) = ?'); + $prepared = $this->prepare('SELECT * FROM slot WHERE poll_id = ? AND SUBSTRING_INDEX(title, \'@\', 1) = ?'); $prepared->execute([$poll_id, $datetime]); $slot = $prepared->fetch(); @@ -173,13 +173,14 @@ class FramaDB { * Insert a new slot into a given poll. * * @param $poll_id int The ID of the poll - * @param $slot mixed The value of the slot + * @param $title mixed The title of the slot + * @param $moments mixed|null The moments joined with "," * @return bool true if action succeeded */ - function insertSlot($poll_id, $slot) { - $prepared = $this->prepare('INSERT INTO sujet_studs (id_sondage, sujet) VALUES (?,?)'); + function insertSlot($poll_id, $title, $moments) { + $prepared = $this->prepare('INSERT INTO slot (poll_id, title, moments) VALUES (?,?,?)'); - return $prepared->execute([$poll_id, $slot]); + return $prepared->execute([$poll_id, $title, $moments]); } /** @@ -187,13 +188,13 @@ class FramaDB { * * @param $poll_id int The ID of the poll * @param $datetime int The datetime of the slot to update - * @param $newValue mixed The new value of the entire slot + * @param $newMoments mixed The new moments * @return bool|null true if action succeeded. */ - function updateSlot($poll_id, $datetime, $newValue) { - $prepared = $this->prepare('UPDATE sujet_studs SET sujet = ? WHERE id_sondage = ? AND SUBSTRING_INDEX(sujet, \'@\', 1) = ?'); + function updateSlot($poll_id, $datetime, $newMoments) { + $prepared = $this->prepare('UPDATE slot SET moments = ? WHERE poll_id = ? AND title = ?'); - return $prepared->execute([$newValue, $poll_id, $datetime]); + return $prepared->execute([$newMoments, $poll_id, $datetime]); } /** @@ -203,12 +204,13 @@ class FramaDB { * @param $datetime mixed The datetime of the slot */ function deleteSlot($poll_id, $datetime) { - $prepared = $this->prepare('DELETE FROM sujet_studs WHERE id_sondage = ? AND SUBSTRING_INDEX(sujet, \'@\', 1) = ?'); + $prepared = $this->prepare('DELETE FROM slot WHERE poll_id = ? AND title = ?'); $prepared->execute([$poll_id, $datetime]); } function deleteSlotsByPollId($poll_id) { - $prepared = $this->prepare('DELETE FROM sujet_studs WHERE id_sondage = ?'); + $prepared = $this->prepare('DELETE FROM slot WHERE poll_id = ?'); + return $prepared->execute([$poll_id]); } @@ -219,31 +221,32 @@ class FramaDB { * @return bool|null true if action succeeded. */ function deleteCommentsByPollId($poll_id) { - $prepared = $this->prepare('DELETE FROM comments WHERE id_sondage = ?'); + $prepared = $this->prepare('DELETE FROM comment WHERE poll_id = ?'); return $prepared->execute([$poll_id]); } function updateVote($poll_id, $vote_id, $choices) { - $prepared = $this->prepare('UPDATE user_studs SET reponses = ? WHERE id_sondage = ? AND id_users = ?'); + $prepared = $this->prepare('UPDATE vote SET choices = ? WHERE poll_id = ? AND id = ?'); return $prepared->execute([$choices, $poll_id, $vote_id]); } function insertComment($poll_id, $name, $comment) { - $prepared = $this->prepare('INSERT INTO comments (id_sondage, usercomment, comment) VALUES (?,?,?)'); + $prepared = $this->prepare('INSERT INTO comment (poll_id, name, comment) VALUES (?,?,?)'); return $prepared->execute([$poll_id, $name, $comment]); } function deleteComment($poll_id, $comment_id) { - $prepared = $this->prepare('DELETE FROM comments WHERE id_sondage = ? AND id_comment = ?'); + $prepared = $this->prepare('DELETE FROM comment WHERE poll_id = ? AND id = ?'); return $prepared->execute([$poll_id, $comment_id]); } function deletePollById($poll_id) { - $prepared = $this->prepare('DELETE FROM sondage WHERE poll_id = ?'); + $prepared = $this->prepare('DELETE FROM poll WHERE id = ?'); + return $prepared->execute([$poll_id]); } @@ -253,7 +256,7 @@ class FramaDB { * @return array Array of old polls */ public function findOldPolls() { - $prepared = $this->prepare('SELECT * FROM sondage WHERE end_date < NOW() LIMIT 20'); + $prepared = $this->prepare('SELECT * FROM poll WHERE end_date < NOW() LIMIT 20'); $prepared->execute([]); return $prepared->fetchAll(); diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php index b8c7fec..48d2502 100644 --- a/app/classes/Framadate/Services/AdminPollService.php +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -77,7 +77,7 @@ class AdminPollService { */ function deleteEntirePoll($poll_id) { $poll = $this->connect->findPollById($poll_id); - $this->logService->log('DELETE_POLL', "id:$poll->poll_id, format:$poll->format, admin:$poll->admin_name, mail:$poll->admin_mail"); + $this->logService->log('DELETE_POLL', "id:$poll->id, format:$poll->format, admin:$poll->admin_name, mail:$poll->admin_mail"); // Delete the entire poll $this->connect->deleteVotesByPollId($poll_id); @@ -109,11 +109,10 @@ class AdminPollService { // Search the index of the slot to delete foreach ($slots as $aSlot) { - $ex = explode('@', $aSlot->sujet); - $moments = explode(',', $ex[1]); + $moments = explode(',', $aSlot->moments); foreach ($moments as $rowMoment) { - if ($datetime == $ex[0]) { + if ($datetime == $aSlot->title) { if ($moment == $rowMoment) { $indexToDelete = $index; } else { @@ -128,7 +127,7 @@ class AdminPollService { $this->connect->beginTransaction(); $this->connect->deleteVotesByIndex($poll_id, $indexToDelete); if (count($newMoments) > 0) { - $this->connect->updateSlot($poll_id, $datetime, $datetime . '@' . implode(',', $newMoments)); + $this->connect->updateSlot($poll_id, $datetime, implode(',', $newMoments)); } else { $this->connect->deleteSlot($poll_id, $datetime); } @@ -145,14 +144,11 @@ class AdminPollService { *
    * * @param $poll_id int The ID of the poll - * @param $new_date string The date (format: d/m/Y) + * @param $datetime int The datetime * @param $new_moment string The moment's name * @return bool true if added */ - public function addSlot($poll_id, $new_date, $new_moment) { - $ex = explode('/', $new_date); - $datetime = mktime(0, 0, 0, $ex[1], $ex[0], $ex[2]); - + public function addSlot($poll_id, $datetime, $new_moment) { $slots = $this->connect->allSlotsByPollId($poll_id); $result = $this->findInsertPosition($slots, $datetime, $new_moment); @@ -164,9 +160,7 @@ class AdminPollService { return false; } elseif ($result->slot != null) { $slot = $result->slot; - - $joined_moments = explode('@', $slot->sujet)[1]; - $moments = explode(',', $joined_moments); + $moments = explode(',', $slot->moments); // Check if moment already exists (maybe not necessary) if (in_array($new_moment, $moments)) { @@ -176,10 +170,10 @@ class AdminPollService { // Update found slot $moments[] = $new_moment; sort($moments); - $this->connect->updateSlot($poll_id, $datetime, $datetime . '@' . implode(',', $moments)); + $this->connect->updateSlot($poll_id, $datetime, implode(',', $moments)); } else { - $this->connect->insertSlot($poll_id, $datetime . '@' . $new_moment); + $this->connect->insertSlot($poll_id, $datetime, $new_moment); } $this->connect->insertDefaultVote($poll_id, $result->insert); @@ -209,9 +203,8 @@ class AdminPollService { $i = 0; foreach ($slots as $slot) { - $ex = explode('@', $slot->sujet); - $rowDatetime = $ex[0]; - $moments = explode(',', $ex[1]); + $rowDatetime = $slot->title; + $moments = explode(',', $slot->moments); if ($datetime == $rowDatetime) { $result->slot = $slot; diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 8ac6fff..163a8e9 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -78,7 +78,7 @@ class PollService { function computeBestChoices($votes) { $result = []; foreach ($votes as $vote) { - $choices = str_split($vote->reponses); + $choices = str_split($vote->choices); foreach ($choices as $i => $choice) { if (empty($result[$i])) { $result[$i] = 0; @@ -95,10 +95,9 @@ class PollService { function splitSlots($slots) { $splitted = array(); foreach ($slots as $slot) { - $ex = explode('@', $slot->sujet); $obj = new \stdClass(); - $obj->day = $ex[0]; - $obj->moments = explode(',', $ex[1]); + $obj->day = $slot->title; + $obj->moments = explode(',', $slot->moments); $splitted[] = $obj; } @@ -110,9 +109,9 @@ class PollService { $splitted = array(); foreach ($votes as $vote) { $obj = new \stdClass(); - $obj->id = $vote->id_users; - $obj->name = $vote->nom; - $obj->choices = str_split($vote->reponses); + $obj->id = $vote->id; + $obj->name = $vote->name; + $obj->choices = str_split($vote->choices); $splitted[] = $obj; } @@ -134,13 +133,13 @@ class PollService { $this->connect->beginTransaction(); // TODO Extract this to FramaDB (or repository layer) - $sql = 'INSERT INTO sondage - (poll_id, admin_poll_id, title, comment, admin_name, admin_mail, end_date, format, editable, receiveNewVotes) + $sql = 'INSERT INTO poll + (id, admin_id, title, description, admin_name, admin_mail, end_date, format, editable, receiveNewVotes) VALUES (?,?,?,?,?,?,FROM_UNIXTIME(?),?,?,?)'; $prepared = $this->connect->prepare($sql); $prepared->execute(array($poll_id, $admin_poll_id, $form->title, $form->description, $form->admin_name, $form->admin_mail, $form->end_date, $form->format, $form->editable, $form->receiveNewVotes)); - $prepared = $this->connect->prepare('INSERT INTO sujet_studs (id_sondage, sujet) VALUES (?, ?)'); + $prepared = $this->connect->prepare('INSERT INTO slot (poll_id, title, moments) VALUES (?, ?, ?)'); foreach ($form->getChoices() as $choice) { @@ -158,16 +157,16 @@ class PollService { // We execute the insertion if (empty($joinedSlots)) { - $prepared->execute(array($poll_id, $choice->getName())); + $prepared->execute(array($poll_id, $choice->getName(), null)); } else { - $prepared->execute(array($poll_id, $choice->getName() . '@' . $joinedSlots)); + $prepared->execute(array($poll_id, $choice->getName(), $joinedSlots)); } } $this->connect->commit(); - $this->logService->log('CREATE_POLL', 'id:' . $poll_id . 'title: ' . $form->title . ', format:' . $form->format . ', admin:' . $form->admin_name . ', mail:' . $form->admin_mail); + $this->logService->log('CREATE_POLL', 'id:' . $poll_id . ', title: ' . $form->title . ', format:' . $form->format . ', admin:' . $form->admin_name . ', mail:' . $form->admin_mail); return [$poll_id, $admin_poll_id]; diff --git a/app/classes/Framadate/Services/PurgeService.php b/app/classes/Framadate/Services/PurgeService.php index f1d73d8..c9fd7d3 100644 --- a/app/classes/Framadate/Services/PurgeService.php +++ b/app/classes/Framadate/Services/PurgeService.php @@ -30,10 +30,10 @@ class PurgeService { $this->logService->log('EXPIRATION', 'Going to purge ' . $count . ' poll(s)...'); foreach ($oldPolls as $poll) { - if ($this->purgePollById($poll->poll_id)) { - $this->logService->log('EXPIRATION_SUCCESS', 'id: ' . $poll->poll_id . ', title:' . $poll->title . ', format: '.$poll->format . ', admin: ' . $poll->admin_name); + if ($this->purgePollById($poll->id)) { + $this->logService->log('EXPIRATION_SUCCESS', 'id: ' . $poll->id . ', title:' . $poll->title . ', format: '.$poll->format . ', admin: ' . $poll->admin_name); } else { - $this->logService->log('EXPIRATION_FAILED', 'id: ' . $poll->poll_id . ', title:' . $poll->title . ', format: '.$poll->format . ', admin: ' . $poll->admin_name); + $this->logService->log('EXPIRATION_FAILED', 'id: ' . $poll->id . ', title:' . $poll->title . ', format: '.$poll->format . ', admin: ' . $poll->admin_name); } } } @@ -48,11 +48,19 @@ class PurgeService { * @return bool true is action succeeded */ function purgePollById($poll_id) { - $done = false; - $done |= $this->connect->deleteCommentsByPollId($poll_id); - $done |= $this->connect->deleteVotesByPollId($poll_id); - $done |= $this->connect->deleteSlotsByPollId($poll_id); - $done |= $this->connect->deletePollById($poll_id); + $done = true; + + $this->connect->beginTransaction(); + $done &= $this->connect->deleteCommentsByPollId($poll_id); + $done &= $this->connect->deleteVotesByPollId($poll_id); + $done &= $this->connect->deleteSlotsByPollId($poll_id); + $done &= $this->connect->deletePollById($poll_id); + + if ($done) { + $this->connect->commit(); + } else { + $this->connect->rollback(); + } return $done; } diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index a07719d..5efb9a0 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -98,59 +98,6 @@ class Utils return filter_var($email, FILTER_VALIDATE_EMAIL); } - /** - * Envoi un courrier avec un codage correct de To et Subject - * Les en-têtes complémentaires ne sont pas gérés - * @deprecated - */ - public static function sendEmail( $to, $subject, $body, $headers='', $param='') - { - - mb_internal_encoding('UTF-8'); - - $subject = mb_encode_mimeheader(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'), 'UTF-8', 'B', "\n", 9); - - $encoded_app = mb_encode_mimeheader(NOMAPPLICATION, 'UTF-8', 'B', "\n", 6); - $size_encoded_app = (6 + strlen($encoded_app)) % 75; - $size_admin_email = strlen(ADRESSEMAILADMIN); - - if (($size_encoded_app + $size_admin_email + 9) > 74 ) { - $folding = "\n"; - } else { - $folding = ''; - }; - - /* - Si $headers ne contient qu'une adresse email, on la considère comme - adresse de reply-to, sinon on met l'adresse de no-reply definie - dans constants.php - */ - if (self::isValidEmail($headers)) { - $replyTo = $headers; - $headers = ''; // on reinitialise $headers - } else { - $replyTo = ADRESSEMAILREPONSEAUTO; - } - - $from = sprintf( "From: %s%s <%s>\n", $encoded_app, $folding, ADRESSEMAILADMIN); - - if ($headers) { - $headers .= "\n" ; - } - - $headers .= $from; - $headers .= "Reply-To: $replyTo\n"; - $headers .= "MIME-Version: 1.0\n"; - $headers .= "Content-Type: text/plain; charset=UTF-8\n"; - $headers .= "Content-Transfer-Encoding: 8bit\n"; - $headers .= "Auto-Submitted:auto-generated\n"; - $headers .= "Return-Path: <>"; - - $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8')._("\n--\n\n« La route est longue, mais la voie est libre… »\nFramasoft ne vit que par vos dons (déductibles des impôts).\nMerci d'avance pour votre soutien http://soutenir.framasoft.org."); - - mail($to, $subject, $body, $headers, $param); - } - /** * Fonction permettant de générer les URL pour les sondage * @param string $id L'identifiant du sondage diff --git a/install.mysql.sql b/install.mysql.sql index 69b36b2..63a8a6d 100644 --- a/install.mysql.sql +++ b/install.mysql.sql @@ -1,103 +1,113 @@ --- Base de données: `opensondage` +-- -------------------------------------------------------- + -- +-- Table structure `poll` +-- + +CREATE TABLE IF NOT EXISTS `poll` ( + `id` CHAR(16) NOT NULL, + `admin_id` CHAR(24) NOT NULL, + `title` TEXT NOT NULL, + `description` TEXT, + `admin_name` VARCHAR(64) DEFAULT NULL, + `admin_mail` VARCHAR(128) DEFAULT NULL, + `creation_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + `end_date` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00', + `format` VARCHAR(1) DEFAULT NULL, + `editable` TINYINT(1) DEFAULT '0', + `receiveNewVotes` TINYINT(1) DEFAULT '0', + `active` TINYINT(1) DEFAULT '1', + PRIMARY KEY (`id`) +) + ENGINE =InnoDB + DEFAULT CHARSET =utf8; -- -------------------------------------------------------- -- --- Structure de la table `comments` +-- Table structure `slot` -- -CREATE TABLE IF NOT EXISTS `comments` ( - `id_comment` int(11) unsigned NOT NULL AUTO_INCREMENT, - `id_sondage` char(16) NOT NULL, - `comment` text NOT NULL, - `usercomment` text, - PRIMARY KEY (`id_comment`), - KEY `id_sondage` (`id_sondage`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE IF NOT EXISTS `slot` ( + `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `poll_id` CHAR(16) NOT NULL, + `title` TEXT, + `moments` TEXT, + PRIMARY KEY (`id`), + KEY `poll_id` (`poll_id`) +) + ENGINE =InnoDB + DEFAULT CHARSET =utf8; -- -------------------------------------------------------- -- --- Structure de la table `sondage` +-- Table structure `comment` -- -CREATE TABLE IF NOT EXISTS `sondage` ( - `poll_id` char(16) NOT NULL, - `admin_poll_id` char(24) DEFAULT NULL, - `title` text NOT NULL, - `comment` text, - `admin_name` varchar(64) DEFAULT NULL, - `admin_mail` varchar(128) DEFAULT NULL, - `creation_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `end_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', - `format` varchar(1) DEFAULT NULL, - `editable` tinyint(1) DEFAULT '0', - `receiveNewVotes` tinyint(1) DEFAULT '0', - `active` tinyint(1) DEFAULT '1', - `statut` int(11) NOT NULL DEFAULT '1' COMMENT '1 = actif ; 0 = inactif ; ', - UNIQUE KEY `poll_id` (`poll_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE IF NOT EXISTS `comment` ( + `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `poll_id` CHAR(16) NOT NULL, + `name` TEXT, + `comment` TEXT NOT NULL, + PRIMARY KEY (`id`), + KEY `poll_id` (`poll_id`) +) + ENGINE =InnoDB + DEFAULT CHARSET =utf8; -- -------------------------------------------------------- -- --- Structure de la table `sujet_studs` +-- Table structure `vote` -- -CREATE TABLE IF NOT EXISTS `sujet_studs` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `id_sondage` char(16) NOT NULL, - `sujet` text, - KEY `id_sondage` (`id_sondage`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE IF NOT EXISTS `vote` ( + `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `poll_id` CHAR(16) NOT NULL, + `name` VARCHAR(64) NOT NULL, + `choices` TEXT NOT NULL, + PRIMARY KEY (`id`), + KEY `poll_id` (`poll_id`) +) + ENGINE =InnoDB + DEFAULT CHARSET =utf8 + AUTO_INCREMENT =160284; --- -------------------------------------------------------- -- --- Structure de la table `user_studs` +-- Data for Name: poll; Type: TABLE DATA; -- -CREATE TABLE IF NOT EXISTS `user_studs` ( - `id_users` int(11) unsigned NOT NULL AUTO_INCREMENT, - `nom` varchar(64) NOT NULL, - `id_sondage` char(16) NOT NULL, - `reponses` text NOT NULL, - PRIMARY KEY (`id_users`), - KEY `id_sondage` (`id_sondage`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=160284 ; - - - -INSERT INTO `sondage` -(`id_sondage`, `commentaires`, `mail_admin`, `nom_admin`, - `titre`, `id_sondage_admin`, - `date_fin`, `format`) +INSERT INTO `poll` +(`id`, `description`, `admin_mail`, `admin_name`, `title`, `admin_id`, `end_date`, `format`) VALUES -('aqg259dth55iuhwm','Repas de Noel du service','Stephanie@retaillard.com','Stephanie', - 'Repas de Noel','aqg259dth55iuhwmy9d8jlwk', - FROM_UNIXTIME('1627100361'),'D+'); + ('aqg259dth55iuhwm', 'Repas de Noel du service', 'Stephanie@retaillard.com', 'Stephanie', 'Repas de Noel', + 'aqg259dth55iuhwmy9d8jlwk', FROM_UNIXTIME('1627100361'), 'D'); -- --- Data for Name: sujet_studs; Type: TABLE DATA; +-- Data for Name: slot; Type: TABLE DATA; -- -INSERT INTO `sujet_studs` (`id_sondage`, `sujet`) VALUES -('aqg259dth55iuhwm','1225839600@12h,1225839600@19h,1226012400@12h,1226012400@19h,1226876400@12h,1226876400@19h,1227049200@12h,1227049200@19h,1227826800@12h,1227826800@19h'); +INSERT INTO `slot` (`poll_id`, `title`, `moments`) VALUES + ('aqg259dth55iuhwm', '1225839600', '12h,19h'), + ('aqg259dth55iuhwm', '1226012400', '12h,19h'), + ('aqg259dth55iuhwm', '1226876400', '12h,19h'), + ('aqg259dth55iuhwm', '1227826800', '12h,19h'); -- --- Data for Name: user_studs; Type: TABLE DATA; +-- Data for Name: vote; Type: TABLE DATA; -- -INSERT INTO `user_studs` (`nom`, `id_sondage`, `reponses`, `id_users`) VALUES -('marcel','aqg259dth55iuhwm','0110111101','933'), -('paul','aqg259dth55iuhwm','1011010111','935'), -('sophie','aqg259dth55iuhwm','1110110000','945'), -('barack','aqg259dth55iuhwm','0110000','948'), -('takashi','aqg259dth55iuhwm','0000110100','951'), -('albert','aqg259dth55iuhwm','1010110','975'), -('alfred','aqg259dth55iuhwm','0110010','1135'), -('marcs','aqg259dth55iuhwm','0100001010','1143'), -('laure','aqg259dth55iuhwm','0011000','1347'), -('benda','aqg259dth55iuhwm','1101101100','1667'), -('Albert','aqg259dth55iuhwm','1111110011','1668'); +INSERT INTO `vote` (`name`, `poll_id`, `choices`) VALUES + ('marcel', 'aqg259dth55iuhwm', '02202222'), + ('paul', 'aqg259dth55iuhwm', '20220202'), + ('sophie', 'aqg259dth55iuhwm', '22202200'), + ('barack', 'aqg259dth55iuhwm', '02200000'), + ('takashi','aqg259dth55iuhwm', '00002202'), + ('albert', 'aqg259dth55iuhwm', '20202200'), + ('alfred', 'aqg259dth55iuhwm', '02200200'), + ('marcs', 'aqg259dth55iuhwm', '02000020'), + ('laure', 'aqg259dth55iuhwm', '00220000'), + ('benda', 'aqg259dth55iuhwm', '22022022'), + ('albert', 'aqg259dth55iuhwm', '22222200'); diff --git a/studs.php b/studs.php index 2fbcbf4..2bda857 100644 --- a/studs.php +++ b/studs.php @@ -50,7 +50,7 @@ $mailService = new MailService($config['use_smtp']); * @param $mailService MailService The mail service */ function sendUpdateNotification($poll, $mailService) { - if ($poll->receiveNewVotes && !isset($_SESSION['mail_sent'][$poll->poll_id])) { + if ($poll->receiveNewVotes && !isset($_SESSION['mail_sent'][$poll->id])) { $subject = '[' . NOMAPPLICATION . '] ' . _('Poll\'s participation') . ' : ' . html_entity_decode($poll->title, ENT_QUOTES, 'UTF-8'); $message = html_entity_decode('"$nom" ', ENT_QUOTES, 'UTF-8') . @@ -60,7 +60,7 @@ function sendUpdateNotification($poll, $mailService) { $mailService->send($poll->admin_mail, $subject, $message); - $_SESSION["mail_sent"][$poll->poll_id] = true; + $_SESSION["mail_sent"][$poll->id] = true; } } diff --git a/tpl/add_slot.tpl b/tpl/add_slot.tpl index 9837817..40e23a6 100644 --- a/tpl/add_slot.tpl +++ b/tpl/add_slot.tpl @@ -3,24 +3,33 @@ {block name=main}
    -

    {_("Column's adding")}

    +

    {_('Column\'s adding')}

    -
    - -
    -
    - - + {if $format === 'D'} +
    + +
    +
    + + +
    + {_('(dd/mm/yyyy)')}
    - {_("(dd/mm/yyyy)")}
    -
    -
    - -
    - +
    + +
    + +
    -
    + {else} +
    + +
    + +
    +
    + {/if}
    diff --git a/tpl/part/comments.tpl b/tpl/part/comments.tpl index a9bb572..2fccf61 100644 --- a/tpl/part/comments.tpl +++ b/tpl/part/comments.tpl @@ -8,9 +8,9 @@ {foreach $comments as $comment}
    {if $admin} - + {/if} - {$comment->usercomment}  + {$comment->name}  {nl2br($comment->comment)}
    {/foreach} diff --git a/tpl/part/vote_table_classic.tpl b/tpl/part/vote_table_classic.tpl index 961274d..3b7fac5 100644 --- a/tpl/part/vote_table_classic.tpl +++ b/tpl/part/vote_table_classic.tpl @@ -14,7 +14,7 @@ {foreach $slots as $id=>$slot} - + {/foreach} @@ -25,7 +25,7 @@ {foreach $slots as $id=>$slot} - {$slot->sujet} + {$slot->title} {/foreach} @@ -113,19 +113,19 @@
    • -
    • -
    • -
    • @@ -177,7 +177,7 @@
        {foreach $slots as $slot} {if $best_choices[$i] == $max} -
      • {$slot->sujet}
      • +
      • {$slot->title}
      • {/if} {$i = $i+1} {/foreach} diff --git a/tpl/part/vote_table_date.tpl b/tpl/part/vote_table_date.tpl index daf8d40..5faacaa 100644 --- a/tpl/part/vote_table_date.tpl +++ b/tpl/part/vote_table_date.tpl @@ -1,5 +1,5 @@ -{if !is_array($best_moments) || empty($best_moments)} - {$best_moments = [0]} +{if !is_array($best_choices) || empty($best_choices)} + {$best_choices = [0]} {/if}

        {_('Votes of the poll')}

        @@ -168,11 +168,11 @@ {* Line displaying best moments *} {$count_bests = 0} - {$max = max($best_moments)} + {$max = max($best_choices)} {if $max > 0} {_("Addition")} - {foreach $best_moments as $best_moment} + {foreach $best_choices as $best_moment} {if $max == $best_moment} {$count_bests = $count_bests +1} {$max} @@ -189,7 +189,7 @@ {* Best votes listing *} -{$max = max($best_moments)} +{$max = max($best_choices)} {if $max > 0}
        {if $count_bests == 1} @@ -207,7 +207,7 @@
          {foreach $slots as $slot} {foreach $slot->moments as $moment} - {if $best_moments[$i] == $max} + {if $best_choices[$i] == $max}
        • {$slot->day|date_format:$date_format.txt_full} - {$moment}
        • {/if} {$i = $i+1} From f399b9e543840881fc5daf8ff01017b2ae117784 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 30 Dec 2014 17:03:43 +0100 Subject: [PATCH 077/151] admin: fix deleteion a slot from a classical poll --- adminstuds.php | 14 +++++++- .../Framadate/Services/AdminPollService.php | 35 ++++++++++++++++--- tpl/part/vote_table_classic.tpl | 2 +- 3 files changed, 44 insertions(+), 7 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index 812df0c..cc8aefd 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -287,7 +287,19 @@ if (isset($_POST['confirm_delete_poll'])) { if (!empty($_POST['delete_column'])) { $column = filter_input(INPUT_POST, 'delete_column', FILTER_DEFAULT); - if ($adminPollService->deleteSlot($poll_id, $column)) { + if ($poll->format === 'D') { + $ex = explode('@', $column); + + $slot = new stdClass(); + $slot->title = $ex[0]; + $slot->moment = $ex[1]; + + $result = $adminPollService->deleteDateSlot($poll_id, $slot); + } else { + $result = $adminPollService->deleteClassicSlot($poll_id, $column); + } + + if ($result) { $message = new Message('success', _('Column deleted.')); } else { $message = new Message('danger', _('Failed to delete the column.')); diff --git a/app/classes/Framadate/Services/AdminPollService.php b/app/classes/Framadate/Services/AdminPollService.php index 48d2502..3926362 100644 --- a/app/classes/Framadate/Services/AdminPollService.php +++ b/app/classes/Framadate/Services/AdminPollService.php @@ -92,14 +92,14 @@ class AdminPollService { * Delete a slot from a poll. * * @param $poll_id int The ID of the poll - * @param $slot string The name of the slot + * @param $slot object The slot informations (datetime + moment) * @return bool true if action succeeded */ - public function deleteSlot($poll_id, $slot) { + public function deleteDateSlot($poll_id, $slot) { $this->logService->log('DELETE_SLOT', 'id:' . $poll_id . ', slot:' . json_encode($slot)); - $ex = explode('@', $slot); - $datetime = $ex[0]; - $moment = $ex[1]; + + $datetime = $slot->title; + $moment = $slot->moment; $slots = $this->pollService->allSlotsByPollId($poll_id); @@ -136,6 +136,31 @@ class AdminPollService { return true; } + public function deleteClassicSlot($poll_id, $slot_title) { + $this->logService->log('DELETE_SLOT', 'id:' . $poll_id . ', slot:' . $slot_title); + + $slots = $this->pollService->allSlotsByPollId($poll_id); + + $index = 0; + $indexToDelete = -1; + + // Search the index of the slot to delete + foreach ($slots as $aSlot) { + if ($slot_title == $aSlot->title) { + $indexToDelete = $index; + } + $index++; + } + + // Remove votes + $this->connect->beginTransaction(); + $this->connect->deleteVotesByIndex($poll_id, $indexToDelete); + $this->connect->deleteSlot($poll_id, $slot_title); + $this->connect->commit(); + + return true; + } + /** * Add a new slot to the poll. And insert default values for user's votes. *
            diff --git a/tpl/part/vote_table_classic.tpl b/tpl/part/vote_table_classic.tpl index 3b7fac5..ecddafb 100644 --- a/tpl/part/vote_table_classic.tpl +++ b/tpl/part/vote_table_classic.tpl @@ -14,7 +14,7 @@ {foreach $slots as $id=>$slot} - + {/foreach} From d37200addd713c92ff7835f91d6da2fb5ff3be93 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 30 Dec 2014 18:15:04 +0100 Subject: [PATCH 078/151] Change version number to 0.9 --- app/inc/constants.php.template | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/inc/constants.php.template b/app/inc/constants.php.template index af7f289..d7b58bc 100644 --- a/app/inc/constants.php.template +++ b/app/inc/constants.php.template @@ -18,7 +18,7 @@ */ // FRAMADATE version -const VERSION = 0.8; +const VERSION = 0.9; // Server name const STUDS_URL = ''; From ca00c4953cd8c459b276a956d2a3a7e083a79d4f Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 30 Dec 2014 18:15:29 +0100 Subject: [PATCH 079/151] migration: Create a script to migrate database from 0.8 to 0.9 --- from_0-8_to_0-9.sql | 136 ++++++++++++++++++++++++++++++++++++++++++++ install.mysql.sql | 27 +++++---- 2 files changed, 149 insertions(+), 14 deletions(-) create mode 100644 from_0-8_to_0-9.sql diff --git a/from_0-8_to_0-9.sql b/from_0-8_to_0-9.sql new file mode 100644 index 0000000..2b2ae23 --- /dev/null +++ b/from_0-8_to_0-9.sql @@ -0,0 +1,136 @@ +-- -------------------------------------------------------- + +-- +-- Table structure `poll` +-- + +CREATE TABLE IF NOT EXISTS `poll` ( + `id` CHAR(16) NOT NULL, + `admin_id` CHAR(24) NOT NULL, + `title` TEXT NOT NULL, + `description` TEXT, + `admin_name` VARCHAR(64) DEFAULT NULL, + `admin_mail` VARCHAR(128) DEFAULT NULL, + `creation_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + `end_date` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00', + `format` VARCHAR(1) DEFAULT NULL, + `editable` TINYINT(1) DEFAULT '0', + `receiveNewVotes` TINYINT(1) DEFAULT '0', + `active` TINYINT(1) DEFAULT '1', + PRIMARY KEY (`id`) +) + ENGINE = InnoDB + DEFAULT CHARSET = utf8; + +-- -------------------------------------------------------- + +-- +-- Table structure `slot` +-- + +CREATE TABLE IF NOT EXISTS `slot` ( + `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `poll_id` CHAR(16) NOT NULL, + `title` TEXT, + `moments` TEXT, + PRIMARY KEY (`id`), + KEY `poll_id` (`poll_id`) +) + ENGINE = InnoDB + DEFAULT CHARSET = utf8; + +-- -------------------------------------------------------- + +-- +-- Table structure `comment` +-- + +CREATE TABLE IF NOT EXISTS `comment` ( + `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `poll_id` CHAR(16) NOT NULL, + `name` TEXT, + `comment` TEXT NOT NULL, + PRIMARY KEY (`id`), + KEY `poll_id` (`poll_id`) +) + ENGINE = InnoDB + DEFAULT CHARSET = utf8; + +-- -------------------------------------------------------- + +-- +-- Table structure `vote` +-- + +CREATE TABLE IF NOT EXISTS `vote` ( + `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `poll_id` CHAR(16) NOT NULL, + `name` VARCHAR(64) NOT NULL, + `choices` TEXT NOT NULL, + PRIMARY KEY (`id`), + KEY `poll_id` (`poll_id`) +) + ENGINE = InnoDB + DEFAULT CHARSET = utf8; + +-- -------------------------------------------------------- + +-- +-- Migrate data from `sondage` to `poll` +-- + +INSERT INTO `poll` +(`id`, `admin_id`, `title`, `description`, `admin_name`, `admin_mail`, `creation_date`, `end_date`, `format`, `editable`, `receiveNewVotes`, `active`) + SELECT + `id_sondage`, + `id_sondage_admin`, + `titre`, + `commentaires`, + `nom_admin`, + `mail_admin`, + `titre`, + `date_creation`, + `date_fin`, + SUBSTR(`format`, 1, 1) AS `format`, + CASE SUBSTR(`format`, 2, 1) + WHEN '+' THEN 1 + ELSE 0 END AS `editable`, + `mailsonde`, + CASE SUBSTR(`format`, 2, 1) + WHEN '-' THEN 0 + ELSE 1 END AS `active` + FROM sondage; + +-- -------------------------------------------------------- + +-- +-- Migrate data from `sujet_studs` to `slot` +-- + +-- TODO Migrate this, is not so simple +/*INSERT INTO `slot` +(`poll_id`, `title`, `moments`) + SELECT `id_sondage`, + FROM `user_studs`;*/ + +-- -------------------------------------------------------- + +-- +-- Migrate data from `comments` to `comment` +-- + +INSERT INTO `comment` +(`poll_id`, `name`, `comment`) + SELECT `id_sondage`, `usercomment`, `comment` + FROM `comments`; + +-- -------------------------------------------------------- + +-- +-- Migrate data from `user_studs` to `vote` +-- + +INSERT INTO `vote` +(`poll_id`, `name`, `choices`) + SELECT `id_sondage`, `nom`, REPLACE(REPLACE(REPLACE(`reponses`, '1', 'X'), '2', '1'), 'X', 2) + FROM `user_studs`; diff --git a/install.mysql.sql b/install.mysql.sql index 63a8a6d..aa0354c 100644 --- a/install.mysql.sql +++ b/install.mysql.sql @@ -19,8 +19,8 @@ CREATE TABLE IF NOT EXISTS `poll` ( `active` TINYINT(1) DEFAULT '1', PRIMARY KEY (`id`) ) - ENGINE =InnoDB - DEFAULT CHARSET =utf8; + ENGINE = InnoDB + DEFAULT CHARSET = utf8; -- -------------------------------------------------------- @@ -36,8 +36,8 @@ CREATE TABLE IF NOT EXISTS `slot` ( PRIMARY KEY (`id`), KEY `poll_id` (`poll_id`) ) - ENGINE =InnoDB - DEFAULT CHARSET =utf8; + ENGINE = InnoDB + DEFAULT CHARSET = utf8; -- -------------------------------------------------------- @@ -53,8 +53,8 @@ CREATE TABLE IF NOT EXISTS `comment` ( PRIMARY KEY (`id`), KEY `poll_id` (`poll_id`) ) - ENGINE =InnoDB - DEFAULT CHARSET =utf8; + ENGINE = InnoDB + DEFAULT CHARSET = utf8; -- -------------------------------------------------------- @@ -70,9 +70,8 @@ CREATE TABLE IF NOT EXISTS `vote` ( PRIMARY KEY (`id`), KEY `poll_id` (`poll_id`) ) - ENGINE =InnoDB - DEFAULT CHARSET =utf8 - AUTO_INCREMENT =160284; + ENGINE = InnoDB + DEFAULT CHARSET = utf8; -- @@ -101,13 +100,13 @@ INSERT INTO `slot` (`poll_id`, `title`, `moments`) VALUES INSERT INTO `vote` (`name`, `poll_id`, `choices`) VALUES ('marcel', 'aqg259dth55iuhwm', '02202222'), - ('paul', 'aqg259dth55iuhwm', '20220202'), + ('paul', 'aqg259dth55iuhwm', '20220202'), ('sophie', 'aqg259dth55iuhwm', '22202200'), ('barack', 'aqg259dth55iuhwm', '02200000'), - ('takashi','aqg259dth55iuhwm', '00002202'), + ('takashi', 'aqg259dth55iuhwm', '00002202'), ('albert', 'aqg259dth55iuhwm', '20202200'), ('alfred', 'aqg259dth55iuhwm', '02200200'), - ('marcs', 'aqg259dth55iuhwm', '02000020'), - ('laure', 'aqg259dth55iuhwm', '00220000'), - ('benda', 'aqg259dth55iuhwm', '22022022'), + ('marcs', 'aqg259dth55iuhwm', '02000020'), + ('laure', 'aqg259dth55iuhwm', '00220000'), + ('benda', 'aqg259dth55iuhwm', '22022022'), ('albert', 'aqg259dth55iuhwm', '22222200'); From 88cae82e715e4a84ccf8bb0b10922346922d89dc Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 31 Dec 2014 01:33:56 +0100 Subject: [PATCH 080/151] Create a migration system to migrate database. + Use this system to migrate from 0.8 to 0.9 (WIP) --- app/classes/Framadate/FramaDB.php | 16 +- .../Migration/From_0_8_to_0_9_Migration.php | 144 ++++++++++++++++++ app/classes/Framadate/Migration/Migration.php | 15 ++ app/inc/constants.php.template | 3 + bandeaux.php | 4 +- from_0-8_to_0-9.sql | 136 ----------------- migration.php | 60 ++++++++ 7 files changed, 239 insertions(+), 139 deletions(-) create mode 100644 app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php create mode 100644 app/classes/Framadate/Migration/Migration.php delete mode 100644 from_0-8_to_0-9.sql create mode 100644 migration.php diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index fe67833..b93ea09 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -30,11 +30,23 @@ class FramaDB { $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); } - function areTablesCreated() { + /** + * @return \PDO Connection to database + */ + function getPDO() { + return $this->pdo; + } + + /** + * Find all tables in database. + * + * @return array The array of table names + */ + function allTables() { $result = $this->pdo->query('SHOW TABLES'); $schemas = $result->fetchAll(\PDO::FETCH_COLUMN); - return 0 != count(array_diff($schemas, ['comment', 'poll', 'slot', 'vote'])); + return $schemas; } function prepare($sql) { diff --git a/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php b/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php new file mode 100644 index 0000000..5e0d452 --- /dev/null +++ b/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php @@ -0,0 +1,144 @@ +createPollTable($pdo); + $this->migrateFromSondageToPoll($pdo); + + $this->createSlotTable($pdo); + $this->migrateFromSujetStudsToSlot($pdo); + + $this->createCommentTable($pdo); + $this->migrateFromCommentsToComment($pdo); + + $this->createVoteTable($pdo); + $this->migrateFromUserStudsToVote($pdo); + + return true; + } + + private function createPollTable(\PDO $pdo) { + $pdo->exec(' +CREATE TABLE IF NOT EXISTS `poll` ( + `id` CHAR(16) NOT NULL, + `admin_id` CHAR(24) NOT NULL, + `title` TEXT NOT NULL, + `description` TEXT, + `admin_name` VARCHAR(64) DEFAULT NULL, + `admin_mail` VARCHAR(128) DEFAULT NULL, + `creation_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + `end_date` TIMESTAMP NOT NULL DEFAULT \'0000-00-00 00:00:00\', + `format` VARCHAR(1) DEFAULT NULL, + `editable` TINYINT(1) DEFAULT \'0\', + `receiveNewVotes` TINYINT(1) DEFAULT \'0\', + `active` TINYINT(1) DEFAULT \'1\', + PRIMARY KEY (`id`) +) + ENGINE = InnoDB + DEFAULT CHARSET = utf8'); + } + + private function migrateFromSondageToPoll(\PDO $pdo) { + $pdo->exec(' +INSERT INTO `poll` +(`id`, `admin_id`, `title`, `description`, `admin_name`, `admin_mail`, `creation_date`, `end_date`, `format`, `editable`, `receiveNewVotes`, `active`) + SELECT + `id_sondage`, + `id_sondage_admin`, + `titre`, + `commentaires`, + `nom_admin`, + `mail_admin`, + `date_creation`, + `date_fin`, + SUBSTR(`format`, 1, 1) AS `format`, + CASE SUBSTR(`format`, 2, 1) + WHEN \'+\' THEN 1 + ELSE 0 END AS `editable`, + `mailsonde`, + CASE SUBSTR(`format`, 2, 1) + WHEN \'-\' THEN 0 + ELSE 1 END AS `active` + FROM sondage'); + } + + private function createSlotTable(\PDO $pdo) { + $pdo->exec(' +CREATE TABLE IF NOT EXISTS `slot` ( + `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `poll_id` CHAR(16) NOT NULL, + `title` TEXT, + `moments` TEXT, + PRIMARY KEY (`id`), + KEY `poll_id` (`poll_id`) +) + ENGINE = InnoDB + DEFAULT CHARSET = utf8'); + } + + private function migrateFromSujetStudsToSlot(\PDO $pdo) { + // TODO Implements + } + + private function createCommentTable(\PDO $pdo) { + $pdo->exec(' +CREATE TABLE IF NOT EXISTS `comment` ( + `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `poll_id` CHAR(16) NOT NULL, + `name` TEXT, + `comment` TEXT NOT NULL, + PRIMARY KEY (`id`), + KEY `poll_id` (`poll_id`) +) + ENGINE = InnoDB + DEFAULT CHARSET = utf8'); + } + + private function migrateFromCommentsToComment(\PDO $pdo) { + $pdo->exec(' +INSERT INTO `comment` +(`poll_id`, `name`, `comment`) + SELECT + `id_sondage`, + `usercomment`, + `comment` + FROM `comments`'); + } + + private function createVoteTable(\PDO $pdo) { + $pdo->exec(' +CREATE TABLE IF NOT EXISTS `vote` ( + `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `poll_id` CHAR(16) NOT NULL, + `name` VARCHAR(64) NOT NULL, + `choices` TEXT NOT NULL, + PRIMARY KEY (`id`), + KEY `poll_id` (`poll_id`) +) + ENGINE = InnoDB + DEFAULT CHARSET = utf8'); + } + + private function migrateFromUserStudsToVote(\PDO $pdo) { + $pdo->exec(' +INSERT INTO `vote` +(`poll_id`, `name`, `choices`) + SELECT + `id_sondage`, + `nom`, + REPLACE(REPLACE(REPLACE(`reponses`, 1, \'X\'), 2, 1), \'X\', 2) + FROM `user_studs`'); + } + +} + \ No newline at end of file diff --git a/app/classes/Framadate/Migration/Migration.php b/app/classes/Framadate/Migration/Migration.php new file mode 100644 index 0000000..e6d0eb9 --- /dev/null +++ b/app/classes/Framadate/Migration/Migration.php @@ -0,0 +1,15 @@ +'; // Database server name, leave empty to use a socket const DB_CONNECTION_STRING = 'mysql:host=;dbname=;port='; +// Name of the table that store migration script already executed +const MIGRATION_TABLE = 'framadate_migration'; + // Default Language using POSIX variant of BC P47 standard (choose in $ALLOWED_LANGUAGES) const LANGUE = 'fr_FR'; diff --git a/bandeaux.php b/bandeaux.php index f931177..a5aea4f 100644 --- a/bandeaux.php +++ b/bandeaux.php @@ -45,7 +45,9 @@ function bandeau_titre($titre)
            '; global $connect; - if ($connect->areTablesCreated()) { + $tables = $connect->allTables(); + $diff = array_diff($tables, ['comment', 'poll', 'slot', 'vote']); + if (0 != count($diff)) { echo '
            '. _('Framadate is not properly installed, please check the "INSTALL" to setup the database before continuing.') .'
            '; bandeau_pied(); die(); diff --git a/from_0-8_to_0-9.sql b/from_0-8_to_0-9.sql deleted file mode 100644 index 2b2ae23..0000000 --- a/from_0-8_to_0-9.sql +++ /dev/null @@ -1,136 +0,0 @@ --- -------------------------------------------------------- - --- --- Table structure `poll` --- - -CREATE TABLE IF NOT EXISTS `poll` ( - `id` CHAR(16) NOT NULL, - `admin_id` CHAR(24) NOT NULL, - `title` TEXT NOT NULL, - `description` TEXT, - `admin_name` VARCHAR(64) DEFAULT NULL, - `admin_mail` VARCHAR(128) DEFAULT NULL, - `creation_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - `end_date` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00', - `format` VARCHAR(1) DEFAULT NULL, - `editable` TINYINT(1) DEFAULT '0', - `receiveNewVotes` TINYINT(1) DEFAULT '0', - `active` TINYINT(1) DEFAULT '1', - PRIMARY KEY (`id`) -) - ENGINE = InnoDB - DEFAULT CHARSET = utf8; - --- -------------------------------------------------------- - --- --- Table structure `slot` --- - -CREATE TABLE IF NOT EXISTS `slot` ( - `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, - `poll_id` CHAR(16) NOT NULL, - `title` TEXT, - `moments` TEXT, - PRIMARY KEY (`id`), - KEY `poll_id` (`poll_id`) -) - ENGINE = InnoDB - DEFAULT CHARSET = utf8; - --- -------------------------------------------------------- - --- --- Table structure `comment` --- - -CREATE TABLE IF NOT EXISTS `comment` ( - `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, - `poll_id` CHAR(16) NOT NULL, - `name` TEXT, - `comment` TEXT NOT NULL, - PRIMARY KEY (`id`), - KEY `poll_id` (`poll_id`) -) - ENGINE = InnoDB - DEFAULT CHARSET = utf8; - --- -------------------------------------------------------- - --- --- Table structure `vote` --- - -CREATE TABLE IF NOT EXISTS `vote` ( - `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, - `poll_id` CHAR(16) NOT NULL, - `name` VARCHAR(64) NOT NULL, - `choices` TEXT NOT NULL, - PRIMARY KEY (`id`), - KEY `poll_id` (`poll_id`) -) - ENGINE = InnoDB - DEFAULT CHARSET = utf8; - --- -------------------------------------------------------- - --- --- Migrate data from `sondage` to `poll` --- - -INSERT INTO `poll` -(`id`, `admin_id`, `title`, `description`, `admin_name`, `admin_mail`, `creation_date`, `end_date`, `format`, `editable`, `receiveNewVotes`, `active`) - SELECT - `id_sondage`, - `id_sondage_admin`, - `titre`, - `commentaires`, - `nom_admin`, - `mail_admin`, - `titre`, - `date_creation`, - `date_fin`, - SUBSTR(`format`, 1, 1) AS `format`, - CASE SUBSTR(`format`, 2, 1) - WHEN '+' THEN 1 - ELSE 0 END AS `editable`, - `mailsonde`, - CASE SUBSTR(`format`, 2, 1) - WHEN '-' THEN 0 - ELSE 1 END AS `active` - FROM sondage; - --- -------------------------------------------------------- - --- --- Migrate data from `sujet_studs` to `slot` --- - --- TODO Migrate this, is not so simple -/*INSERT INTO `slot` -(`poll_id`, `title`, `moments`) - SELECT `id_sondage`, - FROM `user_studs`;*/ - --- -------------------------------------------------------- - --- --- Migrate data from `comments` to `comment` --- - -INSERT INTO `comment` -(`poll_id`, `name`, `comment`) - SELECT `id_sondage`, `usercomment`, `comment` - FROM `comments`; - --- -------------------------------------------------------- - --- --- Migrate data from `user_studs` to `vote` --- - -INSERT INTO `vote` -(`poll_id`, `name`, `choices`) - SELECT `id_sondage`, `nom`, REPLACE(REPLACE(REPLACE(`reponses`, '1', 'X'), '2', '1'), 'X', 2) - FROM `user_studs`; diff --git a/migration.php b/migration.php new file mode 100644 index 0000000..af64ef9 --- /dev/null +++ b/migration.php @@ -0,0 +1,60 @@ +'; +} + +// List a Migration sub classes to execute +$migrations = [ + new From_0_8_to_0_9_Migration(), + new From_0_8_to_0_9_Migration() +]; + +// Check if MIGRATION_TABLE already exists +$tables = $connect->allTables(); +$pdo = $connect->getPDO(); + +if (!in_array(MIGRATION_TABLE, $tables)) { + $pdo->exec(' +CREATE TABLE IF NOT EXISTS `' . MIGRATION_TABLE . '` ( + `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` TEXT NOT NULL, + `execute_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) + ENGINE = MyISAM + DEFAULT CHARSET = utf8;'); + + output('Table ' . MIGRATION_TABLE . ' created.'); +} + +$selectStmt = $pdo->prepare('SELECT id FROM ' . MIGRATION_TABLE . ' WHERE name=?'); +$insertStmt = $pdo->prepare('INSERT INTO ' . MIGRATION_TABLE . ' (name) VALUES (?)'); + +// Loop on every Migration sub classes +foreach ($migrations as $migration) { + $className = get_class($migration); + + // Check if $className is a Migration sub class + if (!$migration instanceof Migration) { + output('The class '. $className . ' is not a sub class of Framadate\\Migration\\Migration.'); + exit; + } + + // Check if the Migration is already executed + $selectStmt->execute([$className]); + $executed = $selectStmt->rowCount(); + $selectStmt->closeCursor(); + + if (!$executed) { + $migration->execute($pdo); + $insertStmt->execute([$className]); + output('Migration done: ' . $className); + } + +} From 64a017a44c892beadb7f8ee46161bfdf67c53b16 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 31 Dec 2014 14:02:36 +0100 Subject: [PATCH 081/151] Migration: Add summary at the end of the execution --- migration.php | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/migration.php b/migration.php index af64ef9..de4e51d 100644 --- a/migration.php +++ b/migration.php @@ -11,9 +11,9 @@ function output($msg) { // List a Migration sub classes to execute $migrations = [ - new From_0_8_to_0_9_Migration(), new From_0_8_to_0_9_Migration() ]; +// --------------------------------------- // Check if MIGRATION_TABLE already exists $tables = $connect->allTables(); @@ -35,6 +35,9 @@ CREATE TABLE IF NOT EXISTS `' . MIGRATION_TABLE . '` ( $selectStmt = $pdo->prepare('SELECT id FROM ' . MIGRATION_TABLE . ' WHERE name=?'); $insertStmt = $pdo->prepare('INSERT INTO ' . MIGRATION_TABLE . ' (name) VALUES (?)'); +$countSucceeded = 0; +$countFailed = 0; +$countSkipped = 0; // Loop on every Migration sub classes foreach ($migrations as $migration) { @@ -42,7 +45,7 @@ foreach ($migrations as $migration) { // Check if $className is a Migration sub class if (!$migration instanceof Migration) { - output('The class '. $className . ' is not a sub class of Framadate\\Migration\\Migration.'); + output('The class ' . $className . ' is not a sub class of Framadate\\Migration\\Migration.'); exit; } @@ -53,8 +56,22 @@ foreach ($migrations as $migration) { if (!$executed) { $migration->execute($pdo); - $insertStmt->execute([$className]); - output('Migration done: ' . $className); + if ($insertStmt->execute([$className])) { + $countSucceeded++; + output('Migration done: ' . $className); + } else { + $countFailed++; + output('Migration failed: ' . $className); + } + } else { + $countSkipped++; } } + +$countTotal = $countSucceeded + $countFailed + $countSkipped; + +output('Summary
            '); +output('Success: ' . $countSucceeded . ' / ' . $countTotal); +output('Fail: ' . $countFailed . ' / ' . $countTotal); +output('Skipped: ' . $countSkipped . ' / ' . $countTotal); From c9be94bc19bb5a55268bd80eab8b639905767a35 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 31 Dec 2014 14:25:56 +0100 Subject: [PATCH 082/151] Migration: Finalize the migration of database from 0.8 to 0.9 --- .../Migration/From_0_8_to_0_9_Migration.php | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php b/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php index 5e0d452..fb80f7e 100644 --- a/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php +++ b/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php @@ -24,6 +24,8 @@ class From_0_8_to_0_9_Migration implements Migration { $this->createVoteTable($pdo); $this->migrateFromUserStudsToVote($pdo); + $this->dropOldTables($pdo); + return true; } @@ -87,7 +89,19 @@ CREATE TABLE IF NOT EXISTS `slot` ( } private function migrateFromSujetStudsToSlot(\PDO $pdo) { - // TODO Implements + $stmt = $pdo->query('SELECT * FROM sujet_studs'); + $sujets = $stmt->fetchAll(); + $slots = []; + + foreach ($sujets as $sujet) { + $newSlots = $this->transformSujetToSlot($sujet); + $slots = array_merge($slots, $newSlots); + } + + $prepared = $pdo->prepare('INSERT INTO slot (`poll_id`, `title`, `moments`) VALUE (?,?,?)'); + foreach ($slots as $slot) { + $prepared->execute([$slot->poll_id, $slot->title, $slot->moments]); + } } private function createCommentTable(\PDO $pdo) { @@ -140,5 +154,33 @@ INSERT INTO `vote` FROM `user_studs`'); } + private function transformSujetToSlot($sujet) { + $slots = []; + $ex = explode(',', $sujet->sujet); + $lastSlot = null; + + foreach ($ex as $atomicSlot) { + $values = explode('@', $atomicSlot); + if ($lastSlot == null || $lastSlot->title !== $values[0]) { + $lastSlot = new \stdClass(); + $lastSlot->poll_id = $sujet->id_sondage; + $lastSlot->title = $values[0]; + $lastSlot->moments = count($values) == 2 ? $values[1] : null; + $slots[] = $lastSlot; + } else { + $lastSlot->moments .= ',' . $values[1]; + } + } + + return $slots; + } + + private function dropOldTables(\PDO $pdo) { + $pdo->exec('DROP TABLE `comments`'); + $pdo->exec('DROP TABLE `sujet_studs`'); + $pdo->exec('DROP TABLE `user_studs`'); + $pdo->exec('DROP TABLE `sondage`'); + } + } \ No newline at end of file From 1111b86e2aabdfddeed97fc8c2576f445db6ccd7 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 31 Dec 2014 15:19:15 +0100 Subject: [PATCH 083/151] Define a prefix for database table names. --- app/classes/Framadate/FramaDB.php | 42 +++++++++--------- .../Migration/From_0_8_to_0_9_Migration.php | 24 ++++++---- .../Framadate/Services/PollService.php | 4 +- app/classes/Framadate/Utils.php | 44 ++----------------- app/inc/constants.php.template | 3 ++ migration.php | 11 ++--- 6 files changed, 52 insertions(+), 76 deletions(-) diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index b93ea09..54e186d 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -78,7 +78,7 @@ class FramaDB { } function findPollById($poll_id) { - $prepared = $this->prepare('SELECT * FROM poll WHERE id = ?'); + $prepared = $this->prepare('SELECT * FROM ' . Utils::table('poll') . ' WHERE id = ?'); $prepared->execute([$poll_id]); $poll = $prepared->fetch(); @@ -88,40 +88,40 @@ class FramaDB { } function updatePoll($poll) { - $prepared = $this->prepare('UPDATE poll SET title=?, admin_mail=?, comment=?, active=?, editable=? WHERE id = ?'); + $prepared = $this->prepare('UPDATE ' . Utils::table('poll') . ' SET title=?, admin_mail=?, comment=?, active=?, editable=? WHERE id = ?'); return $prepared->execute([$poll->title, $poll->admin_mail, $poll->comment, $poll->active, $poll->editable, $poll->id]); } function allCommentsByPollId($poll_id) { - $prepared = $this->prepare('SELECT * FROM comment WHERE poll_id = ? ORDER BY id'); + $prepared = $this->prepare('SELECT * FROM ' . Utils::table('comment') . ' WHERE poll_id = ? ORDER BY id'); $prepared->execute(array($poll_id)); return $prepared->fetchAll(); } function allUserVotesByPollId($poll_id) { - $prepared = $this->prepare('SELECT * FROM vote WHERE poll_id = ? ORDER BY id'); + $prepared = $this->prepare('SELECT * FROM ' . Utils::table('vote') . ' WHERE poll_id = ? ORDER BY id'); $prepared->execute(array($poll_id)); return $prepared->fetchAll(); } function allSlotsByPollId($poll_id) { - $prepared = $this->prepare('SELECT * FROM slot WHERE poll_id = ? ORDER BY title'); + $prepared = $this->prepare('SELECT * FROM ' . Utils::table('slot') . ' WHERE poll_id = ? ORDER BY title'); $prepared->execute(array($poll_id)); return $prepared->fetchAll(); } function insertDefaultVote($poll_id, $insert_position) { - $prepared = $this->prepare('UPDATE vote SET choices = CONCAT(SUBSTRING(choices, 1, ?), "0", SUBSTRING(choices, ?)) WHERE poll_id = ?'); + $prepared = $this->prepare('UPDATE ' . Utils::table('vote') . ' SET choices = CONCAT(SUBSTRING(choices, 1, ?), "0", SUBSTRING(choices, ?)) WHERE poll_id = ?'); return $prepared->execute([$insert_position, $insert_position + 1, $poll_id]); } function insertVote($poll_id, $name, $choices) { - $prepared = $this->prepare('INSERT INTO vote (poll_id, name, choices) VALUES (?,?,?)'); + $prepared = $this->prepare('INSERT INTO ' . Utils::table('vote') . ' (poll_id, name, choices) VALUES (?,?,?)'); $prepared->execute([$poll_id, $name, $choices]); $newVote = new \stdClass(); @@ -134,7 +134,7 @@ class FramaDB { } function deleteVote($poll_id, $vote_id) { - $prepared = $this->prepare('DELETE FROM vote WHERE poll_id = ? AND id = ?'); + $prepared = $this->prepare('DELETE FROM ' . Utils::table('vote') . ' WHERE poll_id = ? AND id = ?'); return $prepared->execute([$poll_id, $vote_id]); } @@ -146,7 +146,7 @@ class FramaDB { * @return bool|null true if action succeeded. */ function deleteVotesByPollId($poll_id) { - $prepared = $this->prepare('DELETE FROM vote WHERE poll_id = ?'); + $prepared = $this->prepare('DELETE FROM ' . Utils::table('vote') . ' WHERE poll_id = ?'); return $prepared->execute([$poll_id]); } @@ -159,7 +159,7 @@ class FramaDB { * @return bool|null true if action succeeded. */ function deleteVotesByIndex($poll_id, $index) { - $prepared = $this->prepare('UPDATE vote SET choices = CONCAT(SUBSTR(choices, 1, ?), SUBSTR(choices, ?)) WHERE poll_id = ?'); + $prepared = $this->prepare('UPDATE ' . Utils::table('vote') . ' SET choices = CONCAT(SUBSTR(choices, 1, ?), SUBSTR(choices, ?)) WHERE poll_id = ?'); return $prepared->execute([$index, $index + 2, $poll_id]); } @@ -172,7 +172,7 @@ class FramaDB { * @return mixed Object The slot found, or null */ function findSlotByPollIdAndDatetime($poll_id, $datetime) { - $prepared = $this->prepare('SELECT * FROM slot WHERE poll_id = ? AND SUBSTRING_INDEX(title, \'@\', 1) = ?'); + $prepared = $this->prepare('SELECT * FROM ' . Utils::table('slot') . ' WHERE poll_id = ? AND SUBSTRING_INDEX(title, \'@\', 1) = ?'); $prepared->execute([$poll_id, $datetime]); $slot = $prepared->fetch(); @@ -190,7 +190,7 @@ class FramaDB { * @return bool true if action succeeded */ function insertSlot($poll_id, $title, $moments) { - $prepared = $this->prepare('INSERT INTO slot (poll_id, title, moments) VALUES (?,?,?)'); + $prepared = $this->prepare('INSERT INTO ' . Utils::table('slot') . ' (poll_id, title, moments) VALUES (?,?,?)'); return $prepared->execute([$poll_id, $title, $moments]); } @@ -204,7 +204,7 @@ class FramaDB { * @return bool|null true if action succeeded. */ function updateSlot($poll_id, $datetime, $newMoments) { - $prepared = $this->prepare('UPDATE slot SET moments = ? WHERE poll_id = ? AND title = ?'); + $prepared = $this->prepare('UPDATE ' . Utils::table('slot') . ' SET moments = ? WHERE poll_id = ? AND title = ?'); return $prepared->execute([$newMoments, $poll_id, $datetime]); } @@ -216,12 +216,12 @@ class FramaDB { * @param $datetime mixed The datetime of the slot */ function deleteSlot($poll_id, $datetime) { - $prepared = $this->prepare('DELETE FROM slot WHERE poll_id = ? AND title = ?'); + $prepared = $this->prepare('DELETE FROM ' . Utils::table('slot') . ' WHERE poll_id = ? AND title = ?'); $prepared->execute([$poll_id, $datetime]); } function deleteSlotsByPollId($poll_id) { - $prepared = $this->prepare('DELETE FROM slot WHERE poll_id = ?'); + $prepared = $this->prepare('DELETE FROM ' . Utils::table('slot') . ' WHERE poll_id = ?'); return $prepared->execute([$poll_id]); } @@ -233,31 +233,31 @@ class FramaDB { * @return bool|null true if action succeeded. */ function deleteCommentsByPollId($poll_id) { - $prepared = $this->prepare('DELETE FROM comment WHERE poll_id = ?'); + $prepared = $this->prepare('DELETE FROM ' . Utils::table('comment') . ' WHERE poll_id = ?'); return $prepared->execute([$poll_id]); } function updateVote($poll_id, $vote_id, $choices) { - $prepared = $this->prepare('UPDATE vote SET choices = ? WHERE poll_id = ? AND id = ?'); + $prepared = $this->prepare('UPDATE ' . Utils::table('vote') . ' SET choices = ? WHERE poll_id = ? AND id = ?'); return $prepared->execute([$choices, $poll_id, $vote_id]); } function insertComment($poll_id, $name, $comment) { - $prepared = $this->prepare('INSERT INTO comment (poll_id, name, comment) VALUES (?,?,?)'); + $prepared = $this->prepare('INSERT INTO ' . Utils::table('comment') . ' (poll_id, name, comment) VALUES (?,?,?)'); return $prepared->execute([$poll_id, $name, $comment]); } function deleteComment($poll_id, $comment_id) { - $prepared = $this->prepare('DELETE FROM comment WHERE poll_id = ? AND id = ?'); + $prepared = $this->prepare('DELETE FROM ' . Utils::table('comment') . ' WHERE poll_id = ? AND id = ?'); return $prepared->execute([$poll_id, $comment_id]); } function deletePollById($poll_id) { - $prepared = $this->prepare('DELETE FROM poll WHERE id = ?'); + $prepared = $this->prepare('DELETE FROM ' . Utils::table('poll') . ' WHERE id = ?'); return $prepared->execute([$poll_id]); } @@ -268,7 +268,7 @@ class FramaDB { * @return array Array of old polls */ public function findOldPolls() { - $prepared = $this->prepare('SELECT * FROM poll WHERE end_date < NOW() LIMIT 20'); + $prepared = $this->prepare('SELECT * FROM ' . Utils::table('poll') . ' WHERE end_date < NOW() LIMIT 20'); $prepared->execute([]); return $prepared->fetchAll(); diff --git a/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php b/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php index fb80f7e..33f1185 100644 --- a/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php +++ b/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php @@ -1,6 +1,8 @@ createPollTable($pdo); $this->migrateFromSondageToPoll($pdo); @@ -31,7 +39,7 @@ class From_0_8_to_0_9_Migration implements Migration { private function createPollTable(\PDO $pdo) { $pdo->exec(' -CREATE TABLE IF NOT EXISTS `poll` ( +CREATE TABLE IF NOT EXISTS `' . Utils::table('poll') . '` ( `id` CHAR(16) NOT NULL, `admin_id` CHAR(24) NOT NULL, `title` TEXT NOT NULL, @@ -52,7 +60,7 @@ CREATE TABLE IF NOT EXISTS `poll` ( private function migrateFromSondageToPoll(\PDO $pdo) { $pdo->exec(' -INSERT INTO `poll` +INSERT INTO `' . Utils::table('poll') . '` (`id`, `admin_id`, `title`, `description`, `admin_name`, `admin_mail`, `creation_date`, `end_date`, `format`, `editable`, `receiveNewVotes`, `active`) SELECT `id_sondage`, @@ -76,7 +84,7 @@ INSERT INTO `poll` private function createSlotTable(\PDO $pdo) { $pdo->exec(' -CREATE TABLE IF NOT EXISTS `slot` ( +CREATE TABLE IF NOT EXISTS `' . Utils::table('slot') . '` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `poll_id` CHAR(16) NOT NULL, `title` TEXT, @@ -98,7 +106,7 @@ CREATE TABLE IF NOT EXISTS `slot` ( $slots = array_merge($slots, $newSlots); } - $prepared = $pdo->prepare('INSERT INTO slot (`poll_id`, `title`, `moments`) VALUE (?,?,?)'); + $prepared = $pdo->prepare('INSERT INTO ' . Utils::table('slot') . ' (`poll_id`, `title`, `moments`) VALUE (?,?,?)'); foreach ($slots as $slot) { $prepared->execute([$slot->poll_id, $slot->title, $slot->moments]); } @@ -106,7 +114,7 @@ CREATE TABLE IF NOT EXISTS `slot` ( private function createCommentTable(\PDO $pdo) { $pdo->exec(' -CREATE TABLE IF NOT EXISTS `comment` ( +CREATE TABLE IF NOT EXISTS `' . Utils::table('comment') . '` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `poll_id` CHAR(16) NOT NULL, `name` TEXT, @@ -120,7 +128,7 @@ CREATE TABLE IF NOT EXISTS `comment` ( private function migrateFromCommentsToComment(\PDO $pdo) { $pdo->exec(' -INSERT INTO `comment` +INSERT INTO `' . Utils::table('comment') . '` (`poll_id`, `name`, `comment`) SELECT `id_sondage`, @@ -131,7 +139,7 @@ INSERT INTO `comment` private function createVoteTable(\PDO $pdo) { $pdo->exec(' -CREATE TABLE IF NOT EXISTS `vote` ( +CREATE TABLE IF NOT EXISTS `' . Utils::table('vote') . '` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `poll_id` CHAR(16) NOT NULL, `name` VARCHAR(64) NOT NULL, @@ -145,7 +153,7 @@ CREATE TABLE IF NOT EXISTS `vote` ( private function migrateFromUserStudsToVote(\PDO $pdo) { $pdo->exec(' -INSERT INTO `vote` +INSERT INTO `' . Utils::table('vote') . '` (`poll_id`, `name`, `choices`) SELECT `id_sondage`, diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 163a8e9..0a21824 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -133,13 +133,13 @@ class PollService { $this->connect->beginTransaction(); // TODO Extract this to FramaDB (or repository layer) - $sql = 'INSERT INTO poll + $sql = 'INSERT INTO ' . Utils::table('poll') . ' (id, admin_id, title, description, admin_name, admin_mail, end_date, format, editable, receiveNewVotes) VALUES (?,?,?,?,?,?,FROM_UNIXTIME(?),?,?,?)'; $prepared = $this->connect->prepare($sql); $prepared->execute(array($poll_id, $admin_poll_id, $form->title, $form->description, $form->admin_name, $form->admin_mail, $form->end_date, $form->format, $form->editable, $form->receiveNewVotes)); - $prepared = $this->connect->prepare('INSERT INTO slot (poll_id, title, moments) VALUES (?, ?, ?)'); + $prepared = $this->connect->prepare('INSERT INTO ' . Utils::table('slot') . ' (poll_id, title, moments) VALUES (?, ?, ?)'); foreach ($form->getChoices() as $choice) { diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index 5efb9a0..190c830 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -123,46 +123,6 @@ class Utils return $url; } - /** - * Completly delete data about the given poll - * TODO Move this function to FramaDB - */ - public static function removeSondage($poll_id) { - global $connect; - - $prepared = $connect->prepare('DELETE FROM sujet_studs WHERE id_sondage = ?'); - $prepared->execute(array($poll_id)); - - $prepared = $connect->prepare('DELETE FROM user_studs WHERE id_sondage = ?'); - $prepared->execute(array($poll_id)); - - $prepared = $connect->prepare('DELETE FROM comments WHERE id_sondage = ?'); - $prepared->execute(array($poll_id)); - - $prepared = $connect->prepare('DELETE FROM sondage WHERE poll_id = ?'); - $prepared->execute(array($poll_id)); - - } - - /** - * Clean old poll (end_date < now). - * TODO Move this function to PurgePollService - */ - public static function cleaningOldPolls($log_txt) { - global $connect; - - $resultSet = $connect->query('SELECT poll_id, format, admin_name FROM sondage WHERE end_date < NOW() LIMIT 20'); - $toClean = $resultSet->fetchAll(\PDO::FETCH_CLASS); - - $connect->beginTransaction(); - foreach ($toClean as $row) { - if (self::removeSondage($row->poll_id)) { - error_log(date('H:i:s d/m/Y:') . ' EXPIRATION: '. $row->poll_id."\t".$row->format."\t".$row->admin_name."\n", 3, $log_txt); - } - } - $connect->commit(); - } - /** * This method pretty prints an object to the page framed by pre tags. * @param mixed $object The object to print. @@ -172,4 +132,8 @@ class Utils print_r($object); echo ''; } + + public static function table($tableName) { + return TABLENAME_PREFIX . $tableName; + } } diff --git a/app/inc/constants.php.template b/app/inc/constants.php.template index 61781a6..bf9fc0c 100644 --- a/app/inc/constants.php.template +++ b/app/inc/constants.php.template @@ -44,6 +44,9 @@ const DB_CONNECTION_STRING = 'mysql:host=;dbname=; // Name of the table that store migration script already executed const MIGRATION_TABLE = 'framadate_migration'; +// Table name prefix +const TABLENAME_PREFIX = 'fd_'; + // Default Language using POSIX variant of BC P47 standard (choose in $ALLOWED_LANGUAGES) const LANGUE = 'fr_FR'; diff --git a/migration.php b/migration.php index de4e51d..6349c08 100644 --- a/migration.php +++ b/migration.php @@ -18,10 +18,11 @@ $migrations = [ // Check if MIGRATION_TABLE already exists $tables = $connect->allTables(); $pdo = $connect->getPDO(); +$prefixedMigrationTable = Utils::table(MIGRATION_TABLE); -if (!in_array(MIGRATION_TABLE, $tables)) { +if (!in_array($prefixedMigrationTable, $tables)) { $pdo->exec(' -CREATE TABLE IF NOT EXISTS `' . MIGRATION_TABLE . '` ( +CREATE TABLE IF NOT EXISTS `' . $prefixedMigrationTable . '` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `name` TEXT NOT NULL, `execute_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, @@ -30,11 +31,11 @@ CREATE TABLE IF NOT EXISTS `' . MIGRATION_TABLE . '` ( ENGINE = MyISAM DEFAULT CHARSET = utf8;'); - output('Table ' . MIGRATION_TABLE . ' created.'); + output('Table ' . $prefixedMigrationTable . ' created.'); } -$selectStmt = $pdo->prepare('SELECT id FROM ' . MIGRATION_TABLE . ' WHERE name=?'); -$insertStmt = $pdo->prepare('INSERT INTO ' . MIGRATION_TABLE . ' (name) VALUES (?)'); +$selectStmt = $pdo->prepare('SELECT id FROM ' . $prefixedMigrationTable . ' WHERE name=?'); +$insertStmt = $pdo->prepare('INSERT INTO ' . $prefixedMigrationTable . ' (name) VALUES (?)'); $countSucceeded = 0; $countFailed = 0; $countSkipped = 0; From 1578703de6263c60f168aa8e07a7aac1131c37a6 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 1 Jan 2015 01:17:53 +0100 Subject: [PATCH 084/151] Fix line breaks on mails sent --- app/classes/Framadate/Services/MailService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/classes/Framadate/Services/MailService.php b/app/classes/Framadate/Services/MailService.php index 233d767..c8ce77d 100644 --- a/app/classes/Framadate/Services/MailService.php +++ b/app/classes/Framadate/Services/MailService.php @@ -39,7 +39,7 @@ class MailService { $headers .= "Auto-Submitted:auto-generated\n"; $headers .= 'Return-Path: <>'; - $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8') . _('\n--\n\n« La route est longue, mais la voie est libre… »\nFramasoft ne vit que par vos dons (déductibles des impôts).\nMerci d\'avance pour votre soutien http://soutenir.framasoft.org.'); + $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8') . _("\n--\n\n« La route est longue, mais la voie est libre… »\nFramasoft ne vit que par vos dons (déductibles des impôts).\nMerci d'avance pour votre soutien http://soutenir.framasoft.org."); mail($to, $subject, $body, $headers, $param); } From c533645d295ac407182a98391557335b136e842e Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 1 Jan 2015 01:18:49 +0100 Subject: [PATCH 085/151] Make installation from scratch work with migration page --- .../Migration/From_0_0_to_0_8_Migration.php | 60 +++++++++++++++++++ bandeaux.php | 2 +- migration.php | 2 + 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 app/classes/Framadate/Migration/From_0_0_to_0_8_Migration.php diff --git a/app/classes/Framadate/Migration/From_0_0_to_0_8_Migration.php b/app/classes/Framadate/Migration/From_0_0_to_0_8_Migration.php new file mode 100644 index 0000000..121e389 --- /dev/null +++ b/app/classes/Framadate/Migration/From_0_0_to_0_8_Migration.php @@ -0,0 +1,60 @@ +exec(' +CREATE TABLE IF NOT EXISTS `sondage` ( + `id_sondage` char(16) NOT NULL, + `commentaires` text, + `mail_admin` varchar(128) DEFAULT NULL, + `nom_admin` varchar(64) DEFAULT NULL, + `titre` text, + `id_sondage_admin` char(24) DEFAULT NULL, + `date_creation` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `date_fin` timestamp NOT NULL DEFAULT \'0000-00-00 00:00:00\', + `format` varchar(2) DEFAULT NULL, + `mailsonde` tinyint(1) DEFAULT \'0\', + `statut` int(11) NOT NULL DEFAULT \'1\' COMMENT \'1 = actif ; 0 = inactif ; \', + UNIQUE KEY `id_sondage` (`id_sondage`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8;'); + + $pdo->exec(' +CREATE TABLE IF NOT EXISTS `sujet_studs` ( + `id_sondage` char(16) NOT NULL, + `sujet` text, + KEY `id_sondage` (`id_sondage`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8;'); + + $pdo->exec(' +CREATE TABLE IF NOT EXISTS `comments` ( + `id_comment` int(11) unsigned NOT NULL AUTO_INCREMENT, + `id_sondage` char(16) NOT NULL, + `comment` text NOT NULL, + `usercomment` text, + PRIMARY KEY (`id_comment`), + KEY `id_sondage` (`id_sondage`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;'); + + $pdo->exec(' +CREATE TABLE IF NOT EXISTS `user_studs` ( + `id_users` int(11) unsigned NOT NULL AUTO_INCREMENT, + `nom` varchar(64) NOT NULL, + `id_sondage` char(16) NOT NULL, + `reponses` text NOT NULL, + PRIMARY KEY (`id_users`), + KEY `id_sondage` (`id_sondage`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;'); + } +} + \ No newline at end of file diff --git a/bandeaux.php b/bandeaux.php index a5aea4f..534bd43 100644 --- a/bandeaux.php +++ b/bandeaux.php @@ -46,7 +46,7 @@ function bandeau_titre($titre) global $connect; $tables = $connect->allTables(); - $diff = array_diff($tables, ['comment', 'poll', 'slot', 'vote']); + $diff = array_diff([Utils::table('comment'), Utils::table('poll'), Utils::table('slot'), Utils::table('vote')], $tables); if (0 != count($diff)) { echo '
            '. _('Framadate is not properly installed, please check the "INSTALL" to setup the database before continuing.') .'
            '; bandeau_pied(); diff --git a/migration.php b/migration.php index 6349c08..70d7c6d 100644 --- a/migration.php +++ b/migration.php @@ -1,4 +1,5 @@ Date: Thu, 1 Jan 2015 22:04:20 +0100 Subject: [PATCH 086/151] Update translations --- locale/de_DE/LC_MESSAGES/Studs.mo | Bin 17977 -> 17968 bytes locale/de_DE/LC_MESSAGES/Studs.po | 14 +++++++------- locale/en_GB/LC_MESSAGES/Studs.mo | Bin 17035 -> 17025 bytes locale/en_GB/LC_MESSAGES/Studs.po | 16 ++++++++-------- locale/es_ES/LC_MESSAGES/Studs.mo | Bin 16221 -> 16215 bytes locale/es_ES/LC_MESSAGES/Studs.po | 6 +++--- locale/fr_FR/LC_MESSAGES/Studs.mo | Bin 18822 -> 18813 bytes locale/fr_FR/LC_MESSAGES/Studs.po | 14 +++++++------- tpl/part/poll_hint_admin.tpl | 2 +- 9 files changed, 26 insertions(+), 26 deletions(-) diff --git a/locale/de_DE/LC_MESSAGES/Studs.mo b/locale/de_DE/LC_MESSAGES/Studs.mo index d225d64f535a56e20d67dac5655325fcadafb7f5..99c35911ba21fa58ca59a9c594d971e7a9ecd8c7 100644 GIT binary patch delta 4344 zcmXxm2~bs49LMp)>H-MzL_kClO_3!92~jIiz@%JrH@7rG6EiK-sJs?pDrm^dG_qV; zOmlx2S|+8U)z~swGp&;)O=?-nG?g_qeShyB?)c+#?tSl`d+z_7d!I+E0uEFKRA)Qw zjWMy&#)M;UOvD^)i{r5s&cq-rL49w&bs5I9Ux96KD|W4g)YdmX@e~wY?|AJ%j z-)Q5QP#U8>?gtYwnEeuLho#m>F_!(cs1A0ZF5p8Ar~%c_S?rAGFafV(42E}bO-7xc zi+p5?IylBe(wNSH-namJ;wDsw$59nOoI`u-)?(8E<^U+jh>Q3F_r`hF$y z&pgi`Rq`Mv<6(z}?&J&92~DUIR7X`J3b}@fK|V66sLJG_?qIatpMx6UVpK(zq57-9 z2;7eRGyD0Y8#|4fdgntL`oedpJH3MQFpPSa;u7qNKcG$wj5B6Aw!yi$8g<9lP#5-4 z7MX+^a0co|@^KapNAEtdFAL@i-$QaD0n1z>673s|FXfdXvI?P5@W`Nxv zg{sInR7Fcr=RIgYFULUkSK|t-^dD#b!|C+)>+S@)>IR!(qWWYm5j$ou5XfPsAPS00B=F9(vhf+W}q(gFlz2AQFB*| zJV|B`>iZ3-^FOhlpT`^6Z$?!tu8UjYMAY~Dp`(rqXsDwp)>8B@4!gerb%!sb271Kq zH=;WF68qw1%)kT|4AnJ7Sc%1$gx9b;Mzh28o17%(UvoT$1M0XO4`DUtVLmHs6|TgU z7{)WB6RWWpccbnsie6Rv7}UTMa2jTyzPA=N1y^x4#`bUrUe?2LPpssC-c%b<6{$s) zdOxb9$1w#zLaJ&0MBQNw^;P9Etp%t#o`gYIjQlh6_|pfU#sS!XL-4voLmdxdc;oRN z9Ee9z75N=?fq-7_E4Bmb!d)T)0EDULah8c=Au`&f2DeJ>Nk@OIR|C!#uDf-`UxYM?)& zD)KYx20~b&n%cI0ng4hi>M#X$p&_VWvk4f1GwuEYWZKPAOD^)!{5uB^Fy(VLSF~QKj64x|5Tr zHS#NJKtY-I6^#+>XQMtJikiwvxCkG|8vHGj`PZU&GRu7>Zo}p5@5F`Jv!7duXHj=@ z#M+3u<4;kgyognJ1@+@nmd*OXCe*<9vgCDx$E@d&OPI?yQGX2}F~=SGAXJC>sF4r1 z$ERD1QHyQ?s&bEDC~icZw*@P3JL>W4#WUI#`=AF0q8__Z*b(n{>=!ERfojy9?nHk0 zOdV<KLap{+P#uKjx^K2*)Okgy#XAx8`7CUYOHl(@gPOt@FczJ98vYBQPH4g? z{0DVH_yBi53ALYzIqHf@n-Tw~b*>AS{;k@Peo@2VwP{&!Q zIUR;trPELYD@9%C3A`N-p*s2(S77WQcPcicN?V7T($A1b|l49R2OF$-0}&#*QAh*~qh zq8`h?QI$#@Ld6{#IW*M4NYu#7FabBCN?B(;gL&wI!@XX>^%)wo#=lDEo)rS_kt2+XN z*^k2_OvDr{!ERWMz3~ugs=q-^?bSl+uf-HH%BH$sVFL6|R*wg~n0x4w>q`7U6Mt-b$4MJA?i&LD$H1-XN?Y!hgVB2Ts)uy#j1 zV4>uUJ+|DccUhKg3oqF~qP3$NoW|cSgcq!T%E8o;OtOyDk_Pe~d73OH+sF5G;auB(7WK|}o@}wl`dC|-P2*LPVGoq! za59qzw2_9M8Nj3K#X5y>anq>#Kpf=J7z zU(cC#=N{`uyo*e?`&GDvJU|X=`Q_1ANm{l>+gOHar+y_?S`fO555?)8vptrk1g#lK-kj zSmjZqNTo>9NuA2!RQ}|oQ|T``)j7RC&;6}?e4f|ucc16p`@7%Y@7{T(%JW8*XHBZ( zGseV58q*vzF&u|r8ytr>V=0DV1qNXy>UUMv_1KDj9o~dTFa}Rx6FiTN@h7|g8aAWv zjWUiIMWbz$F`+mQ^~GWg##I=BtF4=`CH>u~-@T8zz!#_iT|k}ZD#qhAY>iRT#O9szo355DAv8xW;ly}3Krut*bYOezYgq#%PIjTGTzydOEgV@}f8!jAMfcaeO7I^Y}BNdLrM7|v~|BK=W|aRlmw z<4~2EVEgk>6)8hi^fAC6J#e81c8gW57(^jn}R))!Ub9CUQRSQcS|eHhJ0M@;ikf2QAzXNTr^0qVqcxEKAH zgGH>Y75E}Pf+;*QI?j)U_%Z6vdUIBlJ`*+YY@C4ksNd~DO+i$GF;nr@1jiluCU)q+ zdeob0AF3jUP^CVND(QJl#9xu>nz&Bx9cE%A{Q~O@)EqCtAgo0GnJPZI<6i887aSV7 zG~yYSPCO9{a3$V~=TH@iy~Vvi0_qi;fhuh-X5hVeC$7V;cma8EjF*#!VIper_CO7& zFQ%c>p9a%nN|7p>b*MQ$fU3Yr)ZCuOVEhe3@Vf2)ix)jSQoJ^`|1wv<4}ZjNIF1iJ zhRabmQjMzIM&!JXIY^^1J3hiD_&M?}G2fzA{SBl@rg@S(ung2=ITZD~si@=1k@aU* zq6S=tlW;$3V6m)7t(i8c8_B>3J^xvO1}8+F@NQHE7NAPK61}+A_O~F@Z+0R#Z%&~e zr|YN+dQ;p1^swfl&NmAAi77&gW1hrdu5aF^p%WfOjr0oY&aWa1-h{DYD1zyNJ{*JG zlqo|E;5pQ4KZzR1*Qh!E12v$(FdSR+Y--IUVpAN5&doFm>=%!>>pPIc!r4y)+5L;kp!-FO^hSn3-1H>ex@*&32g{kevTPj?3} z0yXm4s6|qW(YVC!ueLsoT69}bCEbM@_%YORr|?ny40XQoJfo`g6pX@RY=;#NjTjnR z?GN_b{=29?Scs8ZgBOR)g;yH7C*GjfdC zhSO0M49#_4aIvU0<3l}`N!Ze%F@lClJ`;5U2Q~8D7`P);DKA@ZpdPF6+uZ-j#36s! zOdHhWn2UE~F^|2Hs_%nZ-8mSHLvb+Xqh3(YVtafKHO1edru0T0_17Yb804O)Gpf|d7=&r)!TX5j zZVu6=1*W-YW&;0R*Wk2i0lq~-h%R`5XsacQNF%bA>>)jgSM#q@9VG9Ndx*BfE`d+p zo`LNpK2^4LWHgyUrjiedwxPsFh7fIf;VdJn%psymyg{_M$B+v0LIEGcNHx*+Cg~Vx zu|iP`h=m;37V@e2)b0i6ff{@23B^owT<6-*eZ^O!|+Lhsa|4U5w^7gN{mk7pbye>_RQN zZsb|wCwCC7cx}bx1M&(PK(yWN68P(tZ`)!A*+*U{&k${Tmjt%j8{Q_)Y};v!vuyim ze2{D;o9wLNnplzIcfh5!orK85l!uFVpdXP!j7R#(_ zQRnYKhBAlZ9Alzre8i3v{05USoU=4wI%=SS*aAnRjvtSD@)_6xE38|w3;n~W8~GM> z{8i*X6GeGc$sX7hQydy9RUYbuF{l$BMpa@Fa!+O{YJh4~W%i(+;E3&ihPuJ;Q5E?K zHQp6$jcq9(P16naVArFj-pQe%14f~qbRtgE4_JynVrMLjcTb#)3+T_ssrWbQiAyMl zE?i+n*zVyr<8xE)oQ z*KEHLRgq(;ik?B8_k;cYG6vKC8_V#je?RkI#sq5Ma?}9JQ8%#3_Uln^!*RR+Guyw2 zx`8XG^CBsqrl2cQG?Q%2My;tas7gDiDOiqCT;Hswq0(*D4y;A3(!;2MPNFV!9yRw@ zQF9mBiB}F2QOEZ~oj(-ydja;qDX5A)jXJIhHQr{_G@E@iG|&m_S=0c(+kOZOKu?%} zy3yXYKL|D8Nc3V6daw$qu6YY9@eC&7ef;T$OORz?b|fy`+VJe2OQx!_b5X?hWr~tKy$D(d*G7dmz zDh;N`RAWnQK&ot-km)z)P;(!W;#Q_Ts&rn|z&Y3gb8SBlKMCUdZucjp88e;Vd!fc% zhnk`T$do(gI1QEb6zUEyqwYMomwTsSsI?JkZI61wWNd{)P_JtqhGQ{?;!L~$5!4Mo zgZWs4deBS${mlOr8hVm2>Zm!7vUWnf9UjyGH)8}AT8mKw%|cDdJk*2uP#>~d>oL^% zU!W>^5w)g*d+Ym8BZdakZU&M$LI4Y6|W~RcbyuI$`&N*Xc1Jue=0d@=^32g}fF_t&DveZ!%l0UA)HI%)eqqTYso?EcW}+>*Dj6?l1-2r1!7f7=GOwOZs`Lj@H{OWj@DnV-zBjm2uns5DZ$RC6mmA&l(lJ!;eyT7H1?r?9rCbd3g%!9YTUEv z6wnCIcK^{SLY4Y?)CIPqKCy42F5HAV@f%dh!x$|UGf@>PMy=}ks0x*%7V$FFjjch} zvw0Rf;fWmTuT^=G9bNHv`$PN?ckVM#l^KpIT@h;F*{IUbwf!eBh`zQB#OH7E0kS@X z3&@*9@4c?6ZHn>zlhhMmZi3pF8;q2{M|*`+I@TR zUZRP)h3H+-_6q4nwA4EgZF@+D-hnzA`rnQjq=^JJma>1lJFvq#3ZEnMh$ceY0n(G? zkoQR*32ftNY$kkM{7ZQPt|3|ly1qF`O38=hJ@PUMY_&9=CVD5vkVnZrvX*Fl-%jeu zt3+E8i6!@wV}$q4zrD`i!?vw!R+HYu`G7yKkyS*Smf9U;5gA6b%_mxlbJVfhTwkrizI~HNCuDyvV;_o7|rfB8eVd%Z(($-Z)J3Ir-q(3y>@}^3ER-; zGn;I+{l3=exRcyWo+3wxwyq?ZbSC{tB-ufxlJVpjvYG_8+cYIl(wj{RNNduZJWL)Z zcadczp6I=AMIIr6Ex|T=VHeV9`{|fQ-m(41@Fns#=|{8$lL!1ug2sL_iR6=YWFQG_ z@6tF#W|85f2MKJ&G|EW{85`J%qiy>rK2O4Jzl{v@c*4ROUu~?(o0wR4dz%}A>b_3P z2=c{yM)^uT9qS6>65@O_lQ;O@PV3~$9x}YHFlAcs|A*9-dNTEMq3^Gp+`u9K0ks~% AT>t<8 delta 4449 zcmZwIc~F)`0LSrtNl+2wOa)P1@dz-LOC^s4@1smn6wQN715C@TOv8Avybv{&tTYu< zEAvG0$jaNWEJtT@%IuH~9kp?4I;Qff?~iBS|Jw1#XZLxZXP?jv#gur zHO4FoHzo|XVh|q0W_St%@haBE-|-&2g*xwFYfywSQM9A5KBi(L?2Zj^IM%~ld%OTc zX%|Nr$7E4i&Vc}|u|NEbb!gwlhUkfO4aFw3V^JNXqi!$&HK1%%KNGMi7N8zv9^Q)^ ztp`xopNVvg;U1=%10nbaCSV=TZiDSn9cH6C8iW4$BI^8N)RQm67~En#i7jZ?pav4a zbm;szViVl1#h5c;yq++W*e%5qo|qr8ub8IZ2Kl^fb|=@ zGZKR8F9w4#9XZAHMLn1^mWtMXqCH^->PhEf0dBx47{t8C;w;pKtFQ>yV?M?*4SM2* zsHNCq-H#gZ3DkpJz+AkD^zWFAXk*Gbum!bA1~Ob-Fbp-)0!+bT)QnW3Hsf(rho7Tn z=B#aBM$O1|)QsLmT^Gpu==^B(!&ofl{wB`;uo2bqW>g0ir~#a??Qc_nZn2OV|z2^HPo0;;3mto|&xZqNjEJQ4MT z-BAM_YTM&b9Ztt2d0UoZ*1h_!_F?7ix+GvY<9bw^Z(ebFBW+4fL8=V24t<89j-GnwC$ zQT?q!FCIpg$T8JawC2B|ru1Lb2%FvSjyxVU(j?S*Y1T~C9vF=EF(381PR9mVg7t8v zJ-!Y#@V%IYRT!Z6KZ<$N4_?$0C8O57leG`>ku$?l=S{^REV7oOX6#MWl9Zz!>KMZsO$aPyEEDdL%6?5q{3{OF37T*iKq@sQ5~&7O>qTk6YfJjc@^>vGS${Q$ctj4 z*nVK6?0TAJCY2P;Fpo~x6Xf1R+61A5XAu>jBG6zrMoZpxjg3(sH?euep% zo#H<6A=Hhltv65uzKME}&{Sh`@m^H_Gq4=1Q<;BllHxS?f)dn7%aLo%J`BNYsMqKp zREM69?#u+B+D%b!i5E4aX{hTm?C(R+k9IZ|V~#!kjYCBp|A6Y?3Tgm1Z9A-!`!=*j z9Z$0Dei%tR3w2!{Y6%KapYl1@Rj56+3pLZ{Q8Rf3H9+SE6;0h8dmym0yGx@{9koT> zs26Ijb1)3^FdS!LC@w~IxYqu@9b3~rjGCd#sPnF)`n!dV_5O#ZyB)<_yP|F|*tT;~ zPxvfqpbKpKHB^V2k?mp*Aa9ttj@o=p_`a568hY^vw!|MX3jO)Krs(~TrJ|0ra5s*} z3=Hq;{--kx=hD7_x^R3q_dkSsJEmF^@KI3B``f)BT#GH2KAn&p_U*WJK#9v;muOa z#81&t$AKB{e>$ni!<&Vu899!+!CBNN_9xVhZ=kNLPcNGC6imcijK)&brhXSSLpxBP z^h(sg4k7#79Lr?>n^XCl1KO31d%9ny=BPE#M9oMxYRV>~IxIv@d9iKJM-Oe4b>y|$ znlb&X&!Iy;CVCJJP9?AQs9Uf7V5qu^tRU-2FEW9sY#^)2G%}g^${Z?MZyO6)T zNF#e}AC4z&Nq@4Kyhyf^R>Y~~k2aOcUc%dB_7FC^d5TmKUt#0cmPdUDti$mwGLvW- zRX!rxBR$C}@-Xq0u~aq^J^}9f=hAqc#1fT*WGXpLJ|kO*uk5C>glIpEB2CE$7isE89-Eu$cJQx8n(QE zt;zeo1IQ=9JWGy{M6#c}OX`sxq*Dxkf=LN^j6{&lB$*5>YY`k#mK0pad7GAs&i0j; zY^4cil6P!7#rh=fBz?(Ta)PL|BniYz^b&@U?WBN=Bg@E2;wyvnnS6!TbdpUPk~-vh zGMkJbr6h{z?GGfgG<2sOwK#H|sHBqn$tP-1{Kc7)73Z{ nF^ooJWamg4volAOy&d1LvTj19-~XT3yIs0_;+nF$2?PHFiG{k? diff --git a/locale/en_GB/LC_MESSAGES/Studs.po b/locale/en_GB/LC_MESSAGES/Studs.po index 4510ab9..ad992ab 100644 --- a/locale/en_GB/LC_MESSAGES/Studs.po +++ b/locale/en_GB/LC_MESSAGES/Studs.po @@ -66,8 +66,8 @@ msgstr "(in the format name@mail.com)" msgid "Description" msgstr "Description" -msgid "Back to the homepage of " -msgstr "Back to the homepage of " +msgid "Back to the homepage of" +msgstr "Back to the homepage of" msgid "Error!" msgstr "Error!" @@ -248,14 +248,14 @@ msgid "Cancel the rules edit" msgstr "Cancel the rules edit" # Help text adminstuds.php -msgid "As poll administrator, you can change all the lines of this poll with this button " -msgstr "As poll administrator, you can change all the lines of this poll with this button " +msgid "As poll administrator, you can change all the lines of this poll with this button" +msgstr "As poll administrator, you can change all the lines of this poll with this button" -msgid " remove a column or a line with " -msgstr " remove a column or a line with " +msgid "remove a column or a line with" +msgstr "remove a column or a line with" -msgid "and add a new column with " -msgstr "and add a new column with " +msgid "and add a new column with" +msgstr "and add a new column with" msgid "Finally, you can change the informations of this poll like the title, the comments or your email address." msgstr "Finally, you can change the informations of this poll like the title, the comments or your email address." diff --git a/locale/es_ES/LC_MESSAGES/Studs.mo b/locale/es_ES/LC_MESSAGES/Studs.mo index 54fc228efc5cfcb0194f6bdb8279a9984b99dd96..a037bd261c407a673d165f7aa351f9b873b5c82b 100644 GIT binary patch delta 2608 zcmXZceN0wm7{~GJ5me+I5kZnbh$jT~Ndch*G7(Tqi$ZZ|YD5D^3FZP{&{Jm37+cWe z$jv!3p+8(R8&a`CYyRV+)?98(9nB49lerdUOO|7Of1cy;`P^^ke!1@JoRLGrhdO(l zN;4aYHk*Ng7_(Shj!{^FiMSCX@D0?seHf2#BY$>`A3fKD^ROQm;xFjONzXI}>G=u_ z!ws?KJe;7~YpBO?I+}4l9`HPlGpYA`{e$=j^()BSHin^i59i_}Mq+H78E3N;)c8f1 zjB9Wc>)3*+IEs2MghA^u z9M!%Vwb8wpiw7MFrzm`h30OJDJyAVsU@Ph>+E7=}?)7)$1oh8Q8#~U!8vluBFYcy( z)~nCwbQ-q+bp%@Wjk>dbRA?`va$^W}1*1sR?QgFh zN~h+TgKGCiQ!bQ~ILY?qa z)X6U3F}#5p*hB`GVh}Zc7}GE`#jF-Hv5NKWD1}NK!5R!aYPJg7@hSWn34(=jTwO&P zvWDg1EPMfVB{jGM>%IOfSVw&fpTo6jW?9&c*?0+^0EKZ1k7F_^uam4oouI+914F2v zM`iT|%*St$xoyI0kK-P66-oRkS5~0LulDNCqLQ!*71^!n#9twQg$A9Z-s{+n_k6rg zxSjUK$IOax2$iI>*riUKgfv+uDnjc}3)i9+YDA{6J*e+VH|oHBNKkDw({WES&F}80 z5U0~ojM{lAHsCt1y$_X~14tg(PpE}&qjF>lwSjoTNzvw`uB;RlscKYGx8f4)btot~ zu6g>h+_zu}YN8_4LS?A;e>*Ayji{6DM_tuP)W&}ByoUM&|Bg!1I4UzR16j(lQ5$w% zq`)`A>XE3}K`g*Cs3g1T`7i2qiYIfpZY#$;Y(PzX5@%u$>S{hmjT^udcoVy^HHTLd zqd7I>9a}_U3k`Xw5Oty^JddULHJ-!&P@z0a{Iv6ns1M7ps0fXrA~1zoAddL@$)Nyh zW1G16S-1@~e*?a!_rHlk7!CiRLOg{^s_-Y=I}D&svI(`py{P`EsVgl=13kB`G1Bs5ELQOn`G580z;}mLw54Z=7KZCjW6>09r!Uar`<>L%K|Ih?5;sw*>Y(yRCN7Q#^9QC^XiQ3SdLRM2~ z(@_s*doIOL>gv~n#i(2;MJ@DFaBcWy-}Ycs#Jj$^!LEoLp9KdaQhf)4BN2VR=3rN3 zwJ#%hCo(mEHlri?uYX!e|2p|!`>^Exya_wKdKZ4!R~$9r3oeZ*>1&QDPwe}~-<$M5 D#(xrt delta 2617 zcmXZcdrZ}39LMqRQRIMt91TRgz`+ZN7ebK)L`^Z1xU?E9%o{TA5Jcpf3j8p&xz-3h z&6-)RsV!)8O|)dovBcKe+|2sJrK6&?FqaLQm0OX$Kb+_6ob!5~=lA@c%lG;Iem7eB zTG~&0H!{FF*HD9Fx$qKBMbCKx{nWeN_0Mq%^{dF(b{iw`K2F48jKzfUX6((< zQ2n!TGM3;3+&y74e-2PZKNyHP8?g<8N*$k*=hrwIIuJ2Aj$wYV2kaR7Cn zpH8JX4%NOMwa_Na#{C|JlN2ssB32}XcT|JwxDRy{t*9etbJvgK5cN*f!cK6r`k!`o zU<38Dt{!A}>Ng9u(fRx_rFpAdLnSIy^~k2I1sU7gQ60~q&a4|1+RK=P*HA|=fJEK? zcJ(MOYMe=^_Bl8Um$>%L$T*%gQYhm>D{80LP-oMJ^KlS$W+`N%&M*(_umTm*D>xm0 zMjf4>KP6onF2pss75Cw**pCNs2ZJUvzul#v(D@mC494PWoPcUyi;BcXcfAqkQQw2w z;RmRlUBox>dz^udWN;zAh3bC`gBUf>?)p{SLj5+DU}?~7HXg@0*o)pH6n>}hFs6|5+R19v4r-n4 zIGXx-R90Wa9PB~Hwm)5aBIm%@rt+s;S&r(z#?_xfC1E8hvQ^WGze2v12JNKAUD%EH zd^}FLiT3)LW=ruJDoNv5rFJ|OX|fDdgvwA8Z$nK~j|^ciquwXSQ5*gg391du^1?fb zOb@T90LO4)1#0C_;4Un4?cJ#4>_PI#zClg=8!AU42%{E|j5OJF)R7gTBDDdP)XkWQ zA9)n!QMl>!b3l3u7NG`OiJGVw_55!|MW6w-vsTnmokA__OXp40EBG!dNt38VVg@pm zWuX@ARZ`#`Vb3E`u>-gmJ5Wj1?;J)wPRV2r$89CJ2F?P>3hQXdM}_DZYQRsh5HI0b^bt3O@?+G>ub^Hm-=QLO2Ni(`;;IRf zFr6IAK`m@O2Oo`FP~+F(AwB=QDMZom4=ThFS>dD#U^?|2)K1o;7TDshzlS=4UgX_l zzo5o>fB}qJ5YCNcRPrrAEwl`^ksX-G{MJN4D?f@v$IhSzzK-#D4`0Iw;;#YTK=tpy zZ2SzhfI-ytXd2(g8A$N#3)HxOAn!U$;oL|I%R^5qtETV@dbk2d@o*o-Rj7e)ph7r^ z3f+Ay#Rsmv^wIERRe_4YA!I0PLyh0-uK$Qb)B_|KL9$V~#Q$*$*||329#n{Xa6kTl z+i`PV_)Yc|)=|&owOEDkB4gTrNPbz)l5locp^oe@>dZSa4$osHUPdi!N&)e2qL5n< zp6CKDr#_9h4RhNDd<>5v>0vieIpJRx9v~AH(qhybavLf_yKo~mpf>b1>b)|EdR+fP zEogEsvnjN*Q8#8e7o%R0%TPBKqH>`KHPPBo(b!(!giu_}0pGsRk(jx@BcV$%sXhz! z#dPt1B=%X~#L%y?sW~suJC>h5nn|B_ep*JgDtun#w{xUKcHyS3rEx>P(ZT#+C^LSU UFW6NZzdC7DFu&_u`k6`p1LrIfaR2}S diff --git a/locale/es_ES/LC_MESSAGES/Studs.po b/locale/es_ES/LC_MESSAGES/Studs.po index 0a0ba51..656842d 100644 --- a/locale/es_ES/LC_MESSAGES/Studs.po +++ b/locale/es_ES/LC_MESSAGES/Studs.po @@ -130,7 +130,7 @@ msgstr "Usted no habia llenado la primera pagina dela encuesta" #: choix_autre.php:63 #: adminstuds.php:79 #: adminstuds.php:1044 -msgid "Back to the homepage of " +msgid "Back to the homepage of" msgstr "Retroceder al inicio de" #: choix_date.php:220 @@ -612,8 +612,8 @@ msgstr "" "Usted puede cambiar su encuesta al enlace siguiente" #: adminstuds.php:582 -msgid "As poll administrator, you can change all the lines of this poll with this button : " -msgstr "En calidad de administrador, Usted puede cambiar todas la líneas de este encuesta con este botón :" +msgid "As poll administrator, you can change all the lines of this poll with this button" +msgstr "En calidad de administrador, Usted puede cambiar todas la líneas de este encuesta con este botón" msgid "Edit" msgstr "Cambio" diff --git a/locale/fr_FR/LC_MESSAGES/Studs.mo b/locale/fr_FR/LC_MESSAGES/Studs.mo index dd5ee79dc0a111d3d6cf041b384e39755ff1bf7c..656e53e83ed91d843ba41edc09649f50aa9cebac 100644 GIT binary patch delta 4437 zcmYk;3v`cV0LSs?ZrS$#%-{*f$@A3P8p6B(x&-=X3FY@9LIVG>4QH*Ac3?D+zWrv3m9 z!Krb^G2s*%>|Y$iQ0iwe63<&NVN2@&pc;s8;XdGcREM%q?exLc*bnt0<1ik}tjkgN zZ$p|g2UA4GNJ0_yr} z$R88M@Mt7cF$L2d3L2_`s2hq=H#~_NiE^Y*W&x^!TGYtAfqH{OwtgDb!EaC_@*}Ff zE7%<489s`p1M0TjZfoD>d)guyo!3`@eGF^ zJl|T4>hL<$i|ocRxF6Min?z&Q@E9|nf)+_9x~m&9Q9bR4SvU$cB9*AcxE9smX4J@R zxAg|ph#WzU=vmZ#-`c-DJJ@R2=#+SV_j zI&cMbUnIk)DM&#E&7@g#QERFgHPQ}h3KnA&&o|W+G;|wu0(YTS=|NOOr%(^Nh?@Ir zsJV-5%a+4r)b-s^_xDBpeG#VO1k{KvLS0vdYHvMin$2zsYUrf(D^vr&+q#zppf^lJ zb+oIk--c@N9?Zls*afSQ(KYX21)jxZe3+jO_yV#F%(i6aUvvCEC)Ds2d>zACQMtGW z=iy&ij%s7&(Dn*#zN?U*_ek@913c9 z7Z%|eycKWk%Q>H*JS6I_UTa5d__ov0!I96O_zlNzBc^x{C&2o<3g@o-ef9>Q#N zCQ@K}Of81v+sG)J!^rfT?@)8^O?OA8HEQTGQ4Qx|81}REf%t)k?>p}0e9{fZ%)!&B zcJI${x93b`${n+i0^bm`0@d(NRL>7ukJksII>>MC#arYK{cQ~rtKPodSE&-%I0ol z`b{Zn?W{#T=q&1s`V(rZLU;&$GL2C$oP&<$Q4y795WtEdrZ z+1;2O*cNBt3DgJ;UZkE7mnE^0B?pr&RYZp1_Q6qek~XC1%5NSvL+_^U@%IqsX* z;qBDxF&_U$4OPr7?hv-YSn4UL?Uaq$j=89IMk1qa9>XTM2DRO`;1b-9>R2y60=hrn zp`iUb7&U|?w!Q%Mk5Csc`Y;W64A)~~t}#A5fNFRMPbtMmQA7DPhT)H>sreO$ zVF(LoI*z~s{0z&n-5u_t+ko0_e)RHu^Dc$Fc#x#oP?Lrd6dF~{rDK*NmPSgo~rH93bl&UP#w%d zb)*RSCYdtSeLHa^eurMn=e5Id5NeedVj~=lLvbwXMRpf3{-G4kaUumTU@C_9clUJ$ zYUp!Oi*E$#`pKvVJYnml=%KD-HPN)`;C%weG=682eWWo7Cpsn=-|XmE=Ov0&WDQ}m z%vhph9eJ5dA&(FpZ<8`|KM5Xn6j(HYe~6j8z$7sCfnyfGACZUMYG8$^xPUxF?$I8& zS7$gDlT{>{yh!dQw-61YR>nM{qtYetJD=a3M7vzan`AWUOqh?rf55=JN;;6&NfOcV z2FcML@Ka#po5|!b2_EdVz%e3t!di&hWX}*ygpR$W6UieV5G}djq1CaT+)Ub#2gowg zmgxCrKhc^zPL7c+BzWwiu!!g@p!NGK*-e%cEyF>io@^yLw6x-gmi7_Chahn5;P;>{ z>zTDg`^5Q>pY3ER(V^Wun3NM%WZ-z7Uw!YMa;t&gr}^zjHvjJ&pFQ&gd55Hvx5z8R zOL~)R(u}-7#*kRe?j{PEq`z-gbeyj;I@DQ9O-E~&!0!xOZi%^MgRS3WEy34FKAA%f z5gpoDX`~&|7c-JHV;Bl9xWHzPvU*H{65x@2wRVlO}lhy+O%P7!`gvkll_BYdU^a?V{<&d3vq@1oEAAPd{fd^ k`zm7F`XkayL;PDarh5EIU56$5rWG{!$}>`Z-TUABA23hHYybcN delta 4439 zcmYk;3v|w90LSs?wF_exww0M_?`GK6$i`S|E@8Gt88#}kTw+L3kzD?B8=KTv<&q*w zncHe=QIbnBm!zEI9G7lKJLDYQbt=^N_x_*voSx(NexB#=|33fc|6E>ftn`#sc`EOA zyvCS{NMl;yRt&|x*anYcQ@n(Y@iz>>e^B@RYYmMurWNg07=m5!R?Nm`I1HO$vAte` z&1siL8OIEvvVsf2c+vjF6%3?(9mCNR?b;k;Xvd>E$U;3J4>h1dR6k>|HI|@WWHH`? zo2S!be;j^gwOHprLiE&tMJ&XyoFQNt# z%yj7fMC6jmK+R;XLnV>QK-8N&j{3rE)E8EvX5uYmY-Ss(gZ-$PIfHtE2HXA{HNcRT z?ub_m*sKZaG=mBR@9sOzzV!`!*7}WJt z)Ej1_23la-qfs4B$IiGAJK`>6_RaUW3~!~ zz41JjVH=LhB76h&y%c&Gk9|>ZwgolyJ5U4Pg(LAZ)O~G}+$AW-F|=!v9CzeV%#Xg9 zgxZ9usF~@4I%c`3DIJcL+$P>cMrW?|p@u^6Qw2sa)hhnL=!gPoQS#8Pq18 ziyD}-lu9O*=aA(w2QV1FM`qbvMy+`$KZ}|XFKVqbQ61)B5a!!<0Uq_R32_hC6K-ce z;CWPk#c9ScMzau`@qDwDiq^ai`7JSrP!G6(8u?Z0HGBOgYCsXZF5AMiMJ-K##P2)}u!L4{FnRI=f5K0o6e#)Bt;- z9ylDCZ8HZowVP3U=X2D9Lg-Y#sI5^;mX3_gbVEmPJf4cyW*Ua#i`WETM?I(-we|;4 zQ-20IQRWJ^z=#a@{sh#UrlR`GLmks8s7+ah>h~Sg_x5Bk|6x>)bAb(S&SE)wx)}2s zE<^3&)UNIf^v9jF2jU#Oj+&uaOrHj}9`&ZRsLfoDTAIta8Gpg2adkId4#T@M|KU_> zy1OIVhtaf8;XT-Zw_r+^yEl5FrZ68PaWLvQjYS>Dsi-%rKxW^p!w@`yI&Nq11w4lu z*kp%a0d?>sYO3a;rf{`w*P;FqI)$2vOV}I(Sl}3p##Y!7HMIj!_Ybz$Cm<)!%tyV* zcGQCpVk|nxsHlSm)ECWNZo4IF3e!;!DnK2tNvJnpVy~}7%~-AVh`oLR`D3o}p*@yy zw|iet)Psj&OP&9zRJ4X=7>C=?i}k1n|7Z=!c8^;eYKqfP1MZ1z15=27umbf$$8jw- zpiag7p6({xf;u&)@phg6zo=-0?RxPqA*SPC{1Z1~Zf}kzUO{#2@RVn84QeVQ*(gC6 zi&`2l7GXNh#-*5xfqmV7yau86+?N>2^UZfu)X`N;z-y>Ci|OZj2M(Z}gIdeyQKw}O zYAU}&&B%4sX$tS}ZnikoIrm!c$APrx;Rrm2&J-$1IqXDSfoynl1Jz+BPt`~VpmuQ) zYJkP4fh<6Nqs$J}_rAtacq^~l7@xu*oP*lr3$PI`$3m>kW&ZUh4O|GsusrvNBNBC< zGf`8XhuU;wQTNS2bv)a)=c9+V%4_6BU(KC0Ri7f7>5oVV(cn}j_^!Hj-|Cyb*=Xsq&Lyjvm(B8&rJKu0zQwEiEh&j*Qit~$atcS zH*t0sO%+=krSkzR1<%Bm&$UYqxJx4O+Fy2NM~{%*-f?)l@27DXrrre+I^*l&jbGT zFQu`bXg41tJBZG_icUfSSxnexzA}%`J!FR4^nK3cvmM#;zia$W&7=wG zMY_fD5k|_%BP5EvP14D|RS98HRh`2Eo!4op=x%?RYb!C>hrDUq8P>_TljM*^{Wu{3T!iHD5?;I?<^OCxPT?GKUnAWuz6+&rwq{OG9@$QcENU ziAooeMm|-85=7o2`$<=#(uh3ns~NKo$C4prHR(b8$TR)8JNT_W`)@HXD

            {_('As poll administrator, you can change all the lines of this poll with this button')} {_('Edit')}, - {_(' remove a column or a line with')} {_('Remove')} + {_('remove a column or a line with')} {_('Remove')} {_('and add a new column with')} {_('Add a column')}.

            {_('Finally, you can change the informations of this poll like the title, the comments or your email address.')}

            From 313c1225d021bafaff17db17ccd59cafe9239d70 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 1 Jan 2015 23:06:35 +0100 Subject: [PATCH 087/151] Vote pages: display number of votes below every slot --- tpl/part/vote_table_classic.tpl | 10 +++++----- tpl/part/vote_table_date.tpl | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/tpl/part/vote_table_classic.tpl b/tpl/part/vote_table_classic.tpl index ecddafb..bf0a0d2 100644 --- a/tpl/part/vote_table_classic.tpl +++ b/tpl/part/vote_table_classic.tpl @@ -145,9 +145,9 @@ {foreach $best_choices as $best_choice} {if $max == $best_choice} {$count_bests = $count_bests +1} - {$max} + {$best_choice} {else} - + {$best_choice} {/if} {/foreach} @@ -165,11 +165,11 @@ {if $count_bests == 1}

            {_("Best choice")}

            -

            {_("The best choice at this time is:")}

            +

            {_('The best choice at this time is:')}

            {elseif $count_bests > 1}

            {_("Best choices")}

            -

            {_("The bests choices at this time are:")}

            +

            {_('The bests choices at this time are:')}

            {/if} @@ -182,7 +182,7 @@ {$i = $i+1} {/foreach}
          -

          {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

          +

          {_('with')} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

    {/if} \ No newline at end of file diff --git a/tpl/part/vote_table_date.tpl b/tpl/part/vote_table_date.tpl index 5faacaa..0fdb8fc 100644 --- a/tpl/part/vote_table_date.tpl +++ b/tpl/part/vote_table_date.tpl @@ -175,9 +175,9 @@ {foreach $best_choices as $best_moment} {if $max == $best_moment} {$count_bests = $count_bests +1} - {$max} + {$best_moment} {else} - + {$best_moment} {/if} {/foreach} @@ -195,11 +195,11 @@ {if $count_bests == 1}

    {_("Best choice")}

    -

    {_("The best choice at this time is:")}

    +

    {_('The best choice at this time is:')}

    {elseif $count_bests > 1}

    {_("Best choices")}

    -

    {_("The bests choices at this time are:")}

    +

    {_('The bests choices at this time are:')}

    {/if} @@ -214,7 +214,7 @@ {/foreach} {/foreach} -

    {_("with")} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

    +

    {_('with')} {$max} {if $max==1}{_('vote')}{else}{_('votes')}{/if}.

    {/if} \ No newline at end of file From a8345cf7f8295c9a946fa7527704e2267134e942 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Thu, 1 Jan 2015 23:24:17 +0100 Subject: [PATCH 088/151] Parse markdown on classic votes --- app/classes/Framadate/Utils.php | 69 ++++++++++++++++++++++----------- app/inc/init.php | 1 + tpl/part/vote_table_classic.tpl | 2 +- 3 files changed, 49 insertions(+), 23 deletions(-) diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index 190c830..b69f5d7 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -18,20 +18,18 @@ */ namespace Framadate; -class Utils -{ - public static function get_server_name() - { +class Utils { + public static function get_server_name() { $scheme = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https' : 'http'; $port = in_array($_SERVER['SERVER_PORT'], [80, 443]) ? '' : ':' . $_SERVER['SERVER_PORT']; $dirname = dirname($_SERVER['SCRIPT_NAME']); $dirname = $dirname === '\\' ? '/' : $dirname . '/'; $server_name = $_SERVER['SERVER_NAME'] . $port . $dirname; - return $scheme . '://' . str_replace('/admin','',str_replace('//','/',str_replace('///','/',$server_name))); + + return $scheme . '://' . str_replace('/admin', '', str_replace('//', '/', str_replace('///', '/', $server_name))); } - public static function is_error($cerr) - { + public static function is_error($cerr) { global $err; if ($err == 0) { return false; @@ -40,8 +38,7 @@ class Utils return ($err & $cerr) != 0; } - public static function is_user() - { + public static function is_user() { return (USE_REMOTE_USER && isset($_SERVER['REMOTE_USER'])) || isset($_SESSION['nom']); } @@ -49,16 +46,15 @@ class Utils * @param string $title * @deprecated */ - public static function print_header($title = '') - { + public static function print_header($title = '') { global $lang; echo ' - + '; - if (! empty($title)) { + if (!empty($title)) { echo '' . stripslashes($title) . ' - ' . NOMAPPLICATION . ''; } else { echo '' . NOMAPPLICATION . ''; @@ -73,9 +69,9 @@ class Utils - + '; - if (file_exists($_SERVER['DOCUMENT_ROOT']."/nav/nav.js")) { + if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/nav/nav.js")) { echo ''; } @@ -89,23 +85,22 @@ class Utils /** * Check if an email address is valid using PHP filters * - * @param string $email Email address to check + * @param string $email Email address to check * @return bool True if valid. False if not valid. * @deprecated */ - public static function isValidEmail($email) - { + public static function isValidEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL); } /** * Fonction permettant de générer les URL pour les sondage - * @param string $id L'identifiant du sondage - * @param bool $admin True pour générer une URL pour l'administration d'un sondage, False pour un URL publique + * + * @param string $id L'identifiant du sondage + * @param bool $admin True pour générer une URL pour l'administration d'un sondage, False pour un URL publique * @return string L'url pour le sondage */ - public static function getUrlSondage($id, $admin = false) - { + public static function getUrlSondage($id, $admin = false) { if (URL_PROPRE) { if ($admin === true) { $url = str_replace('/admin', '', self::get_server_name()) . $id . '/admin'; @@ -125,6 +120,7 @@ class Utils /** * This method pretty prints an object to the page framed by pre tags. + * * @param mixed $object The object to print. */ public static function debug($object) { @@ -136,4 +132,33 @@ class Utils public static function table($tableName) { return TABLENAME_PREFIX . $tableName; } + + public static function markdown($md) { + preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/', $md, $md_a_img); // Markdown [![alt](src)](href) + preg_match_all('/!\[(.*?)\]\((.*?)\)/', $md, $md_img); // Markdown ![alt](src) + preg_match_all('/\[(.*?)\]\((.*?)\)/', $md, $md_a); // Markdown [text](href) + if (isset($md_a_img[2][0]) && $md_a_img[2][0] != '' && isset($md_a_img[3][0]) && $md_a_img[3][0] != '') { // [![alt](src)](href) + + $text = stripslashes($md_a_img[1][0]); + $html = '' . $text . ''; + + } elseif (isset($md_img[2][0]) && $md_img[2][0] != '') { // ![alt](src) + + $text = stripslashes($md_img[1][0]); + $html = '' . $text . ''; + + } elseif (isset($md_a[2][0]) && $md_a[2][0] != '') { // [text](href) + + $text = stripslashes($md_a[1][0]); + $html = '' . $text . ''; + + } else { // text only + + $text = stripslashes($md); + $html = $text; + + } + + return $html; + } } diff --git a/app/inc/init.php b/app/inc/init.php index 2989a0e..e72a8cb 100644 --- a/app/inc/init.php +++ b/app/inc/init.php @@ -45,6 +45,7 @@ $smarty->assign('langs', $ALLOWED_LANGUAGES); $smarty->assign('date_format', $date_format); function smarty_modifier_poll_url($poll_id, $admin=false){return Utils::getUrlSondage($poll_id, $admin);} +function smarty_modifier_markdown($md) {return Utils::markdown($md);} // End- Smarty if (session_id() == '') { diff --git a/tpl/part/vote_table_classic.tpl b/tpl/part/vote_table_classic.tpl index bf0a0d2..b1b9bdb 100644 --- a/tpl/part/vote_table_classic.tpl +++ b/tpl/part/vote_table_classic.tpl @@ -25,7 +25,7 @@ {foreach $slots as $id=>$slot} - {$slot->title} + {$slot->title|markdown} {/foreach} From ca365ff34895f93dd06ee8c33b2ccb6eb395d357 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Fri, 2 Jan 2015 00:19:56 +0100 Subject: [PATCH 089/151] Fix the selected item on langs selection --- app/inc/i18n.php | 26 ++++++++++++-------------- app/inc/init.php | 17 +++++++++-------- bandeaux.php | 2 +- tpl/header.tpl | 4 ++-- 4 files changed, 24 insertions(+), 25 deletions(-) diff --git a/app/inc/i18n.php b/app/inc/i18n.php index 829206c..447518f 100644 --- a/app/inc/i18n.php +++ b/app/inc/i18n.php @@ -37,14 +37,14 @@ if (isset($_POST['lang']) && is_string($_POST['lang']) && in_array($_POST['lang' } $locale = $mlocale . '.utf8';//unix format -if (strtoupper(substr(PHP_OS,0,3))=='WIN'){ - putenv("LC_ALL=$mlocale"); //Windows env. needed to switch between languages - switch ($mlocale){ - case 'fr_FR' : $locale = "fra";break; //$locale in windows locale format, needed to use php function that handle text : strftime() - case 'en_GB' : $locale = "english";break; //see http://msdn.microsoft.com/en-us/library/39cwe7zf%28v=vs.90%29.aspx - case 'de_DE' : $locale = "deu";break; - case 'es_ES' : $locale = "esp";break; - } +if (strtoupper(substr(PHP_OS,0,3))=='WIN'){ + putenv("LC_ALL=$mlocale"); //Windows env. needed to switch between languages + switch ($mlocale){ + case 'fr_FR' : $locale = "fra";break; //$locale in windows locale format, needed to use php function that handle text : strftime() + case 'en_GB' : $locale = "english";break; //see http://msdn.microsoft.com/en-us/library/39cwe7zf%28v=vs.90%29.aspx + case 'de_DE' : $locale = "deu";break; + case 'es_ES' : $locale = "esp";break; + } } putenv('LANGUAGE=');//sert à quoi? @@ -66,14 +66,12 @@ $lang = ($_SESSION['langue']!='') ? strtolower($_SESSION['langue']) : 'fr'; /* Date Format */ -$date_format['txt_full'] = _("%A, den %e. %B %Y"); //summary in choix_date.php and removal date in choix_(date|autre).php -$date_format['txt_short'] = "%A %e %B %Y"; // radio title -$date_format['txt_day'] = "%a %e"; -$date_format['txt_date'] = _("%Y-%m-%d"); +$date_format['txt_full'] = _('%A, den %e. %B %Y'); //summary in choix_date.php and removal date in choix_(date|autre).php +$date_format['txt_short'] = _('%A %e %B %Y'); // radio title +$date_format['txt_day'] = _('%a %e'); +$date_format['txt_date'] = _('%Y-%m-%d'); if (strtoupper(substr(PHP_OS,0,3))=='WIN'){ //%e can't be used on Windows platform, use %#d instead foreach($date_format as $k => $v) { $date_format[$k] = preg_replace('#(?template_dir = 'tpl/'; -$smarty->compile_dir = 'tpl_c/'; -$smarty->cache_dir = 'cache/'; +$smarty->setTemplateDir('tpl/'); +$smarty->setCompileDir('tpl_c/'); +$smarty->setCacheDir('cache/'); $smarty->caching = false; $smarty->assign('APPLICATION_NAME', NOMAPPLICATION); @@ -48,9 +53,5 @@ function smarty_modifier_poll_url($poll_id, $admin=false){return Utils::getUrlSo function smarty_modifier_markdown($md) {return Utils::markdown($md);} // End- Smarty -if (session_id() == '') { - session_start(); -} - $connect = new FramaDB(DB_CONNECTION_STRING, DB_USER, DB_PASSWORD); $err = 0; diff --git a/bandeaux.php b/bandeaux.php index 534bd43..1befbbb 100644 --- a/bandeaux.php +++ b/bandeaux.php @@ -28,7 +28,7 @@ function bandeau_titre($titre) echo '
    '; if(count($ALLOWED_LANGUAGES)>1){ - echo ' + echo '
    diff --git a/tpl/header.tpl b/tpl/header.tpl index 58195c5..a0ca4de 100644 --- a/tpl/header.tpl +++ b/tpl/header.tpl @@ -1,10 +1,10 @@
    {if count($langs)>1} - +
    From 8f8956d70a9be5c9634ab10239bea280dbfc8b4e Mon Sep 17 00:00:00 2001 From: "Olivier Perez [a570709]" Date: Fri, 2 Jan 2015 09:08:07 +0100 Subject: [PATCH 090/151] Migration: Add precondition on every Migration sub-classes --- .../Migration/From_0_0_to_0_8_Migration.php | 18 ++++++++++++++++++ .../Migration/From_0_8_to_0_9_Migration.php | 16 ++++++++++++++++ app/classes/Framadate/Migration/Migration.php | 9 +++++++++ migration.php | 2 +- 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/app/classes/Framadate/Migration/From_0_0_to_0_8_Migration.php b/app/classes/Framadate/Migration/From_0_0_to_0_8_Migration.php index 121e389..dbdb59e 100644 --- a/app/classes/Framadate/Migration/From_0_0_to_0_8_Migration.php +++ b/app/classes/Framadate/Migration/From_0_0_to_0_8_Migration.php @@ -1,11 +1,29 @@ query('SHOW TABLES'); + $tables = $stmt->fetchAll(\PDO::FETCH_COLUMN); + + // Check if there is no tables but the MIGRATION_TABLE one + $diff = array_diff($tables, [Utils::table(MIGRATION_TABLE)]); + return count($diff) === 0; + } + /** * This methode is called only one time in the migration page. * diff --git a/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php b/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php index 33f1185..ea69991 100644 --- a/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php +++ b/app/classes/Framadate/Migration/From_0_8_to_0_9_Migration.php @@ -13,6 +13,22 @@ class From_0_8_to_0_9_Migration implements Migration { function __construct() { } + /** + * This method could check if the execute method should be called. + * It is called before the execute method. + * + * @param \PDO $pdo The connection to database + * @return bool true is the Migration should be executed. + */ + function preCondition(\PDO $pdo) { + $stmt = $pdo->query('SHOW TABLES'); + $tables = $stmt->fetchAll(\PDO::FETCH_COLUMN); + + // Check if tables of v0.8 are presents + $diff = array_diff(['sondage', 'sujet_studs', 'comments', 'user_studs'], $tables); + return count($diff) === 0; + } + /** * This methode is called only one time in the migration page. * diff --git a/app/classes/Framadate/Migration/Migration.php b/app/classes/Framadate/Migration/Migration.php index e6d0eb9..b68362b 100644 --- a/app/classes/Framadate/Migration/Migration.php +++ b/app/classes/Framadate/Migration/Migration.php @@ -3,6 +3,15 @@ namespace Framadate\Migration; interface Migration { + /** + * This method could check if the execute method should be called. + * It is called before the execute method. + * + * @param \PDO $pdo The connection to database + * @return bool true is the Migration should be executed. + */ + function preCondition(\PDO $pdo); + /** * This methode is called only one time in the migration page. * diff --git a/migration.php b/migration.php index 70d7c6d..2617b84 100644 --- a/migration.php +++ b/migration.php @@ -57,7 +57,7 @@ foreach ($migrations as $migration) { $executed = $selectStmt->rowCount(); $selectStmt->closeCursor(); - if (!$executed) { + if (!$executed && $migration->preCondition($pdo)) { $migration->execute($pdo); if ($insertStmt->execute([$className])) { $countSucceeded++; From 985842edf315521348ba111f8c1f1bc90e3c73ea Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sat, 3 Jan 2015 17:24:39 +0100 Subject: [PATCH 091/151] CSV Export: Implements export for classical polls --- adminstuds.php | 2 +- .../Framadate/Services/PollService.php | 2 +- app/classes/Framadate/Utils.php | 19 ++- exportcsv.php | 148 ++++++++++-------- old_exportcsv.php | 104 ++++++++++++ studs.php | 3 +- tpl/part/poll_info.tpl | 2 +- 7 files changed, 207 insertions(+), 73 deletions(-) create mode 100644 old_exportcsv.php diff --git a/adminstuds.php b/adminstuds.php index cc8aefd..9883e42 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -339,7 +339,7 @@ if (isset($_POST['confirm_add_slot'])) { // Retrieve data $slots = $pollService->allSlotsByPollId($poll_id); -$votes = $pollService->allUserVotesByPollId($poll_id); +$votes = $pollService->allVotesByPollId($poll_id); $comments = $pollService->allCommentsByPollId($poll_id); diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 0a21824..828be5a 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -50,7 +50,7 @@ class PollService { return $this->connect->allCommentsByPollId($poll_id); } - function allUserVotesByPollId($poll_id) { + function allVotesByPollId($poll_id) { return $this->connect->allUserVotesByPollId($poll_id); } diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index b69f5d7..1cad76f 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -133,7 +133,7 @@ class Utils { return TABLENAME_PREFIX . $tableName; } - public static function markdown($md) { + public static function markdown($md, $clear) { preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/', $md, $md_a_img); // Markdown [![alt](src)](href) preg_match_all('/!\[(.*?)\]\((.*?)\)/', $md, $md_img); // Markdown ![alt](src) preg_match_all('/\[(.*?)\]\((.*?)\)/', $md, $md_a); // Markdown [text](href) @@ -159,6 +159,21 @@ class Utils { } - return $html; + return $clear ? $text : $html; + } + + public static function csvEscape($text) { + $escaped = str_replace('"', '""', $text); + $escaped = str_replace("\r\n", '', $escaped); + $escaped = str_replace("\n", '', $escaped); + + return '"' . $escaped . '"'; + } + + public static function cleanFilename($title) { + $cleaned = preg_replace('[^a-zA-Z0-9._-]', '_', $title); + $cleaned = preg_replace(' {2,}', ' ', $cleaned); + + return $cleaned; } } diff --git a/exportcsv.php b/exportcsv.php index fd868bf..34b4155 100644 --- a/exportcsv.php +++ b/exportcsv.php @@ -16,89 +16,103 @@ * Auteurs de STUdS (projet initial) : Guilhem BORGHESI (borghesi@unistra.fr) et Raphaël DROZ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ -namespace Framadate; +use Framadate\Services\LogService; +use Framadate\Services\PollService; +use Framadate\Services\InputService; +use Framadate\Services\MailService; +use Framadate\Message; +use Framadate\Utils; include_once __DIR__ . '/app/inc/init.php'; -if(!isset($_GET['numsondage']) || ! preg_match(";^[\w\d]{16}$;i", $_GET['numsondage'])) { - header('Location: studs.php'); +ob_start(); + +/* Variables */ +/* --------- */ + +$poll_id = null; +$poll = null; + +/* Services */ +/*----------*/ + +$logService = new LogService(LOG_FILE); +$pollService = new PollService($connect, $logService); + +/* PAGE */ +/* ---- */ + +if (!empty($_GET['poll'])) { + $poll_id = filter_input(INPUT_GET, 'poll', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^[a-z0-9]+$/']]); + $poll = $pollService->findById($poll_id); } -$sql = 'SELECT * FROM user_studs WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_users'; -$sql = $connect->Prepare($sql); -$user_studs = $connect->Execute($sql, array($_GET['numsondage'])); +if (!$poll) { + $smarty->assign('error', 'This poll doesn\'t exist'); + $smarty->display('error.tpl'); + exit; +} -$dsondage = Utils::get_sondage_from_id($_GET['numsondage']); -$nbcolonnes=substr_count($dsondage->sujet,',')+1; -$toutsujet=explode(",",$dsondage->sujet); +$slots = $pollService->allSlotsByPollId($poll_id); +$votes = $pollService->allVotesByPollId($poll_id); -//affichage des sujets du sondage -$input =","; -foreach ($toutsujet as $value) { - if ($dsondage->format=="D"||$dsondage->format=="D+") { - if (strpos($dsondage->sujet,'@') !== false) { - $days=explode("@",$value); - $input.= '"'.date("j/n/Y",$days[0]).'",'; - } else { - $input.= '"'.date("j/n/Y",$values).'",'; - } - } else { +// CSV header +if ($poll->format === 'D') { + $titles_line = ','; + $moments_line = ','; + foreach ($slots as $slot) { + $title = Utils::csvEscape(strftime($date_format['txt_date'], $slot->title)); + $moments = explode(',', $slot->moments); - preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$value,$md_a_img); // Markdown [![alt](src)](href) - preg_match_all('/!\[(.*?)\]\((.*?)\)/',$value,$md_img); // Markdown ![alt](src) - preg_match_all('/\[(.*?)\]\((.*?)\)/',$value,$md_a); // Markdown [text](href) - if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) - $subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); - } elseif (isset($md_img[2][0]) && $md_img[2][0]!='') { // ![alt](src) - $subject_text = (isset($md_img[1][0]) && $md_img[1][0]!='') ? stripslashes($md_img[1][0]) : _("Choice") .' '.($i+1); - } elseif (isset($md_a[2][0]) && $md_a[2][0]!='') { // [text](href) - $subject_text = (isset($md_a[1][0]) && $md_a[1][0]!='') ? stripslashes($md_a[1][0]) : _("Choice") .' '.($i+1); - } else { // text only - $subject_text = stripslashes($value); - } - $input.= '"'.html_entity_decode($subject_text).'",'; + $titles_line .= str_repeat($title . ',', count($moments)); + $moments_line .= implode(',', array_map('\Framadate\Utils::csvEscape', $moments)) . ','; } -} - -$input.="\r\n"; - -if (strpos($dsondage->sujet,'@') !== false) { - $input.=","; - foreach ($toutsujet as $value) { - $heures=explode("@",$value); - $input.= '"'.$heures[1].'",'; + echo $titles_line . "\r\n"; + echo $moments_line . "\r\n"; +} else { + echo ','; + foreach ($slots as $slot) { + echo Utils::markdown($slot->title, true) . ','; } - - $input.="\r\n"; + echo "\r\n"; } +// END - CSV header -while ( $data=$user_studs->FetchNextObject(false)) { - // Le nom de l'utilisateur - $nombase=html_entity_decode(str_replace("°","'",$data->nom)); - $input.= '"'.$nombase.'",'; - //affichage des resultats - $ensemblereponses=$data->reponses; - for ($k=0;$k<$nbcolonnes;$k++) { - $car=substr($ensemblereponses,$k,1); - switch ($car) { - case "1": $input .= '"'._('Yes').'",'; $somme[$k]++; break; - case "2": $input .= '"'._('Ifneedbe').'",'; break; - default: $input .= '"'._('No').'",'; break; +// Vote lines +foreach ($votes as $vote) { + echo Utils::csvEscape($vote->name) . ','; + $choices = str_split($vote->choices); + foreach ($choices as $choice) { + switch ($choice) { + case 0: + $text = _('No'); + break; + case 1: + $text = _('Ifneedbe'); + break; + case 2: + $text = _('Yes'); + break; + default: + $text = 'unkown'; } + echo Utils::csvEscape($text); + echo ','; } - - $input.="\r\n"; + echo "\r\n"; } +// END - Vote lines -$filesize = strlen( $input ); -$filename=$_GET["numsondage"].".csv"; +// HTTP headers +$content = ob_get_clean(); +$filesize = strlen($content); +$filename = Utils::cleanFilename($poll->title) . '.csv'; -header( 'Content-Type: text/csv; charset=utf-8' ); -header( 'Content-Length: '.$filesize ); -header( 'Content-Disposition: attachment; filename="'.$filename.'"' ); -header( 'Cache-Control: max-age=10' ); +header('Content-Type: text/csv; charset=utf-8'); +header('Content-Length: ' . $filesize); +header('Content-Disposition: attachment; filename="' . $filename . '"'); +header('Cache-Control: max-age=10'); +// END - HTTP headers -echo str_replace('"','""',$input); - -die(); +echo $content; diff --git a/old_exportcsv.php b/old_exportcsv.php new file mode 100644 index 0000000..fd868bf --- /dev/null +++ b/old_exportcsv.php @@ -0,0 +1,104 @@ +Param('numsondage').' ORDER BY id_users'; +$sql = $connect->Prepare($sql); +$user_studs = $connect->Execute($sql, array($_GET['numsondage'])); + +$dsondage = Utils::get_sondage_from_id($_GET['numsondage']); +$nbcolonnes=substr_count($dsondage->sujet,',')+1; + +$toutsujet=explode(",",$dsondage->sujet); + +//affichage des sujets du sondage +$input =","; +foreach ($toutsujet as $value) { + if ($dsondage->format=="D"||$dsondage->format=="D+") { + if (strpos($dsondage->sujet,'@') !== false) { + $days=explode("@",$value); + $input.= '"'.date("j/n/Y",$days[0]).'",'; + } else { + $input.= '"'.date("j/n/Y",$values).'",'; + } + } else { + + preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$value,$md_a_img); // Markdown [![alt](src)](href) + preg_match_all('/!\[(.*?)\]\((.*?)\)/',$value,$md_img); // Markdown ![alt](src) + preg_match_all('/\[(.*?)\]\((.*?)\)/',$value,$md_a); // Markdown [text](href) + if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) + $subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); + } elseif (isset($md_img[2][0]) && $md_img[2][0]!='') { // ![alt](src) + $subject_text = (isset($md_img[1][0]) && $md_img[1][0]!='') ? stripslashes($md_img[1][0]) : _("Choice") .' '.($i+1); + } elseif (isset($md_a[2][0]) && $md_a[2][0]!='') { // [text](href) + $subject_text = (isset($md_a[1][0]) && $md_a[1][0]!='') ? stripslashes($md_a[1][0]) : _("Choice") .' '.($i+1); + } else { // text only + $subject_text = stripslashes($value); + } + $input.= '"'.html_entity_decode($subject_text).'",'; + } +} + +$input.="\r\n"; + +if (strpos($dsondage->sujet,'@') !== false) { + $input.=","; + foreach ($toutsujet as $value) { + $heures=explode("@",$value); + $input.= '"'.$heures[1].'",'; + } + + $input.="\r\n"; +} + +while ( $data=$user_studs->FetchNextObject(false)) { + // Le nom de l'utilisateur + $nombase=html_entity_decode(str_replace("°","'",$data->nom)); + $input.= '"'.$nombase.'",'; + //affichage des resultats + $ensemblereponses=$data->reponses; + for ($k=0;$k<$nbcolonnes;$k++) { + $car=substr($ensemblereponses,$k,1); + switch ($car) { + case "1": $input .= '"'._('Yes').'",'; $somme[$k]++; break; + case "2": $input .= '"'._('Ifneedbe').'",'; break; + default: $input .= '"'._('No').'",'; break; + } + } + + $input.="\r\n"; +} + +$filesize = strlen( $input ); +$filename=$_GET["numsondage"].".csv"; + +header( 'Content-Type: text/csv; charset=utf-8' ); +header( 'Content-Length: '.$filesize ); +header( 'Content-Disposition: attachment; filename="'.$filename.'"' ); +header( 'Cache-Control: max-age=10' ); + +echo str_replace('"','""',$input); + +die(); diff --git a/studs.php b/studs.php index 2bda857..b7c91c8 100644 --- a/studs.php +++ b/studs.php @@ -35,6 +35,7 @@ $editingVoteId = 0; /* Services */ /*----------*/ + $logService = new LogService(LOG_FILE); $pollService = new PollService($connect, $logService); $inputService = new InputService(); @@ -161,7 +162,7 @@ if (isset($_POST['add_comment'])) { // Retrieve data $slots = $pollService->allSlotsByPollId($poll_id); -$votes = $pollService->allUserVotesByPollId($poll_id); +$votes = $pollService->allVotesByPollId($poll_id); $comments = $pollService->allCommentsByPollId($poll_id); diff --git a/tpl/part/poll_info.tpl b/tpl/part/poll_info.tpl index a8b8c8d..653048f 100644 --- a/tpl/part/poll_info.tpl +++ b/tpl/part/poll_info.tpl @@ -22,7 +22,7 @@
    - {_('Export to CSV')} + {_('Export to CSV')} {if $admin}
    -

    ' . _('Your poll will be automatically removed after') . ' ' . $config['default_poll_duration'] . ' ' . _('days') . '.
    ' . _("You can fix another removal date for it.") . '

    +

    ' . _('Your poll will be automatically removed after') . ' ' . $config['default_poll_duration'] . ' ' . _('days') . '.
    ' . _('You can set a closer removal date for it.') . '

    - +
    - +
    - ' . _("(dd/mm/yyyy)") . ' + ' . _('(dd/mm/yyyy)') . '
    -

    ' . _("Once you have confirmed the creation of your poll, you will be automatically redirected on the administration page of your poll.") . '

    '; +

    ' . _('Once you have confirmed the creation of your poll, you will be automatically redirected on the administration page of your poll.') . '

    '; if ($config['use_smtp'] == true) { echo ' -

    ' . _("Then, you will receive quickly two emails: one contening the link of your poll for sending it to the voters, the other contening the link to the administration page of your poll.") . '

    '; +

    ' . _('Then, you will receive quickly two emails: one contening the link of your poll for sending it to the voters, the other contening the link to the administration page of your poll.') . '

    '; } echo '
    diff --git a/choix_date.php b/choix_date.php index 623f5a5..6671def 100644 --- a/choix_date.php +++ b/choix_date.php @@ -58,22 +58,29 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || if (!empty($_POST['confirmation'])) { // Define expiration date - if (!empty($_POST['champdatefin'])) - { - $registredate = explode('/', $_POST['champdatefin']); - if (is_array($registredate) && count($registredate) == 3) - { - $time = mktime(0,0,0, $registredate[1], $registredate[0], $registredate[2]); - if ($time > time() + (24*60*60)) - { - $_SESSION['form']->end_date=$time; + $enddate = filter_input(INPUT_POST, 'enddate', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '#^[0-9]{2}/[0-9]{2}/[0-9]{4}$#']]); + $min_time = time() + (24 * 60 * 60); + $max_time = time() + (86400 * $config['default_poll_duration']); + + if (!empty($enddate)) { + $registredate = explode('/', $enddate); + + if (is_array($registredate) && count($registredate) == 3) { + $time = mktime(0, 0, 0, $registredate[1], $registredate[0], $registredate[2]); + + if ($time < $min_time) { + $_SESSION['form']->end_date = $min_time; + } elseif ($max_time < $time) { + $_SESSION['form']->end_date = $max_time; + } else { + $_SESSION['form']->end_date = $time; } } } - if(empty($_SESSION['form']->end_date)) { + if (empty($_SESSION['form']->end_date)) { // By default, expiration date is 6 months after last day - $_SESSION['form']->end_date=end($temp_results)+(86400 * $config['default_poll_duration']); + $_SESSION['form']->end_date = $max_time; } // Insert poll in database @@ -165,6 +172,8 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || } $summary .= ''; + $end_date_str = utf8_encode(strftime('%d/%m/%Y', $_SESSION['form']->end_date)); //textual date + echo '
    @@ -175,13 +184,13 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || '. $summary .'
    -

    ' . _('Your poll will be automatically removed '). $config['default_poll_duration'] . ' ' . _("days") . ' ' ._('after the last date of your poll') . '.
    ' . _('You can fix another removal date for it.') .'

    +

    ' . _('Your poll will be automatically removed '). $config['default_poll_duration'] . ' ' . _('days') . ' ' ._('after the last date of your poll') . '.
    ' . _('You can set a closer removal date for it.') .'

    - +
    - +
    '. _("(dd/mm/yyyy)") .' diff --git a/locale/de_DE/LC_MESSAGES/Studs.mo b/locale/de_DE/LC_MESSAGES/Studs.mo index 99c35911ba21fa58ca59a9c594d971e7a9ecd8c7..b9acebd24cefe6b724c68f3955bc40c55ba42c46 100644 GIT binary patch delta 1869 zcmXZcd2CKu7{~GF)y=ehyXbV+x9zm09cpRS($~IJbQ+>2h-6A51Th*aBDQM@5-CEX z(liysA2dVCJ55v&iFN)WvHZc9*eYt5MrMRC-=BN``kZs_z2`jVInTN64ZhP2zV<&N zoFX#|_A~nx7hyS`!&v-?eXv)5vmY=SGcg-SU=XXY9)HG5n2xV73L^^5qS23Gn1*H8 z7qhXt&>Z`T#wrE^cmR{|Py7*YU;;kGaD0mq*yHs-;ZvX4S8x0YQ7q&63yi^81Kf?w z$1M8GQS-qn2LX40X{|r6gAK+1v63am0%41f(m>NYT`9mgF8`y zK1XHbHEIKq#b$9Bm(1b;(g(jj>JsbVF!0WHTeEMsV%~~ra<26(U|3(Gy%`;(; zJ6|p`WMxQFY#}O;J*fGdMjDFrENbT$F&FP4o45Zk2lEG;u?d@k3Sbo`Vhbvelc+Pk zj0)&F#^Os<&HRh;m^8$#i9BT7u|YJH+Dg=fwWv(gd+x+I`YotbwxM=%1yv*OPyvMx zb&IYT{q)OF&nKadaxSjKO}HQ5V;1Y%wi3>Tfg`vHk7FJ7FLg6<5Vey|&uge1-$tdf z8yoN~F2(i3C|vA91%8T>*9I?m-a(eISD3~678veEJ{mRQWK`tSyzv^(#i*iNflBE* zRNzgh?^|Cy$1wvtP=VY+P1uF1_BW^r zVn>?si?BS@ca^B(or8K_i;1`v6~Hdk5gx)+JUf#7e_wzBeb9vo_yzTWf0WzLMfFQi zA66j8ZZ)U{_hK40V;?+&+Q3z>{|M9R_jr9je>uIEQ%?RhaVZ1II2Bc;zo7#A9ktL_ zti%v%qOZ6a(}M0%G^0}6f%?(hMb@$&RA!1to1MUN9FNcN6c#vRNH>i;s0lWXQd9=-VsCtos+o7FYxxS#Y; zsh!AFAs2 GEc<`+jo2dq delta 1868 zcmXZcduYvJ9LMqRu^ntXb7t7ttYfpyj2)NF3}^1QOsL7FWNx|5wTWE94@Iew+*)fw z{y@2(6^fMG{I_!XhY6X?T}z0_`{Vbk)$8{>=lA$pIxr;UE=SY-zhM&vV5}{ zxEP~&9Rv6cQ_CicJ~7{w{L4*TLQ%)s~90pkgthyjel5Dvyn%)*KSb1a94 zY9@N%VeEo2?23(;g3TC@pU{tO-uNfJ_L=?h=3kM;3Vwf!NjSaG-N-x)GhT^`w--BN zU7_Q?c#4U1CN5$KA7C$hiAtz_#4HWFquwjRB%F*&d=@J32Aqd`P>H@lRpbL|1O9$y zoiNce!{I>z3s4Jyc+WuZ$vh0_1F#Xp(^+cmB3%mV1GAWHZo-;NKtGN zDv^Dtc+No{l<8H}&TnE*e1dG=eqc7{4lrXAHXfBgHFm~2R3hh4XM7u#(0vTxJ5)Wnk&X(`q*nur6i3r11bZW^ZH8g%r+Zg1iMYNw~MJ2s#aX+i~TL3R5_RDh(RR0(rX-<6}9 zcNXgR1=txkq7vAPI>KWZ!mC56|NjM;&<8D;g1=E81ctfeY}B|2_2C5M*sT(^;C@WU zT1>^us14lp#xF2~aho>|@Lx{vWkspK0v9vU4JV?ybS^5fRj7q_;$*yn3iJneV5rPJ zids}@8&Lmf9wTd68>%vq;WRD|!_oK}FJPWC!t4wWk5B=&jx<|>^{A4!8|7ZlL{uqL za4Y7Z-aC#F^pED;u^3gs$Ji0ypnB#r>RSFnRVqBjt+-Rlg91!NWxfS7u@+UL2G2&+ zwR(!}uoZLh1L`^k$C}N-C{D*CNRg}+mt*cYt|Hc;;xr)@cI-J1%CrrYz;C3#EMq)( z7Avq6&!X<}OH|jlpWt?PGR8Ab$8ro~0WQOycmVt071U8TqmK3~hO|}xL^ogig@=Q%|3nIWzzBpa0CccXz$Br{1}8b%2{; zjA@x*Oc}ny8JL}BOf+u9Ay|t(JdC696sBVfW@0x^#7G85VlEECV(gDga4;^z2&}@X zxIW#uW(9fY#$FtXkz^TvEw^Y2_MH2 zY({Og&yN3cX=o==)G-EQtz$5Oeikage2m6&Yb7esR@9NyqBe38hheMrK5G4IR3$%Q z03)*41iC|MaO`F_Dqtll&_+~g526+vL+!i?6S2+u0>{$tLnSh7vNu13N@O1D%*#%l| z^E0p?X5lUj+3{9X-0SEnKnD#a@D$a5hx!_R+i~ACub+ZSAc&e*fVv}PsLQ&{x(#)w z4xx^s1y#uo)W*6{m3uLb`fH$vfmrNA1?oTDe($KW4`Cb@;1DcD&96eO-(jEc!}0VR zQ5Cq2n%9X+{23--FDj0cNBz}^&+}f8hU({|cDM+Y=}Oz*gbKJDv+)G-MVU_2<@Q=j`3hhT-;v=ZUP9yi(oW*2(i~~)PF`sGZm+8BGFsjfy`+QVo ziczJjKn1QrmA=;Y>%zU!MUHc)Au}e`x!Of~i=I zA7Bk;;94Ao4Y&ZCBIemt8XXLb!CoxDe$2;VoPenxn`L7zW?~!_xDrQWmFrjIy?|NL zjTaWN37*eJ#cjv&cp0_9TScB(9*qG8l;JB><|(uNOfyguL(W{(4kMV3%kV?2#<5tB zX}Hae??EMe9Fuq!wb2nb{+~xfJISDqAq+e7F^7H(6<`GhvDR6S3bY+{B+aOewBbbT za^66#A4FC1ZwzC~95ae!UKS0G-4>$))}sP#MwRw3YC$V%=N&i&dz|-iI{gt;BH6|M z{5UF+3e=g`qK;r4s#5!q`JNr25oX{VsuI7V&iXPcz-6HmVXVWyQ1L&VXZ9oZpzg?;`ON42ww{JEZARu=D~9np>N4Iz1suR^eB}E7 zpephjRnp)Bf88Y1{0OFC3=d%3jd!8q{)V0c^wLlQcTxRksITFT8&50s`%_T~L{am~ zQFmlD>awnN?m*qCBdDY3L{+jEwXuFw*VkclIxK%>h17v-YPK91wD9J4Tq zn%{t0zuP@;!I|{iQ5Cp`n%9R){142*VN@JTP=7ThB>Wc?qWTHc4p*Tv{oM7ppaLGi zIG#YhDCQD@=s@l8Dyl*coPVOu_#-Pf#V#AX*d?s0!7iZuLG?g<4RT_$Vr|)5v|c?=T;4;}~1cPa=&1 z241=cla~2sUxup8Dpcv}P=R-#O8=$n@9lmTTpkEqY>S0v1gtF?x*53MofrNgCw=3l aJ=4~2-L|W#`(^p#K=)6PmG6(Wro06JMA=3F diff --git a/locale/en_GB/LC_MESSAGES/Studs.po b/locale/en_GB/LC_MESSAGES/Studs.po index ad992ab..be82231 100644 --- a/locale/en_GB/LC_MESSAGES/Studs.po +++ b/locale/en_GB/LC_MESSAGES/Studs.po @@ -576,8 +576,8 @@ msgstr "Removal date:" msgid "Your poll will be automatically removed after" msgstr "Your poll will be automatically removed after" -msgid "You can fix another removal date for it." -msgstr "You can fix another removal date for it." +msgid "You can set a closer removal date for it." +msgstr "You can set a closer removal date for it." msgid "Removal date (optional)" msgstr "Removal date (optional)" diff --git a/locale/es_ES/LC_MESSAGES/Studs.mo b/locale/es_ES/LC_MESSAGES/Studs.mo index a037bd261c407a673d165f7aa351f9b873b5c82b..2339be802a393b6fa9b554c12934e075f5e5ade8 100644 GIT binary patch delta 1538 zcmXZcSxD4T6vy#1I$3IqO;c%$O)gWW)o8YuOGRpn20?`bWmYCB3>hidhSNe11wL4i zMGytqOH_(RC1n!5RWDK$=iGDe|NpY}RcqG~ceu{X z-pw+r#PvS2x!8g8Z~zx#1n1!N*=Cuz8q=}Cu?=JCcVish#>IFaS=zoj?{??!tJicgFYQcb8cU)-WE*Fe}EVI35$oaxA7GL*~b+ zSb+*$i;5G<3`a9+W?%*b9jG1mVk*8v?IhM8O{f4z(Jw*mv=r;H!Wr*H5B)w&!Dpzz zAJB^ z!>FUWgi7p@;|t89AO1*VA`K6{ILts|SvD%;O*k3rkz!aYF2$=j9fur$VIF-i7l-4v zHJFbLsC6&lXzWBC%?;$au=UZn$iNVu!voor1t+j=O_+~caWSew?WhI2aW&q>oA?J+ z$?KF)i9f_7e2%KndsGERQ0sdruiwS_2WTiz6$c-WHK+g$coO&F82o`M@d)ZtB?h8r z7(nf~3YFkN)bAHiN6?SS_!hO!FeYJaE_Z|Y=B1&_mxIc59cm}FsM5EfGH*kQW0z42 zKg9|78BgN~YW``?LC;^sMR*65Km_%>o53rXieai|12nYoC!B^U930oe@==LZ<8eHM ztMD(L!4E$| z#WGy5ENU~V#C>=SU*jI!R$#UpALCxkTF#q*=aD7tH*&o!P#C@3TTw@LqLBLQ%sUwv zhqo|@4^W9sDKa~Pi%@~Oa0MpwwIQ|zaV54R*TM$Tk1-|D`B|unmZQFqJ5d#?!|fOf z($J2cpgt@S)cg7cmC$6OskG^+iP?^M=%!zQnpc9l3#F()o6oLGXmqvp+)McBa#>IJ X*p^8NO?Az_oxa*oV^dGA&p+!QvsJDN delta 1537 zcmXZcTS!$w6vpv&O!JbOb_&fjP1DS4UNXzHi&<$!P@$5N8j>djB?`4L4+%kqK@?aJ z5>dTGm~o?K=oWfNYx56wHw_*x<9Q$w{{UMx>4{{OZO*_h4CaRe7>M;4giRQVEzbBc{OL05zy`)!SDKaL7)D|!S%zaQGGwV3gH@=& zhf#4_Q@#F-jx!L?KtF27K3tBUP&)}o^Cwh{LG(*eJ1s{KRypH7Ttt5um*Oi_;Lo@i z=THf_DJM;f_tJ3FC`Xm52D7mfbMOvk;TuO+x>*GM9MnP^QGqIO0XCp2(25ktPN9x! z0F~Ht$2Yi|zV{1_Xd2P<=3@#H%Q8?I@53e7f)v9}<2t;B%W%T+H|EoKb8$Fs+m40k zL9IK0!FU^WH209_yf#eZIs+5fkDZxj2^h(?H6aV@un<+DOQ;2hupA%bApS*F@-F35 z;?FP&U!y8CiK@UHYW--+o95#Db7?40H3uJxhfo1Lcoy3+1b?AQJcqheVQc(nn2XwR zH7da_)bH0&M=*l1_z|_v3`Su<9(RNI=BA;`mx;=BCu%2$QKj!dW!{Gr$8Mk&9>azB z4KLsvYW{i7LC@d90(^u@U<&p7JO*!K0(z;MjndG%TW}UH zV;Qf879K}ca0*qqAGil+obeq+{l%oRezfu|2?lRwS*l(BXqVGX?r#tk> R(XOPXw)PVqUw%?r;y=u$tup`s diff --git a/locale/es_ES/LC_MESSAGES/Studs.po b/locale/es_ES/LC_MESSAGES/Studs.po index 656842d..28f5fd2 100644 --- a/locale/es_ES/LC_MESSAGES/Studs.po +++ b/locale/es_ES/LC_MESSAGES/Studs.po @@ -526,7 +526,7 @@ msgid "Characters \" < and > are not permitted" msgstr "Los caracteres \" < y > no estan autorizados!" #: choix_autre.php:191 -msgid "Your poll will be automatically removed after 6 months.
    You can fix another removal date for it." +msgid "Your poll will be automatically removed after 6 months.
    You can set a closer removal date for it." msgstr "Su encuesta será automaticamente borrado dentro de 6 meses.
    Mientras, usted puede cambiar este fecha aquí." #: choix_autre.php:193 diff --git a/locale/fr_FR/LC_MESSAGES/Studs.mo b/locale/fr_FR/LC_MESSAGES/Studs.mo index 656e53e83ed91d843ba41edc09649f50aa9cebac..8e31fb3f2ba3b3789ab5227e9bc98563c9b16489 100644 GIT binary patch delta 1964 zcmXZce@s6S|vwlK9A+=^Wi#)Zw6?y%`> zWv&IYwYotys^yl+E`LNnY}$_v`r%d%TlJ5%*2tA@w&9wr-k+VbF<#&2**WL=e!tK2 z-1(uvH$#E56CrnnnTN~X#sZvk36#;I)na6$I9L3Fe~~tU|hM z4oeTMpgJ1YO8`QLQa;6DtH63C9Z8F$YSDg%)owBCyt=@{1htV(-^^X zn1{chp8p3`={#zWOYZaz;bzpKY(qVF4E5egT!f<-Wqo^(;8`Xv;Rqh6H7mw>R0oRI znZ1u?co;9DI&?q%Q(}FnN{^!sa}u>RALHBjISycaJ>9`8n2ks8CLz|hAp%u8hK)Fh z1$YzHs{9RJ3zuL%;|S_Htw&wQ22^GHk#1WLX5#Cp>vkGnz%!`CHr?aB--NF2Ycqjb z7)Ont!#i*c)rpTV7iX{tf5$Lt!`0ei)bkP4d>yXDR#YK_sD)p`VjMv|H(5vj_2T#b z#2=^@2JiJ2sz6<@dQ|0m{rM+R9Xsy(sy}}g`LikhsdJ%?-g9}Vg`-%A4X7<_+erUQ z2wWx{Ork3M#CHaB7+*uR_&-#_dG%%-1FOUa+>feg6kowf)U9aUAps9W<6sxx1s z61?FOd_fT0Y_=Px@l9O3#cUYQp+4NgDu=Ke)ym&6gny#8<~lxzK@QN<_%QCk%Xkc( zt=^$~3w7HjP~UOS6D%c|LREIvH*Fg~tBk{_jN37aCsD1OKy~CI>N;J)bi9VT=huD9 zw{ue%H{(M%g4&`vjO+f_HkonIZ4~vv%c$!yi#o+OPzk1yjS{Iqev@oB>b*hShacbq zETHTVmZEM+1k-Re?!g+2;xiaDsy#zc&O{2A;SB0t-$b=Occ*vwsxZj79<@NDKi-j= z&Dt6WoFA^vjszx#o3pv!6nj_#gB>Oyo~+3;)Iv#L8kd$*&jGuG#H qE+04;b2{7m`4@8%1HHX{u|%S)=b+QuJ&#QYRs~60O#Nfn1y?>1P`L#o5Xtj2Jb-+gGJbg z9$beR*nzj=Ms#BUmtbG5#jK3RI0Lir6Rf~9I1jJj9q5^Fb|;o#9yXvRUW1v~>h#y) zXD+igJjrdbD#ou~x&*2T=cG!8SMi6>E!pLRU!jDLX&6c zyc;J_&rdu3Yp4q5E=mWm5H-(gR3dGtEr$Q47vT zs%-0#?Y9xs*?9}K(08Z|e?x7Rn?;DpW}^~bifl>DT4-c5uo-7#1XYPq)Se$iMV!D& zJcarA1M2xdP?_FD?QuzC`Vg){9m-DBbGuOQ?Z?}39IIL1-lMUHfr~hf&)#QNj5kpg zC|qoI9OvOEUO-joG3uwlo=0W68+Dk+P+Rj69>Wwyao~QlxA8LO;LA%1i1qDt8p?D6 zAH*pvz`s$Y%3qc);ar?UzXElgmY}XJvX(2 z`s>9noq?;U61pEqFI0)TUQMXXH#*~ksEX}&JmQQWNB(S@f2v$YQ~J3))WTI*h|Q=i z>};a`r8IUj;KMOgh95g#!d&{-Q6>Ht6>#24Gme4P;2P{gWi*aQa0+!R+E=9y;SSWT zIfkmtIaGju#%P?O;a<%);8}bJi<`~jcnURf8>@`q7E~#J#!UPbwKX^JDRgsycHkyl zi(la@Sk{t0bnl{WTM{)->{A-$G^SCRU2}9jWcDz9FDl~aup0NHN|{7eZ)%7Sso#I+lfQ_g?I*{)qdkOX4 zBzEBy^q`-#Gx2fMEosMFup6Jm9#kS9Vuq3J_cSUP_zA0U)+6bAU56@tGwSed!VKJs zT431ek0h^Vx42v<;`KR|E{nJ2oO7K{&dq(JFl%%Fh_5FU-qx2)RWB}kbbTt(6WSW? z4@G?2!_kOuC>-4$e9;$3C3^bePjXpnf%|{fPyUSn diff --git a/locale/fr_FR/LC_MESSAGES/Studs.po b/locale/fr_FR/LC_MESSAGES/Studs.po index db74782..30789b7 100644 --- a/locale/fr_FR/LC_MESSAGES/Studs.po +++ b/locale/fr_FR/LC_MESSAGES/Studs.po @@ -576,8 +576,8 @@ msgstr "Date de suppression :" msgid "Your poll will be automatically removed after" msgstr "Votre sondage sera automatiquement effacé dans" -msgid "You can fix another removal date for it." -msgstr "Néanmoins vous pouvez décider ci-dessous d'une date plus rapprochée pour la suppression de votre sondage." +msgid "You can set a closer removal date for it." +msgstr "Vous pouvez décider d'une date de suppression plus proche." msgid "Removal date (optional)" msgstr "Date de fin (facultative)" From 1330ea825f019a8fd6db2e2bfc0ea5bca1ae5aaa Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 4 Jan 2015 01:37:03 +0100 Subject: [PATCH 095/151] Remove old .php --- old_adminstuds.php | 131 --------- old_exportcsv.php | 104 ------- old_studs.php | 706 --------------------------------------------- 3 files changed, 941 deletions(-) delete mode 100644 old_adminstuds.php delete mode 100644 old_exportcsv.php delete mode 100644 old_studs.php diff --git a/old_adminstuds.php b/old_adminstuds.php deleted file mode 100644 index 46a8b8e..0000000 --- a/old_adminstuds.php +++ /dev/null @@ -1,131 +0,0 @@ - two modifications (comment, title, description, ...) on differents polls in the same session will generate only one mail. -$email_admin = $poll->admin_mail; -$poll_title = $poll->title; -$smtp_allowed = $config['use_smtp']; -function send_mail_admin() { - global $email_admin; - global $poll_title; - global $admin_poll_id; - global $smtp_allowed; - if($smtp_allowed==true){ - if(!isset($_SESSION['mail_admin_sent'])) { - Utils::sendEmail( $email_admin, - _("[ADMINISTRATOR] New settings for your poll") . ' ' . stripslashes( $poll_title ), - _("You have changed the settings of your poll. \nYou can modify this poll with this link") . - " :\n\n" . Utils::getUrlSondage($admin_poll_id, true) . "\n\n" . - _("Thanks for your confidence.") . "\n" . NOMAPPLICATION - ); - $_SESSION["mail_admin_sent"]=true; - } - } - -} - - -$nbcolonnes = count($sujets); -$nblignes = count($users); - -//si il n'y a pas suppression alors on peut afficher normalement le tableau - - - -//action quand on ajoute une colonne au format AUTRE -if (isset($_POST["ajoutercolonne"]) && !empty($_POST['nouvellecolonne']) && $poll->format == "A") { - $nouveauxsujets=$dsujet->sujet; - - //on rajoute la valeur a la fin de tous les sujets deja entrés - $nouveauxsujets.=","; - $nouveauxsujets.=str_replace(","," ",$_POST["nouvellecolonne"]); - $nouveauxsujets = htmlentities(html_entity_decode($nouveauxsujets, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8'); - - //mise a jour avec les nouveaux sujets dans la base - $sql = 'UPDATE sujet_studs SET sujet = '.$connect->Param('nouveauxsujets').' WHERE id_sondage = '.$connect->Param('numsondage'); - $sql = $connect->Prepare($sql); - if ($connect->Execute($sql, array($nouveauxsujets, $poll_id))) { - send_mail_admin(); - } -} - - -//on teste pour voir si une ligne doit etre modifiée -$testmodifier = false; -$testligneamodifier = false; - - - -// Button in the first td to avoid remove col on "Return" keypress) -$tr_add_remove_col = ''; - -$border = array(); // bordure pour distinguer les mois -$td_headers = array(); // for a11y, headers="M1 D4 H5" on each td -$radio_title = array(); // date for - -if ($poll->format == "A") { - $tr_subjects = ''; - - foreach ($sujets as $i=>$sujet) { - - $td_headers[$i]='';$radio_title[$i]=''; // init before concatenate - - // Subjects - preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$sujet->sujet,$md_a_img); // Markdown [![alt](src)](href) - preg_match_all('/!\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_img); // Markdown ![alt](src) - preg_match_all('/\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_a); // Markdown [text](href) - if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) - - $th_subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); - $th_subject_html = ''.$th_subject_text.''; - - } elseif (isset($md_img[2][0]) && $md_img[2][0]!='') { // ![alt](src) - - $th_subject_text = (isset($md_img[1][0]) && $md_img[1][0]!='') ? stripslashes($md_img[1][0]) : _("Choice") .' '.($i+1); - $th_subject_html = ''.$th_subject_text.''; - - } elseif (isset($md_a[2][0]) && $md_a[2][0]!='') { // [text](href) - - $th_subject_text = (isset($md_a[1][0]) && $md_a[1][0]!='') ? stripslashes($md_a[1][0]) : _("Choice") .' '.($i+1); - $th_subject_html = ''.$th_subject_text.''; - - } else { // text only - - $th_subject_text = stripslashes($sujet->sujet); - $th_subject_html = $th_subject_text; - - } - $tr_subjects .= ''.$th_subject_html.''; - - $border[$i] = false; - $td_headers[$i] .= 'S'.$i; - $radio_title[$i] .= $th_subject_text; - - // Remove col - $tr_add_remove_col .= ''; - } - - // Add col - $tr_add_remove_col .= ''; - - $thead = $tr_add_remove_col.$tr_subjects.''; -} - -// Print headers diff --git a/old_exportcsv.php b/old_exportcsv.php deleted file mode 100644 index fd868bf..0000000 --- a/old_exportcsv.php +++ /dev/null @@ -1,104 +0,0 @@ -Param('numsondage').' ORDER BY id_users'; -$sql = $connect->Prepare($sql); -$user_studs = $connect->Execute($sql, array($_GET['numsondage'])); - -$dsondage = Utils::get_sondage_from_id($_GET['numsondage']); -$nbcolonnes=substr_count($dsondage->sujet,',')+1; - -$toutsujet=explode(",",$dsondage->sujet); - -//affichage des sujets du sondage -$input =","; -foreach ($toutsujet as $value) { - if ($dsondage->format=="D"||$dsondage->format=="D+") { - if (strpos($dsondage->sujet,'@') !== false) { - $days=explode("@",$value); - $input.= '"'.date("j/n/Y",$days[0]).'",'; - } else { - $input.= '"'.date("j/n/Y",$values).'",'; - } - } else { - - preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$value,$md_a_img); // Markdown [![alt](src)](href) - preg_match_all('/!\[(.*?)\]\((.*?)\)/',$value,$md_img); // Markdown ![alt](src) - preg_match_all('/\[(.*?)\]\((.*?)\)/',$value,$md_a); // Markdown [text](href) - if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) - $subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); - } elseif (isset($md_img[2][0]) && $md_img[2][0]!='') { // ![alt](src) - $subject_text = (isset($md_img[1][0]) && $md_img[1][0]!='') ? stripslashes($md_img[1][0]) : _("Choice") .' '.($i+1); - } elseif (isset($md_a[2][0]) && $md_a[2][0]!='') { // [text](href) - $subject_text = (isset($md_a[1][0]) && $md_a[1][0]!='') ? stripslashes($md_a[1][0]) : _("Choice") .' '.($i+1); - } else { // text only - $subject_text = stripslashes($value); - } - $input.= '"'.html_entity_decode($subject_text).'",'; - } -} - -$input.="\r\n"; - -if (strpos($dsondage->sujet,'@') !== false) { - $input.=","; - foreach ($toutsujet as $value) { - $heures=explode("@",$value); - $input.= '"'.$heures[1].'",'; - } - - $input.="\r\n"; -} - -while ( $data=$user_studs->FetchNextObject(false)) { - // Le nom de l'utilisateur - $nombase=html_entity_decode(str_replace("°","'",$data->nom)); - $input.= '"'.$nombase.'",'; - //affichage des resultats - $ensemblereponses=$data->reponses; - for ($k=0;$k<$nbcolonnes;$k++) { - $car=substr($ensemblereponses,$k,1); - switch ($car) { - case "1": $input .= '"'._('Yes').'",'; $somme[$k]++; break; - case "2": $input .= '"'._('Ifneedbe').'",'; break; - default: $input .= '"'._('No').'",'; break; - } - } - - $input.="\r\n"; -} - -$filesize = strlen( $input ); -$filename=$_GET["numsondage"].".csv"; - -header( 'Content-Type: text/csv; charset=utf-8' ); -header( 'Content-Length: '.$filesize ); -header( 'Content-Disposition: attachment; filename="'.$filename.'"' ); -header( 'Cache-Control: max-age=10' ); - -echo str_replace('"','""',$input); - -die(); diff --git a/old_studs.php b/old_studs.php deleted file mode 100644 index 96f880f..0000000 --- a/old_studs.php +++ /dev/null @@ -1,706 +0,0 @@ -findPollById($numsondage); -if ($dsondage){ - $sujets = $connect->allSujetsByPollId($numsondage); - $users = $connect->allUsersByPollId($numsondage); -} else { - Utils::print_header( _("Error!")); - - bandeau_titre(_("Error!")); - - echo ' -
    -

    ' . _("This poll doesn't exist !") . '

    -

    ' . _('Back to the homepage of ') . ' ' . NOMAPPLICATION . '

    -
    '."\n"; - - bandeau_pied(); - - die(); -} - -//output a CSV and die() -if(!empty($_GET['export']) && $dsondage) { - if($_GET['export'] == 'csv') { - require_once('exportcsv.php'); - } - - die(); -} - -// quand on ajoute un commentaire utilisateur -if(isset($_POST['ajoutcomment'])) { - if (isset($_SESSION['nom']) && Utils::issetAndNoEmpty('commentuser') === false) { - // Si le nom vient de la session, on le de-htmlentities - $comment_user = html_entity_decode($_SESSION['nom'], ENT_QUOTES, 'UTF-8'); - } elseif(Utils::issetAndNoEmpty('commentuser')) { - $comment_user = $_POST["commentuser"]; - } elseif(isset($_POST["commentuser"])) { - $err |= COMMENT_USER_EMPTY; - } else { - $comment_user = _('anonyme'); - } - - if(Utils::issetAndNoEmpty('comment') === false) { - $err |= COMMENT_EMPTY; - } - - if (isset($_POST["comment"]) && !Utils::is_error(COMMENT_EMPTY) && !Utils::is_error(NO_POLL) && !Utils::is_error(COMMENT_USER_EMPTY)) { - // protection contre les XSS : htmlentities - $comment = htmlentities($_POST['comment'], ENT_QUOTES, 'UTF-8'); - $comment_user = htmlentities($comment_user, ENT_QUOTES, 'UTF-8'); - - // Check for doublons - $comment_doublon = false; - $req = 'SELECT * FROM comments WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_comment'; - $sql = $connect->Prepare($req); - $comment_user_doublon = $connect->Execute($sql, array($numsondage)); - if ($comment_user_doublon->RecordCount() != 0) { - while ( $dcomment_user_doublon=$comment_user_doublon->FetchNextObject(false)) { - if($dcomment_user_doublon->comment == $comment && $dcomment_user_doublon->usercomment == $comment_user) { - $comment_doublon = true; - }; - } - } - - if(!$comment_doublon) { - $req = 'INSERT INTO comments (id_sondage, comment, usercomment) VALUES ('. - $connect->Param('id_sondage').','. - $connect->Param('comment').','. - $connect->Param('comment_user').')'; - $sql = $connect->Prepare($req); - - $comments = $connect->Execute($sql, array($numsondage, $comment, $comment_user)); - if ($comments === false) { - $err |= COMMENT_INSERT_FAILED; - } - } - } -} - - -// Action quand on clique le bouton participer -$user_studs = $connect->allUsersByPollId($numsondage); - -$nbcolonnes = countStuds($sujets); -if (!Utils::is_error(NO_POLL) && (isset($_POST["boutonp"]))) { - //Si le nom est bien entré - if (empty($_POST['nom'])) { - $err |= NAME_EMPTY; - } - - if(!Utils::is_error(NAME_EMPTY) && (! ( USE_REMOTE_USER && isset($_SERVER['REMOTE_USER']) ) || $_POST["nom"] == $_SESSION["nom"])) { - $nouveauchoix = ''; - for ($i=0;$i<$nbcolonnes;$i++) { - // radio checked 1 = Yes, 2 = Ifneedbe, 0 = No - if (isset($_POST["choix$i"])) { - switch ($_POST["choix$i"]) { - case 1: $nouveauchoix .= "1";break; - case 2: $nouveauchoix .= "2";break; - default: $nouveauchoix .= "0";break; - } - } - } - - $nom=substr($_POST["nom"],0,64); - - // protection contre les XSS : htmlentities - $nom = htmlentities($nom, ENT_QUOTES, 'UTF-8'); - - foreach ($users as $user) { - if ($nom == $user->nom) { - $err |= NAME_TAKEN; - } - } - - // Ecriture des choix de l'utilisateur dans la base - if (!Utils::is_error(NAME_TAKEN) && !Utils::is_error(NAME_EMPTY)) { - - // Todo : Il faudrait lever une erreur en cas d'erreur d'insertion - $newVote = $connect->insertVote($nom, $numsondage, $nouveauchoix); - $user_studs[] = $newVote; - - if ($dsondage->receiveNewVotes || /* compatibility for non boolean DB */ $dsondage->receiveNewVotes==="yes" || $dsondage->receiveNewVotes==="true") { - if($config['use_smtp']==true){ - Utils::sendEmail( $dsondage->admin_mail, - "[".NOMAPPLICATION."] "._("Poll's participation")." : ".html_entity_decode($dsondage->title, ENT_QUOTES, 'UTF-8') . ' ', - html_entity_decode($nom, ENT_QUOTES, 'UTF-8'). ' ' . - _("has filled a line.\nYou can find your poll at the link") . " :\n\n". - Utils::getUrlSondage($numsondage) . " \n\n" . - _("Thanks for your confidence.") . "\n". NOMAPPLICATION ); - } - } - } - } else { - $err |= NAME_EMPTY; - } - -} - -if($err != 0) { - Utils::print_header(_("Error!").' - '.$dsondage->title); - bandeau_titre(_("Error!")); - - echo '
      '."\n"; - - if(Utils::is_error(NAME_EMPTY)) { - echo '
    • ' . _("Enter a name") . "
    • \n"; - } - if(Utils::is_error(NAME_TAKEN)) { - echo '
    • ' . _("The name you've chosen already exist in this poll!") . "
    • \n"; - } - if(Utils::is_error(COMMENT_EMPTY) || Utils::is_error(COMMENT_USER_EMPTY)) { - echo '
    • ' . _("Enter a name and a comment!") . "
    • \n"; - } - if(Utils::is_error(COMMENT_INSERT_FAILED) ) { - echo '
    • ' . _("Failed to insert the comment!") . "
    • \n"; - } - - echo '
    '; - -} else { - Utils::print_header(_('Poll').' - '.$dsondage->title); - bandeau_titre(_('Poll').' - '.$dsondage->title); -} - -$title=stripslashes(str_replace("\\","",$dsondage->title)); -echo ' -
    -
    -
    -

    '.$title.'

    -
    -
    -
    - - -
    -
    -
    -
    -
    -
    -

    '. _("Initiator of the poll") .'

    -

    '.stripslashes($dsondage->admin_name).'

    -
    - -
    '."\n"; - -//affichage de la description du sondage -if ($dsondage->comment) { - $commentaires = $dsondage->comment; - $commentaires=nl2br(str_replace("\\","",$comment)); - echo ' -
    -

    '._("Description") .'


    -

    '. $commentaires .'

    -
    '; -} -echo ' -
    -
    '."\n"; // .jumbotron - -//On récupere les données et les sujets du sondage -$nblignes = count($users); - -//on teste pour voir si une ligne doit etre modifiée -$testmodifier = false; -$ligneamodifier = -1; -for ($i=0;$i<$nblignes;$i++) { - if (isset($_POST["modifierligne$i"])) { - $ligneamodifier = $i; - } - - //test pour voir si une ligne est a modifier - if (isset($_POST['validermodifier'.$i])) { - $modifier = $i; - $testmodifier = true; - } -} - -//si le test est valide alors on affiche des checkbox pour entrer de nouvelles valeurs -if ($testmodifier) { - $nouveauchoix = ''; - for ($i=0;$i<$nbcolonnes;$i++) { - // radio checked 1 = Yes, 2 = Ifneedbe, 0 = No - if (isset($_POST["choix$i"])) { - switch ($_POST["choix$i"]) { - case 1: $nouveauchoix .= "1";break; - case 2: $nouveauchoix .= "2";break; - default: $nouveauchoix .= "0";break; - } - } - } - - $compteur=0; - while ($data = $user_studs->FetchNextObject(false) ) { - //mise a jour des données de l'utilisateur dans la base SQL - if ($compteur == $modifier) { - $sql = 'UPDATE user_studs SET reponses='.$connect->Param('nouveauchoix').' WHERE nom='.$connect->Param('nom').' AND id_users='.$connect->Param('id_users'); - $sql = $connect->Prepare($sql); - $connect->Execute($sql, array($nouveauchoix, $data->nom, $data->id_users)); - - if ($dsondage->mailsonde=="yes") { - Utils::sendEmail( "$dsondage->mail_admin", "[".NOMAPPLICATION."] " . _("Poll's participation") . " : ".html_entity_decode($dsondage->title, ENT_QUOTES, 'UTF-8'), "\"".html_entity_decode($data->nom, ENT_QUOTES, 'UTF-8')."\""."" . _("has filled a line.\nYou can find your poll at the link") . " :\n\n" . Utils::getUrlSondage($numsondage) . " \n\n" . _("Thanks for your confidence.") . "\n".NOMAPPLICATION ); - } - } - $compteur++; - } -} - -// Table headers -$thead = ''; - -// Button in the first td to avoid remove col on "Return" keypress) -$border = array(); // bordure pour distinguer les mois -$td_headers = array(); // for a11y, headers="M1 D4 H5" on each td -$radio_title = array(); // date for - -// Dates poll -if ($dsondage->format === 'D') { - - $tr_months = ''; - $tr_days = ''; - $tr_hours = ''; - - // Headers - $colspan_month = 0; - - $col_number = 0; - foreach ($sujets as $i=>$sujet) { - - // Current date - $horoCur = explode("@", $sujet->sujet); //horoCur[0] = date, horoCur[1] = hour,hour,hour - if (isset($sujets[$i+1])){ - $next = $sujets[$i+1]; - $horoNext = explode("@", $next->sujet); - } else { - unset($next); - } - - - $border[$col_number] = false; - $current_radio_title = strftime($date_format['txt_short'], $horoCur[0]); - - // Months - $current_td_headers = 'M'.($i+1-$colspan_month); - - $currentYearMonth = strftime("%B%Y", $horoCur[0]); - $nextYearMonth = strftime("%B%Y", $horoNext[0]); - if (isset($next) && $currentYearMonth == $nextYearMonth) { - $colspan_month += substr_count($horoCur[1], ',') + 1; - } else { - $border[$i] = true; - $colspan_month += substr_count($horoCur[1], ',') + 1; - $tr_months .= ''.strftime("%B",$horoCur[0]).' '.strftime("%Y", $horoCur[0]).''; - $colspan_month=0; - } - - // Days - - $colspan_day = substr_count($horoCur[1], ',') + 1; - $current_td_headers .= ' D'.($col_number+1-$colspan_day); - $tr_days .= ''.strftime($date_format['txt_day'],$horoCur[0]).''; - - // Hours - if (!empty($horoCur[1])) { - $hours = explode(',', $horoCur[1]); - foreach($hours as $hour) { - if (end($hours) == $hour) { - $border[$col_number] = false; - } else { - $border[$col_number] = true; - } - - $rbd = ($border[$col_number]) ? ' rbd' : ''; - - $tr_hours .= ''.$hour.''; - $radio_title[$col_number] = $current_radio_title . ' - '.$hour; - $td_headers[$col_number] = $current_td_headers . ' H'.$col_number; - $col_number++; - } - } else { - $tr_hours .= ''; - } - } - - $border[count($border)-1] = false; // suppression de la bordure droite du dernier mois - - $tr_months .= ''; - $tr_days .= ''; - $tr_hours .= ''; - - $thead = "\n".$tr_months."\n".$tr_days."\n".$tr_hours."\n"; - -// Subjects poll -} else { - - $tr_subjects = ''; - - foreach ($sujets as $i=>$sujet) { - - $td_headers[$i]='';$radio_title[$i]=''; // init before concatenate - - // Subjects - preg_match_all('/\[!\[(.*?)\]\((.*?)\)\]\((.*?)\)/',$sujet->sujet,$md_a_img); // Markdown [![alt](src)](href) - preg_match_all('/!\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_img); // Markdown ![alt](src) - preg_match_all('/\[(.*?)\]\((.*?)\)/',$sujet->sujet,$md_a); // Markdown [text](href) - if (isset($md_a_img[2][0]) && $md_a_img[2][0]!='' && isset($md_a_img[3][0]) && $md_a_img[3][0]!='') { // [![alt](src)](href) - - $th_subject_text = (isset($md_a_img[1][0]) && $md_a_img[1][0]!='') ? stripslashes($md_a_img[1][0]) : _("Choice") .' '.($i+1); - $th_subject_html = ''.$th_subject_text.''; - - } elseif (isset($md_img[2][0]) && $md_img[2][0]!='') { // ![alt](src) - - $th_subject_text = (isset($md_img[1][0]) && $md_img[1][0]!='') ? stripslashes($md_img[1][0]) : _("Choice") .' '.($i+1); - $th_subject_html = ''.$th_subject_text.''; - - } elseif (isset($md_a[2][0]) && $md_a[2][0]!='') { // [text](href) - - $th_subject_text = (isset($md_a[1][0]) && $md_a[1][0]!='') ? stripslashes($md_a[1][0]) : _("Choice") .' '.($i+1); - $th_subject_html = ''.$th_subject_text.''; - - } else { // text only - - $th_subject_text = stripslashes($sujet->sujet); - $th_subject_html = $th_subject_text; - - } - $tr_subjects .= ''.$th_subject_html.''; - - $border[$i] = false; - $td_headers[$i] .= 'S'.$i; - $radio_title[$i] .= $th_subject_text; - - } - - $thead = $tr_subjects.''; -} - -// Print headers -echo ' - - -'; -if ($dsondage->format=="A-" || $dsondage->format=="D-") { - echo ' -
    -

    ' . _("The administrator locked this poll, votes and comments are frozen, it's not possible to participate anymore.") . '

    - -
    '; -} else { - echo ' -
    -

    ' . _("If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line.") . '

    - -
    '; -} -echo' - - -

    '._('Votes of the poll ').'

    -
    - - - '. $thead . ' - '; - -// Print poll results - -//Usager pré-authentifié dans la liste? -$user_mod = false; - -//affichage des resultats actuels -$somme[] = 0; -$compteur = 0; - -foreach ($users as $user) { - - $ensemblereponses = $user->reponses; - - //affichage du nom - $nombase=str_replace("°","'",$user->nom); - echo ' -'."\n"; - - // ligne d'un usager pré-authentifié - $mod_ok = !( USE_REMOTE_USER && isset($_SERVER['REMOTE_USER']) ) || ($nombase == $_SESSION['nom']); - $user_mod |= $mod_ok; - - // pour chaque colonne - for ($k=0; $k < $nbcolonnes; $k++) { - // on remplace les choix de l'utilisateur par une ligne de checkbox pour recuperer de nouvelles valeurs - if ($compteur == $ligneamodifier) { - - $car = substr($ensemblereponses, $k , 1); - - // variable pour afficher la valeur cochée - $car_html[0]='value="0"';$car_html[1]='value="1"';$car_html[2]='value="2"'; - switch ($car) { - case "1": $car_html[1]='value="1" checked';break; - case "2": $car_html[2]='value="2" checked';break; - default: $car_html[0]='value="0" checked';break; - } - - echo ' - '."\n"; - - } else { - $rbd = ($border[$k]) ? ' rbd' : ''; - $car = substr($ensemblereponses, $k, 1); - switch ($car) { - case "1": echo ''."\n"; - if (isset($somme[$k]) === false) { - $somme[$k] = 0; - } - $somme[$k]++; break; - case "2": echo ''."\n"; break; - default: echo ''."\n"; - } - } - } - - //a la fin de chaque ligne se trouve les boutons modifier - if ($compteur != $ligneamodifier && ($dsondage->format=="A+"||$dsondage->format=="D+") && $mod_ok) { - echo ' - '."\n"; - } - - //demande de confirmation pour modification de ligne - for ($i=0;$i<$nblignes;$i++) { - if (isset($_POST["modifierligne$i"])) { - if ($compteur == $i) { - echo ''."\n"; - } - } - } - - $compteur++; - echo ''."\n"; -} - -// affichage de la ligne pour un nouvel utilisateur -if (( !(USE_REMOTE_USER && isset($_SERVER['REMOTE_USER'])) || !$user_mod) && $ligneamodifier==-1 && ($dsondage->format!="A-" && $dsondage->format!="D-")) { - //affichage de la case vide de texte pour un nouvel utilisateur - echo ' -'."\n"; - - //une ligne de checkbox pour le choix du nouvel utilisateur - for ($i = 0; $i < $nbcolonnes; $i++) { - echo ' - '."\n"; - } - - // Affichage du bouton de formulaire pour inscrire un nouvel utilisateur dans la base - echo ' -'."\n"; - -} - -// Addition and Best choice -//affichage de la ligne contenant les sommes de chaque colonne -$tr_addition = ''; -$meilleurecolonne = max($somme); -$compteursujet = 0; -$meilleursujet = '
      '; -for ($i = 0; $i < $nbcolonnes; $i++) { - if (isset($somme[$i]) && $somme[$i] > 0 ) { - if (in_array($i, array_keys($somme, max($somme)))){ - - $tr_addition .= '
    '; - - $meilleursujet.= '
  • '.$radio_title[$i].'
  • '; - $compteursujet++; - - } else { - $tr_addition .= ''; - } - } else { - $tr_addition .= ''; - } -} -$tr_addition .= ''; - -$meilleursujet = str_replace("°", "'", $meilleursujet).''; -$vote_str = ($meilleurecolonne > 1) ? $vote_str = _('votes') : _('vote'); - -// Print Addition and Best choice -echo $tr_addition.' - -
    '._('Votes of the poll ').$title.'
    '.stripslashes($nombase).' -
      -
    • - - -
    • -
    • - - -
    • -
    • - - -
    • -
    -
    ' . _('Yes') . '() ' . _('Yes') . _(', ifneedbe') . '' . _('No') . ' - -
    -
    - - -
    -
    -
      -
    • - - -
    • -
    • - - -
    • -
    • - - -
    • -
    -
    '. _("Addition") .''.$somme[$i].''.$somme[$i].'
    -
    -
    '."\n"; - -if ($compteursujet == 1) { - echo ' -

    ' . _("Best choice") . '

    -
    -

    ' . _("The best choice at this time is:") . '

    - ' . $meilleursujet . ' -

    ' . _("with") . ' ' . $meilleurecolonne . ' ' . $vote_str . '.

    -
    '."\n"; -} elseif ($compteursujet > 1) { - echo ' -

    ' . _("Best choices") . '

    -
    -

    ' . _("The bests choices at this time are:") . '

    - ' . $meilleursujet . ' -

    ' . _("with") . ' ' . $meilleurecolonne . ' ' . $vote_str . '.

    -
    '."\n"; -} - -echo ' -
    -
    '; - -// Comments -$comments = $connect->allCommentsByPollId($numsondage); - -if (count($comments) != 0) { - echo '

    ' . _("Comments of polled people") . '

    '."\n"; - - while($dcomment = $comment_user->FetchNextObject(false)) { - echo ' -
    - '.stripslashes($dcomment->usercomment). ' : - ' . stripslashes(nl2br($dcomment->comment)) . ' -
    '; - } - - echo '
    '; -} - -if ($dsondage->format!="A-" && $dsondage->format!="D-") { -echo ' -
    -
    -
    ' . _("Add a comment in the poll") . ' -
    -

    -
    -
    -


    -

    -
    -

    -
    -
    -
    -
    '; -} - -echo ' -'; - -bandeau_pied(); From 15e5b4087710e2599109dbc8a831d4c7beb8989a Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 4 Jan 2015 02:00:02 +0100 Subject: [PATCH 096/151] Hide some useless elements when printing --- bandeaux.php | 2 +- tpl/header.tpl | 2 +- tpl/part/comments.tpl | 2 +- tpl/part/poll_info.tpl | 2 +- tpl/part/vote_table_classic.tpl | 2 +- tpl/part/vote_table_date.tpl | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/bandeaux.php b/bandeaux.php index 1befbbb..a2c4caf 100644 --- a/bandeaux.php +++ b/bandeaux.php @@ -28,7 +28,7 @@ function bandeau_titre($titre) echo '
    '; if(count($ALLOWED_LANGUAGES)>1){ - echo '
    + echo '
    diff --git a/tpl/header.tpl b/tpl/header.tpl index a0ca4de..838de01 100644 --- a/tpl/header.tpl +++ b/tpl/header.tpl @@ -1,6 +1,6 @@
    {if count($langs)>1} - +
    +
    +
    + + +
    +
    + + +
    + +
    + Database + +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + + +
    + + + From 059f4c2fc75eecef383662ac3d103a6f4ddc5e75 Mon Sep 17 00:00:00 2001 From: Simon Leblanc Date: Sun, 30 Nov 2014 01:02:11 +0100 Subject: [PATCH 102/151] move install into his own folder and split code into class (cherry picked from commit 1a5846a156f797849842c63244fe737c5a632b9f) --- install.php | 187 ------------------ install/InstallComposer.php | 90 +++++++++ install/InstallConfiguration.php | 73 +++++++ install/InstallSql.php | 24 +++ install/error.html | 33 ++++ install/install.css | 11 ++ install/install.html | 72 +++++++ .../install.mysql.auto.sql | 0 .../install.mysql.sql | 0 install/install.php | 43 ++++ 10 files changed, 346 insertions(+), 187 deletions(-) delete mode 100644 install.php create mode 100644 install/InstallComposer.php create mode 100644 install/InstallConfiguration.php create mode 100644 install/InstallSql.php create mode 100644 install/error.html create mode 100644 install/install.css create mode 100644 install/install.html rename install.mysql.auto.sql => install/install.mysql.auto.sql (100%) rename install.mysql.sql => install/install.mysql.sql (100%) create mode 100644 install/install.php diff --git a/install.php b/install.php deleted file mode 100644 index 0e12bad..0000000 --- a/install.php +++ /dev/null @@ -1,187 +0,0 @@ -'; - ob_flush(); - flush(); - - require_once 'phar://'.$composer.'/src/bootstrap.php'; - ob_flush(); - flush(); - - $composer_home = getenv('COMPOSER_HOME'); - $personal_home = getenv('HOME'); - if (empty($composer_home) === true && empty($personal_home) === true) { - putenv('COMPOSER_HOME='.sys_get_temp_dir()); - } - - $application = new \Composer\Console\Application(); - $application->setAutoExit(false); - $command = $application->find('install'); - $input = new \Symfony\Component\Console\Input\ArrayInput(array( - 'command' => 'install', - '-d' => __DIR__, - '-vvv', - '--optimize-autoloader', - )); - $fhandle = fopen('php://output', 'wb'); - $output = new \Symfony\Component\Console\Output\StreamOutput($fhandle); - - $application->run($input, $output); - fclose($fhandle); - ob_flush(); - flush(); - - // Save configuration - $configuration = file_get_contents($configuration_file.'.template'); - if (false === $configuration) { - throw new \Exception('Impossible to read template configuration'); - } - - $configuration = str_replace( - array( - '\'\'', - '\'\'', - '\'\'', - '\'\'', - '\'\'', - '\'\'', - '\'\'', - '\'\'', - ), - array( - var_export($_POST['title'], true), - var_export($_POST['email'], true), - var_export($_POST['no-reply-email'], true), - var_export($_POST['db-name'], true), - var_export($_POST['db-user'], true), - var_export($_POST['db-pass'], true), - var_export($_POST['db-host'], true), - var_export($_POST['db-type'], true), - ), - $configuration - ); - - if (file_put_contents($configuration_file, $configuration) === false) { - throw new \Exception('Impossible to save configuration'); - } - - // Inject database - require_once __DIR__.'/app/inc/init.php'; - - $sqls = explode("\n", file_get_contents(__DIR__.'/install.mysql.auto.sql')); - foreach ($sqls as $sql) { - $sql = trim($sql); - if (empty($sql) === true) { - continue; - } - - $query = $connect->Prepare($sql); - $cleaning = $connect->Execute($query); - } - - ob_flush(); - flush(); - ob_end_clean(); - } catch (Exception $e) { - echo '
    '.$e->getMessage().'
    '; - echo "
    ".$e->getTraceAsString()."
    "; - die('installation failed'); - } -} -?> - - - - OpenSondage Installation - - - -
    -

    OpenSondage Installation

    -
    -
    - General - -
    - - -
    -
    - - -
    -
    - - -
    -
    -
    - Database - -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - - diff --git a/install/InstallComposer.php b/install/InstallComposer.php new file mode 100644 index 0000000..a370f95 --- /dev/null +++ b/install/InstallComposer.php @@ -0,0 +1,90 @@ +getComposer().'/src/bootstrap.php'; + + $this->initEnv(); + + $application = new \Composer\Console\Application(); + $application->setAutoExit(false); + + $input = new \Symfony\Component\Console\Input\ArrayInput(array( + 'command' => 'install', + '-d' => __DIR__.'/..', + '-vvv', + '--optimize-autoloader', + )); + $output = new \Symfony\Component\Console\Output\NullOutput(); + + $application->run($input, $output); + } + + /** + * @return string + */ + private function getComposer() + { + if (null === $this->composer) { + $this->initComposer(); + } + + return $this->composer; + } + + private function initComposer() + { + // Composer exist ? + $locations = array( + __DIR__.'/../composer.phar', + '/usr/bin/composer.phar', + '/usr/local/bin/composer.phar', + ); + + $this->composer = null; + foreach ($locations as $location) { + if (file_exists($location) === true) { + $this->composer = $location; + break; + } + } + + // If composer not found, download it ! + if (null === $this->composer) { + if (!file_put_contents( + __DIR__.'/../composer.phar', + file_get_contents('https://getcomposer.org/composer.phar') + ) + ) { + throw new \Exception('Impossible to download composer'); + } + + $this->composer = __DIR__.'/../composer.phar'; + } + } + + private function initEnv() + { + $composer_home = getenv('COMPOSER_HOME'); + $personal_home = getenv('HOME'); + if (empty($composer_home) === true && empty($personal_home) === true) { + putenv('COMPOSER_HOME='.sys_get_temp_dir()); + } + } + +} diff --git a/install/InstallConfiguration.php b/install/InstallConfiguration.php new file mode 100644 index 0000000..3595312 --- /dev/null +++ b/install/InstallConfiguration.php @@ -0,0 +1,73 @@ + 'Application name', + 'email' => 'email address', + 'no-reply-email' => 'no-reply@mydomain.com', + 'db-name' => 'database name', + 'db-user' => 'database user', + 'db-pass' => 'database password', + 'db-host' => 'database server', + 'db-type' => 'database type', + ); + + /** + * @param array $datas + */ + public function __construct(array $datas) + { + $this->datas = $datas; + } + + /** + * @return bool + */ + public function checkValues() + { + foreach (array_keys($this->checks) as $key) { + if (isset($this->datas[$key]) === false) { + return false; + } + } + + return true; + } + + public function copy($template, $destination) + { + $configuration = file_get_contents($template); + if (false === $configuration) { + throw new \Exception('Impossible to read template configuration'); + } + + $configuration = $this->convertConfigurationFile($configuration); + + if (file_put_contents($destination, $configuration) === false) { + throw new \Exception('Impossible to save configuration'); + } + } + + + private function convertConfigurationFile($content) + { + foreach ($this->checks as $replace => $search) { + $content = str_replace( + '\'<'.$search.'>\'', + var_export($this->datas[$replace], true), + $content + ); + } + + return $content; + } +} diff --git a/install/InstallSql.php b/install/InstallSql.php new file mode 100644 index 0000000..749767b --- /dev/null +++ b/install/InstallSql.php @@ -0,0 +1,24 @@ +ErrorMsg() !== '') { + throw new \Exception('Bad database configuration : '.$connect->ErrorMsg()); + } + + $sqls = explode("\n", file_get_contents(__DIR__.'/install.mysql.auto.sql')); + foreach ($sqls as $sql) { + $sql = trim($sql); + if (empty($sql) === true) { + continue; + } + + $query = $connect->Prepare($sql); + $cleaning = $connect->Execute($query); + } + } +} diff --git a/install/error.html b/install/error.html new file mode 100644 index 0000000..a758055 --- /dev/null +++ b/install/error.html @@ -0,0 +1,33 @@ + + + + + OpenSondage Installation + + + + + + +
    +
    +

    + OpenSondage +

    +

    Make your polls

    + +
    +
    +

    OpenSondage Installation

    + + +
    +
    + + diff --git a/install/install.css b/install/install.css new file mode 100644 index 0000000..18f3dc5 --- /dev/null +++ b/install/install.css @@ -0,0 +1,11 @@ +header { + padding-bottom: 0; +} + +main { + padding-top: 0; +} + +fieldset { + margin: 1.5em 0; +} \ No newline at end of file diff --git a/install/install.html b/install/install.html new file mode 100644 index 0000000..004097a --- /dev/null +++ b/install/install.html @@ -0,0 +1,72 @@ + + + + + OpenSondage Installation + + + + + + +
    +
    +

    + OpenSondage +

    +

    Make your polls

    + +
    +
    +

    OpenSondage Installation

    +
    +
    + General + +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    + Database + +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    + + diff --git a/install.mysql.auto.sql b/install/install.mysql.auto.sql similarity index 100% rename from install.mysql.auto.sql rename to install/install.mysql.auto.sql diff --git a/install.mysql.sql b/install/install.mysql.sql similarity index 100% rename from install.mysql.sql rename to install/install.mysql.sql diff --git a/install/install.php b/install/install.php new file mode 100644 index 0000000..8cf9f3f --- /dev/null +++ b/install/install.php @@ -0,0 +1,43 @@ +check() === false) { + ini_set('max_execution_time', 0); + $composer->install(); + } + + // Save configuration + $configuration = new InstallConfiguration($_POST); + if ($configuration->checkValues() === false) { + throw new \Exception('Bad value for configuration'); + } + + $configuration->copy($configuration_file.'.template', $configuration_file); + + // Inject database + $sql = new InstallSql(); + $sql->inject(); + + header('Location: ../index.php'); + die(); + } catch (Exception $e) { + require_once __DIR__.'/error.html'; + die(); + } +} + +require_once __DIR__.'/install.html'; From 057ebba96124bc791bd0f0be51daf579cb4c5b23 Mon Sep 17 00:00:00 2001 From: FramaJosephK Date: Tue, 2 Dec 2014 18:15:15 +0100 Subject: [PATCH 103/151] Fix horaires vides + fix mails qui partent pas + de_DE (cherry picked from commit 2c49a9f0acdc6ee1164d3d533a35b273af30c263) Conflicts: adminstuds.php creation_sondage.php locale/de_DE/LC_MESSAGES/Studs.mo locale/de_DE/LC_MESSAGES/Studs.po studs.php --- locale/de_DE/LC_MESSAGES/Studs.mo | Bin 17969 -> 18237 bytes locale/de_DE/LC_MESSAGES/Studs.po | 228 +++++++++++++++--------------- 2 files changed, 114 insertions(+), 114 deletions(-) diff --git a/locale/de_DE/LC_MESSAGES/Studs.mo b/locale/de_DE/LC_MESSAGES/Studs.mo index b9acebd24cefe6b724c68f3955bc40c55ba42c46..1fae2345c1667109f2872927c3b1ccbffd98b39a 100644 GIT binary patch delta 6423 zcmai$eQ;f6oyVWhH`>zo($Y8jq;HfqH*L~4nigo%CZ&c(At_m_INbC;NltU`x#66X zmW|+5%A)u}SI;`b;wa+aAfh7B=`xzC5XRjFmno}@f9xorE0tZPqB1zhsGsjSC&^`Z zXSb8y&+|OzJTJfR@8vmOy9xT@My-rhKuQc3~K%tp*DCF>Og0p)_DdlhtI=h@HKcboUt&aU06vM*v4{0T~l+33k0W&vc#tcOzODkuXEX8k@f2{;Sh z2l+FVuk$O*o`&-MvrsSm1j^F?f*zcX-bEO~mGC8~dFB#hJ_M%0et0L8#pj_mo`)>r zrBDan2xUk!yovoy8x3vnAiNLGTbc&RqfisR1v!H`3mf4%C`FcHj)HLm)Pjvr%IwJc z*Fq_B9h9ODYTnJ+^N+v_*x%eq5%P-vX5lH)P}atbYsC z0Zu^8y9dezUxNzP$1*+x6;nThv)JEEM`ua780v(VLP=Ji^>;xdtr+YJ=Od{z)hc zzXWyA(^-EMYMmd$&G45n2bT~qh->!4PrxJ4!t*Q9e>IJ{^l-n~3gzPtsD(cQAA@(p zJ+PU`x)a_G?|{=u8O^&JI`|bR%Vx8vq+bAa@Fnp5a3j=vAA@qiYpc<}hsMQg(v#l; zHSsQ}N_7%Sk$a$|{yLPTBXB+Z0Ypvn29$*h)~3pB%Gd&xO^4tlcm(oi`uN!dKUJZz zlg1g?4Bvz*JUcmF7d!%+;1f`a{0_=B=CZWJE`Zv21>6C5!fWBpa0C1fltQnby! zR`AY*I#6X1jcqiRLfm5B15wcoLfmI!C|^GYrNsB4eEjclGW->s0$gB4x-_I8FJ#jE3@ib;c$r$*zO4d;n_U3Y70Z0jI;y zLA+tU40X^SK)K>|r~}NZPv5VDGH`d+KM46VH}bQA{mmz7NXmbJivAHOADxG?{4J;h z%_3qj-dqMP?1UI)A}E*L4`uPwP|Caj<>S|(-g^UH1Xq!pB!JljD>_*x4Q*I}Dllaz zMLr6(;1{5x{F`ttd=AcrFG3ycHK+|PY)HqqLELZlK?Pk2&VoZw`<#Hpxw*Rm{R=cs zF>n$t!F+A>5S$AC5q<$a2g|UuCB0UE0u=*qWt_V;b-Knv`K>fZ|$j88x<_#{;DeILrAU&8tDH*g-DMD9t6i=hs_32NSU z_&0DD)VwF56!>ST`9G@AP|%!%i{PXy(g#c7V){8KpS42y^m@1umY^2A9V*y94mJNF zsG$5F)Vy<0!TNis82J-aP}lBES=mP85(W-r?8*2+s0IHH%I6P5O&rPkXEVMGbwQ0ulrN&W$-^-55#y8|v!{@+VO!Ep-e#i!sL_Yt z5n%8d$U^2*@Wb#yC>O5Zon}cJD%Viz^9;M<1AD?`7x}m(D*qG zNjQZFlr$@#(rF9SU2s#zk7qmuW${m;EcpYx08YU?<@JS-fH!sUFwDb4a0HStW=)I4+WzmM+U}dhlfhG zq26{L=?}apddG0%|27=hYsw`zDBUD{+?-pw@ZE!vSN2Vd3nL6jd+|VSLrp#|=N8A0 zo2(=ezX3AlMnR=!||<~8a5>M6pO6U$)+Al_;!Cjz(#|U%)WdyRLUi;i9fVw z@n02OFQG!fBub#C^LmII$ubyV4zoF^ZS|v&j#p4jMS<(>WkPp(e4h|iER*s<4^g8t zHg0ZSok>^aXWKLJN*6B{)zQ)C8H?NG}*xWH=Z|4oU)>{V4K@@j4ylZ~J zbKyjw5ce(~X}Dx@Ywlp)E86Bl;KI<2DP13*Z|IzoC>pmn)=q8iaeg6;Z*JUMA*Ve2 z>=#MD91ihAaO3*Qxsi8QR*i}y7n6Q*Ga)2JnuX-D=+j3i5VDrQ|YoKg?sMnfqDHtR%UKPw$qgy6I zyt8ck9C7L5SGKI2rXXN)Jay|(rQ7*w2%z711*wWF=aJIRcBr7Rvxgk{A`zx|As7jE z8ghLSg{^u!q%!#huP-SKF6bXUO?cGVepe(KRFIO8!-gi)9lx^mrm0y{9oQCCS_9II za0!yCHH;_6tCO9e1U5+n#B)`CUynnz@q(zf?4F)roEUCLr;M|o_1rIOkqyW@0&!5 z@fUntnmvg>yZuY+a|iZ~Wxwk1aVn3=K}7j~=~D=k&|G4^8A?@G>(KfmMbvg*p9 za^6cpA;DS+<9PUr%Ud(2WAVhpW|X$=`7CWJ{OE9l~XX?kHz8plZj<13|DQ&Q5C=p4H`p59fryw>bX0#W;^s89y_ z*n=X3GbiodFok%uopIyt$0})Lwz;CbA5v;;Ik}MXMY5Z>21ZZ&*%B2 zNmN>Fsk)8plW9l}1M>{=R)z{#c&y@di~t3U+U~JRoZa_?$?JO2|5?tSZ8)4BD}` zT*UuswFKqkTr!~@D3=EL2T)N))eCHRn8uuXGo*IL{t+62*73l}OD! zVV1q|@;zr}7F?J_L})tVSNAOAi*sso?Gj$*s(b3&skkP|cW0k^*v2i*J1Y}Qu%6@^ zPau~DVjp+E3xde}zi*D!rX(BQ@%C8w_PO*MDB|OYi;oJlX50d{uXeZT<}#LlxRm2_ z&D+-gw*X2?NobQVn2E5DceLD^e*K(kX^!7+*>V9N2n~C`9shdo^YM50t(!yvil3}s zI9YCwr?z(PF1S*a>y=qe#`fov?}PEWK33Kvnx4siIq457vKb3f#dLU9D~Cs->viA zh=ts5#_@O$PQ`~X1E0mS@R0xf)f|;jjIBQ4!G-uAOvm$cRr2{t9LxPMPQ;M!)tJxy z7L@k)qYSVQC7^>S{T#yS_%asZCzywsQ#?zjB)ksJ;Q{Yd4^G0%uoA;~Hr|EO;WH>1 zc@ER?ZIthiq0Iaw%7D3yBGzIFE=LIe&!epUizpu)L7C}? z7{m|nTzXq zvDJT($-+s;lTkV-Lp>(I=&wF;_bK?JE^Q2@dmsBGuSfH?sl~CVU(F=)2XCB z4<+y-{4Q3be76N<2|k%c{`U_IUcGD^xgEsP~g8VZNZ%c5|%*8=$$CD@rPb=ZAKpR`|DU^(Sin27Rv%MoW z4`tw)*o3Wk9!7BvK8uo}_i-Gi5w#R=7D_;g0xlZ4n2s!qx(Lala*^dzKSWvU$5Arz z0?Hb{hGX#~Ov4lY{YiW~MX9g+=Wh|kTHgNyWgGU*^(JyTlDUKmaUmUU!Lx7|X5a(J z8KQoHQuV(>lB3>4320oEw=IiMzN^O!T!s?(DwKZL;~KmPCD3)kb8pYB$PmdLAW%e?tl2zrNWuUVkOXBh`p=7+(!= zA*s9-r9*=f>60ike+DUd^(SQV>T}dsMg=hm)r}H>i&E{oPy+cm${LTN1oT_X#P?8Y z<}*x8;v%=!D~eetFKSRuyrn1|S}2)_`rd>Sx!;A7%7>BVRlh;0k&jUV8e8WTT{UKL z--z27c^gWHT_}F_8@wSS1xKJy&!WSfQ3ZYfIfu0nZl;bh#155~V>_ zvv*&Da$k?qZV9sNY7NSOw_yS9z#QC*GJ)s(`!}#q_Wue0K^DiHe5g@6Za`VnZ=)3H zWhjA#Q3m=xF2#LFN9rrQ4hvenrPzUz+5IR>`YJM%I)Rdz>NftLL-v0Q7mIoD4nB(I z-y+@k3Q7mxTj>30>_$oXm_^?9%s@%yWV{Avp^f)q6{atyfUyB3gRkOQ_%2G#e2k?D zF23MGQdQjUrMwBHgI<)#uf`(Wfs zAvC`tG{9@9z%ZE)CVZrF}p*l)!2#`;hjj5 z)G-WTStt4DTHV5hbaWUc#jm48dIBYYFOm9E)4C`mya*TI!zlasO_Zu1*X>pJL>$X~ zA@*P~R$u^2a64AwzHWX5WvyT1fed^crI^x}cpVm_q`Vx*VD%F7RAz5V>b~(=M^aMK z%(02a{3|QlY@2i-)bcm!`Ucwl;^V%cpf(&VU`#v4E}J zc*u@wdoURDUT4)*bccciwiC5g--v4s@XZE$AP}`fjvBqe8MIwn57N=8;H1;lc98EJ zU8?nLt=qI6(+kagHB-&Dnzph*E2_J!SlkWkV8FG%o>pfl!XU}qnSa-mX7}4NT?zXF z+l@vXbLG5z(>iZxf(%h{aloxyZGJMZuCOy6A{7?7zA8eNhAo#&C^BsJ=9OhK^8tnl z_Q#!J^JZT4qz>D1`|Tk8dNYjFw$JWnzRBs2L_#4i2c*pZE}7UBGzgj3Ynx1dU2(bu z>1fkf*E^+q<4DAf1xbUW9nzya`&OD;>XtT*9_VLsq$YYgIeG(;%Q7WifpK_R!Es+*ubhBlRU|R=@2Gn!D;dO>RNLT-7jQz9?8`n&#)H ztTq?VkDH$st~KX2T4PA8+0z)C+T#Rc!I&k*ARYUQWBxF0nc2CZ%+wZ5Z(3=)AuB$l zPA%MWYn@FEN(NN7OSyzXrvrDiS79uxscE{uTK9CR3nW$6U^wUmqcN9ij8OP~JLim1 zKW{3{Pkx;&u2Tb2ZDGr_oO3u!lY=2DI=OR9d2{6yZ*`N4q(h@mu!6Q@zB8l7{GfSx z?s?vWZ&sZ--W<-CvXBDT(UD~Rx&8u&Tk>=IEZHm6u48ZT*4ON4Daz?~H^?9^wR0*( zw-#5lbl6O2Aiz_W@6?;G%YXENKuD^Gg*?52I?4hO;Ofmqb#TG)aVI) zbewFFoc!q_q^T7$p@n&c-o~WOhGd(n(<7O?7xsF=+2K=Zvyvy$`Urb2AP1sjau%^~ zOM~XfqTS}^SwmAh?4Vw2OIVH_r`Nt%kZobcw?Ca78A>i%@-SpWI_8hc|&ncQl(%%N&!|*-&)Gks`@Vo;6`Y>^GNnUc+{It+PFy;UbjsjIQ~qblTVTE0fjz zQi^Mibe~<~o#9&2Ky#^>_?d^f(M$Rk3`Ihm^n=V(j%P*2V&3O|9chj%*+Ma0(QAcm zE#Jo~&7LJ?m8Yxy>oGVm*=)%(AUUS@+hHE7m@}6;vIszCLZYH0K@MumS){xy`8X=f Gf&D+YEWY6Y diff --git a/locale/de_DE/LC_MESSAGES/Studs.po b/locale/de_DE/LC_MESSAGES/Studs.po index 297e281..68fb4da 100644 --- a/locale/de_DE/LC_MESSAGES/Studs.po +++ b/locale/de_DE/LC_MESSAGES/Studs.po @@ -19,7 +19,7 @@ msgstr "" ########### Generic ########### msgid "Make your polls" -msgstr "Erstelle Umfragen für dich" +msgstr "Eigene Umfragen erstellen" msgid "Home" msgstr "Home" @@ -49,25 +49,25 @@ msgid "Next" msgstr "Weiter" msgid "Back" -msgstr "Back" +msgstr "Zurück" msgid "Close" -msgstr "Close" +msgstr "Schließen" msgid "Your name" msgstr "Ihr Name" msgid "Your email address" -msgstr "Ihre E-Mail Addresse" +msgstr "Ihre E-Mail Adresse" msgid "(in the format name@mail.com)" -msgstr "(in the format name@mail.com)" +msgstr "(Format: name@mail.com)" msgid "Description" msgstr "Beschreibung" msgid "Back to the homepage of" -msgstr "Zurück zur Homepage von" +msgstr "Zurück zur Homepage von " msgid "Error!" msgstr "Fehler!" @@ -93,77 +93,77 @@ msgstr "Sprache wählen" ############ Homepage ############ msgid "Schedule an event" -msgstr "Erweiterte Umfrage" +msgstr "Termin finden" msgid "Make a classic poll" -msgstr "Umfrage" +msgstr "Klassische Umfrage" # 1st section msgid "What is that?" -msgstr "What is that?" +msgstr "Was ist das?" msgid "Framadate is an online service for planning an appointment or make a decision quickly and easily. No registration is required." -msgstr "Framadate is an online service for planning an appointment or make a decision quickly and easily. No registration is required." +msgstr "Framadate ist ein Online-Dienst, das Ihnen hilft, Termine zu finden oder Entscheidungen schnell und einfach zu treffen. Keine Registrierung ist erforderlich. " msgid "Here is how it works:" -msgstr "Here is how it works:" +msgstr "So geht es:" msgid "Make a poll" -msgstr "Make a poll" +msgstr "Umfrage erstellen" msgid "Define dates or subjects to choose" -msgstr "Define dates or subjects to choose" +msgstr "Datum- oder Auswahlmöglichkeiten definieren" msgid "Send the poll link to your friends or colleagues" -msgstr "Send the poll link to your friends or colleagues" +msgstr "Link zur Umfrage an Ihre Freunde oder Kollegen schicken" msgid "Discuss and make a decision" -msgstr "Discuss and make a decision" +msgstr "Besprechen und Entscheidung treffen" msgid "Do you want to " -msgstr "Do you want to " +msgstr "Wollen Sie sich " msgid "view an example?" -msgstr "schaue ein Beispiel an?" +msgstr "einen Beispiel ansehen?" # 2nd section msgid "The software" -msgstr "The software" +msgstr "Die Software" msgid "Framadate was initially based on " -msgstr "Framadate was initially based on " +msgstr "Framadate war am Anfang auf " msgid " a software developed by the University of Strasbourg. Today, it is devevoped by the association Framasoft" -msgstr " a software developed by the University of Strasbourg. Today, it is devevoped by the association Framasoft" +msgstr " basiert, eine von der Straßburg-Universität entwickelte Software. Heutzutage wird sie von der Framasoft-Vereinigung entwickelt." msgid "This software needs javascript and cookies enabled. It is compatible with the following web browsers:" -msgstr "This software needs javascript and cookies enabled. It is compatible with the following web browsers:" +msgstr "Für diese Software müssen Javascript und Cookie aktiviert sein. Sie ist mit den folgenden Browsers kompatibel:" msgid "It is governed by the " -msgstr "It is governed by the " +msgstr "Sie ist lizenziert unter der " msgid "CeCILL-B license" -msgstr "CeCILL-B license" +msgstr "CeCILL-B Lizenz" # 3rd section msgid "Cultivate your garden" -msgstr "Cultivate your garden" +msgstr "Bestellen Sie ihren Garten" msgid "To participate in the software development, suggest improvements or simply download it, please visit " -msgstr "To participate in the software development, suggest improvements or simply download it, please visit " +msgstr "Um zur Software-Entwicklung teilzunehmen, Verbesserungen vorzuschlagen oder um sie herunterzuladen, gehen Sie auf " msgid "the development site" -msgstr "the development site" +msgstr "die Entwicklung-Seite" msgid "If you want to install the software for your own use and thus increase your independence, we help you on:" -msgstr "If you want to install the software for your own use and thus increase your independence, we help you on:" +msgstr "Wenn Sie die Software für Ihre eigene Nutzung installieren möchten und Ihre Eigenständigkeit erhöhen, helfen wir Sie auf:" ############## Poll ############## msgid "Poll administration" -msgstr "Poll administration" +msgstr "Umfrage-Verwaltung" msgid "Legend:" -msgstr "Legend:" +msgstr "Legende:" # Jumbotron adminstuds.php (+ studs.php) msgid "Back to the poll" @@ -173,25 +173,25 @@ msgid "Print" msgstr "Drucken" msgid "Export to CSV" -msgstr "Exportieren nach CSV" +msgstr "CSV-Export" msgid "Remove the poll" -msgstr "Lösche die Umfrage" +msgstr "Umfrage löschen" msgid "Title of the poll" msgstr "Titel der Umfrage" msgid "Edit the title" -msgstr "Bearbeite den Titel" +msgstr "Titel bearbeiten" msgid "Save the new title" msgstr "Den neuen Titel speichern" msgid "Cancel the title edit" -msgstr "Die Änderung des Titels abbrechen" +msgstr "Änderung des Titels abbrechen" msgid "Initiator of the poll" -msgstr "Inititator der Umfrage" +msgstr "Ersteller der Umfrage" msgid "Email" msgstr "E-Mail Adresse" @@ -203,70 +203,70 @@ msgid "Save the adress email" msgstr "E-Mail Adresse speichern" msgid "Cancel the adress email edit" -msgstr "Änderung der E-Mail Adresse ändern" +msgstr "Änderung der E-Mail Adresse abbrechen" msgid "Edit the description" -msgstr "Die Beschreibung bearbeiten" +msgstr "Beschreibung bearbeiten" msgid "Save the description" -msgstr "Die Beschreibung speichern" +msgstr "Beschreibung speichern" msgid "Cancel the description edit" -msgstr "Die Änderung der Beschreibung verwerfen" +msgstr "Änderung der Beschreibung verwerfen" msgid "Public link of the poll" msgstr "Öffentlicher Link zur Umfrage" msgid "Admin link of the poll" -msgstr "Administrator Link zur Umfrage" +msgstr "Administrator-Link der Umfrage" msgid "Poll rules" -msgstr "Poll rules" +msgstr "Regeln der Umfrage" msgid "Edit the poll rules" -msgstr "Edit the poll rules" +msgstr "Regeln der Umfrage bearbeiten" msgid "Votes and comments are locked" -msgstr "Votes and comments are locked" +msgstr "Abstimmungen und Kommentare sind gesperrt" msgid "Votes and comments are open" -msgstr "Votes and comments are open" +msgstr "Abstimmungen und Kommentare sind möglich" msgid "Votes are editable" -msgstr "Votes are editable" +msgstr "Die Abstimmungen können geändert werden" msgid "Save the new rules" -msgstr "Save the new rules" +msgstr "Neue Regeln speichern" msgid "Cancel the rules edit" -msgstr "Cancel the rules edit" +msgstr "Neue Regeln nicht speichern" # Help text adminstuds.php msgid "As poll administrator, you can change all the lines of this poll with this button" msgstr "Als Administrator der Umfrage, können Sie alle Zeilen der Umfrage über diesen Button ändern" msgid "remove a column or a line with" -msgstr "entfernen Sie eine Zeile oder eine Spalte" +msgstr "Zeile oder Spalte entfernen mit" msgid "and add a new column with" -msgstr "und fügen Sie eine neue Spalte hinzu" +msgstr "und neue Spalte hinzufügen mit" msgid "Finally, you can change the informations of this poll like the title, the comments or your email address." -msgstr "Sie können auch die Informationen über diese Umfrage wie den Titel, Kommentare oder ihre E-Mail Adresse ändern" +msgstr "Sie können auch die Informationen dieser Umfrage wie Titel, Kommentare oder E-Mail Adresse ändern." # Help text studs.php msgid "If you want to vote in this poll, you have to give your name, choose the values that fit best for you and validate with the plus button at the end of the line." -msgstr "Wenn Sie bei dieser Umfrage abstimmen möchten, müssen Sie ihren Namen angeben. Wählen Sie die Daten, die für Sie am besten passen und bestätigen Sie diese über den Plus-Button am Ende der Zeile." +msgstr "Wenn Sie bei dieser Umfrage abstimmen möchten, müssen Sie ihren Namen angeben. Wählen Sie die Optionen, die für Sie am besten passen und bestätigen Sie diese über den Plus-Button am Ende der Zeile." # Poll results msgid "Votes of the poll " -msgstr "Votes of the poll " +msgstr "Abstimmungen der Umfrage " msgid "Remove the column" msgstr "Spalte entfernen" msgid "Add a column" -msgstr "Eine Spalte hinzufügen" +msgstr "Spalte hinzufügen" msgid "Edit the line:" msgstr "Zeile bearbeiten:" @@ -287,31 +287,31 @@ msgid "No" msgstr "Nein" msgid "Vote \"no\" for " -msgstr "Stimme « nein » für " +msgstr "Stimme « nein » für " msgid "Vote \"yes\" for " -msgstr "Stimme « ja » für " +msgstr "Stimme « ja » für " msgid "Vote \"ifneedbe\" for " -msgstr "Stimme « Wenn notwendig » für " +msgstr "Stimme « Wenn notwendig » für " msgid "Save the choices" -msgstr "Die Wahl speichern" +msgstr "Wahl speichern" msgid "Addition" msgstr "Hinzufügen" msgid "Best choice" -msgstr "Bste Wahl" +msgstr "Bste Option" msgid "Best choices" -msgstr "Besten Wahlen" +msgstr "Besten Optionen" msgid "The best choice at this time is:" -msgstr "Die beste Wahl ist derzeit:" +msgstr "Die beste Option ist derzeit:" msgid "The bests choices at this time are:" -msgstr "Die besten Wahlen sind derzeit:" +msgstr "Die beste Optionen sind derzeit:" msgid "with" msgstr "mit" @@ -326,45 +326,45 @@ msgid "for" msgstr "für" msgid "Remove all the votes" -msgstr "Remove all the votes" +msgstr "Alle Stimmungen löschen" msgid "Scroll to the left" -msgstr "Scroll to the left" +msgstr "Links scrollen" msgid "Scroll to the right" -msgstr "Scroll to the right" +msgstr "Rechts scrollen" # Comments msgid "Comments of polled people" -msgstr "Kommentare von befragten Personen" +msgstr "Kommentare von Teilnehmer" msgid "Remove the comment" msgstr "Kommentar entfernen" msgid "Add a comment in the poll" -msgstr "Ein Kommentar zur Umfrage hinzufügen" +msgstr "Kommentar zur Umfrage hinzufügen" msgid "Your comment" msgstr "Ihr Kommentar" msgid "Send the comment" -msgstr "Den Kommentar senden" +msgstr "Kommentar senden" msgid "anonyme" msgstr "anonym" msgid "Remove all the comments" -msgstr "Remove all the comments" +msgstr "Alle Kommentare löschen" # Add a colum adminstuds.php msgid "Column's adding" -msgstr "Eine Spalte hinzufügen" +msgstr "Spalte hinzufügen" msgid "You can add a new scheduling date to your poll." -msgstr "Sie können ihrer Umfrage ein Datum geben." +msgstr "Sie können zur Umfrage ein neues Datum hinzufügen." msgid "If you just want to add a new hour to an existant date, put the same date and choose a new hour." -msgstr "Wenn Sie nur eine neue Zeit zu einem existierenden Datum hinzufügen wollen, wählen Sie das selbe Datum und wählen Sie eine neue Zeit aus." +msgstr "Wenn Sie nur eine neue Uhrzeiteit zu einem existierenden Datum hinzufügen wollen, wählen Sie das selbe Datum und wählen Sie eine neue Zeit aus." # Remove poll adminstuds.php msgid "Confirm removal of your poll" @@ -381,30 +381,30 @@ msgstr "Ihre Umfrage wurde gelöscht!" # Errors adminstuds.php/studs msgid "This poll doesn't exist !" -msgstr "Diese Umfrage existiert nicht !" +msgstr "Diese Umfrage existiert nicht!" msgid "Enter a name" msgstr "Geben Sie einen Namen ein" msgid "The name you've chosen already exist in this poll!" -msgstr "Ihr eingegebener Name existiert bereits in dieser Umfrage" +msgstr "Der von Ihnen eingegebenen Name existiert bereits in dieser Umfrage" msgid "Enter a name and a comment!" -msgstr "Geben Sie ein Namen und ein Kommentar ein!" +msgstr "Geben Sie einen Namen und ein Kommentar ein!" msgid "Failed to insert the comment!" msgstr "Einfügen des Kommentars gescheitert!" msgid "Characters \" ' < et > are not permitted" -msgstr "Die Zeichen \" ' < et > sind nicht erlaubt !" +msgstr "Die Zeichen \" ' < und > sind nicht erlaubt !" msgid "The date is not correct !" -msgstr "Das Datum ist nicht korrekt !" +msgstr "Das Datum ist nicht korrekt!" ########### Step 1 ########### # Step 1 info_sondage.php msgid "Poll creation (1 on 3)" -msgstr "Erstellen der Umfrage (1 von 3)" +msgstr "Umfrage erstellen (1 von 3)" msgid "Framadate is not properly installed, please check the 'INSTALL' to setup the database before continuing." msgstr "Framadate ist nicht richtig installiert, lesen Sie 'INSTALL' um die Datenbank aufzusetzen bevor es weiter geht." @@ -422,14 +422,14 @@ msgid "Voters can modify their vote themselves." msgstr "Teilnehmer können ihre Antworten verändern" msgid "To receive an email for each new vote." -msgstr "Bei jeder neuen Stimme eine E-Mail erhalten." +msgstr "Bei jeder neuen Abstimmung eine E-Mail erhalten." msgid "Go to step 2" -msgstr "Go to step 2" +msgstr "Weiter zum 2. Schritt" # Errors info_sondage.php msgid "Enter a title" -msgstr "Einen Titel eingeben" +msgstr "Titel eingeben" msgid "Characters < > and \" are not permitted" msgstr "Die Zeichen < > und \" sind nicht erlaubt !" @@ -445,7 +445,7 @@ msgid "You haven't filled the first section of the poll creation." msgstr "Sie haben den ersten Teil der Umfrageerstellung nicht ausgefüllt." msgid "Back to step 1" -msgstr "Back to step 1" +msgstr "Zurück zum 1. Schritt" ########### Step 2 ########### # Step 2 choix_date.php @@ -453,16 +453,16 @@ msgid "Poll dates (2 on 3)" msgstr "Umfragedaten (2 von 3)" msgid "Choose the dates of your poll" -msgstr "Wählen Sie das Daturm ihrer Umfrage" +msgstr "Wählen Sie Terminmöglichkeiten für Ihre Umfrage" msgid "To schedule an event you need to propose at least two choices (two hours for one day or two days)." msgstr "Um eine Umfrage für einen Termin zu erstellen, müssen Sie mindestens zwei Auswahlmöglichkeiten angeben (zwei verschiedene Zeiten an einem Tag oder zwei Tage)." msgid "You can add or remove additionnal days and hours with the buttons" -msgstr "Sie können weitere Tage und Zeiten über diesen Button hinzufügen oder entfernen" +msgstr "Sie können weitere Tage und Uhrzeiten über diesen Button hinzufügen oder entfernen" msgid "For each selected day, you can choose, or not, meeting hours (e.g.: \"8h\", \"8:30\", \"8h-10h\", \"evening\", etc.)" -msgstr "Sie können (müssen aber nicht), für jeden ausgewählten Tage, Zeiten für den Treffpunkt (z.B. \"8h\", \"8:30\", \"8-10Uhr\", \"abend\", etc.) angeben." +msgstr "Sie können (müssen aber nicht), für jeden ausgewählten Tage, Zeiten für den Termin (z.B. \"8h\", \"8:30\", \"8-10Uhr\", \"Abends\", etc.) angeben." msgid "Day" msgstr "Tag" @@ -477,23 +477,23 @@ msgid "Add an hour" msgstr "Eine Uhrzeit hinzufügen" msgid "Copy hours of the first day" -msgstr "Die (Uhr)Zeiten des ersten Tags kopieren" +msgstr "Uhrzeiten des ersten Tags kopieren" msgid "Remove a day" -msgstr "Ein Tag entfernen" +msgstr "Einen Tag entfernen" msgid "Add a day" -msgstr "Ein Tag hinzufügen" +msgstr "Einen Tag hinzufügen" msgid "Remove all days" msgstr "Alle Tage entfernen" msgid "Remove all hours" -msgstr "Alle (Uhr)Zeiten löschen" +msgstr "Alle Uhrzeiten entfernen" # Step 2 choix_autre.php msgid "Poll subjects (2 on 3)" -msgstr "Umfragethema (2 von 3)" +msgstr "Umfragethemen (2 von 3)" msgid "To make a generic poll you need to propose at least two choices between differents subjects." msgstr "Um eine allgemeine Umfrage zu erstellen, benötigen Sie mindestens zwei Auswahlmöglichkeiten zwischen verschiedenen Themen." @@ -502,40 +502,40 @@ msgid "You can add or remove additional choices with the buttons" msgstr "Sie können über den Button zusätzliche Auswahlmöglichkeiten hinzufügen oder entfernen" msgid "It's possible to propose links or images by using " -msgstr "It's possible to propose links or images by using " +msgstr "Es besteht die Möglichkeit, Links oder Bilder vorszuschlagen mit " msgid "the Markdown syntax" -msgstr "the Markdown syntax" +msgstr "Markdown" msgid "Choice" msgstr "Wahl" msgid "Add a link or an image" -msgstr "Add a link or an image" +msgstr "Link oder Bild hinzufügen" msgid "These fields are optional. You can add a link, an image or both." -msgstr "These fields are optional. You can add a link, an image or both." +msgstr "Diese Felder sind optional. Sie können einen Link, ein Bild oder beide hinzufügen." msgid "URL of the image" -msgstr "URL of the image" +msgstr "URL des Bilds" msgid "Link" msgstr "Link" msgid "Alternative text" -msgstr "Alternative text" +msgstr "Alternativer Text" msgid "Remove a choice" -msgstr "Eine Auswahl entfernen" +msgstr "Eine Auswahlmöglichkeit entfernen" msgid "Add a choice" -msgstr "Eine Auswahl hinzufügen" +msgstr "Eine Auswahlmöglichkeit hinzufügen" msgid "Back to step 2" -msgstr "Back to step 2" +msgstr "Zurück zum 2. Schritt" msgid "Go to step 3" -msgstr "Go to step 3" +msgstr "Weiter zum 3. Schritt" ########### Step 3 ########### msgid "Removal date and confirmation (3 on 3)" @@ -545,7 +545,7 @@ msgid "Confirm the creation of your poll" msgstr "Bestätigen Sie die Erstellung ihrer Umfrage" msgid "List of your choices" -msgstr "List of your choices" +msgstr "Liste Ihrer Auswahlmöglichkeiten" msgid "Once you have confirmed the creation of your poll, you will be automatically redirected on the administration page of your poll." msgstr "Wenn Sie die Erstellung ihrer Umfrage bestätigt haben, werden sie automatisch zur Administrationsseite ihrer Umfrage weitergeleitet." @@ -568,7 +568,7 @@ msgid "Your poll will be automatically removed after 6 months." msgstr "Ihre Umfrage wird automatisch nach 6 Monaten gelöscht." msgid "You can set a closer removal date for it." -msgstr "Sie können jedoch auch ein anderes Löschdatum festlegen." +msgstr "Sie können auch ein anderes Löschdatum festlegen." msgid "Removal date (optional)" msgstr "Löschdatum (optional)" @@ -584,7 +584,7 @@ msgid "polls in the database at this time" msgstr "Umfragen derzeit in der Datenbank" msgid "Poll ID" -msgstr "Umfrage ID" +msgstr "Umfrage-ID" msgid "Format" msgstr "Format" @@ -596,16 +596,16 @@ msgid "Author" msgstr "Autor" msgid "Users" -msgstr "Benutzer" +msgstr "Nutzer" msgid "Actions" msgstr "Aktionen" msgid "See the poll" -msgstr "Betrachte die Umfrage" +msgstr "Umfrage sehen" msgid "Change the poll" -msgstr "Ändere die Umfrage" +msgstr "Umfrage ändern" msgid "Logs" msgstr "Verlauf" @@ -620,14 +620,14 @@ msgid "" "You can find your poll at the link" msgstr "" " hat eine Zeile ausgefüllt.\n" -"Sie finden Ihre Umfrage unter folgendem Link" +"Sie finden Ihre Umfrage unter dem folgenden Link:" msgid "Thanks for your confidence." msgstr "Danke für Ihr Vertrauen." msgid "\n" "--\n\n" -"« La route est longue, mais la voie est libre… »\n" +"« La route est longue, mais la voie est libre… »\n" "Framasoft ne vit que par vos dons (déductibles des impôts).\n" "Merci d'avance pour votre soutien http://soutenir.framasoft.org." msgstr "\n" @@ -638,13 +638,13 @@ msgstr "\n" # Mails adminstuds.php msgid "[ADMINISTRATOR] New settings for your poll" -msgstr "[ADMINISTRATOR] Neuer Einstellungen für Ihre Umfrage " +msgstr "[ADMINISTRATOR] Neue Einstellungen für Ihre Umfrage " msgid "" "You have changed the settings of your poll. \n" "You can modify this poll with this link" msgstr "" -"Sie haben den Einstellungen Ihrer Umfrage geändert. \n" +"Sie haben die Einstellungen Ihrer Umfrage geändert. \n" "Sie können Ihre Umfrage unter diesem Link ändern" # Mails creation_sondage.php @@ -652,26 +652,26 @@ msgid "" "This is the message you have to send to the people you want to poll. \n" "Now, you have to send this message to everyone you want to poll." msgstr "" -"Dies ist die Nachricht, diese den Personen gesendet haben, die an der Umfrage teilnehmen sollen. \n" -"Sie haben die Nachricht an alle Personen, die Sie befragen wollen, gesendet." +"Dies ist die Nachricht, die Sie an die Personen, die Sie zur Umfrage einladen möchten, schicken sollen. \n" +"Schicken Sie jetzt bitte diese Nachricht an alle Personen, die Sie zur Umfrage einladen möchten." msgid "hast just created a poll called" -msgstr " hat eine Umfrage erstellt (Name folgt) " +msgstr " hat eine Umfrage erstellt - Name folgt: " msgid "Thanks for filling the poll at the link above" -msgstr "Dankeschön, dass Sie die Umfrage unter dem obrigen Link ausgefüllt haben" +msgstr "Danke, dass Sie die Umfrage unter dem obrigen Link ausgefüllt haben" msgid "" "This message should NOT be sent to the polled people. It is private for the poll's creator.\n" "\n" "You can now modify it at the link above" msgstr "" -"Diese Nachricht sollte NICHT an die befragten Personen gesendet werden. Sie ist dem Umfrageautor vorbehalten.\n" +"Diese Nachricht sollte NICHT an die befragten Personen gesendet werden. Sie nur für den Autor der Umfrage gemeint.\n" "\n" "Sie können die Umfrage unter dem oberen Link bearbeiten " msgid "Author's message" -msgstr "Nachricht für den Autor " +msgstr "Nachricht vom Autor " msgid "For sending to the polled users" msgstr "Nachricht für die Teilnehmer" From e4d0487c216bcd25b249021e86c10186a476df82 Mon Sep 17 00:00:00 2001 From: "Spanti Nicola (RyDroid)" Date: Wed, 26 Nov 2014 18:32:50 +0100 Subject: [PATCH 104/151] Clearer names for LICENSE files Licence also exists in english. https://en.wiktionary.org/wiki/licence (cherry picked from commit 0e91c25789ea7d0f652ac1d0efa7872e367e3c82) --- LICENCE => LICENCE.fr.txt | 0 LICENSE => LICENSE.en.txt | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename LICENCE => LICENCE.fr.txt (100%) rename LICENSE => LICENSE.en.txt (100%) diff --git a/LICENCE b/LICENCE.fr.txt similarity index 100% rename from LICENCE rename to LICENCE.fr.txt diff --git a/LICENSE b/LICENSE.en.txt similarity index 100% rename from LICENSE rename to LICENSE.en.txt From f5ab47ff196b9817476f7b37ac788ae0a8b22250 Mon Sep 17 00:00:00 2001 From: "Spanti Nicola (RyDroid)" Date: Wed, 26 Nov 2014 20:11:20 +0100 Subject: [PATCH 105/151] Updating .gitignore (cherry picked from commit 151f18bd96ef9ea9c5ea231c3359e2129e29d97a) Conflicts: .gitignore --- .gitignore | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.gitignore b/.gitignore index 472c128..556e7bc 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,14 @@ vendor cache/ tpl_c/ +# Temp files +*~ +\#*\# + +# Cache +Thumbs.db + +# IDE .settings/ .project .idea/ From c3cff57bf39ce115d886544def6d8b5ec6cba696 Mon Sep 17 00:00:00 2001 From: "Spanti Nicola (RyDroid)" Date: Wed, 26 Nov 2014 23:47:40 +0100 Subject: [PATCH 106/151] Small cleaning of choix_date.php (cherry picked from commit 9017676f70a59a0676be92d33794a48147a34e80) Conflicts: choix_date.php --- choix_date.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/choix_date.php b/choix_date.php index 6671def..aa9d7ca 100644 --- a/choix_date.php +++ b/choix_date.php @@ -5,7 +5,7 @@ * http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.txt * * Authors of STUdS (initial project): Guilhem BORGHESI (borghesi@unistra.fr) and Raphaël DROZ - * Authors of Framadate/OpenSondate: Framasoft (https://github.com/framasoft) + * Authors of Framadate/OpenSondate: Framasoft (https://github.com/framasoft https://git.framasoft.org/framasoft/framadate/) * * ============================= * @@ -14,7 +14,7 @@ * http://www.cecill.info/licences/Licence_CeCILL-B_V1-fr.txt * * Auteurs de STUdS (projet initial) : Guilhem BORGHESI (borghesi@unistra.fr) et Raphaël DROZ - * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) + * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft https://git.framasoft.org/framasoft/framadate/) */ use Framadate\Services\LogService; use Framadate\Services\PollService; @@ -41,8 +41,8 @@ if (is_readable('bandeaux_local.php')) { // Step 1/4 : error if $_SESSION from info_sondage are not valid if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || ($config['use_smtp'] && !isset($_SESSION['form']->admin_mail))) { - Utils::print_header ( _("Error!") ); - bandeau_titre(_("Error!")); + Utils::print_header ( _('Error!') ); + bandeau_titre(_('Error!')); echo '
    @@ -151,8 +151,8 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || // Step 3/4 : Confirm poll creation if (!empty($_POST['choixheures']) && !isset($_SESSION['form']->totalchoixjour)) { - Utils::print_header ( _("Removal date and confirmation (3 on 3)") ); - bandeau_titre(_("Removal date and confirmation (3 on 3)")); + Utils::print_header ( _('Removal date and confirmation (3 on 3)') ); + bandeau_titre(_('Removal date and confirmation (3 on 3)')); $_SESSION['form']->sortChoices(); $last_date = $_SESSION['form']->lastChoice()->getName(); @@ -198,7 +198,7 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) ||

    '. _('Once you have confirmed the creation of your poll, you will be automatically redirected on the administration page of your poll.'). '

    '; - if($config['use_smtp']==true){ + if($config['use_smtp'] == true) { echo '

    ' . _('Then, you will receive quickly two emails: one contening the link of your poll for sending it to the voters, the other contening the link to the administration page of your poll.') .'

    '; } echo ' @@ -222,7 +222,7 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) ||
    -

    '. _("Choose the dates of your poll") .'

    +

    '. _('Choose the dates of your poll') .'

    '. _('To schedule an event you need to propose at least two choices (two hours for one day or two days).').'

    '. _('You can add or remove additionnal days and hours with the buttons') .' '. _('Remove') .' '. _('Add') .'

    From 381c4444e3b4254750f427c23f8061263374c4d9 Mon Sep 17 00:00:00 2001 From: "Spanti Nicola (RyDroid)" Date: Thu, 27 Nov 2014 01:15:01 +0100 Subject: [PATCH 107/151] Minor modifications to Utils.php (cherry picked from commit e6d171a4b033aabe525f39dd463b5a686fb2d247) Conflicts: app/classes/Framadate/Utils.php --- app/classes/Framadate/Utils.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index 0d2788b..e515b76 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -55,8 +55,12 @@ class Utils { echo ' + '; if (!empty($title)) { + echo '' . stripslashes($title) . ' - ' . NOMAPPLICATION . ''; + } else { + echo '' . NOMAPPLICATION . ''; } echo ' From 35ba15219986dbf9ca64b4c84415a3ed4316b06d Mon Sep 17 00:00:00 2001 From: FramaJosephK Date: Wed, 3 Dec 2014 14:30:25 +0100 Subject: [PATCH 108/151] =?UTF-8?q?Retouches=20apr=C3=A8s=20s=C3=A9rie=20d?= =?UTF-8?q?e=20merges?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit 6751a8a9cfc84f2a49d46ccd2aec2ad0bcd72485) Conflicts: adminstuds.php app/classes/Framadate/Utils.php creation_sondage.php --- app/classes/Framadate/Utils.php | 6 +++--- install/error.html | 4 ++-- install/install.html | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/app/classes/Framadate/Utils.php b/app/classes/Framadate/Utils.php index e515b76..94dfeeb 100644 --- a/app/classes/Framadate/Utils.php +++ b/app/classes/Framadate/Utils.php @@ -19,9 +19,9 @@ namespace Framadate; class Utils { - /** - * @return string Server name - */ + /** + * @return string Server name + */ public static function get_server_name() { $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http'; $port = in_array($_SERVER['SERVER_PORT'], [80, 443]) ? '' : ':' . $_SERVER['SERVER_PORT']; diff --git a/install/error.html b/install/error.html index a758055..c6dc5ba 100644 --- a/install/error.html +++ b/install/error.html @@ -12,13 +12,13 @@

    - OpenSondage + Framadate

    Make your polls

    -

    OpenSondage Installation

    +

    Framadate Installation

    diff --git a/install/install.html b/install/install.html index 004097a..1caa3af 100644 --- a/install/install.html +++ b/install/install.html @@ -12,13 +12,13 @@

    - OpenSondage + Framadate

    Make your polls

    -

    OpenSondage Installation

    +

    Framadate Installation

    General From c9cdc88ffae25a9daf58b5018bb475f23a66e613 Mon Sep 17 00:00:00 2001 From: JosephK Date: Wed, 3 Dec 2014 15:04:12 +0100 Subject: [PATCH 109/151] =?UTF-8?q?Produit=20l'erreur=20=C2=AB=20PHP=20Par?= =?UTF-8?q?se=20error:=20=20syntax=20error,=20unexpected=20'')=20=3D=3D=3D?= =?UTF-8?q?=20true=20=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit dcee9d4cd69151d105473163407a61a24703bc9e) --- admin/index.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/admin/index.php b/admin/index.php index f03fa77..a320e25 100644 --- a/admin/index.php +++ b/admin/index.php @@ -114,6 +114,6 @@ echo ''."\n"; bandeau_pied(true); // si on annule la suppression, rafraichissement de la page -if (Utils::issetAndNoEmpty('annulesuppression') === true) { +/*if (Utils::issetAndNoEmpty('annulesuppression') === true) { // TODO -} +}*/ From f71326f496a201c85b00d5c146e8d3243b2abf72 Mon Sep 17 00:00:00 2001 From: FramaJosephK Date: Wed, 3 Dec 2014 18:39:01 +0100 Subject: [PATCH 110/151] Keep polls with bad expiration date in database (cherry picked from commit c15ce049ad12d8aeb08623c1936fa17e6f81941f) Conflicts: app/classes/Framadate/Utils.php --- app/classes/Framadate/FramaDB.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 54e186d..8c15772 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -268,7 +268,7 @@ class FramaDB { * @return array Array of old polls */ public function findOldPolls() { - $prepared = $this->prepare('SELECT * FROM ' . Utils::table('poll') . ' WHERE end_date < NOW() LIMIT 20'); + $prepared = $this->prepare('SELECT * FROM ' . Utils::table('poll') . ' WHERE end_date < NOW() AND date_fin != 0 LIMIT 20'); $prepared->execute([]); return $prepared->fetchAll(); From 98018de54167f9da55badabb577eb0f339209996 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 4 Jan 2015 18:49:57 +0100 Subject: [PATCH 111/151] Fix some things after cherry-picking --- app/classes/Framadate/FramaDB.php | 2 +- choix_autre.php | 4 +++- choix_date.php | 7 ++++--- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 8c15772..35797d1 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -268,7 +268,7 @@ class FramaDB { * @return array Array of old polls */ public function findOldPolls() { - $prepared = $this->prepare('SELECT * FROM ' . Utils::table('poll') . ' WHERE end_date < NOW() AND date_fin != 0 LIMIT 20'); + $prepared = $this->prepare('SELECT * FROM ' . Utils::table('poll') . ' WHERE end_date < NOW() AND end_date != 0 LIMIT 20'); $prepared->execute([]); return $prepared->fetchAll(); diff --git a/choix_autre.php b/choix_autre.php index 11e693f..586bc52 100644 --- a/choix_autre.php +++ b/choix_autre.php @@ -53,6 +53,8 @@ if (empty($_SESSION['form']->title) || empty($_SESSION['form']->admin_name) || ( bandeau_pied(); } else { + $min_time = time() + 86400; + $max_time = time() + (86400 * $config['default_poll_duration']); // Step 4 : Data prepare before insert in DB if (isset($_POST['confirmecreation'])) { @@ -174,7 +176,7 @@ if (empty($_SESSION['form']->title) || empty($_SESSION['form']->admin_name) || ( } $summary .= ''; - $end_date_str = utf8_encode(strftime('%d/%m/%Y', $_SESSION['form']->end_date)); //textual date + $end_date_str = utf8_encode(strftime('%d/%m/%Y', $max_time)); //textual date echo '
    diff --git a/choix_date.php b/choix_date.php index aa9d7ca..9c0ae49 100644 --- a/choix_date.php +++ b/choix_date.php @@ -54,13 +54,14 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || bandeau_pied(); } else { + $min_time = time() + 86400; + $max_time = time() + (86400 * $config['default_poll_duration']); + // Step 4 : Data prepare before insert in DB if (!empty($_POST['confirmation'])) { // Define expiration date $enddate = filter_input(INPUT_POST, 'enddate', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '#^[0-9]{2}/[0-9]{2}/[0-9]{4}$#']]); - $min_time = time() + (24 * 60 * 60); - $max_time = time() + (86400 * $config['default_poll_duration']); if (!empty($enddate)) { $registredate = explode('/', $enddate); @@ -172,7 +173,7 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || } $summary .= ''; - $end_date_str = utf8_encode(strftime('%d/%m/%Y', $_SESSION['form']->end_date)); //textual date + $end_date_str = utf8_encode(strftime('%d/%m/%Y', $max_time)); //textual date echo ' From 342440991ab62fabd78463ce72a5bb6f418cc4e7 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Sun, 4 Jan 2015 21:34:19 +0100 Subject: [PATCH 112/151] Composer: fix composer.json --- composer.json | 8 ++++++-- composer.lock | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index d84c53b..df41b50 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,9 @@ { "name": "framasoft/framadate", "description": "Application to facilitate the schedule of events or classic polls", - "keywords": "poll", + "keywords": [ + "poll" + ], "version": "0.9.0", "license": "CeCILL-B", @@ -12,6 +14,8 @@ }, "autoload": { - "psr-4": {"Framadate\\": "app/classes/Framadate/"} + "psr-4": { + "Framadate\\": "app/classes/Framadate/" + } } } diff --git a/composer.lock b/composer.lock index 7c555e2..c4f9e50 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "f74efbf4d641243e743a7e0c7587d227", + "hash": "4bf9a3fa30eb400c9ed140dd2d6fa266", "packages": [ { "name": "smarty/smarty", From 1e2877e863e484e0f70e53ac872f8e58a8df78ea Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Mon, 5 Jan 2015 23:30:47 +0100 Subject: [PATCH 113/151] Don't encode to HTML value before storing it to database --- .../Framadate/Services/InputService.php | 2 +- choix_autre.php | 3 ++- choix_date.php | 4 +++- infos_sondage.php | 19 +++++++++---------- 4 files changed, 15 insertions(+), 13 deletions(-) diff --git a/app/classes/Framadate/Services/InputService.php b/app/classes/Framadate/Services/InputService.php index d985bb5..aafed00 100644 --- a/app/classes/Framadate/Services/InputService.php +++ b/app/classes/Framadate/Services/InputService.php @@ -29,7 +29,7 @@ class InputService { * This method filter an array calling "filter_var" on each items. * Only items validated are added at their own indexes, the others are not returned. */ - function filterArray(array $arr, $type, $options) { + function filterArray(array $arr, $type, $options = null) { $newArr = []; foreach($arr as $id=>$item) { diff --git a/choix_autre.php b/choix_autre.php index 586bc52..95ba3cd 100644 --- a/choix_autre.php +++ b/choix_autre.php @@ -134,7 +134,8 @@ if (empty($_SESSION['form']->title) || empty($_SESSION['form']->admin_name) || ( $_SESSION['form']->clearChoices(); foreach ($_POST['choices'] as $c) { if (!empty($c)) { - $choice = new Choice(htmlentities(html_entity_decode($c, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8')); + $c = filter_var($c, FILTER_SANITIZE_STRING); + $choice = new Choice($c); $_SESSION['form']->addChoice($choice); } } diff --git a/choix_date.php b/choix_date.php index 9c0ae49..5170306 100644 --- a/choix_date.php +++ b/choix_date.php @@ -16,6 +16,7 @@ * Auteurs de STUdS (projet initial) : Guilhem BORGHESI (borghesi@unistra.fr) et Raphaël DROZ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft https://git.framasoft.org/framasoft/framadate/) */ +use Framadate\Services\InputService; use Framadate\Services\LogService; use Framadate\Services\PollService; use Framadate\Services\MailService; @@ -31,6 +32,7 @@ $logService = new LogService(LOG_FILE); $pollService = new PollService($connect, $logService); $mailService = new MailService($config['use_smtp']); $purgeService = new PurgeService($connect, $logService); +$inputService = new InputService(); if (is_readable('bandeaux_local.php')) { include_once('bandeaux_local.php'); @@ -135,7 +137,7 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || $choice = new Choice($time); $_SESSION['form']->addChoice($choice); - $schedules = $_POST['horaires'.$i]; + $schedules = $inputService->filterArray($_POST['horaires'.$i], FILTER_DEFAULT); for($j = 0; $j < count($schedules); $j++) { if (!empty($schedules[$j])) { $choice->addSlot($schedules[$j]); diff --git a/infos_sondage.php b/infos_sondage.php index da95104..b98ccd3 100644 --- a/infos_sondage.php +++ b/infos_sondage.php @@ -40,16 +40,15 @@ if ((isset($_GET['choix_sondage']) && $_GET['choix_sondage'] == 'date') || $_SESSION['form']->choix_sondage = $choix_sondage; } -// On teste toutes les variables pour supprimer l'ensemble des warnings PHP -// On transforme en entites html les données afin éviter les failles XSS -$post_var = array('poursuivre', 'titre', 'nom', 'adresse', 'commentaires', 'editable', 'receiveNewVotes', 'creation_sondage_date', 'creation_sondage_autre'); -foreach ($post_var as $var) { - if (isset($_POST[$var]) === true) { - $$var = htmlentities($_POST[$var], ENT_QUOTES, 'UTF-8'); - } else { - $$var = null; - } -} +// We clean the data +$poursuivre = filter_input(INPUT_POST, 'poursuivre', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^(creation_sondage_date|creation_sondage_autre)$/']]); +$titre = filter_input(INPUT_POST, 'titre', FILTER_SANITIZE_STRING); +$nom = filter_input(INPUT_POST, 'nom', FILTER_SANITIZE_STRING); +$adresse = filter_input(INPUT_POST, 'adresse', FILTER_VALIDATE_EMAIL); +$commentaires = filter_input(INPUT_POST, 'commentaires', FILTER_SANITIZE_STRING); +$editable = filter_input(INPUT_POST, 'editable', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^(on|off|true|false|1|0)$/']]); +$receiveNewVotes = filter_input(INPUT_POST, 'receiveNewVotes', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^(on|off|true|false|1|0)$/']]); + // On initialise également les autres variables $erreur_adresse = false; From 7727ffde739f71413f862b67f30fd544835685ab Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Mon, 5 Jan 2015 23:31:12 +0100 Subject: [PATCH 114/151] Workaround for LC_MESSAGES and some PHP versions --- app/inc/i18n.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/inc/i18n.php b/app/inc/i18n.php index 447518f..025efe7 100644 --- a/app/inc/i18n.php +++ b/app/inc/i18n.php @@ -50,7 +50,7 @@ if (strtoupper(substr(PHP_OS,0,3))=='WIN'){ putenv('LANGUAGE=');//sert à quoi? setlocale(LC_ALL, $locale); setlocale(LC_TIME, $locale); -//setlocale(LC_MESSAGES, $locale); +setlocale(5, $locale); // 5 = LC_MESSAGES (but LC_MESSAGES is not always present) $domain = 'Studs'; bindtextdomain($domain, 'locale'); From a4f3041a738494e6b21c1d90748ddc0f2995f674 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 6 Jan 2015 23:21:10 +0100 Subject: [PATCH 115/151] Implement error page template --- tpl/error.tpl | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 tpl/error.tpl diff --git a/tpl/error.tpl b/tpl/error.tpl new file mode 100644 index 0000000..baf5cbe --- /dev/null +++ b/tpl/error.tpl @@ -0,0 +1,8 @@ +{extends file='page.tpl'} + +{block name=main} +
    +

    {$error}

    +

    {_('Back to the homepage of')} {$APPLICATION_NAME}

    +
    +{/block} From 073bc9048ddabd6b6e7ec98003ba30f5759721d5 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Tue, 6 Jan 2015 23:52:52 +0100 Subject: [PATCH 116/151] Admin: Fix the admin page --- admin/index.php | 119 +++++++++--------- adminstuds.php | 2 +- app/classes/Framadate/FramaDB.php | 17 +++ app/classes/Framadate/Services/LogService.php | 7 +- .../Framadate/Services/PollService.php | 4 + .../Framadate/Services/SuperAdminService.php | 29 +++++ choix_autre.php | 2 +- choix_date.php | 2 +- exportcsv.php | 2 +- studs.php | 2 +- 10 files changed, 116 insertions(+), 70 deletions(-) create mode 100644 app/classes/Framadate/Services/SuperAdminService.php diff --git a/admin/index.php b/admin/index.php index a320e25..f1cc487 100644 --- a/admin/index.php +++ b/admin/index.php @@ -16,104 +16,103 @@ * Auteurs de STUdS (projet initial) : Guilhem BORGHESI (borghesi@unistra.fr) et Raphaël DROZ * Auteurs de Framadate/OpenSondage : Framasoft (https://github.com/framasoft) */ -namespace Framadate; + +use Framadate\Services\AdminPollService; +use Framadate\Services\LogService; +use Framadate\Services\PollService; +use Framadate\Services\SuperAdminService; +use Framadate\Utils; include_once __DIR__ . '/../app/inc/init.php'; include_once __DIR__ . '/../bandeaux.php'; +/* Services */ +/*----------*/ +$logService = new LogService(); +$pollService = new PollService($connect, $logService); +$adminPollService = new AdminPollService($connect, $pollService, $logService); +$superAdminService = new SuperAdminService($connect); + // Ce fichier index.php se trouve dans le sous-repertoire ADMIN de Studs. Il sert à afficher l'intranet de studs // pour modifier les sondages directement sans avoir reçu les mails. C'est l'interface d'aministration // de l'application. // Affichage des balises standards -Utils::print_header( _('Polls administrator') ); +Utils::print_header(_('Polls administrator')); bandeau_titre(_('Polls administrator')); -$sondage=$connect->Execute('SELECT * FROM sondage'); +$polls = $superAdminService->findAllPolls(); + +echo '' . "\n"; -echo' - '."\n"; // Test et affichage du bouton de confirmation en cas de suppression de sondage -while($dsondage = $sondage->FetchNextObject(false)) { - if (Utils::issetAndNoEmpty('supprimersondage'.$dsondage->id_sondage) === true) { +foreach ($polls as $poll) { + if (!empty($_POST['supprimersondage' . $poll->id])) { echo '
    -

    '. _("Confirm removal of the poll ") .'"'.$dsondage->id_sondage.'

    -

    -

    +

    ' . _("Confirm removal of the poll ") . '"' . $poll->id . '

    +

    +

    '; } // Traitement de la confirmation de suppression - if (Utils::issetAndNoEmpty('confirmesuppression'.$dsondage->id_sondage) === true) { + if (!empty($_POST['confirmesuppression' . $poll->id])) { // On inclut la routine de suppression $date = date('H:i:s d/m/Y'); - if (Utils::remove_sondage($connect, $dsondage->id_sondage)) { - // ecriture des traces dans le fichier de logs - error_log($date . " SUPPRESSION: $dsondage->id_sondage\t$dsondage->format\t$dsondage->nom_admin\t$dsondage->mail_admin\n", 3, 'logs_studs.txt'); - } + $adminPollService->deleteEntirePoll($poll->id); } } -$sondage=$connect->Execute('SELECT * FROM sondage WHERE date_fin > DATE_SUB(now(), INTERVAL 3 MONTH) ORDER BY date_fin ASC'); -$nbsondages=$sondage->RecordCount(); +$btn_logs = (is_readable('../' . LOG_FILE)) ? '' . _("Logs") . '' : ''; -$btn_logs = (is_readable('logs_studs.txt')) ? ''. _("Logs") .'' : ''; - -echo '

    ' . $nbsondages. ' ' . _("polls in the database at this time") . $btn_logs .'

    '."\n"; +echo '

    ' . count($polls) . ' ' . _("polls in the database at this time") . $btn_logs . '

    ' . "\n"; // tableau qui affiche tous les sondages de la base echo ' - - - - - - - - - '."\n"; + + + + + + + + + ' . "\n"; $i = 0; -while($dsondage = $sondage->FetchNextObject(false)) { - /* possible en 1 bonne requête dans $sondage */ - $subjects = $connect->Execute("SELECT * FROM sujet_studs WHERE id_sondage='$dsondage->id_sondage'"); - $dsujets = $subjects->FetchObject(false); +foreach ($polls as $poll) { + $nb_users = $pollService->countVotesByPollId($poll->id); - $user_studs = $connect->Execute("SELECT * from user_studs WHERE id_sondage='$dsondage->id_sondage'"); - $nb_users = $user_studs->RecordCount(); - - echo ' - - - - - - '; - - if (strtotime($dsondage->date_fin) > time()) { - echo ''; + if ($poll->format === 'D') { + $format_html = ''. _('Date').''; } else { - echo ''; + $format_html = ''. _('Classic').''; } echo ' - - - - - '."\n"; + + + + + + '; + + if (strtotime($poll->end_date) > time()) { + echo ''; + } else { + echo ''; + } + echo ' + + + + + ' . "\n"; ++$i; } -echo '
    '. _('Poll ID') .''. _('Format') .''. _('Title') .''. _('Author') .''. _('Email') .''. _('Expiration\'s date') .''. _('Users') .''. _('Actions') .'
    ' . _('Poll ID') . '' . _('Format') . '' . _('Title') . '' . _('Author') . '' . _('Email') . '' . _('Expiration\'s date') . '' . _('Users') . '' . _('Actions') . '
    '.$dsondage->id_sondage.''.$dsondage->format.''. stripslashes($dsondage->titre).''.stripslashes($dsondage->nom_admin).''.stripslashes($dsondage->mail_admin).''.date('d/m/y', strtotime($dsondage->date_fin)).'' - . date('d/m/y', strtotime($dsondage->date_fin)) - . ''.$nb_users.'' . _('See the poll') . '' . _("Change the poll") . '
    ' . $poll->id . '' . $format_html . '' . htmlentities($poll->title) . '' . htmlentities($poll->admin_name) . '' . htmlentities($poll->admin_mail) . '' . date('d/m/y', strtotime($poll->end_date)) . '' . date('d/m/y', strtotime($poll->end_date)) . '' . $nb_users . '' . _('See the poll') . '' . _("Change the poll") . '
    '."\n"; +echo '' . "\n"; bandeau_pied(true); - -// si on annule la suppression, rafraichissement de la page -/*if (Utils::issetAndNoEmpty('annulesuppression') === true) { - // TODO -}*/ diff --git a/adminstuds.php b/adminstuds.php index 9883e42..0ab3563 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -36,7 +36,7 @@ $editingVoteId = 0; /* Services */ /*----------*/ -$logService = new LogService(LOG_FILE); +$logService = new LogService(); $pollService = new PollService($connect, $logService); $adminPollService = new AdminPollService($connect, $pollService, $logService); $inputService = new InputService(); diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 35797d1..15ae3ce 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -274,4 +274,21 @@ class FramaDB { return $prepared->fetchAll(); } + public function findAllPolls() { + $prepared = $this->prepare('SELECT * FROM ' . Utils::table('poll') . ' ORDER BY end_date ASC'); + $prepared->execute([]); + + return $prepared->fetchAll(); + } + + public function countVotesByPollId($poll_id) { + $prepared = $this->prepare('SELECT count(1) nb FROM ' . Utils::table('vote') . ' WHERE poll_id = ?'); + + $prepared->execute([$poll_id]); + $result = $prepared->fetch(); + $prepared->closeCursor(); + + return $result->nb; + } + } diff --git a/app/classes/Framadate/Services/LogService.php b/app/classes/Framadate/Services/LogService.php index 61c5e79..8ccb48f 100644 --- a/app/classes/Framadate/Services/LogService.php +++ b/app/classes/Framadate/Services/LogService.php @@ -8,10 +8,7 @@ namespace Framadate\Services; */ class LogService { - private $output; - - function __construct($output) { - $this->output = $output; + function __construct() { } /** @@ -21,7 +18,7 @@ class LogService { * @param $message string some message */ function log($tag, $message) { - error_log(date('Ymd His') . ' [' . $tag . '] ' . $message . "\n", 3, $this->output); + error_log(date('Ymd His') . ' [' . $tag . '] ' . $message . "\n", 3, LOG_FILE); } } diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 828be5a..949afcb 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -75,6 +75,10 @@ class PollService { return $this->connect->insertComment($poll_id, $name, $comment); } + public function countVotesByPollId($poll_id) { + return $this->connect->countVotesByPollId($poll_id); + } + function computeBestChoices($votes) { $result = []; foreach ($votes as $vote) { diff --git a/app/classes/Framadate/Services/SuperAdminService.php b/app/classes/Framadate/Services/SuperAdminService.php new file mode 100644 index 0000000..bea7b14 --- /dev/null +++ b/app/classes/Framadate/Services/SuperAdminService.php @@ -0,0 +1,29 @@ +connect = $connect; + } + + /** + * Return the list of all polls. + * + * @return array All the polls + */ + public function findAllPolls() { + return $this->connect->findAllPolls(); + } + +} + \ No newline at end of file diff --git a/choix_autre.php b/choix_autre.php index 95ba3cd..e9bd1d1 100644 --- a/choix_autre.php +++ b/choix_autre.php @@ -27,7 +27,7 @@ include_once __DIR__ . '/app/inc/init.php'; /* Service */ /*---------*/ -$logService = new LogService(LOG_FILE); +$logService = new LogService(); $pollService = new PollService($connect, $logService); $mailService = new MailService($config['use_smtp']); $purgeService = new PurgeService($connect, $logService); diff --git a/choix_date.php b/choix_date.php index 5170306..bfe0790 100644 --- a/choix_date.php +++ b/choix_date.php @@ -28,7 +28,7 @@ include_once __DIR__ . '/app/inc/init.php'; /* Service */ /*---------*/ -$logService = new LogService(LOG_FILE); +$logService = new LogService(); $pollService = new PollService($connect, $logService); $mailService = new MailService($config['use_smtp']); $purgeService = new PurgeService($connect, $logService); diff --git a/exportcsv.php b/exportcsv.php index 34b4155..f5efcd7 100644 --- a/exportcsv.php +++ b/exportcsv.php @@ -36,7 +36,7 @@ $poll = null; /* Services */ /*----------*/ -$logService = new LogService(LOG_FILE); +$logService = new LogService(); $pollService = new PollService($connect, $logService); /* PAGE */ diff --git a/studs.php b/studs.php index b7c91c8..b04ce05 100644 --- a/studs.php +++ b/studs.php @@ -36,7 +36,7 @@ $editingVoteId = 0; /* Services */ /*----------*/ -$logService = new LogService(LOG_FILE); +$logService = new LogService(); $pollService = new PollService($connect, $logService); $inputService = new InputService(); $mailService = new MailService($config['use_smtp']); From 1f8fd2e3e244d4f3ded848dd436708c4c78a301b Mon Sep 17 00:00:00 2001 From: "Olivier Perez [a570709]" Date: Wed, 7 Jan 2015 14:01:08 +0100 Subject: [PATCH 117/151] Admin: Move migration page + add landing page --- admin/index.php | 119 +-------------------------- migration.php => admin/migration.php | 30 ++++--- admin/polls.php | 118 ++++++++++++++++++++++++++ app/inc/init.php | 12 ++- tpl/admin/admin_page.tpl | 10 +++ tpl/admin/index.tpl | 12 +++ tpl/admin/migration.tpl | 35 ++++++++ tpl/head.tpl | 22 ++--- tpl/header.tpl | 4 +- 9 files changed, 218 insertions(+), 144 deletions(-) rename migration.php => admin/migration.php (74%) create mode 100644 admin/polls.php create mode 100644 tpl/admin/admin_page.tpl create mode 100644 tpl/admin/index.tpl create mode 100644 tpl/admin/migration.tpl diff --git a/admin/index.php b/admin/index.php index f1cc487..2d98b7e 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1,118 +1,5 @@ findAllPolls(); - -echo '
    ' . "\n"; - -// Test et affichage du bouton de confirmation en cas de suppression de sondage -foreach ($polls as $poll) { - if (!empty($_POST['supprimersondage' . $poll->id])) { - echo ' -
    -

    ' . _("Confirm removal of the poll ") . '"' . $poll->id . '

    -

    -

    -
    '; - } - - // Traitement de la confirmation de suppression - if (!empty($_POST['confirmesuppression' . $poll->id])) { - // On inclut la routine de suppression - $date = date('H:i:s d/m/Y'); - - $adminPollService->deleteEntirePoll($poll->id); - } -} - -$btn_logs = (is_readable('../' . LOG_FILE)) ? '' . _("Logs") . '' : ''; - -echo '

    ' . count($polls) . ' ' . _("polls in the database at this time") . $btn_logs . '

    ' . "\n"; - -// tableau qui affiche tous les sondages de la base -echo ' - - - - - - - - - - ' . "\n"; - -$i = 0; -foreach ($polls as $poll) { - $nb_users = $pollService->countVotesByPollId($poll->id); - - if ($poll->format === 'D') { - $format_html = ''. _('Date').''; - } else { - $format_html = ''. _('Classic').''; - } - echo ' - - - - - - '; - - if (strtotime($poll->end_date) > time()) { - echo ''; - } else { - echo ''; - } - echo ' - - - - - ' . "\n"; - ++$i; -} - -echo '
    ' . _('Poll ID') . '' . _('Format') . '' . _('Title') . '' . _('Author') . '' . _('Email') . '' . _('Expiration\'s date') . '' . _('Users') . '' . _('Actions') . '
    ' . $poll->id . '' . $format_html . '' . htmlentities($poll->title) . '' . htmlentities($poll->admin_name) . '' . htmlentities($poll->admin_mail) . '' . date('d/m/y', strtotime($poll->end_date)) . '' . date('d/m/y', strtotime($poll->end_date)) . '' . $nb_users . '' . _('See the poll') . '' . _("Change the poll") . '
    ' . "\n"; - -bandeau_pied(true); +$smarty->assign('title', _('Administration')); +$smarty->display('admin/index.tpl'); \ No newline at end of file diff --git a/migration.php b/admin/migration.php similarity index 74% rename from migration.php rename to admin/migration.php index 2617b84..07ffb2e 100644 --- a/migration.php +++ b/admin/migration.php @@ -4,11 +4,7 @@ use Framadate\Migration\From_0_8_to_0_9_Migration; use Framadate\Migration\Migration; use Framadate\Utils; -include_once __DIR__ . '/app/inc/init.php'; - -function output($msg) { - echo $msg . '
    '; -} +include_once __DIR__ . '/../app/inc/init.php'; // List a Migration sub classes to execute $migrations = [ @@ -43,12 +39,15 @@ $countFailed = 0; $countSkipped = 0; // Loop on every Migration sub classes +$success = []; +$fail = []; foreach ($migrations as $migration) { $className = get_class($migration); // Check if $className is a Migration sub class if (!$migration instanceof Migration) { - output('The class ' . $className . ' is not a sub class of Framadate\\Migration\\Migration.'); + $smarty->assign('error', 'The class ' . $className . ' is not a sub class of Framadate\\Migration\\Migration.'); + $smarty->display('error.tpl'); exit; } @@ -61,10 +60,10 @@ foreach ($migrations as $migration) { $migration->execute($pdo); if ($insertStmt->execute([$className])) { $countSucceeded++; - output('Migration done: ' . $className); + $success[] = $className; } else { $countFailed++; - output('Migration failed: ' . $className); + $fail[] = $className; } } else { $countSkipped++; @@ -74,7 +73,14 @@ foreach ($migrations as $migration) { $countTotal = $countSucceeded + $countFailed + $countSkipped; -output('Summary
    '); -output('Success: ' . $countSucceeded . ' / ' . $countTotal); -output('Fail: ' . $countFailed . ' / ' . $countTotal); -output('Skipped: ' . $countSkipped . ' / ' . $countTotal); +$smarty->assign('success', $success); +$smarty->assign('fail', $fail); + +$smarty->assign('countSucceeded', $countSucceeded); +$smarty->assign('countFailed', $countFailed); +$smarty->assign('countSkipped', $countSkipped); +$smarty->assign('countTotal', $countTotal); + +$smarty->assign('title', _('Migration')); + +$smarty->display('admin/migration.tpl'); diff --git a/admin/polls.php b/admin/polls.php new file mode 100644 index 0000000..f1cc487 --- /dev/null +++ b/admin/polls.php @@ -0,0 +1,118 @@ +findAllPolls(); + +echo '
    ' . "\n"; + +// Test et affichage du bouton de confirmation en cas de suppression de sondage +foreach ($polls as $poll) { + if (!empty($_POST['supprimersondage' . $poll->id])) { + echo ' +
    +

    ' . _("Confirm removal of the poll ") . '"' . $poll->id . '

    +

    +

    +
    '; + } + + // Traitement de la confirmation de suppression + if (!empty($_POST['confirmesuppression' . $poll->id])) { + // On inclut la routine de suppression + $date = date('H:i:s d/m/Y'); + + $adminPollService->deleteEntirePoll($poll->id); + } +} + +$btn_logs = (is_readable('../' . LOG_FILE)) ? '' . _("Logs") . '' : ''; + +echo '

    ' . count($polls) . ' ' . _("polls in the database at this time") . $btn_logs . '

    ' . "\n"; + +// tableau qui affiche tous les sondages de la base +echo ' + + + + + + + + + + ' . "\n"; + +$i = 0; +foreach ($polls as $poll) { + $nb_users = $pollService->countVotesByPollId($poll->id); + + if ($poll->format === 'D') { + $format_html = ''. _('Date').''; + } else { + $format_html = ''. _('Classic').''; + } + echo ' + + + + + + '; + + if (strtotime($poll->end_date) > time()) { + echo ''; + } else { + echo ''; + } + echo ' + + + + + ' . "\n"; + ++$i; +} + +echo '
    ' . _('Poll ID') . '' . _('Format') . '' . _('Title') . '' . _('Author') . '' . _('Email') . '' . _('Expiration\'s date') . '' . _('Users') . '' . _('Actions') . '
    ' . $poll->id . '' . $format_html . '' . htmlentities($poll->title) . '' . htmlentities($poll->admin_name) . '' . htmlentities($poll->admin_mail) . '' . date('d/m/y', strtotime($poll->end_date)) . '' . date('d/m/y', strtotime($poll->end_date)) . '' . $nb_users . '' . _('See the poll') . '' . _("Change the poll") . '
    ' . "\n"; + +bandeau_pied(true); diff --git a/app/inc/init.php b/app/inc/init.php index a9dc8b1..4c9eaf5 100644 --- a/app/inc/init.php +++ b/app/inc/init.php @@ -30,15 +30,17 @@ if (ini_get('date.timezone') == '') { date_default_timezone_set('Europe/Paris'); } +define('ROOT_DIR', __DIR__ . '/../../'); + require_once __DIR__ . '/constants.php'; require_once __DIR__ . '/i18n.php'; // Smarty require_once __DIR__ . '/../../vendor/smarty/smarty/libs/Smarty.class.php'; $smarty = new \Smarty(); -$smarty->setTemplateDir('tpl/'); -$smarty->setCompileDir('tpl_c/'); -$smarty->setCacheDir('cache/'); +$smarty->setTemplateDir(ROOT_DIR . '/tpl/'); +$smarty->setCompileDir(ROOT_DIR . '/tpl_c/'); +$smarty->setCacheDir(ROOT_DIR . '/cache/'); $smarty->caching = false; $smarty->assign('APPLICATION_NAME', NOMAPPLICATION); @@ -57,6 +59,10 @@ function smarty_modifier_markdown($md, $clear = false) { return Utils::markdown($md, $clear); } +function smarty_modifier_resource($link) { + return Utils::get_server_name() . $link; +} + // End- Smarty $connect = new FramaDB(DB_CONNECTION_STRING, DB_USER, DB_PASSWORD); diff --git a/tpl/admin/admin_page.tpl b/tpl/admin/admin_page.tpl new file mode 100644 index 0000000..2fb2f77 --- /dev/null +++ b/tpl/admin/admin_page.tpl @@ -0,0 +1,10 @@ +{extends 'page.tpl'} + +{block 'main'} + + {block 'admin_main'}{/block} +{/block} \ No newline at end of file diff --git a/tpl/admin/index.tpl b/tpl/admin/index.tpl new file mode 100644 index 0000000..11bf4b7 --- /dev/null +++ b/tpl/admin/index.tpl @@ -0,0 +1,12 @@ +{extends 'admin/admin_page.tpl'} + +{block 'main'} + +{/block} \ No newline at end of file diff --git a/tpl/admin/migration.tpl b/tpl/admin/migration.tpl new file mode 100644 index 0000000..6cd818c --- /dev/null +++ b/tpl/admin/migration.tpl @@ -0,0 +1,35 @@ +{extends 'admin/admin_page.tpl'} + +{block 'admin_main'} +
    +
    +

    {_('Summary')}

    + {_('Succeeded:')} {$countSucceeded} / {$countTotal} +
    + {_('Failed:')} {$countFailed} / {$countTotal} +
    + {_('Skipped:')} {$countSkipped} / {$countTotal} +
    +
    +

    {_('Success')}

    +
      + {foreach $success as $s} +
    • {$s}
    • + {foreachelse} +
    • {_('Nothing')}
    • + {/foreach} +
    +
    + +
    +

    {_('Fail')}

    +
      + {foreach $fail as $f} +
    • {$f}
    • + {foreachelse} +
    • {_('Nothing')}
    • + {/foreach} +
    +
    +
    +{/block} \ No newline at end of file diff --git a/tpl/head.tpl b/tpl/head.tpl index 6267892..98084de 100644 --- a/tpl/head.tpl +++ b/tpl/head.tpl @@ -9,19 +9,19 @@ {$APPLICATION_NAME} {/if} - - - - - - - - - - + + + + + + + + + + {if !empty($nav_js)} - + {/if} diff --git a/tpl/header.tpl b/tpl/header.tpl index 838de01..949d3b6 100644 --- a/tpl/header.tpl +++ b/tpl/header.tpl @@ -2,7 +2,7 @@ {if count($langs)>1}
    - {foreach $langs as $lang_key=>$lang_value} {/foreach} @@ -14,7 +14,7 @@ {/if} -

    {$APPLICATION_NAME}

    +

    {$APPLICATION_NAME}

    {if !empty($title)}

    {$title}

    {/if}
    From 2495a8002fa194e45d6fd686cbd5fdba36fc13da Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 7 Jan 2015 22:47:34 +0100 Subject: [PATCH 118/151] Admin: The polls page now use Smarty template --- admin/polls.php | 102 +++++------------- adminstuds.php | 1 + app/classes/Framadate/Services/LogService.php | 2 +- tpl/admin/polls.tpl | 63 +++++++++++ 4 files changed, 89 insertions(+), 79 deletions(-) create mode 100644 tpl/admin/polls.tpl diff --git a/admin/polls.php b/admin/polls.php index f1cc487..ac5780a 100644 --- a/admin/polls.php +++ b/admin/polls.php @@ -26,93 +26,39 @@ use Framadate\Utils; include_once __DIR__ . '/../app/inc/init.php'; include_once __DIR__ . '/../bandeaux.php'; +/* Variables */ +/* --------- */ + +$polls = null; +$poll_to_delete = null; + /* Services */ /*----------*/ + $logService = new LogService(); $pollService = new PollService($connect, $logService); $adminPollService = new AdminPollService($connect, $pollService, $logService); $superAdminService = new SuperAdminService($connect); -// Ce fichier index.php se trouve dans le sous-repertoire ADMIN de Studs. Il sert à afficher l'intranet de studs -// pour modifier les sondages directement sans avoir reçu les mails. C'est l'interface d'aministration -// de l'application. +/* PAGE */ +/* ---- */ -// Affichage des balises standards -Utils::print_header(_('Polls administrator')); -bandeau_titre(_('Polls administrator')); +if (!empty($_POST['delete_poll'])) { + $delete_id = filter_input(INPUT_POST, 'delete_poll', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^[a-z0-9]+$/']]); + $poll_to_delete = $pollService->findById($delete_id); +} + +// Traitement de la confirmation de suppression +if (!empty($_POST['delete_confirm'])) { + $poll_id = filter_input(INPUT_POST, 'delete_confirm', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^[a-z0-9]+$/']]); + $adminPollService->deleteEntirePoll($poll_id); +} $polls = $superAdminService->findAllPolls(); -echo '
    ' . "\n"; +// Assign data to template +$smarty->assign('polls', $polls); +$smarty->assign('poll_to_delete', $poll_to_delete); +$smarty->assign('log_file', is_readable('../' . LOG_FILE) ? LOG_FILE : null); -// Test et affichage du bouton de confirmation en cas de suppression de sondage -foreach ($polls as $poll) { - if (!empty($_POST['supprimersondage' . $poll->id])) { - echo ' -
    -

    ' . _("Confirm removal of the poll ") . '"' . $poll->id . '

    -

    -

    -
    '; - } - - // Traitement de la confirmation de suppression - if (!empty($_POST['confirmesuppression' . $poll->id])) { - // On inclut la routine de suppression - $date = date('H:i:s d/m/Y'); - - $adminPollService->deleteEntirePoll($poll->id); - } -} - -$btn_logs = (is_readable('../' . LOG_FILE)) ? '' . _("Logs") . '' : ''; - -echo '

    ' . count($polls) . ' ' . _("polls in the database at this time") . $btn_logs . '

    ' . "\n"; - -// tableau qui affiche tous les sondages de la base -echo ' - - - - - - - - - - ' . "\n"; - -$i = 0; -foreach ($polls as $poll) { - $nb_users = $pollService->countVotesByPollId($poll->id); - - if ($poll->format === 'D') { - $format_html = ''. _('Date').''; - } else { - $format_html = ''. _('Classic').''; - } - echo ' - - - - - - '; - - if (strtotime($poll->end_date) > time()) { - echo ''; - } else { - echo ''; - } - echo ' - - - - - ' . "\n"; - ++$i; -} - -echo '
    ' . _('Poll ID') . '' . _('Format') . '' . _('Title') . '' . _('Author') . '' . _('Email') . '' . _('Expiration\'s date') . '' . _('Users') . '' . _('Actions') . '
    ' . $poll->id . '' . $format_html . '' . htmlentities($poll->title) . '' . htmlentities($poll->admin_name) . '' . htmlentities($poll->admin_mail) . '' . date('d/m/y', strtotime($poll->end_date)) . '' . date('d/m/y', strtotime($poll->end_date)) . '' . $nb_users . '' . _('See the poll') . '' . _("Change the poll") . '
    ' . "\n"; - -bandeau_pied(true); +$smarty->display('admin/polls.tpl'); diff --git a/adminstuds.php b/adminstuds.php index 0ab3563..8de758c 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -27,6 +27,7 @@ include_once __DIR__ . '/app/inc/init.php'; /* Variables */ /* --------- */ + $admin_poll_id = null; $poll_id = null; $poll = null; diff --git a/app/classes/Framadate/Services/LogService.php b/app/classes/Framadate/Services/LogService.php index 8ccb48f..4f68463 100644 --- a/app/classes/Framadate/Services/LogService.php +++ b/app/classes/Framadate/Services/LogService.php @@ -18,7 +18,7 @@ class LogService { * @param $message string some message */ function log($tag, $message) { - error_log(date('Ymd His') . ' [' . $tag . '] ' . $message . "\n", 3, LOG_FILE); + error_log(date('Ymd His') . ' [' . $tag . '] ' . $message . "\n", 3, ROOT_DIR . LOG_FILE); } } diff --git a/tpl/admin/polls.tpl b/tpl/admin/polls.tpl new file mode 100644 index 0000000..c594caa --- /dev/null +++ b/tpl/admin/polls.tpl @@ -0,0 +1,63 @@ +{extends 'admin/admin_page.tpl'} + +{block 'admin_main'} +
    + {if $poll_to_delete} +
    +

    {_("Confirm removal of the poll ")}"{$poll_to_delete->id}"

    + +

    + + +

    +
    + {/if} + +

    + {$polls|count} {_('polls in the database at this time')} + {if $log_file} + {_('Logs')} + {/if} +

    + + + + + + + + + + + + + {foreach $polls as $poll} + + + + + + + + {if strtotime($poll->end_date) > time()} + + {else} + + {/if} + + + + + + {/foreach} +
    {_('Poll ID')}{_('Format')}{_('Title')}{_('Author')}{_('Email')}{_('Expiration\'s date')}{_('Users')}{_('Actions')}
    {$poll->id} + {if $poll->format === 'D'} + { _('Date')} + {else} + {_('Classic')} + {/if} + {htmlentities($poll->title)}{htmlentities($poll->admin_name)}{htmlentities($poll->admin_mail)}{date('d/m/y', strtotime($poll->end_date))}{strtotime($poll->end_date)|date_format:'d/m/Y'}TODO{_('See the poll')}{_('Change the poll')}
    +
    +{/block} \ No newline at end of file From c67a4c7c1447280d197345ebe580b0ed86a2a0ac Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 7 Jan 2015 23:16:42 +0100 Subject: [PATCH 119/151] Add some security with strip_tags + Don't encode quotes --- adminstuds.php | 28 ++++++++++++++-------------- app/inc/constants.php.template | 5 +++++ choix_autre.php | 2 +- choix_date.php | 2 +- studs.php | 16 ++++++++-------- 5 files changed, 29 insertions(+), 24 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index 8de758c..1cdff56 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -46,7 +46,7 @@ $inputService = new InputService(); /* ---- */ if (!empty($_GET['poll']) && strlen($_GET['poll']) === 24) { - $admin_poll_id = filter_input(INPUT_GET, 'poll', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^[a-z0-9]+$/']]); + $admin_poll_id = filter_input(INPUT_GET, 'poll', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => POLL_REGEX]]); $poll_id = substr($admin_poll_id, 0, 16); $poll = $pollService->findById($poll_id); } @@ -67,7 +67,7 @@ if (isset($_POST['update_poll_info'])) { // Update the right poll field if ($field == 'title') { - $title = filter_input(INPUT_POST, 'title', FILTER_DEFAULT); + $title = strip_tags($_POST['title']); if ($title) { $poll->title = $title; $updated = true; @@ -79,13 +79,13 @@ if (isset($_POST['update_poll_info'])) { $updated = true; } } elseif ($field == 'comment') { - $comment = filter_input(INPUT_POST, 'comment', FILTER_DEFAULT); + $comment = strip_tags($_POST['comment']); if ($comment) { $poll->comment = $comment; $updated = true; } } elseif ($field == 'rules') { - $rules = filter_input(INPUT_POST, 'rules', FILTER_DEFAULT); + $rules = strip_tags($_POST['rules']); switch ($rules) { case 0: $poll->active = false; @@ -127,7 +127,7 @@ if (!empty($_POST['edit_vote'])) { if (!empty($_POST['save'])) { // Save edition of an old vote $editedVote = filter_input(INPUT_POST, 'save', FILTER_VALIDATE_INT); - $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[012]$/']]); + $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => CHOICE_REGEX]]); if (empty($editedVote)) { $message = new Message('danger', _('Something is going wrong...')); @@ -146,8 +146,8 @@ if (!empty($_POST['save'])) { // Save edition of an old vote } } } elseif (isset($_POST['save'])) { // Add a new vote - $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9_ -]+$/i']]); - $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[012]$/']]); + $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => NAME_REGEX]]); + $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => CHOICE_REGEX]]); if (empty($name)) { $message = new Message('danger', _('Name is incorrect.')); @@ -204,8 +204,8 @@ if (isset($_POST['confirm_remove_all_votes'])) { // ------------------------------- if (isset($_POST['add_comment'])) { - $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9_ -]+$/i']]); - $comment = filter_input(INPUT_POST, 'comment', FILTER_DEFAULT); + $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => NAME_REGEX]]); + $comment = strip_tags($_POST['comment']); if (empty($name)) { $message = new Message('danger', _('Name is incorrect.')); @@ -308,7 +308,7 @@ if (!empty($_POST['delete_column'])) { } // ------------------------------- -// Delete a slot +// Add a slot // ------------------------------- if (isset($_POST['add_slot'])) { @@ -321,14 +321,14 @@ if (isset($_POST['add_slot'])) { } if (isset($_POST['confirm_add_slot'])) { if ($poll->format === 'D') { - $newdate = filter_input(INPUT_POST, 'newdate', FILTER_DEFAULT); - $newmoment = filter_input(INPUT_POST, 'newmoment', FILTER_DEFAULT); + $newdate = strip_tags($_POST['newdate']); + $newmoment = strip_tags($_POST['newmoment']); $ex = explode('/', $newdate); $result = $adminPollService->addSlot($poll_id, mktime(0, 0, 0, $ex[1], $ex[0], $ex[2]), $newmoment); } else { - $newslot = filter_input(INPUT_POST, 'choice', FILTER_DEFAULT); - $result = $adminPollService->addSlot($poll_id,$newslot, null); + $newslot = strip_tags($_POST['choice']); + $result = $adminPollService->addSlot($poll_id, $newslot, null); } if ($result) { diff --git a/app/inc/constants.php.template b/app/inc/constants.php.template index ca5db6a..d8faf34 100644 --- a/app/inc/constants.php.template +++ b/app/inc/constants.php.template @@ -55,6 +55,11 @@ $ALLOWED_LANGUAGES = [ 'de_DE' => 'Deutsch', ]; +// Regex +const POLL_REGEX = '/^[a-z0-9]+$/'; +const CHOICE_REGEX = '/^[012]$/'; +const NAME_REGEX = '/^[ a-z0-9_ -]+$/i'; + // Path to logo const LOGOBANDEAU = ''; diff --git a/choix_autre.php b/choix_autre.php index e9bd1d1..c16ed50 100644 --- a/choix_autre.php +++ b/choix_autre.php @@ -134,7 +134,7 @@ if (empty($_SESSION['form']->title) || empty($_SESSION['form']->admin_name) || ( $_SESSION['form']->clearChoices(); foreach ($_POST['choices'] as $c) { if (!empty($c)) { - $c = filter_var($c, FILTER_SANITIZE_STRING); + $c = strip_tags($c); $choice = new Choice($c); $_SESSION['form']->addChoice($choice); } diff --git a/choix_date.php b/choix_date.php index bfe0790..b94658f 100644 --- a/choix_date.php +++ b/choix_date.php @@ -140,7 +140,7 @@ if (!isset($_SESSION['form']->title) || !isset($_SESSION['form']->admin_name) || $schedules = $inputService->filterArray($_POST['horaires'.$i], FILTER_DEFAULT); for($j = 0; $j < count($schedules); $j++) { if (!empty($schedules[$j])) { - $choice->addSlot($schedules[$j]); + $choice->addSlot(strip_tags($schedules[$j])); } } } diff --git a/studs.php b/studs.php index b04ce05..96b2360 100644 --- a/studs.php +++ b/studs.php @@ -53,7 +53,7 @@ $mailService = new MailService($config['use_smtp']); function sendUpdateNotification($poll, $mailService) { if ($poll->receiveNewVotes && !isset($_SESSION['mail_sent'][$poll->id])) { - $subject = '[' . NOMAPPLICATION . '] ' . _('Poll\'s participation') . ' : ' . html_entity_decode($poll->title, ENT_QUOTES, 'UTF-8'); + $subject = '[' . NOMAPPLICATION . '] ' . _('Poll\'s participation') . ' : ' . $poll->title; $message = html_entity_decode('"$nom" ', ENT_QUOTES, 'UTF-8') . _('has filled a line.\nYou can find your poll at the link') . " :\n\n" . Utils::getUrlSondage($poll->admin_poll_id, true) . " \n\n" . @@ -68,8 +68,8 @@ function sendUpdateNotification($poll, $mailService) { /* PAGE */ /* ---- */ -if(!empty($_GET['poll'])) { - $poll_id = filter_input(INPUT_GET, 'poll', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9]+$/']]); +if (!empty($_GET['poll'])) { + $poll_id = filter_input(INPUT_GET, 'poll', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => POLL_REGEX]]); $poll = $pollService->findById($poll_id); } @@ -94,7 +94,7 @@ if (!empty($_POST['edit_vote'])) { if (!empty($_POST['save'])) { // Save edition of an old vote $editedVote = filter_input(INPUT_POST, 'save', FILTER_VALIDATE_INT); - $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[012]$/']]); + $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => CHOICE_REGEX]]); if (empty($editedVote)) { $message = new Message('danger', _('Something is going wrong...')); @@ -114,8 +114,8 @@ if (!empty($_POST['save'])) { // Save edition of an old vote } } } elseif (isset($_POST['save'])) { // Add a new vote - $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9_ -]+$/i']]); - $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[012]$/']]); + $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => NAME_REGEX]]); + $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => CHOICE_REGEX]]); if (empty($name)) { $message = new Message('danger', _('Name is incorrect.')); @@ -141,8 +141,8 @@ if (!empty($_POST['save'])) { // Save edition of an old vote // ------------------------------- if (isset($_POST['add_comment'])) { - $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'/^[a-z0-9_ -]+$/i']]); - $comment = filter_input(INPUT_POST, 'comment', FILTER_DEFAULT); + $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => NAME_REGEX]]); + $comment = strip_tags($_POST['comment']); if (empty($name)) { $message = new Message('danger', _('Name is incorrect.')); From afd6079420e55a10cc49042e100e5e16544eb9ff Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 7 Jan 2015 23:29:46 +0100 Subject: [PATCH 120/151] Issue #22 Enable vote name modification --- adminstuds.php | 3 ++- app/classes/Framadate/FramaDB.php | 6 +++--- app/classes/Framadate/Services/PollService.php | 4 ++-- studs.php | 6 +++--- tpl/part/vote_table_classic.tpl | 12 ++++++++++-- tpl/part/vote_table_date.tpl | 12 ++++++++++-- 6 files changed, 30 insertions(+), 13 deletions(-) diff --git a/adminstuds.php b/adminstuds.php index 1cdff56..b168345 100644 --- a/adminstuds.php +++ b/adminstuds.php @@ -126,6 +126,7 @@ if (!empty($_POST['edit_vote'])) { // ------------------------------- if (!empty($_POST['save'])) { // Save edition of an old vote + $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => NAME_REGEX]]); $editedVote = filter_input(INPUT_POST, 'save', FILTER_VALIDATE_INT); $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => CHOICE_REGEX]]); @@ -138,7 +139,7 @@ if (!empty($_POST['save'])) { // Save edition of an old vote if ($message == null) { // Update vote - $result = $pollService->updateVote($poll_id, $editedVote, $choices); + $result = $pollService->updateVote($poll_id, $editedVote, $name, $choices); if ($result) { $message = new Message('success', _('Update vote successfully.')); } else { diff --git a/app/classes/Framadate/FramaDB.php b/app/classes/Framadate/FramaDB.php index 15ae3ce..c41a439 100644 --- a/app/classes/Framadate/FramaDB.php +++ b/app/classes/Framadate/FramaDB.php @@ -238,10 +238,10 @@ class FramaDB { return $prepared->execute([$poll_id]); } - function updateVote($poll_id, $vote_id, $choices) { - $prepared = $this->prepare('UPDATE ' . Utils::table('vote') . ' SET choices = ? WHERE poll_id = ? AND id = ?'); + function updateVote($poll_id, $vote_id, $name, $choices) { + $prepared = $this->prepare('UPDATE ' . Utils::table('vote') . ' SET choices = ?, name = ? WHERE poll_id = ? AND id = ?'); - return $prepared->execute([$choices, $poll_id, $vote_id]); + return $prepared->execute([$choices, $name, $poll_id, $vote_id]); } function insertComment($poll_id, $name, $comment) { diff --git a/app/classes/Framadate/Services/PollService.php b/app/classes/Framadate/Services/PollService.php index 949afcb..5193081 100644 --- a/app/classes/Framadate/Services/PollService.php +++ b/app/classes/Framadate/Services/PollService.php @@ -58,10 +58,10 @@ class PollService { return $this->connect->allSlotsByPollId($poll_id); } - public function updateVote($poll_id, $vote_id, $choices) { + public function updateVote($poll_id, $vote_id, $name, $choices) { $choices = implode($choices); - return $this->connect->updateVote($poll_id, $vote_id, $choices); + return $this->connect->updateVote($poll_id, $vote_id, $name, $choices); } function addVote($poll_id, $name, $choices) { diff --git a/studs.php b/studs.php index 96b2360..09bddab 100644 --- a/studs.php +++ b/studs.php @@ -47,7 +47,7 @@ $mailService = new MailService($config['use_smtp']); /** * Send a notification to the poll admin to notify him about an update. * - * @param $poll Object The poll + * @param $poll stdClass The poll * @param $mailService MailService The mail service */ function sendUpdateNotification($poll, $mailService) { @@ -87,12 +87,12 @@ if (!empty($_POST['edit_vote'])) { $editingVoteId = filter_input(INPUT_POST, 'edit_vote', FILTER_VALIDATE_INT); } - // ------------------------------- // Something to save (edit or add) // ------------------------------- if (!empty($_POST['save'])) { // Save edition of an old vote + $name = filter_input(INPUT_POST, 'name', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => NAME_REGEX]]); $editedVote = filter_input(INPUT_POST, 'save', FILTER_VALIDATE_INT); $choices = $inputService->filterArray($_POST['choices'], FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => CHOICE_REGEX]]); @@ -105,7 +105,7 @@ if (!empty($_POST['save'])) { // Save edition of an old vote if ($message == null) { // Update vote - $result = $pollService->updateVote($poll_id, $editedVote, $choices); + $result = $pollService->updateVote($poll_id, $editedVote, $name, $choices); if ($result) { $message = new Message('success', _('Update vote successfully.')); sendUpdateNotification($poll, $mailService); diff --git a/tpl/part/vote_table_classic.tpl b/tpl/part/vote_table_classic.tpl index 13be21f..5fb4014 100644 --- a/tpl/part/vote_table_classic.tpl +++ b/tpl/part/vote_table_classic.tpl @@ -35,9 +35,15 @@ {* Edited line *} - {$vote->name} - {if $editingVoteId == $vote->id} + + +
    + + +
    + + {foreach $vote->choices as $id=>$choice} @@ -68,6 +74,8 @@ {* Voted line *} + {$vote->name} + {foreach $vote->choices as $choice} {if $choice==2} diff --git a/tpl/part/vote_table_date.tpl b/tpl/part/vote_table_date.tpl index 5983e8e..e3945a8 100644 --- a/tpl/part/vote_table_date.tpl +++ b/tpl/part/vote_table_date.tpl @@ -61,9 +61,15 @@ {* Edited line *} - {$vote->name} - {if $editingVoteId == $vote->id} + + +
    + + +
    + + {foreach $vote->choices as $k=>$choice} @@ -94,6 +100,8 @@ {* Voted line *} + {$vote->name} + {foreach $vote->choices as $k=>$choice} {if $choice==2} From 73a5bd3615361eb2625e16e4135a889082d66f69 Mon Sep 17 00:00:00 2001 From: Olivier PEREZ Date: Wed, 7 Jan 2015 23:30:55 +0100 Subject: [PATCH 121/151] Fix label "for" attribute --- tpl/part/poll_info.tpl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tpl/part/poll_info.tpl b/tpl/part/poll_info.tpl index 6729417..f74625b 100644 --- a/tpl/part/poll_info.tpl +++ b/tpl/part/poll_info.tpl @@ -45,9 +45,9 @@

    {$poll->admin_mail}

    \ No newline at end of file diff --git a/tpl/part/comments.tpl b/tpl/part/comments.tpl index 3170b5f..87a8be6 100644 --- a/tpl/part/comments.tpl +++ b/tpl/part/comments.tpl @@ -8,10 +8,10 @@ {foreach $comments as $comment}
    {if $admin} - + {/if} - {$comment->name}  - {nl2br($comment->comment)} + {$comment->name|html}  + {nl2br($comment->comment|html)}
    {/foreach} {/if} diff --git a/tpl/part/poll_info.tpl b/tpl/part/poll_info.tpl index c121d4d..7c1b220 100644 --- a/tpl/part/poll_info.tpl +++ b/tpl/part/poll_info.tpl @@ -1,16 +1,15 @@ -{* TODO Add a form maybe *} {$admin = $admin|default:false} {if $admin}
    {/if}
    -

    {$poll->title}{if $admin} {/if}

    +

    {$poll->title|html}{if $admin} {/if}

    {if $admin}