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