1<?php
2
3if (!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../../../') . '/');
4require_once DOKU_INC . 'inc/init.php';
5
6/** @var helper_plugin_questionnaire $helper */
7$helper = plugin_load('helper', 'questionnaire');
8$ID = getID();
9
10if (!auth_isadmin()) {
11    http_status(403);
12    echo $helper->getLang('forbidden');
13    exit;
14}
15
16$quest = $helper->getQuestionnaire($ID);
17
18if (!$quest) {
19    http_status(404);
20    echo $helper->getLang('noquestionnaire');
21    exit;
22}
23
24$db = $helper->getDB();
25if (!$db) {
26    http_status(500);
27    echo $helper->getLang('nodb');
28    exit;
29}
30
31$items = array_merge(['answered_on', 'answered_by'], $helper->getQuestionIDs($ID));
32$lastuser = '';
33
34// first row is the header
35$data = array_combine($items, $items);
36$data['answered_on'] = $helper->getLang('answered_on');
37$data['answered_by'] = $helper->getLang('answered_by');
38
39header('Content-Type: text/csv; charset=utf-8');
40header('Content-Disposition: attachment; filename="' . $ID . '.csv"');
41$resp = $db->query('SELECT * FROM answers WHERE page = ? ORDER BY answered_on, answered_by', $ID);
42$fp = fopen('php://output', 'w');
43while ($row = $resp->fetch(PDO::FETCH_ASSOC)) {
44    // if this row is for a new user, output the last user's data
45    $user = $row['answered_by'];
46    if ($user != $lastuser) {
47        fputcsv($fp, array_values($data));
48
49        // prepare new data array
50        $lastuser = $user;
51        $data = array_fill_keys($items, '');
52        $data['answered_on'] = date('Y-m-d H:i:s', $row['answered_on']);
53        $data['answered_by'] = $user;
54    }
55
56    // store answer data
57    if ($data[$row['question']] !== '') $data[$row['question']] .= ', ';
58    $data[$row['question']] .= $row['answer'];
59}
60fputcsv($fp, array_values($data)); // last entry
61fclose($fp);
62