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