Renamed wrreport.body.php to wrreport_body.php.
[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'));
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', 'class' => 'fullwidth', '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', 'class' => 'fullwidth', 'maxlength' => '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                         $p = $doc->appendElement('p')->appendElement('em')->appendText(wfMessage($error_key)->text());
599                         return $doc->saveHTML($p);
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), 'markerType' => 'nowiki');
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), 'markerType' => 'nowiki');
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_ids = array();
676                         foreach ($page_titles as $page_title) $mysql_page_ids[] = $page_title->getArticleID();
677                         $where_array[] = 'page.page_id in (' . implode(', ', $mysql_page_ids) . ')';
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', 'information_web'), $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_phone = $row->information_phone;
766                         if ($info_phone) {
767                                 $info_parts = explode(';', $info_phone);
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_phone);
773                         }
774                         $info_web = $row->information_web;
775                         if ($info_web === 'Nein') $info_web = null;
776                         if ($info_phone && $info_web) $td->appendText('; ');
777                         if ($info_web) {
778                                 $td->appendElement('a', array('href' => $info_web))->appendText('web');
779                         }
780
781
782                         $tr->appendElement('td')->appendText($row->walkup_time ? $row->walkup_time . ' min' : '');
783
784                         $tr->appendElement('td')->appendText(
785                                 ($row->bottom_elevation ? $row->bottom_elevation  : '') .
786                                 ($row->bottom_elevation && $row->top_elevation ? ' - ' : '') .
787                                 ($row->top_elevation ? $row->top_elevation : '') .
788                                 ($row->bottom_elevation || $row->top_elevation ? ' m' : ''));
789
790                         $tr->appendElement('td')->appendText($row->length ? $row->length . ' m' : '');
791                 }
792                 $dbr->freeResult($res);
793
794                 return $doc->saveHTML();
795         }
796
797
798         /// \brief Is called when the tag <bahnentabelle/> is encountered.
799         ///
800         /// Example:
801         /// <bahnentabelle>
802         /// Birgitzer Alm (vom Adelshof)
803         /// Kemater Alm
804         /// Axamer Lizum
805         /// </bahnentabelle>
806         public static function bahnentabelleParserHook($input, $args, $parser) {
807                 $parser->getOutput()->addModules('ext.wrreport');
808
809                 // Add feed
810                 // 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.
811                 WrReport::addRegionFeedLink($parser->getTitle());
812
813                 // Add each page title that has been found
814                 $page_titles = array(); // array of Title objects
815                 foreach (explode("\n", $input) as $page_title) {
816                         $page_title = Title::newFromText(trim($page_title));
817                         if (!$page_title || !$page_title->exists()) continue;
818                         $page_titles[] = $page_title;
819                 }
820
821                 // Create bahnentabelle
822                 $html = WrReport::createBahnentabelle($page_titles);
823                 return array($html, 'markerType' => 'nowiki');
824         }
825
826
827         /// \brief Is called when the tag <bahnenregiontabelle/> is encountered.
828         ///
829         /// Example 1:
830         /// <bahnenregiontabelle />
831         ///
832         /// Example 2:
833         /// <bahnenregiontabelle wiki="Innsbruck" /> (refers to region represented by the MediaWiki Title name)
834         /// <bahnenregiontabelle region_id="3" /> (refers to id in the wrregion table)
835         /// <bahnenregiontabelle region_name="Innsbruck" /> (refers to name in the wrregion table)
836         public static function bahnenregiontabelleParserHook($input, $args, $parser) {
837                 $parser->getOutput()->addModules('ext.wrreport');
838
839                 try {
840                         // we accept 0 or 1 parameters
841                         if (count($args) > 1) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-toomanyarguments')->text());
842
843                         if (count($args) == 0) {
844                                 // current page represents a region
845                                 $title = $parser->getTitle(); // default title: current page
846                                 list($region_id, $region_name, $region_border_wkb) = WrReport::getPageRegion($title);
847                                 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-thispagenoregion')->text());
848                         } elseif (isset($args['wiki'])) {
849                                 // other page represents a region
850                                 $title = Title::newFromText($args['wiki']);
851                                 list($region_id, $region_name, $region_border_wkb) = WrReport::getPageRegion($title);
852                                 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-pagenoregion')->text());
853                         } elseif (isset($args['region_id'])) {
854                                 list($region_id, $region_name, $region_border_wkb) = WrReport::getRegionDetails(array('id' => $args['region_id']));
855                                 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-noregionid')->text());
856                         } elseif (isset($args['region_name'])) {
857                                 list($region_id, $region_name, $region_border_wkb) = WrReport::getRegionDetails(array('name' => $args['region_name']));
858                                 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-noregionname')->text());
859                         } else {
860                                 throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-invalidargument', array_keys($args)[0])->text());
861                         }
862
863                         // get titles that are in the region
864                         $page_titles = array();
865                         $dbr = wfGetDB(DB_SLAVE);
866                         // the following line would work if MySQL 5.5 would implement a real geospatial version of CONTAINS.
867                         // $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');
868                         $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');
869                         foreach ($res as $row) {
870                                 $page_titles[] = Title::newFromId($row->page_id);
871                         }
872                         $dbr->freeResult($res);
873                         $html = WrReport::createBahnentabelle($page_titles);
874
875                 } catch (WrReportException $e) {
876                         $doc = new WrDOMDocument();
877                         $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-bahnenregiontabelle-error', $e->getMessage())->text());
878                         $html = $doc->saveHTML($doc->firstChild);
879                 }
880
881                 return array($html, 'markerType' => 'nowiki');
882         }
883
884
885         /// \brief Is called when the tag <rodelbahntabelle/> is encountered.
886         ///
887         /// Description: See description of wrreport.php
888         public static function rodelbahntabelleParserHook($input, $args, $parser) {
889                 $parser->getOutput()->addModules('ext.wrreport');
890
891                 // Add feed
892                 // 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.
893                 WrReport::addRegionFeedLink($parser->getTitle());
894
895                 $dbr = wfGetDB(DB_SLAVE);
896                 try {
897                         libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
898                         try {
899                                 $xml_input = '<rodelbahntabelle>' . $input . '</rodelbahntabelle>';
900                                 $xml = new SimpleXMLElement($xml_input); // input
901                         } catch (Exception $e) {
902                                 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-xml', $xml_input)->text());
903                         }
904                         $whitespace = (string) $xml; // everything between <rodelbahntabelle> and </rodelbahntabelle> that's not a sub-element
905                         if (strlen($whitespace) > 0 && !ctype_space($whitespace)) // there must not be anythin except sub-elements or whitespace
906                                 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-textbetweenelements', trim($xml))->text());
907
908                         // page_ids of sledrun titles that that are going to be returned
909                         $page_ids = array();
910                         foreach ($xml as $entry) { // entry is <rodelbahn>, <region> or <rodelbahnen>
911                                 $entry_page_ids = array(); // page_ids selected (or un-selected) for this entry.
912                                 $tagname = $entry->getName();
913                                 $attributes = array();
914                                 foreach ($entry->attributes() as $key => $value) $attributes[(string) $key] = (string) $value;
915
916                                 // is the tagname valid?
917                                 if (!in_array($tagname, array('rodelbahn', 'rodelbahnen', 'region')))
918                                         throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-element', $tagname)->text());
919
920                                 // parse operation attribute
921                                 $operation = '+'; // '+' (append) or '-' (subtract)
922                                 if (array_key_exists('operation', $attributes)) {
923                                         $operation = $attributes['operation'];
924                                         if (!in_array($operation, array('+', '-')))
925                                                 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-value', $tagname, 'operation', $operation)->text());
926                                         unset($attributes['operation']);
927                                 }
928
929                                 // parse in_arbeit attribute
930                                 $under_construction = false; // false (only sledruns that are not under construction), true (only sledruns under construction) or null (doen't matter)
931                                 if ($tagname === 'rodelbahn') $under_construction = null; // different default value for tag <rodelbahn>.
932                                 if (array_key_exists('in_arbeit', $attributes)) {
933                                         if ($attributes['in_arbeit'] === 'nein') $under_construction = false;
934                                         elseif ($attributes['in_arbeit'] === 'ja') $under_construction = true;
935                                         elseif ($attributes['in_arbeit'] === '*') $under_construction = null;
936                                         else throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-value', $tagname, 'in_arbeit', $attributes['in_arbeit'])->text());
937                                         unset($attributes['in_arbeit']);
938                                 }
939
940                                 // any attributes left that are not handled yet?
941                                 if (count($attributes) > 0)
942                                         throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-name', $tagname, array_keys($attributes)[0])->text());
943
944
945                                 // build SQL query
946                                 $tables = array('wrsledruncache');
947                                 $where = array();
948
949                                 // <region>
950                                 if ($tagname === 'region') {
951                                         // the following line would work if MySQL 5.5 would implement a real geospatial version of CONTAINS.
952                                         // $where[] = 'CONTAINS(GEOMFROMWKB(' . $dbr->addQuotes($region_border_wkb) . '), POINT(position_longitude, position_latitude))'
953                                         $tables[] = 'wrregion';
954                                         $tables[] = 'wrregioncache';
955                                         $where[] = 'wrregioncache.region_id=wrregion.id';
956                                         $where[] = 'wrregioncache.page_id=wrsledruncache.page_id';
957                                         $where['wrregion.name'] = $entry;
958                                 }
959
960                                 // <rodelbahn>
961                                 if ($tagname == 'rodelbahn') {
962                                         $page_title = Title::newFromText(trim($entry));
963                                         $where['page_title'] = $page_title->getDBkey();
964                                 }
965
966                                 // under contruction
967                                 if ($under_construction === true) $where[] = 'wrsledruncache.under_construction';
968                                 if ($under_construction === false) $where[] = 'not wrsledruncache.under_construction';
969
970                                 // query
971                                 $res = $dbr->select($tables, array('page_id' => 'wrsledruncache.page_id'), $where, __METHOD__, 'page_id');
972                                 foreach ($res as $row) {
973                                         $entry_page_ids[] = $row->page_id;
974                                 }
975                                 $dbr->freeResult($res);
976
977
978                                 // merge the entry page_ids with the page_ids
979                                 if ($operation == '+') $page_ids = array_merge($page_ids, $entry_page_ids);
980                                 elseif ($operation == '-') $page_ids = array_diff($page_ids, $entry_page_ids);
981                         }
982
983                         // page_titles that are going to be returned
984                         $page_titles = Title::newFromIDs($page_ids);
985
986                         $html = WrReport::createBahnentabelle($page_titles);
987
988                 } catch (WrReportException $e) {
989                         $doc = new WrDOMDocument();
990                         $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-rodelbahntabelle-error', $e->getMessage())->text());
991                         $html = $doc->saveHTML($doc->firstChild);
992                 }
993
994                 return array($html, 'markerType' => 'nowiki');
995         }
996
997
998         /// \brief Is called when the tag <avatar>username</avatar> is encountered.
999         public static function avatarParserHook($input, $args, $parser, $frame) {
1000                 $doc = new WrDOMDocument();
1001                 $sla = new WrServicesLibravatar();
1002
1003                 try {
1004                         // check user name
1005                         if (is_null($input)) throw new WrReportException(wfMessage('wrreport-avatar-nousername')->text());
1006                         $username = $parser->recursiveTagParse($input, $frame);
1007                         $user = User::newFromName($username);
1008                         if ($user === false) throw new WrReportException(wfMessage('wrreport-avatar-invalidusername', $username)->text());
1009                         if ($user->getId() == 0) throw new WrReportException(wfMessage('wrreport-avatar-userunknown', $username)->text());
1010
1011                         // size attribute (optional)
1012                         if (isset($args['size'])) $sla->setSize((int) $parser->recursiveTagParse($args['size'], $frame));
1013
1014                         // alt attribute (optional)
1015                         $alt = wfMessage('wrreport-avatar-of', $username)->text();
1016
1017                         // create avatar (using the Services_Libravatar library to get avatar URL)
1018                         $url = $sla->getUrl($user->getEmail());
1019                         $doc->appendElement('img', array('src' => $url, 'alt' => $username, 'width' => $sla->getSize(), 'height' => $sla->getSize()));
1020
1021                 } catch (WrReportException $e) {
1022                         $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-avatar-error', $e->getMessage())->text());
1023                 }
1024
1025                 // return result (markerType => nowiki prevents wiki formatting of the result)
1026                 $html = $doc->saveHTML($doc->firstChild);
1027                 return array($html, 'markerType' => 'nowiki');
1028         }
1029
1030
1031
1032 }
1033 WrReport::initWrConditions();
1034
1035
1036
1037 // Special page
1038 // ------------
1039
1040 /// Specal Page to show reports
1041 class SpecialWrReport extends SpecialPage {
1042         function __construct() {
1043                 parent::__construct('wrreport');
1044         }
1045
1046
1047         /// \param $par Possibilities:
1048         /// - action == 'view' (default)
1049         /// - action == 'preview': Preview new report
1050         /// - action == 'store': Store new report
1051         /// - action == 'deletepreview': Preview the deleted record
1052         /// - action == 'delete': Delete an existing report
1053         /// - action == 'showerror': Shows the error and exits
1054         /// \param $override_action If not NULL (default), it overrides the action in $par
1055         /// \param $errorMsg UFT-8 encoded error message (in WikiText) to show on top of the page or NULL (default):
1056         function execute($par, $override_action = NULL, $errorMsg = NULL) {
1057                 $request = $this->getRequest();
1058                 $output = $this->getOutput();
1059         
1060                 global $wgParser;
1061
1062                 $output->addModules('ext.wrreport');
1063                 $this->setHeaders();
1064
1065                 // Get request data
1066                 $action = $request->getText('action');
1067                 if (!$action) {
1068                         if ($request->getVal('preview')) $action = 'preview';
1069                         elseif ($request->getVal('store')) $action = 'store';
1070                         elseif ($request->getVal('deletepreview')) $action = 'deletepreview';
1071                         elseif ($request->getVal('delete')) $action = 'delete';
1072                         else $action = 'view';
1073                 }
1074                 if ($override_action) $action = $override_action;
1075
1076                 // Show error message
1077                 if ($errorMsg || $action == 'showerror') {
1078                         $output->addWikiText('<div class="errorbox">' . $errorMsg . "</div>\n");
1079                         if ($action == 'showerror') return;
1080                 }
1081
1082                 // Action view
1083                 if ($action == 'view') {
1084                         global $wgWrReportFeedRoot;
1085                         $output->addFeedLink('atom', $wgWrReportFeedRoot . '/berichte/alle');
1086                         $conditions = array('date_invalid > now()');
1087                         $rows = wrReportGetReports($conditions);
1088                         if (count($rows) == 0) $output->addHTML(wfMessage('wrreport-reports-none')->text());
1089                         else {
1090                                 $output->addWikiText(''); // this is necessary because otherwise $wgParser is not properly initialized but $wgParser is needed in the next line
1091                                 $output->addHTML(wrReportTableRender($rows, WRREPORT_DETAIL, wrReportUserMayDelete(), $wgParser));
1092                         }
1093                 }
1094
1095                 // Action deletepreview or delete
1096                 elseif ($action == 'deletepreview' || $action == 'delete') {
1097                         $reportid = (int) $request->getText('reportid');
1098                         if ($reportid == 0) {
1099                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-noreport')->text());
1100                                 return;
1101                         }
1102                         $rows = wrReportGetReports(array('id' => $reportid));
1103                         if (count($rows) != 1) {
1104                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-invalid')->text());
1105                                 return;
1106                         }
1107                         $row = $rows[0];
1108                         if (!is_null($row['delete_date'])) {
1109                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-alreadydeleted')->text());
1110                                 return;
1111                         }
1112                         $delete_reason_public = $request->getText('delete_reason_public');
1113                         $delete_person_name = $request->getText('delete_person_name');
1114                         $delete_invisible = $request->getText('delete_invisible') ? TRUE : FALSE;
1115                         if ($action == 'delete') {
1116                                 // page
1117                                 $title = Title::newFromId($row['page_id']);
1118
1119                                 // user
1120                                 global $wgUser;
1121                                 $delete_person_userid = $wgUser->getId();
1122                                 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.
1123                                 $delete_person_username = $wgUser->getName();
1124
1125                                 // Check permissions - see also function wrReportUserMayDelete, that does also check permissions but does not return an error message.
1126                                 $errorMsg = NULL;
1127                                 global $wgWrReportDeleteMode;
1128                                 if ($wgWrReportDeleteMode == 'deny') $errorMsg = wfMessage('wrreport-deletereport-deny')->text();
1129                                 elseif ($wgWrReportDeleteMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = wfMessage('wrreport-deletereport-loggedin')->text();
1130                                 elseif (!$delete_person_name || !$delete_reason_public) $errorMsg = wfMessage('wrreport-deletereport-incomplete')->text();
1131                                 if ($errorMsg) {
1132                                         $this->execute($par, 'deletepreview', $errorMsg);
1133                                         return;
1134                                 }
1135
1136                                 // "Delete" (update) entry
1137                                 $dbr = wfGetDB(DB_MASTER);
1138                                 $dbr->update(
1139                                         'wrreport',
1140                                         array(
1141                                                 'delete_date' => date('c'),
1142                                                 'delete_person_name' => $delete_person_name,
1143                                                 'delete_person_ip' => $_SERVER['REMOTE_ADDR'],
1144                                                 'delete_person_userid' => $delete_person_userid,
1145                                                 'delete_person_username' => $delete_person_username,
1146                                                 'delete_reason_public' => $delete_reason_public,
1147                                                 'delete_invisible' => $delete_invisible ? 't' : 'f'
1148                                         ),
1149                                         array('id' => $reportid)
1150                                 );
1151
1152                                 // Purge cache
1153                                 $title->invalidateCache();
1154                                 wrRecacheRegions();
1155
1156                                 // Show success message
1157                                 $output->addWikiText(wfMessage('wrreport-deletereport-success', '[[' . $row['page_title'] . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $row['page_title'] . ']]')->text());
1158                         }
1159                         if ($action == 'deletepreview') {
1160                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-before')->text());
1161                                 $format = WRREPORT_COMPACT_PAGE;
1162                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1163                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-after')->text());
1164                                 $row['delete_date'] = date('c');
1165                                 $row['delete_reason_public'] = $delete_reason_public;
1166                                 $row['delete_person_name'] = $delete_person_name;
1167                                 $row['delete_invisible'] = $delete_invisible;
1168                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1169                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-form')->text());
1170                                 $output->addHTML(wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible));
1171                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-bottom')->text());
1172                         }
1173                 }
1174
1175                 // Action preview or store
1176                 elseif ($action == 'preview' || $action == 'store') {
1177                         $page_title = $request->getText('page_title');
1178                         $date_report = $request->getText('date_report');
1179                         $time_report = $request->getText('time_report');
1180                         $condition = $request->getText('condition');
1181                         $description = $request->getText('description');
1182                         $author_name = $request->getText('author_name');
1183
1184                         // time_report
1185                         $time_report = trim($time_report); // strip whitespace
1186                         $matches = array();
1187                         $hour = NULL;
1188                         $minute = NULL;
1189                         if (preg_match('/^[0-2]?[0-9]$/', $time_report)) {
1190                                 // $time_report has 1 or 2 digits, e.g. 'h', or 'hh'.
1191                                 $hour = intval($time_report);
1192                                 $minute = 0;
1193                         } elseif (preg_match('/^([0-2]?[0-9]):?([0-9]{2})$/', $time_report, $matches)) {
1194                                 // $time_report has 3 or 4 digits, e.g. 'hmm' or 'hhmm' or 'h:mm' or 'hh:mm'.
1195                                 $hour = intval($matches[1]);
1196                                 $minute = intval($matches[2]);
1197                         }
1198                         if (!is_null($hour) && $hour >= 0 && $hour < 24 && $minute >= 0 && $minute < 60) $time_report = sprintf('%02d:%02d', $hour, $minute);
1199                         else $time_report = NULL;
1200
1201                         // condition
1202                         $condition = (int) $condition; // force to be nummeric. -1 ... "keine Bewertung", 0 ... "Bitte eingeben", 1 to 5 ... "Sehr gut" to "Geht nicht"
1203                         if ($condition < -1 or $condition > 5) $condition = 0; // invalid condition: Tread like 0.
1204                         $condition_sql = NULL;
1205                         if ($condition >= 1 and $condition <= 5) $condition_sql = $condition;
1206
1207                         // author_name
1208                         $author_name = trim($author_name);
1209
1210                         // page_id
1211                         $title = Title::newFromText($page_title);
1212                         $page_id = $title->getArticleID();
1213                         if ($page_id == 0) $page_id = NULL;
1214
1215                         // user_id
1216                         global $wgUser;
1217                         $author_userid = $wgUser->getId();
1218                         if ($author_userid == 0) $author_userid = NULL; // to store a NULL value in the database if no user is logged in instead of 0.
1219                         $author_username = $wgUser->getName();
1220
1221                         if ($action == 'store') {
1222                                 // check conditions/permissions
1223                                 $errorMsg = NULL;
1224                                 global $wgWrReportMode;
1225                                 global $wgWrReportBlackListAll;
1226                                 global $wgWrReportBlackListStrangers;
1227                                 if ($wgWrReportMode == 'summer') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-summer')->text());
1228                                 elseif ($wgWrReportMode == 'deny') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-deny')->text());
1229                                 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-loggedin')->text());
1230                                 elseif (!$page_id) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-pagenotfound')->text());
1231                                 elseif (in_array($page_title, $wgWrReportBlackListAll)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blacklist')->text());
1232                                 elseif (!$wgUser->isLoggedIn() && in_array($page_title, $wgWrReportBlackListStrangers)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blackliststrangers')->text());
1233                                 elseif ($condition == 0) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-choosecondition')->text());
1234                                 elseif (!$wgUser->isLoggedIn()) {
1235                                         if (!$description) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterdescription')->text());
1236                                         elseif (!(stripos($description, 'http') === FALSE)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-nohttp')->text());
1237                                         elseif (!$author_name) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterauthor')->text());
1238                                 }
1239
1240                                 // check author name
1241                                 if (!$errorMsg) {
1242                                         $author_name_id = $wgUser->idFromName(strtolower($author_name));
1243                                         if ($wgUser->isLoggedIn()) {
1244                                                 if ($author_name_id != 0 && $author_name_id != $wgUser->getId())
1245                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorused')->text());
1246                                         } else {
1247                                                 if ($author_name_id != 0)
1248                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorlogin')->text());
1249                                         }
1250                                 }
1251
1252                                 // Chech whether identical reports are present
1253                                 if (!$errorMsg) {
1254                                         $dbr = wfGetDB(DB_SLAVE);
1255                                         $cond = 'condition';
1256                                         global $wgDBtype;
1257                                         if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
1258                                         $sqlConditions = array('page_id' => $page_id, 'date_report' => $date_report, 'time_report' => $time_report, $cond => $condition_sql, 'description' => $description, 'author_name' => $author_name);
1259                                         $res = $dbr->select('wrreport', 'id', $sqlConditions);
1260                                         if ($res->numRows() == 1) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-alreadysaved')->text());
1261                                         $dbr->freeResult($res);
1262                                 }
1263
1264                                 // Show error if any
1265                                 if ($errorMsg) {
1266                                         $this->execute($par, 'preview', $errorMsg);
1267                                         return;
1268                                 }
1269
1270                                 // Save entry
1271                                 $dbr = wfGetDB(DB_MASTER);
1272                                 $dbr->insert(
1273                                         'wrreport',
1274                                         array(
1275                                                 'page_id' => $page_id,
1276                                                 'page_title' => $page_title,
1277                                                 'date_report' => $date_report,
1278                                                 'time_report' => $time_report,
1279                                                 'date_entry' => date('c'),
1280                                                 'date_invalid' => date('c', strtotime('+9 days')),
1281                                                 $cond => $condition_sql,
1282                                                 'description' => $description,
1283                                                 'author_name' => $author_name,
1284                                                 'author_ip' => $_SERVER['REMOTE_ADDR'],
1285                                                 'author_userid' => $author_userid,
1286                                                 'author_username' => $author_username
1287                                                 // 'delete_*' => // use database defaults (NULL)
1288                                         )
1289                                 );
1290
1291                                 // Purge cache
1292                                 $title->invalidateCache();
1293                                 wrRecacheRegions();
1294                                 wrUpdateWrReportCacheTable($page_id);
1295
1296                                 // Show success message
1297                                 $output->addWikiText(wfMessage('wrreport-newreport-success', '[[' . $page_title . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $page_title . ']]')->text());
1298                                 // We could redirect to result with the following line but we don't want to.
1299                                 // $output->redirect($title->getFullURL() . '#' . wfMessage('wrreport-reports-sectionname')->text());
1300                         }
1301                         if ($action == 'preview') {
1302                                 $output->addWikiText(wfMessage('wrreport-newreport-preview-top')->text());
1303                                 $format = WRREPORT_COMPACT_PAGE;
1304                                 $row = array_fill_keys(wrReportGetColumnNames(), NULL);
1305                                 $row['page_id'] = $page_id;
1306                                 $row['page_title'] = $page_title;
1307                                 $row['date_report'] = $date_report;
1308                                 $row['time_report'] = $time_report;
1309                                 $row['condition'] = $condition_sql;
1310                                 $row['description'] = $description;
1311                                 $row['author_name'] = $author_name;
1312                                 $row['author_userid'] = $author_userid;
1313                                 $row['author_username'] = $author_username;
1314
1315                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1316                                 $output->addWikiText(wfMessage('wrreport-newreport-preview-middle')->text());
1317                                 $output->addHTML(wrReportFormRender(FALSE, $page_title, $date_report, $time_report, $condition, $description, $author_name));
1318                                 $output->addWikiText(wfMessage('wrreport-newreport-preview-bottom')->text());
1319                                 if ($author_userid)
1320                                         $output->addWikiText(wfMessage('wrreport-newreport-preview-bottom-loggedin')->text());
1321                                 else
1322                                         $output->addWikiText(wfMessage('wrreport-newreport-preview-bottom-anonymous')->text());
1323                         }
1324
1325                 }
1326
1327                 else die('Wrong action');
1328         }
1329 }
1330
1331
1332 ?>