fe28d0f8bd5e6dde860e765a5e416b3672147a91
[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         public static 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. array('Kategorie:Region' => 'Osttirol')
636                 global $wgContLang;
637                 $key_region = $wgContLang->getNSText(NS_CATEGORY) . ':Region';
638                 if (array_key_exists($key_region, $categories)) {
639                         // Do we have a feed entry of the region?
640                         // Example: select name from wrregion where page_id = 882;
641                         $res = $dbr->select('wrregion', 'name', array('page_id' => $title->getArticleID()));
642                         while ($row = $dbr->fetchObject($res)) {
643                                 // If yes, create the feed.
644                                 // 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.
645                                 global $wgWrReportFeedRoot;
646                                 global $wgOut; // class OutputPage
647                                 $wgOut->addFeedLink('atom', $wgWrReportFeedRoot . '/berichte/region/' . strtolower($row->name));
648                         }
649                 }
650
651                 // Add each page title that has been found
652                 $page_titles = array(); // array of Title objects
653                 foreach (explode("\n", $input) as $page_title) {
654                         $page_title = Title::newFromText(trim($page_title));
655                         if (!$page_title || !$page_title->exists()) continue;
656                         $page_titles[] = $page_title;
657                 }
658
659                 // 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
660                 $where_array = array('page.page_id = wrsledruncache.page_id');
661                 if (count($page_titles) > 0) {
662                         $mysql_page_titles = array();
663                         for ($i = 0; $i != count($page_titles); ++$i) $mysql_page_titles[] = "'" . mysql_real_escape_string($page_titles[$i]->getDBKey()) . "'";
664                         $where_array[] = 'page.page_title in (' . implode(', ', $mysql_page_titles) . ')';
665                 } else $where_array[] = 'false';
666                 $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'));
667
668                 global $wgUser;
669                 global $wgWrReportMode; // e.g. 'summer'
670                 global $wgWrReportBlackListAll;
671                 global $wgWrReportBlackListStrangers;
672                 global $wgDBtype;
673
674                 // Determine, whether the user is allowed to make a new report
675                 $userMayReport = ($wgWrReportMode == 'allow' || ($wgWrReportMode == 'loggedin' && $wgUser->isLoggedIn()));
676
677                 // Generate DOM for HTML
678                 $doc = new WrDOMDocument();
679                 $table = $doc->appendElement('table', array('class' => 'wikitable'));
680
681                 // Title
682                 $tr = $table->appendElement('tr');
683                 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_rental.png', 'alt' => wfMessage('wrreport-icon-sledrental')->text(), 'title' => wfMessage('wrreport-icon-sledrental')->text()));
684                 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_light.png', 'alt' => wfMessage('wrreport-icon-nightlight')->text(), 'title' => wfMessage('wrreport-icon-nightlight')->text()));
685                 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
686                 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_walk.png', 'alt' => wfMessage('wrreport-icon-walkupseparate')->text(), 'title' => wfMessage('wrreport-icon-walkupseparate')->text()));
687                 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_bus.png', 'alt' => wfMessage('wrreport-icon-publictransport')->text(), 'title' => wfMessage('wrreport-icon-publictransport')->text()));
688                 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
689                 if ($wgWrReportMode != 'summer') $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
690                 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-information')->text());
691                 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-walkuptime')->text());
692                 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-height')->text());
693                 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-length')->text());
694
695                 // Rows
696                 while ($row = $dbr->fetchObject($res)) {
697                         $title = Title::newFromRow($row);
698                         $tr = $table->appendElement('tr');
699
700                         $td = $tr->appendElement('td');
701                         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()));
702
703                         $td = $tr->appendElement('td');
704                         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()));
705
706                         $td = $tr->appendElement('td');
707                         if ($row->lift) $td->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
708
709                         $td = $tr->appendElement('td');
710                         if (!is_null($row->walkup_possible)) {
711                                 if ($row->walkup_possible) {
712                                         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()));
713                                 } else $td->appendElement('img', array('src' => '/vorlagen/s_nowalk.png', 'alt' => wfMessage('wrreport-icon-walkupnotpossible')->text(), 'title' => wfMessage('wrreport-icon-walkupnotpossible')->text()));
714                         }
715
716                         $td = $tr->appendElement('td');
717                         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()));
718
719                         $tr->appendElement('td')->appendElement('a', array('href' => $title->getLocalURL()))->appendText($title->getPrefixedText());
720
721                         if ($wgWrReportMode != 'summer') {
722                                 // Check rights
723                                 $userMayReportThis = $userMayReport;
724                                 if ($userMayReportThis) {
725                                         if (in_array($title->getText(), $wgWrReportBlackListAll)) $userMayReportThis = FALSE;
726                                         if (!$wgUser->isLoggedIn() && in_array($title->getText(), $wgWrReportBlackListStrangers)) $userMayReportThis = FALSE; // Title::getText() uses spaces instead of underscores
727                                 }
728
729                                 // Select condition
730                                 list($report_id, $condition, $date_report) = wrGetSledrunCondition($dbr, $row->page_id);
731                                 if (is_null($report_id)) $date = '';
732                                 else $date = strftime('%d.%m.', $date_report);
733
734                                 $td = $tr->appendElement('td');
735                                 if (isset(WrReport::$wrConditions[$condition])) {
736                                         $td->appendElement('a', array('href' => $title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-reports-sectionname')->text())))->appendText(WrReport::$wrConditions[$condition]);
737                                         $td->appendText(' ');
738                                         $small = $td->appendElement('small');
739                                         $small->appendText($date);
740                                         if ($userMayReportThis) {
741                                                 $small->appendText(' ');
742                                                 $small->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-newreport-sectionname')->text())))->appendText(wfMessage('wrreport-newreport-new')->text());
743                                         }
744                                 } else {
745                                         if ($userMayReportThis)
746                                                 $td->appendElement('small')->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Title::escapeFragmentForURL(wfMessage('wrreport-newreport-sectionname')->text())))->appendText(wfMessage('wrreport-newreport-please')->text());
747                                         else $td->appendText('--');
748                                 }
749                         }
750
751                         $td = $tr->appendElement('td');
752                         $info = $row->information_phone;
753                         if ($info) {
754                                 $info_parts = explode(';', $info);
755                                 $info_parts = explode('(', $info_parts[0], 2);
756                                 if (count($info_parts) == 2 && substr($info_parts[1], -1) == ')') {
757                                         $td->appendText($info_parts[0]);
758                                         $td->appendElement('span', array('class' => 'wrtelinfo'))->appendText(substr($info_parts[1], 0, -1));
759                                 } else $td->appendText($info);
760                         }
761
762                         $tr->appendElement('td')->appendText($row->walkup_time ? $row->walkup_time . ' min' : '');
763
764                         $tr->appendElement('td')->appendText(
765                                 ($row->bottom_elevation ? $row->bottom_elevation  : '') .
766                                 ($row->bottom_elevation && $row->top_elevation ? ' - ' : '') .
767                                 ($row->top_elevation ? $row->top_elevation : '') .
768                                 ($row->bottom_elevation || $row->top_elevation ? ' m' : ''));
769
770                         $tr->appendElement('td')->appendText($row->length ? $row->length . ' m' : '');
771                 }
772                 $dbr->freeResult($res);
773
774                 return array($doc->saveHTML(), 'noparse' => true, 'isHTML' => true);
775         }
776
777
778         /// \brief Is called when the tag <avatar>username</avatar> is encountered.
779         public static function avatarParserHook($input, $args, $parser, $frame) {
780                 $doc = new WrDOMDocument();
781                 $sla = new WrServicesLibravatar();
782
783                 try {
784                         // check user name
785                         if (is_null($input)) throw new InvalidArgumentException(wfMessage('wrreport-avatar-nousername')->text());
786                         $username = $parser->recursiveTagParse($input, $frame);
787                         $user = User::newFromName($username);
788                         if ($user === false) throw new InvalidArgumentException(wfMessage('wrreport-avatar-invalidusername', $username)->text());
789                         if ($user->getId() == 0) throw new InvalidArgumentException(wfMessage('wrreport-avatar-userunknown', $username)->text());
790
791                         // size attribute (optional)
792                         if (isset($args['size'])) $sla->setSize((int) $parser->recursiveTagParse($args['size'], $frame));
793
794                         // alt attribute (optional)
795                         $alt = wfMessage('wrreport-avatar-of', $username)->text();
796
797                         // create avatar (using the Services_Libravatar library to get avatar URL)
798                         $url = $sla->getUrl($user->getEmail());
799                         $doc->appendElement('img', array('src' => $url, 'alt' => $username, 'width' => $sla->getSize(), 'height' => $sla->getSize()));
800
801                 } catch (Exception $e) {
802                         $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-avatar-error', $e->getMessage())->text());
803                 }
804
805                 // return result (markerType => nowiki prevents wiki formatting of the result)
806                 $html = $doc->saveHTML($doc->firstChild);
807                 return array($html, 'markerType' => 'nowiki');
808         }
809
810
811
812 }
813 WrReport::initWrConditions();
814
815
816
817 // Special page
818 // ------------
819
820 /// Specal Page to show reports
821 class SpecialWrReport extends SpecialPage {
822         function __construct() {
823                 parent::__construct('wrreport');
824         }
825
826
827         /// \param $par Possibilities:
828         /// - action == 'view' (default)
829         /// - action == 'preview': Preview new report
830         /// - action == 'store': Store new report
831         /// - action == 'deletepreview': Preview the deleted record
832         /// - action == 'delete': Delete an existing report
833         /// - action == 'showerror': Shows the error and exits
834         /// \param $override_action If not NULL (default), it overrides the action in $par
835         /// \param $errorMsg UFT-8 encoded error message (in WikiText) to show on top of the page or NULL (default):
836         function execute($par, $override_action = NULL, $errorMsg = NULL) {
837                 $request = $this->getRequest();
838                 $output = $this->getOutput();
839         
840                 global $wgParser;
841
842                 $output->addModules('ext.wrreport');
843                 $this->setHeaders();
844
845                 // Get request data
846                 $action = $request->getText('action');
847                 if (!$action) {
848                         if ($request->getVal('preview')) $action = 'preview';
849                         elseif ($request->getVal('store')) $action = 'store';
850                         elseif ($request->getVal('deletepreview')) $action = 'deletepreview';
851                         elseif ($request->getVal('delete')) $action = 'delete';
852                         else $action = 'view';
853                 }
854                 if ($override_action) $action = $override_action;
855
856                 // Show error message
857                 if ($errorMsg || $action == 'showerror') {
858                         $output->addWikiText('<div class="errorbox">' . $errorMsg . "</div>\n");
859                         if ($action == 'showerror') return;
860                 }
861
862                 // Action view
863                 if ($action == 'view') {
864                         global $wgWrReportFeedRoot;
865                         $output->addFeedLink('atom', $wgWrReportFeedRoot . '/berichte/alle');
866                         $conditions = array('date_invalid > now()');
867                         $rows = wrReportGetReports($conditions);
868                         if (count($rows) == 0) $output->addHTML(wfMessage('wrreport-reports-none')->text());
869                         else {
870                                 $output->addWikiText(''); // this is necessary because otherwise $wgParser is not properly initialized but $wgParser is needed in the next line
871                                 $output->addHTML(wrReportTableRender($rows, WRREPORT_DETAIL, wrReportUserMayDelete(), $wgParser));
872                         }
873                 }
874
875                 // Action deletepreview or delete
876                 elseif ($action == 'deletepreview' || $action == 'delete') {
877                         $reportid = (int) $request->getText('reportid');
878                         if ($reportid == 0) {
879                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-noreport')->text());
880                                 return;
881                         }
882                         $rows = wrReportGetReports(array('id' => $reportid));
883                         if (count($rows) != 1) {
884                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-invalid')->text());
885                                 return;
886                         }
887                         $row = $rows[0];
888                         if (!is_null($row['delete_date'])) {
889                                 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-alreadydeleted')->text());
890                                 return;
891                         }
892                         $delete_reason_public = $request->getText('delete_reason_public');
893                         $delete_person_name = $request->getText('delete_person_name');
894                         $delete_invisible = $request->getText('delete_invisible') ? TRUE : FALSE;
895                         if ($action == 'delete') {
896                                 // page
897                                 $title = Title::newFromId($row['page_id']);
898
899                                 // user
900                                 global $wgUser;
901                                 $delete_person_userid = $wgUser->getId();
902                                 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.
903                                 $delete_person_username = $wgUser->getName();
904
905                                 // Check permissions - see also function wrReportUserMayDelete, that does also check permissions but does not return an error message.
906                                 $errorMsg = NULL;
907                                 global $wgWrReportDeleteMode;
908                                 if ($wgWrReportDeleteMode == 'deny') $errorMsg = wfMessage('wrreport-deletereport-deny')->text();
909                                 elseif ($wgWrReportDeleteMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = wfMessage('wrreport-deletereport-loggedin')->text();
910                                 elseif (!$delete_person_name || !$delete_reason_public) $errorMsg = wfMessage('wrreport-deletereport-incomplete')->text();
911                                 if ($errorMsg) {
912                                         $this->execute($par, 'deletepreview', $errorMsg);
913                                         return;
914                                 }
915
916                                 // "Delete" (update) entry
917                                 $dbr = wfGetDB(DB_MASTER);
918                                 $dbr->update(
919                                         'wrreport',
920                                         array(
921                                                 'delete_date' => date('c'),
922                                                 'delete_person_name' => $delete_person_name,
923                                                 'delete_person_ip' => $_SERVER['REMOTE_ADDR'],
924                                                 'delete_person_userid' => $delete_person_userid,
925                                                 'delete_person_username' => $delete_person_username,
926                                                 'delete_reason_public' => $delete_reason_public,
927                                                 'delete_invisible' => $delete_invisible ? 't' : 'f'
928                                         ),
929                                         array('id' => $reportid)
930                                 );
931
932                                 // Purge cache
933                                 $title->invalidateCache();
934                                 wrRecacheRegions();
935
936                                 // Show success message
937                                 $output->addWikiText(wfMessage('wrreport-deletereport-success', '[[' . $row['page_title'] . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $row['page_title'] . ']]')->text());
938                         }
939                         if ($action == 'deletepreview') {
940                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-before')->text());
941                                 $format = WRREPORT_COMPACT_PAGE;
942                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
943                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-after')->text());
944                                 $row['delete_date'] = date('c');
945                                 $row['delete_reason_public'] = $delete_reason_public;
946                                 $row['delete_person_name'] = $delete_person_name;
947                                 $row['delete_invisible'] = $delete_invisible;
948                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
949                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-form')->text());
950                                 $output->addHTML(wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible));
951                                 $output->addWikiText(wfMessage('wrreport-deletereport-preview-bottom')->text());
952                         }
953                 }
954
955                 // Action preview or store
956                 elseif ($action == 'preview' || $action == 'store') {
957                         $page_title = $request->getText('page_title');
958                         $date_report = $request->getText('date_report');
959                         $time_report = $request->getText('time_report');
960                         $condition = $request->getText('condition');
961                         $description = $request->getText('description');
962                         $author_name = $request->getText('author_name');
963
964                         // time_report
965                         $time_report = trim($time_report); // strip whitespace
966                         $matches = array();
967                         $hour = NULL;
968                         $minute = NULL;
969                         if (preg_match('/^[0-2]?[0-9]$/', $time_report)) {
970                                 // $time_report has 1 or 2 digits, e.g. 'h', or 'hh'.
971                                 $hour = intval($time_report);
972                                 $minute = 0;
973                         } elseif (preg_match('/^([0-2]?[0-9]):?([0-9]{2})$/', $time_report, $matches)) {
974                                 // $time_report has 3 or 4 digits, e.g. 'hmm' or 'hhmm' or 'h:mm' or 'hh:mm'.
975                                 $hour = intval($matches[1]);
976                                 $minute = intval($matches[2]);
977                         }
978                         if (!is_null($hour) && $hour >= 0 && $hour < 24 && $minute >= 0 && $minute < 60) $time_report = sprintf('%02d:%02d', $hour, $minute);
979                         else $time_report = NULL;
980
981                         // condition
982                         $condition = (int) $condition; // force to be nummeric. -1 ... "keine Bewertung", 0 ... "Bitte eingeben", 1 to 5 ... "Sehr gut" to "Geht nicht"
983                         if ($condition < -1 or $condition > 5) $condition = 0; // invalid condition: Tread like 0.
984                         $condition_sql = NULL;
985                         if ($condition >= 1 and $condition <= 5) $condition_sql = $condition;
986
987                         // author_name
988                         $author_name = trim($author_name);
989
990                         // page_id
991                         $title = Title::newFromText($page_title);
992                         $page_id = $title->getArticleId();
993                         if ($page_id == 0) $page_id = NULL;
994
995                         // user_id
996                         global $wgUser;
997                         $author_userid = $wgUser->getId();
998                         if ($author_userid == 0) $author_userid = NULL; // to store a NULL value in the database if no user is logged in instead of 0.
999                         $author_username = $wgUser->getName();
1000
1001                         if ($action == 'store') {
1002                                 // check conditions/permissions
1003                                 $errorMsg = NULL;
1004                                 global $wgWrReportMode;
1005                                 global $wgWrReportBlackListAll;
1006                                 global $wgWrReportBlackListStrangers;
1007                                 if ($wgWrReportMode == 'summer') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-summer')->text());
1008                                 elseif ($wgWrReportMode == 'deny') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-deny')->text());
1009                                 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-loggedin')->text());
1010                                 elseif (!$page_id) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-pagenotfound')->text());
1011                                 elseif (in_array($page_title, $wgWrReportBlackListAll)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blacklist')->text());
1012                                 elseif (!$wgUser->isLoggedIn() && in_array($page_title, $wgWrReportBlackListStrangers)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blackliststrangers')->text());
1013                                 elseif ($condition == 0) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-choosecondition')->text());
1014                                 elseif (!$wgUser->isLoggedIn()) {
1015                                         if (!$description) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterdescription')->text());
1016                                         elseif (!(stripos($description, 'http') === FALSE)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-nohttp')->text());
1017                                         elseif (!$author_name) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterauthor')->text());
1018                                 }
1019
1020                                 // check author name
1021                                 if (!$errorMsg) {
1022                                         $author_name_id = $wgUser->idFromName(strtolower($author_name));
1023                                         if ($wgUser->isLoggedIn()) {
1024                                                 if ($author_name_id != 0 && $author_name_id != $wgUser->getId())
1025                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorused')->text());
1026                                         } else {
1027                                                 if ($author_name_id != 0)
1028                                                         $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorlogin')->text());
1029                                         }
1030                                 }
1031
1032                                 // Chech whether identical reports are present
1033                                 if (!$errorMsg) {
1034                                         $dbr = wfGetDB(DB_SLAVE);
1035                                         $cond = 'condition';
1036                                         global $wgDBtype;
1037                                         if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
1038                                         $sqlConditions = array('page_id' => $page_id, 'date_report' => $date_report, 'time_report' => $time_report, $cond => $condition_sql, 'description' => $description, 'author_name' => $author_name);
1039                                         $res = $dbr->select('wrreport', 'id', $sqlConditions);
1040                                         if ($res->numRows() == 1) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-alreadysaved')->text());
1041                                         $dbr->freeResult($res);
1042                                 }
1043
1044                                 // Show error if any
1045                                 if ($errorMsg) {
1046                                         $this->execute($par, 'preview', $errorMsg);
1047                                         return;
1048                                 }
1049
1050                                 // Save entry
1051                                 $dbr = wfGetDB(DB_MASTER);
1052                                 $dbr->insert(
1053                                         'wrreport',
1054                                         array(
1055                                                 'page_id' => $page_id,
1056                                                 'page_title' => $page_title,
1057                                                 'date_report' => $date_report,
1058                                                 'time_report' => $time_report,
1059                                                 'date_entry' => date('c'),
1060                                                 'date_invalid' => date('c', strtotime('+9 days')),
1061                                                 $cond => $condition_sql,
1062                                                 'description' => $description,
1063                                                 'author_name' => $author_name,
1064                                                 'author_ip' => $_SERVER['REMOTE_ADDR'],
1065                                                 'author_userid' => $author_userid,
1066                                                 'author_username' => $author_username
1067                                                 // 'delete_*' => // use database defaults (NULL)
1068                                         )
1069                                 );
1070
1071                                 // Purge cache
1072                                 $title->invalidateCache();
1073                                 wrRecacheRegions();
1074                                 wrUpdateWrReportCacheTable($page_id);
1075
1076                                 // Show success message
1077                                 $output->addWikiText(wfMessage('wrreport-newreport-success', '[[' . $page_title . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $page_title . ']]')->text());
1078                                 // We could redirect to result with the following line but we don't want to.
1079                                 // $output->redirect($title->getFullURL() . '#' . wfMessage('wrreport-reports-sectionname')->text());
1080                         }
1081                         if ($action == 'preview') {
1082                                 $output->addWikiText(wfMessage('wrreport-newreport-preview-top')->text());
1083                                 $format = WRREPORT_COMPACT_PAGE;
1084                                 $row = array_fill_keys(wrReportGetColumnNames(), NULL);
1085                                 $row['page_id'] = $page_id;
1086                                 $row['page_title'] = $page_title;
1087                                 $row['date_report'] = $date_report;
1088                                 $row['time_report'] = $time_report;
1089                                 $row['condition'] = $condition_sql;
1090                                 $row['description'] = $description;
1091                                 $row['author_name'] = $author_name;
1092                                 $row['author_userid'] = $author_userid;
1093                                 $row['author_username'] = $author_username;
1094
1095                                 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1096                                 $output->addWikiText(wfMessage('wrreport-newreport-preview-middle')->text());
1097                                 $output->addHTML(wrReportFormRender(FALSE, $page_title, $date_report, $time_report, $condition, $description, $author_name));
1098                                 $output->addWikiText(wfMessage('wrreport-newreport-preview-bottom')->text());
1099                                 if ($author_userid)
1100                                         $output->addWikiText(wfMessage('wrreport-newreport-preview-bottom-loggedin')->text());
1101                                 else
1102                                         $output->addWikiText(wfMessage('wrreport-newreport-preview-bottom-anonymous')->text());
1103                         }
1104
1105                 }
1106
1107                 else die('Wrong action');
1108         }
1109 }
1110
1111
1112 ?>