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