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