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