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