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