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