Now the user name is a link if the user page exists.
[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                         // get user page
399                         $title = $user->getUserPage();
400                         if ($title->exists()) {
401                                 $td->appendCDATA(Linker::link($title, $row['author_name']));
402                         } else {
403                                 $td->appendText($row['author_name']);
404                         }
405                 } else {
406                         $td->appendText($row['author_name']);
407                 }
408         }
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 array(wrReportFormRender(TRUE, $parser->getTitle()->getText(), NULL, NULL, NULL, NULL), 'noparse' => true, 'isHTML' => true);
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 $wgUser;
585         global $wgWrReportMode; // e.g. 'summer'
586         global $wgWrReportBlackListAll;
587         global $wgWrReportBlackListStrangers;
588         global $wgDBtype;
589
590         // Determine, whether the user is allowed to make a new report
591         $userMayReport = ($wgWrReportMode == 'allow' || ($wgWrReportMode == 'loggedin' && $wgUser->isLoggedIn()));
592
593         // Generate DOM for HTML
594         $doc = new WrDOMDocument();
595         $table = $doc->appendElement('table', array('class' => 'wikitable'));
596
597         // Title
598         $tr = $table->appendElement('tr');
599         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_rental.png', 'alt' => wfMessage('wrreport-icon-sledrental')->text(), 'title' => wfMessage('wrreport-icon-sledrental')->text()));
600         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_light.png', 'alt' => wfMessage('wrreport-icon-nightlight')->text(), 'title' => wfMessage('wrreport-icon-nightlight')->text()));
601         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
602         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_walk.png', 'alt' => wfMessage('wrreport-icon-walkupseparate')->text(), 'title' => wfMessage('wrreport-icon-walkupseparate')->text()));
603         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_bus.png', 'alt' => wfMessage('wrreport-icon-publictransport')->text(), 'title' => wfMessage('wrreport-icon-publictransport')->text()));
604         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
605         if ($wgWrReportMode != 'summer') $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
606         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-information')->text());
607         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-walkuptime')->text());
608         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-height')->text());
609         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-length')->text());
610
611         // Rows
612         while ($row = $dbr->fetchObject($res)) {
613                 $title = Title::newFromRow($row);
614                 $tr = $table->appendElement('tr');
615
616                 $td = $tr->appendElement('td');
617                 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()));
618
619                 $td = $tr->appendElement('td');
620                 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()));
621                    
622                 $td = $tr->appendElement('td');
623                 if ($row->lift) $td->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
624
625                 $td = $tr->appendElement('td');
626                 if (!is_null($row->walkup_possible)) {
627                         if ($row->walkup_possible) {
628                                 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()));
629                         } else $td->appendElement('img', array('src' => '/vorlagen/s_nowalk.png', 'alt' => wfMessage('wrreport-icon-walkupnotpossible')->text(), 'title' => wfMessage('wrreport-icon-walkupnotpossible')->text()));
630                 }
631
632                 $td = $tr->appendElement('td');
633                 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()));
634
635                 $tr->appendElement('td')->appendElement('a', array('href' => $title->getLocalURL()))->appendText($title->getPrefixedText());
636
637                 if ($wgWrReportMode != 'summer') {
638                         // Check rights
639                         $userMayReportThis = $userMayReport;
640                         if ($userMayReportThis) {
641                                 if (in_array($title->getText(), $wgWrReportBlackListAll)) $userMayReportThis = FALSE;
642                                 if (!$wgUser->isLoggedIn() && in_array($title->getText(), $wgWrReportBlackListStrangers)) $userMayReportThis = FALSE; // Title::getText() uses spaces instead of underscores
643                         }
644
645                         // Select condition
646                         list($report_id, $condition, $date_report) = wrGetSledrunCondition($dbr, $row->page_id);
647                         if (is_null($report_id)) $date = '';
648                         else $date = strftime('%d.%m.', $date_report);
649
650                         $td = $tr->appendElement('td');
651                         if (isset(WrReport::$wrConditions[$condition])) {
652                                 $td->appendElement('a', array('href' => $title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-reports-sectionname')->text())))->appendText(WrReport::$wrConditions[$condition]);
653                                 $td->appendText(' ');
654                                 $small = $td->appendElement('small');
655                                 $small->appendText($date);
656                                 if ($userMayReportThis) {
657                                         $small->appendText(' ');
658                                         $small->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-newreport-sectionname')->text())))->appendText(wfMessage('wrreport-newreport-new')->text());
659                                 }
660                         } else {
661                                 if ($userMayReportThis) 
662                                         $td->appendElement('small')->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-newreport-sectionname')->text())))->appendText(wfMessage('wrreport-newreport-please')->text());
663                                 else $td->appendText('--');
664                         }
665                 }
666
667                 $td = $tr->appendElement('td');
668                 $info = $row->information_phone;
669                 if ($info) {
670                         $info_parts = explode(';', $info);
671                         $info_parts = explode('(', $info_parts[0], 2);
672                         if (count($info_parts) == 2) {
673                                 $td->appendText($info_parts[0]);
674                                 $td->appendElement('small')->appendText('(' . $info_parts[1]);
675                         } else $td->appendText($info);
676                 }
677
678                 $tr->appendElement('td')->appendText($row->walkup_time ? $row->walkup_time . ' min' : '');
679
680                 $tr->appendElement('td')->appendText(
681                         ($row->bottom_elevation ? $row->bottom_elevation  : '') . 
682                         ($row->bottom_elevation && $row->top_elevation ? ' - ' : '') . 
683                         ($row->top_elevation ? $row->top_elevation : '') . 
684                         ($row->bottom_elevation || $row->top_elevation ? ' m' : '')); 
685
686                 $tr->appendElement('td')->appendText($row->length ? $row->length . ' m' : '');
687         }
688         $dbr->freeResult($res);
689
690         return $doc->saveHTML();
691 }
692
693
694 // tag extension hooks
695 // -------------------
696
697 class WrReport {
698         // Conditions: array(1 => 'Sehr gut', 2 => 'Gut', 3 => 'Mittelmäßig', 4 => 'Schlecht', 5 => 'Geht nicht');
699         public static $wrConditions;
700
701
702         function initWrConditions() {
703                 WrReport::$wrConditions = array();
704                 for ($i = 1; $i != 6; ++$i) WrReport::$wrConditions[$i] = wfMessage('wrreport-condition-' . $i)->text();
705         }
706
707
708         public static function languageGetSpecialPageAliasesHook(&$specialPageArray, $languageCode) {
709                 $text = wfMessage('wrreport')->text(); // 'Bahnberichte'
710                 $title = Title::newFromText($text); // 'Bahnberichte'
711                 $specialPageArray['wrreport'][] = $title->getDBKey(); // 'Bahnberichte'
712                 return true;
713         }
714
715
716         public static function parserFirstCallInitHook(&$parser) {
717                 $parser->setHook('bahnberichtformular', 'bahnberichtformularParserHook');
718                 $parser->setHook('bahnberichte', 'bahnberichteParserHook');
719                 $parser->setHook('bahnentabelle', 'bahnentabelleParserHook');
720                 return true;
721         }
722 }
723 WrReport::initWrConditions();
724
725
726
727 // Special page
728 // ------------
729
730 /// Specal Page to show reports
731 class SpecialWrReport extends SpecialPage {
732         function __construct() {
733                 parent::__construct('wrreport');
734         }
735
736
737         /// \param $par Possibilities:
738         /// - action == 'view' (default)
739         /// - action == 'preview': Preview new report
740         /// - action == 'store': Store new report
741         /// - action == 'deletepreview': Preview the deleted record
742         /// - action == 'delete': Delete an existing report
743         /// - action == 'showerror': Shows the error and exits
744         /// \param $override_action If not NULL (default), it overrides the action in $par
745         /// \param $errorMsg UFT-8 encoded error message (in WikiText) to show on top of the page or NULL (default):
746         function execute($par, $override_action = NULL, $errorMsg = NULL) {
747                 // $request = $this->getRequest();
748                 // $output = $this->getOutput(); // see http://www.mediawiki.org/wiki/Manual:Special_pages
749                 // $param = $request->getText('param');
750         
751                 global $wgRequest, $wgOut, $wgParser;
752
753                 $this->setHeaders();
754
755                 // Get request data
756                 $action = $wgRequest->getText('action');
757                 if (!$action) {
758                         if ($wgRequest->getVal('preview')) $action = 'preview';
759                         elseif ($wgRequest->getVal('store')) $action = 'store';
760                         elseif ($wgRequest->getVal('deletepreview')) $action = 'deletepreview';
761                         elseif ($wgRequest->getVal('delete')) $action = 'delete';
762                         else $action = 'view';
763                 }
764                 if ($override_action) $action = $override_action;
765
766                 // Show error message
767                 if ($errorMsg || $action == 'showerror') {
768                         $wgOut->addWikiText('<div class="errorbox">' . $errorMsg . "</div>\n");
769                         if ($action == 'showerror') return;
770                 }
771
772                 // Action view
773                 if ($action == 'view') {
774                         $conditions = array('date_invalid > now()');
775                         $rows = wrReportGetReports($conditions);
776                         if (count($rows) == 0) $wgOut->addHTML(wfMessage('wrreport-reports-none')->text());
777                         else {
778                                 $wgOut->addWikiText(''); // this is necessary because otherwise $wgParser is not properly initialized but $wgParser is needed in the next line
779                                 $wgOut->addHTML(wrReportTableRender($rows, WRREPORT_DETAIL, wrReportUserMayDelete(), $wgParser));
780                         }
781                 }
782
783                 // Action deletepreview or delete
784                 elseif ($action == 'deletepreview' || $action == 'delete') {
785                         $reportid = (int) $wgRequest->getText('reportid');
786                         if ($reportid == 0) {
787                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-noreport')->text());
788                                 return;
789                         }
790                         $rows = wrReportGetReports(array('id' => $reportid));
791                         if (count($rows) != 1) {
792                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-invalid')->text());
793                                 return;
794                         }
795                         $row = $rows[0];
796                         if (!is_null($row['delete_date'])) {
797                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-alreadydeleted')->text());
798                                 return;
799                         }
800                         $delete_reason_public = $wgRequest->getText('delete_reason_public');
801                         $delete_person_name = $wgRequest->getText('delete_person_name');
802                         $delete_invisible = $wgRequest->getText('delete_invisible') ? TRUE : FALSE;
803                         if ($action == 'delete') {
804                                 // page
805                                 $title = Title::newFromId($row['page_id']);
806
807                                 // user
808                                 global $wgUser;
809                                 $delete_person_userid = $wgUser->getId();
810                                 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.
811                                 $delete_person_username = $wgUser->getName();
812
813                                 // Check permissions - see also function wrReportUserMayDelete, that does also check permissions but does not return an error message.
814                                 $errorMsg = NULL;
815                                 global $wgWrReportDeleteMode;
816                                 if ($wgWrReportDeleteMode == 'deny') $errorMsg = wfMessage('wrreport-deletereport-deny')->text();
817                                 elseif ($wgWrReportDeleteMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = wfMessage('wrreport-deletereport-loggedin')->text();
818                                 elseif (!$delete_person_name || !$delete_reason_public) $errorMsg = wfMessage('wrreport-deletereport-incomplete')->text();
819                                 if ($errorMsg) {
820                                         $this->execute($par, 'deletepreview', $errorMsg);
821                                         return;
822                                 }
823
824                                 // "Delete" (update) entry
825                                 $dbr = wfGetDB(DB_MASTER);
826                                 $dbr->update(
827                                         'wrreport',
828                                         array(
829                                                 'delete_date' => date('c'),
830                                                 'delete_person_name' => $delete_person_name,
831                                                 'delete_person_ip' => $_SERVER['REMOTE_ADDR'],
832                                                 'delete_person_userid' => $delete_person_userid,
833                                                 'delete_person_username' => $delete_person_username,
834                                                 'delete_reason_public' => $delete_reason_public,
835                                                 'delete_invisible' => $delete_invisible ? 't' : 'f'
836                                         ),
837                                         array('id' => $reportid)
838                                 );
839
840                                 // Purge cache
841                                 $title->invalidateCache();
842                                 wrRecacheRegions();
843
844                                 // Show success message
845                                 $wgOut->addWikiText(wfMessage('wrreport-deletereport-success', '[[' . $row['page_title'] . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $row['page_title'] . ']]')->text());
846                         }
847                         if ($action == 'deletepreview') {
848                                 $wgOut->addWikiText(wfMessage('wrreport-deletereport-preview-before')->text());
849                                 $format = WRREPORT_COMPACT_PAGE;
850                                 $wgOut->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
851                                 $wgOut->addWikiText(wfMessage('wrreport-deletereport-preview-after')->text());
852                                 $row['delete_date'] = date('c');
853                                 $row['delete_reason_public'] = $delete_reason_public;
854                                 $row['delete_person_name'] = $delete_person_name;
855                                 $row['delete_invisible'] = $delete_invisible;
856                                 $wgOut->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
857                                 $wgOut->addWikiText(wfMessage('wrreport-deletereport-preview-form')->text());
858                                 $wgOut->addHTML(wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible));
859                                 $wgOut->addWikiText(wfMessage('wrreport-deletereport-preview-bottom')->text());
860                         }
861                 }
862
863                 // Action preview or store
864                 elseif ($action == 'preview' || $action == 'store') {
865                         $page_title = $wgRequest->getText('page_title');
866                         $date_report = $wgRequest->getText('date_report');
867                         $condition = $wgRequest->getText('condition');
868                         $description = $wgRequest->getText('description');
869                         $author_name = $wgRequest->getText('author_name');
870
871                         // condition
872                         $condition = (int) $condition; // force to be nummeric. -1 ... "keine Bewertung", 0 ... "Bitte eingeben", 1 to 5 ... "Sehr gut" to "Geht nicht"
873                         if ($condition < -1 or $condition > 5) $condition = 0; // invalid condition: Tread like 0.
874                         $condition_sql = NULL;
875                         if ($condition >= 1 and $condition <= 5) $condition_sql = $condition;
876
877                         // author_name
878                         $author_name = trim($author_name);
879
880                         // page_id
881                         $title = Title::newFromText($page_title);
882                         $page_id = $title->getArticleId();
883                         if ($page_id == 0) $page_id = NULL;
884
885                         // user_id
886                         global $wgUser;
887                         $author_userid = $wgUser->getId();
888                         if ($author_userid == 0) $author_userid = NULL; // to store a NULL value in the database if no user is logged in instead of 0.
889                         $author_username = $wgUser->getName();
890
891                         if ($action == 'store') {
892                                 // check conditions/permissions
893                                 $errorMsg = NULL;
894                                 global $wgWrReportMode;
895                                 global $wgWrReportBlackListAll;
896                                 global $wgWrReportBlackListStrangers;
897                                 if ($wgWrReportMode == 'summer') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-summer')->text());
898                                 elseif ($wgWrReportMode == 'deny') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-deny')->text());
899                                 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-loggedin')->text());
900                                 elseif (!$page_id) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-pagenotfound')->text());
901                                 elseif (in_array($page_title, $wgWrReportBlackListAll)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blacklist')->text());
902                                 elseif (!$wgUser->isLoggedIn() && in_array($page_title, $wgWrReportBlackListStrangers)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blackliststrangers')->text());
903                                 elseif ($condition == 0) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-choosecondition')->text());
904                                 elseif (!$wgUser->isLoggedIn()) {
905                                         if (!$description) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterdescription')->text());
906                                         elseif (!(stripos($description, 'http') === FALSE)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-nohttp')->text());
907                                         elseif (!$author_name) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterauthor')->text());
908                                 }
909
910                                 // check author name
911                                 if (!$errorMsg) {
912                                         $author_name_id = $wgUser->idFromName(strtolower($author_name));
913                                         if ($wgUser->isLoggedIn()) {
914                                                 if ($author_name_id != 0 && $author_name_id != $wgUser->getId())
915                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorused')->text());
916                                         } else {
917                                                 if ($author_name_id != 0)
918                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorlogin')->text());
919                                         }
920                                 }
921
922                                 // Chech whether identical reports are present
923                                 if (!$errorMsg) {
924                                         $dbr = wfGetDB(DB_SLAVE);
925                                         $cond = 'condition';
926                                         global $wgDBtype;
927                                         if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
928                                         $sqlConditions = array('page_id' => $page_id, 'date_report' => $date_report, $cond => $condition_sql, 'description' => $description, 'author_name' => $author_name);
929                                         $res = $dbr->select('wrreport', 'id', $sqlConditions);
930                                         if ($res->numRows() == 1) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-alreadysaved')->text());
931                                         $dbr->freeResult($res);
932                                 }
933
934                                 // Show error if any
935                                 if ($errorMsg) {
936                                         $this->execute($par, 'preview', $errorMsg);
937                                         return;
938                                 }
939
940                                 // Save entry
941                                 $dbr = wfGetDB(DB_MASTER);
942                                 $dbr->insert(
943                                         'wrreport',
944                                         array(
945                                                 'page_id' => $page_id,
946                                                 'page_title' => $page_title,
947                                                 'date_report' => $date_report,
948                                                 'date_entry' => date('c'),
949                                                 'date_invalid' => date('c', strtotime('+9 days')),
950                                                 $cond => $condition_sql,
951                                                 'description' => $description,
952                                                 'author_name' => $author_name,
953                                                 'author_ip' => $_SERVER['REMOTE_ADDR'],
954                                                 'author_userid' => $author_userid,
955                                                 'author_username' => $author_username
956                                                 // 'delete_*' => // use database defaults (NULL)
957                                         )
958                                 );
959
960                                 // Purge cache
961                                 $title->invalidateCache();
962                                 wrRecacheRegions();
963                                 wrUpdateWrReportCacheTable($page_id);
964
965                                 // Show success message
966                                 $wgOut->addWikiText(wfMessage('wrreport-newreport-success', '[[' . $page_title . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $page_title . ']]')->text());
967                                 // We could redirect to result with the following line but we don't want to.
968                                 // $wgOut->redirect($title->getFullURL() . '#' . wfMessage('wrreport-reports-sectionname')->text());
969                         }
970                         if ($action == 'preview') {
971                                 $wgOut->addWikiText(wfMessage('wrreport-newreport-preview-top')->text());
972                                 $format = WRREPORT_COMPACT_PAGE;
973                                 $row = array_fill_keys(wrReportGetColumnNames(), NULL);
974                                 $row['page_id'] = $page_id;
975                                 $row['page_title'] = $page_title;
976                                 $row['date_report'] = $date_report;
977                                 $row['condition'] = $condition_sql;
978                                 $row['description'] = $description;
979                                 $row['author_name'] = $author_name;
980                                 $row['author_userid'] = $author_userid;
981                                 $row['author_username'] = $author_username;
982
983                                 $wgOut->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
984                                 $wgOut->addWikiText(wfMessage('wrreport-newreport-preview-middle')->text());
985                                 $wgOut->addHTML(wrReportFormRender(FALSE, $page_title, $date_report, $condition, $description, $author_name));
986                                 $wgOut->addWikiText(wfMessage('wrreport-newreport-preview-bottom')->text());
987                         }
988
989                 }
990
991                 else die('Wrong action');
992         }
993 }
994
995
996 ?>