'noparse' => true and 'isHTML' => true is returned by all parser hooks now.
[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')->appendCDATA(Linker::link($title));
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                         $td->appendText(' ');
406                         
407                         // get number of sledrun reports
408                         $td->appendElement('span', array('class' => 'wrreportcount'))
409                                 ->appendText((string) WrReport::getUserSeldrunReportCount($user->getId()));
410
411                 } else {
412                         $td->appendText($row['author_name']);
413                 }
414         }
415
416         // actions
417         // wiki/Spezial:Bahnberichte?action=deletepreview&reportid=42
418         if ($showActions) {
419                 $td = $tr->appendElement('td');
420                 if (!isset($row['delete_date'])) {
421                         $specialPageName = wfMessage('wrreport')->text(); // 'Bahnberichte'
422                         $title = Title::newFromText($specialPageName, NS_SPECIAL);
423                         $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
424                         $td->appendElement('a', array('href' => $specialPageUrl . '?action=deletepreview&reportid=' . $row['id']))
425                                 ->appendText(wfMessage('wrreport-deletereport-delete')->text() . '...');
426                 }
427         }
428         return $tr;
429 }
430
431
432 /// \brief Renders the report table. Call wrReportGetReports for the $rows parameter.
433 ///
434 /// \param $rows array of associative row arrays
435 /// \param $format row format like WRREPORT_TABLE_SHORT
436 function wrReportTableRender($rows, $format, $showActions, $parser) {
437         $doc = new WrDOMDocument();
438         $table = $doc->appendElement('table', array('class' => 'wrreporttable'));
439         wrReportTableTitleRender($table, $format, $showActions);
440         foreach ($rows as $key => $row) wrReportTableRowRender($table, $row, $format, $showActions, $parser);
441         return $doc->saveHTML($table);
442 }
443
444
445 /// Returns an array with column names
446 function wrReportGetColumnNames() {
447         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');
448 }
449
450
451 /// \brief Returns reports as associative array.
452 ///
453 /// Examples:
454 ///   $conditions = array('page_title' => 'Birgitzer Alm', 'date_invalid > now()');
455 ///   $limit = 1; // or NULL for no limit
456 function wrReportGetReports($conditions, $limit=NULL) {
457         $dbr = wfGetDB(DB_SLAVE);
458         $columns = wrReportGetColumnNames();
459         global $wgDBtype;
460         if ($wgDBtype == "mysql") // "condition" is a reserved word in mysql
461                  for ($i = 0; $i != count($columns); ++$i) $columns[$i] = sprintf('`%s`', $columns[$i]);
462         $options = array('ORDER BY' => 'date_report desc, date_entry desc');
463         if (!is_null($limit)) $options['LIMIT'] = $limit;
464         $res = $dbr->select('wrreport', $columns, $conditions, 'wrReportGetReports', $options);
465         $result = array();
466         while ($row = $dbr->fetchRow($res)) $result[] = $row;
467         $dbr->freeResult($res);
468         return $result;
469 }
470
471
472 /// \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));
473 ///
474 /// If no condition is present, array(NULL, NULL) is returned
475 function wrReportConditionRender($page_title) {
476         $dbr = wfGetDB(DB_SLAVE);
477         $cond = 'condition';
478         global $wgDBtype;
479         // 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;
480         if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
481         $res = $dbr->select(
482                 'wrreport',
483                 array('wrreport.id as report_id', $cond, 'date_report'),
484                 array('page_title' => $page_title, "$cond is not null", 'date_invalid > now()', 'delete_date is null'),
485                 'wrReportConditionRender',
486                 array('ORDER BY' => 'date_report desc, date_entry desc', 'LIMIT' => '1')
487         );
488         if ($res->numRows() <= 0) {
489                 $dbr->freeResult($res);
490                 return array(NULL, NULL);
491         }
492         $row = $dbr->fetchObject($res);
493         $date = $row->date_report;
494         if ($date) $date = strtotime($date);
495         $dbr->freeResult($res);
496         return array($row->condition, $date);
497 }
498
499
500 /// \brief Returns true if the user is allowed to delete reports (in general)
501 function wrReportUserMayDelete() {
502         global $wgUser;
503         global $wgWrReportDeleteMode;
504         return $wgWrReportDeleteMode == 'allow' || ($wgWrReportDeleteMode == 'loggedin' && $wgUser->isLoggedIn());
505 }
506
507
508
509 // Parser Hook Functions
510 // ---------------------
511
512 /// \brief Is called when the tag <bahnberichtformular/> is encountered.
513 ///
514 /// The current page name is taken.
515 function bahnberichtformularParserHook($input, $args, $parser) {
516         // Username
517         global $wgUser;
518         $author_name = NULL;
519         if ($wgUser->isLoggedIn()) {
520                 $author_name = $wgUser->getRealName();
521                 if (!$author_name) $author_name = $wgUser->getName();
522         }
523
524         global $wgWrReportMode;
525         global $wgWrReportBlackListAll;
526         global $wgWrReportBlackListStrangers;
527
528         // is the form allowed to be shown?
529         $error_key = null;
530         if ($wgWrReportMode == 'summer') $error_key = 'wrreport-newreport-summer';
531         elseif ($wgWrReportMode == 'deny') $error_key = 'wrreport-newreport-deny';
532         elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $error_key = 'wrreport-newreport-loggedin';
533         elseif (in_array($parser->getTitle()->getText(), $wgWrReportBlackListAll)) $error_key = 'wrreport-newreport-blacklist';
534         elseif (!$wgUser->isLoggedIn() && in_array($parser->getTitle()->getText(), $wgWrReportBlackListStrangers)) $error_key = 'wrreport-newreport-blackliststrangers';
535
536         // report error
537         if (!is_null($error_key)) {
538                 $doc = new WrDOMDocument();
539                 $doc->appendElement('p')->appendElement('em')->appendText(wfMessage($error_key)->text());
540                 return $doc->saveHTML($form);
541         }
542
543         // Calling "$title = $parser->getTitle(); $title->invalidateCache();" doesn't help here to force regeneration
544         // However, this would not be the best solution because the page has to be re-rendered only at midnight
545
546         // In the following line, $author_name was replaced by NULL to prevent a bug, where the wrong author_name
547         // is shown due to caching (see ticket #35).
548         return array(wrReportFormRender(TRUE, $parser->getTitle()->getText(), NULL, NULL, NULL, NULL), 'noparse' => true, 'isHTML' => true);
549 }
550
551
552 /// \brief Is called when the tag <bahnberichte/> is encountered.
553 ///
554 /// The current page name is taken.
555 function bahnberichteParserHook($input, $args, $parser) {
556         $parser->getOutput()->addModules('ext.wrreport');
557         $page_title = $parser->getTitle()->getText();
558         $conditions = array('page_title' => $page_title, 'date_invalid > now()');
559         $rows = wrReportGetReports($conditions);
560         if (count($rows) == 0) return wfMessage('wrreport-reports-none')->text();
561         return array(wrReportTableRender($rows, WRREPORT_COMPACT, wrReportUserMayDelete(), $parser), 'noparse' => true, 'isHTML' => true);
562 }
563
564
565 /// \brief Is called when the tag <bahnentabelle/> is encountered.
566 ///
567 /// Example:
568 /// <bahnentabelle>
569 /// Birgitzer Alm (vom Adelshof)
570 /// Kemater Alm
571 /// Axamer Lizum
572 /// </bahnentabelle>
573 function bahnentabelleParserHook($input, $args, $parser) {
574         $page_titles = array(); // array of Title objects
575         foreach (explode("\n", $input) as $page_title) {
576                 $page_title = Title::newFromText(trim($page_title));
577                 if (!$page_title || !$page_title->exists()) continue;
578                 $page_titles[] = $page_title;
579         }
580
581         $dbr = wfGetDB(DB_SLAVE);
582         // 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
583         $where_array = array('page.page_id = wrsledruncache.page_id');
584         if (count($page_titles) > 0) {
585                 $mysql_page_titles = array();
586                 for ($i = 0; $i != count($page_titles); ++$i) $mysql_page_titles[] = "'" . mysql_real_escape_string($page_titles[$i]->getDBKey()) . "'";
587                 $where_array[] = 'page.page_title in (' . implode(', ', $mysql_page_titles) . ')';
588         } else $where_array[] = 'false';
589         $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'));
590
591         global $wgUser;
592         global $wgWrReportMode; // e.g. 'summer'
593         global $wgWrReportBlackListAll;
594         global $wgWrReportBlackListStrangers;
595         global $wgDBtype;
596
597         // Determine, whether the user is allowed to make a new report
598         $userMayReport = ($wgWrReportMode == 'allow' || ($wgWrReportMode == 'loggedin' && $wgUser->isLoggedIn()));
599
600         // Generate DOM for HTML
601         $doc = new WrDOMDocument();
602         $table = $doc->appendElement('table', array('class' => 'wikitable'));
603
604         // Title
605         $tr = $table->appendElement('tr');
606         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_rental.png', 'alt' => wfMessage('wrreport-icon-sledrental')->text(), 'title' => wfMessage('wrreport-icon-sledrental')->text()));
607         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_light.png', 'alt' => wfMessage('wrreport-icon-nightlight')->text(), 'title' => wfMessage('wrreport-icon-nightlight')->text()));
608         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
609         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_walk.png', 'alt' => wfMessage('wrreport-icon-walkupseparate')->text(), 'title' => wfMessage('wrreport-icon-walkupseparate')->text()));
610         $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_bus.png', 'alt' => wfMessage('wrreport-icon-publictransport')->text(), 'title' => wfMessage('wrreport-icon-publictransport')->text()));
611         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
612         if ($wgWrReportMode != 'summer') $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
613         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-information')->text());
614         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-walkuptime')->text());
615         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-height')->text());
616         $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-length')->text());
617
618         // Rows
619         while ($row = $dbr->fetchObject($res)) {
620                 $title = Title::newFromRow($row);
621                 $tr = $table->appendElement('tr');
622
623                 $td = $tr->appendElement('td');
624                 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()));
625
626                 $td = $tr->appendElement('td');
627                 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()));
628                    
629                 $td = $tr->appendElement('td');
630                 if ($row->lift) $td->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
631
632                 $td = $tr->appendElement('td');
633                 if (!is_null($row->walkup_possible)) {
634                         if ($row->walkup_possible) {
635                                 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()));
636                         } else $td->appendElement('img', array('src' => '/vorlagen/s_nowalk.png', 'alt' => wfMessage('wrreport-icon-walkupnotpossible')->text(), 'title' => wfMessage('wrreport-icon-walkupnotpossible')->text()));
637                 }
638
639                 $td = $tr->appendElement('td');
640                 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()));
641
642                 $tr->appendElement('td')->appendElement('a', array('href' => $title->getLocalURL()))->appendText($title->getPrefixedText());
643
644                 if ($wgWrReportMode != 'summer') {
645                         // Check rights
646                         $userMayReportThis = $userMayReport;
647                         if ($userMayReportThis) {
648                                 if (in_array($title->getText(), $wgWrReportBlackListAll)) $userMayReportThis = FALSE;
649                                 if (!$wgUser->isLoggedIn() && in_array($title->getText(), $wgWrReportBlackListStrangers)) $userMayReportThis = FALSE; // Title::getText() uses spaces instead of underscores
650                         }
651
652                         // Select condition
653                         list($report_id, $condition, $date_report) = wrGetSledrunCondition($dbr, $row->page_id);
654                         if (is_null($report_id)) $date = '';
655                         else $date = strftime('%d.%m.', $date_report);
656
657                         $td = $tr->appendElement('td');
658                         if (isset(WrReport::$wrConditions[$condition])) {
659                                 $td->appendElement('a', array('href' => $title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-reports-sectionname')->text())))->appendText(WrReport::$wrConditions[$condition]);
660                                 $td->appendText(' ');
661                                 $small = $td->appendElement('small');
662                                 $small->appendText($date);
663                                 if ($userMayReportThis) {
664                                         $small->appendText(' ');
665                                         $small->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-newreport-sectionname')->text())))->appendText(wfMessage('wrreport-newreport-new')->text());
666                                 }
667                         } else {
668                                 if ($userMayReportThis) 
669                                         $td->appendElement('small')->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-newreport-sectionname')->text())))->appendText(wfMessage('wrreport-newreport-please')->text());
670                                 else $td->appendText('--');
671                         }
672                 }
673
674                 $td = $tr->appendElement('td');
675                 $info = $row->information_phone;
676                 if ($info) {
677                         $info_parts = explode(';', $info);
678                         $info_parts = explode('(', $info_parts[0], 2);
679                         if (count($info_parts) == 2) {
680                                 $td->appendText($info_parts[0]);
681                                 $td->appendElement('small')->appendText('(' . $info_parts[1]);
682                         } else $td->appendText($info);
683                 }
684
685                 $tr->appendElement('td')->appendText($row->walkup_time ? $row->walkup_time . ' min' : '');
686
687                 $tr->appendElement('td')->appendText(
688                         ($row->bottom_elevation ? $row->bottom_elevation  : '') . 
689                         ($row->bottom_elevation && $row->top_elevation ? ' - ' : '') . 
690                         ($row->top_elevation ? $row->top_elevation : '') . 
691                         ($row->bottom_elevation || $row->top_elevation ? ' m' : '')); 
692
693                 $tr->appendElement('td')->appendText($row->length ? $row->length . ' m' : '');
694         }
695         $dbr->freeResult($res);
696
697         return array($doc->saveHTML(), 'noparse' => true, 'isHTML' => true);
698 }
699
700
701 // tag extension hooks
702 // -------------------
703
704 class WrReport {
705         // Conditions: array(1 => 'Sehr gut', 2 => 'Gut', 3 => 'Mittelmäßig', 4 => 'Schlecht', 5 => 'Geht nicht');
706         public static $wrConditions;
707
708
709         function initWrConditions() {
710                 WrReport::$wrConditions = array();
711                 for ($i = 1; $i != 6; ++$i) WrReport::$wrConditions[$i] = wfMessage('wrreport-condition-' . $i)->text();
712         }
713
714
715         public static function languageGetSpecialPageAliasesHook(&$specialPageArray, $languageCode) {
716                 $text = wfMessage('wrreport')->text(); // 'Bahnberichte'
717                 $title = Title::newFromText($text); // 'Bahnberichte'
718                 $specialPageArray['wrreport'][] = $title->getDBKey(); // 'Bahnberichte'
719                 return true;
720         }
721
722
723         public static function parserFirstCallInitHook(&$parser) {
724                 $parser->setHook('bahnberichtformular', 'bahnberichtformularParserHook');
725                 $parser->setHook('bahnberichte', 'bahnberichteParserHook');
726                 $parser->setHook('bahnentabelle', 'bahnentabelleParserHook');
727                 return true;
728         }
729         
730         
731         /// Returns the number of sledrun reports issued by a user with the given id.
732         public static function getUserSeldrunReportCount($user_id) {
733                 $dbr = wfGetDB(DB_SLAVE);
734                 // select count(*) from wrreport where author_userid = $user_id;
735                 $res = $dbr->select('wrreport', array('ccc' => 'count(*)'), array('author_userid' => $user_id));
736                 $row = $res->fetchRow();
737                 $count = $row[0];
738                 $dbr->freeResult($res);
739                 return $count;
740         }
741 }
742 WrReport::initWrConditions();
743
744
745
746 // Special page
747 // ------------
748
749 /// Specal Page to show reports
750 class SpecialWrReport extends SpecialPage {
751         function __construct() {
752                 parent::__construct('wrreport');
753         }
754
755
756         /// \param $par Possibilities:
757         /// - action == 'view' (default)
758         /// - action == 'preview': Preview new report
759         /// - action == 'store': Store new report
760         /// - action == 'deletepreview': Preview the deleted record
761         /// - action == 'delete': Delete an existing report
762         /// - action == 'showerror': Shows the error and exits
763         /// \param $override_action If not NULL (default), it overrides the action in $par
764         /// \param $errorMsg UFT-8 encoded error message (in WikiText) to show on top of the page or NULL (default):
765         function execute($par, $override_action = NULL, $errorMsg = NULL) {
766                 $request = $this->getRequest();
767                 $output = $this->getOutput();
768         
769                 global $wgParser;
770
771                 $output->addModules('ext.wrreport');
772                 $this->setHeaders();
773
774                 // Get request data
775                 $action = $request->getText('action');
776                 if (!$action) {
777                         if ($request->getVal('preview')) $action = 'preview';
778                         elseif ($request->getVal('store')) $action = 'store';
779                         elseif ($request->getVal('deletepreview')) $action = 'deletepreview';
780                         elseif ($request->getVal('delete')) $action = 'delete';
781                         else $action = 'view';
782                 }
783                 if ($override_action) $action = $override_action;
784
785                 // Show error message
786                 if ($errorMsg || $action == 'showerror') {
787                         $output->addWikiText('<div class="errorbox">' . $errorMsg . "</div>\n");
788                         if ($action == 'showerror') return;
789                 }
790
791                 // Action view
792                 if ($action == 'view') {
793                         $conditions = array('date_invalid > now()');
794                         $rows = wrReportGetReports($conditions);
795                         if (count($rows) == 0) $output->addHTML(wfMessage('wrreport-reports-none')->text());
796                         else {
797                                 $output->addWikiText(''); // this is necessary because otherwise $wgParser is not properly initialized but $wgParser is needed in the next line
798                                 $output->addHTML(wrReportTableRender($rows, WRREPORT_DETAIL, wrReportUserMayDelete(), $wgParser));
799                         }
800                 }
801
802                 // Action deletepreview or delete
803                 elseif ($action == 'deletepreview' || $action == 'delete') {
804                         $reportid = (int) $request->getText('reportid');
805                         if ($reportid == 0) {
806                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-noreport')->text());
807                                 return;
808                         }
809                         $rows = wrReportGetReports(array('id' => $reportid));
810                         if (count($rows) != 1) {
811                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-invalid')->text());
812                                 return;
813                         }
814                         $row = $rows[0];
815                         if (!is_null($row['delete_date'])) {
816                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-alreadydeleted')->text());
817                                 return;
818                         }
819                         $delete_reason_public = $request->getText('delete_reason_public');
820                         $delete_person_name = $request->getText('delete_person_name');
821                         $delete_invisible = $request->getText('delete_invisible') ? TRUE : FALSE;
822                         if ($action == 'delete') {
823                                 // page
824                                 $title = Title::newFromId($row['page_id']);
825
826                                 // user
827                                 global $wgUser;
828                                 $delete_person_userid = $wgUser->getId();
829                                 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.
830                                 $delete_person_username = $wgUser->getName();
831
832                                 // Check permissions - see also function wrReportUserMayDelete, that does also check permissions but does not return an error message.
833                                 $errorMsg = NULL;
834                                 global $wgWrReportDeleteMode;
835                                 if ($wgWrReportDeleteMode == 'deny') $errorMsg = wfMessage('wrreport-deletereport-deny')->text();
836                                 elseif ($wgWrReportDeleteMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = wfMessage('wrreport-deletereport-loggedin')->text();
837                                 elseif (!$delete_person_name || !$delete_reason_public) $errorMsg = wfMessage('wrreport-deletereport-incomplete')->text();
838                                 if ($errorMsg) {
839                                         $this->execute($par, 'deletepreview', $errorMsg);
840                                         return;
841                                 }
842
843                                 // "Delete" (update) entry
844                                 $dbr = wfGetDB(DB_MASTER);
845                                 $dbr->update(
846                                         'wrreport',
847                                         array(
848                                                 'delete_date' => date('c'),
849                                                 'delete_person_name' => $delete_person_name,
850                                                 'delete_person_ip' => $_SERVER['REMOTE_ADDR'],
851                                                 'delete_person_userid' => $delete_person_userid,
852                                                 'delete_person_username' => $delete_person_username,
853                                                 'delete_reason_public' => $delete_reason_public,
854                                                 'delete_invisible' => $delete_invisible ? 't' : 'f'
855                                         ),
856                                         array('id' => $reportid)
857                                 );
858
859                                 // Purge cache
860                                 $title->invalidateCache();
861                                 wrRecacheRegions();
862
863                                 // Show success message
864                                 $output->addWikiText(wfMessage('wrreport-deletereport-success', '[[' . $row['page_title'] . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $row['page_title'] . ']]')->text());
865                         }
866                         if ($action == 'deletepreview') {
867                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-before')->text());
868                                 $format = WRREPORT_COMPACT_PAGE;
869                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
870                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-after')->text());
871                                 $row['delete_date'] = date('c');
872                                 $row['delete_reason_public'] = $delete_reason_public;
873                                 $row['delete_person_name'] = $delete_person_name;
874                                 $row['delete_invisible'] = $delete_invisible;
875                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
876                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-form')->text());
877                                 $output->addHTML(wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible));
878                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-bottom')->text());
879                         }
880                 }
881
882                 // Action preview or store
883                 elseif ($action == 'preview' || $action == 'store') {
884                         $page_title = $request->getText('page_title');
885                         $date_report = $request->getText('date_report');
886                         $condition = $request->getText('condition');
887                         $description = $request->getText('description');
888                         $author_name = $request->getText('author_name');
889
890                         // condition
891                         $condition = (int) $condition; // force to be nummeric. -1 ... "keine Bewertung", 0 ... "Bitte eingeben", 1 to 5 ... "Sehr gut" to "Geht nicht"
892                         if ($condition < -1 or $condition > 5) $condition = 0; // invalid condition: Tread like 0.
893                         $condition_sql = NULL;
894                         if ($condition >= 1 and $condition <= 5) $condition_sql = $condition;
895
896                         // author_name
897                         $author_name = trim($author_name);
898
899                         // page_id
900                         $title = Title::newFromText($page_title);
901                         $page_id = $title->getArticleId();
902                         if ($page_id == 0) $page_id = NULL;
903
904                         // user_id
905                         global $wgUser;
906                         $author_userid = $wgUser->getId();
907                         if ($author_userid == 0) $author_userid = NULL; // to store a NULL value in the database if no user is logged in instead of 0.
908                         $author_username = $wgUser->getName();
909
910                         if ($action == 'store') {
911                                 // check conditions/permissions
912                                 $errorMsg = NULL;
913                                 global $wgWrReportMode;
914                                 global $wgWrReportBlackListAll;
915                                 global $wgWrReportBlackListStrangers;
916                                 if ($wgWrReportMode == 'summer') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-summer')->text());
917                                 elseif ($wgWrReportMode == 'deny') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-deny')->text());
918                                 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-loggedin')->text());
919                                 elseif (!$page_id) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-pagenotfound')->text());
920                                 elseif (in_array($page_title, $wgWrReportBlackListAll)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blacklist')->text());
921                                 elseif (!$wgUser->isLoggedIn() && in_array($page_title, $wgWrReportBlackListStrangers)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blackliststrangers')->text());
922                                 elseif ($condition == 0) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-choosecondition')->text());
923                                 elseif (!$wgUser->isLoggedIn()) {
924                                         if (!$description) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterdescription')->text());
925                                         elseif (!(stripos($description, 'http') === FALSE)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-nohttp')->text());
926                                         elseif (!$author_name) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterauthor')->text());
927                                 }
928
929                                 // check author name
930                                 if (!$errorMsg) {
931                                         $author_name_id = $wgUser->idFromName(strtolower($author_name));
932                                         if ($wgUser->isLoggedIn()) {
933                                                 if ($author_name_id != 0 && $author_name_id != $wgUser->getId())
934                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorused')->text());
935                                         } else {
936                                                 if ($author_name_id != 0)
937                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorlogin')->text());
938                                         }
939                                 }
940
941                                 // Chech whether identical reports are present
942                                 if (!$errorMsg) {
943                                         $dbr = wfGetDB(DB_SLAVE);
944                                         $cond = 'condition';
945                                         global $wgDBtype;
946                                         if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
947                                         $sqlConditions = array('page_id' => $page_id, 'date_report' => $date_report, $cond => $condition_sql, 'description' => $description, 'author_name' => $author_name);
948                                         $res = $dbr->select('wrreport', 'id', $sqlConditions);
949                                         if ($res->numRows() == 1) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-alreadysaved')->text());
950                                         $dbr->freeResult($res);
951                                 }
952
953                                 // Show error if any
954                                 if ($errorMsg) {
955                                         $this->execute($par, 'preview', $errorMsg);
956                                         return;
957                                 }
958
959                                 // Save entry
960                                 $dbr = wfGetDB(DB_MASTER);
961                                 $dbr->insert(
962                                         'wrreport',
963                                         array(
964                                                 'page_id' => $page_id,
965                                                 'page_title' => $page_title,
966                                                 'date_report' => $date_report,
967                                                 'date_entry' => date('c'),
968                                                 'date_invalid' => date('c', strtotime('+9 days')),
969                                                 $cond => $condition_sql,
970                                                 'description' => $description,
971                                                 'author_name' => $author_name,
972                                                 'author_ip' => $_SERVER['REMOTE_ADDR'],
973                                                 'author_userid' => $author_userid,
974                                                 'author_username' => $author_username
975                                                 // 'delete_*' => // use database defaults (NULL)
976                                         )
977                                 );
978
979                                 // Purge cache
980                                 $title->invalidateCache();
981                                 wrRecacheRegions();
982                                 wrUpdateWrReportCacheTable($page_id);
983
984                                 // Show success message
985                                 $output->addWikiText(wfMessage('wrreport-newreport-success', '[[' . $page_title . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $page_title . ']]')->text());
986                                 // We could redirect to result with the following line but we don't want to.
987                                 // $output->redirect($title->getFullURL() . '#' . wfMessage('wrreport-reports-sectionname')->text());
988                         }
989                         if ($action == 'preview') {
990                                 $output->addWikiText(wfMessage('wrreport-newreport-preview-top')->text());
991                                 $format = WRREPORT_COMPACT_PAGE;
992                                 $row = array_fill_keys(wrReportGetColumnNames(), NULL);
993                                 $row['page_id'] = $page_id;
994                                 $row['page_title'] = $page_title;
995                                 $row['date_report'] = $date_report;
996                                 $row['condition'] = $condition_sql;
997                                 $row['description'] = $description;
998                                 $row['author_name'] = $author_name;
999                                 $row['author_userid'] = $author_userid;
1000                                 $row['author_username'] = $author_username;
1001
1002                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1003                                 $output->addWikiText(wfMessage('wrreport-newreport-preview-middle')->text());
1004                                 $output->addHTML(wrReportFormRender(FALSE, $page_title, $date_report, $condition, $description, $author_name));
1005                                 $output->addWikiText(wfMessage('wrreport-newreport-preview-bottom')->text());
1006                         }
1007
1008                 }
1009
1010                 else die('Wrong action');
1011         }
1012 }
1013
1014
1015 ?>