Prevent bug #35 (Caching problems of report form).
[philipp/winterrodeln/mediawiki_extensions/wrreport.git] / wrreport.body.php
1 <?php
2
3
4 // Init
5 // ----
6
7 function wrReportParserInit() {
8         global $wgParser;
9         wfLoadExtensionMessages('WrReport');
10         $wgParser->setHook('bahnberichtformular', 'bahnberichtformularParserHook');
11         $wgParser->setHook('bahnberichte', 'bahnberichteParserHook');
12         $wgParser->setHook('bahnbewertung', 'bahnbewertungParserHook');
13         return true;
14 }
15
16
17 // Tool functions
18 // --------------
19
20 /// \brief This function is used to translate WikiText to HTML. Normally it should be avoided to do this
21 /// but I found situations where I did not find an other possibility.
22 function wrReportSandboxParse($wikiText) {
23         global $wgTitle, $wgUser;
24         $myParser = new Parser();
25         $myParserOptions = new ParserOptions();
26         $myParserOptions->initialiseFromUser($wgUser);
27         $result = $myParser->parse($wikiText, $wgTitle, $myParserOptions);
28         return $result->getText();
29 }
30
31
32 /// List of markers - used by the functions replaceByMarker and wrReportAfterTidy
33 $wrReportMarkerList = array();
34
35
36 /// Returns a marker for a text and back-replaces the text in wrReportAfterTidy
37 function replaceByMarker($text, $marker = 'marker') {
38         $marker = $marker . mt_rand(1e5, 1e7);
39         global $wrReportMarkerList;
40         $wrReportMarkerList[$marker] = $text;
41         return $marker;
42 }
43
44
45 /// Replaces the markers by its contents
46 function wrReportAfterTidy(&$parser, &$text) {
47         // find markers in $text
48         // replace markers with actual output
49         global $wrReportMarkerList;
50         foreach ($wrReportMarkerList as $marker => $html) $text = str_replace($marker, $html, $text);
51         return true;
52 }
53
54
55 /// Forces a regeneration of region overview pages
56 function wrRecacheRegions() {
57         // TODO: Better implementation - it's a "quick fix" now.
58         $title = Title::newFromText('Tirol');
59         $title->invalidateCache();
60         
61         $title = Title::newFromText('Vorarlberg');
62         $title->invalidateCache();
63
64         $title = Title::newFromText('Steiermark');
65         $title->invalidateCache();
66 }
67
68
69
70 // Render Functions
71 // ----------------
72
73 /// \brief Returns a form to enter a report (string containing HTML).
74 ///
75 /// All parameters have to be UTF-8 encoded.
76 /// \param $page_title Name of the sledding run.
77 /// \return UTF-8 encoded HTML form
78 function wrReportFormRender($hide_save_button = TRUE, $page_title = NULL, $date_report = NULL, $condition = NULL, $description = NULL, $author_name = NULL, $page_title_list = NULL) {
79         if ($page_title) $page_title = htmlspecialchars($page_title);
80         // Date options
81         $daynames = array('Heute', 'Gestern', 'Vorgestern', 'Vor 3 Tagen', 'Vor 4 Tagen');
82         $date_options = '';
83         $date_selected = false;
84         $time = time(); // number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
85         for ($day=0; $day!=5; ++$day) {
86                 $date = strtotime("-$day days", $time);
87                 $date_f = strftime("%Y-%m-%d", $date); // Formats it according to locale, that is set to CET.
88                 $date_options .= '<option value="' . $date_f . '"';
89                 if ((is_null($date_report) && $day == 0) || (!is_null($date_report) && $date_report == $date_f)) {
90                         $date_options .= ' selected="selected"';
91                         $date_selected = true;
92                 }
93                 $date_options .= '>' . htmlspecialchars($daynames[$day]) . ' (' . strftime('%d.%m.', $date) . ')</option>' . "\n";
94         }
95         if (!$date_selected) {
96                 $date_options = '<option value="' . $date_report . '" selected="selected">' . htmlspecialchars($date_report) . "</option>\n" . $date_options;
97         }
98         
99         // Condition options
100         $condition_options = '';
101         global $wrConditions; // $wrConditions = array(1 => 'Sehr gut', 2 => 'Gut', 3 => utf8_encode('Mittelmäßig'), 4 => 'Schlecht', 5 => 'Geht nicht');
102         $condition_options .= utf8_encode('<option value="">(keine Beurteilung)</option>') . "\n";
103         foreach ($wrConditions as $condition_num => $condition_text) {
104                 $condition_options .= "<option value=\"$condition_num\"";
105                 if ($condition == $condition_num) $condition_options .= ' selected="selected"';
106                 $condition_options .= '>' . htmlspecialchars($condition_text) . "</option>\n";
107         }
108         $description_html = htmlspecialchars($description);
109
110         // Buttons
111         // I would like to do it this way, but due to a bug of internet explorer, the <button> element is not useable.
112         //   $buttons = '<button name="action" type="submit" value="preview">Vorschau';
113         //   if ($hide_save_button) $buttons .= ' &amp; Speichern';
114         //   $buttons .= '</button>';
115         //   if (!$hide_save_button) $buttons .= '<button name="action" type="submit" value="store">Speichern</button>';
116         // Workaround: User <input type="submit"/>
117         $buttons = '<input name="preview" type="submit" value="Vorschau';
118         if ($hide_save_button) $buttons .= ' &amp; Speichern'; 
119         $buttons .= '" /> ';
120         if (!$hide_save_button) $buttons .= '<input name="store" type="submit" value="Speichern"/>';
121         
122         $specialPageName = wfMsg('wrreport'); // 'Bahnberichte'
123         $title = Title::newFromText($specialPageName, NS_SPECIAL);
124         $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
125
126         $form = <<<EOT
127 <form action="$specialPageUrl" method="post">
128 <table class="wrreportform" summary="Formular zum Eintragen eines Rodelbahnberichtes">
129         <tr class="oddrow"><th>Rodelbahn</th><td>$page_title<input type="hidden" name="page_title" value="$page_title"/></td></tr>
130         <tr class="evenrow"><th>Datum des Rodelns</th>
131         <td>
132         <select name="date_report">
133         $date_options
134         </select>
135         </td>
136         </tr>
137         <tr class="oddrow"><th>Bahnzustand*</th><td><select name="condition">
138         $condition_options
139         </select></td></tr>
140         <tr class="evenrow"><th>Meinung</th><td><textarea name="description" cols="50" rows="7">$description_html</textarea></td></tr>
141         <tr class="oddrow"><th>Autor/in</th><td><input name="author_name" maxlength="30" size="30" value="$author_name" /></td></tr>
142         <tr class="evenrow"><th>Bericht abschicken</th><td>$buttons</td></tr>
143 </table>
144 </form>
145 EOT;
146         return $form;
147 }
148
149
150 /// \brief Renders the form to delete a report
151 ///
152 /// All in and output strings should be/are UTF-8 encoded.
153 function wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible) {
154         // Buttons
155         $buttons = '<input name="deletepreview" type="submit" value="Vorschau" /> ';
156         $buttons .= utf8_encode('<input name="delete" type="submit" value="Löschen"/>');
157         $buttons .= '<input name="reportid" type="hidden" value="' . $reportid . '"/>';
158         // $buttons .= '<input name="delete_invisible" type="hidden" value="' . $delete_invisible . '"/>'; // who is allowed to do so?
159         $summary = utf8_encode('Formular zum Löschen eines Schneelageberichtes');
160         $reason = utf8_encode('Begründung');
161         $delete_reason_public_html = htmlspecialchars($delete_reason_public);
162         $delete_person_name_html = htmlspecialchars($delete_person_name);
163
164         $specialPageName = wfMsg('wrreport'); // 'Bahnberichte'
165         $title = Title::newFromText($specialPageName, NS_SPECIAL);
166         $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
167
168         $form = <<<EOT
169 <form action="$specialPageUrl" method="post">
170 <table class="wrreportform" summary="$summary">
171         <tr class="evenrow"><th>$reason</th><td><textarea name="delete_reason_public" cols="50" rows="7">$delete_reason_public_html</textarea></td></tr>
172         <tr class="oddrow"><th>Name</th><td><input name="delete_person_name" maxlength="30" size="30" value="$delete_person_name" /></td></tr>
173         <tr class="evenrow"><th>Aktion</th><td>$buttons</td></tr>
174 </table>
175 </form>
176 EOT;
177         return $form;
178 }
179
180
181
182 // Constants for wrReportTableRender2
183 define(WRREPORT_COMPACT_PAGE, 1); ///< includes the page name
184 define(WRREPORT_COMPACT, 2);      ///< shown on a single page 
185 define(WRREPORT_DETAIL, 3);       ///< more columns
186
187 /// \brief Renders a table header ("private" sub-function of wrReportTableRender2)
188 ///
189 /// \param $format row format like WRREPORT_COMPACT
190 /// \param $showActions boolean to indicate whether an actions column should be created
191 /// \return UTF-8 encoded titles of HTML table
192 function wrReportTableTitleRender2($format, $showActions) {
193         $out = '<tr>';
194         if ($format == WRREPORT_DETAIL) $out .= '<th>ID</th>';
195         if ($format != WRREPORT_COMPACT) $out .= '<th>Bahn</th>';
196         $out .= '<th>Datum</th>';
197         if ($format == WRREPORT_DETAIL) $out .= '<th>Datum Eintrag</th>';
198         if ($format == WRREPORT_DETAIL) $out .= '<th>Datum Ungültig</th>';
199         $out .= '<th>Zustand</th>';
200         $out .= '<th>Beschreibung</th>';
201         $out .= '<th>Autor</th>';
202         if ($showActions) $out .= '<th>Aktion</th>';
203         return utf8_encode($out . "</tr>\n");
204 }
205
206
207 /// \brief Renders a table row ("private" sub-function of wrReportTableRender2)
208 ///
209 /// \param $row associative array of table columns like one row in the wrreport table
210 /// \param $format row format like WRREPORT_COMPACT
211 /// \param $showActions boolean to indicate whether an actions column should be created
212 /// \return UTF-8 encoded titles of HTML table
213 function wrReportTableRowRender2($row, $format, $showActions) {
214         extract($row);
215
216         $out = '<tr>';
217         // $id
218         if ($format == WRREPORT_DETAIL) $out .= '<td>' . $id . '</td>';
219         // $page_title
220         if ($format != WRREPORT_COMPACT) $out .= '<td>' . wrReportSandboxParse('[[' . $page_title . ']]') . '</td>';
221         // $date_report
222         $dayOfWeek = array('Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So');
223         $date_report = strtotime($date_report);
224         $date_report = $dayOfWeek[strftime('%u', $date_report)-1] . strftime(', %d.%m.', $date_report);
225         $out .= '<td>' . $date_report . '</td>';
226         // $date_entry
227         if ($format == WRREPORT_DETAIL) $out .= '<td>' . date('Y-m-d, H:i', strtotime($date_entry)) . '</td>';
228         // $date_invalid
229         if ($format == WRREPORT_DETAIL) $out .= '<td>' . date('Y-m-d, H:i', strtotime($date_invalid)) . '</td>';
230         // $condition
231         global $wrConditions;
232         $condition_text = '---';
233         if (isset($wrConditions[$condition])) $condition_text = $wrConditions[$condition];
234         $out .= '<td>';
235         if ($delete_date) $out .= utf8_encode('<em>Gelöscht</em>');
236         else $out .= htmlspecialchars($condition_text);
237         $out .= '</td>';
238         // $description
239         $out .= '<td class="wrreportdescription">';
240         if ($delete_date) $out .= utf8_encode('<em>Gelöscht</em>');
241         else $out .= wrReportSandboxParse($description);
242         $out .= '</td>';
243         // $author_name
244         $out .= '<td>';
245         if ($delete_date) $out .= utf8_encode('<em>Gelöscht</em>');
246         else $out .= htmlspecialchars($author_name);
247         $out .= '</td>';
248         // actions
249         // wiki/Spezial:Bahnberichte?action=deletepreview&reportid=42
250         if ($showActions) {
251                 $out .= '<td>';
252                 if (!isset($row['delete_date'])) {
253                         $specialPageName = wfMsg('wrreport'); // 'Bahnberichte'
254                         $title = Title::newFromText($specialPageName, NS_SPECIAL);
255                         $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
256                         $out .= "<a href=\"$specialPageUrl?action=deletepreview&amp;reportid=" . $row['id'] . '">' . utf8_encode('Löschen...') . '</a>';
257                 }
258                 $out .= '</td>';
259         }
260         return $out . "</tr>\n";
261 }
262
263
264 /// \brief Renders the report table. Call wrReportGetReports for the $rows parameter.
265 ///
266 /// \param $rows array of associative row arrays
267 /// \param $format row format like WRREPORT_TABLE_SHORT
268 function wrReportTableRender2($rows, $format, $showActions) {
269         $out = "<table class=\"wrreporttable\">\n" . wrReportTableTitleRender2($format, $showActions);
270         foreach ($rows as $key => $row) $out .= wrReportTableRowRender2($row, $format, $showActions);
271         return $out . "</table>\n";
272 }
273
274
275 /// Returns an array with column names
276 function wrReportGetColumnNames() {
277         return array('id', 'page_id', 'page_title', 'date_report', 'date_entry', 'date_invalid', 'condition', 'description', 'author_name', 'author_username', 'delete_date', 'delete_person_name', 'delete_person_ip', 'delete_person_userid', 'delete_person_username', 'delete_reason_public', 'delete_invisible');
278 }
279
280
281 /// \brief Returns reports as associative array.
282 ///
283 /// Examples: 
284 ///   $conditions = array('page_title' => 'Birgitzer Alm', 'date_invalid > now()');
285 ///   $order = 'date_report desc, date_entry desc';
286 function wrReportGetReports($conditions, $order) {
287         $dbr = wfGetDB(DB_SLAVE);
288         $columns = wrReportGetColumnNames();
289         global $wgDBtype;
290         if ($wgDBtype == "mysql") // "condition" is a reserved word in mysql
291                  for ($i = 0; $i != count($columns); ++$i) $columns[$i] = sprintf('`%s`', $columns[$i]);
292         $res = $dbr->select('wrreport', $columns, $conditions, $fname = 'Database::select', $options = array('ORDER BY' => 'date_report desc, date_entry desc'));
293         $result = array();
294         while ($row = $dbr->fetchRow($res)) $result[] = $row;
295         $dbr->freeResult($res);
296         return $result;
297 }
298
299
300 /// \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);
301 ///
302 /// If no condition is present, array(NULL, NULL) is returned
303 function wrReportConditionRender($page_title) {
304         $dbr = wfGetDB(DB_SLAVE);
305         $cond = 'condition';
306         global $wgDBtype;
307         if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
308         $res = $dbr->select('wrreport', array('max(wrreport.id) as max'), array('page_title' => $page_title, "$cond is not null", 'date_invalid > now()'));
309         //  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);
310         if ($res->numRows() <= 0) {
311                 $dbr->freeResult($res);
312                 return array(NULL, NULL);
313         }
314         $row = $dbr->fetchObject($res);
315         $dbr->freeResult($res);
316         $res = $dbr->select('wrreport', array($cond, 'date_report'), array('id' => $row->max));
317         if ($res->numRows() <= 0) {
318                 $dbr->freeResult($res);
319                 return array(NULL, NULL);
320         }
321         $row = $dbr->fetchObject($res);
322         $date = $row->date_report;
323         if ($date) $date = strtotime($date);
324         $dbr->freeResult($res);
325         return array($row->condition, $date);
326 }
327
328
329 /// \brief Returns true if the user is allowed to delete reports (in general)
330 function wrReportUserMayDelete() {
331         global $wgUser;
332         global $wgWrReportDeleteMode;
333         return $wgWrReportDeleteMode == 'allow' || ($wgWrReportDeleteMode == 'loggedin' && $wgUser->isLoggedIn());
334 }
335
336
337
338 // Parser Hook Functions
339 // ---------------------
340
341 /// \brief Is called when the tag <bahnberichtformular/> is encountered.
342 ///
343 /// The current page name is taken.
344 function bahnberichtformularParserHook($input, $args, $parser) {
345         // Username
346         global $wgUser;
347         $author_name = NULL;
348         if ($wgUser->isLoggedIn()) {
349                 $author_name = $wgUser->getRealName();
350                 if (!$author_name) $author_name = $wgUser->getName();
351         }
352
353         global $wgWrReportMode;
354         global $wgWrReportBlackListAll;
355         global $wgWrReportBlackListStrangers;
356         if ($wgWrReportMode == 'summer') return wrReportSandboxParse(utf8_encode("''An dieser Stelle kann während des Winters die Schneelage von Rodelbahnen eingetragen werden.''\n\n"));
357         if ($wgWrReportMode == 'deny') return wrReportSandboxParse(utf8_encode("''Rodelbahnberichte sind derzeit leider nicht erlaubt.''\n\n"));
358
359         if ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) return wrReportSandboxParse(utf8_encode("''Derzeit sind Rodelbahnberichte nur für angemeldete Benutzer erlaubt.''\n\n"));
360
361         if (in_array($parser->getTitle()->getText(), $wgWrReportBlackListAll)) return wrReportSandboxParse(utf8_encode("''Bei dieser Rodelbahn dürfen derzeit leider keine Rodelbahnberichte abgegeben werden.''\n"));
362         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"));
363         
364         // Calling "$title = $parser->getTitle(); $title->invalidateCache();" doesn't help here to force regeneration
365         // However, this would not be the best solution because the page has to be re-rendered only at midnight
366
367         // In the following line, $author_name was replaced by NULL to prevent a bug, where the wrong author_name
368         // is shown (see ticket #35). TODO: Find reason.
369         // return replaceByMarker(wrReportFormRender(TRUE, $parser->getTitle()->getText(), NULL, NULL, NULL, $author_name));
370         return replaceByMarker(wrReportFormRender(TRUE, $parser->getTitle()->getText(), NULL, NULL, NULL, NULL));
371 }
372
373
374 /// \brief Is called when the tag <bahnberichte/> is encountered.
375 ///
376 /// The current page name is taken.
377 function bahnberichteParserHook($input, $args, &$parser) {
378         $page_title = $parser->getTitle()->getText();
379         $conditions = array('page_title' => $page_title, 'date_invalid > now()');
380         $order = 'date_report desc, date_entry desc';
381         $rows = wrReportGetReports($conditions, $order);
382         if (count($rows) == 0) return wrReportSandboxParse("''Es wurden keine Bahnberichte in der Datenbank gefunden.''\n\n");
383         return wrReportTableRender2($rows, WRREPORT_COMPACT, wrReportUserMayDelete());
384 }
385
386
387 /// \brief Is called when the tag <bahnbewertung/> is encountered.
388 ///
389 /// * <bahnbewertung/>: The current page name is taken.
390 /// * <bahnbewertung>page_name</bahnbewertung>: The given page name is taken.
391 function bahnbewertungParserHook($input, $args, &$parser) {
392         $titleText = $input;
393         if (!$titleText) $titleText = $parser->getTitle()->getText();
394         list($condition, $date) = wrReportConditionRender($titleText);
395         if ($date) $date = strftime('%d.%m.', $date);
396         global $wrConditions;
397         global $wrNewReportSection; //  = utf8_encode('Eintragen');
398         global $wrShowReportsSection; //  = utf8_encode('Einträge');
399         global $wgUser;
400         global $wgWrReportMode; // e.g. 'summer'
401         global $wgWrReportBlackListAll;
402         global $wgWrReportBlackListStrangers;
403
404         // Determine, whether the user is allowed to make a new report
405         $userMayReport = ($wgWrReportMode == 'allow' || ($wgWrReportMode == 'loggedin' && $wgUser->isLoggedIn()));
406         if ($userMayReport) {
407                 if (in_array($titleText, $wgWrReportBlackListAll)) $userMayReport = false;
408                 if (!$wgUser->isLoggedIn() && in_array($titleText, $wgWrReportBlackListStrangers)) $userMayReport = false;
409         }
410
411         // Get the condition and create the response wiki text
412         if (isset($wrConditions[$condition])) {
413                 $wikiText = '[['. $titleText . '#' . $wrShowReportsSection . '|'. $wrConditions[$condition] . "]] <small>$date";
414                 if ($userMayReport) $wikiText .= " ''[[" . $titleText . '#' . $wrNewReportSection . "|Neu]]''";
415                 $wikiText .= "</small>";
416         } else {
417                 if ($userMayReport) $wikiText = "<small>''[[" . $titleText . '#' . $wrNewReportSection . "|Bitte eintragen]]''</small>";
418                 else $wikiText = '--';
419         }
420         return wrReportSandboxParse($wikiText);
421 }
422
423
424
425 // Special page
426 // ------------
427
428 /// Specal Page to show reports
429 class WrReport extends SpecialPage {
430         function WrReport() {
431                 SpecialPage::SpecialPage('WrReport');
432                 wfLoadExtensionMessages('WrReport');
433         }
434
435
436         /// \param $par Possibilities:
437         /// - action == 'view' (default)
438         /// - action == 'preview': Preview new report
439         /// - action == 'store': Store new report
440         /// - action == 'deletepreview': Preview the deleted record
441         /// - action == 'delete': Delete an existing report
442         /// - action == 'showerror': Shows the error and exits
443         /// \param $override_action If not NULL (default), it overrides the action in $par
444         /// \param $errorMsg UFT-8 encoded error message (in WikiText) to show on top of the page or NULL (default):
445         function execute($par, $override_action = NULL, $errorMsg = NULL) {
446                 global $wgRequest, $wgOut;
447
448                 $this->setHeaders();
449
450                 // Get request data
451                 $action = $wgRequest->getText('action');
452                 if (!$action) {
453                         if ($wgRequest->getVal('preview')) $action = 'preview';
454                         elseif ($wgRequest->getVal('store')) $action = 'store';
455                         elseif ($wgRequest->getVal('deletepreview')) $action = 'deletepreview';
456                         elseif ($wgRequest->getVal('delete')) $action = 'delete';
457                         else $action = 'view';
458                 }
459                 if ($override_action) $action = $override_action;
460
461                 // Show error message
462                 if ($errorMsg || $action == 'showerror') {
463                         $wgOut->addWikiText('<div class="errorbox">' . $errorMsg . "</div>\n");
464                         if ($action == 'showerror') return;
465                 }
466
467                 // Action view
468                 if ($action == 'view') {                
469                         $conditions = array('date_invalid > now()');
470                         $order = 'date_entry desc, date_report desc';
471                         $rows = wrReportGetReports($conditions, $order);
472                         if (count($rows) == 0) $wgOut->addWikiText("''Es wurden keine Bahnberichte in der Datenbank gefunden.''\n\n");
473                         $wgOut->addHTML(wrReportTableRender2($rows, WRREPORT_DETAIL, wrReportUserMayDelete())); 
474                 }
475
476                 // Action deletepreview or delete
477                 elseif ($action == 'deletepreview' || $action == 'delete') {
478                         $reportid = (int) $wgRequest->getText('reportid');
479                         if ($reportid == 0) {
480                                 $this->execute($par, 'showerror', utf8_encode('Es wurde kein Bericht zum Löschen ausgewählt.'));
481                                 return;
482                         }
483                         $rows = wrReportGetReports(array('id' => $reportid), '');
484                         if (count($rows) != 1) {
485                                 $this->execute($par, 'showerror', utf8_encode('Es wurde ein ungültiger Bericht zum Löschen ausgewählt.'));
486                                 return;
487                         }
488                         $row = $rows[0];
489                         if (!is_null($row['delete_date'])) {
490                                 $this->execute($par, 'showerror', utf8_encode('Der angegebende Bericht ist bereits gelöscht.'));
491                                 return;
492                         }
493                         $delete_reason_public = $wgRequest->getText('delete_reason_public');
494                         $delete_person_name = $wgRequest->getText('delete_person_name');
495                         $delete_invisible = $wgRequest->getText('delete_invisible') ? TRUE : FALSE;
496                         if ($action == 'delete') {
497                                 // page
498                                 $title = Title::newFromId($row['page_id']);
499
500                                 // user
501                                 global $wgUser;
502                                 $delete_person_userid = $wgUser->getId();
503                                 if ($delete_person_userid == 0) $delete_person_userid = NULL; // to store a NULL value in the database if no user is logged in instead of 0.
504                                 $delete_person_username = $wgUser->getName();
505
506                                 // Check permissions - see also function wrReportUserMayDelete, that does also check permissions but does not return an error message.
507                                 $errorMsg = NULL;
508                                 global $wgWrReportDeleteMode;
509                                 if ($wgWrReportDeleteMode == 'deny') $errorMsg = utf8_encode('Das Löschen von Rodelbahnberichten ist derzeit leider nicht erlaubt.');
510                                 elseif ($wgWrReportDeleteMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = utf8_encode('Derzeit dürfen nur angemeldete Benutzer Rodelbahnberichte löschen.');
511                                 elseif (!$delete_person_name || !$delete_reason_public) $errorMsg = utf8_encode('Es müssen sowohl die Begründung als auch der Name angegeben werden.');
512                                 if ($errorMsg) {
513                                         $this->execute($par, 'deletepreview', $errorMsg);
514                                         return;
515                                 }
516                                 
517                                 // "Delete" (update) entry
518                                 $dbr = wfGetDB(DB_MASTER);
519                                 $dbr->update(
520                                         'wrreport', 
521                                         array(
522                                                 'delete_date' => date('c'),
523                                                 'delete_person_name' => $delete_person_name,
524                                                 'delete_person_ip' => $_SERVER['REMOTE_ADDR'],
525                                                 'delete_person_userid' => $delete_person_userid,
526                                                 'delete_person_username' => $delete_person_username,
527                                                 'delete_reason_public' => $delete_reason_public,
528                                                 'delete_invisible' => $delete_invisible ? 't' : 'f'
529                                         ),
530                                         array('id' => $reportid)
531                                 );
532
533                                 // Purge cache
534                                 $title->invalidateCache();
535                                 wrRecacheRegions();                             
536
537                                 // Show success message
538                                 global $wrShowReportsSection;
539                                 $wgOut->addWikiText(utf8_encode('<div class="successbox">Der Bahnbericht für [[') . $row['page_title'] . '#' . $wrShowReportsSection . '|' . $row['page_title'] . utf8_encode("]] wurde erfolgreich gelöscht.</div>\n"));
540                         }
541                         if ($action == 'deletepreview') {
542                                 $preview_msg = "Bitte nur dann einen Bericht löschen, wenn Gründe vorliegen wie\n" .
543                                 "* Beschimpfungen, Verleumdungen (wir wollen ''Rodelbahnen'' bewerten, nicht Personen)\n" .
544                                 "* Werbung oder Spam (wenn jemand allerdings ''werbend'' zu gute Noten vergibt, lieber eigenen Bericht eintragen als löschen).\n\n";
545                                 $wgOut->addWikiText(utf8_encode($preview_msg));
546                                 $wgOut->addWikiText(utf8_encode("== Schneelagebericht, um den es beim Löschen geht ==\n"));
547                                 $format = WRREPORT_COMPACT_PAGE;
548                                 $wgOut->addHTML(wrReportTableRender2(array($row), $format, FALSE));
549                                 $wgOut->addWikiText(utf8_encode("\n\n== Vorschau (derzeit noch nicht gelöscht) ==\n"));
550                                 $row['delete_date'] = date('c');
551                                 $row['delete_reason_public'] = $delete_reason_public;
552                                 $row['delete_person_name'] = $delete_person_name;
553                                 $row['delete_invisible'] = $delete_invisible;
554                                 $wgOut->addHTML(wrReportTableRender2(array($row), $format, FALSE));
555                                 $wgOut->addWikiText(utf8_encode("== Löschen ==\n"));
556                                 $wgOut->addWikiText(utf8_encode("Die Begründung und der Name scheinen nicht in den normalen Listen auf, allerdings dienen sie den Administratoren dazu, sich schnell einen Überblick zu verschaffen, wer was warum gelöscht hat.\n"));
557                                 $wgOut->addHTML(wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible));
558                         }
559                 }
560
561                 // Action preview or store
562                 elseif ($action == 'preview' || $action == 'store') {
563                         $page_title = $wgRequest->getText('page_title');
564                         $date_report = $wgRequest->getText('date_report');
565                         $condition = $wgRequest->getText('condition');
566                         $description = $wgRequest->getText('description');
567                         $author_name = $wgRequest->getText('author_name');
568                         if ($action == 'store') {
569                                 // page_id
570                                 $title = Title::newFromText($page_title);
571                                 $page_id = $title->getArticleId();
572                                 if ($page_id == 0) $page_id = NULL;
573                                 
574                                 // user_id
575                                 global $wgUser;
576                                 $author_userid = $wgUser->getId();
577                                 if ($author_userid == 0) $author_userid = NULL; // to store a NULL value in the database if no user is logged in instead of 0.
578                                 $author_username = $wgUser->getName();
579
580                                 // condition
581                                 $condition_int = (int) $condition;
582                                 if ($condition_int >= 1 and $condition_int <= 5) $condition = $condition_int;
583                                 else $condition = NULL;
584                                 
585                                 // check conditions/permissions
586                                 $errorMsg = NULL;
587                                 global $wgWrReportMode;
588                                 global $wgWrReportBlackListAll;
589                                 global $wgWrReportBlackListStrangers;
590                                 if ($wgWrReportMode == 'summer') $errorMsg = utf8_encode('Rodelbahnberichte sind in der schneefreien Zeit nicht erlaubt.');
591                                 elseif ($wgWrReportMode == 'deny') $errorMsg = utf8_encode('Rodelbahnberichte sind derzeit leider nicht erlaubt.');
592                                 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = utf8_encode('Derzeit sind Rodelbahnberichte nur für angemeldete Benutzer erlaubt.');
593                                 elseif (!$page_id) $errorMsg = utf8_encode('Die angegebene Seite wurde nicht gefunden.');
594                                 elseif (in_array($page_title, $wgWrReportBlackListAll)) $errorMsg = utf8_encode('Bei der angegebenen Rodelbahn dürfen derzeit keine Rodelbahnberichte abgegeben werden.');
595                                 elseif (!$wgUser->isLoggedIn() && in_array($page_title, $wgWrReportBlackListStrangers)) $errorMsg = utf8_encode('Bei der angegebenen Rodelbahn dürfen derzeit nur angemeldete Benutzer Rodelbahnberichte abgebe.');
596                                 elseif (!$condition && !$description) $errorMsg = utf8_encode('Es sind sowohl die Beschreibung als auch die Bewertung leer/nicht vergeben.');
597                                 elseif (!$wgUser->isLoggedIn()) {
598                                         if (!$description) $errorMsg = utf8_encode('Bitte bei der Beschreibung eine kurze Begründung für die Bewertung abgeben.');
599                                         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.');
600                                 }
601
602                                 // Chech whether identical reports are present
603                                 if (!$errorMsg) {
604                                         $dbr = wfGetDB(DB_SLAVE);
605                                         $cond = 'condition';
606                                         global $wgDBtype;
607                                         if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
608                                         $sqlConditions = array('page_id' => $page_id, 'date_report' => $date_report, $cond => $condition, 'description' => $description, 'author_name' => $author_name);
609                                         $res = $dbr->select('wrreport', 'id', $sqlConditions);
610                                         if ($res->numRows() == 1) $errorMsg = utf8_encode('Der Rodelbahnbericht wurde bereits früher gespeichert.');
611                                         $dbr->freeResult($res);
612                                 }
613
614                                 // Show error if any
615                                 if ($errorMsg) {
616                                         $this->execute($par, 'preview', $errorMsg);
617                                         return;
618                                 }
619
620                                 // Save entry
621                                 $dbr = wfGetDB(DB_MASTER);
622                                 $dbr->insert(
623                                         'wrreport', 
624                                         array(
625                                                 'page_id' => $page_id, 
626                                                 'page_title' => $page_title, 
627                                                 'date_report' => $date_report, 
628                                                 'date_entry' => date('c'),
629                                                 'date_invalid' => date('c', strtotime('+9 days')),
630                                                 $cond => $condition,
631                                                 'description' => $description,
632                                                 'author_name' => $author_name,
633                                                 'author_ip' => $_SERVER['REMOTE_ADDR'],
634                                                 'author_userid' => $author_userid,
635                                                 'author_username' => $author_username
636                                                 // 'delete_*' => // use database defaults (NULL)
637                                         )
638                                 );
639
640                                 // Purge cache
641                                 $title->invalidateCache();
642                                 wrRecacheRegions();                             
643
644                                 // Show success message
645                                 global $wrShowReportsSection;
646                                 $wgOut->addWikiText(utf8_encode('<div class="successbox">Der Bahnbericht für [[') . $page_title . '#' . $wrShowReportsSection . '|' . $page_title . utf8_encode("]] wurde erfolgreich gespeichert.</div>\n"));
647                                 // We could redirect to result with the following line but we don't want to.
648                                 // $wgOut->redirect($title->getFullURL() . '#Eintr.C3.A4ge');
649                         }
650                         if ($action == 'preview') {
651                                 $wgOut->addWikiText(utf8_encode("== Vorschau (noch nicht gespeichert) ==\n"));
652                                 $format = WRREPORT_COMPACT_PAGE;
653                                 $row = array_fill_keys(wrReportGetColumnNames(), NULL);
654                                 $row['page_title'] = $page_title;
655                                 $row['date_report'] = $date_report;
656                                 $row['condition'] = $condition;
657                                 $row['description'] = $description;
658                                 $row['author_name'] = $author_name;
659                                 $wgOut->addHTML(wrReportTableRender2(array($row), $format, FALSE));
660                                 $wgOut->addWikiText(utf8_encode("== Speichern oder Ändern ==\n"));
661                                 $wgOut->addHTML(wrReportFormRender(FALSE, $page_title, $date_report, $condition, $description, $author_name));
662                         } 
663                         
664                 }
665
666                 else die('Wrong action');
667         }
668 }
669
670
671 ?>