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