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_SLAVE);
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_SLAVE);)
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_SLAVE);
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_SLAVE);
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_SLAVE);
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_SLAVE);
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_SLAVE);
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_SLAVE);
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, 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
752 $where_array = array('page.page_id = wrsledruncache.page_id');
753 if (count($page_titles) > 0) {
754 $mysql_page_ids = array();
755 foreach ($page_titles as $page_title) $mysql_page_ids[] = $page_title->getArticleID();
756 $where_array[] = 'page.page_id in (' . implode(', ', $mysql_page_ids) . ')';
757 } else $where_array[] = 'false';
758 $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', 'information_web'), $where_array, 'bahnentabelleParserHook', array('ORDER BY' => 'page.page_title'));
761 global $wgWrReportMode; // e.g. 'summer'
762 global $wgWrReportBlackListAll;
763 global $wgWrReportBlackListStrangers;
766 // Determine, whether the user is allowed to make a new report
767 $userMayReport = ($wgWrReportMode == 'allow' || ($wgWrReportMode == 'loggedin' && $wgUser->isLoggedIn()));
769 // Generate DOM for HTML
770 $doc = new WrDOMDocument();
771 $table = $doc->appendElement('table', array('class' => 'wikitable'));
774 $tr = $table->appendElement('tr');
775 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_rental.png', 'alt' => wfMessage('wrreport-icon-sledrental')->text(), 'title' => wfMessage('wrreport-icon-sledrental')->text()));
776 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_light.png', 'alt' => wfMessage('wrreport-icon-nightlight')->text(), 'title' => wfMessage('wrreport-icon-nightlight')->text()));
777 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
778 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_walk.png', 'alt' => wfMessage('wrreport-icon-walkupseparate')->text(), 'title' => wfMessage('wrreport-icon-walkupseparate')->text()));
779 $tr->appendElement('th')->appendElement('img', array('src' => '/vorlagen/s_bus.png', 'alt' => wfMessage('wrreport-icon-publictransport')->text(), 'title' => wfMessage('wrreport-icon-publictransport')->text()));
780 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun')->text());
781 if ($wgWrReportMode != 'summer') $tr->appendElement('th')->appendText(wfMessage('wrreport-newreport-condition')->text());
782 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-information')->text());
783 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-walkuptime')->text());
784 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-height')->text());
785 $tr->appendElement('th')->appendText(wfMessage('wrreport-sledrun-length')->text());
788 while ($row = $dbr->fetchObject($res)) {
789 $title = Title::newFromRow($row);
790 $tr = $table->appendElement('tr');
792 $td = $tr->appendElement('td');
793 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()));
795 $td = $tr->appendElement('td');
796 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()));
798 $td = $tr->appendElement('td');
799 if ($row->lift) $td->appendElement('img', array('src' => '/vorlagen/s_lift.png', 'alt' => wfMessage('wrreport-icon-lift')->text(), 'title' => wfMessage('wrreport-icon-lift')->text()));
801 $td = $tr->appendElement('td');
802 if (!is_null($row->walkup_possible)) {
803 if ($row->walkup_possible) {
804 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()));
805 } else $td->appendElement('img', array('src' => '/vorlagen/s_nowalk.png', 'alt' => wfMessage('wrreport-icon-walkupnotpossible')->text(), 'title' => wfMessage('wrreport-icon-walkupnotpossible')->text()));
808 $td = $tr->appendElement('td');
809 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()));
811 $tr->appendElement('td')->appendElement('a', array('href' => $title->getLocalURL()))->appendText($title->getPrefixedText());
813 if ($wgWrReportMode != 'summer') {
815 $userMayReportThis = $userMayReport;
816 if ($userMayReportThis) {
817 if (in_array($title->getText(), $wgWrReportBlackListAll)) $userMayReportThis = FALSE;
818 if (!$wgUser->isLoggedIn() && in_array($title->getText(), $wgWrReportBlackListStrangers)) $userMayReportThis = FALSE; // Title::getText() uses spaces instead of underscores
822 list($report_id, $condition, $date_report) = wrGetSledrunCondition($dbr, $row->page_id);
823 if (is_null($report_id)) $date = '';
824 else $date = strftime('%d.%m.', $date_report);
826 $td = $tr->appendElement('td');
827 if (in_array($condition, WrReport::$wrConditions)) {
828 $td->appendElement('a', array('href' => $title->getLocalURL() . '#' . Sanitizer::escapeIdForLink(wfMessage('wrreport-reports-sectionname'))))->appendText(WrReport::getWrConditionText($condition));
829 $td->appendText(' ');
830 $small = $td->appendElement('small');
831 $small->appendText($date);
832 if ($userMayReportThis) {
833 $small->appendText(' ');
834 $small->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Sanitizer::escapeIdForLink(wfMessage('wrreport-newreport-sectionname'))))->appendText(wfMessage('wrreport-newreport-new')->text());
837 if ($userMayReportThis)
838 $td->appendElement('small')->appendElement('em')->appendElement('a', array('href' =>$title->getLocalURL() . '#' . Sanitizer::escapeIdForLink(wfMessage('wrreport-newreport-sectionname'))))->appendText(wfMessage('wrreport-newreport-please')->text());
839 else $td->appendText('--');
843 $td = $tr->appendElement('td');
844 $info_phone = $row->information_phone;
846 $info_parts = explode(';', $info_phone);
847 $info_parts = explode('(', $info_parts[0], 2);
848 if (count($info_parts) == 2 && substr($info_parts[1], -1) == ')') {
849 $td->appendText($info_parts[0]);
850 $td->appendElement('span', array('class' => 'wrtelinfo'))->appendText(substr($info_parts[1], 0, -1));
851 } else $td->appendText($info_phone);
853 $info_web = $row->information_web;
854 if ($info_web === 'Nein') $info_web = null;
855 if ($info_phone && $info_web) $td->appendText('; ');
857 $td->appendElement('a', array('href' => $info_web))->appendText('web');
861 $tr->appendElement('td')->appendText($row->walkup_time ? $row->walkup_time . ' min' : '');
863 $tr->appendElement('td')->appendText(
864 ($row->bottom_elevation ? $row->bottom_elevation : '') .
865 ($row->bottom_elevation && $row->top_elevation ? ' - ' : '') .
866 ($row->top_elevation ? $row->top_elevation : '') .
867 ($row->bottom_elevation || $row->top_elevation ? ' m' : ''));
869 $tr->appendElement('td')->appendText($row->length ? $row->length . ' m' : '');
871 $dbr->freeResult($res);
873 return $doc->saveHTML();
877 /// \brief Is called when the tag <bahnentabelle/> is encountered.
881 /// Birgitzer Alm (vom Adelshof)
885 public static function bahnentabelleParserHook($input, array $args, Parser $parser, PPFrame $frame) {
886 $parser->getOutput()->addModules('ext.wrreport');
889 // 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.
890 WrReport::addRegionFeedLink($parser->getTitle());
892 // Add each page title that has been found
893 $page_titles = array(); // array of Title objects
894 foreach (explode("\n", $input) as $page_title) {
895 $page_title = Title::newFromText(trim($page_title));
896 if (!$page_title || !$page_title->exists()) continue;
897 $page_titles[] = $page_title;
900 // Create bahnentabelle
901 $html = WrReport::createBahnentabelle($page_titles);
902 return array($html, 'markerType' => 'nowiki');
906 /// \brief Is called when the tag <bahnenregiontabelle/> is encountered.
909 /// <bahnenregiontabelle />
912 /// <bahnenregiontabelle wiki="Innsbruck" /> (refers to region represented by the MediaWiki Title name)
913 /// <bahnenregiontabelle region_id="3" /> (refers to id in the wrregion table)
914 /// <bahnenregiontabelle region_name="Innsbruck" /> (refers to name in the wrregion table)
915 public static function bahnenregiontabelleParserHook($input, array $args, Parser $parser, PPFrame $frame) {
916 $parser->getOutput()->addModules('ext.wrreport');
919 // we accept 0 or 1 parameters
920 if (count($args) > 1) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-toomanyarguments')->text());
922 if (count($args) == 0) {
923 // current page represents a region
924 $title = $parser->getTitle(); // default title: current page
925 list($region_id, $region_name, $region_border_wkb) = WrReport::getPageRegion($title);
926 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-thispagenoregion')->text());
927 } elseif (isset($args['wiki'])) {
928 // other page represents a region
929 $title = Title::newFromText($args['wiki']);
930 list($region_id, $region_name, $region_border_wkb) = WrReport::getPageRegion($title);
931 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-pagenoregion')->text());
932 } elseif (isset($args['region_id'])) {
933 list($region_id, $region_name, $region_border_wkb) = WrReport::getRegionDetails(array('id' => $args['region_id']));
934 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-noregionid')->text());
935 } elseif (isset($args['region_name'])) {
936 list($region_id, $region_name, $region_border_wkb) = WrReport::getRegionDetails(array('name' => $args['region_name']));
937 if (is_null($region_id)) throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-noregionname')->text());
939 throw new WrReportException(wfMessage('wrreport-bahnenregiontabelle-invalidargument', array_keys($args)[0])->text());
942 // get titles that are in the region
943 $page_titles = array();
944 $dbr = wfGetDB(DB_SLAVE);
945 // the following line would work if MySQL 5.5 would implement a real geospatial version of CONTAINS.
946 // $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');
947 $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');
948 foreach ($res as $row) {
949 $page_titles[] = Title::newFromId($row->page_id);
951 $dbr->freeResult($res);
952 $html = WrReport::createBahnentabelle($page_titles);
954 } catch (WrReportException $e) {
955 $doc = new WrDOMDocument();
956 $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-bahnenregiontabelle-error', $e->getMessage())->text());
957 $html = $doc->saveHTML($doc->firstChild);
960 return array($html, 'markerType' => 'nowiki');
964 /// \brief Is called when the tag <rodelbahntabelle/> is encountered.
966 /// Description: See description of wrreport.php
967 public static function rodelbahntabelleParserHook($input, array $args, Parser $parser, PPFrame $frame) {
968 $parser->getOutput()->addModules('ext.wrreport');
971 // 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.
972 WrReport::addRegionFeedLink($parser->getTitle());
974 $dbr = wfGetDB(DB_SLAVE);
976 libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
978 $xml_input = '<rodelbahntabelle>' . $input . '</rodelbahntabelle>';
979 $xml = new SimpleXMLElement($xml_input); // input
980 } catch (Exception $e) {
981 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-xml', $xml_input)->text());
983 $whitespace = (string) $xml; // everything between <rodelbahntabelle> and </rodelbahntabelle> that's not a sub-element
984 if (strlen($whitespace) > 0 && !ctype_space($whitespace)) // there must not be anythin except sub-elements or whitespace
985 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-textbetweenelements', trim($xml))->text());
987 // page_ids of sledrun titles that that are going to be returned
989 foreach ($xml as $entry) { // entry is <rodelbahn>, <region> or <rodelbahnen>
990 $entry_page_ids = array(); // page_ids selected (or un-selected) for this entry.
991 $tagname = $entry->getName();
992 $attributes = array();
993 foreach ($entry->attributes() as $key => $value) $attributes[(string) $key] = (string) $value;
995 // is the tagname valid?
996 if (!in_array($tagname, array('rodelbahn', 'rodelbahnen', 'region')))
997 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-element', $tagname)->text());
999 // parse operation attribute
1000 $operation = '+'; // '+' (append) or '-' (subtract)
1001 if (array_key_exists('operation', $attributes)) {
1002 $operation = $attributes['operation'];
1003 if (!in_array($operation, array('+', '-')))
1004 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-value', $tagname, 'operation', $operation)->text());
1005 unset($attributes['operation']);
1008 // parse in_arbeit attribute
1009 $under_construction = false; // false (only sledruns that are not under construction), true (only sledruns under construction) or null (doen't matter)
1010 if ($tagname === 'rodelbahn') $under_construction = null; // different default value for tag <rodelbahn>.
1011 if (array_key_exists('in_arbeit', $attributes)) {
1012 if ($attributes['in_arbeit'] === 'nein') $under_construction = false;
1013 elseif ($attributes['in_arbeit'] === 'ja') $under_construction = true;
1014 elseif ($attributes['in_arbeit'] === '*') $under_construction = null;
1015 else throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-value', $tagname, 'in_arbeit', $attributes['in_arbeit'])->text());
1016 unset($attributes['in_arbeit']);
1019 // any attributes left that are not handled yet?
1020 if (count($attributes) > 0)
1021 throw new WrReportException(wfMessage('wrreport-rodelbahntabelle-invalid-attribute-name', $tagname, array_keys($attributes)[0])->text());
1025 $tables = array('wrsledruncache');
1029 if ($tagname === 'region') {
1030 // the following line would work if MySQL 5.5 would implement a real geospatial version of CONTAINS.
1031 // $where[] = 'CONTAINS(GEOMFROMWKB(' . $dbr->addQuotes($region_border_wkb) . '), POINT(position_longitude, position_latitude))'
1032 $tables[] = 'wrregion';
1033 $tables[] = 'wrregioncache';
1034 $where[] = 'wrregioncache.region_id=wrregion.id';
1035 $where[] = 'wrregioncache.page_id=wrsledruncache.page_id';
1036 $where['wrregion.name'] = $entry;
1040 if ($tagname == 'rodelbahn') {
1041 $page_title = Title::newFromText(trim($entry));
1042 $where['page_title'] = $page_title->getDBkey();
1045 // under contruction
1046 if ($under_construction === true) $where[] = 'wrsledruncache.under_construction';
1047 if ($under_construction === false) $where[] = 'not wrsledruncache.under_construction';
1050 $res = $dbr->select($tables, array('page_id' => 'wrsledruncache.page_id'), $where, __METHOD__, 'page_id');
1051 foreach ($res as $row) {
1052 $entry_page_ids[] = $row->page_id;
1054 $dbr->freeResult($res);
1057 // merge the entry page_ids with the page_ids
1058 if ($operation == '+') $page_ids = array_merge($page_ids, $entry_page_ids);
1059 elseif ($operation == '-') $page_ids = array_diff($page_ids, $entry_page_ids);
1062 // page_titles that are going to be returned
1063 $page_titles = Title::newFromIDs($page_ids);
1065 $html = WrReport::createBahnentabelle($page_titles);
1067 } catch (WrReportException $e) {
1068 $doc = new WrDOMDocument();
1069 $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-rodelbahntabelle-error', $e->getMessage())->text());
1070 $html = $doc->saveHTML($doc->firstChild);
1073 return array($html, 'markerType' => 'nowiki');
1077 /// \brief Is called when the tag <avatar>username</avatar> is encountered.
1078 public static function avatarParserHook($input, array $args, Parser $parser, PPFrame $frame) {
1079 $doc = new WrDOMDocument();
1080 $sla = new WrServicesLibravatar();
1084 if (is_null($input)) throw new WrReportException(wfMessage('wrreport-avatar-nousername')->text());
1085 $username = $parser->recursiveTagParse($input, $frame);
1086 $user = User::newFromName($username);
1087 if ($user === false) throw new WrReportException(wfMessage('wrreport-avatar-invalidusername', $username)->text());
1088 if ($user->getId() == 0) throw new WrReportException(wfMessage('wrreport-avatar-userunknown', $username)->text());
1090 // size attribute (optional)
1091 if (isset($args['size'])) $sla->setSize((int) $parser->recursiveTagParse($args['size'], $frame));
1093 // alt attribute (optional)
1094 $alt = wfMessage('wrreport-avatar-of', $username)->text();
1096 // create avatar (using the Services_Libravatar library to get avatar URL)
1097 $url = $sla->getUrl($user->getEmail());
1098 $doc->appendElement('img', array('src' => $url, 'alt' => $username, 'width' => $sla->getSize(), 'height' => $sla->getSize()));
1100 } catch (WrReportException $e) {
1101 $doc->appendElement('span', array('class' => 'error'))->appendText(wfMessage('wrreport-avatar-error', $e->getMessage())->text());
1104 // return result (markerType => nowiki prevents wiki formatting of the result)
1105 $html = $doc->saveHTML($doc->firstChild);
1106 return array($html, 'markerType' => 'nowiki');
1110 public static function MobileMenuHook($name, \MediaWiki\Minerva\MenuBuilder &$menu) {
1111 if ($name === 'discovery') {
1112 // delete "Random page". As a removeEntry function is missing,
1113 // a new menu is built here without the random page.
1114 $new_menu = new \MediaWiki\Minerva\MenuBuilder();
1115 foreach ($menu->getEntries() as $menuEntryRepresentation) {
1116 $new_entry_name = $menuEntryRepresentation['name'];
1117 if ($new_entry_name == 'random') continue;
1118 $new_entry_components = $menuEntryRepresentation['components'];
1119 $new_entry_isjsonly = isset($menuEntryRepresentation['class']) and $menuEntryRepresentation['class'] === 'jsonly';
1120 $new_entry = $new_menu->insert($new_entry_name, $new_entry_isjsonly);
1121 foreach ($new_entry_components as $new_entry_component) {
1122 $label = $new_entry_component['text'];
1123 $url = $new_entry_component['href'];
1124 $className = $new_entry_component['class'];
1125 $new_entry->addComponent($label, $url, $className, $new_entry_components);
1130 // add region menu entry
1131 $icon = MobileUI::iconClass('random', 'before');
1132 $title = Title::newFromText('Region', NS_CATEGORY);
1133 $menu->insert('region')->addComponent('Regionen', $title->getLocalURL(), $icon, array('id' => 'regionButton', 'data-event-name' => 'region'));
1144 /// Specal Page to show reports
1145 class SpecialWrReport extends SpecialPage {
1146 function __construct() {
1147 parent::__construct('wrreport');
1151 /// \param $par Possibilities:
1152 /// - action == 'view' (default)
1153 /// - action == 'preview': Preview new report
1154 /// - action == 'store': Store new report
1155 /// - action == 'deletepreview': Preview the deleted record
1156 /// - action == 'delete': Delete an existing report
1157 /// - action == 'showerror': Shows the error and exits
1158 /// \param $override_action If not NULL (default), it overrides the action in $par
1159 /// \param $errorMsg UFT-8 encoded error message (in WikiText) to show on top of the page or NULL (default):
1160 function execute($par, $override_action = NULL, $errorMsg = NULL) {
1161 $request = $this->getRequest();
1162 $output = $this->getOutput();
1165 $output->addWikiText(''); // this is necessary because otherwise $wgParser is not properly initialized
1167 $output->addModules('ext.wrreport');
1168 $this->setHeaders();
1171 $action = $request->getText('action');
1173 if ($request->getVal('preview')) $action = 'preview';
1174 elseif ($request->getVal('store')) $action = 'store';
1175 elseif ($request->getVal('deletepreview')) $action = 'deletepreview';
1176 elseif ($request->getVal('delete')) $action = 'delete';
1177 else $action = 'view';
1179 if ($override_action) $action = $override_action;
1181 // Show error message
1182 if ($errorMsg || $action == 'showerror') {
1183 $output->addWikiText('<div class="errorbox">' . $errorMsg . "</div>\n");
1184 if ($action == 'showerror') return;
1188 if ($action == 'view') {
1189 global $wgWrReportFeedRoot;
1190 $output->addFeedLink('atom', $wgWrReportFeedRoot . '/berichte/alle');
1191 $conditions = array('date_invalid > now()');
1192 $rows = wrReportGetReports($conditions);
1193 if (count($rows) == 0) $output->addHTML(wfMessage('wrreport-reports-none')->text());
1195 $output->addHTML(wrReportTableRender($rows, WRREPORT_DETAIL, wrReportUserMayDelete(), $wgParser));
1199 // Action deletepreview or delete
1200 elseif ($action == 'deletepreview' || $action == 'delete') {
1201 $reportid = (int) $request->getText('reportid');
1202 if ($reportid == 0) {
1203 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-noreport')->text());
1206 $rows = wrReportGetReports(array('id' => $reportid));
1207 if (count($rows) != 1) {
1208 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-invalid')->text());
1212 if (!is_null($row['delete_date'])) {
1213 $this->execute($par, 'showerror', wfMessage('wrreport-deletereport-alreadydeleted')->text());
1216 $delete_reason_public = $request->getText('delete_reason_public');
1217 $delete_person_name = $request->getText('delete_person_name');
1218 $delete_invisible = $request->getText('delete_invisible') ? TRUE : FALSE;
1219 if ($action == 'delete') {
1221 $title = Title::newFromId($row['page_id']);
1225 $delete_person_userid = $wgUser->getId();
1226 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.
1227 $delete_person_username = $wgUser->getName();
1229 // Check permissions - see also function wrReportUserMayDelete, that does also check permissions but does not return an error message.
1231 global $wgWrReportDeleteMode;
1232 if ($wgWrReportDeleteMode == 'deny') $errorMsg = wfMessage('wrreport-deletereport-deny')->text();
1233 elseif ($wgWrReportDeleteMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = wfMessage('wrreport-deletereport-loggedin')->text();
1234 elseif (!$delete_person_name || !$delete_reason_public) $errorMsg = wfMessage('wrreport-deletereport-incomplete')->text();
1236 $this->execute($par, 'deletepreview', $errorMsg);
1240 // "Delete" (update) entry
1241 $dbr = wfGetDB(DB_MASTER);
1245 'delete_date' => date('c'),
1246 'delete_person_name' => $delete_person_name,
1247 'delete_person_ip' => $_SERVER['REMOTE_ADDR'],
1248 'delete_person_userid' => $delete_person_userid,
1249 'delete_person_username' => $delete_person_username,
1250 'delete_reason_public' => $delete_reason_public,
1251 'delete_invisible' => $delete_invisible ? 't' : 'f'
1253 array('id' => $reportid)
1257 $title->invalidateCache();
1260 // Show success message
1261 $output->addWikiText(wfMessage('wrreport-deletereport-success', '[[' . $row['page_title'] . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $row['page_title'] . ']]')->text());
1263 if ($action == 'deletepreview') {
1264 $output->addWikiMsg('wrreport-deletereport-preview-before');
1265 $format = WRREPORT_COMPACT_PAGE;
1266 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1267 $output->addWikiMsg('wrreport-deletereport-preview-after');
1268 $row['delete_date'] = date('c');
1269 $row['delete_reason_public'] = $delete_reason_public;
1270 $row['delete_person_name'] = $delete_person_name;
1271 $row['delete_invisible'] = $delete_invisible;
1272 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1273 $output->addWikiMsg('wrreport-deletereport-preview-form');
1274 $output->addHTML(wrDeleteReportFormRender($reportid, $delete_person_name, $delete_reason_public, $delete_invisible));
1275 $output->addWikiMsg('wrreport-deletereport-preview-bottom');
1279 // Action preview or store
1280 elseif ($action == 'preview' || $action == 'store') {
1281 $page_title = $request->getText('page_title');
1282 $date_report = $request->getText('date_report');
1283 $time_report = $request->getText('time_report');
1284 $condition = $request->getText('condition');
1285 $description = $request->getText('description');
1286 $author_name = $request->getText('author_name');
1289 $time_report = trim($time_report); // strip whitespace
1293 if (preg_match('/^[0-2]?[0-9]$/', $time_report)) {
1294 // $time_report has 1 or 2 digits, e.g. 'h', or 'hh'.
1295 $hour = intval($time_report);
1297 } elseif (preg_match('/^([0-2]?[0-9]):?([0-9]{2})$/', $time_report, $matches)) {
1298 // $time_report has 3 or 4 digits, e.g. 'hmm' or 'hhmm' or 'h:mm' or 'hh:mm'.
1299 $hour = intval($matches[1]);
1300 $minute = intval($matches[2]);
1302 if (!is_null($hour) && $hour >= 0 && $hour < 24 && $minute >= 0 && $minute < 60) $time_report = sprintf('%02d:%02d', $hour, $minute);
1303 else $time_report = NULL;
1306 $condition = (int) $condition; // force to be nummeric. -1 ... "keine Bewertung", 0 ... "Bitte eingeben", 1 to 5 ... "Sehr gut" to "Geht nicht"
1307 if ($condition < -1 or $condition > 5) $condition = 0; // invalid condition: Tread like 0.
1308 $condition_sql = NULL;
1309 if ($condition >= 1 and $condition <= 5) $condition_sql = $condition;
1312 $author_name = trim($author_name);
1315 $title = Title::newFromText($page_title);
1316 $page_id = $title->getArticleID();
1317 if ($page_id == 0) $page_id = NULL;
1321 $author_userid = $wgUser->getId();
1322 if ($author_userid == 0) $author_userid = NULL; // to store a NULL value in the database if no user is logged in instead of 0.
1323 $author_username = $wgUser->getName();
1325 if ($action == 'store') {
1326 // check conditions/permissions
1328 global $wgWrReportMode;
1329 global $wgWrReportBlackListAll;
1330 global $wgWrReportBlackListStrangers;
1331 if ($wgWrReportMode == 'summer') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-summer')->text());
1332 elseif ($wgWrReportMode == 'deny') $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-deny')->text());
1333 elseif ($wgWrReportMode == 'loggedin' && !$wgUser->isLoggedIn()) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-loggedin')->text());
1334 elseif (!$page_id) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-pagenotfound')->text());
1335 elseif (in_array($page_title, $wgWrReportBlackListAll)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blacklist')->text());
1336 elseif (!$wgUser->isLoggedIn() && in_array($page_title, $wgWrReportBlackListStrangers)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-blackliststrangers')->text());
1337 elseif ($condition == 0) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-choosecondition')->text());
1338 elseif (!$wgUser->isLoggedIn()) {
1339 if (!$description) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterdescription')->text());
1340 elseif (!(stripos($description, 'http') === FALSE)) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-nohttp')->text());
1341 elseif (!$author_name) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-enterauthor')->text());
1344 // check author name
1346 $author_name_id = $wgUser->idFromName(strtolower($author_name));
1347 if ($wgUser->isLoggedIn()) {
1348 if ($author_name_id != 0 && $author_name_id != $wgUser->getId())
1349 $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorused')->text());
1351 if ($author_name_id != 0)
1352 $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-authorlogin')->text());
1356 // Chech whether identical reports are present
1358 $dbr = wfGetDB(DB_SLAVE);
1359 $cond = 'condition';
1361 if ($wgDBtype == "mysql") $cond = "`$cond`"; // "condition" is a reserved word in mysql
1362 $sqlConditions = array('page_id' => $page_id, 'date_report' => $date_report, 'time_report' => $time_report, $cond => $condition_sql, 'description' => $description, 'author_name' => $author_name);
1363 $res = $dbr->select('wrreport', 'id', $sqlConditions);
1364 if ($res->numRows() == 1) $errorMsg = htmlspecialchars(wfMessage('wrreport-newreport-alreadysaved')->text());
1365 $dbr->freeResult($res);
1368 // Show error if any
1370 $this->execute($par, 'preview', $errorMsg);
1375 $dbr = wfGetDB(DB_MASTER);
1379 'page_id' => $page_id,
1380 'page_title' => $page_title,
1381 'date_report' => $date_report,
1382 'time_report' => $time_report,
1383 'date_entry' => date('c'),
1384 'date_invalid' => date('c', strtotime('+9 days')),
1385 $cond => $condition_sql,
1386 'description' => $description,
1387 'author_name' => $author_name,
1388 'author_ip' => $_SERVER['REMOTE_ADDR'],
1389 'author_userid' => $author_userid,
1390 'author_username' => $author_username
1391 // 'delete_*' => // use database defaults (NULL)
1396 $title->invalidateCache();
1398 wrUpdateWrReportCacheTable($page_id);
1400 // Show success message
1401 $output->addWikiText(wfMessage('wrreport-newreport-success', '[[' . $page_title . '#' . wfMessage('wrreport-reports-sectionname')->text() . '|' . $page_title . ']]')->text());
1402 // We could redirect to result with the following line but we don't want to.
1403 // $output->redirect($title->getFullURL() . '#' . wfMessage('wrreport-reports-sectionname')->text());
1405 if ($action == 'preview') {
1406 $output->addWikiMsg('wrreport-newreport-preview-top');
1407 $format = WRREPORT_COMPACT_PAGE;
1408 $row = array_fill_keys(wrReportGetColumnNames(), NULL);
1409 $row['page_id'] = $page_id;
1410 $row['page_title'] = $page_title;
1411 $row['date_report'] = $date_report;
1412 $row['time_report'] = $time_report;
1413 $row['condition'] = $condition_sql;
1414 $row['description'] = $description;
1415 $row['author_name'] = $author_name;
1416 $row['author_userid'] = $author_userid;
1417 $row['author_username'] = $author_username;
1419 $output->addHTML(wrReportTableRender(array($row), $format, FALSE, $wgParser));
1420 $output->addWikiMsg('wrreport-newreport-preview-middle');
1421 $output->addHTML(wrReportFormRender(FALSE, $page_title, $date_report, $time_report, $condition, $description, $author_name));
1422 $output->addWikiMsg('wrreport-newreport-preview-bottom');
1423 if ($wgUser->isLoggedIn())
1424 $output->addWikiMsg('wrreport-newreport-preview-bottom-loggedin');
1426 $output->addWikiMsg('wrreport-newreport-preview-bottom-anonymous');
1431 else die('Wrong action');