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