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