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