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