Completed
Push — master ( 4c0a47...4e7d8d )
by
unknown
17:45
created

SRFCalendar::handleParameters()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 0
cts 13
cp 0
rs 9.6
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 6
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 14 and the first side effect is on line 3.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
$wgAutoloadClasses['SRFCHistoricalDate'] = dirname( __FILE__ )
4
	. '/SRFC_HistoricalDate.php';
5
6
/**
7
 * Result printer that prints query results as a monthly calendar.
8
 *
9
 * @file SRF_Calendar.php
10
 * @ingroup SemanticResultFormats
11
 *
12
 * @author Yaron Koren
13
 */
14
class SRFCalendar extends SMWResultPrinter {
15
	protected $mTemplate;
16
	protected $mUserParam;
17
	protected $mRealUserLang = null;
18
	protected $mStartMonth;
19
	protected $mStartYear;
20
21
	protected function setColors( $colorsText ) {
22
		$colors = [];
23
		$colorElements = explode( ',', $colorsText );
24
		foreach ( $colorElements as $colorElem ) {
25
			$propAndColor = explode( '=>', $colorElem );
26
			if ( count( $propAndColor ) == 2 ) {
27
				$colors[$propAndColor[0]] = $propAndColor[1];
28
			}
29
		}
30
		$this->mColors = $colors;
31
	}
32
33
	protected function handleParameters( array $params, $outputmode ) {
34
		parent::handleParameters( $params, $outputmode );
35
36
		$this->mTemplate = trim( $params['template'] );
37
		$this->mUserParam = trim( $params['userparam'] );
38
		// startmonth is initialized with current month by default
39
		$this->mStartMonth = trim( $params['startmonth'] );
40
		// startyear is initialized with current year by default
41
		$this->mStartYear = trim( $params['startyear'] );
42
43
		if ( $params['lang'] !== false ) {
44
			global $wgLang;
45
			// Store the actual user's language, so we can revert
46
			// back to it after printing the calendar.
47
			$this->mRealUserLang = clone ( $wgLang );
48
			$wgLang = Language::factory( trim( $params['lang'] ) );
49
		}
50
51
		$this->setColors( $params['colors'] );
52
	}
53
54
	public function getName() {
55
		return wfMessage( 'srf_printername_calendar' )->text();
56
	}
57
58
	/**
59
	 * @see SMWResultPrinter::buildResult
60
	 *
61
	 * @since 1.8
62
	 *
63
	 * @param SMWQueryResult $results
64
	 *
65
	 * @return string
66
	 */
67
	protected function buildResult( SMWQueryResult $results ) {
68
		$this->isHTML = false;
69
		$this->hasTemplates = false;
70
71
		// Skip checks - results with 0 entries are normal.
72
		return $this->getResultText( $results, SMW_OUTPUT_HTML );
73
	}
74
75
	/**
76
	 * (non-PHPdoc)
77
	 * @see SMWResultPrinter::getResultText()
78
	 *
79
	 * @todo Split up megamoth
80
	 */
81
	protected function getResultText( SMWQueryResult $res, $outputmode ) {
82
		$events = [];
83
84
		// Print all result rows.
85
		while ( $row = $res->getNext() ) {
86
			$dates = [];
87
			$title = $text = $color = '';
88
89
			if ( $this->mTemplate != '' ) {
90
				// Build template code
91
				$this->hasTemplates = true;
92
93
				if ( $this->mUserParam ) {
94
					$text = "|userparam=$this->mUserParam";
95
				}
96
97
				foreach ( $row as $i => $field ) {
98
					$pr = $field->getPrintRequest();
99
					$text .= '|' . ( $i + 1 ) . '=';
100
101
					while (
102
						( $object = $field->getNextDataValue() ) !== false
103
					) {
104
						if ( $object->getTypeID() == '_dat' ) {
105
							$text .= $object->getLongWikiText();
106
107
						// use shorter "LongText" for wikipage
108
						} elseif ( $object->getTypeID() == '_wpg' ) {
109
							// handling of "link=" param
110
							if ( $this->mLinkOthers ) {
111
								$text .=
112
									$object->getLongText( $outputmode, null );
113
							} else {
114
								$text .= $object->getWikiValue();
115
							}
116
						} else {
117
							$text .= $object->getShortText( $outputmode, null );
118
						}
119
120
						if (
121
							$pr->getMode() == SMWPrintRequest::PRINT_PROP &&
122
							$pr->getTypeID() == '_dat'
123
						) {
124
							$datePropLabel = $pr->getLabel();
125
							if ( !array_key_exists( $datePropLabel, $dates ) ) {
126
								$dates[$datePropLabel] = [];
127
							}
128
							$dates[$datePropLabel][] =
129
								$this->formatDateStr( $object );
130
						}
131
					}
132
				}
133
			} else {
134
				// Build simple text.
135
				$numNonDateProperties = 0;
136
				// Cycle through a 'row', which is the page
137
				// name (the first field) plus all its
138
				// properties.
139
				foreach ( $row as $i => $field ) {
140
					$pr = $field->getPrintRequest();
141
					// A property can have more than one
142
					// value - cycle through all the values
143
					// for this property.
144
					$textForProperty = '';
145
146
					while (
147
						( $object = $field->getNextDataValue() ) !== false
148
					) {
149
						if ( $object->getTypeID() == '_dat' ) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
150
							// Don't add date values to the display.
151
152
							// use shorter "LongText" for wikipage
153
						} elseif ( $object->getTypeID() == '_wpg' ) {
154
							if ( $i == 0 ) {
155
								$title = Title::newFromText(
156
									$object->getShortWikiText( false )
157
								);
158
							} else {
159
								$numNonDateProperties++;
160
161
								// handling of "headers=" param
162
								if ( $this->mShowHeaders == SMW_HEADERS_SHOW ) {
163
									$textForProperty .= $pr->getHTMLText(
164
										smwfGetLinker()
165
									) . ' ';
166
								} elseif (
167
									$this->mShowHeaders == SMW_HEADERS_PLAIN
168
								) {
169
									$textForProperty .= $pr->getLabel() . ' ';
170
								}
171
172
								// If $this->mShowHeaders == SMW_HEADERS_HIDE,
173
								//	print nothing.
174
								// handling of "link=" param
175
								if ( $this->mLinkOthers ) {
176
									$textForProperty .= $object->getLongText(
177
										$outputmode, smwfGetLinker()
178
									);
179
								} else {
180
									$textForProperty .= $object->getWikiValue();
181
								}
182
							}
183
						} else {
184
							$numNonDateProperties++;
185
							$textForProperty .=
186
								$pr->getHTMLText( smwfGetLinker() )
187
								. ' ' . $object->getShortText(
188
									$outputmode, smwfGetLinker()
189
								);
190
						}
191
						if (
192
							$pr->getMode() == SMWPrintRequest::PRINT_PROP &&
193
							$pr->getTypeID() == '_dat'
194
						) {
195
							$datePropLabel = $pr->getLabel();
196
							if ( !array_key_exists( $datePropLabel, $dates ) ) {
197
								$dates[$datePropLabel] = [];
198
							}
199
							$dates[$datePropLabel][] =
200
								$this->formatDateStr( $object );
201
						}
202
					}
203
204
					// Add the text for this property to
205
					// the main text, adding on parentheses
206
					// or commas as needed.
207
					if ( $numNonDateProperties == 1 ) {
208
						$text .= ' (';
209
					} elseif ( $numNonDateProperties > 1 ) {
210
						$text .= ', ';
211
					}
212
					$text .= $textForProperty;
213
				}
214
				if ( $numNonDateProperties > 0 ) {
215
					$text .= ')';
216
				}
217
			}
218
219
			if ( count( $dates ) > 0 ) {
220
				// Handle the 'color=' value, whether it came
221
				// from a compound query or a regular one.
222
				$resSubject = $field->getResultSubject();
0 ignored issues
show
Bug introduced by
The variable $field does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
223
				if ( isset( $resSubject->display_options )
224
					&& is_array( $resSubject->display_options ) ) {
225
					if ( array_key_exists(
226
							'color', $resSubject->display_options )
227
					) {
228
						$color = $resSubject->display_options['color'];
229
					}
230
					if (
231
						array_key_exists( 'colors',
232
							$resSubject->display_options )
233
					) {
234
						$this->setColors(
235
							$resSubject->display_options['colors']
236
						);
237
					}
238
				}
239
240
				foreach ( $dates as $label => $datesForLabel ) {
241
					foreach ( $datesForLabel as $date ) {
242
						$curText = $text;
243
						// If there's more than one
244
						// label, i.e. more than one
245
						// date property being displayed,
246
						// show the name of the current
247
						// property in parentheses.
248
						if ( count( $dates ) > 1 ) {
249
							$curText = "($label) " . $curText;
250
						}
251
						$curColor = $color;
252
						if ( array_key_exists( $label, $this->mColors ) ) {
253
							$curColor = $this->mColors[$label];
254
						}
255
						$events[] = [ $title, $curText, $date, $curColor ];
256
					}
257
				}
258
			}
259
		}
260
261
		$result = $this->displayCalendar( $events );
262
263
		// Go back to the actual user's language, in case a different
264
		// language had been specified for this calendar.
265
		if ( ! is_null( $this->mRealUserLang ) ) {
266
			global $wgLang;
267
			$wgLang = $this->mRealUserLang;
268
		}
269
270
		global $wgParser;
271
272
		if ( is_null( $wgParser->getTitle() ) ) {
273
			return $result;
274
		} else {
275
			return [ $result, 'noparse' => 'true', 'isHTML' => 'true' ];
276
		}
277
	}
