Completed some encoding todo's.
[philipp/winterrodeln/mediawiki_extensions/wrreport.git] / wrreport.body.php
1 <?php
2 // File encoding: utf-8
3 // Classes for the wrreport extension.
4
5
6 // Constants
7 // ---------
8
9 // Constants for wrReportTableRender
10 define('WRREPORT_COMPACT_PAGE', 1); ///< includes the page name
11 define('WRREPORT_COMPACT', 2);      ///< shown on a single page
12 define('WRREPORT_DETAIL', 3);       ///< more columns
13
14
15
16 // DOM helper classes
17 // ------------------
18
19 class WrDOMDocument extends DOMDocument {
20         function __construct() {
21                 parent::__construct('1.0', 'utf-8');
22                 $this->registerNodeClass('DOMElement', 'WrDOMElement');
23         }
24
25         /// Creates and adds the element with the given tag name and returns it.
26         /// Additionally, it calls setAttribute($key, $value) for every entry
27         /// in $attributes.
28         function appendElement($tagName, $attributes=array()) {
29                 $child = $this->appendChild($this->createElement($tagName));
30                 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
31                 return $child;
32         }
33
34 }
35
36
37 class WrDOMElement extends DOMElement {
38
39         /// Creates and adds the element with the given tag name and returns it
40         /// Additionally, it calls setAttribute($key, $value) for every entry
41         /// in $attributes.
42         function appendElement($tagName, $attributes=array()) {
43                 $child = $this->appendChild($this->ownerDocument->createElement($tagName));
44                 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
45                 return $child;
46         }
47
48         /// Adds any UTF-8 string as content of the element - it will be escaped.
49         function appendText($text) {
50                 return $this->appendChild($this->ownerDocument->createTextNode($text));
51         }
52 }
53
54
55
56 // Tool functions
57 // --------------
58
59 /// Forces a regeneration of region overview pages ('Tirol', 'Vorarlberg', ...)
60 function wrRecacheRegions() {
61         $dbr = wfGetDB(DB_SLAVE);
62         // SELECT cl_from FROM categorylinks where cl_to = 'Region'
63         $res = $dbr->select('categorylinks', 'cl_from', array('cl_to' => 'Region'));
64         $page_ids = array();
65         while ($row = $dbr->fetchObject($res)) $page_ids[] = $row->cl_from;
66         $dbr->freeResult($res);
67
68         $titles = Title::newFromIDs($page_ids);
69         foreach ($titles as $title) $title->invalidateCache();
70 }
71
72
73 /// Returns the tuple ($report_id, $sledrun_condition, $date_report)
74 /// $date_report is NULL or a time as returned by strtotime
75 /// Expects a database connection ($dbr = wfGetDB(DB_SLAVE);)
76 /// and a page_id describung the page where the condition should be returned.
77 /// If no condition is found, (NULL, NULL, NULL) is returned.
78 function wrGetSledrunCondition($dbr, $page_id) {
79         // 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;
80         $cres = $dbr->select(
81                 'wrreport',
82                 array('wrreport.id as report_id', '`condition`', 'date_report'),
83                 array('page_id' => $page_id, '`condition` is not null', 'date_invalid > now()', 'delete_date is null'),
84                 'wrReportConditionRender',
85                 array('ORDER BY' => 'date_report desc, date_entry desc', 'LIMIT' => '1')
86         );
87         if ($cres->numRows() <= 0) {
88                 $report_id = NULL;
89                 $condition = NULL;
90                 $date_report = NULL;
91         } else {
92                 $crow = $dbr->fetchObject($cres);
93                 $report_id = $crow->report_id;
94                 $condition = $crow->condition;
95                 $date_report = strtotime($crow->date_report);
96         }
97         $dbr->freeResult($cres);
98         return array($report_id, $condition, $date_report);
99 }
100
101
102 /// Updates the line of the wrreportcache table that corresponds to the $page_id parameter
103 function wrUpdateWrReportCacheTable($page_id) {
104         // Determine the new content for the row that should be updated
105         $dbr = wfGetDB(DB_SLAVE);
106         list($report_id, $condition, $date_report) = wrGetSledrunCondition($dbr, $page_id);
107         $rows = wrReportGetReports(array('id' => $report_id), 1);
108
109         // Delete the old content (if any)
110         $dbw = wfGetDB(DB_MASTER);
111         $dbw->begin();
112         $dbw->delete('wrreportcache', array('page_id' => $page_id));
113
114         // Insert the updated row
115         if (count($rows) == 1) {
116                 $row = $rows[0];
117                 $dbw->insert('wrreportcache', array(
118                         'page_id' => $row['page_id'],
119                         'page_title' => $row['page_title'],
120                         'report_id' => $row['id'],
121                         'date_report' => $row['date_report'],
122                         '`condition`' => $row['condition'],
123                         'description' => $row['description'],
124                         'author_name' => $row['author_name'],
125                         'author_username' => (is_null($row['author_userid']) ? NULL : $row['author_username'])));
126         }
127         $dbw->commit();
128 }
129
130
131
132 // Render Functions
133 // ----------------
134
135 /// \brief Returns a form to enter a report (string containing HTML).
136 ///
137 /// All parameters have to be UTF-8 encoded.
138 /// \param $page_title Name of the sledrun.
139 /// \param $condition 1 to 5 for normal condition, 0 or NULL for missing condition and -1 for intentionally no condition.
140 /// \return UTF-8 encoded HTML form
141 function wrReportFormRender($hide_save_button = TRUE, $page_title = NULL, $date_report = NULL, $condition = NULL, $description = NULL, $author_name = NULL, $page_title_list = NULL) {
142         $doc = new WrDOMDocument();
143         $evenoddrow = array('oddrow', 'evenrow');
144         $rownum = 0;
145
146         // Info about special page
147         $specialPageName = wfMessage('wrreport')->text(); // 'Bahnberichte'
148         $title = Title::newFromText($specialPageName, NS_SPECIAL);
149         $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
150
151         // form
152         $form = $doc->appendElement('form', array('action' => $specialPageUrl, 'method' => 'post'));
153
154         // table (for layout of form elements)
155         $table = $form->appendElement('table', array('class' => 'wrreportform', 'summary' => wfMessage('wrreport-newreport-tablesummary')->text()));
156
157         // sledrun name
158         $tr = $table->appendElement('tr', array('class' => $evenoddrow[$rownum++ % 2]));
159         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
160         $td = $tr->appendElement('td');
161         $td->appendText($page_title);
162         $input = $td->appendElement('input', array('type' => 'hidden', 'name' => 'page_title', 'value' => $page_title));
163
164         // report date
165         $tr = $table->appendElement('tr', array('class' => $evenoddrow[$rownum++ % 2]));
166         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-date')->text());
167         $td = $tr->appendElement('td');
168         $select = $td->appendElement('select', array('name' => 'date_report'));
169         $daynames = array(
170                 wfMessage('wrreport-date-today')->text(),
171                 wfMessage('wrreport-date-yesterday')->text(),
172                 wfMessage('wrreport-date-2daysbefore')->text(),
173                 wfMessage('wrreport-date-3daysbefore')->text(),
174                 wfMessage('wrreport-date-4daysbefore')->text());
175         $date_selected = false;
176         $time = time(); // number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
177         for ($day=0; $day!=5; ++$day) {
178                 $date = strtotime("-$day days", $time);
179                 $date_f = strftime("%Y-%m-%d", $date); // Formats it according to locale, that is set to CET.
180                 $option = $select->appendElement('option', array('value' => $date_f));
181                 if ((is_null($date_report) && $day == 0) || (!is_null($date_report) && $date_report == $date_f)) {
182                         $option->setAttribute('selected', 'selected');
183                         $date_selected = true;
184                 }
185                 $option->appendText($daynames[$day] . ' (' . strftime('%d.%m.', $date) . ')');
186         }
187         if (!$date_selected) { // note: if $date_report is null $date_selected is true here
188                 $option = $select->appendElement('option', array('value' => $date_report, 'selected' => 'selected'));
189                 $option->appendText($date_report);
190         }
191
192         // condition
193         $tr = $table->appendElement('tr', array('class' => $evenoddrow[$rownum++ % 2]));
194         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
195         $td = $tr->appendElement('td');
196         $select = $td->appendElement('select', array('name' => 'condition'));
197         $option = $select->appendElement('option', array('value' => '0'));
198         $option->appendText(wfMessage('wrreport-condition-select')->text());
199         foreach (WrReport::$wrConditions as $condition_num => $condition_text) {
200                 $option = $select->appendElement('option', array('value' => (string) $condition_num));
201                 if ($condition == $condition_num) $option->setAttribute('selected', 'selected');
202                 $option->appendText($condition_text);
203         }
204         $option = $select->appendElement('option', array('value' => '-1'));
205         if ($condition == -1) $option->setAttribute('selected', 'selected');
206         $option->appendText(wfMessage('wrreport-condition-no')->text());
207
208         // description
209         $tr = $table->appendElement('tr', array('class' => $evenoddrow[$rownum++ % 2]));
210         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-description')->text());
211         $tr->appendElement('td')->appendElement('textarea', array('name' => 'description', 'cols' => '50', 'rows' => '7'))->appendText($description);
212
213         // author
214         $tr = $table->appendElement('tr', array('class' => $evenoddrow[$rownum++ % 2]));
215         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-author')->text());
216         $tr->appendElement('td')->appendElement('input', array('name' => 'author_name', 'maxlength' => '30', 'size' => '30', 'value' => $author_name));
217
218         // Buttons
219         // I would like to do it this way, but due to a bug of internet explorer, the <button> element is not useable.
220         //   $buttons = '<button name="action" type="submit" value="preview">Vorschau';
221         //   if ($hide_save_button) $buttons .= ' &amp; Speichern';
222         //   $buttons .= '</button>';
223         //   if (!$hide_save_button) $buttons .= '<button name="action" type="submit" value="store">Speichern</button>';
224         // Workaround: User <input type="submit"/>
225         $tr = $table->appendElement('tr', array('class' => $evenoddrow[$rownum++ % 2]));
226         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-submit')->text());
227         $td = $tr->appendElement('td');
228         $input = $td->appendElement('input', array('name' => 'preview', 'type' => 'submit'));
229         if ($hide_save_button)
230                 $input->setAttribute('value', wfMessage('wrreport-newreport-preview')->text() . ' & ' . wfMessage('wrreport-newreport-save')->text());
231         else {
232                 $input->setAttribute('value', wfMessage('wrreport-newreport-preview')->text());
233
234                 $td->appendElement('input', array('name' => 'store', 'type' => 'submit', 'value' => wfMessage('wrreport-newreport-save')->text()));
235         }
236
237         return $doc->saveHTML($form);
238 }
239
240
241 /// \brief Renders the form to delete a report
242 ///
243 /// All in and output strings should be/are UTF-8 encoded.
244 /// \param $reportid the id of the report that is going to be deleted
245 /// \param $delete_person_name name of the person that wants to delete the report (form field)
246 /// \param $delete_reason_public publically visible reason for deleting the entry.
247 /// \param $delete_invisible don't show the report as being deleted
248 /// \return UTF-8 encoded HTML form
249 function wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible) {
250         $doc = new WrDOMDocument();
251         $evenoddrow = array('oddrow', 'evenrow');
252         $rownum = 0;
253
254         // Info about special page
255         $specialPageName = wfMessage('wrreport')->text(); // 'Bahnberichte'
256         $title = Title::newFromText($specialPageName, NS_SPECIAL);
257         $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
258
259         // form
260         $form = $doc->appendElement('form', array('action' => $specialPageUrl, 'method' => 'post'));
261
262         // table (for layout of form elements)
263         $table = $form->appendElement('table', array('class' => 'wrreportform', 'summary' => wfMessage('wrreport-deletereport-tablesummary')->text()));
264
265         // delete_reason_public
266         $tr = $table->appendElement('tr', array('class' => $evenoddrow[$rownum++ % 2]));
267         $tr->appendElement('th')->appendText(wfMessage('wrreport-deletereport-reason')->text());
268         $tr->appendElement('td')->appendElement('textarea', array('name' => 'delete_reason_public', 'cols' => '50', 'rows' => '7'))->appendText($delete_reason_public);
269
270         // delete_person_name
271         $tr = $table->appendElement('tr', array('class' => $evenoddrow[$rownum++ % 2]));
272         $tr->appendElement('th')->appendText(wfMessage('wrreport-deletereport-name')->text());
273         $tr->appendElement('td')->appendElement('input', array('name' => 'delete_person_name', 'maxlength' => '30', 'size' => '30', 'value' => $delete_person_name));
274
275         // buttons
276         $tr = $table->appendElement('tr', array('class' => $evenoddrow[$rownum++ % 2]));
277         $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-action')->text());
278         $td = $tr->appendElement('td');
279         $td->appendElement('input', array('name' => 'deletepreview', 'type' => 'submit', 'value' => wfMessage('wrreport-newreport-preview')->text()));
280         $td->appendElement('input', array('name' => 'delete', 'type' => 'submit', 'value' => wfMessage('wrreport-deletereport-delete')->text()));
281
282         // hidden field
283         $input = $td->appendElement('input', array('name' => 'reportid', 'type' => 'hidden', 'value' => (string) $reportid));
284         // delete_invisible - who is allowed to do so?
285         // $td->appendElement('input', array('name' => 'delete_invisible', 'type' => 'hidden', 'value' => (string) $delete_invisible));
286
287         return $doc->saveHTML($form);
288 }
289
290
291 /// \brief Generates the DOM of the table header ("private" sub-function of wrReportTableRender)
292 ///
293 /// \param $table table WrDOMElement where the header should be appended
294 /// \param $format row format like WRREPORT_COMPACT
295 /// \param $showActions boolean to indicate whether an actions column should be created
296 /// \return WrDOMElement of the HTML table header
297 function wrReportTableTitleRender($table, $format, $showActions) {
298         $tr = $table->appendElement('tr');
299         if ($format == WRREPORT_DETAIL) $tr->appendElement('th')->appendText('ID');
300         if ($format != WRREPORT_COMPACT) $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
301         $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-date')->text());
302         if ($format == WRREPORT_DETAIL) $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-date-entry')->text());
303         if ($format == WRREPORT_DETAIL) $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-date-invalid')->text());
304         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
305         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-description')->text());
306         $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-author')->text());
307         if ($showActions) $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-action')->text());
308         return $tr;
309 }
310
311
312 /// \brief Generates the DOM of a table row ("private" sub-function of wrReportTableRender)
313 ///
314 /// \param $table table WrDOMElement where the row should be appended
315 /// \param $row associative array of table columns like one row in the wrreport table
316 /// \param $format row format like WRREPORT_COMPACT
317 /// \param $showActions boolean to indicate whether an actions column should be created
318 /// \param $parser Parser instance of a Parser class that can be used to parse the condition
319 /// \return WrDOMElement of the HTML table row
320 function wrReportTableRowRender($table, $row, $format, $showActions, $parser) {
321         $tr = $table->appendElement('tr');
322
323         // $row['id']
324         if ($format == WRREPORT_DETAIL) $tr->appendElement('td')->appendText($row['id']);
325
326         // $row['page_title']
327         if ($format != WRREPORT_COMPACT) {
328                 $title = Title::newFromText($row['page_title']);
329                 $tr->appendElement('td')->appendElement('a', array('href' => $title->getLocalURL()))->appendText($title->getPrefixedText());
330         }
331
332         // $row['date_report']
333         $date_report = strtotime($row['date_report']);
334         $date_report = wfMessage(Language::$mWeekdayAbbrevMsgs[(int) date('w', $date_report)])->text() . strftime(', %d.%m.', $date_report);
335         $tr->appendElement('td')->appendText($date_report);
336
337         // $row['date_entry']
338         if ($format == WRREPORT_DETAIL) $tr->appendElement('td')->appendText(date('d.m. H:i', strtotime($row['date_entry'])));
339
340         // $row['date_invalid']
341         if ($format == WRREPORT_DETAIL) $tr->appendElement('td')->appendText(date('d.m. H:i', strtotime($row['date_invalid'])));
342
343         // $row['condition']
344         $condition_text = '---';
345         if (isset(WrReport::$wrConditions[$row['condition']])) $condition_text = WrReport::$wrConditions[$row['condition']];
346         $td = $tr->appendElement('td');
347         if ($row['delete_date']) $td->appendElement('em')->appendText(wfMessage('wrreport-deletereport-deleted')->text());
348         else $td->appendText($condition_text);
349
350         // $row['description']
351         $td = $tr->appendElement('td', array('class' => 'wrreportdescription'));
352         if ($row['delete_date']) $td->appendElement('em')->appendText(wfMessage('wrreport-deletereport-deleted')->text());
353         else {
354                 // for registered users, use wikitext formatting
355                 if (is_null($row['author_userid'])) $td->appendText($row['description']);
356                 else {
357                         $html = $parser->recursiveTagParse($row['description']);
358                         // $parser->recursiveTagParse does not always escape & characters.
359                         // (see https://bugzilla.wikimedia.org/show_bug.cgi?id=55526 )
360                         //
361                         // Workaround: Use a CDATA section. When serializing with $doc->saveHTML,
362                         // the <![CDATA[...]]> is returned as ... .
363                         // However, we end up having unescaped & in the output due to this bug in recursiveTagParse.
364                         $td->appendChild($tr->ownerDocument->createCDATASection($html));
365                 }
366         }
367
368         // $row['author_name']
369         $td = $tr->appendElement('td');
370         if ($row['delete_date']) $td->appendElement('em')->appendText(wfMessage('wrreport-deletereport-deleted')->text());
371         else $td->appendText($row['author_name']); # TODO: Make it special :-), e.g. link to user + avatar + number of reports
372
373         // actions
374         // wiki/Spezial:Bahnberichte?action=deletepreview&reportid=42
375         if ($showActions) {
376                 $td = $tr->appendElement('td');
377                 if (!isset($row['delete_date'])) {
378                         $specialPageName = wfMessage('wrreport')->text(); // 'Bahnberichte'
379                         $title = Title::newFromText($specialPageName, NS_SPECIAL);
380                         $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
381                         $td->appendElement('a', array('href' => $specialPageUrl . '?action=deletepreview&reportid=' . $row['id']))
382                                 ->appendText(wfMessage('wrreport-deletereport-delete')->text() . '...');
383                 }
384         }
385         return $tr;
386 }
387
388
389 /// \brief Renders the report table. Call wrReportGetReports for the $rows parameter.
390 ///
391 /// \param $rows array of associative row arrays
392 /// \param $format row format like WRREPORT_TABLE_SHORT
393 function wrReportTableRender($rows, $format, $showActions, $parser) {
394         $doc = new WrDOMDocument();
395         $table = $doc->appendElement('table', array('class' => 'wrreporttable'));
396         wrReportTableTitleRender($table, $format, $showActions);
397         foreach ($rows as $key => $row) wrReportTableRowRender($table, $row, $format, $showActions, $parser);
398         return $doc->saveHTML($table);
399 }
400
401
402 /// Returns an array with column names
403 function wrReportGetColumnNames() {
404         return array('id', 'page_id', 'page_title', 'date_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');
405 }
406
407
408 /// \brief Returns reports as associative array.
409 ///
410 /// Examples:
411 ///   $conditions = array('page_title' => 'Birgitzer Alm', 'date_invalid > now()');
412 ///   $limit = 1; // or NULL for no limit
413 function wrReportGetReports($conditions, $limit=NULL) {
414         $dbr = wfGetDB(DB_SLAVE);
415         $columns = wrReportGetColumnNames();
416         global $wgDBtype;
417         if ($wgDBtype == "mysql") // "condition" is a reserved word in mysql
418                  for ($i = 0; $i != count($columns); ++$i) $columns[$i] = sprintf('`%s`', $columns[$i]);
419         $options = array('ORDER BY' => 'date_report desc, date_entry desc');
420         if (!is_null($limit)) $options['LIMIT'] = $limit;
421         $res = $dbr->select('wrreport', $columns, $conditions, 'wrReportGetReports', $options);
422         $result = array();
423         while ($row = $dbr->fetchRow($res)) $result[] = $row;
424         $dbr->freeResult($res);
425         return $result;
426 }
427
428
429 /// \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));
430 ///
431 /// If no condition is present, array(NULL, NULL) is returned
432 function wrReportConditionRender($page_title) {
433         $dbr = wfGetDB(DB_SLAVE);
434         $cond = 'condition';
435         global $wgDBtype;
436         // 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;
437         if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
438         $res = $dbr->select(
439                 'wrreport',
440                 array('wrreport.id as report_id', $cond, 'date_report'),
441                 array('page_title' => $page_title, "$cond is not null", 'date_invalid > now()', 'delete_date is null'),
442                 'wrReportConditionRender',
443                 array('ORDER BY' => 'date_report desc, date_entry desc', 'LIMIT' => '1')
444         );
445         if ($res->numRows() <= 0) {
446                 $dbr->freeResult($res);
447                 return array(NULL, NULL);
448         }
449         $row = $dbr->fetchObject($res);
450         $date = $row->date_report;
451         if ($date) $date = strtotime($date);
452         $dbr->freeResult($res);
453         return array($row->condition, $date);
454 }
455
456
457 /// \brief Returns true if the user is allowed to delete reports (in general)
458 function wrReportUserMayDelete() {
459         global $wgUser;
460         global $wgWrReportDeleteMode;
461         return $wgWrReportDeleteMode == 'allow' || ($wgWrReportDeleteMode == 'loggedin' && $wgUser->isLoggedIn());
462 }
463
464
465
466 // Parser Hook Functions
467 // ---------------------
468
469 /// \brief Is called when the tag <bahnberichtformular/> is encountered.
470 ///
471 /// The current page name is taken.
472 function bahnberichtformularParserHook($input, $args, $parser) {
473         // Username
474         global $wgUser;
475         $author_name = NULL;
476         if ($wgUser->isLoggedIn()) {
477                 $author_name = $wgUser->getRealName();
478                 if (!$author_name) $author_name = $wgUser->getName();
479         }
480
481         global $wgWrReportMode;
482         global $wgWrReportBlackListAll;
483         global $wgWrReportBlackListStrangers;
484
485         // is the form allowed to be shown?
486         $error_key = null;
487         if ($wgWrReportMode == 'summer') $error_key = 'wrreport-newreport-summer';
488         elseif ($wgWrReportMode == 'deny') $error_key = 'wrreport-newreport-deny';
489         elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $error_key = 'wrreport-newreport-loggedin';
490         elseif (in_array($parser->getTitle()->getText(), $wgWrReportBlackListAll)) $error_key = 'wrreport-newreport-blacklist';
491         elseif (!$wgUser->isLoggedIn() && in_array($parser->getTitle()->getText(), $wgWrReportBlackListStrangers)) $error_key = 'wrreport-newreport-blackliststrangers';
492
493         // report error
494         if (!is_null($error_key)) {
495                 $doc = new WrDOMDocument();
496                 $doc->appendElement('p')->appendElement('em')->appendText(wfMessage($error_key)->text());
497                 return $doc->saveHTML($form);
498         }
499
500         // Calling "$title = $parser->getTitle(); $title->invalidateCache();" doesn't help here to force regeneration
501         // However, this would not be the best solution because the page has to be re-rendered only at midnight
502
503         // In the following line, $author_name was replaced by NULL to prevent a bug, where the wrong author_name
504         // is shown due to caching (see ticket #35).
505         return wrReportFormRender(TRUE, $parser->getTitle()->getText(), NULL, NULL, NULL, NULL);
506 }
507
508
509 /// \brief Is called when the tag <bahnberichte/> is encountered.
510 ///
511 /// The current page name is taken.
512 function bahnberichteParserHook($input, $args, $parser) {
513         $page_title = $parser->getTitle()->getText();
514         $conditions = array('page_title' => $page_title, 'date_invalid > now()');
515         $rows = wrReportGetReports($conditions);
516         if (count($rows) == 0) return wfMessage('wrreport-reports-none')->text();
517         return wrReportTableRender($rows, WRREPORT_COMPACT, wrReportUserMayDelete(), $parser);
518 }
519
520
521 /// \brief Is called when the tag <bahnentabelle/> is encountered.
522 ///
523 /// Example:
524 /// <bahnentabelle>
525 /// Birgitzer Alm (vom Adelshof)
526 /// Kemater Alm
527 /// Axamer Lizum
528 /// </bahnentabelle>
529 function bahnentabelleParserHook($input, $args, $parser) {
530         $page_titles = array(); // array of Title objects
531         foreach (explode("\n", $input) as $page_title) {
532                 $page_title = Title::newFromText(trim($page_title));
533                 if (!$page_title || !$page_title->exists()) continue;
534                 $page_titles[] = $page_title;
535         }
536
537         $dbr = wfGetDB(DB_SLAVE);
538         // 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
539         $where_array = array('page.page_id = wrsledruncache.page_id');
540         if (count($page_titles) > 0) {
541                 $mysql_page_titles = array();
542                 for ($i = 0; $i != count($page_titles); ++$i) $mysql_page_titles[] = "'" . mysql_real_escape_string($page_titles[$i]->getDBKey()) . "'";
543                 $where_array[] = 'page.page_title in (' . implode(', ', $mysql_page_titles) . ')';
544         } else $where_array[] = 'false';
545         $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'), $where_array, 'bahnentabelleParserHook', array('ORDER BY' => 'page.page_title'));
546
547         global $wgUser;
548         global $wgWrReportMode; // e.g. 'summer'
549         global $wgWrReportBlackListAll;
550         global $wgWrReportBlackListStrangers;
551         global $wgDBtype;
552
553         // Determine, whether the user is allowed to make a new report
554         $userMayReport = ($wgWrReportMode == 'allow' || ($wgWrReportMode == 'loggedin' && $wgUser->isLoggedIn()));
555
556         // Generate DOM for HTML
557         $doc = new WrDOMDocument();
558         $table = $doc->appendElement('table', array('class' => 'wikitable'));
559
560         // Title
561         $tr = $table->appendElement('tr');
562         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_rental.png', 'alt' => wfMessage('wrreport-icon-sledrental')->text(), 'title' => wfMessage('wrreport-icon-sledrental')->text()));
563         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_light.png', 'alt' => wfMessage('wrreport-icon-nightlight')->text(), 'title' => wfMessage('wrreport-icon-nightlight')->text()));
564         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
565         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_walk.png', 'alt' => wfMessage('wrreport-icon-walkupseparate')->text(), 'title' => wfMessage('wrreport-icon-walkupseparate')->text()));
566         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_bus.png', 'alt' => wfMessage('wrreport-icon-publictransport')->text(), 'title' => wfMessage('wrreport-icon-publictransport')->text()));
567         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
568         if ($wgWrReportMode != 'summer') $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
569         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-information')->text());
570         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-walkuptime')->text());
571         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-height')->text());
572         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-length')->text());
573
574         // Rows
575         while ($row = $dbr->fetchObject($res)) {
576                 $title = Title::newFromRow($row);
577                 $tr = $table->appendElement('tr');
578
579                 $td = $tr->appendElement('td');
580                 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()));
581
582                 $td = $tr->appendElement('td');
583                 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()));
584                    
585                 $td = $tr->appendElement('td');
586                 if ($row->lift) $td->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
587
588                 $td = $tr->appendElement('td');
589                 if (!is_null($row->walkup_possible)) {
590                         if ($row->walkup_possible) {
591                                 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()));
592                         } else $td->appendElement('img', array('src' => '/vorlagen/s_nowalk.png', 'alt' => wfMessage('wrreport-icon-walkupnotpossible')->text(), 'title' => wfMessage('wrreport-icon-walkupnotpossible')->text()));
593                 }
594
595                 $td = $tr->appendElement('td');
596                 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()));
597
598                 $tr->appendElement('td')->appendElement('a', array('href' => $title->getLocalURL()))->appendText($title->getPrefixedText());
599
600                 if ($wgWrReportMode != 'summer') {
601                         // Check rights
602                         $userMayReportThis = $userMayReport;
603                         if ($userMayReportThis) {
604                                 if (in_array($title->getText(), $wgWrReportBlackListAll)) $userMayReportThis = FALSE;
605                                 if (!$wgUser->isLoggedIn() && in_array($title->getText(), $wgWrReportBlackListStrangers)) $userMayReportThis = FALSE; // Title::getText() uses spaces instead of underscores
606                         }
607
608                         // Select condition
609                         list($report_id, $condition, $date_report) = wrGetSledrunCondition($dbr, $row->page_id);
610                         if (is_null($report_id)) $date = '';
611                         else $date = strftime('%d.%m.', $date_report);
612
613                         $td = $tr->appendElement('td');
614                         if (isset(WrReport::$wrConditions[$condition])) {
615                                 $td->appendElement('a', array('href' => $title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-reports-sectionname')->text())))->appendText(WrReport::$wrConditions[$condition]);
616                                 $td->appendText(' ');
617                                 $small = $td->appendElement('small');
618                                 $small->appendText($date);
619                                 if ($userMayReportThis) {
620                                         $small->appendText(' ');
621                                         $small->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-newreport-sectionname')->text())))->appendText(wfMessage('wrreport-newreport-new')->text());
622                                 }
623                         } else {
624                                 if ($userMayReportThis) 
625                                         $td->appendElement('small')->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-newreport-sectionname')->text())))->appendText(wfMessage('wrreport-newreport-please')->text());
626                                 else $td->appendText('--');
627                         }
628                 }
629
630                 $td = $tr->appendElement('td');
631                 $info = $row->information_phone;
632                 if ($info) {
633                         $info_parts = explode(';', $info);
634                         $info_parts = explode('(', $info_parts[0], 2);
635                         if (count($info_parts) == 2) {
636                                 $td->appendText($info_parts[0]);
637                                 $td->appendElement('small')->appendText('(' . $info_parts[1]);
638                         } else $td->appendText($info);
639                 }
640
641                 $tr->appendElement('td')->appendText($row->walkup_time ? $row->walkup_time . ' min' : '');
642
643                 $tr->appendElement('td')->appendText(
644                         ($row->bottom_elevation ? $row->bottom_elevation  : '') . 
645                         ($row->bottom_elevation && $row->top_elevation ? ' - ' : '') . 
646                         ($row->top_elevation ? $row->top_elevation : '') . 
647                         ($row->bottom_elevation || $row->top_elevation ? ' m' : '')); 
648
649                 $tr->appendElement('td')->appendText($row->length ? $row->length . ' m' : '');
650         }
651         $dbr->freeResult($res);
652
653         return $doc->saveHTML();
654 }
655
656
657 // tag extension hooks
658 // -------------------
659
660 class WrReport {
661         // Conditions: array(1 => 'Sehr gut', 2 => 'Gut', 3 => 'Mittelmäßig', 4 => 'Schlecht', 5 => 'Geht nicht');
662         public static $wrConditions;
663
664
665         function initWrConditions() {
666                 WrReport::$wrConditions = array();
667                 for ($i = 1; $i != 6; ++$i) WrReport::$wrConditions[$i] = wfMessage('wrreport-condition-' . $i)->text();
668         }
669
670
671         public static function languageGetSpecialPageAliasesHook(&$specialPageArray, $languageCode) {
672                 $text = wfMessage('wrreport')->text(); // 'Bahnberichte'
673                 $title = Title::newFromText($text); // 'Bahnberichte'
674                 $specialPageArray['wrreport'][] = $title->getDBKey(); // 'Bahnberichte'
675                 return true;
676         }
677
678
679         public static function parserFirstCallInitHook(&$parser) {
680                 $parser->setHook('bahnberichtformular', 'bahnberichtformularParserHook');
681                 $parser->setHook('bahnberichte', 'bahnberichteParserHook');
682                 $parser->setHook('bahnentabelle', 'bahnentabelleParserHook');
683                 return true;
684         }
685 }
686 WrReport::initWrConditions();
687
688
689
690 // Special page
691 // ------------
692
693 /// Specal Page to show reports
694 class SpecialWrReport extends SpecialPage {
695         function __construct() {
696                 parent::__construct('wrreport');
697         }
698
699
700         /// \param $par Possibilities:
701         /// - action == 'view' (default)
702         /// - action == 'preview': Preview new report
703         /// - action == 'store': Store new report
704         /// - action == 'deletepreview': Preview the deleted record
705         /// - action == 'delete': Delete an existing report
706         /// - action == 'showerror': Shows the error and exits
707         /// \param $override_action If not NULL (default), it overrides the action in $par
708         /// \param $errorMsg UFT-8 encoded error message (in WikiText) to show on top of the page or NULL (default):
709         function execute($par, $override_action = NULL, $errorMsg = NULL) {
710                 // $request = $this->getRequest();
711                 // $output = $this->getOutput(); // see http://www.mediawiki.org/wiki/Manual:Special_pages
712                 // $param = $request->getText('param');
713         
714                 global $wgRequest, $wgOut, $wgParser;
715
716                 $this->setHeaders();
717
718                 // Get request data
719                 $action = $wgRequest->getText('action');
720                 if (!$action) {
721                         if ($wgRequest->getVal('preview')) $action = 'preview';
722                         elseif ($wgRequest->getVal('store')) $action = 'store';
723                         elseif ($wgRequest->getVal('deletepreview')) $action = 'deletepreview';
724                         elseif ($wgRequest->getVal('delete')) $action = 'delete';
725                         else $action = 'view';
726                 }
727                 if ($override_action) $action = $override_action;
728
729                 // Show error message
730                 if ($errorMsg || $action == 'showerror') {
731                         $wgOut->addWikiText('<div class="errorbox">' . $errorMsg . "</div>\n");
732                         if ($action == 'showerror') return;
733                 }
734
735                 // Action view
736                 if ($action == 'view') {
737                         $conditions = array('date_invalid > now()');
738                         $rows = wrReportGetReports($conditions);
739                         if (count($rows) == 0) $wgOut->addHTML(wfMessage('wrreport-reports-none')->text());
740                         else {
741                                 $wgOut->addWikiText(''); // this is necessary because otherwise $wgParser is not properly initialized but $wgParser is needed in the next line
742                                 $wgOut->addHTML(wrReportTableRender($rows, WRREPORT_DETAIL, wrReportUserMayDelete(), $wgParser));
743                         }
744                 }
745
746                 // Action deletepreview or delete
747                 elseif ($action == 'deletepreview' || $action == 'delete') {
748                         $reportid = (int) $wgRequest->getText('reportid');
749                         if ($reportid == 0) {
750                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-noreport')->text());
751                                 return;
752                         }
753                         $rows = wrReportGetReports(array('id' => $reportid));
754                         if (count($rows) != 1) {
755                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-invalid')->text());
756                                 return;
757                         }
758                         $row = $rows[0];
759                         if (!is_null($row['delete_date'])) {
760                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-alreadydeleted')->text());
761                                 return;
762                         }
763                         $delete_reason_public = $wgRequest->getText('delete_reason_public');
764                         $delete_person_name = $wgRequest->getText('delete_person_name');
765                         $delete_invisible = $wgRequest->getText('delete_invisible') ? TRUE : FALSE;
766                         if ($action == 'delete') {
767                                 // page
768                                 $title = Title::newFromId($row['page_id']);
769
770                                 // user
771                                 global $wgUser;
772                                 $delete_person_userid = $wgUser->getId();
773                                 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.
774                                 $delete_person_username = $wgUser->getName();
775
776                                 // Check permissions - see also function wrReportUserMayDelete, that does also check permissions but does not return an error message.
777                                 $errorMsg = NULL;
778                                 global $wgWrReportDeleteMode;
779                                 if ($wgWrReportDeleteMode == 'deny') $errorMsg = wfMessage('wrreport-deletereport-deny')->text();
780                                 elseif ($wgWrReportDeleteMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = wfMessage('wrreport-deletereport-loggedin')->text();
781                                 elseif (!$delete_person_name || !$delete_reason_public) $errorMsg = wfMessage('wrreport-deletereport-incomplete')->text();
782                                 if ($errorMsg) {
783                                         $this->execute($par, 'deletepreview', $errorMsg);
784                                         return;
785                                 }
786
787                                 // "Delete" (update) entry
788                                 $dbr = wfGetDB(DB_MASTER);
789                                 $dbr->update(
790                                         'wrreport',
791                                         array(
792                                                 'delete_date' => date('c'),
793                                                 'delete_person_name' => $delete_person_name,
794                                                 'delete_person_ip' => $_SERVER['REMOTE_ADDR'],
795                                                 'delete_person_userid' => $delete_person_userid,
796                                                 'delete_person_username' => $delete_person_username,
797                                                 'delete_reason_public' => $delete_reason_public,
798                                                 'delete_invisible' => $delete_invisible ? 't' : 'f'
799                                         ),
800                                         array('id' => $reportid)
801                                 );
802
803                                 // Purge cache
804                                 $title->invalidateCache();
805                                 wrRecacheRegions();
806
807                                 // Show success message
808                                 $wgOut->addWikiText(wfMessage('wrreport-deletereport-success', '[[' . $row['page_title'] . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $row['page_title'] . ']]')->text());
809                         }
810                         if ($action == 'deletepreview') {
811                                 $wgOut->addWikiText(wfMessage('wrreport-deletereport-preview-before')->text());
812                                 $format = WRREPORT_COMPACT_PAGE;
813                                 $wgOut->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
814                                 $wgOut->addWikiText(wfMessage('wrreport-deletereport-preview-after')->text());
815                                 $row['delete_date'] = date('c');
816                                 $row['delete_reason_public'] = $delete_reason_public;
817                                 $row['delete_person_name'] = $delete_person_name;
818                                 $row['delete_invisible'] = $delete_invisible;
819                                 $wgOut->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
820                                 $wgOut->addWikiText(wfMessage('wrreport-deletereport-preview-form')->text());
821                                 $wgOut->addHTML(wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible));
822                                 $wgOut->addWikiText(wfMessage('wrreport-deletereport-preview-bottom')->text());
823                         }
824                 }
825
826                 // Action preview or store
827                 elseif ($action == 'preview' || $action == 'store') {
828                         $page_title = $wgRequest->getText('page_title');
829                         $date_report = $wgRequest->getText('date_report');
830                         $condition = $wgRequest->getText('condition');
831                         $description = $wgRequest->getText('description');
832                         $author_name = $wgRequest->getText('author_name');
833
834                         // condition
835                         $condition = (int) $condition; // force to be nummeric. -1 ... "keine Bewertung", 0 ... "Bitte eingeben", 1 to 5 ... "Sehr gut" to "Geht nicht"
836                         if ($condition < -1 or $condition > 5) $condition = 0; // invalid condition: Tread like 0.
837                         $condition_sql = NULL;
838                         if ($condition >= 1 and $condition <= 5) $condition_sql = $condition;
839
840                         // author_name
841                         $author_name = trim($author_name);
842
843                         // page_id
844                         $title = Title::newFromText($page_title);
845                         $page_id = $title->getArticleId();
846                         if ($page_id == 0) $page_id = NULL;
847
848                         // user_id
849                         global $wgUser;
850                         $author_userid = $wgUser->getId();
851                         if ($author_userid == 0) $author_userid = NULL; // to store a NULL value in the database if no user is logged in instead of 0.
852                         $author_username = $wgUser->getName();
853
854                         if ($action == 'store') {
855                                 // check conditions/permissions
856                                 $errorMsg = NULL;
857                                 global $wgWrReportMode;
858                                 global $wgWrReportBlackListAll;
859                                 global $wgWrReportBlackListStrangers;
860                                 if ($wgWrReportMode == 'summer') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-summer')->text());
861                                 elseif ($wgWrReportMode == 'deny') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-deny')->text());
862                                 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-loggedin')->text());
863                                 elseif (!$page_id) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-pagenotfound')->text());
864                                 elseif (in_array($page_title, $wgWrReportBlackListAll)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blacklist')->text());
865                                 elseif (!$wgUser->isLoggedIn() && in_array($page_title, $wgWrReportBlackListStrangers)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blackliststrangers')->text());
866                                 elseif ($condition == 0) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-choosecondition')->text());
867                                 elseif (!$wgUser->isLoggedIn()) {
868                                         if (!$description) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterdescription')->text());
869                                         elseif (!(stripos($description, 'http') === FALSE)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-nohttp')->text());
870                                         elseif (!$author_name) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterauthor')->text());
871                                 }
872
873                                 // check author name
874                                 if (!$errorMsg) {
875                                         $author_name_id = $wgUser->idFromName(strtolower($author_name));
876                                         if ($wgUser->isLoggedIn()) {
877                                                 if ($author_name_id != 0 && $author_name_id != $wgUser->getId())
878                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorused')->text());
879                                         } else {
880                                                 if ($author_name_id != 0)
881                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorlogin')->text());
882                                         }
883                                 }
884
885                                 // Chech whether identical reports are present
886                                 if (!$errorMsg) {
887                                         $dbr = wfGetDB(DB_SLAVE);
888                                         $cond = 'condition';
889                                         global $wgDBtype;
890                                         if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
891                                         $sqlConditions = array('page_id' => $page_id, 'date_report' => $date_report, $cond => $condition_sql, 'description' => $description, 'author_name' => $author_name);
892                                         $res = $dbr->select('wrreport', 'id', $sqlConditions);
893                                         if ($res->numRows() == 1) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-alreadysaved')->text());
894                                         $dbr->freeResult($res);
895                                 }
896
897                                 // Show error if any
898                                 if ($errorMsg) {
899                                         $this->execute($par, 'preview', $errorMsg);
900                                         return;
901                                 }
902
903                                 // Save entry
904                                 $dbr = wfGetDB(DB_MASTER);
905                                 $dbr->insert(
906                                         'wrreport',
907                                         array(
908                                                 'page_id' => $page_id,
909                                                 'page_title' => $page_title,
910                                                 'date_report' => $date_report,
911                                                 'date_entry' => date('c'),
912                                                 'date_invalid' => date('c', strtotime('+9 days')),
913                                                 $cond => $condition_sql,
914                                                 'description' => $description,
915                                                 'author_name' => $author_name,
916                                                 'author_ip' => $_SERVER['REMOTE_ADDR'],
917                                                 'author_userid' => $author_userid,
918                                                 'author_username' => $author_username
919                                                 // 'delete_*' => // use database defaults (NULL)
920                                         )
921                                 );
922
923                                 // Purge cache
924                                 $title->invalidateCache();
925                                 wrRecacheRegions();
926                                 wrUpdateWrReportCacheTable($page_id);
927
928                                 // Show success message
929                                 $wgOut->addWikiText(wfMessage('wrreport-newreport-success', '[[' . $page_title . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $page_title . ']]')->text());
930                                 // We could redirect to result with the following line but we don't want to.
931                                 // $wgOut->redirect($title->getFullURL() . '#' . wfMessage('wrreport-reports-sectionname')->text());
932                         }
933                         if ($action == 'preview') {
934                                 $wgOut->addWikiText(wfMessage('wrreport-newreport-preview-top')->text());
935                                 $format = WRREPORT_COMPACT_PAGE;
936                                 $row = array_fill_keys(wrReportGetColumnNames(), NULL);
937                                 $row['page_id'] = $page_id;
938                                 $row['page_title'] = $page_title;
939                                 $row['date_report'] = $date_report;
940                                 $row['condition'] = $condition_sql;
941                                 $row['description'] = $description;
942                                 $row['author_name'] = $author_name;
943                                 $row['author_userid'] = $author_userid;
944                                 $row['author_username'] = $author_username;
945
946                                 $wgOut->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
947                                 $wgOut->addWikiText(wfMessage('wrreport-newreport-preview-middle')->text());
948                                 $wgOut->addHTML(wrReportFormRender(FALSE, $page_title, $date_report, $condition, $description, $author_name));
949                                 $wgOut->addWikiText(wfMessage('wrreport-newreport-preview-bottom')->text());
950                         }
951
952                 }
953
954                 else die('Wrong action');
955         }
956 }
957
958
959 ?>