06461cb419e7270385f3139cd7c5d609f1c83173
[philipp/winterrodeln/mediawiki_extensions/wrreport.git] / wrreport.body.php
1 <?php
2
3
4 // Init
5 // ----
6
7 function wrReportParserInit() {
8         global $wgParser;
9         $wgParser->setHook('bahnberichtformular', 'bahnberichtformularParserHook');
10         $wgParser->setHook('bahnberichte', 'bahnberichteParserHook');
11         $wgParser->setHook('bahnbewertung', 'bahnbewertungParserHook');
12         return true;
13 }
14
15
16 // Tool functions
17 // --------------
18
19 /// \brief This function is used to translate WikiText to HTML. Normally it should be avoided to do this
20 /// but I found situations where I did not find an other possibility.
21 function wrReportSandboxParse($wikiText) {
22         global $wgTitle, $wgUser;
23         $myParser = new Parser();
24         $myParserOptions = new ParserOptions();
25         $myParserOptions->initialiseFromUser($wgUser);
26         $result = $myParser->parse($wikiText, $wgTitle, $myParserOptions);
27         return $result->getText();
28 }
29
30
31 /// List of markers - used by the functions replaceByMarker and wrReportAfterTidy
32 $wrReportMarkerList = array();
33
34
35 /// Returns a marker for a text and back-replaces the text in wrReportAfterTidy
36 function replaceByMarker($text, $marker = 'marker') {
37         $marker = $marker . mt_rand(1e5, 1e7);
38         global $wrReportMarkerList;
39         $wrReportMarkerList[$marker] = $text;
40         return $marker;
41 }
42
43
44 /// Replaces the markers by its contents
45 function wrReportAfterTidy(&$parser, &$text) {
46         // find markers in $text
47         // replace markers with actual output
48         global $wrReportMarkerList;
49         foreach ($wrReportMarkerList as $marker => $html) $text = str_replace($marker, $html, $text);
50         return true;
51 }
52
53
54
55 // Render Functions
56 // ----------------
57
58 /// \brief Returns a form to enter a report (string containing HTML).
59 ///
60 /// All parameters have to be UTF-8 encoded.
61 /// \param $page_title Name of the sledding run.
62 /// \return UTF-8 encoded HTML form
63 function wrReportFormRender($hide_save_button = TRUE, $page_title = NULL, $date_report = NULL, $condition = NULL, $description = NULL, $author_name = NULL, $page_title_list = NULL) {
64         if ($page_title) $page_title = htmlspecialchars($page_title);
65         // Date options
66         $daynames = array('Heute', 'Gestern', 'Vorgestern', 'Vor 3 Tagen', 'Vor 4 Tagen');
67         $date_options = '';
68         $date_selected = false;
69         $time = time(); // number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
70         for ($day=0; $day!=5; ++$day) {
71                 $date = strtotime("-$day days", $time);
72                 $date_f = strftime("%Y-%m-%d", $date); // Formats it according to locale, that is set to CET.
73                 $date_options .= '<option value="' . $date_f . '"';
74                 if ((is_null($date_report) && $day == 0) || (!is_null($date_report) && $date_report == $date_f)) {
75                         $date_options .= ' selected="selected"';
76                         $date_selected = true;
77                 }
78                 $date_options .= '>' . htmlspecialchars($daynames[$day]) . ' (' . strftime('%d.%m.', $date) . ')</option>' . "\n";
79         }
80         if (!$date_selected) {
81                 $date_options = '<option value="' . $date_report . '" selected="selected">' . htmlspecialchars($date_report) . "</option>\n" . $date_options;
82         }
83         
84         // Condition options
85         $condition_options = '';
86         global $wrConditions; // $wrConditions = array(1 => 'Sehr gut', 2 => 'Gut', 3 => utf8_encode('Mittelmäßig'), 4 => 'Schlecht', 5 => 'Geht nicht');
87         $condition_options .= utf8_encode('<option value="">(keine Beurteilung)</option>') . "\n";
88         foreach ($wrConditions as $condition_num => $condition_text) {
89                 $condition_options .= "<option value=\"$condition_num\"";
90                 if ($condition == $condition_num) $condition_options .= ' selected="selected"';
91                 $condition_options .= '>' . htmlspecialchars($condition_text) . "</option>\n";
92         }
93         $description_html = htmlspecialchars($description);
94
95         // Buttons
96         // I would like to do it this way, but due to a bug of internet explorer, the <button> element is not useable.
97         //   $buttons = '<button name="action" type="submit" value="preview">Vorschau';
98         //   if ($hide_save_button) $buttons .= ' &amp; Speichern';
99         //   $buttons .= '</button>';
100         //   if (!$hide_save_button) $buttons .= '<button name="action" type="submit" value="store">Speichern</button>';
101         // Workaround: User <input type="submit"/>
102         $buttons = '<input name="preview" type="submit" value="Vorschau';
103         if ($hide_save_button) $buttons .= ' &amp; Speichern'; 
104         $buttons .= '" /> ';
105         if (!$hide_save_button) $buttons .= '<input name="store" type="submit" value="Speichern"/>';
106
107         $form = <<<EOT
108 <form action="/wiki/Spezial:Bahnberichte" method="post">
109 <table class="wrreportform" summary="Formular zum Eintragen eines Rodelbahnberichtes">
110         <tr class="oddrow"><th>Rodelbahn</th><td>$page_title<input type="hidden" name="page_title" value="$page_title"/></td></tr>
111         <tr class="evenrow"><th>Datum des Rodelns</th>
112         <td>
113         <select name="date_report">
114         $date_options
115         </select>
116         </td>
117         </tr>
118         <tr class="oddrow"><th>Bahnzustand*</th><td><select name="condition">
119         $condition_options
120         </select></td></tr>
121         <tr class="evenrow"><th>Meinung</th><td><textarea name="description" cols="50" rows="7">$description_html</textarea></td></tr>
122         <tr class="oddrow"><th>Autor/in</th><td><input name="author_name" maxlength="30" size="30" value="$author_name" /></td></tr>
123         <tr class="evenrow"><th>Bericht abschicken</th><td>$buttons</td></tr>
124 </table>
125 </form>
126 EOT;
127         return $form;
128 }
129
130
131
132 /// \brief sub-function of wrReportTableRender - renders the table head
133 ///
134 /// The input variables are either NULL (-> the column is not present) or a UTF-8 encoded string (that is ignored ;-) ).
135 /// \return UTF-8 encoded titles of HTML table
136 function wrReportTableTitleRender($page_id, $page_title, $date_report, $date_entry, $date_invalid, $condition, $description, $author_name) {
137         $out = '<tr>';
138         if ($page_id) $out .= '<th>ID</th>';
139         if ($page_title) $out .= '<th>Bahn</th>';
140         if ($date_report) $out .= '<th>Datum</th>';
141         if ($date_entry) $out .= '<th>Datum Eintrag</th>';
142         if ($date_invalid) $out .= '<th>Datum Ungültig</th>';
143         if ($condition) $out .= '<th>Zustand</th>';
144         if ($description) $out .= '<th>Beschreibung</th>';
145         if ($author_name) $out .= '<th>Autor</th>';
146         return utf8_encode($out . "</tr>\n");
147 }
148
149
150 /// \brief sub-function of wrReportTableRender - renders a table row
151 ///
152 /// The in- and output parameters are expected to be UTF-8 encoded.
153 function wrReportTableRowRender($page_id, $page_title, $date_report, $date_entry, $date_invalid, $condition, $description, $author_name) {
154         $out = "<tr>";
155         if (!is_null($page_id)) $out .= '<td>' . $page_id . '</td>';
156         if (!is_null($page_title)) $out .= '<td>' . wrReportSandboxParse('[[' . $page_title . ']]') . '</td>';
157         $dayOfWeek = array('Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So');
158         $date_report = strtotime($date_report);
159         $date_report = $dayOfWeek[strftime('%u', $date_report)-1] . strftime(', %d.%m.', $date_report);
160         $out .= '<td>' . $date_report . '</td>';
161         if (!is_null($date_entry)) $out .= '<td>' . date('Y-m-d, H:i', strtotime($date_entry)) . '</td>';
162         if (!is_null($date_invalid)) $out .= '<td>' . date('Y-m-d, H:i', strtotime($date_invalid)) . '</td>';
163         global $wrConditions;
164         $condition_text = '---';
165         if (isset($wrConditions[$condition])) $condition_text = $wrConditions[$condition];
166         $out .= '<td>' . htmlspecialchars($condition_text) . '</td>';
167         $out .= '<td class="wrreportdescription">' . wrReportSandboxParse($description) . '</td>';
168         $out .= '<td>' . htmlspecialchars($author_name) . '</td>';
169         $out .= "</tr>\n";
170         return $out;
171 }
172
173
174 /// \brief It returns a table (string containing HTML) showing the results.
175 ///
176 /// Is called when the tag <bahnberichte/> is encounted and renders a table /
177 /// \param $page_title If the name is specified (UTF-8 encoded), only reports of this "page" (e.g. 'Birgitzer Alm') is shown. Default: NULL
178 /// \return UTF-8 encoded HTML result table
179 function wrReportTableRender($page_title = NULL) {
180         $out = '';
181         $dbr = wfGetDB(DB_SLAVE);
182         $conditions = array();
183         if ($page_title) $conditions['page_title'] = $page_title;
184         $res = $dbr->select('wrreport', array('id', 'page_title', 'date_report', 'date_entry', 'date_invalid', 'condition', 'description', 'author_name', 'author_username'), $conditions, $fname = 'Database::select', $options = array('ORDER BY' => 'date_report desc, date_entry desc'));
185         $admin = is_null($page_title);
186         if ($res->numRows() > 0) {
187                 $out .= "<table class=\"wrreporttable\">\n";
188                 $out .= wrReportTableTitleRender($admin, $admin, TRUE, $admin, $admin, TRUE, TRUE, TRUE);
189                 while ($row = $dbr->fetchObject($res)) {
190                         $author = $row->author_name;
191                         $out .= wrReportTableRowRender($admin ? $row->id : NULL, $admin ? $row->page_title : NULL, $row->date_report, $admin ? $row->date_entry : NULL, $admin ? $row->date_invalid : NULL, $row->condition, $row->description, $author);
192                 }
193                 $out .= "</table>\n";
194         } else {
195                 $out .= wrReportSandboxParse("''Es wurden keine Bahnberichte in der Datenbank gefunden.''\n\n");
196         }
197         $dbr->freeResult($res);
198         return $out;
199 }
200
201
202 /// \brief It returns an array of the "condition" (as number) and the date of the "most recent" report of the specified page (to decode as list($condition, $date);
203 ///
204 /// If no condition is present, array(NULL, NULL) is returned
205 function wrReportConditionRender($page_title) {
206         $dbr = wfGetDB(DB_SLAVE);
207         $res = $dbr->select('wrreport', array('max(wrreport.id) as max'), array('page_title' => $page_title, 'condition is not null', 'date_invalid > now()'));
208         //  select condition, date_report from wrreport where id = (select max(wrreport.id) as max from wrreport where page_title='Birgitzer Alm (vom Adelshof)' and date_invalid > now() and condition is not null);
209         if ($res->numRows() <= 0) return array(NULL, NULL);
210         $row = $dbr->fetchObject($res);
211         $res = $dbr->select('wrreport', array('condition', 'date_report'), array('id' => $row->max));
212         if ($res->numRows() <= 0) return array(NULL, NULL);
213         $row = $dbr->fetchObject($res);
214         $date = $row->date_report;
215         if ($date) $date = strtotime($date);
216         return array($row->condition, $date);
217 }
218
219
220 // Parser Hook Functions
221 // ---------------------
222
223 /// \brief Is called when the tag <bahnberichtformular/> is encountered.
224 ///
225 /// The current page name is taken.
226 function bahnberichtformularParserHook($input, $args, $parser) {
227         // Username
228         global $wgUser;
229         $author_name = NULL;
230         if ($wgUser->isLoggedIn()) {
231                 $author_name = $wgUser->getRealName();
232                 if (!$author_name) $author_name = $wgUser->getName();
233         }
234
235         global $wgWrReportMode;
236         global $wgWrReportBlackListAll;
237         global $wgWrReportBlackListStrangers;
238         if ($wgWrReportMode == 'summer') return wrReportSandboxParse(utf8_encode("''An dieser Stelle kann während des Winters die Schneelage von Rodelbahnen eingetragen werden.''\n\n"));
239         if ($wgWrReportMode == 'deny') return wrReportSandboxParse(utf8_encode("''Rodelbahnberichte sind derzeit leider nicht erlaubt.''\n\n"));
240         if ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) return wrReportSandboxParse(utf8_encode("''Derzeit sind Rodelbahnberichte nur für angemeldete Benutzer erlaubt.''\n\n"));
241         if (in_array($parser->getTitle()->getText(), $wgWrReportBlackListAll)) return wrReportSandboxParse(utf8_encode("''Bei dieser Rodelbahn dürfen derzeit leider keine Rodelbahnberichte abgegeben werden.''\n"));
242         if (!$wgUser->isLoggedIn() && in_array($parser->getTitle()->getText(), $wgWrReportBlackListStrangers)) return wrReportSandboxParse(utf8_encode("''Bei der angegebenen Rodelbahn dürfen derzeit nur angemeldete Benutzer Rodelbahnberichte abgebe.''\n\n"));
243         return replaceByMarker(wrReportFormRender(TRUE, $parser->getTitle()->getText(), NULL, NULL, NULL, $author_name));
244 }
245
246
247 /// \brief Is called when the tag <bahnberichte/> is encountered.
248 ///
249 /// The current page name is taken.
250 function bahnberichteParserHook($input, $args, &$parser) {
251         return wrReportTableRender($parser->getTitle()->getText());
252 }
253
254
255 /// \brief Is called when the tag <bahnbewertung/> is encountered.
256 ///
257 /// * <bahnbewertung/>: The current page name is taken.
258 /// * <bahnbewertung>page_name</bahnbewertung>: The given page name is taken.
259 function bahnbewertungParserHook($input, $args, &$parser) {
260         $titleText = $input;
261         if (!$titleText) $titleText = $parser->getTitle()->getText();
262         list($condition, $date) = wrReportConditionRender($titleText);
263         if ($date) $date = strftime('%d.%m.', $date);
264         global $wrConditions;
265         global $wrNewReportSection; //  = utf8_encode('Eintragen');
266         global $wrShowReportsSection; //  = utf8_encode('Einträge');
267         global $wgUser;
268         global $wgWrReportMode; // e.g. 'summer'
269         global $wgWrReportBlackListAll;
270         global $wgWrReportBlackListStrangers;
271
272         // Determine, whether the user is allowed to make a new report
273         $userMayReport = ($wgWrReportMode == 'allow' || ($wgWrReportMode == 'loggedin' && $wgUser->isLoggedIn()));
274         if ($userMayReport) {
275                 if (in_array($titleText, $wgWrReportBlackListAll)) $userMayReport = false;
276                 if (!$wgUser->isLoggedIn() && in_array($titleText, $wgWrReportBlackListStrangers)) $userMayReport = false;
277         }
278
279         // Get the condition and create the response wiki text
280         if (isset($wrConditions[$condition])) {
281                 $wikiText = '[['. $titleText . '#' . $wrShowReportsSection . '|'. $wrConditions[$condition] . "]] <small>$date";
282                 if ($userMayReport) $wikiText .= " ''[[" . $titleText . '#' . $wrNewReportSection . "|Neu]]''";
283                 $wikiText .= "</small>";
284         } else {
285                 if ($userMayReport) $wikiText = "<small>''[[" . $titleText . '#' . $wrNewReportSection . "|Bitte eintragen]]''</small>";
286                 else $wikiText = '--';
287         }
288         return wrReportSandboxParse($wikiText);
289 }
290
291
292
293 // Special page
294 // ------------
295
296 /// Specal Page to show reports
297 class WrReport extends SpecialPage {
298         function WrReport() {
299                 SpecialPage::SpecialPage('WrReport');
300                 wfLoadExtensionMessages('WrReport');
301         }
302
303
304         /// \param $par Possibilities:
305         /// - action == 'view' (default)
306         /// - action == 'preview': Preview new report
307         /// - action == 'store': Store new report
308         /// \param $override_action If not NULL (defualt), it overrides the action in $par
309         /// \param $errorMsg UFT-8 encoded error message (in WikiText) to show on top of the page or NULL (default):
310         function execute($par, $override_action = NULL, $errorMsg = NULL) {
311                 global $wgRequest, $wgOut;
312
313                 $this->setHeaders();
314
315                 // Get request data
316                 $action = $wgRequest->getText('action');
317                 if (!$action) {
318                         if ($wgRequest->getVal('preview')) $action = 'preview';
319                         elseif ($wgRequest->getVal('store')) $action = 'store';
320                         else $action = 'view';
321                 }
322                 if ($override_action) $action = $override_action;
323
324                 // Show error message
325                 if ($errorMsg) {
326                         $wgOut->addWikiText(utf8_encode('<div class="errorbox">') . $errorMsg . utf8_encode("</div>\n"));
327                 }
328
329                 // Action view
330                 if ($action == 'view') {                
331                         $wgOut->addHTML(wrReportTableRender());
332                 }
333
334                 // Action preview or store
335                 elseif ($action == 'preview' || $action == 'store') {
336                         $page_title = $wgRequest->getText('page_title');
337                         $date_report = $wgRequest->getText('date_report');
338                         $condition = $wgRequest->getText('condition');
339                         $description = $wgRequest->getText('description');
340                         $author_name = $wgRequest->getText('author_name');
341                         if ($action == 'store') {
342                                 // page_id
343                                 $title = Title::newFromText($page_title);
344                                 $page_id = $title->getArticleId();
345                                 if ($page_id == 0) $page_id = NULL;
346                                 
347                                 // user_id
348                                 global $wgUser;
349                                 $author_userid = $wgUser->getId();
350                                 if ($author_userid == 0) $author_userid = NULL; // to store a NULL value in the database if no user is logged in instead of 0.
351                                 $author_username = $wgUser->getName();
352
353                                 // condition
354                                 $condition_int = (int) $condition;
355                                 if ($condition_int >= 1 and $condition_int <= 5) $condition = $condition_int;
356                                 else $condition = NULL;
357                                 
358                                 // check conditions/permissions
359                                 $errorMsg = NULL;
360                                 global $wgWrReportMode;
361                                 global $wgWrReportBlackListAll;
362                                 global $wgWrReportBlackListStrangers;
363                                 if ($wgWrReportMode == 'summer') $errorMsg = utf8_encode('Rodelbahnberichte sind in der schneefreien Zeit nicht erlaubt.');
364                                 elseif ($wgWrReportMode == 'deny') $errorMsg = utf8_encode('Rodelbahnberichte sind derzeit leider nicht erlaubt.');
365                                 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = utf8_encode('Derzeit sind Rodelbahnberichte nur für angemeldete Benutzer erlaubt.');
366                                 elseif (!$page_id) $errorMsg = utf8_encode('Die angegebene Seite wurde nicht gefunden.');
367                                 elseif (in_array($page_title, $wgWrReportBlackListAll)) $errorMsg = utf8_encode('Bei der angegebenen Rodelbahn dürfen derzeit keine Rodelbahnberichte abgegeben werden.');
368                                 elseif (!$wgUser->isLoggedIn() && in_array($page_title, $wgWrReportBlackListStrangers)) $errorMsg = utf8_encode('Bei der angegebenen Rodelbahn dürfen derzeit nur angemeldete Benutzer Rodelbahnberichte abgebe.');
369                                 elseif (!$condition && !$description) $errorMsg = utf8_encode('Es sind sowohl die Beschreibung als auch die Bewertung leer/nicht vergeben.');
370                                 elseif (!$wgUser->isLoggedIn()) {
371                                         if (!$description) $errorMsg = utf8_encode('Bitte bei der Beschreibung eine kurze Begründung für die Bewertung abgeben.');
372                                         elseif (!(stripos($description, 'http') === FALSE)) $errorMsg = utf8_encode('Der Text "http" ist leider für nicht-angemeldete Benutzer nicht erlaubt, weil wir in der Vergangenheit Fälle hatten, bei denen externe Werbelinks automatisiert eingetragen wurden.');
373                                 }
374                                 if ($errorMsg) {
375                                         $this->execute($par, 'preview', $errorMsg);
376                                         return;
377                                 }
378
379                                 // Save entry
380                                 $dbr = wfGetDB(DB_MASTER);
381                                 $dbr->insert(
382                                         'wrreport', 
383                                         array(
384                                                 'page_id' => $page_id, 
385                                                 'page_title' => $page_title, 
386                                                 'date_report' => $date_report, 
387                                                 // 'date_entry' => '',  // use database default
388                                                 // 'date_invalid' => '', // use database default
389                                                 'condition' => $condition,
390                                                 'description' => $description,
391                                                 'author_name' => $author_name,
392                                                 'author_ip' => $_SERVER['REMOTE_ADDR'],
393                                                 'author_userid' => $author_userid,
394                                                 'author_username' => $author_username
395                                         )
396                                 );
397
398                                 // Purge cache
399                                 $title->invalidateCache();
400                                 // Show success message
401                                 global $wrShowReportsSection;
402                                 $wgOut->addWikiText(utf8_encode('<div class="successbox">Der Bahnbericht für [[') . $page_title . '#' . $wrShowReportsSection . '|' . $page_title . utf8_encode("]] wurde erfolgreich gespeichert.</div>\n"));
403                                 // We could redirect to result with the following line but we don't want to.
404                                 // $wgOut->redirect($title->getFullURL() . '#Eintr.C3.A4ge');
405                         }
406                         if ($action == 'preview') {
407                                 $wgOut->addWikiText(utf8_encode("== Vorschau (noch nicht gespeichert) ==\n"));
408                                 $wgOut->addHTML("<table class=\"wrreporttable\">\n");
409                                 $wgOut->addHTML(wrReportTableTitleRender(FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE));
410                                 $wgOut->addHTML(wrReportTableRowRender(NULL, $page_title, $date_report, NULL, NULL, $condition, $description, $author_name));
411                                 $wgOut->addHTML("</table>");
412                                 $wgOut->addWikiText("\n");
413                                 $wgOut->addWikiText(utf8_encode("== Speichern oder Ändern ==\n"));
414                                 $wgOut->addHTML(wrReportFormRender(FALSE, $page_title, $date_report, $condition, $description, $author_name));
415                         } 
416                         
417                 }
418
419                 else die('Wrong action');
420         }
421 }
422
423
424 ?>