278
279
	protected static function intToMonth( $int ) {
280
		$months = [
281
			'1' => 'january',
282
			'2' => 'february',
283
			'3' => 'march',
284
			'4' => 'april',
285
			'5' => 'may_long',
286
			'6' => 'june',
287
			'7' => 'july',
288
			'8' => 'august',
289
			'9' => 'september',
290
			'10' => 'october',
291
			'11' => 'november',
292
			'12' => 'december',
293
		];
294
295
		return wfMessage( array_key_exists( $int, $months )
296
			? $months[$int]
297
			: 'january' )->inContentLanguage()->text();
298
	}
299
300
	function formatDateStr( $object ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for formatDateStr.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
301
		// For some reason, getMonth() and getDay() sometimes return a
302
		// number with a leading zero - get rid of it using (int)
303
		return $object->getYear()
304
			. '-' . (int)$object->getMonth() . '-' . (int)$object->getDay();
305
	}
306
307
	function displayCalendar( $events ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Coding Style introduced by
displayCalendar uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for displayCalendar.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
308
		global $wgParser;
309
		global $srfgFirstDayOfWeek;
310
		global $srfgScriptPath;
311
312
		$context = RequestContext::getMain();
313
		$request = $context->getRequest();
314
		if ( ! $wgParser->mFirstCall ) {
315
			$wgParser->disableCache();
316
		}
317
318
		$context->getOutput()->addLink( [
319
			'rel' => 'stylesheet',
320
			'type' => 'text/css',
321
			'media' => 'screen, print',
322
			'href' => $srfgScriptPath
323
			. '/formats/calendar/resources/ext.srf.calendar.css'
324
		] );
325
326
		// Set variables differently depending on whether this is
327
		// being called from a regular page, via #ask, or from a
328
		// special page: most likely either Special:Ask or
329
		// Special:RunQuery.
330
		$pageTitle = $context->getTitle();
331
		if ( !$pageTitle ) {
332
			$pageTitle = $wgParser->getTitle();
333
		}
334
		$additionalQueryString = '';
335
		$hiddenInputs = '';
336
337
		if ( $pageTitle->isSpecialPage() ) {
338
			$requestValues = $request->getValues();
339
			// Also go through the predefined PHP variable
340
			// $_REQUEST, because $request->getValues() for
341
			// some reason doesn't return array values - is
342
			// there a better (less hacky) way to do this?
343
			foreach ( $_REQUEST as $key => $value ) {
344
				if ( is_array( $value ) ) {
345
					foreach ($value as $k2 => $v2 ) {
346
						$newKey = $key . '[' . $k2 . ']';
347
						$requestValues[$newKey] = $v2;
348
					}
349
				}
350
			}
351
352
			foreach ( $requestValues as $key => $value ) {
353
				if ( $key != 'month' && $key != 'year'
354
					// values from 'RunQuery'
355
					&& $key != 'query' && $key != 'free_text'
356
				) {
357
					$additionalQueryString .= "&$key=$value";
358
					$hiddenInputs .= "<input type=\"hidden\" " .
359
						"name=\"$key\" value=\"$value\" />";
360
				}
361
			}
362
		}
363
364
		// Set days of the week.
365
		$weekDayNames = [
366
			1 => wfMessage( 'sunday' )->text(),
367
			2 => wfMessage( 'monday' )->text(),
368
			3 => wfMessage( 'tuesday' )->text(),
369
			4 => wfMessage( 'wednesday' )->text(),
370
			5 => wfMessage( 'thursday' )->text(),
371
			6 => wfMessage( 'friday' )->text(),
372
			7 => wfMessage( 'saturday' )->text()
373
		];
374
		if ( empty( $srfgFirstDayOfWeek ) ) {
375
			$firstDayOfWeek = 1;
376
			$lastDayOfWeek = 7;
377
		} else {
378
			$firstDayOfWeek =
379
				array_search( $srfgFirstDayOfWeek, $weekDayNames );
380
			if ( $firstDayOfWeek === false ) {
381
				// Bad value for $srfgFirstDayOfWeek!
382
				print 'Warning: Bad value for $srfgFirstDayOfWeek "' .
383
					'(' . $srfgFirstDayOfWeek . '")';
384
				$firstDayOfWeek = 1;
385
			}
386
			if ( $firstDayOfWeek == 1 ) {
387
				$lastDayOfWeek = 7;
388
			} else {
389
				$lastDayOfWeek = $firstDayOfWeek - 1;
390
			}
391
		}
392
393
		// Now create the actual array of days of the week, based on
394
		// the start day
395
		$weekDays = [];
396
		for ( $i = 1; $i <= 7; $i++ ) {
397
			$curDay = ( ( $firstDayOfWeek + $i - 2 ) % 7 ) + 1;
398
			$weekDays[$i] = $weekDayNames[$curDay];
399
		}
400
401
		// Get all the date-based values we need - the current month
402
		// and year (i.e., the one the user is looking at - not
403
		// necessarily the "current" ones), the previous and next months
404
		// and years (same - note that the previous or next month could
405
		// be in a different year), the number of days in the current,
406
		// previous and next months, etc.
407
408
409
		if ( is_numeric( $this->mStartMonth ) &&
410
			( intval( $this->mStartMonth ) == $this->mStartMonth ) &&
411
			$this->mStartMonth >= 1 && $this->mStartMonth <= 12
412
		) {
413
			$curMonthNum = $this->mStartMonth;
414
		} else {
415
			$curMonthNum = date( 'n' );
416
		}
417
		if ( $request->getCheck( 'month' ) ) {
418
			$queryMonth = $request->getVal( 'month' );
419
			if ( is_numeric( $queryMonth ) &&
420
				( intval( $queryMonth ) == $queryMonth ) &&
421
				$queryMonth >= 1 && $queryMonth <= 12
422
			) {
423
				$curMonthNum = $request->getVal( 'month' );
424
			}
425
		}
426
427
		$curMonth = self::intToMonth( $curMonthNum );
428
429
		if ( is_numeric( $this->mStartYear ) &&
430
			( intval( $this->mStartYear ) == $this->mStartYear )
431
		) {
432
			$curYear = $this->mStartYear;
433
		} else {
434
			$curYear = date( 'Y' );
435
		}
436
		if ( $request->getCheck( 'year' ) ) {
437
			$queryYear = $request->getVal( 'year' );
438
			if ( is_numeric( $queryYear ) &&
439
				intval( $queryYear ) == $queryYear
440
			) {
441
				$curYear = $request->getVal( 'year' );
442
			}
443
		}
444
445
		if ( $curMonthNum == '1' ) {
446
			$prevMonthNum = '12';
447
			$prevYear = $curYear - 1;
448
		} else {
449
			$prevMonthNum = $curMonthNum - 1;
450
			$prevYear = $curYear;
451
		}
452
453
		if ( $curMonthNum == '12' ) {
454
			$nextMonthNum = '1';
455
			$nextYear = $curYear + 1;
456
		} else {
457
			$nextMonthNum = $curMonthNum + 1;
458
			$nextYear = $curYear;
459
		}
460
461
		// There's no year '0' - change it to '1' or '-1'.
462
		if ( $curYear == '0' ) { $curYear = '1'; }
463
		if ( $nextYear == '0' ) { $nextYear = '1'; }
464
		if ( $prevYear == '0' ) { $prevYear = '-1'; }
465
466
		$prevMonthUrl = $pageTitle->getLocalURL(
467
			"month=$prevMonthNum&year=$prevYear" .
468
			$additionalQueryString
469
		);
470
		$nextMonthUrl = $pageTitle->getLocalURL(
471
			"month=$nextMonthNum&year=$nextYear" .
472
			$additionalQueryString
473
		);
474
		$todayUrl = $pageTitle->getLocalURL( $additionalQueryString );
475
		$pageName = $pageTitle->getPrefixedDbKey();
0 ignored issues
show
Unused Code introduced by
$pageName is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
476
477
		$todayText = wfMessage( 'srfc_today' )->text();
478
		$prevMonthText = wfMessage( 'srfc_previousmonth' )->text();
479
		$nextMonthText = wfMessage( 'srfc_nextmonth' )->text();
480
		$goToMonthText = wfMessage( 'srfc_gotomonth' )->text();
481
482
		// Get day of the week that the first of this month falls on.
483
		$firstDay = new SRFCHistoricalDate();
484
		$firstDay->create( $curYear, $curMonthNum, 1 );
485
		$startDay = $firstDayOfWeek - $firstDay->getDayOfWeek();
486
		if ( $startDay > 0 ) { $startDay -= 7; }
487
		$daysInPrevMonth =
488
			SRFCHistoricalDate::daysInMonth( $prevYear, $prevMonthNum );
489
		$daysInCurMonth =
490
			SRFCHistoricalDate::daysInMonth( $curYear, $curMonthNum );
491
		$todayString = date( 'Y n j', time() );
492
		$pageName = $pageTitle->getPrefixedDbKey();
493
494
		// Create table for holding title and navigation information.
495
		$text = <<<END
496
<table class="navigation_table">
497
<tr><td class="month_name">$curMonth $curYear</td>
498
<td class="nav_links"><a href="$prevMonthUrl" title="$prevMonthText">
499
<img src="{$srfgScriptPath}/formats/calendar/resources/images/left-arrow.png" border="0" />
500
</a>&#160;<a href="$todayUrl">$todayText</a>&#160;
501
<a href="$nextMonthUrl" title="$nextMonthText">
502
<img src="{$srfgScriptPath}/formats/calendar/resources/images/right-arrow.png" border="0" />
503
</a></td><td class="nav_form"><form>
504
<input type="hidden" name="title" value="$pageName">
505
<select name="month">
506
507
END;
508
		for ( $i = 1; $i <= 12; $i++ ) {
509
			$monthName = self::intToMonth( $i );
510
			$selectedStr = ( $i == $curMonthNum ) ? "selected" : "";
511
			$text .= "<option value=\"$i\" $selectedStr>
512
				$monthName</option>\n";
513
		}
514
		$text .= <<<END
515
</select>
516
<input name="year" type="text" value="$curYear" size="4">
517
$hiddenInputs
518
<input type="submit" value="$goToMonthText">
519
</form>
520
</td>
521
</tr>
522
</table>
523
524
<table class="month_calendar">
525
<tr class="weekdays">
526
527
END;
528
		// First row of the main table holds the days of the week
529
		foreach ( $weekDays as $weekDay ) {
530
			$text .= "<td>$weekDay</td>";
531
		}
532
		$text .= "</tr>\n";
533
534
		// Now, create the calendar itself -
535
		// loop through a set of weeks, from a "Sunday" (which might be
536
		// before the beginning of the month) to a "Saturday" (which
537
		// might be after the end of the month).
538
		// "Sunday" and "Saturday" are in quotes because the actual
539
		// start and end days of the week can be set by the admin.
540
		$dayOfTheWeek = $firstDayOfWeek;
541
		$isLastWeek = false;
542
		for ( $day = $startDay;
543
			  ( ! $isLastWeek || $dayOfTheWeek != $firstDayOfWeek );
544
			  $day++ )
545
			{
546
			if ( $dayOfTheWeek == $firstDayOfWeek ) {
547
				$text .= "<tr>\n";
548
			}
549
			if ( "$curYear $curMonthNum $day" == $todayString ) {
550
				$text .= "<td class=\"today\">\n";
551
			} elseif ( $dayOfTheWeek == 1 || $dayOfTheWeek == 7 ) {
552
				$text .= "<td class=\"weekend_day\">\n";
553
			} else {
554
				$text .= "<td>\n";
555
			}
556
			if ( $day == $daysInCurMonth || $day > 50 ) {
557
				$isLastWeek = true;
558
			}
559
			// If this day is before or after the current month,
560
			// set a "display day" to show on the calendar, and
561
			// use a different CSS style for it.
562
			if ( $day > $daysInCurMonth || $day < 1 ) {
563
				if ( $day < 1 ) {
564
					$displayDay = $day + $daysInPrevMonth;
565
					$dateStr =
566
						$prevYear . '-' . $prevMonthNum . '-' . $displayDay;
567
				}
568
				if ( $day > $daysInCurMonth ) {
569
					$displayDay = $day - $daysInCurMonth;
570
					$dateStr =
571
						$nextYear . '-' . $nextMonthNum . '-' . $displayDay;
572
				}
573
				$text .=
574
					"<div class=\"day day_other_month\">$displayDay</div>\n";
0 ignored issues
show
Bug introduced by
The variable $displayDay does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
575
			} else {
576
				$dateStr = $curYear . '-' . $curMonthNum . '-' . $day;
577
				$text .= "<div class=\"day\">$day</div>\n";
578
			}
579
			// Finally, the most important step - get the events
580
			// that match this date, and the given set of criteria,
581
			// and display them in this date's box.
582
			$text .= "<div class=\"main\">\n";
583
			if ( $events == null ) {
584
				$events = [];
585
			}
586
			foreach ( $events as $event ) {
587
				list( $eventTitle, $otherText, $eventDate, $color ) = $event;
588
				if ( $eventDate == $dateStr ) {
589
					if ( $this->mTemplate != '' ) {
590
						$templatetext = '{{' . $this->mTemplate . $otherText .
591
							'|thisdate=' . $dateStr . '}}';
0 ignored issues
show
Bug introduced by
The variable $dateStr does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
592
						$templatetext =
593
							$wgParser->replaceVariables( $templatetext );
594
						$templatetext =
595
							$wgParser->recursiveTagParse( $templatetext );
596
						$text .= $templatetext;
597
					} else {
598
						$eventStr = Linker::link( $eventTitle );
599
						if ( $color != '' ) {
600
							$text .= "<div class=\"colored-entry\">
601
								<p style=\"border-left: 7px $color solid;\">
602
								$eventStr $otherText</p></div>\n";
603
						} else {
604
							$text .= "$eventStr $otherText\n\n";
605
						}
606
					}
607
				}
608
			}
609
			$text .= <<<END
610
</div>
611
</td>
612
613
END;
614
			if ( $dayOfTheWeek == $lastDayOfWeek ) {
615
				$text .= "</tr>\n";
616
			}
617
			if ( $dayOfTheWeek == 7 ) {
618
				$dayOfTheWeek = 1;
619
			} else {
620
				$dayOfTheWeek++;
621
			}
622
		}
623
		$text .= "</table>\n";
624
625
		return $text;
626
	}
