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