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