627
628
	/**
629
	 * @see SMWResultPrinter::getParamDefinitions
630
	 *
631
	 * @since 1.8
632
	 *
633
	 * @param $definitions array of IParamDefinition
634
	 *
635
	 * @return array of IParamDefinition|array
636
	 */
637
	public function getParamDefinitions( array $definitions ) {
638
		$params = parent::getParamDefinitions( $definitions );
639
640
		$params['lang'] = [
641
			'message' => 'srf_paramdesc_calendarlang',
642
			'default' => false,
643
			'manipulatedefault' => false,
644
		];
645
646
		$params['template'] = [
647
			'message' => 'smw-paramdesc-template',
648
			'default' => '',
649
		];
650
651
		$params['userparam'] = [
652
			'message' => 'smw-paramdesc-userparam',
653
			'default' => '',
654
		];
655
656
		$params['color'] = [
657
			'message' => 'srf-paramdesc-color',
658
			'default' => '',
659
		];
660
661
		$params['colors'] = [
662
			'message' => 'srf_paramdesc_calendarcolors',
663
			'default' => '',
664
		];
665
666
		$params['startmonth'] = [
667
			'message' => 'srf-paramdesc-calendar-startmonth',
668
			'default' => date( 'n' ),
669
		];
670
671
		$params['startyear'] = [
672
			'message' => 'srf-paramdesc-calendar-startyear',
673
			'default' => date( 'Y' ),
674
		];
675
676
		return $params;
677
	}
678
}
679