Fixed parameter when displaying an error message.
[philipp/winterrodeln/mediawiki_extensions/wrreport.git] / wrreport.body.php
1 <?php
2 // File encoding: utf-8
3 // Classes for the wrreport extension.
4
5
6 // Constants
7 // ---------
8
9 // Constants for wrReportTableRender
10 define('WRREPORT_COMPACT_PAGE', 1); ///< includes the page name
11 define('WRREPORT_COMPACT', 2);      ///< shown on a single page
12 define('WRREPORT_DETAIL', 3);       ///< more columns
13
14
15
16 // DOM helper classes
17 // ------------------
18
19 class WrDOMDocument extends DOMDocument {
20         function __construct() {
21                 parent::__construct('1.0', 'utf-8');
22                 $this->registerNodeClass('DOMElement', 'WrDOMElement');
23         }
24
25         /// Creates and adds the element with the given tag name and returns it.
26         /// Additionally, it calls setAttribute($key, $value) for every entry
27         /// in $attributes.
28         function appendElement($tagName, $attributes=array()) {
29                 $child = $this->appendChild($this->createElement($tagName));
30                 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
31                 return $child;
32         }
33
34 }
35
36
37 class WrDOMElement extends DOMElement {
38
39         /// Creates and adds the element with the given tag name and returns it
40         /// Additionally, it calls setAttribute($key, $value) for every entry
41         /// in $attributes.
42         function appendElement($tagName, $attributes=array()) {
43                 $child = $this->appendChild($this->ownerDocument->createElement($tagName));
44                 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
45                 return $child;
46         }
47
48         /// Adds any UTF-8 string as content of the element - it will be escaped.
49         function appendText($text) {
50                 return $this->appendChild($this->ownerDocument->createTextNode($text));
51         }
52
53         // Appends a CDATASections to the element. This can be used to include
54         // raw (unparsed) HTML to the DOM tree as it is necessary because
55         // $parser->recursiveTagParse does not always escape & characters.
56         // (see https://bugzilla.wikimedia.org/show_bug.cgi?id=55526 )
57         // Workaround: Use a CDATA section. When serializing with $doc->saveHTML,
58         // the <![CDATA[...]]> is returned as ... .
59         // However, we end up having unescaped & in the output due to this bug in recursiveTagParse.
60         function appendCDATA($data) {
61                 return $this->appendChild($this->ownerDocument->createCDATASection($data));
62         }
63 }
64
65
66
67 // WrReportException
68 // -----------------
69
70 /// Exception type that is used internally by WrReport
71 class WrReportException extends Exception {}
72
73
74
75 // Fast version of Services_Libravatar
76 // -----------------------------------
77
78 /// This is a fast version of Services_Libravatar by omitting the DNS
79 /// lookup and always falling back to libravatar.org
80 class WrServicesLibravatar extends Services_Libravatar {
81         function __construct() {
82                 $this->setSize(32);
83                 $this->setDefault('monsterid');
84         }
85
86
87         protected function srvGet($domain, $https = false) {
88                 if ($https === true) return 'seccdn.libravatar.org';
89                 return 'cdn.libravatar.org';
90         }
91
92
93         public function getSize() {
94                 return $this->size;
95         }
96 }
97
98
99
100 // Tool functions
101 // --------------
102
103 /// Forces a regeneration of region overview pages ('Tirol', 'Vorarlberg', ...)
104 function wrRecacheRegions() {
105         $dbr = wfGetDB(DB_SLAVE);
106         // SELECT cl_from FROM categorylinks where cl_to = 'Region'
107         $res = $dbr->select('categorylinks', 'cl_from', array('cl_to' => 'Region'));
108         $page_ids = array();
109         while ($row = $dbr->fetchObject($res)) $page_ids[] = $row->cl_from;
110         $dbr->freeResult($res);
111
112         $titles = Title::newFromIDs($page_ids);
113         foreach ($titles as $title) $title->invalidateCache();
114 }
115
116
117 /// Returns the tuple ($report_id, $sledrun_condition, $date_report)
118 /// $date_report is NULL or a time as returned by strtotime
119 /// Expects a database connection ($dbr = wfGetDB(DB_SLAVE);)
120 /// and a page_id describung the page where the condition should be returned.
121 /// If no condition is found, (NULL, NULL, NULL) is returned.
122 function wrGetSledrunCondition($dbr, $page_id) {
123         // 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;
124         $cres = $dbr->select(
125                 'wrreport',
126                 array('wrreport.id as report_id', '`condition`', 'date_report'),
127                 array('page_id' => $page_id, '`condition` is not null', 'date_invalid > now()', 'delete_date is null'),
128                 'wrReportConditionRender',
129                 array('ORDER BY' => 'date_report desc, date_entry desc', 'LIMIT' => '1')
130         );
131         if ($cres->numRows() <= 0) {
132                 $report_id = NULL;
133                 $condition = NULL;
134                 $date_report = NULL;
135         } else {
136                 $crow = $dbr->fetchObject($cres);
137                 $report_id = $crow->report_id;
138                 $condition = $crow->condition;
139                 $date_report = strtotime($crow->date_report);
140         }
141         $dbr->freeResult($cres);
142         return array($report_id, $condition, $date_report);
143 }
144
145
146 /// Updates the line of the wrreportcache table that corresponds to the $page_id parameter
147 function wrUpdateWrReportCacheTable($page_id) {
148         // Determine the new content for the row that should be updated
149         $dbr = wfGetDB(DB_SLAVE);
150         list($report_id, $condition, $date_report) = wrGetSledrunCondition($dbr, $page_id);
151         $rows = wrReportGetReports(array('id' => $report_id), 1);
152
153         // Delete the old content (if any)
154         $dbw = wfGetDB(DB_MASTER);
155         $dbw->begin();
156         $dbw->delete('wrreportcache', array('page_id' => $page_id));
157
158         // Insert the updated row
159         if (count($rows) == 1) {
160                 $row = $rows[0];
161                 $dbw->insert('wrreportcache', array(
162                         'page_id' => $row['page_id'],
163                         'page_title' => $row['page_title'],
164                         'report_id' => $row['id'],
165                         'date_report' => $row['date_report'],
166                         '`condition`' => $row['condition'],
167                         'description' => $row['description'],
168                         'author_name' => $row['author_name'],
169                         'author_username' => (is_null($row['author_userid']) ? NULL : $row['author_username'])));
170         }
171         $dbw->commit();
172 }
173
174
175
176 // Render Functions
177 // ----------------
178
179 /// \brief Returns a form to enter a report (string containing HTML).
180 ///
181 /// All parameters have to be UTF-8 encoded.
182 /// \param $page_title Name of the sledrun.
183 /// \param $condition 1 to 5 for normal condition, 0 or NULL for missing condition and -1 for intentionally no condition.
184 /// \return UTF-8 encoded HTML form
185 function wrReportFormRender($hide_save_button = TRUE, $page_title = NULL, $date_report = NULL, $time_report = NULL, $condition = NULL, $description = NULL, $author_name = NULL, $page_title_list = NULL) {
186         $doc = new WrDOMDocument();
187         $rownum = 0;
188
189         // Info about special page
190         $specialPageName = wfMessage('wrreport')->text(); // 'Bahnberichte'
191         $title = Title::newFromText($specialPageName, NS_SPECIAL);
192         $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
193
194         // form
195         $form = $doc->appendElement('form', array('action' => $specialPageUrl, 'method' => 'post'));
196
197         // table (for layout of form elements)
198         $table = $form->appendElement('table', array('class' => 'wrreportform', 'summary' => wfMessage('wrreport-newreport-tablesummary')->text()));
199
200         // sledrun name
201         $tr = $table->appendElement('tr');
202         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
203         $td = $tr->appendElement('td');
204         $td->appendText($page_title);
205         $td->appendElement('input', array('type' => 'hidden', 'name' => 'page_title', 'value' => $page_title));
206
207         // report date
208         $tr = $table->appendElement('tr');
209         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-date')->text());
210         $td = $tr->appendElement('td');
211         $select = $td->appendElement('select', array('name' => 'date_report'));
212         $daynames = array(
213                 wfMessage('wrreport-date-today')->text(),
214                 wfMessage('wrreport-date-yesterday')->text(),
215                 wfMessage('wrreport-date-2daysbefore')->text(),
216                 wfMessage('wrreport-date-3daysbefore')->text(),
217                 wfMessage('wrreport-date-4daysbefore')->text());
218         $date_selected = false;
219         $time = time(); // number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
220         for ($day=0; $day!=5; ++$day) {
221                 $date = strtotime("-$day days", $time);
222                 $date_f = strftime("%Y-%m-%d", $date); // Formats it according to locale, that is set to CET.
223                 $option = $select->appendElement('option', array('value' => $date_f));
224                 if ((is_null($date_report) && $day == 0) || (!is_null($date_report) && $date_report == $date_f)) {
225                         $option->setAttribute('selected', 'selected');
226                         $date_selected = true;
227                 }
228                 $option->appendText($daynames[$day] . ' (' . strftime('%d.%m.', $date) . ')');
229         }
230         if (!$date_selected) { // note: if $date_report is null $date_selected is true here
231                 $option = $select->appendElement('option', array('value' => $date_report, 'selected' => 'selected'));
232                 $option->appendText($date_report);
233         }
234
235         // report time
236         $tr = $table->appendElement('tr');
237         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-time')->text());
238         $td = $tr->appendElement('td');
239         $td->appendElement('input', array('name' => 'time_report', 'maxlength' => '5', 'size' => '5', 'value' => $time_report));
240         $td->appendText(' ');
241         $td->appendText('Uhr');
242         $td->appendText(' ');
243         $td->appendElement('span', array('class' => 'wrcomment'))->appendText("(z.B. '14', '1400' oder '14:00'. Optional.)");
244
245         // condition
246         $tr = $table->appendElement('tr');
247         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
248         $td = $tr->appendElement('td');
249         $select = $td->appendElement('select', array('name' => 'condition'));
250         $option = $select->appendElement('option', array('value' => '0'));
251         $option->appendText(wfMessage('wrreport-condition-select')->text());
252         foreach (WrReport::$wrConditions as $condition_num => $condition_text) {
253                 $option = $select->appendElement('option', array('value' => (string) $condition_num));
254                 if ($condition == $condition_num) $option->setAttribute('selected', 'selected');
255                 $option->appendText($condition_text);
256         }
257         $option = $select->appendElement('option', array('value' => '-1'));
258         if ($condition == -1) $option->setAttribute('selected', 'selected');
259         $option->appendText(wfMessage('wrreport-condition-no')->text());
260
261         // description
262         $tr = $table->appendElement('tr');
263         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-description')->text());
264         $tr->appendElement('td')->appendElement('textarea', array('name' => 'description', 'cols' => '50', 'rows' => '7'))->appendText($description);
265
266         // author
267         $tr = $table->appendElement('tr');
268         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-author')->text());
269         $tr->appendElement('td')->appendElement('input', array('name' => 'author_name', 'maxlength' => '30', 'size' => '30', 'value' => $author_name));
270
271         // Buttons
272         // I would like to do it this way, but due to a bug of internet explorer, the <button> element is not useable.
273         //   $buttons = '<button name="action" type="submit" value="preview">Vorschau';
274         //   if ($hide_save_button) $buttons .= ' &amp; Speichern';
275         //   $buttons .= '</button>';
276         //   if (!$hide_save_button) $buttons .= '<button name="action" type="submit" value="store">Speichern</button>';
277         // Workaround: User <input type="submit"/>
278         $tr = $table->appendElement('tr');
279         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-submit')->text());
280         $td = $tr->appendElement('td');
281         $input = $td->appendElement('input', array('name' => 'preview', 'type' => 'submit'));
282         if ($hide_save_button)
283                 $input->setAttribute('value', wfMessage('wrreport-newreport-preview')->text() . ' & ' . wfMessage('wrreport-newreport-save')->text());
284         else {
285                 $input->setAttribute('value', wfMessage('wrreport-newreport-preview')->text());
286
287                 $td->appendElement('input', array('name' => 'store', 'type' => 'submit', 'value' => wfMessage('wrreport-newreport-save')->text()));
288         }
289
290         return $doc->saveHTML($form);
291 }
292
293
294 /// \brief Renders the form to delete a report
295 ///
296 /// All in and output strings should be/are UTF-8 encoded.
297 /// \param $reportid the id of the report that is going to be deleted
298 /// \param $delete_person_name name of the person that wants to delete the report (form field)
299 /// \param $delete_reason_public publically visible reason for deleting the entry.
300 /// \param $delete_invisible don't show the report as being deleted
301 /// \return UTF-8 encoded HTML form
302 function wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible) {
303         $doc = new WrDOMDocument();
304         $rownum = 0;
305
306         // Info about special page
307         $specialPageName = wfMessage('wrreport')->text(); // 'Bahnberichte'
308         $title = Title::newFromText($specialPageName, NS_SPECIAL);
309         $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
310
311         // form
312         $form = $doc->appendElement('form', array('action' => $specialPageUrl, 'method' => 'post'));
313
314         // table (for layout of form elements)
315         $table = $form->appendElement('table', array('class' => 'wrreportform', 'summary' => wfMessage('wrreport-deletereport-tablesummary')->text()));
316
317         // delete_reason_public
318         $tr = $table->appendElement('tr');
319         $tr->appendElement('th')->appendText(wfMessage('wrreport-deletereport-reason')->text());
320         $tr->appendElement('td')->appendElement('textarea', array('name' => 'delete_reason_public', 'cols' => '50', 'rows' => '7'))->appendText($delete_reason_public);
321
322         // delete_person_name
323         $tr = $table->appendElement('tr');
324         $tr->appendElement('th')->appendText(wfMessage('wrreport-deletereport-name')->text());
325         $tr->appendElement('td')->appendElement('input', array('name' => 'delete_person_name', 'maxlength' => '30', 'size' => '30', 'value' => $delete_person_name));
326
327         // buttons
328         $tr = $table->appendElement('tr');
329         $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-action')->text());
330         $td = $tr->appendElement('td');
331         $td->appendElement('input', array('name' => 'deletepreview', 'type' => 'submit', 'value' => wfMessage('wrreport-newreport-preview')->text()));
332         $td->appendElement('input', array('name' => 'delete', 'type' => 'submit', 'value' => wfMessage('wrreport-deletereport-delete')->text()));
333
334         // hidden field
335         $input = $td->appendElement('input', array('name' => 'reportid', 'type' => 'hidden', 'value' => (string) $reportid));
336         // delete_invisible - who is allowed to do so?
337         // $td->appendElement('input', array('name' => 'delete_invisible', 'type' => 'hidden', 'value' => (string) $delete_invisible));
338
339         return $doc->saveHTML($form);
340 }
341
342
343 /// \brief Generates the DOM of the table header ("private" sub-function of wrReportTableRender)
344 ///
345 /// \param $table table WrDOMElement where the header should be appended
346 /// \param $format row format like WRREPORT_COMPACT
347 /// \param $showActions boolean to indicate whether an actions column should be created
348 /// \return WrDOMElement of the HTML table header
349 function wrReportTableTitleRender($table, $format, $showActions) {
350         $tr = $table->appendElement('tr');
351         $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-date-trip')->text());
352         if ($format != WRREPORT_COMPACT) $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
353         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
354         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-description')->text());
355         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-author')->text());
356         if ($format == WRREPORT_DETAIL) $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-date-entry')->text());
357         if ($showActions) $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-action')->text());
358         return $tr;
359 }
360
361
362 /// \brief Generates the DOM of a table row ("private" sub-function of wrReportTableRender)
363 ///
364 /// \param $table table WrDOMElement where the row should be appended
365 /// \param $row associative array of table columns like one row in the wrreport table
366 /// \param $format row format like WRREPORT_COMPACT
367 /// \param $showActions boolean to indicate whether an actions column should be created
368 /// \param $parser Parser instance of a Parser class that can be used to parse the condition
369 /// \return WrDOMElement of the HTML table row
370 function wrReportTableRowRender($table, $row, $format, $showActions, $parser) {
371         $tr = $table->appendElement('tr');
372
373         // $row['date_report'] and $row['time_report']
374         $date_report = strtotime($row['date_report']);
375         $date_report = wfMessage(Language::$mWeekdayAbbrevMsgs[(int) date('w', $date_report)])->text() . strftime(', %d.%m.', $date_report);
376         $td = $tr->appendElement('td');
377         $td->appendText($date_report);
378         if ($row['time_report']) {
379                 $td->appendText(' ');
380                 $td->appendElement('span', array('class' => 'wrcomment'))->appendText(date('H:i', strtotime($row['time_report'])));
381         }
382
383         // $row['page_title']
384         if ($format != WRREPORT_COMPACT) {
385                 $title = Title::newFromText($row['page_title']);
386                 $tr->appendElement('td')->appendCDATA(Linker::link($title));
387         }
388
389         // $row['condition']
390         $condition_text = '---';
391         if (isset(WrReport::$wrConditions[$row['condition']])) $condition_text = WrReport::$wrConditions[$row['condition']];
392         $td = $tr->appendElement('td');
393         if ($row['delete_date']) $td->appendElement('em')->appendText(wfMessage('wrreport-deletereport-deleted')->text());
394         else $td->appendText($condition_text);
395
396         // $row['description']
397         $td = $tr->appendElement('td', array('class' => 'wrreportdescription'));
398         if ($row['delete_date']) $td->appendElement('em')->appendText(wfMessage('wrreport-deletereport-deleted')->text());
399         else {
400                 // for registered users, use wikitext formatting
401                 if (is_null($row['author_userid'])) $td->appendText($row['description']);
402                 else {
403                         $html = $parser->recursiveTagParse($row['description']);
404                         $td->appendCDATA($html);
405                 }
406         }
407
408         // $row['author_name']
409         $td = $tr->appendElement('td');
410         if ($row['delete_date']) $td->appendElement('em')->appendText(wfMessage('wrreport-deletereport-deleted')->text());
411         else {
412                 if (!is_null($row['author_userid'])) {
413                         // find user's email ($user->getEmail())
414                         $user = User::newFromId($row['author_userid']);
415
416                         // create avatar (using the Services_Libravatar library to get avatar URL)
417                         $sla = new WrServicesLibravatar();
418                         $url = $sla->getUrl($user->getEmail());
419
420                         // create img tag for the avatar
421                         $td->appendElement('img', array('src' => $url, 'alt' => $row['author_name'], 'width' => $sla->getSize(), 'height' => $sla->getSize()));
422                         $td->appendText(' ');
423
424                         // get user page
425                         $title = $user->getUserPage();
426                         if ($title->exists()) {
427                                 $td->appendCDATA(Linker::link($title, $row['author_name']));
428                         } else {
429                                 $td->appendText($row['author_name']);
430                         }
431                         $td->appendText(' ');
432                         
433                         // get number of sledrun reports
434                         $td->appendElement('span', array('class' => 'wrreportcount'))
435                                 ->appendText((string) WrReport::getUserSeldrunReportCount($user->getId()));
436
437                 } else {
438                         $td->appendText($row['author_name']);
439                 }
440         }
441
442         // $row['date_entry']
443         if ($format == WRREPORT_DETAIL) {
444                 $td = $tr->appendElement('td');
445                 $td->appendText(date('d.m. ', strtotime($row['date_entry'])));
446                 $td->appendElement('span', array('class' => 'wrcomment'))->appendText(date('H:i', strtotime($row['date_entry'])));
447         }
448
449         // actions
450         // wiki/Spezial:Bahnberichte?action=deletepreview&reportid=42
451         if ($showActions) {
452                 $td = $tr->appendElement('td');
453                 if (!isset($row['delete_date'])) {
454                         $specialPageName = wfMessage('wrreport')->text(); // 'Bahnberichte'
455                         $title = Title::newFromText($specialPageName, NS_SPECIAL);
456                         $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
457                         $td->appendElement('a', array('href' => $specialPageUrl . '?action=deletepreview&reportid=' . $row['id']))
458                                 ->appendText(wfMessage('wrreport-deletereport-delete')->text() . '...');
459                 }
460         }
461         return $tr;
462 }
463
464
465 /// \brief Renders the report table. Call wrReportGetReports for the $rows parameter.
466 ///
467 /// \param $rows array of associative row arrays
468 /// \param $format row format like WRREPORT_TABLE_SHORT
469 function wrReportTableRender($rows, $format, $showActions, $parser) {
470         $doc = new WrDOMDocument();
471         $table = $doc->appendElement('table', array('class' => 'wrreporttable'));
472         wrReportTableTitleRender($table, $format, $showActions);
473         foreach ($rows as $key => $row) wrReportTableRowRender($table, $row, $format, $showActions, $parser);
474         return $doc->saveHTML($table);
475 }
476
477
478 /// Returns an array with column names
479 function wrReportGetColumnNames() {
480         return array('id', 'page_id', 'page_title', 'date_report', 'time_report', 'date_entry', 'date_invalid', 'condition', 'description', 'author_name', 'author_userid', 'author_username', 'delete_date', 'delete_person_name', 'delete_person_ip', 'delete_person_userid', 'delete_person_username', 'delete_reason_public', 'delete_invisible');
481 }
482
483
484 /// \brief Returns reports as associative array.
485 ///
486 /// Examples:
487 ///   $conditions = array('page_title' => 'Birgitzer Alm', 'date_invalid > now()');
488 ///   $limit = 1; // or NULL for no limit
489 function wrReportGetReports($conditions, $limit=NULL) {
490         $dbr = wfGetDB(DB_SLAVE);
491         $columns = wrReportGetColumnNames();
492         global $wgDBtype;
493         if ($wgDBtype == "mysql") // "condition" is a reserved word in mysql
494                  for ($i = 0; $i != count($columns); ++$i) $columns[$i] = sprintf('`%s`', $columns[$i]);
495         $options = array('ORDER BY' => 'date_report desc, date_entry desc');
496         if (!is_null($limit)) $options['LIMIT'] = $limit;
497         $res = $dbr->select('wrreport', $columns, $conditions, 'wrReportGetReports', $options);
498         $result = array();
499         while ($row = $dbr->fetchRow($res)) $result[] = $row;
500         $dbr->freeResult($res);
501         return $result;
502 }
503
504
505 /// \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));
506 ///
507 /// If no condition is present, array(NULL, NULL) is returned
508 function wrReportConditionRender($page_title) {
509         $dbr = wfGetDB(DB_SLAVE);
510         $cond = 'condition';
511         global $wgDBtype;
512         // 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;
513         if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
514         $res = $dbr->select(
515                 'wrreport',
516                 array('wrreport.id as report_id', $cond, 'date_report'),
517                 array('page_title' => $page_title, "$cond is not null", 'date_invalid > now()', 'delete_date is null'),
518                 'wrReportConditionRender',
519                 array('ORDER BY' => 'date_report desc, date_entry desc', 'LIMIT' => '1')
520         );
521         if ($res->numRows() <= 0) {
522                 $dbr->freeResult($res);
523                 return array(NULL, NULL);
524         }
525         $row = $dbr->fetchObject($res);
526         $date = $row->date_report;
527         if ($date) $date = strtotime($date);
528         $dbr->freeResult($res);
529         return array($row->condition, $date);
530 }
531
532
533 /// \brief Returns true if the user is allowed to delete reports (in general)
534 function wrReportUserMayDelete() {
535         global $wgUser;
536         global $wgWrReportDeleteMode;
537         return $wgWrReportDeleteMode == 'allow' || ($wgWrReportDeleteMode == 'loggedin' && $wgUser->isLoggedIn());
538 }
539
540
541
542 // tag extension hooks
543 // -------------------
544
545 class WrReport {
546         // Conditions: array(1 => 'Sehr gut', 2 => 'Gut', 3 => 'Mittelmäßig', 4 => 'Schlecht', 5 => 'Geht nicht');
547         public static $wrConditions;
548
549
550         public static function initWrConditions() {
551                 WrReport::$wrConditions = array();
552                 for ($i = 1; $i != 6; ++$i) WrReport::$wrConditions[$i] = wfMessage('wrreport-condition-' . $i)->text();
553         }
554
555
556         /// Returns the number of sledrun reports issued by a user with the given id.
557         public static function getUserSeldrunReportCount($user_id) {
558                 $dbr = wfGetDB(DB_SLAVE);
559                 // select count(*) from wrreport where author_userid = 1 and delete_date is null and `condition` is not null;
560                 $res = $dbr->select('wrreport', 'count(*)', array('author_userid' => $user_id, 'delete_date' => null, '`condition` is not null'));
561                 $row = $res->fetchRow();
562                 $count = $row[0];
563                 $dbr->freeResult($res);
564                 return $count;
565         }
566
567
568         // Parser Hook Functions
569         // ---------------------
570
571         /// \brief Is called when the tag <bahnberichtformular/> is encountered.
572         ///
573         /// The current page name is taken.
574         public static function bahnberichtformularParserHook($input, $args, $parser) {
575                 // Username
576                 global $wgUser;
577                 $author_name = NULL;
578                 if ($wgUser->isLoggedIn()) {
579                         $author_name = $wgUser->getRealName();
580                         if (!$author_name) $author_name = $wgUser->getName();
581                 }
582
583                 global $wgWrReportMode;
584                 global $wgWrReportBlackListAll;
585                 global $wgWrReportBlackListStrangers;
586
587                 // is the form allowed to be shown?
588                 $error_key = null;
589                 if ($wgWrReportMode == 'summer') $error_key = 'wrreport-newreport-summer';
590                 elseif ($wgWrReportMode == 'deny') $error_key = 'wrreport-newreport-deny';
591                 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $error_key = 'wrreport-newreport-loggedin';
592                 elseif (in_array($parser->getTitle()->getText(), $wgWrReportBlackListAll)) $error_key = 'wrreport-newreport-blacklist';
593                 elseif (!$wgUser->isLoggedIn() && in_array($parser->getTitle()->getText(), $wgWrReportBlackListStrangers)) $error_key = 'wrreport-newreport-blackliststrangers';
594
595                 // report error
596                 if (!is_null($error_key)) {
597                         $doc = new WrDOMDocument();
598                         $doc->appendElement('p')->appendElement('em')->appendText(wfMessage($error_key)->text());
599                         return $doc->saveHTML($form);
600                 }
601
602                 // Calling "$title = $parser->getTitle(); $title->invalidateCache();" doesn't help here to force regeneration
603                 // However, this would not be the best solution because the page has to be re-rendered only at midnight
604
605                 // In the following line, $author_name was replaced by NULL to prevent a bug, where the wrong author_name
606                 // is shown due to caching (see ticket #35).
607                 return array(wrReportFormRender(TRUE, $parser->getTitle()->getText(), NULL, NULL, NULL, NULL, NULL), 'noparse' => true, 'isHTML' => true);
608         }
609
610
611         /// \brief Is called when the tag <bahnberichte/> is encountered.
612         ///
613         /// The current page name is taken.
614         public static function bahnberichteParserHook($input, $args, $parser) {
615                 $parser->getOutput()->addModules('ext.wrreport'); // getOutput() returns class ParserOutput
616                 $title = $parser->getTitle();
617
618                 global $wgOut; // class OutputPage
619                 global $wgWrReportFeedRoot;
620                 $wgOut->addFeedLink('atom', $wgWrReportFeedRoot . '/berichte/bahn/' . strtolower($title->getPartialURL()));
621
622                 $conditions = array('page_title' => $title->getText(), 'date_invalid > now()');
623                 $rows = wrReportGetReports($conditions);
624                 if (count($rows) == 0) return wfMessage('wrreport-reports-none')->text();
625                 return array(wrReportTableRender($rows, WRREPORT_COMPACT, wrReportUserMayDelete(), $parser), 'noparse' => true, 'isHTML' => true);
626         }
627
628
629         /// Returns the region details of the region specifed in $conditions.
630         /// region_id (as in the database), region name (as in the database), and region border (as WKB).
631         /// conditions is an array that's given to the where clause
632         private static function getRegionDetails($conditions) {
633                 // Example: SELECT name FROM wrregion WHERE page_id = 882;
634                 $dbr = wfGetDB(DB_SLAVE);
635                 $res = $dbr->select('wrregion', array('id', 'name', 'aswkb(border)'), $conditions);
636                 if ($dbr->numRows($res) == 1) {
637                         $row = $dbr->fetchRow($res);
638                         return array($row[0], $row[1], $row[2]); // region_id, region_name, region_border_wkb
639                 }
640                 $dbr->freeResult($res);
641                 return array(null, null, null);
642         }
643
644
645         /// Returns the region details if the specified title is one.
646         /// region_id (as in the database), region name (as in the database), and region border (as WKB).
647         private static function getPageRegion($title) {
648                 $categories = $title->getParentCategories(); // e.g. array('Kategorie:Region' => 'Osttirol')
649                 global $wgContLang;
650                 $key_region = $wgContLang->getNSText(NS_CATEGORY) . ':Region';
651                 if (array_key_exists($key_region, $categories)) {
652                         return WrReport::getRegionDetails(array('page_id' => $title->getArticleID()));
653                 }
654                 return array(null, null, null);
655         }
656
657
658         /// Adds a region feed to the current page
659         private static function addRegionFeedLink($title) {
660                 list($region_id, $region_name, $region_border_wkb) = WrReport::getPageRegion($title);
661                 if (is_null($region_name)) return;
662                 global $wgWrReportFeedRoot;
663                 global $wgOut; // class OutputPage
664                 $wgOut->addFeedLink('atom', $wgWrReportFeedRoot . '/berichte/region/' . strtolower($region_name));
665         }
666
667
668         /// Creates the HTML of the <bahnentabelle>, <bahnenregiontabelle> and <rodelbahntabelle> tags.
669         private static function createBahnentabelle($page_titles) {
670                 $dbr = wfGetDB(DB_SLAVE);
671
672                 // SELECT p.page_id,p.page_title, c.length, c.walkup_time, c.top_elevation, c.bottom_elevation, c.walkup_separate, c.lift, c.night_light, c.public_transport, c.sled_rental, c.information_phone FROM `page` p, wrsledruncache 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
673                 $where_array = array('page.page_id = wrsledruncache.page_id');
674                 if (count($page_titles) > 0) {
675                         $mysql_page_titles = array();
676                         for ($i = 0; $i != count($page_titles); ++$i) $mysql_page_titles[] = "'" . mysql_real_escape_string($page_titles[$i]->getDBKey()) . "'";
677                         $where_array[] = 'page.page_title in (' . implode(', ', $mysql_page_titles) . ')';
678                 } else $where_array[] = 'false';
679                 $res = $dbr->select(array('page', 'wrsledruncache'), array('page.page_id', 'page.page_title', 'page_namespace', 'length', 'walkup_time', 'top_elevation', 'bottom_elevation', 'walkup_possible', 'walkup_separate', 'lift', 'night_light', 'public_transport', 'sled_rental', 'information_phone'), $where_array, 'bahnentabelleParserHook', array('ORDER BY' => 'page.page_title'));
680
681                 global $wgUser;
682                 global $wgWrReportMode; // e.g. 'summer'
683                 global $wgWrReportBlackListAll;
684                 global $wgWrReportBlackListStrangers;
685                 global $wgDBtype;
686
687                 // Determine, whether the user is allowed to make a new report
688                 $userMayReport = ($wgWrReportMode == 'allow' || ($wgWrReportMode == 'loggedin' && $wgUser->isLoggedIn()));
689
690                 // Generate DOM for HTML
691                 $doc = new WrDOMDocument();
692                 $table = $doc->appendElement('table', array('class' => 'wikitable'));
693
694                 // Title
695                 $tr = $table->appendElement('tr');
696                 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_rental.png', 'alt' => wfMessage('wrreport-icon-sledrental')->text(), 'title' => wfMessage('wrreport-icon-sledrental')->text()));
697                 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_light.png', 'alt' => wfMessage('wrreport-icon-nightlight')->text(), 'title' => wfMessage('wrreport-icon-nightlight')->text()));
698                 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
699                 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_walk.png', 'alt' => wfMessage('wrreport-icon-walkupseparate')->text(), 'title' => wfMessage('wrreport-icon-walkupseparate')->text()));
700                 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_bus.png', 'alt' => wfMessage('wrreport-icon-publictransport')->text(), 'title' => wfMessage('wrreport-icon-publictransport')->text()));
701                 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
702                 if ($wgWrReportMode != 'summer') $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
703                 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-information')->text());
704                 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-walkuptime')->text());
705                 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-height')->text());
706                 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-length')->text());
707
708                 // Rows
709                 while ($row = $dbr->fetchObject($res)) {
710                         $title = Title::newFromRow($row);
711                         $tr = $table->appendElement('tr');
712
713                         $td = $tr->appendElement('td');
714                         if ($row->sled_rental) $td->appendElement('img', array('src' => '/vorlagen/s_rental.png', 'alt' => wfMessage('wrreport-icon-sledrental')->text(), 'title' => wfMessage('wrreport-icon-sledrental')->text()));
715
716                         $td = $tr->appendElement('td');
717                         if ($row->night_light) $td->appendElement('img', array('src' => '/vorlagen/s_light.png', 'alt' => wfMessage('wrreport-icon-nightlight')->text(), 'title' => wfMessage('wrreport-icon-nightlight')->text()));
718
719                         $td = $tr->appendElement('td');
720                         if ($row->lift) $td->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
721
722                         $td = $tr->appendElement('td');
723                         if (!is_null($row->walkup_possible)) {
724                                 if ($row->walkup_possible) {
725                                         if ($row->walkup_separate) $td->appendElement('img', array('src' => '/vorlagen/s_walk.png', 'alt' => wfMessage('wrreport-icon-walkupseparate')->text(), 'title' => wfMessage('wrreport-icon-walkupseparate')->text()));
726                                 } else $td->appendElement('img', array('src' => '/vorlagen/s_nowalk.png', 'alt' => wfMessage('wrreport-icon-walkupnotpossible')->text(), 'title' => wfMessage('wrreport-icon-walkupnotpossible')->text()));
727                         }
728
729                         $td = $tr->appendElement('td');
730                         if ($row->public_transport and $row->public_transport != 5) $td->appendElement('img', array('src' => '/vorlagen/s_bus.png', 'alt' => wfMessage('wrreport-icon-publictransport')->text(), 'title' => wfMessage('wrreport-icon-publictransport')->text()));
731
732                         $tr->appendElement('td')->appendElement('a', array('href' => $title->getLocalURL()))->appendText($title->getPrefixedText());
733
734                         if ($wgWrReportMode != 'summer') {
735                                 // Check rights
736                                 $userMayReportThis = $userMayReport;
737                                 if ($userMayReportThis) {
738                                         if (in_array($title->getText(), $wgWrReportBlackListAll)) $userMayReportThis = FALSE;
739                                         if (!$wgUser->isLoggedIn() && in_array($title->getText(), $wgWrReportBlackListStrangers)) $userMayReportThis = FALSE; // Title::getText() uses spaces instead of underscores
740                                 }
741
742                                 // Select condition
743                                 list($report_id, $condition, $date_report) = wrGetSledrunCondition($dbr, $row->page_id);
744                                 if (is_null($report_id)) $date = '';
745                                 else $date = strftime('%d.%m.', $date_report);
746
747                                 $td = $tr->appendElement('td');
748                                 if (isset(WrReport::$wrConditions[$condition])) {
749                                         $td->appendElement('a', array('href' => $title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-reports-sectionname')->text())))->appendText(WrReport::$wrConditions[$condition]);
750                                         $td->appendText(' ');
751                                         $small = $td->appendElement('small');
752                                         $small->appendText($date);
753                                         if ($userMayReportThis) {
754                                                 $small->appendText(' ');
755                                                 $small->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-newreport-sectionname')->text())))->appendText(wfMessage('wrreport-newreport-new')->text());
756                                         }
757                                 } else {
758                                         if ($userMayReportThis)
759                                                 $td->appendElement('small')->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-newreport-sectionname')->text())))->appendText(wfMessage('wrreport-newreport-please')->text());
760                                         else $td->appendText('--');
761                                 }
762                         }
763
764                         $td = $tr->appendElement('td');
765                         $info = $row->information_phone;
766                         if ($info) {
767                                 $info_parts = explode(';', $info);
768                                 $info_parts = explode('(', $info_parts[0], 2);
769                                 if (count($info_parts) == 2 && substr($info_parts[1], -1) == ')') {
770                                         $td->appendText($info_parts[0]);
771                                         $td->appendElement('span', array('class' => 'wrtelinfo'))->appendText(substr($info_parts[1], 0, -1));
772                                 } else $td->appendText($info);
773                         }
774
775                         $tr->appendElement('td')->appendText($row->walkup_time ? $row->walkup_time . ' min' : '');
776
777                         $tr->appendElement('td')->appendText(
778                                 ($row->bottom_elevation ? $row->bottom_elevation  : '') .
779                                 ($row->bottom_elevation && $row->top_elevation ? ' - ' : '') .
780                                 ($row->top_elevation ? $row->top_elevation : '') .
781                                 ($row->bottom_elevation || $row->top_elevation ? ' m' : ''));
782
783                         $tr->appendElement('td')->appendText($row->length ? $row->length . ' m' : '');
784                 }
785                 $dbr->freeResult($res);
786
787                 return $doc->saveHTML();
788         }
789
790
791         /// \brief Is called when the tag <bahnentabelle/> is encountered.
792         ///
793         /// Example:
794         /// <bahnentabelle>
795         /// Birgitzer Alm (vom Adelshof)
796         /// Kemater Alm
797         /// Axamer Lizum
798         /// </bahnentabelle>
799         public static function bahnentabelleParserHook($input, $args, $parser) {
800                 $parser->getOutput()->addModules('ext.wrreport');
801
802                 // Add feed
803                 // Note: As (of MediaWiki 1.19), only one feed can be added and each feed added replaces the previous one, the following is possible without risk of having duplicated feed entries.
804                 WrReport::addRegionFeedLink($parser->getTitle());
805
806                 // Add each page title that has been found
807                 $page_titles = array(); // array of Title objects
808                 foreach (explode("\n", $input) as $page_title) {
809                         $page_title = Title::newFromText(trim($page_title));
810                         if (!$page_title || !$page_title->exists()) continue;
811                         $page_titles[] = $page_title;
812                 }
813
814                 // Create bahnentabelle
815                 $html = WrReport::createBahnentabelle($page_titles);
816                 return array($html, 'noparse' => true, 'isHTML' => true);
817         }
818
819
820         /// \brief Is called when the tag <bahnenregiontabelle/> is encountered.
821         ///
822         /// Example 1:
823         /// <bahnenregiontabelle />
824         ///
825         /// Example 2:
826         /// <bahnenregiontabelle wiki="Innsbruck" /> (refers to region represented by the MediaWiki Title name)
827         /// <bahnenregiontabelle region_id="3" /> (refers to id in the wrregion table)
828         /// <bahnenregiontabelle region_name="Innsbruck" /> (refers to name in the wrregion table)
829         public static function bahnenregiontabelleParserHook($input, $args, $parser) {
830                 $parser->getOutput()->addModules('ext.wrreport');
831
832                 try {
833                         // we accept 0 or 1 parameters
834                         if (count($args) > 1) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-toomanyarguments')->text());
835
836                         if (count($args) == 0) {
837                                 // current page represents a region
838                                 $title = $parser->getTitle(); // default title: current page
839                                 list($region_id, $region_name, $region_border_wkb) = WrReport::getPageRegion($title);
840                                 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-thispagenoregion')->text());
841                         } elseif (isset($args['wiki'])) {
842                                 // other page represents a region
843                                 $title = Title::newFromText($args['wiki']);
844                                 list($region_id, $region_name, $region_border_wkb) = WrReport::getPageRegion($title);
845                                 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-pagenoregion')->text());
846                         } elseif (isset($args['region_id'])) {
847                                 list($region_id, $region_name, $region_border_wkb) = WrReport::getRegionDetails(array('id' => $args['region_id']));
848                                 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-noregionid')->text());
849                         } elseif (isset($args['region_name'])) {
850                                 list($region_id, $region_name, $region_border_wkb) = WrReport::getRegionDetails(array('name' => $args['region_name']));
851                                 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-noregionname')->text());
852                         } else {
853                                 throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-invalidargument', array_keys($args)[0])->text());
854                         }
855
856                         // get titles that are in the region
857                         $page_titles = array();
858                         $dbr = wfGetDB(DB_SLAVE);
859                         // the following line would work if MySQL 5.5 would implement a real geospatial version of CONTAINS.
860                         // $res = $dbr->select('wrsledruncache', 'page_id', array('CONTAINS(GEOMFROMWKB(' . $dbr->addQuotes($region_border_wkb) . '), POINT(position_longitude, position_latitude))', 'NOT under_construction'), __METHOD__, 'page_title');
861                         $res = $dbr->select(array('wrsledruncache', 'wrregioncache'), array('page_id' => 'wrregioncache.page_id'), array('wrregioncache.region_id' => $region_id, 'wrregioncache.page_id=wrsledruncache.page_id', 'NOT under_construction'), __METHOD__, 'page_title');
862                         foreach ($res as $row) {
863                                 $page_titles[] = Title::newFromId($row->page_id);
864                         }
865                         $dbr->freeResult($res);
866                         $html = WrReport::createBahnentabelle($page_titles);
867
868                 } catch (WrReportException $e) {
869                         $doc = new WrDOMDocument();
870                         $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-bahnenregiontabelle-error', $e->getMessage())->text());
871                         $html = $doc->saveHTML($doc->firstChild);
872                 }
873
874                 return array($html, 'noparse' => true, 'isHTML' => true);
875         }
876
877
878         /// \brief Is called when the tag <rodelbahntabelle/> is encountered.
879         ///
880         /// Description: See description of wrreport.php
881         public static function rodelbahntabelleParserHook($input, $args, $parser) {
882                 $parser->getOutput()->addModules('ext.wrreport');
883
884                 // Add feed
885                 // Note: As (of MediaWiki 1.19), only one feed can be added and each feed added replaces the previous one, the following is possible without risk of having duplicated feed entries.
886                 WrReport::addRegionFeedLink($parser->getTitle());
887
888                 $dbr = wfGetDB(DB_SLAVE);
889                 try {
890                         libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
891                         try {
892                                 $xml_input = '<rodelbahntabelle>' . $input . '</rodelbahntabelle>';
893                                 $xml = new SimpleXMLElement($xml_input); // input
894                         } catch (Exception $e) {
895                                 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-xml', $xml_input)->text());
896                         }
897                         $whitespace = (string) $xml; // everything between <rodelbahntabelle> and </rodelbahntabelle> that's not a sub-element
898                         if (strlen($whitespace) > 0 && !ctype_space($whitespace)) // there must not be anythin except sub-elements or whitespace
899                                 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-textbetweenelements', trim($xml))->text());
900
901                         // page_ids of sledrun titles that that are going to be returned
902                         $page_ids = array();
903                         foreach ($xml as $entry) { // entry is <rodelbahn>, <region> or <rodelbahnen>
904                                 $entry_page_ids = array(); // page_ids selected (or un-selected) for this entry.
905                                 $tagname = $entry->getName();
906                                 $attributes = array();
907                                 foreach ($entry->attributes() as $key => $value) $attributes[(string) $key] = (string) $value;
908
909                                 // parse operation attribute
910                                 $operation = '+'; // '+' (append) or '-' (subtract)
911                                 if (array_key_exists('operation', $attributes)) {
912                                         $operation = $attributes['operation'];
913                                         if (!in_array($operation, array('+', '-')))
914                                                 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-value', $tagname, 'operation', $operation)->text());
915                                         unset($attributes['operation']);
916                                 }
917
918                                 // parse in_arbeit attribute
919                                 $under_construction = false; // false (only sledruns that are not under construction), true (only sledruns under construction) or null (doen't matter)
920                                 if ($tagname === 'rodelbahn') $under_construction = null; // different default value for tag <rodelbahn>.
921                                 if (array_key_exists('in_arbeit', $attributes)) {
922                                         if ($attributes['in_arbeit'] === 'nein') $under_construction = false;
923                                         elseif ($attributes['in_arbeit'] === 'ja') $under_construction = true;
924                                         elseif ($attributes['in_arbeit'] === '*') $under_construction = null;
925                                         else throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-value', $tagname, 'in_arbeit', $attributes['in_arbeit'])->text());
926                                         unset($attributes['in_arbeit']);
927                                 }
928
929                                 // any attributes left that are not handled yet?
930                                 if (count($attributes) > 0)
931                                         throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-name', $tagname, array_keys($attributes)[0])->text());
932
933                                 // <rodelbahn>
934                                 if ($tagname == 'rodelbahn') {
935                                         $page_title = Title::newFromText(trim($entry));
936                                         if ($page_title && $page_title->exists()) $entry_page_ids[] = $page_title->getArticleID();
937                                 }
938
939                                 // <region> and <rodelbahn>
940                                 elseif ($tagname === 'region' || $tagname === 'rodelbahnen') {
941                                         $tables = array('wrsledruncache');
942                                         $where = array();
943
944                                         // region
945                                         if ($tagname === 'region') {
946                                                 // the following line would work if MySQL 5.5 would implement a real geospatial version of CONTAINS.
947                                                 // $where[] = 'CONTAINS(GEOMFROMWKB(' . $dbr->addQuotes($region_border_wkb) . '), POINT(position_longitude, position_latitude))'
948                                                 $tables[] = 'wrregion';
949                                                 $tables[] = 'wrregioncache';
950                                                 $where[] = 'wrregioncache.region_id=wrregion.id';
951                                                 $where[] = 'wrregioncache.page_id=wrsledruncache.page_id';
952                                                 $where['wrregion.name'] = $entry;
953                                         }
954
955                                         // under contruction
956                                         if ($under_construction === true) $where[] = 'wrsledruncache.under_construction';
957                                         if ($under_construction === false) $where[] = 'not wrsledruncache.under_construction';
958
959                                         // query
960                                         $res = $dbr->select($tables, array('page_id' => 'wrsledruncache.page_id'), $where, __METHOD__, 'page_id');
961                                         foreach ($res as $row) {
962                                                 $entry_page_ids[] = $row->page_id;
963                                         }
964                                         $dbr->freeResult($res);
965                                 }
966
967                                 else throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-element', $tagname)->text());
968
969                                 // merge the entry page_ids with the page_ids
970                                 if ($operation == '+') $page_ids = array_merge($page_ids, $entry_page_ids);
971                                 elseif ($operation == '-') $page_ids = array_diff($page_ids, $entry_page_ids);
972                         }
973
974                         // page_titles that are going to be returned
975                         $page_titles = Title::newFromIDs($page_ids);
976
977                         $html = WrReport::createBahnentabelle($page_titles);
978
979                 } catch (WrReportException $e) {
980                         $doc = new WrDOMDocument();
981                         $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-rodelbahntabelle-error', $e->getMessage())->text());
982                         $html = $doc->saveHTML($doc->firstChild);
983                 }
984
985                 return array($html, 'noparse' => true, 'isHTML' => true);
986         }
987
988
989         /// \brief Is called when the tag <avatar>username</avatar> is encountered.
990         public static function avatarParserHook($input, $args, $parser, $frame) {
991                 $doc = new WrDOMDocument();
992                 $sla = new WrServicesLibravatar();
993
994                 try {
995                         // check user name
996                         if (is_null($input)) throw new WrReportException(wfMessage('wrreport-avatar-nousername')->text());
997                         $username = $parser->recursiveTagParse($input, $frame);
998                         $user = User::newFromName($username);
999                         if ($user === false) throw new WrReportException(wfMessage('wrreport-avatar-invalidusername', $username)->text());
1000                         if ($user->getId() == 0) throw new WrReportException(wfMessage('wrreport-avatar-userunknown', $username)->text());
1001
1002                         // size attribute (optional)
1003                         if (isset($args['size'])) $sla->setSize((int) $parser->recursiveTagParse($args['size'], $frame));
1004
1005                         // alt attribute (optional)
1006                         $alt = wfMessage('wrreport-avatar-of', $username)->text();
1007
1008                         // create avatar (using the Services_Libravatar library to get avatar URL)
1009                         $url = $sla->getUrl($user->getEmail());
1010                         $doc->appendElement('img', array('src' => $url, 'alt' => $username, 'width' => $sla->getSize(), 'height' => $sla->getSize()));
1011
1012                 } catch (WrReportException $e) {
1013                         $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-avatar-error', $e->getMessage())->text());
1014                 }
1015
1016                 // return result (markerType => nowiki prevents wiki formatting of the result)
1017                 $html = $doc->saveHTML($doc->firstChild);
1018                 return array($html, 'markerType' => 'nowiki');
1019         }
1020
1021
1022
1023 }
1024 WrReport::initWrConditions();
1025
1026
1027
1028 // Special page
1029 // ------------
1030
1031 /// Specal Page to show reports
1032 class SpecialWrReport extends SpecialPage {
1033         function __construct() {
1034                 parent::__construct('wrreport');
1035         }
1036
1037
1038         /// \param $par Possibilities:
1039         /// - action == 'view' (default)
1040         /// - action == 'preview': Preview new report
1041         /// - action == 'store': Store new report
1042         /// - action == 'deletepreview': Preview the deleted record
1043         /// - action == 'delete': Delete an existing report
1044         /// - action == 'showerror': Shows the error and exits
1045         /// \param $override_action If not NULL (default), it overrides the action in $par
1046         /// \param $errorMsg UFT-8 encoded error message (in WikiText) to show on top of the page or NULL (default):
1047         function execute($par, $override_action = NULL, $errorMsg = NULL) {
1048                 $request = $this->getRequest();
1049                 $output = $this->getOutput();
1050         
1051                 global $wgParser;
1052
1053                 $output->addModules('ext.wrreport');
1054                 $this->setHeaders();
1055
1056                 // Get request data
1057                 $action = $request->getText('action');
1058                 if (!$action) {
1059                         if ($request->getVal('preview')) $action = 'preview';
1060                         elseif ($request->getVal('store')) $action = 'store';
1061                         elseif ($request->getVal('deletepreview')) $action = 'deletepreview';
1062                         elseif ($request->getVal('delete')) $action = 'delete';
1063                         else $action = 'view';
1064                 }
1065                 if ($override_action) $action = $override_action;
1066
1067                 // Show error message
1068                 if ($errorMsg || $action == 'showerror') {
1069                         $output->addWikiText('<div class="errorbox">' . $errorMsg . "</div>\n");
1070                         if ($action == 'showerror') return;
1071                 }
1072
1073                 // Action view
1074                 if ($action == 'view') {
1075                         global $wgWrReportFeedRoot;
1076                         $output->addFeedLink('atom', $wgWrReportFeedRoot . '/berichte/alle');
1077                         $conditions = array('date_invalid > now()');
1078                         $rows = wrReportGetReports($conditions);
1079                         if (count($rows) == 0) $output->addHTML(wfMessage('wrreport-reports-none')->text());
1080                         else {
1081                                 $output->addWikiText(''); // this is necessary because otherwise $wgParser is not properly initialized but $wgParser is needed in the next line
1082                                 $output->addHTML(wrReportTableRender($rows, WRREPORT_DETAIL, wrReportUserMayDelete(), $wgParser));
1083                         }
1084                 }
1085
1086                 // Action deletepreview or delete
1087                 elseif ($action == 'deletepreview' || $action == 'delete') {
1088                         $reportid = (int) $request->getText('reportid');
1089                         if ($reportid == 0) {
1090                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-noreport')->text());
1091                                 return;
1092                         }
1093                         $rows = wrReportGetReports(array('id' => $reportid));
1094                         if (count($rows) != 1) {
1095                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-invalid')->text());
1096                                 return;
1097                         }
1098                         $row = $rows[0];
1099                         if (!is_null($row['delete_date'])) {
1100                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-alreadydeleted')->text());
1101                                 return;
1102                         }
1103                         $delete_reason_public = $request->getText('delete_reason_public');
1104                         $delete_person_name = $request->getText('delete_person_name');
1105                         $delete_invisible = $request->getText('delete_invisible') ? TRUE : FALSE;
1106                         if ($action == 'delete') {
1107                                 // page
1108                                 $title = Title::newFromId($row['page_id']);
1109
1110                                 // user
1111                                 global $wgUser;
1112                                 $delete_person_userid = $wgUser->getId();
1113                                 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.
1114                                 $delete_person_username = $wgUser->getName();
1115
1116                                 // Check permissions - see also function wrReportUserMayDelete, that does also check permissions but does not return an error message.
1117                                 $errorMsg = NULL;
1118                                 global $wgWrReportDeleteMode;
1119                                 if ($wgWrReportDeleteMode == 'deny') $errorMsg = wfMessage('wrreport-deletereport-deny')->text();
1120                                 elseif ($wgWrReportDeleteMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = wfMessage('wrreport-deletereport-loggedin')->text();
1121                                 elseif (!$delete_person_name || !$delete_reason_public) $errorMsg = wfMessage('wrreport-deletereport-incomplete')->text();
1122                                 if ($errorMsg) {
1123                                         $this->execute($par, 'deletepreview', $errorMsg);
1124                                         return;
1125                                 }
1126
1127                                 // "Delete" (update) entry
1128                                 $dbr = wfGetDB(DB_MASTER);
1129                                 $dbr->update(
1130                                         'wrreport',
1131                                         array(
1132                                                 'delete_date' => date('c'),
1133                                                 'delete_person_name' => $delete_person_name,
1134                                                 'delete_person_ip' => $_SERVER['REMOTE_ADDR'],
1135                                                 'delete_person_userid' => $delete_person_userid,
1136                                                 'delete_person_username' => $delete_person_username,
1137                                                 'delete_reason_public' => $delete_reason_public,
1138                                                 'delete_invisible' => $delete_invisible ? 't' : 'f'
1139                                         ),
1140                                         array('id' => $reportid)
1141                                 );
1142
1143                                 // Purge cache
1144                                 $title->invalidateCache();
1145                                 wrRecacheRegions();
1146
1147                                 // Show success message
1148                                 $output->addWikiText(wfMessage('wrreport-deletereport-success', '[[' . $row['page_title'] . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $row['page_title'] . ']]')->text());
1149                         }
1150                         if ($action == 'deletepreview') {
1151                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-before')->text());
1152                                 $format = WRREPORT_COMPACT_PAGE;
1153                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1154                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-after')->text());
1155                                 $row['delete_date'] = date('c');
1156                                 $row['delete_reason_public'] = $delete_reason_public;
1157                                 $row['delete_person_name'] = $delete_person_name;
1158                                 $row['delete_invisible'] = $delete_invisible;
1159                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1160                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-form')->text());
1161                                 $output->addHTML(wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible));
1162                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-bottom')->text());
1163                         }
1164                 }
1165
1166                 // Action preview or store
1167                 elseif ($action == 'preview' || $action == 'store') {
1168                         $page_title = $request->getText('page_title');
1169                         $date_report = $request->getText('date_report');
1170                         $time_report = $request->getText('time_report');
1171                         $condition = $request->getText('condition');
1172                         $description = $request->getText('description');
1173                         $author_name = $request->getText('author_name');
1174
1175                         // time_report
1176                         $time_report = trim($time_report); // strip whitespace
1177                         $matches = array();
1178                         $hour = NULL;
1179                         $minute = NULL;
1180                         if (preg_match('/^[0-2]?[0-9]$/', $time_report)) {
1181                                 // $time_report has 1 or 2 digits, e.g. 'h', or 'hh'.
1182                                 $hour = intval($time_report);
1183                                 $minute = 0;
1184                         } elseif (preg_match('/^([0-2]?[0-9]):?([0-9]{2})$/', $time_report, $matches)) {
1185                                 // $time_report has 3 or 4 digits, e.g. 'hmm' or 'hhmm' or 'h:mm' or 'hh:mm'.
1186                                 $hour = intval($matches[1]);
1187                                 $minute = intval($matches[2]);
1188                         }
1189                         if (!is_null($hour) && $hour >= 0 && $hour < 24 && $minute >= 0 && $minute < 60) $time_report = sprintf('%02d:%02d', $hour, $minute);
1190                         else $time_report = NULL;
1191
1192                         // condition
1193                         $condition = (int) $condition; // force to be nummeric. -1 ... "keine Bewertung", 0 ... "Bitte eingeben", 1 to 5 ... "Sehr gut" to "Geht nicht"
1194                         if ($condition < -1 or $condition > 5) $condition = 0; // invalid condition: Tread like 0.
1195                         $condition_sql = NULL;
1196                         if ($condition >= 1 and $condition <= 5) $condition_sql = $condition;
1197
1198                         // author_name
1199                         $author_name = trim($author_name);
1200
1201                         // page_id
1202                         $title = Title::newFromText($page_title);
1203                         $page_id = $title->getArticleID();
1204                         if ($page_id == 0) $page_id = NULL;
1205
1206                         // user_id
1207                         global $wgUser;
1208                         $author_userid = $wgUser->getId();
1209                         if ($author_userid == 0) $author_userid = NULL; // to store a NULL value in the database if no user is logged in instead of 0.
1210                         $author_username = $wgUser->getName();
1211
1212                         if ($action == 'store') {
1213                                 // check conditions/permissions
1214                                 $errorMsg = NULL;
1215                                 global $wgWrReportMode;
1216                                 global $wgWrReportBlackListAll;
1217                                 global $wgWrReportBlackListStrangers;
1218                                 if ($wgWrReportMode == 'summer') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-summer')->text());
1219                                 elseif ($wgWrReportMode == 'deny') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-deny')->text());
1220                                 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-loggedin')->text());
1221                                 elseif (!$page_id) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-pagenotfound')->text());
1222                                 elseif (in_array($page_title, $wgWrReportBlackListAll)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blacklist')->text());
1223                                 elseif (!$wgUser->isLoggedIn() && in_array($page_title, $wgWrReportBlackListStrangers)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blackliststrangers')->text());
1224                                 elseif ($condition == 0) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-choosecondition')->text());
1225                                 elseif (!$wgUser->isLoggedIn()) {
1226                                         if (!$description) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterdescription')->text());
1227                                         elseif (!(stripos($description, 'http') === FALSE)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-nohttp')->text());
1228                                         elseif (!$author_name) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterauthor')->text());
1229                                 }
1230
1231                                 // check author name
1232                                 if (!$errorMsg) {
1233                                         $author_name_id = $wgUser->idFromName(strtolower($author_name));
1234                                         if ($wgUser->isLoggedIn()) {
1235                                                 if ($author_name_id != 0 && $author_name_id != $wgUser->getId())
1236                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorused')->text());
1237                                         } else {
1238                                                 if ($author_name_id != 0)
1239                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorlogin')->text());
1240                                         }
1241                                 }
1242
1243                                 // Chech whether identical reports are present
1244                                 if (!$errorMsg) {
1245                                         $dbr = wfGetDB(DB_SLAVE);
1246                                         $cond = 'condition';
1247                                         global $wgDBtype;
1248                                         if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
1249                                         $sqlConditions = array('page_id' => $page_id, 'date_report' => $date_report, 'time_report' => $time_report, $cond => $condition_sql, 'description' => $description, 'author_name' => $author_name);
1250                                         $res = $dbr->select('wrreport', 'id', $sqlConditions);
1251                                         if ($res->numRows() == 1) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-alreadysaved')->text());
1252                                         $dbr->freeResult($res);
1253                                 }
1254
1255                                 // Show error if any
1256                                 if ($errorMsg) {
1257                                         $this->execute($par, 'preview', $errorMsg);
1258                                         return;
1259                                 }
1260
1261                                 // Save entry
1262                                 $dbr = wfGetDB(DB_MASTER);
1263                                 $dbr->insert(
1264                                         'wrreport',
1265                                         array(
1266                                                 'page_id' => $page_id,
1267                                                 'page_title' => $page_title,
1268                                                 'date_report' => $date_report,
1269                                                 'time_report' => $time_report,
1270                                                 'date_entry' => date('c'),
1271                                                 'date_invalid' => date('c', strtotime('+9 days')),
1272                                                 $cond => $condition_sql,
1273                                                 'description' => $description,
1274                                                 'author_name' => $author_name,
1275                                                 'author_ip' => $_SERVER['REMOTE_ADDR'],
1276                                                 'author_userid' => $author_userid,
1277                                                 'author_username' => $author_username
1278                                                 // 'delete_*' => // use database defaults (NULL)
1279                                         )
1280                                 );
1281
1282                                 // Purge cache
1283                                 $title->invalidateCache();
1284                                 wrRecacheRegions();
1285                                 wrUpdateWrReportCacheTable($page_id);
1286
1287                                 // Show success message
1288                                 $output->addWikiText(wfMessage('wrreport-newreport-success', '[[' . $page_title . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $page_title . ']]')->text());
1289                                 // We could redirect to result with the following line but we don't want to.
1290                                 // $output->redirect($title->getFullURL() . '#' . wfMessage('wrreport-reports-sectionname')->text());
1291                         }
1292                         if ($action == 'preview') {
1293                                 $output->addWikiText(wfMessage('wrreport-newreport-preview-top')->text());
1294                                 $format = WRREPORT_COMPACT_PAGE;
1295                                 $row = array_fill_keys(wrReportGetColumnNames(), NULL);
1296                                 $row['page_id'] = $page_id;
1297                                 $row['page_title'] = $page_title;
1298                                 $row['date_report'] = $date_report;
1299                                 $row['time_report'] = $time_report;
1300                                 $row['condition'] = $condition_sql;
1301                                 $row['description'] = $description;
1302                                 $row['author_name'] = $author_name;
1303                                 $row['author_userid'] = $author_userid;
1304                                 $row['author_username'] = $author_username;
1305
1306                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1307                                 $output->addWikiText(wfMessage('wrreport-newreport-preview-middle')->text());
1308                                 $output->addHTML(wrReportFormRender(FALSE, $page_title, $date_report, $time_report, $condition, $description, $author_name));
1309                                 $output->addWikiText(wfMessage('wrreport-newreport-preview-bottom')->text());
1310                                 if ($author_userid)
1311                                         $output->addWikiText(wfMessage('wrreport-newreport-preview-bottom-loggedin')->text());
1312                                 else
1313                                         $output->addWikiText(wfMessage('wrreport-newreport-preview-bottom-anonymous')->text());
1314                         }
1315
1316                 }
1317
1318                 else die('Wrong action');
1319         }
1320 }
1321
1322
1323 ?>