Add date in open/closed text.
[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                                                 $msg = wfMessage('wrreport-icon-intermaps-open', $row->last_update)->text();
828                                                 $td->appendElement('img', array('src' => '/vorlagen/s_open.png', 'alt' => $msg, 'title' => $msg));
829                                         } elseif ($row->status == 'closed') {
830                                                 $msg = wfMessage('wrreport-icon-intermaps-closed', $row->last_update)->text();
831                                                 $td->appendElement('img', array('src' => '/vorlagen/s_closed.png', 'alt' => $msg, 'title' => $msg));
832                                         } else {
833                                                 $td->appendText($row->status);
834                                         }
835                                 }
836                         }
837
838                         $tr->appendElement('td')->appendElement('a', array('href' => $title->getLocalURL()))->appendText($title->getPrefixedText());
839
840                         if ($wgWrReportMode != 'summer') {
841                                 // Check rights
842                                 $userMayReportThis = $userMayReport;
843                                 if ($userMayReportThis) {
844                                         if (in_array($title->getText(), $wgWrReportBlackListAll)) $userMayReportThis = FALSE;
845                                         if (!$wgUser->isLoggedIn() && in_array($title->getText(), $wgWrReportBlackListStrangers)) $userMayReportThis = FALSE; // Title::getText() uses spaces instead of underscores
846                                 }
847
848                                 // Select condition
849                                 list($report_id, $condition, $date_report) = wrGetSledrunCondition($dbr, $row->page_id);
850                                 if (is_null($report_id)) $date = '';
851                                 else $date = strftime('%d.%m.', $date_report);
852
853                                 $td = $tr->appendElement('td');
854                                 if (in_array($condition, WrReport::$wrConditions)) {
855                                         $td->appendElement('a', array('href' => $title->getLocalURL() . '#' . Sanitizer::escapeIdForLink(wfMessage('wrreport-reports-sectionname'))))->appendText(WrReport::getWrConditionText($condition));
856                                         $td->appendText(' ');
857                                         $small = $td->appendElement('small');
858                                         $small->appendText($date);
859                                         if ($userMayReportThis) {
860                                                 $small->appendText(' ');
861                                                 $small->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Sanitizer::escapeIdForLink(wfMessage('wrreport-newreport-sectionname'))))->appendText(wfMessage('wrreport-newreport-new')->text());
862                                         }
863                                 } else {
864                                         if ($userMayReportThis)
865                                                 $td->appendElement('small')->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Sanitizer::escapeIdForLink(wfMessage('wrreport-newreport-sectionname'))))->appendText(wfMessage('wrreport-newreport-please')->text());
866                                         else $td->appendText('--');
867                                 }
868                         }
869
870                         $td = $tr->appendElement('td');
871                         $info_phone = $row->information_phone;
872                         if ($info_phone) {
873                                 $info_parts = explode(';', $info_phone);
874                                 $info_parts = explode('(', $info_parts[0], 2);
875                                 if (count($info_parts) == 2 && substr($info_parts[1], -1) == ')') {
876                                         $td->appendText($info_parts[0]);
877                                         $td->appendElement('span', array('class' => 'wrtelinfo'))->appendText(substr($info_parts[1], 0, -1));
878                                 } else $td->appendText($info_phone);
879                         }
880                         $info_web = $row->information_web;
881                         if ($info_web === 'Nein') $info_web = null;
882                         if ($info_phone && $info_web) $td->appendText('; ');
883                         if ($info_web) {
884                                 $td->appendElement('a', array('href' => $info_web))->appendText('web');
885                         }
886
887
888                         $tr->appendElement('td')->appendText($row->walkup_time ? $row->walkup_time . ' min' : '');
889
890                         $tr->appendElement('td')->appendText(
891                                 ($row->bottom_elevation ? $row->bottom_elevation  : '') .
892                                 ($row->bottom_elevation && $row->top_elevation ? ' - ' : '') .
893                                 ($row->top_elevation ? $row->top_elevation : '') .
894                                 ($row->bottom_elevation || $row->top_elevation ? ' m' : ''));
895
896                         $tr->appendElement('td')->appendText($row->length ? $row->length . ' m' : '');
897                 }
898                 $dbr->freeResult($res);
899
900                 return $doc->saveHTML();
901         }
902
903
904         /// \brief Is called when the tag <bahnentabelle/> is encountered.
905         ///
906         /// Example:
907         /// <bahnentabelle>
908         /// Birgitzer Alm (vom Adelshof)
909         /// Kemater Alm
910         /// Axamer Lizum
911         /// </bahnentabelle>
912         public static function bahnentabelleParserHook($input, array $args, Parser $parser, PPFrame $frame) {
913                 $parser->getOutput()->addModules('ext.wrreport');
914
915                 // Add feed
916                 // 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.
917                 WrReport::addRegionFeedLink($parser->getTitle());
918
919                 // Add each page title that has been found
920                 $page_titles = array(); // array of Title objects
921                 foreach (explode("\n", $input) as $page_title) {
922                         $page_title = Title::newFromText(trim($page_title));
923                         if (!$page_title || !$page_title->exists()) continue;
924                         $page_titles[] = $page_title;
925                 }
926
927                 // Create bahnentabelle
928                 $html = WrReport::createBahnentabelle($page_titles);
929                 return array($html, 'markerType' => 'nowiki');
930         }
931
932
933         /// \brief Is called when the tag <bahnenregiontabelle/> is encountered.
934         ///
935         /// Example 1:
936         /// <bahnenregiontabelle />
937         ///
938         /// Example 2:
939         /// <bahnenregiontabelle wiki="Innsbruck" /> (refers to region represented by the MediaWiki Title name)
940         /// <bahnenregiontabelle region_id="3" /> (refers to id in the wrregion table)
941         /// <bahnenregiontabelle region_name="Innsbruck" /> (refers to name in the wrregion table)
942         public static function bahnenregiontabelleParserHook($input, array $args, Parser $parser, PPFrame $frame) {
943                 $parser->getOutput()->addModules('ext.wrreport');
944
945                 try {
946                         // we accept 0 or 1 parameters
947                         if (count($args) > 1) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-toomanyarguments')->text());
948
949                         if (count($args) == 0) {
950                                 // current page represents a region
951                                 $title = $parser->getTitle(); // default title: current page
952                                 list($region_id, $region_name, $region_border_wkb) = WrReport::getPageRegion($title);
953                                 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-thispagenoregion')->text());
954                         } elseif (isset($args['wiki'])) {
955                                 // other page represents a region
956                                 $title = Title::newFromText($args['wiki']);
957                                 list($region_id, $region_name, $region_border_wkb) = WrReport::getPageRegion($title);
958                                 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-pagenoregion')->text());
959                         } elseif (isset($args['region_id'])) {
960                                 list($region_id, $region_name, $region_border_wkb) = WrReport::getRegionDetails(array('id' => $args['region_id']));
961                                 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-noregionid')->text());
962                         } elseif (isset($args['region_name'])) {
963                                 list($region_id, $region_name, $region_border_wkb) = WrReport::getRegionDetails(array('name' => $args['region_name']));
964                                 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-noregionname')->text());
965                         } else {
966                                 throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-invalidargument', array_keys($args)[0])->text());
967                         }
968
969                         // get titles that are in the region
970                         $page_titles = array();
971                         $dbr = wfGetDB(DB_REPLICA);
972                         // the following line would work if MySQL 5.5 would implement a real geospatial version of CONTAINS.
973                         // $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');
974                         $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');
975                         foreach ($res as $row) {
976                                 $page_titles[] = Title::newFromId($row->page_id);
977                         }
978                         $dbr->freeResult($res);
979                         $html = WrReport::createBahnentabelle($page_titles);
980
981                 } catch (WrReportException $e) {
982                         $doc = new WrDOMDocument();
983                         $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-bahnenregiontabelle-error', $e->getMessage())->text());
984                         $html = $doc->saveHTML($doc->firstChild);
985                 }
986
987                 return array($html, 'markerType' => 'nowiki');
988         }
989
990
991         /// \brief Is called when the tag <rodelbahntabelle/> is encountered.
992         ///
993         /// Description: See description of wrreport.php
994         public static function rodelbahntabelleParserHook($input, array $args, Parser $parser, PPFrame $frame) {
995                 $parser->getOutput()->addModules('ext.wrreport');
996
997                 // Add feed
998                 // 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.
999                 WrReport::addRegionFeedLink($parser->getTitle());
1000
1001                 $dbr = wfGetDB(DB_REPLICA);
1002                 try {
1003                         libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
1004                         try {
1005                                 $xml_input = '<rodelbahntabelle>' . $input . '</rodelbahntabelle>';
1006                                 $xml = new SimpleXMLElement($xml_input); // input
1007                         } catch (Exception $e) {
1008                                 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-xml', $xml_input)->text());
1009                         }
1010                         $whitespace = (string) $xml; // everything between <rodelbahntabelle> and </rodelbahntabelle> that's not a sub-element
1011                         if (strlen($whitespace) > 0 && !ctype_space($whitespace)) // there must not be anythin except sub-elements or whitespace
1012                                 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-textbetweenelements', trim($xml))->text());
1013
1014                         // page_ids of sledrun titles that that are going to be returned
1015                         $page_ids = array();
1016                         foreach ($xml as $entry) { // entry is <rodelbahn>, <region> or <rodelbahnen>
1017                                 $entry_page_ids = array(); // page_ids selected (or un-selected) for this entry.
1018                                 $tagname = $entry->getName();
1019                                 $attributes = array();
1020                                 foreach ($entry->attributes() as $key => $value) $attributes[(string) $key] = (string) $value;
1021
1022                                 // is the tagname valid?
1023                                 if (!in_array($tagname, array('rodelbahn', 'rodelbahnen', 'region')))
1024                                         throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-element', $tagname)->text());
1025
1026                                 // parse operation attribute
1027                                 $operation = '+'; // '+' (append) or '-' (subtract)
1028                                 if (array_key_exists('operation', $attributes)) {
1029                                         $operation = $attributes['operation'];
1030                                         if (!in_array($operation, array('+', '-')))
1031                                                 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-value', $tagname, 'operation', $operation)->text());
1032                                         unset($attributes['operation']);
1033                                 }
1034
1035                                 // parse in_arbeit attribute
1036                                 $under_construction = false; // false (only sledruns that are not under construction), true (only sledruns under construction) or null (doen't matter)
1037                                 if ($tagname === 'rodelbahn') $under_construction = null; // different default value for tag <rodelbahn>.
1038                                 if (array_key_exists('in_arbeit', $attributes)) {
1039                                         if ($attributes['in_arbeit'] === 'nein') $under_construction = false;
1040                                         elseif ($attributes['in_arbeit'] === 'ja') $under_construction = true;
1041                                         elseif ($attributes['in_arbeit'] === '*') $under_construction = null;
1042                                         else throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-value', $tagname, 'in_arbeit', $attributes['in_arbeit'])->text());
1043                                         unset($attributes['in_arbeit']);
1044                                 }
1045
1046                                 // any attributes left that are not handled yet?
1047                                 if (count($attributes) > 0)
1048                                         throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-name', $tagname, array_keys($attributes)[0])->text());
1049
1050
1051                                 // build SQL query
1052                                 $tables = array('wrsledruncache');
1053                                 $where = array();
1054
1055                                 // <region>
1056                                 if ($tagname === 'region') {
1057                                         // the following line would work if MySQL 5.5 would implement a real geospatial version of CONTAINS.
1058                                         // $where[] = 'CONTAINS(GEOMFROMWKB(' . $dbr->addQuotes($region_border_wkb) . '), POINT(position_longitude, position_latitude))'
1059                                         $tables[] = 'wrregion';
1060                                         $tables[] = 'wrregioncache';
1061                                         $where[] = 'wrregioncache.region_id=wrregion.id';
1062                                         $where[] = 'wrregioncache.page_id=wrsledruncache.page_id';
1063                                         $where['wrregion.name'] = $entry;
1064                                 }
1065
1066                                 // <rodelbahn>
1067                                 if ($tagname == 'rodelbahn') {
1068                                         $page_title = Title::newFromText(trim($entry));
1069                                         $where['page_title'] = $page_title->getDBkey();
1070                                 }
1071
1072                                 // under contruction
1073                                 if ($under_construction === true) $where[] = 'wrsledruncache.under_construction';
1074                                 if ($under_construction === false) $where[] = 'not wrsledruncache.under_construction';
1075
1076                                 // query
1077                                 $res = $dbr->select($tables, array('page_id' => 'wrsledruncache.page_id'), $where, __METHOD__, 'page_id');
1078                                 foreach ($res as $row) {
1079                                         $entry_page_ids[] = $row->page_id;
1080                                 }
1081                                 $dbr->freeResult($res);
1082
1083
1084                                 // merge the entry page_ids with the page_ids
1085                                 if ($operation == '+') $page_ids = array_merge($page_ids, $entry_page_ids);
1086                                 elseif ($operation == '-') $page_ids = array_diff($page_ids, $entry_page_ids);
1087                         }
1088
1089                         // page_titles that are going to be returned
1090                         $page_titles = Title::newFromIDs($page_ids);
1091
1092                         $html = WrReport::createBahnentabelle($page_titles);
1093
1094                 } catch (WrReportException $e) {
1095                         $doc = new WrDOMDocument();
1096                         $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-rodelbahntabelle-error', $e->getMessage())->text());
1097                         $html = $doc->saveHTML($doc->firstChild);
1098                 }
1099
1100                 return array($html, 'markerType' => 'nowiki');
1101         }
1102
1103
1104         /// \brief Is called when the tag <avatar>username</avatar> is encountered.
1105         public static function avatarParserHook($input, array $args, Parser $parser, PPFrame $frame) {
1106                 $doc = new WrDOMDocument();
1107                 $sla = new WrServicesLibravatar();
1108
1109                 try {
1110                         // check user name
1111                         if (is_null($input)) throw new WrReportException(wfMessage('wrreport-avatar-nousername')->text());
1112                         $username = $parser->recursiveTagParse($input, $frame);
1113                         $user = User::newFromName($username);
1114                         if ($user === false) throw new WrReportException(wfMessage('wrreport-avatar-invalidusername', $username)->text());
1115                         if ($user->getId() == 0) throw new WrReportException(wfMessage('wrreport-avatar-userunknown', $username)->text());
1116
1117                         // size attribute (optional)
1118                         if (isset($args['size'])) $sla->setSize((int) $parser->recursiveTagParse($args['size'], $frame));
1119
1120                         // alt attribute (optional)
1121                         $alt = wfMessage('wrreport-avatar-of', $username)->text();
1122
1123                         // create avatar (using the Services_Libravatar library to get avatar URL)
1124                         $url = $sla->getUrl($user->getEmail());
1125                         $doc->appendElement('img', array('src' => $url, 'alt' => $username, 'width' => $sla->getSize(), 'height' => $sla->getSize()));
1126
1127                 } catch (WrReportException $e) {
1128                         $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-avatar-error', $e->getMessage())->text());
1129                 }
1130
1131                 // return result (markerType => nowiki prevents wiki formatting of the result)
1132                 $html = $doc->saveHTML($doc->firstChild);
1133                 return array($html, 'markerType' => 'nowiki');
1134         }
1135
1136
1137         public static function MobileMenuHook($name, \MediaWiki\Minerva\MenuBuilder &$menu) {
1138                 if ($name === 'discovery') {
1139                         // delete "Random page". As a removeEntry function is missing,
1140                         // a new menu is built here without the random page.
1141                         $new_menu = new \MediaWiki\Minerva\MenuBuilder();
1142                         foreach ($menu->getEntries() as $menuEntryRepresentation) {
1143                                 $new_entry_name = $menuEntryRepresentation['name'];
1144                                 if ($new_entry_name == 'random') continue;
1145                                 $new_entry_components = $menuEntryRepresentation['components'];
1146                                 $new_entry_isjsonly = isset($menuEntryRepresentation['class']) and $menuEntryRepresentation['class'] === 'jsonly';
1147                                 $new_entry = $new_menu->insert($new_entry_name, $new_entry_isjsonly);
1148                                 foreach ($new_entry_components as $new_entry_component) {
1149                                         $label = $new_entry_component['text'];
1150                                         $url = $new_entry_component['href'];
1151                                         $className = $new_entry_component['class'];
1152                                         $new_entry->addComponent($label, $url, $className, $new_entry_components);
1153                                 }
1154                         }
1155                         $menu = $new_menu;
1156
1157                         // add region menu entry
1158                         $icon = MobileUI::iconClass('random', 'before');
1159                         $title = Title::newFromText('Region', NS_CATEGORY);
1160                         $menu->insert('region')->addComponent('Regionen', $title->getLocalURL(), $icon, array('id' => 'regionButton', 'data-event-name' => 'region'));
1161                 }
1162         }
1163
1164 }
1165
1166
1167
1168 // Special page
1169 // ------------
1170
1171 /// Specal Page to show reports
1172 class SpecialWrReport extends SpecialPage {
1173         function __construct() {
1174                 parent::__construct('wrreport');
1175         }
1176
1177
1178         /// \param $par Possibilities:
1179         /// - action == 'view' (default)
1180         /// - action == 'preview': Preview new report
1181         /// - action == 'store': Store new report
1182         /// - action == 'deletepreview': Preview the deleted record
1183         /// - action == 'delete': Delete an existing report
1184         /// - action == 'showerror': Shows the error and exits
1185         /// \param $override_action If not NULL (default), it overrides the action in $par
1186         /// \param $errorMsg UFT-8 encoded error message (in WikiText) to show on top of the page or NULL (default):
1187         function execute($par, $override_action = NULL, $errorMsg = NULL) {
1188                 $request = $this->getRequest();
1189                 $output = $this->getOutput();
1190         
1191                 global $wgParser;
1192                 $output->addWikiText(''); // this is necessary because otherwise $wgParser is not properly initialized
1193
1194                 $output->addModules('ext.wrreport');
1195                 $this->setHeaders();
1196
1197                 // Get request data
1198                 $action = $request->getText('action');
1199                 if (!$action) {
1200                         if ($request->getVal('preview')) $action = 'preview';
1201                         elseif ($request->getVal('store')) $action = 'store';
1202                         elseif ($request->getVal('deletepreview')) $action = 'deletepreview';
1203                         elseif ($request->getVal('delete')) $action = 'delete';
1204                         else $action = 'view';
1205                 }
1206                 if ($override_action) $action = $override_action;
1207
1208                 // Show error message
1209                 if ($errorMsg || $action == 'showerror') {
1210                         $output->addWikiText('<div class="errorbox">' . $errorMsg . "</div>\n");
1211                         if ($action == 'showerror') return;
1212                 }
1213
1214                 // Action view
1215                 if ($action == 'view') {
1216                         global $wgWrReportFeedRoot;
1217                         $output->addFeedLink('atom', $wgWrReportFeedRoot . '/berichte/alle');
1218                         $conditions = array('date_invalid > now()');
1219                         $rows = wrReportGetReports($conditions);
1220                         if (count($rows) == 0) $output->addHTML(wfMessage('wrreport-reports-none')->text());
1221                         else {
1222                                 $output->addHTML(wrReportTableRender($rows, WRREPORT_DETAIL, wrReportUserMayDelete(), $wgParser));
1223                         }
1224                 }
1225
1226                 // Action deletepreview or delete
1227                 elseif ($action == 'deletepreview' || $action == 'delete') {
1228                         $reportid = (int) $request->getText('reportid');
1229                         if ($reportid == 0) {
1230                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-noreport')->text());
1231                                 return;
1232                         }
1233                         $rows = wrReportGetReports(array('id' => $reportid));
1234                         if (count($rows) != 1) {
1235                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-invalid')->text());
1236                                 return;
1237                         }
1238                         $row = $rows[0];
1239                         if (!is_null($row['delete_date'])) {
1240                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-alreadydeleted')->text());
1241                                 return;
1242                         }
1243                         $delete_reason_public = $request->getText('delete_reason_public');
1244                         $delete_person_name = $request->getText('delete_person_name');
1245                         $delete_invisible = $request->getText('delete_invisible') ? TRUE : FALSE;
1246                         if ($action == 'delete') {
1247                                 // page
1248                                 $title = Title::newFromId($row['page_id']);
1249
1250                                 // user
1251                                 global $wgUser;
1252                                 $delete_person_userid = $wgUser->getId();
1253                                 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.
1254                                 $delete_person_username = $wgUser->getName();
1255
1256                                 // Check permissions - see also function wrReportUserMayDelete, that does also check permissions but does not return an error message.
1257                                 $errorMsg = NULL;
1258                                 global $wgWrReportDeleteMode;
1259                                 if ($wgWrReportDeleteMode == 'deny') $errorMsg = wfMessage('wrreport-deletereport-deny')->text();
1260                                 elseif ($wgWrReportDeleteMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = wfMessage('wrreport-deletereport-loggedin')->text();
1261                                 elseif (!$delete_person_name || !$delete_reason_public) $errorMsg = wfMessage('wrreport-deletereport-incomplete')->text();
1262                                 if ($errorMsg) {
1263                                         $this->execute($par, 'deletepreview', $errorMsg);
1264                                         return;
1265                                 }
1266
1267                                 // "Delete" (update) entry
1268                                 $dbr = wfGetDB(DB_MASTER);
1269                                 $dbr->update(
1270                                         'wrreport',
1271                                         array(
1272                                                 'delete_date' => date('c'),
1273                                                 'delete_person_name' => $delete_person_name,
1274                                                 'delete_person_ip' => $_SERVER['REMOTE_ADDR'],
1275                                                 'delete_person_userid' => $delete_person_userid,
1276                                                 'delete_person_username' => $delete_person_username,
1277                                                 'delete_reason_public' => $delete_reason_public,
1278                                                 'delete_invisible' => $delete_invisible ? 't' : 'f'
1279                                         ),
1280                                         array('id' => $reportid)
1281                                 );
1282
1283                                 // Purge cache
1284                                 $title->invalidateCache();
1285                                 wrRecacheRegions();
1286
1287                                 // Show success message
1288                                 $output->addWikiText(wfMessage('wrreport-deletereport-success', '[[' . $row['page_title'] . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $row['page_title'] . ']]')->text());
1289                         }
1290                         if ($action == 'deletepreview') {
1291                                 $output->addWikiMsg('wrreport-deletereport-preview-before');
1292                                 $format = WRREPORT_COMPACT_PAGE;
1293                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1294                                 $output->addWikiMsg('wrreport-deletereport-preview-after');
1295                                 $row['delete_date'] = date('c');
1296                                 $row['delete_reason_public'] = $delete_reason_public;
1297                                 $row['delete_person_name'] = $delete_person_name;
1298                                 $row['delete_invisible'] = $delete_invisible;
1299                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1300                                 $output->addWikiMsg('wrreport-deletereport-preview-form');
1301                                 $output->addHTML(wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible));
1302                                 $output->addWikiMsg('wrreport-deletereport-preview-bottom');
1303                         }
1304                 }
1305
1306                 // Action preview or store
1307                 elseif ($action == 'preview' || $action == 'store') {
1308                         $page_title = $request->getText('page_title');
1309                         $date_report = $request->getText('date_report');
1310                         $time_report = $request->getText('time_report');
1311                         $condition = $request->getText('condition');
1312                         $description = $request->getText('description');
1313                         $author_name = $request->getText('author_name');
1314
1315                         // time_report
1316                         $time_report = trim($time_report); // strip whitespace
1317                         $matches = array();
1318                         $hour = NULL;
1319                         $minute = NULL;
1320                         if (preg_match('/^[0-2]?[0-9]$/', $time_report)) {
1321                                 // $time_report has 1 or 2 digits, e.g. 'h', or 'hh'.
1322                                 $hour = intval($time_report);
1323                                 $minute = 0;
1324                         } elseif (preg_match('/^([0-2]?[0-9]):?([0-9]{2})$/', $time_report, $matches)) {
1325                                 // $time_report has 3 or 4 digits, e.g. 'hmm' or 'hhmm' or 'h:mm' or 'hh:mm'.
1326                                 $hour = intval($matches[1]);
1327                                 $minute = intval($matches[2]);
1328                         }
1329                         if (!is_null($hour) && $hour >= 0 && $hour < 24 && $minute >= 0 && $minute < 60) $time_report = sprintf('%02d:%02d', $hour, $minute);
1330                         else $time_report = NULL;
1331
1332                         // condition
1333                         $condition = (int) $condition; // force to be nummeric. -1 ... "keine Bewertung", 0 ... "Bitte eingeben", 1 to 5 ... "Sehr gut" to "Geht nicht"
1334                         if ($condition < -1 or $condition > 5) $condition = 0; // invalid condition: Tread like 0.
1335                         $condition_sql = NULL;
1336                         if ($condition >= 1 and $condition <= 5) $condition_sql = $condition;
1337
1338                         // author_name
1339                         $author_name = trim($author_name);
1340
1341                         // page_id
1342                         $title = Title::newFromText($page_title);
1343                         $page_id = $title->getArticleID();
1344                         if ($page_id == 0) $page_id = NULL;
1345
1346                         // user_id
1347                         global $wgUser;
1348                         $author_userid = $wgUser->getId();
1349                         if ($author_userid == 0) $author_userid = NULL; // to store a NULL value in the database if no user is logged in instead of 0.
1350                         $author_username = $wgUser->getName();
1351
1352                         if ($action == 'store') {
1353                                 // check conditions/permissions
1354                                 $errorMsg = NULL;
1355                                 global $wgWrReportMode;
1356                                 global $wgWrReportBlackListAll;
1357                                 global $wgWrReportBlackListStrangers;
1358                                 if ($wgWrReportMode == 'summer') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-summer')->text());
1359                                 elseif ($wgWrReportMode == 'deny') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-deny')->text());
1360                                 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-loggedin')->text());
1361                                 elseif (!$page_id) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-pagenotfound')->text());
1362                                 elseif (in_array($page_title, $wgWrReportBlackListAll)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blacklist')->text());
1363                                 elseif (!$wgUser->isLoggedIn() && in_array($page_title, $wgWrReportBlackListStrangers)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blackliststrangers')->text());
1364                                 elseif ($condition == 0) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-choosecondition')->text());
1365                                 elseif (!$wgUser->isLoggedIn()) {
1366                                         if (!$description) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterdescription')->text());
1367                                         elseif (!(stripos($description, 'http') === FALSE)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-nohttp')->text());
1368                                         elseif (!$author_name) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterauthor')->text());
1369                                 }
1370
1371                                 // check author name
1372                                 if (!$errorMsg) {
1373                                         $author_name_id = $wgUser->idFromName(strtolower($author_name));
1374                                         if ($wgUser->isLoggedIn()) {
1375                                                 if ($author_name_id != 0 && $author_name_id != $wgUser->getId())
1376                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorused')->text());
1377                                         } else {
1378                                                 if ($author_name_id != 0)
1379                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorlogin')->text());
1380                                         }
1381                                 }
1382
1383                                 // Chech whether identical reports are present
1384                                 if (!$errorMsg) {
1385                                         $dbr = wfGetDB(DB_REPLICA);
1386                                         $cond = 'condition';
1387                                         global $wgDBtype;
1388                                         if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
1389                                         $sqlConditions = array('page_id' => $page_id, 'date_report' => $date_report, 'time_report' => $time_report, $cond => $condition_sql, 'description' => $description, 'author_name' => $author_name);
1390                                         $res = $dbr->select('wrreport', 'id', $sqlConditions);
1391                                         if ($res->numRows() == 1) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-alreadysaved')->text());
1392                                         $dbr->freeResult($res);
1393                                 }
1394
1395                                 // Show error if any
1396                                 if ($errorMsg) {
1397                                         $this->execute($par, 'preview', $errorMsg);
1398                                         return;
1399                                 }
1400
1401                                 // Save entry
1402                                 $dbr = wfGetDB(DB_MASTER);
1403                                 $dbr->insert(
1404                                         'wrreport',
1405                                         array(
1406                                                 'page_id' => $page_id,
1407                                                 'page_title' => $page_title,
1408                                                 'date_report' => $date_report,
1409                                                 'time_report' => $time_report,
1410                                                 'date_entry' => date('c'),
1411                                                 'date_invalid' => date('c', strtotime('+9 days')),
1412                                                 $cond => $condition_sql,
1413                                                 'description' => $description,
1414                                                 'author_name' => $author_name,
1415                                                 'author_ip' => $_SERVER['REMOTE_ADDR'],
1416                                                 'author_userid' => $author_userid,
1417                                                 'author_username' => $author_username
1418                                                 // 'delete_*' => // use database defaults (NULL)
1419                                         )
1420                                 );
1421
1422                                 // Purge cache
1423                                 $title->invalidateCache();
1424                                 wrRecacheRegions();
1425                                 wrUpdateWrReportCacheTable($page_id);
1426
1427                                 // Show success message
1428                                 $output->addWikiText(wfMessage('wrreport-newreport-success', '[[' . $page_title . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $page_title . ']]')->text());
1429                                 // We could redirect to result with the following line but we don't want to.
1430                                 // $output->redirect($title->getFullURL() . '#' . wfMessage('wrreport-reports-sectionname')->text());
1431                         }
1432                         if ($action == 'preview') {
1433                                 $output->addWikiMsg('wrreport-newreport-preview-top');
1434                                 $format = WRREPORT_COMPACT_PAGE;
1435                                 $row = array_fill_keys(wrReportGetColumnNames(), NULL);
1436                                 $row['page_id'] = $page_id;
1437                                 $row['page_title'] = $page_title;
1438                                 $row['date_report'] = $date_report;
1439                                 $row['time_report'] = $time_report;
1440                                 $row['condition'] = $condition_sql;
1441                                 $row['description'] = $description;
1442                                 $row['author_name'] = $author_name;
1443                                 $row['author_userid'] = $author_userid;
1444                                 $row['author_username'] = $author_username;
1445
1446                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1447                                 $output->addWikiMsg('wrreport-newreport-preview-middle');
1448                                 $output->addHTML(wrReportFormRender(FALSE, $page_title, $date_report, $time_report, $condition, $description, $author_name));
1449                                 $output->addWikiMsg('wrreport-newreport-preview-bottom');
1450                                 if ($wgUser->isLoggedIn())
1451                                         $output->addWikiMsg('wrreport-newreport-preview-bottom-loggedin');
1452                                 else
1453                                         $output->addWikiMsg('wrreport-newreport-preview-bottom-anonymous');
1454                         }
1455
1456                 }
1457
1458                 else die('Wrong action');
1459         }
1460 }
1461
1462
1463 ?>