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