CSV Export: Implements export for classical polls

This commit is contained in:
Olivier PEREZ 2015-01-03 17:24:39 +01:00
parent 8f8956d70a
commit 985842edf3
7 changed files with 207 additions and 73 deletions

View File

@ -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);

View File

@ -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);
}

View File

@ -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;
}
}

View File

@ -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']));
$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).'",';
}
if (!$poll) {
$smarty->assign('error', 'This poll doesn\'t exist');
$smarty->display('error.tpl');
exit;
}
$input.="\r\n";
if (strpos($dsondage->sujet,'@') !== false) {
$input.=",";
foreach ($toutsujet as $value) {
$heures=explode("@",$value);
$input.= '"'.$heures[1].'",';
$slots = $pollService->allSlotsByPollId($poll_id);
$votes = $pollService->allVotesByPollId($poll_id);
// 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);
$titles_line .= str_repeat($title . ',', count($moments));
$moments_line .= implode(',', array_map('\Framadate\Utils::csvEscape', $moments)) . ',';
}
$input.="\r\n";
echo $titles_line . "\r\n";
echo $moments_line . "\r\n";
} else {
echo ',';
foreach ($slots as $slot) {
echo Utils::markdown($slot->title, true) . ',';
}
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('&quot;','""',$input);
die();
echo $content;

104
old_exportcsv.php Normal file
View File

@ -0,0 +1,104 @@
<?php
/**
* This software is governed by the CeCILL-B license. If a copy of this license
* is not distributed with this file, you can obtain one at
* 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)
*
* =============================
*
* Ce logiciel est régi par la licence CeCILL-B. Si une copie de cette licence
* ne se trouve pas avec ce fichier vous pouvez l'obtenir sur
* 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)
*/
namespace Framadate;
include_once __DIR__ . '/app/inc/init.php';
if(!isset($_GET['numsondage']) || ! preg_match(";^[\w\d]{16}$;i", $_GET['numsondage'])) {
header('Location: studs.php');
}
$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']));
$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('&quot;','""',$input);
die();

View File

@ -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);

View File

@ -22,7 +22,7 @@
<div class="col-md-5">
<div class="btn-group pull-right">
<button onclick="print(); return false;" class="btn btn-default"><span class="glyphicon glyphicon-print"></span> {_('Print')}</button>
<a href="{$SERVER_URL}export.php?poll={$poll_id}&mode=csv" class="btn btn-default"><span class="glyphicon glyphicon-download-alt"></span> {_('Export to CSV')}</a>
<a href="{$SERVER_URL}exportcsv.php?poll={$poll_id}" class="btn btn-default"><span class="glyphicon glyphicon-download-alt"></span> {_('Export to CSV')}</a>
{if $admin}
<button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown">
<span class="glyphicon glyphicon-trash"></span> <span class="sr-only">{_("Remove")}</span> <span class="caret"></span>