2 // File encoding: utf-8
3 // This extension does not depend on other extensions.
5 // Variables that can be changed in LocalSettings.php:
6 // $wgWrReportMode = 'allow'; // 'summer', 'allow', 'loggedin', 'deny'
7 // $wgWrReportBlackListAll = array(); // array of page names where reports disallowed for all users. Example: array('Birgitzer Alm (vom Adelshof)');
8 // $wgWrReportBlackListStrangers = array(); // array of page names where reports are disallowed for not logged in users
9 // $wgWrReportDeleteMode = 'loggedin'; // 'allow', 'loggedin', 'deny'
10 // $wgWrReportFeedRoot = 'http://www.winterrodeln.org/feed'; // root URL of the Winterrodeln feed without trailing slash
13 // The following tags are supported:
15 // Creates an overview table of all sledruns specified (one per line) in the tag.
17 // <bahnenregiontabelle/>
18 // Like <bahnentabelle> but includes all sledruns that are in the region of the current page
19 // or in the region specified by one of the following parameters:
20 // <bahnenregiontabelle wiki="Innsbruck" /> (refers to region represented by the MediaWiki Title name)
21 // <bahnenregiontabelle region_id="3" /> (refers to id in the wrregion table)
22 // <bahnenregiontabelle region_name="Innsbruck" /> (refers to name in the wrregion table)
23 // This tag does not accept any contents.
26 // Shows an overview of the sledrun reports of the current page.
28 // <bahnberichtformular/>
29 // Creates the form that is used to enter sledrun reports.
31 // <rodelbahntabelle/>
32 // Generates a list of sledrun entries in a flexible way.
33 // Each line (entry) either add sledruns or removes sledruns.
34 // Without entries, the table contains no sledruns.
38 // <rodelbahntabelle/>
40 // Sledrun "Rumer Alm" and sledrun "Juifenalm"
42 // <rodelbahn>Juifenalm</rodelbahn>
43 // <rodelbahn>Rumer Alm</rodelbahn>
44 // </rodelbahntabelle>
46 // All sledruns in region Innsbruck thats entries are not "under construction".
47 // The name of the region has to correspond to a name (column name)
48 // in the table wrregion.
50 // <region>Innsbruck</region>
51 // </rodelbahntabelle>
53 // Same as above but excluding the sledrun "Rumer Alm":
55 // <region>Innsbruck</region>
56 // <rodelbahn operation="-">Rumer Alm</rodelbahn>
57 // </rodelbahntabelle>
59 // All sledruns thats entries are "under construction"
61 // <rodelbahnen in_arbeit="ja"/>
62 // </rodelbahntabelle>
65 // * in_arbeit: values "ja", "nein" (default for <region> and <rodelbahnen>), "*" (default for <rodelbahn>)
66 // Just include the sledrun(s) if the condition is fulfilled.
67 // * operation: values "+" (add the sledrun(s) to the set, default), "-" (subtract the sledrun(s) from the set)
68 // Attributes that may be implemented later
69 // * beleuchtungstage: values "0", "unknown" (is null), ">0" (excludes null), "7", "*" (includes null)
70 // Just include the sledrun(s) if the condition is fulfilled.
77 // Constants for wrReportTableRender
78 define('WRREPORT_COMPACT_PAGE', 1); ///< includes the page name
79 define('WRREPORT_COMPACT', 2); ///< shown on a single page
80 define('WRREPORT_DETAIL', 3); ///< more columns
87 class WrDOMDocument extends DOMDocument {
88 function __construct() {
89 parent::__construct('1.0', 'utf-8');
90 $this->registerNodeClass('DOMElement', 'WrDOMElement');
93 /// Creates and adds the element with the given tag name and returns it.
94 /// Additionally, it calls setAttribute($key, $value) for every entry
96 function appendElement($tagName, $attributes=array()) {
97 $child = $this->appendChild($this->createElement($tagName));
98 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
105 class WrDOMElement extends DOMElement {
107 /// Creates and adds the element with the given tag name and returns it
108 /// Additionally, it calls setAttribute($key, $value) for every entry
110 function appendElement($tagName, $attributes=array()) {
111 $child = $this->appendChild($this->ownerDocument->createElement($tagName));
112 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
116 /// Adds any UTF-8 string as content of the element - it will be escaped.
117 function appendText($text) {
118 return $this->appendChild($this->ownerDocument->createTextNode($text));
121 // Appends a CDATASections to the element. This can be used to include
122 // raw (unparsed) HTML to the DOM tree as it is necessary because
123 // $parser->recursiveTagParse does not always escape & characters.
124 // (see https://bugzilla.wikimedia.org/show_bug.cgi?id=55526 )
125 // Workaround: Use a CDATA section. When serializing with $doc->saveHTML,
126 // the <![CDATA[...]]> is returned as ... .
127 // However, we end up having unescaped & in the output due to this bug in recursiveTagParse.
128 function appendCDATA($data) {
129 return $this->appendChild($this->ownerDocument->createCDATASection($data));
138 /// Exception type that is used internally by WrReport
139 class WrReportException extends Exception {}
143 // Fast version of Services_Libravatar
144 // -----------------------------------
146 /// This is a fast version of Services_Libravatar by omitting the DNS
147 /// lookup and always falling back to libravatar.org
148 class WrServicesLibravatar extends Services_Libravatar {
149 function __construct() {
151 $this->setDefault('monsterid');
152 $this->setHttps(true);
156 protected function srvGet($domain, $https = false) {
157 if ($https === true) return 'seccdn.libravatar.org';
158 return 'cdn.libravatar.org';
162 public function getSize() {
172 /// Forces a regeneration of region overview pages ('Tirol', 'Vorarlberg', ...)
173 function wrRecacheRegions() {
174 $dbr = wfGetDB(DB_REPLICA);
175 // SELECT cl_from FROM categorylinks where cl_to = 'Region'
176 $res = $dbr->select('categorylinks', 'cl_from', array('cl_to' => 'Region'));
178 while ($row = $dbr->fetchObject($res)) $page_ids[] = $row->cl_from;
179 $dbr->freeResult($res);
181 $titles = Title::newFromIDs($page_ids);
182 foreach ($titles as $title) $title->invalidateCache();
186 /// Returns the tuple ($report_id, $sledrun_condition, $date_report)
187 /// $date_report is NULL or a time as returned by strtotime
188 /// Expects a database connection ($dbr = wfGetDB(DB_REPLICA);)
189 /// and a page_id describung the page where the condition should be returned.
190 /// If no condition is found, (NULL, NULL, NULL) is returned.
191 function wrGetSledrunCondition($dbr, $page_id) {
192 // 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;
193 $cres = $dbr->select(
195 array('wrreport.id as report_id', '`condition`', 'date_report'),
196 array('page_id' => $page_id, '`condition` is not null', 'date_invalid > now()', 'delete_date is null'),
197 'wrReportConditionRender',
198 array('ORDER BY' => 'date_report desc, date_entry desc', 'LIMIT' => '1')
200 if ($cres->numRows() <= 0) {
205 $crow = $dbr->fetchObject($cres);
206 $report_id = $crow->report_id;
207 $condition = $crow->condition;
208 $date_report = strtotime($crow->date_report);
210 $dbr->freeResult($cres);
211 return array($report_id, $condition, $date_report);
215 /// Updates the line of the wrreportcache table that corresponds to the $page_id parameter
216 function wrUpdateWrReportCacheTable($page_id) {
217 // Determine the new content for the row that should be updated
218 $dbr = wfGetDB(DB_REPLICA);
219 list($report_id, $condition, $date_report) = wrGetSledrunCondition($dbr, $page_id);
220 $rows = wrReportGetReports(array('id' => $report_id), 1);
222 // Delete the old content (if any)
223 $dbw = wfGetDB(DB_MASTER);
224 $dbw->delete('wrreportcache', array('page_id' => $page_id));
226 // Insert the updated row
227 if (count($rows) == 1) {
229 $dbw->insert('wrreportcache', array(
230 'page_id' => $row['page_id'],
231 'page_title' => $row['page_title'],
232 'report_id' => $row['id'],
233 'date_report' => $row['date_report'],
234 '`condition`' => $row['condition'],
235 'description' => $row['description'],
236 'author_name' => $row['author_name'],
237 'author_username' => (is_null($row['author_userid']) ? NULL : $row['author_username'])));
246 /// \brief Returns a form to enter a report (string containing HTML).
248 /// All parameters have to be UTF-8 encoded.
249 /// \param $page_title Name of the sledrun.
250 /// \param $condition 1 to 5 for normal condition, 0 or NULL for missing condition and -1 for intentionally no condition.
251 /// \return UTF-8 encoded HTML form
252 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) {
253 $doc = new WrDOMDocument();
256 // Info about special page
257 $specialPageName = wfMessage('wrreport')->text(); // 'Bahnberichte'
258 $title = Title::newFromText($specialPageName, NS_SPECIAL);
259 $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
262 $form = $doc->appendElement('form', array('action' => $specialPageUrl, 'method' => 'post'));
264 // table (for layout of form elements)
265 $table = $form->appendElement('table', array('class' => 'wrreportform'));
268 $tr = $table->appendElement('tr');
269 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
270 $td = $tr->appendElement('td');
271 $td->appendText($page_title);
272 $td->appendElement('input', array('type' => 'hidden', 'name' => 'page_title', 'value' => $page_title));
275 $tr = $table->appendElement('tr');
276 $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-date')->text());
277 $td = $tr->appendElement('td');
278 $select = $td->appendElement('select', array('name' => 'date_report'));
280 wfMessage('wrreport-date-today')->text(),
281 wfMessage('wrreport-date-yesterday')->text(),
282 wfMessage('wrreport-date-2daysbefore')->text(),
283 wfMessage('wrreport-date-3daysbefore')->text(),
284 wfMessage('wrreport-date-4daysbefore')->text());
285 $date_selected = false;
286 $time = time(); // number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
287 for ($day=0; $day!=5; ++$day) {
288 $date = strtotime("-$day days", $time);
289 $date_f = strftime("%Y-%m-%d", $date); // Formats it according to locale, that is set to CET.
290 $option = $select->appendElement('option', array('value' => $date_f));
291 if ((is_null($date_report) && $day == 0) || (!is_null($date_report) && $date_report == $date_f)) {
292 $option->setAttribute('selected', 'selected');
293 $date_selected = true;
295 $option->appendText($daynames[$day] . ' (' . strftime('%d.%m.', $date) . ')');
297 if (!$date_selected) { // note: if $date_report is null $date_selected is true here
298 $option = $select->appendElement('option', array('value' => $date_report, 'selected' => 'selected'));
299 $option->appendText($date_report);
303 $tr = $table->appendElement('tr');
304 $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-time')->text());
305 $td = $tr->appendElement('td');
306 $td->appendElement('input', array('name' => 'time_report', 'maxlength' => '5', 'size' => '5', 'class' => 'mw-ui-input mw-ui-input-inline', 'value' => $time_report));
307 $td->appendText(' ');
308 $td->appendText('Uhr');
309 $td->appendText(' ');
310 $td->appendElement('span', array('class' => 'wrcomment'))->appendText("(z.B. '14', '1400' oder '14:00'. Optional.)");
313 $tr = $table->appendElement('tr');
314 $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
315 $td = $tr->appendElement('td');
316 $select = $td->appendElement('select', array('name' => 'condition', 'required' => 'required'));
317 $option = $select->appendElement('option', array('value' => '0'));
318 $option->appendText(wfMessage('wrreport-condition-select')->text());
319 foreach (WrReport::$wrConditions as $condition_num) {
320 $option = $select->appendElement('option', array('value' => (string) $condition_num));
321 if ($condition == $condition_num) $option->setAttribute('selected', 'selected');
322 $option->appendText(WrReport::getWrConditionText($condition_num));
324 $option = $select->appendElement('option', array('value' => '-1'));
325 if ($condition == -1) $option->setAttribute('selected', 'selected');
326 $option->appendText(wfMessage('wrreport-condition-no')->text());
329 $tr = $table->appendElement('tr');
330 $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-description')->text());
331 $tr->appendElement('td')->appendElement('textarea', array('name' => 'description', 'class' => /* 'fullwidth' */ 'mw-ui-input', 'rows' => '7', 'required' => 'required'))->appendText($description);
334 $tr = $table->appendElement('tr');
335 $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-author')->text());
336 $tr->appendElement('td')->appendElement('input', array('name' => 'author_name', 'class' => /* fullwidth */ 'mw-ui-input', 'maxlength' => '30', 'value' => $author_name));
339 // I would like to do it this way, but due to a bug of internet explorer, the <button> element is not useable.
340 // $buttons = '<button name="action" type="submit" value="preview">Vorschau';
341 // if ($hide_save_button) $buttons .= ' & Speichern';
342 // $buttons .= '</button>';
343 // if (!$hide_save_button) $buttons .= '<button name="action" type="submit" value="store">Speichern</button>';
344 // Workaround: User <input type="submit"/>
345 $tr = $table->appendElement('tr');
346 $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-submit')->text());
347 $td = $tr->appendElement('td');
348 if ($hide_save_button) {
349 $input = $td->appendElement('input', array('name' => 'preview', 'type' => 'submit', 'class' => 'mw-ui-button mw-ui-progressive', 'value' => wfMessage('wrreport-newreport-next')->text()));
351 $input = $td->appendElement('input', array('name' => 'preview', 'type' => 'submit', 'class' => 'mw-ui-button', 'value' => wfMessage('wrreport-newreport-preview')->text()));
352 $td->appendElement('input', array('name' => 'store', 'type' => 'submit', 'class' => 'mw-ui-button mw-ui-constructive', 'value' => wfMessage('wrreport-newreport-save')->text()));
355 return $doc->saveHTML($form);
359 /// \brief Renders the form to delete a report
361 /// All in and output strings should be/are UTF-8 encoded.
362 /// \param $reportid the id of the report that is going to be deleted
363 /// \param $delete_person_name name of the person that wants to delete the report (form field)
364 /// \param $delete_reason_public publically visible reason for deleting the entry.
365 /// \param $delete_invisible don't show the report as being deleted
366 /// \return UTF-8 encoded HTML form
367 function wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible) {
368 $doc = new WrDOMDocument();
371 // Info about special page
372 $specialPageName = wfMessage('wrreport')->text(); // 'Bahnberichte'
373 $title = Title::newFromText($specialPageName, NS_SPECIAL);
374 $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
377 $form = $doc->appendElement('form', array('action' => $specialPageUrl, 'method' => 'post'));
379 // table (for layout of form elements)
380 $table = $form->appendElement('table', array('class' => 'wrreportform', 'summary' => wfMessage('wrreport-deletereport-tablesummary')->text()));
382 // delete_reason_public
383 $tr = $table->appendElement('tr');
384 $tr->appendElement('th')->appendText(wfMessage('wrreport-deletereport-reason')->text());
385 $tr->appendElement('td')->appendElement('textarea', array('name' => 'delete_reason_public', 'cols' => '50', 'rows' => '7'))->appendText($delete_reason_public);
387 // delete_person_name
388 $tr = $table->appendElement('tr');
389 $tr->appendElement('th')->appendText(wfMessage('wrreport-deletereport-name')->text());
390 $tr->appendElement('td')->appendElement('input', array('name' => 'delete_person_name', 'maxlength' => '30', 'size' => '30', 'value' => $delete_person_name));
393 $tr = $table->appendElement('tr');
394 $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-action')->text());
395 $td = $tr->appendElement('td');
396 $td->appendElement('input', array('name' => 'deletepreview', 'type' => 'submit', 'class' => 'mw-ui-button', 'value' => wfMessage('wrreport-newreport-preview')->text()));
397 $td->appendElement('input', array('name' => 'delete', 'type' => 'submit', 'class' => 'mw-ui-button mw-ui-destructive', 'value' => wfMessage('wrreport-deletereport-delete')->text()));
400 $input = $td->appendElement('input', array('name' => 'reportid', 'type' => 'hidden', 'value' => (string) $reportid));
401 // delete_invisible - who is allowed to do so?
402 // $td->appendElement('input', array('name' => 'delete_invisible', 'type' => 'hidden', 'value' => (string) $delete_invisible));
404 return $doc->saveHTML($form);
408 /// \brief Generates the DOM of the table header ("private" sub-function of wrReportTableRender)
410 /// \param $table table WrDOMElement where the header should be appended
411 /// \param $format row format like WRREPORT_COMPACT
412 /// \param $showActions boolean to indicate whether an actions column should be created
413 /// \return WrDOMElement of the HTML table header
414 function wrReportTableTitleRender($table, $format, $showActions) {
415 $tr = $table->appendElement('tr');
416 $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-date-trip')->text());
417 if ($format != WRREPORT_COMPACT) $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
418 $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
419 $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-description')->text());
420 $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-author')->text());
421 if ($format == WRREPORT_DETAIL) $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-date-entry')->text());
422 if ($showActions) $tr->appendElement('th')->appendText(wfMessage('wrreport-reports-action')->text());
427 /// \brief Generates the DOM of a table row ("private" sub-function of wrReportTableRender)
429 /// \param $table table WrDOMElement where the row should be appended
430 /// \param $row associative array of table columns like one row in the wrreport table
431 /// \param $format row format like WRREPORT_COMPACT
432 /// \param $showActions boolean to indicate whether an actions column should be created
433 /// \param $parser Parser instance of a Parser class that can be used to parse the condition
434 /// \return WrDOMElement of the HTML table row
435 function wrReportTableRowRender($table, $row, $format, $showActions, $parser) {
436 $tr = $table->appendElement('tr');
438 // $row['date_report'] and $row['time_report']
439 $date_report = strtotime($row['date_report']);
440 $date_report = wfMessage(Language::$mWeekdayAbbrevMsgs[(int) date('w', $date_report)])->text() . strftime(', %d.%m.', $date_report);
441 $td = $tr->appendElement('td');
442 $td->appendText($date_report);
443 if ($row['time_report']) {
444 $td->appendText(' ');
445 $td->appendElement('span', array('class' => 'wrcomment'))->appendText(date('H:i', strtotime($row['time_report'])));
448 // $row['page_title']
449 if ($format != WRREPORT_COMPACT) {
450 $title = Title::newFromText($row['page_title']);
451 $tr->appendElement('td')->appendCDATA(Linker::link($title));
455 $condition_text = '---';
456 if (in_array($row['condition'], WrReport::$wrConditions)) $condition_text = WrReport::getWrConditionText($row['condition']);
457 $td = $tr->appendElement('td');
458 if ($row['delete_date']) $td->appendElement('em')->appendText(wfMessage('wrreport-deletereport-deleted')->text());
459 else $td->appendText($condition_text);
461 // $row['description']
462 $td = $tr->appendElement('td', array('class' => 'wrreportdescription'));
463 if ($row['delete_date']) $td->appendElement('em')->appendText(wfMessage('wrreport-deletereport-deleted')->text());
465 // for registered users, use wikitext formatting
466 if (is_null($row['author_userid'])) $td->appendText($row['description']);
468 $html = $parser->recursiveTagParse($row['description']);
469 $td->appendCDATA($html);
473 // $row['author_name']
474 $td = $tr->appendElement('td');
475 if ($row['delete_date']) $td->appendElement('em')->appendText(wfMessage('wrreport-deletereport-deleted')->text());
477 if (!is_null($row['author_userid'])) {
478 // find user's email ($user->getEmail())
479 $user = User::newFromId($row['author_userid']);
481 // create avatar (using the Services_Libravatar library to get avatar URL)
482 $sla = new WrServicesLibravatar();
483 $url = $sla->getUrl($user->getEmail());
485 // create img tag for the avatar
486 $td->appendElement('img', array('src' => $url, 'alt' => $row['author_name'], 'width' => $sla->getSize(), 'height' => $sla->getSize()));
487 $td->appendText(' ');
490 $title = $user->getUserPage();
491 if ($title->exists()) {
492 $td->appendCDATA(Linker::link($title, $row['author_name']));
494 $td->appendText($row['author_name']);
496 $td->appendText(' ');
498 // get number of sledrun reports
499 $td->appendElement('span', array('class' => 'wrreportcount'))
500 ->appendText((string) WrReport::getUserSeldrunReportCount($user->getId()));
503 $td->appendText($row['author_name']);
507 // $row['date_entry']
508 if ($format == WRREPORT_DETAIL) {
509 $td = $tr->appendElement('td');
510 $td->appendText(date('d.m. ', strtotime($row['date_entry'])));
511 $td->appendElement('span', array('class' => 'wrcomment'))->appendText(date('H:i', strtotime($row['date_entry'])));
515 // wiki/Spezial:Bahnberichte?action=deletepreview&reportid=42
517 $td = $tr->appendElement('td');
518 if (!isset($row['delete_date'])) {
519 $specialPageName = wfMessage('wrreport')->text(); // 'Bahnberichte'
520 $title = Title::newFromText($specialPageName, NS_SPECIAL);
521 $specialPageUrl = $title->getLocalURL(); // e.g. '/wiki/Spezial:Bahnberichte'
522 $td->appendElement('a', array('href' => $specialPageUrl . '?action=deletepreview&reportid=' . $row['id']))
523 ->appendText(wfMessage('wrreport-deletereport-delete')->text() . '...');
530 /// \brief Renders the report table. Call wrReportGetReports for the $rows parameter.
532 /// \param $rows array of associative row arrays
533 /// \param $format row format like WRREPORT_TABLE_SHORT
534 function wrReportTableRender($rows, $format, $showActions, $parser) {
535 $doc = new WrDOMDocument();
536 $table = $doc->appendElement('table', array('class' => 'wrreporttable'));
537 wrReportTableTitleRender($table, $format, $showActions);
538 foreach ($rows as $key => $row) wrReportTableRowRender($table, $row, $format, $showActions, $parser);
539 return $doc->saveHTML($table);
543 /// Returns an array with column names
544 function wrReportGetColumnNames() {
545 return array('id', 'page_id', 'page_title', 'date_report', 'time_report', 'date_entry', 'date_invalid', 'condition', 'description', 'author_name', 'author_userid', 'author_username', 'delete_date', 'delete_person_name', 'delete_person_ip', 'delete_person_userid', 'delete_person_username', 'delete_reason_public', 'delete_invisible');
549 /// \brief Returns reports as associative array.
552 /// $conditions = array('page_title' => 'Birgitzer Alm', 'date_invalid > now()');
553 /// $limit = 1; // or NULL for no limit
554 function wrReportGetReports($conditions, $limit=NULL) {
555 $dbr = wfGetDB(DB_REPLICA);
556 $columns = wrReportGetColumnNames();
558 if ($wgDBtype == "mysql") // "condition" is a reserved word in mysql
559 for ($i = 0; $i != count($columns); ++$i) $columns[$i] = sprintf('`%s`', $columns[$i]);
560 $options = array('ORDER BY' => 'date_report desc, date_entry desc');
561 if (!is_null($limit)) $options['LIMIT'] = $limit;
562 $res = $dbr->select('wrreport', $columns, $conditions, 'wrReportGetReports', $options);
564 while ($row = $dbr->fetchRow($res)) $result[] = $row;
565 $dbr->freeResult($res);
570 /// \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));
572 /// If no condition is present, array(NULL, NULL) is returned
573 function wrReportConditionRender($page_title) {
574 $dbr = wfGetDB(DB_REPLICA);
577 // 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;
578 if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
581 array('wrreport.id as report_id', $cond, 'date_report'),
582 array('page_title' => $page_title, "$cond is not null", 'date_invalid > now()', 'delete_date is null'),
583 'wrReportConditionRender',
584 array('ORDER BY' => 'date_report desc, date_entry desc', 'LIMIT' => '1')
586 if ($res->numRows() <= 0) {
587 $dbr->freeResult($res);
588 return array(NULL, NULL);
590 $row = $dbr->fetchObject($res);
591 $date = $row->date_report;
592 if ($date) $date = strtotime($date);
593 $dbr->freeResult($res);
594 return array($row->condition, $date);
598 /// \brief Returns true if the user is allowed to delete reports (in general)
599 function wrReportUserMayDelete() {
601 global $wgWrReportDeleteMode;
602 return $wgWrReportDeleteMode == 'allow' || ($wgWrReportDeleteMode == 'loggedin' && $wgUser->isLoggedIn());
607 // tag extension hooks
608 // -------------------
611 // Conditions: 1 => 'Sehr gut', 2 => 'Gut', 3 => 'Mittelmäßig', 4 => 'Schlecht', 5 => 'Geht nicht'
612 public static $wrConditions = array(1, 2, 3, 4, 5);
615 /// Returns the translated text of a specified numeric condition
616 public static function getWrConditionText(int $condition): string {
617 return wfMessage('wrreport-condition-' . $condition)->text();
621 /// Returns the number of sledrun reports issued by a user with the given id.
622 public static function getUserSeldrunReportCount($user_id) {
623 $dbr = wfGetDB(DB_REPLICA);
624 // select count(*) from wrreport where author_userid = 1 and delete_date is null and `condition` is not null;
625 $res = $dbr->select('wrreport', 'count(*)', array('author_userid' => $user_id, 'delete_date' => null, '`condition` is not null'));
626 $row = $res->fetchRow();
628 $dbr->freeResult($res);
633 // Parser Hook Functions
634 // ---------------------
636 public static function ParserFirstCallInitHook(Parser &$parser) {
637 $parser->setHook('bahnberichtformular', 'WrReport::bahnberichtformularParserHook');
638 $parser->setHook('bahnberichte', 'WrReport::bahnberichteParserHook');
639 $parser->setHook('bahnentabelle', 'WrReport::bahnentabelleParserHook');
640 $parser->setHook('bahnenregiontabelle', 'WrReport::bahnenregiontabelleParserHook');
641 $parser->setHook('rodelbahntabelle', 'WrReport::rodelbahntabelleParserHook');
642 $parser->setHook('avatar', 'WrReport::avatarParserHook');
646 /// \brief Is called when the tag <bahnberichtformular/> is encountered.
648 /// The current page name is taken.
649 public static function bahnberichtformularParserHook($input, array $args, Parser $parser, PPFrame $frame) {
651 $wgUser = $parser->getUser();
653 if ($wgUser->isLoggedIn()) {
654 $author_name = $wgUser->getRealName();
655 if (!$author_name) $author_name = $wgUser->getName();
658 global $wgWrReportMode;
659 global $wgWrReportBlackListAll;
660 global $wgWrReportBlackListStrangers;
662 // is the form allowed to be shown?
664 if ($wgWrReportMode == 'summer') $error_key = 'wrreport-newreport-summer';
665 elseif ($wgWrReportMode == 'deny') $error_key = 'wrreport-newreport-deny';
666 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $error_key = 'wrreport-newreport-loggedin';
667 elseif (in_array($parser->getTitle()->getText(), $wgWrReportBlackListAll)) $error_key = 'wrreport-newreport-blacklist';
668 elseif (!$wgUser->isLoggedIn() && in_array($parser->getTitle()->getText(), $wgWrReportBlackListStrangers)) $error_key = 'wrreport-newreport-blackliststrangers';
671 if (!is_null($error_key)) {
672 $doc = new WrDOMDocument();
673 $p = $doc->appendElement('p')->appendElement('em')->appendText(wfMessage($error_key)->text());
674 return $doc->saveHTML($p);
677 // Calling "$title = $parser->getTitle(); $title->invalidateCache();" doesn't help here to force regeneration
678 // However, this would not be the best solution because the page has to be re-rendered only at midnight
680 // In the following line, $author_name was replaced by NULL to prevent a bug, where the wrong author_name
681 // is shown due to caching (see ticket #35).
682 return array(wrReportFormRender(TRUE, $parser->getTitle()->getText(), NULL, NULL, NULL, NULL, NULL), 'markerType' => 'nowiki');
686 /// \brief Is called when the tag <bahnberichte/> is encountered.
688 /// The current page name is taken.
689 public static function bahnberichteParserHook($input, array $args, Parser $parser, PPFrame $frame) {
690 $parser->getOutput()->addModules('ext.wrreport'); // getOutput() returns class ParserOutput
691 $title = $parser->getTitle();
692 $page_id = $title->getArticleID();
696 global $wgOut; // class OutputPage
697 global $wgWrReportFeedRoot;
698 $wgOut->addFeedLink('atom', $wgWrReportFeedRoot . '/berichte/bahn/' . strtolower($title->getPartialURL()));
700 $conditions = array('page_id' => $page_id, 'date_invalid > now()');
701 $rows = wrReportGetReports($conditions);
703 if (count($rows) == 0) return wfMessage('wrreport-reports-none')->text();
704 return array(wrReportTableRender($rows, WRREPORT_COMPACT, wrReportUserMayDelete(), $parser), 'markerType' => 'nowiki');
708 /// Returns the region details of the region specifed in $conditions.
709 /// region_id (as in the database), region name (as in the database), and region border (as WKB).
710 /// conditions is an array that's given to the where clause
711 private static function getRegionDetails($conditions) {
712 // Example: SELECT name FROM wrregion WHERE page_id = 882;
713 $dbr = wfGetDB(DB_REPLICA);
714 $res = $dbr->select('wrregion', array('id', 'name', 'aswkb(border)'), $conditions);
715 if ($dbr->numRows($res) == 1) {
716 $row = $dbr->fetchRow($res);
717 return array($row[0], $row[1], $row[2]); // region_id, region_name, region_border_wkb
719 $dbr->freeResult($res);
720 return array(null, null, null);
724 /// Returns the region details if the specified title is one.
725 /// region_id (as in the database), region name (as in the database), and region border (as WKB).
726 private static function getPageRegion($title) {
727 $categories = $title->getParentCategories(); // e.g. array('Kategorie:Region' => 'Osttirol')
729 $key_region = $wgContLang->getNSText(NS_CATEGORY) . ':Region';
730 if (array_key_exists($key_region, $categories)) {
731 return WrReport::getRegionDetails(array('page_id' => $title->getArticleID()));
733 return array(null, null, null);
737 /// Adds a region feed to the current page
738 private static function addRegionFeedLink($title) {
739 list($region_id, $region_name, $region_border_wkb) = WrReport::getPageRegion($title);
740 if (is_null($region_name)) return;
741 global $wgWrReportFeedRoot;
742 global $wgOut; // class OutputPage
743 $wgOut->addFeedLink('atom', $wgWrReportFeedRoot . '/berichte/region/' . strtolower($region_name));
747 /// Creates the HTML of the <bahnentabelle>, <bahnenregiontabelle> and <rodelbahntabelle> tags.
748 private static function createBahnentabelle($page_titles) {
749 $dbr = wfGetDB(DB_REPLICA);
751 // 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,
752 // c.sled_rental, c.information_phone, s.show_status, r.status, r.last_check, r.last_update
753 // FROM (`page` p JOIN wrsledruncache c ON p.page_id=c.page_id) LEFT OUTER JOIN (wrintermapssledrun s JOIN wrintermapsreport r ON s.intermaps_sledrun_id=r.intermaps_sledrun_id) ON p.page_id=s.wr_page_id
754 // WHERE p.page_title in ('Birgitzer_Alm_(vom_Adelshof)', 'Mutterer_Alm_-_Sportrodelbahn', 'Axamer_Lizum') ORDER BY page_title;
755 $where_array = array();
756 if (count($page_titles) > 0) {
757 $mysql_page_ids = array();
758 foreach ($page_titles as $page_title) $mysql_page_ids[] = $page_title->getArticleID();
759 $where_array[] = 'p.page_id in (' . implode(', ', $mysql_page_ids) . ')';
760 } else $where_array[] = 'false';
761 $res = $dbr->select(['AA' => ['p' => 'page', 'c' => 'wrsledruncache'], 'BB' => ['r' => 'wrintermapsreport', 's' => 'wrintermapssledrun']],
762 ['p.page_id', 'p.page_title', 'p.page_namespace',
763 'c.length', 'c.walkup_time', 'c.top_elevation', 'c.bottom_elevation', 'c.walkup_possible', 'c.walkup_separate',
764 'c.lift', 'c.night_light', 'c.public_transport', 'c.sled_rental', 'c.information_phone', 'c.information_web',
765 's.show_status', 'r.status', 'r.last_check', 'r.last_update'],
767 'bahnentabelleParserHook',
768 ['ORDER BY' => 'p.page_title'],
769 ['p' => ['JOIN', 'p.page_id=c.page_id'], 'r' => ['JOIN', 's.intermaps_sledrun_id=r.intermaps_sledrun_id'], 'AA' => ['LEFT OUTER JOIN', 'p.page_id=s.wr_page_id']]
773 global $wgWrReportMode; // e.g. 'summer'
774 global $wgWrReportBlackListAll;
775 global $wgWrReportBlackListStrangers;
777 // Determine, whether the user is allowed to make a new report
778 $userMayReport = ($wgWrReportMode == 'allow' || ($wgWrReportMode == 'loggedin' && $wgUser->isLoggedIn()));
780 // Generate DOM for HTML
781 $doc = new WrDOMDocument();
782 $table = $doc->appendElement('table', array('class' => 'wikitable'));
785 $tr = $table->appendElement('tr');
786 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_rental.png', 'alt' => wfMessage('wrreport-icon-sledrental')->text(), 'title' => wfMessage('wrreport-icon-sledrental')->text()));
787 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_light.png', 'alt' => wfMessage('wrreport-icon-nightlight')->text(), 'title' => wfMessage('wrreport-icon-nightlight')->text()));
788 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
789 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_walk.png', 'alt' => wfMessage('wrreport-icon-walkupseparate')->text(), 'title' => wfMessage('wrreport-icon-walkupseparate')->text()));
790 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_bus.png', 'alt' => wfMessage('wrreport-icon-publictransport')->text(), 'title' => wfMessage('wrreport-icon-publictransport')->text()));
791 if ($wgWrReportMode != 'summer') $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_opened.png', 'alt' => wfMessage('wrreport-icon-intermaps-status')->text(), 'title' => wfMessage('wrreport-icon-intermaps-status')->text()));
792 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
793 if ($wgWrReportMode != 'summer') $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
794 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-information')->text());
795 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-walkuptime')->text());
796 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-height')->text());
797 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-length')->text());
800 while ($row = $dbr->fetchObject($res)) {
801 $title = Title::newFromRow($row);
802 $tr = $table->appendElement('tr');
804 $td = $tr->appendElement('td');
805 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()));
807 $td = $tr->appendElement('td');
808 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()));
810 $td = $tr->appendElement('td');
811 if ($row->lift) $td->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
813 $td = $tr->appendElement('td');
814 if (!is_null($row->walkup_possible)) {
815 if ($row->walkup_possible) {
816 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()));
817 } else $td->appendElement('img', array('src' => '/vorlagen/s_nowalk.png', 'alt' => wfMessage('wrreport-icon-walkupnotpossible')->text(), 'title' => wfMessage('wrreport-icon-walkupnotpossible')->text()));
820 $td = $tr->appendElement('td');
821 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()));
823 if ($wgWrReportMode != 'summer') {
824 $td = $tr->appendElement('td');
825 if ($row->show_status) {
826 if ($row->status == 'open') {
827 $td->appendElement('img', array('src' => '/vorlagen/s_opened.png', 'alt' => wfMessage('wrreport-icon-intermaps-opened')->text(), 'title' => wfMessage('wrreport-icon-intermaps-opened')->text()));
828 } elseif ($row->status == 'closed') {
829 $td->appendElement('img', array('src' => '/vorlagen/s_closed.png', 'alt' => wfMessage('wrreport-icon-intermaps-closed')->text(), 'title' => wfMessage('wrreport-icon-intermaps-closed')->text()));
831 $td->appendText($row->status);
836 // check whether info should be shown at all
839 $tr->appendElement('td')->appendElement('a', array('href' => $title->getLocalURL()))->appendText($title->getPrefixedText());
841 if ($wgWrReportMode != 'summer') {
843 $userMayReportThis = $userMayReport;
844 if ($userMayReportThis) {
845 if (in_array($title->getText(), $wgWrReportBlackListAll)) $userMayReportThis = FALSE;
846 if (!$wgUser->isLoggedIn() && in_array($title->getText(), $wgWrReportBlackListStrangers)) $userMayReportThis = FALSE; // Title::getText() uses spaces instead of underscores
850 list($report_id, $condition, $date_report) = wrGetSledrunCondition($dbr, $row->page_id);
851 if (is_null($report_id)) $date = '';
852 else $date = strftime('%d.%m.', $date_report);
854 $td = $tr->appendElement('td');
855 if (in_array($condition, WrReport::$wrConditions)) {
856 $td->appendElement('a', array('href' => $title->getLocalURL() . '#' . Sanitizer::escapeIdForLink(wfMessage('wrreport-reports-sectionname'))))->appendText(WrReport::getWrConditionText($condition));
857 $td->appendText(' ');
858 $small = $td->appendElement('small');
859 $small->appendText($date);
860 if ($userMayReportThis) {
861 $small->appendText(' ');
862 $small->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Sanitizer::escapeIdForLink(wfMessage('wrreport-newreport-sectionname'))))->appendText(wfMessage('wrreport-newreport-new')->text());
865 if ($userMayReportThis)
866 $td->appendElement('small')->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Sanitizer::escapeIdForLink(wfMessage('wrreport-newreport-sectionname'))))->appendText(wfMessage('wrreport-newreport-please')->text());
867 else $td->appendText('--');
871 $td = $tr->appendElement('td');
872 $info_phone = $row->information_phone;
874 $info_parts = explode(';', $info_phone);
875 $info_parts = explode('(', $info_parts[0], 2);
876 if (count($info_parts) == 2 && substr($info_parts[1], -1) == ')') {
877 $td->appendText($info_parts[0]);
878 $td->appendElement('span', array('class' => 'wrtelinfo'))->appendText(substr($info_parts[1], 0, -1));
879 } else $td->appendText($info_phone);
881 $info_web = $row->information_web;
882 if ($info_web === 'Nein') $info_web = null;
883 if ($info_phone && $info_web) $td->appendText('; ');
885 $td->appendElement('a', array('href' => $info_web))->appendText('web');
889 $tr->appendElement('td')->appendText($row->walkup_time ? $row->walkup_time . ' min' : '');
891 $tr->appendElement('td')->appendText(
892 ($row->bottom_elevation ? $row->bottom_elevation : '') .
893 ($row->bottom_elevation && $row->top_elevation ? ' - ' : '') .
894 ($row->top_elevation ? $row->top_elevation : '') .
895 ($row->bottom_elevation || $row->top_elevation ? ' m' : ''));
897 $tr->appendElement('td')->appendText($row->length ? $row->length . ' m' : '');
899 $dbr->freeResult($res);
901 return $doc->saveHTML();
905 /// \brief Is called when the tag <bahnentabelle/> is encountered.
909 /// Birgitzer Alm (vom Adelshof)
913 public static function bahnentabelleParserHook($input, array $args, Parser $parser, PPFrame $frame) {
914 $parser->getOutput()->addModules('ext.wrreport');
917 // Note: As (of MediaWiki 1.19), only one feed can be added and each feed added replaces the previous one, the following is possible without risk of having duplicated feed entries.
918 WrReport::addRegionFeedLink($parser->getTitle());
920 // Add each page title that has been found
921 $page_titles = array(); // array of Title objects
922 foreach (explode("\n", $input) as $page_title) {
923 $page_title = Title::newFromText(trim($page_title));
924 if (!$page_title || !$page_title->exists()) continue;
925 $page_titles[] = $page_title;
928 // Create bahnentabelle
929 $html = WrReport::createBahnentabelle($page_titles);
930 return array($html, 'markerType' => 'nowiki');
934 /// \brief Is called when the tag <bahnenregiontabelle/> is encountered.
937 /// <bahnenregiontabelle />
940 /// <bahnenregiontabelle wiki="Innsbruck" /> (refers to region represented by the MediaWiki Title name)
941 /// <bahnenregiontabelle region_id="3" /> (refers to id in the wrregion table)
942 /// <bahnenregiontabelle region_name="Innsbruck" /> (refers to name in the wrregion table)
943 public static function bahnenregiontabelleParserHook($input, array $args, Parser $parser, PPFrame $frame) {
944 $parser->getOutput()->addModules('ext.wrreport');
947 // we accept 0 or 1 parameters
948 if (count($args) > 1) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-toomanyarguments')->text());
950 if (count($args) == 0) {
951 // current page represents a region
952 $title = $parser->getTitle(); // default title: current page
953 list($region_id, $region_name, $region_border_wkb) = WrReport::getPageRegion($title);
954 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-thispagenoregion')->text());
955 } elseif (isset($args['wiki'])) {
956 // other page represents a region
957 $title = Title::newFromText($args['wiki']);
958 list($region_id, $region_name, $region_border_wkb) = WrReport::getPageRegion($title);
959 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-pagenoregion')->text());
960 } elseif (isset($args['region_id'])) {
961 list($region_id, $region_name, $region_border_wkb) = WrReport::getRegionDetails(array('id' => $args['region_id']));
962 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-noregionid')->text());
963 } elseif (isset($args['region_name'])) {
964 list($region_id, $region_name, $region_border_wkb) = WrReport::getRegionDetails(array('name' => $args['region_name']));
965 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-noregionname')->text());
967 throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-invalidargument', array_keys($args)[0])->text());
970 // get titles that are in the region
971 $page_titles = array();
972 $dbr = wfGetDB(DB_REPLICA);
973 // the following line would work if MySQL 5.5 would implement a real geospatial version of CONTAINS.
974 // $res = $dbr->select('wrsledruncache', 'page_id', array('CONTAINS(GEOMFROMWKB(' . $dbr->addQuotes($region_border_wkb) . '), POINT(position_longitude, position_latitude))', 'NOT under_construction'), __METHOD__, 'page_title');
975 $res = $dbr->select(array('wrsledruncache', 'wrregioncache'), array('page_id' => 'wrregioncache.page_id'), array('wrregioncache.region_id' => $region_id, 'wrregioncache.page_id=wrsledruncache.page_id', 'NOT under_construction'), __METHOD__, 'page_title');
976 foreach ($res as $row) {
977 $page_titles[] = Title::newFromId($row->page_id);
979 $dbr->freeResult($res);
980 $html = WrReport::createBahnentabelle($page_titles);
982 } catch (WrReportException $e) {
983 $doc = new WrDOMDocument();
984 $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-bahnenregiontabelle-error', $e->getMessage())->text());
985 $html = $doc->saveHTML($doc->firstChild);
988 return array($html, 'markerType' => 'nowiki');
992 /// \brief Is called when the tag <rodelbahntabelle/> is encountered.
994 /// Description: See description of wrreport.php
995 public static function rodelbahntabelleParserHook($input, array $args, Parser $parser, PPFrame $frame) {
996 $parser->getOutput()->addModules('ext.wrreport');
999 // Note: As (of MediaWiki 1.19), only one feed can be added and each feed added replaces the previous one, the following is possible without risk of having duplicated feed entries.
1000 WrReport::addRegionFeedLink($parser->getTitle());
1002 $dbr = wfGetDB(DB_REPLICA);
1004 libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
1006 $xml_input = '<rodelbahntabelle>' . $input . '</rodelbahntabelle>';
1007 $xml = new SimpleXMLElement($xml_input); // input
1008 } catch (Exception $e) {
1009 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-xml', $xml_input)->text());
1011 $whitespace = (string) $xml; // everything between <rodelbahntabelle> and </rodelbahntabelle> that's not a sub-element
1012 if (strlen($whitespace) > 0 && !ctype_space($whitespace)) // there must not be anythin except sub-elements or whitespace
1013 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-textbetweenelements', trim($xml))->text());
1015 // page_ids of sledrun titles that that are going to be returned
1016 $page_ids = array();
1017 foreach ($xml as $entry) { // entry is <rodelbahn>, <region> or <rodelbahnen>
1018 $entry_page_ids = array(); // page_ids selected (or un-selected) for this entry.
1019 $tagname = $entry->getName();
1020 $attributes = array();
1021 foreach ($entry->attributes() as $key => $value) $attributes[(string) $key] = (string) $value;
1023 // is the tagname valid?
1024 if (!in_array($tagname, array('rodelbahn', 'rodelbahnen', 'region')))
1025 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-element', $tagname)->text());
1027 // parse operation attribute
1028 $operation = '+'; // '+' (append) or '-' (subtract)
1029 if (array_key_exists('operation', $attributes)) {
1030 $operation = $attributes['operation'];
1031 if (!in_array($operation, array('+', '-')))
1032 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-value', $tagname, 'operation', $operation)->text());
1033 unset($attributes['operation']);
1036 // parse in_arbeit attribute
1037 $under_construction = false; // false (only sledruns that are not under construction), true (only sledruns under construction) or null (doen't matter)
1038 if ($tagname === 'rodelbahn') $under_construction = null; // different default value for tag <rodelbahn>.
1039 if (array_key_exists('in_arbeit', $attributes)) {
1040 if ($attributes['in_arbeit'] === 'nein') $under_construction = false;
1041 elseif ($attributes['in_arbeit'] === 'ja') $under_construction = true;
1042 elseif ($attributes['in_arbeit'] === '*') $under_construction = null;
1043 else throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-value', $tagname, 'in_arbeit', $attributes['in_arbeit'])->text());
1044 unset($attributes['in_arbeit']);
1047 // any attributes left that are not handled yet?
1048 if (count($attributes) > 0)
1049 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-name', $tagname, array_keys($attributes)[0])->text());
1053 $tables = array('wrsledruncache');
1057 if ($tagname === 'region') {
1058 // the following line would work if MySQL 5.5 would implement a real geospatial version of CONTAINS.
1059 // $where[] = 'CONTAINS(GEOMFROMWKB(' . $dbr->addQuotes($region_border_wkb) . '), POINT(position_longitude, position_latitude))'
1060 $tables[] = 'wrregion';
1061 $tables[] = 'wrregioncache';
1062 $where[] = 'wrregioncache.region_id=wrregion.id';
1063 $where[] = 'wrregioncache.page_id=wrsledruncache.page_id';
1064 $where['wrregion.name'] = $entry;
1068 if ($tagname == 'rodelbahn') {
1069 $page_title = Title::newFromText(trim($entry));
1070 $where['page_title'] = $page_title->getDBkey();
1073 // under contruction
1074 if ($under_construction === true) $where[] = 'wrsledruncache.under_construction';
1075 if ($under_construction === false) $where[] = 'not wrsledruncache.under_construction';
1078 $res = $dbr->select($tables, array('page_id' => 'wrsledruncache.page_id'), $where, __METHOD__, 'page_id');
1079 foreach ($res as $row) {
1080 $entry_page_ids[] = $row->page_id;
1082 $dbr->freeResult($res);
1085 // merge the entry page_ids with the page_ids
1086 if ($operation == '+') $page_ids = array_merge($page_ids, $entry_page_ids);
1087 elseif ($operation == '-') $page_ids = array_diff($page_ids, $entry_page_ids);
1090 // page_titles that are going to be returned
1091 $page_titles = Title::newFromIDs($page_ids);
1093 $html = WrReport::createBahnentabelle($page_titles);
1095 } catch (WrReportException $e) {
1096 $doc = new WrDOMDocument();
1097 $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-rodelbahntabelle-error', $e->getMessage())->text());
1098 $html = $doc->saveHTML($doc->firstChild);
1101 return array($html, 'markerType' => 'nowiki');
1105 /// \brief Is called when the tag <avatar>username</avatar> is encountered.
1106 public static function avatarParserHook($input, array $args, Parser $parser, PPFrame $frame) {
1107 $doc = new WrDOMDocument();
1108 $sla = new WrServicesLibravatar();
1112 if (is_null($input)) throw new WrReportException(wfMessage('wrreport-avatar-nousername')->text());
1113 $username = $parser->recursiveTagParse($input, $frame);
1114 $user = User::newFromName($username);
1115 if ($user === false) throw new WrReportException(wfMessage('wrreport-avatar-invalidusername', $username)->text());
1116 if ($user->getId() == 0) throw new WrReportException(wfMessage('wrreport-avatar-userunknown', $username)->text());
1118 // size attribute (optional)
1119 if (isset($args['size'])) $sla->setSize((int) $parser->recursiveTagParse($args['size'], $frame));
1121 // alt attribute (optional)
1122 $alt = wfMessage('wrreport-avatar-of', $username)->text();
1124 // create avatar (using the Services_Libravatar library to get avatar URL)
1125 $url = $sla->getUrl($user->getEmail());
1126 $doc->appendElement('img', array('src' => $url, 'alt' => $username, 'width' => $sla->getSize(), 'height' => $sla->getSize()));
1128 } catch (WrReportException $e) {
1129 $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-avatar-error', $e->getMessage())->text());
1132 // return result (markerType => nowiki prevents wiki formatting of the result)
1133 $html = $doc->saveHTML($doc->firstChild);
1134 return array($html, 'markerType' => 'nowiki');
1138 public static function MobileMenuHook($name, \MediaWiki\Minerva\MenuBuilder &$menu) {
1139 if ($name === 'discovery') {
1140 // delete "Random page". As a removeEntry function is missing,
1141 // a new menu is built here without the random page.
1142 $new_menu = new \MediaWiki\Minerva\MenuBuilder();
1143 foreach ($menu->getEntries() as $menuEntryRepresentation) {
1144 $new_entry_name = $menuEntryRepresentation['name'];
1145 if ($new_entry_name == 'random') continue;
1146 $new_entry_components = $menuEntryRepresentation['components'];
1147 $new_entry_isjsonly = isset($menuEntryRepresentation['class']) and $menuEntryRepresentation['class'] === 'jsonly';
1148 $new_entry = $new_menu->insert($new_entry_name, $new_entry_isjsonly);
1149 foreach ($new_entry_components as $new_entry_component) {
1150 $label = $new_entry_component['text'];
1151 $url = $new_entry_component['href'];
1152 $className = $new_entry_component['class'];
1153 $new_entry->addComponent($label, $url, $className, $new_entry_components);
1158 // add region menu entry
1159 $icon = MobileUI::iconClass('random', 'before');
1160 $title = Title::newFromText('Region', NS_CATEGORY);
1161 $menu->insert('region')->addComponent('Regionen', $title->getLocalURL(), $icon, array('id' => 'regionButton', 'data-event-name' => 'region'));
1172 /// Specal Page to show reports
1173 class SpecialWrReport extends SpecialPage {
1174 function __construct() {
1175 parent::__construct('wrreport');
1179 /// \param $par Possibilities:
1180 /// - action == 'view' (default)
1181 /// - action == 'preview': Preview new report
1182 /// - action == 'store': Store new report
1183 /// - action == 'deletepreview': Preview the deleted record
1184 /// - action == 'delete': Delete an existing report
1185 /// - action == 'showerror': Shows the error and exits
1186 /// \param $override_action If not NULL (default), it overrides the action in $par
1187 /// \param $errorMsg UFT-8 encoded error message (in WikiText) to show on top of the page or NULL (default):
1188 function execute($par, $override_action = NULL, $errorMsg = NULL) {
1189 $request = $this->getRequest();
1190 $output = $this->getOutput();
1193 $output->addWikiText(''); // this is necessary because otherwise $wgParser is not properly initialized
1195 $output->addModules('ext.wrreport');
1196 $this->setHeaders();
1199 $action = $request->getText('action');
1201 if ($request->getVal('preview')) $action = 'preview';
1202 elseif ($request->getVal('store')) $action = 'store';
1203 elseif ($request->getVal('deletepreview')) $action = 'deletepreview';
1204 elseif ($request->getVal('delete')) $action = 'delete';
1205 else $action = 'view';
1207 if ($override_action) $action = $override_action;
1209 // Show error message
1210 if ($errorMsg || $action == 'showerror') {
1211 $output->addWikiText('<div class="errorbox">' . $errorMsg . "</div>\n");
1212 if ($action == 'showerror') return;
1216 if ($action == 'view') {
1217 global $wgWrReportFeedRoot;
1218 $output->addFeedLink('atom', $wgWrReportFeedRoot . '/berichte/alle');
1219 $conditions = array('date_invalid > now()');
1220 $rows = wrReportGetReports($conditions);
1221 if (count($rows) == 0) $output->addHTML(wfMessage('wrreport-reports-none')->text());
1223 $output->addHTML(wrReportTableRender($rows, WRREPORT_DETAIL, wrReportUserMayDelete(), $wgParser));
1227 // Action deletepreview or delete
1228 elseif ($action == 'deletepreview' || $action == 'delete') {
1229 $reportid = (int) $request->getText('reportid');
1230 if ($reportid == 0) {
1231 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-noreport')->text());
1234 $rows = wrReportGetReports(array('id' => $reportid));
1235 if (count($rows) != 1) {
1236 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-invalid')->text());
1240 if (!is_null($row['delete_date'])) {
1241 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-alreadydeleted')->text());
1244 $delete_reason_public = $request->getText('delete_reason_public');
1245 $delete_person_name = $request->getText('delete_person_name');
1246 $delete_invisible = $request->getText('delete_invisible') ? TRUE : FALSE;
1247 if ($action == 'delete') {
1249 $title = Title::newFromId($row['page_id']);
1253 $delete_person_userid = $wgUser->getId();
1254 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.
1255 $delete_person_username = $wgUser->getName();
1257 // Check permissions - see also function wrReportUserMayDelete, that does also check permissions but does not return an error message.
1259 global $wgWrReportDeleteMode;
1260 if ($wgWrReportDeleteMode == 'deny') $errorMsg = wfMessage('wrreport-deletereport-deny')->text();
1261 elseif ($wgWrReportDeleteMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = wfMessage('wrreport-deletereport-loggedin')->text();
1262 elseif (!$delete_person_name || !$delete_reason_public) $errorMsg = wfMessage('wrreport-deletereport-incomplete')->text();
1264 $this->execute($par, 'deletepreview', $errorMsg);
1268 // "Delete" (update) entry
1269 $dbr = wfGetDB(DB_MASTER);
1273 'delete_date' => date('c'),
1274 'delete_person_name' => $delete_person_name,
1275 'delete_person_ip' => $_SERVER['REMOTE_ADDR'],
1276 'delete_person_userid' => $delete_person_userid,
1277 'delete_person_username' => $delete_person_username,
1278 'delete_reason_public' => $delete_reason_public,
1279 'delete_invisible' => $delete_invisible ? 't' : 'f'
1281 array('id' => $reportid)
1285 $title->invalidateCache();
1288 // Show success message
1289 $output->addWikiText(wfMessage('wrreport-deletereport-success', '[[' . $row['page_title'] . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $row['page_title'] . ']]')->text());
1291 if ($action == 'deletepreview') {
1292 $output->addWikiMsg('wrreport-deletereport-preview-before');
1293 $format = WRREPORT_COMPACT_PAGE;
1294 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1295 $output->addWikiMsg('wrreport-deletereport-preview-after');
1296 $row['delete_date'] = date('c');
1297 $row['delete_reason_public'] = $delete_reason_public;
1298 $row['delete_person_name'] = $delete_person_name;
1299 $row['delete_invisible'] = $delete_invisible;
1300 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1301 $output->addWikiMsg('wrreport-deletereport-preview-form');
1302 $output->addHTML(wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible));
1303 $output->addWikiMsg('wrreport-deletereport-preview-bottom');
1307 // Action preview or store
1308 elseif ($action == 'preview' || $action == 'store') {
1309 $page_title = $request->getText('page_title');
1310 $date_report = $request->getText('date_report');
1311 $time_report = $request->getText('time_report');
1312 $condition = $request->getText('condition');
1313 $description = $request->getText('description');
1314 $author_name = $request->getText('author_name');
1317 $time_report = trim($time_report); // strip whitespace
1321 if (preg_match('/^[0-2]?[0-9]$/', $time_report)) {
1322 // $time_report has 1 or 2 digits, e.g. 'h', or 'hh'.
1323 $hour = intval($time_report);
1325 } elseif (preg_match('/^([0-2]?[0-9]):?([0-9]{2})$/', $time_report, $matches)) {
1326 // $time_report has 3 or 4 digits, e.g. 'hmm' or 'hhmm' or 'h:mm' or 'hh:mm'.
1327 $hour = intval($matches[1]);
1328 $minute = intval($matches[2]);
1330 if (!is_null($hour) && $hour >= 0 && $hour < 24 && $minute >= 0 && $minute < 60) $time_report = sprintf('%02d:%02d', $hour, $minute);
1331 else $time_report = NULL;
1334 $condition = (int) $condition; // force to be nummeric. -1 ... "keine Bewertung", 0 ... "Bitte eingeben", 1 to 5 ... "Sehr gut" to "Geht nicht"
1335 if ($condition < -1 or $condition > 5) $condition = 0; // invalid condition: Tread like 0.
1336 $condition_sql = NULL;
1337 if ($condition >= 1 and $condition <= 5) $condition_sql = $condition;
1340 $author_name = trim($author_name);
1343 $title = Title::newFromText($page_title);
1344 $page_id = $title->getArticleID();
1345 if ($page_id == 0) $page_id = NULL;
1349 $author_userid = $wgUser->getId();
1350 if ($author_userid == 0) $author_userid = NULL; // to store a NULL value in the database if no user is logged in instead of 0.
1351 $author_username = $wgUser->getName();
1353 if ($action == 'store') {
1354 // check conditions/permissions
1356 global $wgWrReportMode;
1357 global $wgWrReportBlackListAll;
1358 global $wgWrReportBlackListStrangers;
1359 if ($wgWrReportMode == 'summer') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-summer')->text());
1360 elseif ($wgWrReportMode == 'deny') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-deny')->text());
1361 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-loggedin')->text());
1362 elseif (!$page_id) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-pagenotfound')->text());
1363 elseif (in_array($page_title, $wgWrReportBlackListAll)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blacklist')->text());
1364 elseif (!$wgUser->isLoggedIn() && in_array($page_title, $wgWrReportBlackListStrangers)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blackliststrangers')->text());
1365 elseif ($condition == 0) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-choosecondition')->text());
1366 elseif (!$wgUser->isLoggedIn()) {
1367 if (!$description) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterdescription')->text());
1368 elseif (!(stripos($description, 'http') === FALSE)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-nohttp')->text());
1369 elseif (!$author_name) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterauthor')->text());
1372 // check author name
1374 $author_name_id = $wgUser->idFromName(strtolower($author_name));
1375 if ($wgUser->isLoggedIn()) {
1376 if ($author_name_id != 0 && $author_name_id != $wgUser->getId())
1377 $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorused')->text());
1379 if ($author_name_id != 0)
1380 $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorlogin')->text());
1384 // Chech whether identical reports are present
1386 $dbr = wfGetDB(DB_REPLICA);
1387 $cond = 'condition';
1389 if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
1390 $sqlConditions = array('page_id' => $page_id, 'date_report' => $date_report, 'time_report' => $time_report, $cond => $condition_sql, 'description' => $description, 'author_name' => $author_name);
1391 $res = $dbr->select('wrreport', 'id', $sqlConditions);
1392 if ($res->numRows() == 1) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-alreadysaved')->text());
1393 $dbr->freeResult($res);
1396 // Show error if any
1398 $this->execute($par, 'preview', $errorMsg);
1403 $dbr = wfGetDB(DB_MASTER);
1407 'page_id' => $page_id,
1408 'page_title' => $page_title,
1409 'date_report' => $date_report,
1410 'time_report' => $time_report,
1411 'date_entry' => date('c'),
1412 'date_invalid' => date('c', strtotime('+9 days')),
1413 $cond => $condition_sql,
1414 'description' => $description,
1415 'author_name' => $author_name,
1416 'author_ip' => $_SERVER['REMOTE_ADDR'],
1417 'author_userid' => $author_userid,
1418 'author_username' => $author_username
1419 // 'delete_*' => // use database defaults (NULL)
1424 $title->invalidateCache();
1426 wrUpdateWrReportCacheTable($page_id);
1428 // Show success message
1429 $output->addWikiText(wfMessage('wrreport-newreport-success', '[[' . $page_title . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $page_title . ']]')->text());
1430 // We could redirect to result with the following line but we don't want to.
1431 // $output->redirect($title->getFullURL() . '#' . wfMessage('wrreport-reports-sectionname')->text());
1433 if ($action == 'preview') {
1434 $output->addWikiMsg('wrreport-newreport-preview-top');
1435 $format = WRREPORT_COMPACT_PAGE;
1436 $row = array_fill_keys(wrReportGetColumnNames(), NULL);
1437 $row['page_id'] = $page_id;
1438 $row['page_title'] = $page_title;
1439 $row['date_report'] = $date_report;
1440 $row['time_report'] = $time_report;
1441 $row['condition'] = $condition_sql;
1442 $row['description'] = $description;
1443 $row['author_name'] = $author_name;
1444 $row['author_userid'] = $author_userid;
1445 $row['author_username'] = $author_username;
1447 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1448 $output->addWikiMsg('wrreport-newreport-preview-middle');
1449 $output->addHTML(wrReportFormRender(FALSE, $page_title, $date_report, $time_report, $condition, $description, $author_name));
1450 $output->addWikiMsg('wrreport-newreport-preview-bottom');
1451 if ($wgUser->isLoggedIn())
1452 $output->addWikiMsg('wrreport-newreport-preview-bottom-loggedin');
1454 $output->addWikiMsg('wrreport-newreport-preview-bottom-anonymous');
1459 else die('Wrong action');