Skip to content

Commit

Permalink
New functionality to allow reports to have placeholders
Browse files Browse the repository at this point in the history
Then the user is prompted to enter values to stubstitute for the
parameters when the report is run.

Also, other minor tweaks made at the OU recently.
  • Loading branch information
timhunt committed Jan 19, 2012
1 parent 599531e commit 811043d
Show file tree
Hide file tree
Showing 13 changed files with 265 additions and 64 deletions.
11 changes: 8 additions & 3 deletions README.txt
Expand Up @@ -2,9 +2,14 @@ Ad-hoc database queries

This report plugin allows Administrators to set up arbitrary database queries
to act as ad-hoc reports. Reports can be of two types, either run on demand,
or scheduled to run automatically. Other users with the right capability can
go in and see a list of queries that they have access to. Results can be viewed
on-screen or downloaded as CSV.
or scheduled to run automatically.

Other users with the right capability can go in and see a list of queries that
they have access to. Results can be viewed on-screen or downloaded as CSV.

Reports can contain placeholders, in which case, the user running the report is
presented with a form where they can enter the values to substitute for the
placeholders before running the report.

See http://docs.moodle.org/22/en/Custom_SQL_queries_report for more information.

Expand Down
2 changes: 1 addition & 1 deletion db/install.xml
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" ?>
<XMLDB PATH="admin/report/customsql/db" VERSION="20091027" COMMENT="XMLDB file for Moodle admin/report/customsql"
<XMLDB PATH="report/customsql/db" VERSION="20091027" COMMENT="XMLDB file for Moodle report/customsql"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../lib/xmldb/xmldb.xsd"
>
Expand Down
4 changes: 2 additions & 2 deletions download.php
Expand Up @@ -26,7 +26,7 @@
require_once(dirname(__FILE__) . '/locallib.php');

$id = required_param('id', PARAM_INT);
$cvstimestamp = required_param('timestamp', PARAM_INT);
$csvtimestamp = required_param('timestamp', PARAM_INT);

$report = $DB->get_record('report_customsql_queries', array('id' => $id));
if (!$report) {
Expand All @@ -39,7 +39,7 @@
require_capability($report->capability, $context);
}

list($csvfilename) = report_customsql_csv_filename($report, $cvstimestamp);
list($csvfilename) = report_customsql_csv_filename($report, $csvtimestamp);
if (!is_readable($csvfilename)) {
print_error('unknowndownloadfile', 'report_customsql',
report_customsql_url('view.php?id=' . $id));
Expand Down
7 changes: 3 additions & 4 deletions edit.php
Expand Up @@ -53,10 +53,9 @@
}

$querysql = optional_param('querysql', $reportquerysql, PARAM_RAW);
$queryparamscount = preg_match_all('/(?<!:):[a-z][a-z0-9_]*/', $querysql, $matches);
$queryparams = array();
foreach ($matches[0] as $queryparam) {
$queryparams[substr($queryparam, 1)] = 'queryparam'.substr($queryparam, 1);
foreach (report_customsql_get_query_placeholders($querysql) as $queryparam) {
$queryparams[substr($queryparam, 1)] = 'queryparam' . substr($queryparam, 1);
}

$mform = new report_customsql_edit_form(report_customsql_url($relativeurl), $queryparams);
Expand All @@ -71,7 +70,7 @@
}

