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