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