// Pick up named parameters into serialised array
if ($queryparamscount) {
if ($queryparams) {
foreach ($queryparams as $queryparam => $formparam) {
$queryparams[$queryparam] = $newreport->{$formparam};
unset($newreport->{$formparam});
Expand Down
11 changes: 5 additions & 6 deletions edit_form.php
Expand Up @@ -53,7 +53,7 @@ public function definition() {
$mform->setType('querysql', PARAM_RAW);

if (count($this->_customdata)) {
$mform->addElement('static', 'params', get_string('queryparams', 'report_customsql'));
$mform->addElement('static', 'params', '', get_string('queryparams', 'report_customsql'));
foreach ($this->_customdata as $queryparam => $formparam) {
$mform->addElement('text', $formparam, $queryparam);
}
Expand Down Expand Up @@ -104,13 +104,12 @@ public function validation($data, $files) {
$sql = report_customsql_prepare_sql($report, time());

// Check for required query parameters if there are any
$queryparamscount = preg_match_all('/(?<!:):[a-z][a-z0-9_]*/', $sql, $matches);
$queryparams = array();
foreach ($matches[0] as $queryparam) {
foreach (report_customsql_get_query_placeholders($sql) as $queryparam) {
$queryparam = substr($queryparam, 1);
$formparam = 'queryparam'.$queryparam;
if (!isset($data[$formparam]) || empty($data[$formparam])) {
$errors['params'] = get_string('queryparamsnew', 'report_customsql');
$formparam = 'queryparam' . $queryparam;
if (!isset($data[$formparam])) {
$errors['params'] = get_string('queryparamschanged', 'report_customsql');
break;
}
$queryparams[$queryparam] = $data[$formparam];
Expand Down
12 changes: 8 additions & 4 deletions lang/en/report_customsql.php
Expand Up @@ -15,10 +15,10 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

/**
* Lang strings for admin/report/customsql
* Lang strings for report/customsql
*
* @package report_customsql
* @copyright &copy; 2009 The Open University
* @copyright 2009 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

Expand All @@ -30,6 +30,7 @@
$string['availablereports'] = 'On-demand queries';
$string['availableto'] = 'Available to {$a}.';
$string['backtoreportlist'] = 'Back to the list of queries';
$string['changetheparameters'] = 'Change the parameters';
$string['customsql:definequeries'] = 'Define custom queries';
$string['customsql:view'] = 'View custom queries report';
$string['deleteareyousure'] = 'Are you sure you want to delete this query?';
Expand Down Expand Up @@ -59,16 +60,19 @@
$string['note'] = 'Notes';
$string['notrunyet'] = 'This query has not yet been run.';
$string['onerow'] = 'The query returns one row, accumulate the results one row at a time';
$string['parametervalue'] = '{$a->name}: {$a->value}';
$string['pluginname'] = 'Ad-hoc database queries';
$string['queryfailed'] = 'Error when executing the query: {$a}';
$string['querynote'] = '<ul>
<li>The token <tt>%%%%WWWROOT%%%%</tt> in the results will be replaced with <tt>{$a}</tt>.</li>
<li>Any field in the output that looks like a URL will automatically be made into a link.</li>
<li>The token <tt>%%%%USERID%%%%</tt> in the query will be replaced with the user id of the user viewing the report, before the report is executed.</li>
<li>For scheduled reports, the tokens <tt>%%%%STARTTIME%%%%</tt> and <tt>%%%%ENDTIME%%%%</tt> are replaced by the Unix timestamp at the start and end of the reporting week/month in the query before it is executed.</li>
<li>You can put parameters into the SQL using named placeholders, for example <tt>:parameter_name</tt>. Then, when the report is run, the user can enter values for the parameters to use when running the query.</li>
</ul>';
$string['queryparams'] = 'Query parameters';
$string['queryparamsnew'] = 'Please complete new query parameters';
$string['queryparameters'] = 'Query parameters';
$string['queryparams'] = 'Please enter default values for the query parameters.';
$string['queryparamschanged'] = 'The placeholders in the query have changed.';
$string['queryrundate'] = 'query run date';
$string['querysql'] = 'Query SQL';
$string['querysqlrequried'] = 'You must enter some SQL.';
Expand Down
88 changes: 88 additions & 0 deletions lang/fr/report_customsql.php
@@ -0,0 +1,88 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

/**
* Lang strings for report/customsql
*
* @package report_customsql
* @copyright 2010 Séverin Terrier
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

$string['addreport'] = 'Ajouter une nouvelle requête';
$string['anyonewhocanveiwthisreport'] = 'Toute personne pouvant voir ce rapport (report/customsql:view)';
$string['archivedversions'] = 'Versions archivées de cette requête';
$string['automaticallymonthly'] = 'Planifiée, le premier jour de chaque mois';
$string['automaticallyweekly'] = 'Planifiée, le premier jour de chaque semaine';
$string['availablereports'] = 'Requêtes à la demande';
$string['availableto'] = 'Disponible pour $a.';
$string['backtoreportlist'] = 'Retour à la liste des requêtes';
//$string['changetheparameters'] = '';
$string['customsql:definequeries'] = 'Définir des requêtes personnalisées';
$string['customsql:view'] = 'Voir les rapports personnalisés';
$string['deleteareyousure'] = 'Êtes vous certain de vouloir supprimer cette requête ?';
$string['deletethisreport'] = 'Supprimer cette requête';
$string['description'] = 'Description';
$string['displayname'] = 'Nom de la requête';
$string['displaynamerequired'] = 'Vous devez saisir un nom de requête';
$string['displaynamex'] = 'Nom de la requête : $a';
$string['downloadthisreportascsv'] = 'Télécharger le résultat sous forme CSV';
$string['editingareport'] = 'Modifier une requête personnalisée';
$string['editthisreport'] = 'Modifier cette requête';
//$string['enterparameters'] = '';
$string['errordeletingreport'] = 'Erreur de suppression d\'une requête.';
$string['errorinsertingreport'] = 'Erreur d\'insertion d\'une requête.';
$string['errorupdatingreport'] = 'Erreur de modification d\'une requête.';
$string['invalidreportid'] = 'Requête invalide id $a.';
$string['lastexecuted'] = 'Dernière exécution le $a->lastrun. Durée d\'exécution {$a->lastexecutiontime}s.';
$string['manually'] = 'À la demande';
$string['manualnote'] = 'Ces requêtes sont exécutées à la demande, lorsque vous cliquez sur leur lien pour voir les résultats.';
$string['morethanonerowreturned'] = 'Plus d\'une ligne retournée comme résultat. Cette requête devrait retourner une seule ligne.';
$string['nodatareturned'] = 'Cette requête n\'a retourné aucun résultat.';
$string['noexplicitprefix'] = 'Utilisez prefix_ dans votre requête, au lieu de $a.';
$string['noreportsavailable'] = 'Pas de requête disponible';
$string['norowsreturned'] = 'Aucune ligne retournée comme résultat. Cette requête devrait retourner une ligne.';
$string['nosemicolon'] = 'Vous ne pouvez pas utiliser le caractère ; dans la commande SQL.';
$string['notallowedwords'] = 'Vous ne pouvez pas utiliser les mots $a dans la commande SQL.';
$string['note'] = 'Attention';
$string['notrunyet'] = 'Cette requête n\'a pas encore été exécutée.';
$string['onerow'] = 'La requête renvoie une ligne, et cumule les résultats une ligne à la fois';
//$string['parametervalue'] = '';
$string['pluginname'] = 'Rapports personnalisés';
$string['queryfailed'] = 'Erreur à l\'exécution de la requête : $a';
$string['querynote'] = '<ul>
<li>La chaîne <tt>%%%%WWWROOT%%%%</tt> dans les résultats sera remplacée par <tt>$a</tt>.</li>
<li>Tout champ de sortie ressemblant à une URL sera automatiquement transformé en lien.</li>
<li>La chaîne <tt>%%%%USERID%%%%</tt> dans la requête sera remplacée par le \"user id\" de l\'utilisateur visualisant le rapport, avant l\'exécution du rapport.</li>
<li>Pour des rapports programmés, les chaînes <tt>%%%%STARTTIME%%%%</tt> et <tt>%%%%ENDTIME%%%%</tt> sont remplacées par le timestamp Unix du début et de fin de semaine/mois du rapport dans la requête avant son exécution.</li>
</ul>';// Note, new last li point needs to be translated.
//$string['queryparameters'] = '';
//$string['queryparams'] = '';
//$string['queryparamschanged'] = '';
$string['queryrundate'] = 'date d\'exécution de la requête';
$string['querysql'] = 'Requête SQL';
$string['querysqlrequried'] = 'Vous devez saisir du code SQL';
$string['recordlimitreached'] = 'Cette requête a atteint la limite de $a lignes de résultat. Des lignes ont certainement été omises à la fin.';
$string['reportfor'] = 'Requête exécutée le $a';
$string['runable'] = 'Exécution';
$string['runablex'] = 'Exécution : $a.';
$string['schedulednote'] = 'Ces requêtes sont lancées automatiquement le premier jour de chaque semaine ou chaque mois, pour des rapports sur la semaine ou le mois précédent. Ces liens vous permettent de visualiser les résultats qui ont déjà été accumulés.';
$string['scheduledqueries'] = 'Requêtes programmées';
$string['typeofresult'] = 'Type de résultat';
$string['unknowndownloadfile'] = 'Fichier à télécharger inconnu.';
$string['userswhocanconfig'] = 'Administrateurs uniquement (moodle/site:config)';
$string['userswhocanviewsitereports'] = 'Utilisateurs pouvant voir les rapports (moodle/site:viewreports)';
$string['whocanaccess'] = 'Qui peut accéder à cette requête';
15 changes: 9 additions & 6 deletions lang/pl/report_customsql.php
Expand Up @@ -15,7 +15,7 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

/**
* Lang strings for admin/report/customsql
* Lang strings for report/customsql
*
* @package report_customsql
* @copyright 2012 Paweł Suwiński <dracono@wp.pl>
Expand All @@ -30,18 +30,19 @@
$string['availablereports'] = 'Raporty na żądanie';
$string['availableto'] = 'Dostęp: $a.';
$string['backtoreportlist'] = 'Wróć do listy raportów';
$string['customsql'] = 'Raporty ad-hoc';
//$string['changetheparameters'] = '';
$string['customsql:definequeries'] = 'Tworzenie raportów ad-hoc';
$string['customsql:view'] = 'Podgląd wyniku/ uruchamianie raportów ad-hoc';
$string['deleteareyousure'] = 'Czy na pewno chcesz usunąć raport?';
$string['deletethisreport'] = 'Usuń raport';
$string['description'] = 'Opis';
$string['displayname'] = 'Nazwa raportu';
$string['displaynamex'] = 'Nazwa raportu: $a';
$string['displaynamerequired'] = 'Musisz wpisać nazwę raportu';
$string['displaynamex'] = 'Nazwa raportu: $a';
$string['downloadthisreportascsv'] = 'Pobierz wyniki jako CSV';
$string['editingareport'] = 'Edytowanie raportu ad-hoc';
$string['editthisreport'] = 'Edytuj raport';
//$string['enterparameters'] = '';
$string['errordeletingreport'] = 'Błąd podczas usuwania raportu.';
$string['errorinsertingreport'] = 'Błąd podczas dodawania raportu.';
$string['errorupdatingreport'] = 'Błąd podczas aktualizacji raportu.';
Expand All @@ -59,16 +60,18 @@
$string['note'] = 'Uwagi';
$string['notrunyet'] = 'Raport nie był jeszcze uruchamiany.';
$string['onerow'] = 'Raport zwraca jeden wiersz agregując dane';
//$string['parametervalue'] = '';
$string['pluginname'] = 'Raporty ad-hoc';
$string['queryfailed'] = 'Błąd podczas wykonywania zapytania: $a';
$string['querynote'] = '<ul>
<li>Tag <tt>%%%%WWWROOT%%%%</tt> w wynikach będzie zastąpiony przez <tt>$a</tt>.</li>
<li>Każde pole wynikowe wyglądające jak URL będzie automatycznie przetworzone na aktywny link.</li>
<li>Tag <tt>%%%%USERID%%%%</tt> w zapytaniu SQL przed wykonaniem będzie zastąpiony identyfikatorem id użytkownika przeglądającego raport.</li>
<li>W przypadku automatycznych raportów tagi <tt>%%%%STARTTIME%%%%</tt> i <tt>%%%%ENDTIME%%%%</tt> w zapytaniach SQL przed wykonaniem będą zastępowane Uniksowymi znacznikami czasu oznaczającymi początek i koniec raportowanego okresu (tygodnia/ miesiąca).</li>
</ul>';
</ul>';// Note, new last li point needs to be translated.
//$string['queryparameters'] = '';
//$string['queryparams'] = '';
//$string['queryparamsnew'] = '';
//$string['queryparamschanged'] = '';
$string['queryrundate'] = 'data wykonania raportu';
$string['querysql'] = 'Zapytanie SQL';
$string['querysqlrequried'] = 'Musisz podać zapytanie SQL.';
Expand All @@ -80,6 +83,6 @@
$string['scheduledqueries'] = 'Zaplanowane raporty';
$string['typeofresult'] = 'Wynik raportu';
$string['unknowndownloadfile'] = 'Unknown download file.';
$string['userswhocanviewsitereports'] = 'Użytkownicy z dostępem do wszystkich raportów (moodle/site:viewreports)';
$string['userswhocanconfig'] = 'Tylko administratorzy (moodle/site:config)';
$string['userswhocanviewsitereports'] = 'Użytkownicy z dostępem do wszystkich raportów (moodle/site:viewreports)';
$string['whocanaccess'] = 'Dostęp do raportu';

0 comments on commit 811043d

Please sign in to comment.