Completed
Push — master256 ( 37ad46 )
by Karsten
05:12 queued 02:27
created

Gallery::buildResult()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 5.024

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 3
cts 5
cp 0.6
rs 9.8333
c 0
b 0
f 0
cc 4
nc 2
nop 1
crap 5.024
1
<?php
2
3
namespace SRF;
4
5
use Html;
6
use SMW\ResultPrinter;
7
use SMWDataItem;
8
use SMWOutputs;
9
use SMWPrintRequest;
10
use SMWQueryResult;
11
use SRFUtils;
12
use Title;
13
14
/**
15
 * Result printer that outputs query results as a image gallery.
16
 *
17
 * @author Jeroen De Dauw < [email protected] >
18
 * @author mwjames
19
 * @author Rowan Rodrik van der Molen
20
 */
21
class Gallery extends ResultPrinter {
22
23
	/**
24
	 * @see SMWResultPrinter::getName
25
	 *
26
	 * @return string
27
	 */
28
	public function getName() {
29
		return $this->msg( 'srf_printername_gallery' )->text();
30
	}
31
32
	/**
33
	 * @see SMWResultPrinter::buildResult
34
	 *
35
	 * @since 1.8
36
	 *
37
	 * @param SMWQueryResult $results
38
	 *
39
	 * @return string
40
	 */
41 1
	protected function buildResult( SMWQueryResult $results ) {
42
43
		// Intro/outro are not planned to work with the widget option
44 1
		if ( ( $this->params['intro'] !== '' || $this->params['outro'] !== '' ) && $this->params['widget'] !== '' ) {
45
			return $results->addErrors(
46
				[
47
					$this->msg( 'srf-error-option-mix', 'widget' )->inContentLanguage()->text()
48
				]
49
			);
50
		};
51
52 1
		return $this->getResultText( $results, $this->outputMode );
53
	}
54
55
	/**
56
	 * @see SMWResultPrinter::getResultText
57
	 *
58
	 * @param $results SMWQueryResult
59
	 * @param $outputmode integer
60
	 *
61
	 * @return string
62
	 */
63 1
	public function getResultText( SMWQueryResult $results, $outputmode ) {
0 ignored issues
show
Coding Style introduced by
getResultText uses the super-global variable $GLOBALS 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...
64
65
		// #224
66 1
		$ig = class_exists( '\TraditionalImageGallery' ) ? new \TraditionalImageGallery() : new \ImageGallery();
67
68 1
		$ig->setShowBytes( false );
69 1
		$ig->setShowFilename( false );
70 1
		$ig->setCaption( $this->mIntro ); // set caption to IQ header
71
72
		// No need for a special page to use the parser but for the "normal" page
73
		// view we have to ensure caption text is parsed correctly through the parser
74 1
		if ( !$this->isSpecialPage() ) {
75 1
			$ig->setParser( $GLOBALS['wgParser'] );
76
		}
77
78 1
		$html = '';
79 1
		$processing = '';
80
81 1
		if ( $this->params['widget'] == 'carousel' ) {
82
			// Carousel widget
83
			$ig->setAttributes( $this->getCarouselWidget() );
84 1
		} elseif ( $this->params['widget'] == 'slideshow' ) {
85
			// Slideshow widget
86
			$ig->setAttributes( $this->getSlideshowWidget() );
87
		} else {
88
89
			// Standard gallery attributes
90
			$attribs = [
91 1
				'id' => uniqid(),
92 1
				'class' => $this->getImageOverlay(),
93
			];
94
95 1
			$ig->setAttributes( $attribs );
96
		}
97
98
		// Only use redirects where the overlay option is not used and redirect
99
		// thumb images towards a different target
100 1
		if ( $this->params['redirects'] !== '' && !$this->params['overlay'] ) {
101
			SMWOutputs::requireResource( 'ext.srf.gallery.redirect' );
102
		}
103
104
		// For the carousel widget, the perrow option should not be set
105 1
		if ( $this->params['perrow'] !== '' && $this->params['widget'] !== 'carousel' ) {
106
			$ig->setPerRow( $this->params['perrow'] );
107
		}
108
109 1
		if ( $this->params['widths'] !== '' ) {
110
			$ig->setWidths( $this->params['widths'] );
111
		}
112
113 1
		if ( $this->params['heights'] !== '' ) {
114
			$ig->setHeights( $this->params['heights'] );
115
		}
116
117 1
		$printReqLabels = [];
118 1
		$redirectType = '';
119
120
		/**
121
		 * @var SMWPrintRequest $printReq
122
		 */
123 1
		foreach ( $results->getPrintRequests() as $printReq ) {
124 1
			$printReqLabels[] = $printReq->getLabel();
125
126
			// Get redirect type
127 1
			if ( $this->params['redirects'] === $printReq->getLabel() ) {
128 1
				$redirectType = $printReq->getTypeID();
129
			}
130
		}
131
132 1
		if ( $this->params['imageproperty'] !== '' && in_array( $this->params['imageproperty'], $printReqLabels ) ||
133 1
			$this->params['redirects'] !== '' && in_array( $this->params['redirects'], $printReqLabels ) ) {
134
135
			$this->addImageProperties(
136
				$results,
137
				$ig,
138
				$this->params['imageproperty'],
139
				$this->params['captionproperty'],
140
				$this->params['redirects'],
141
				$outputmode
142
			);
143
		} else {
144 1
			$this->addImagePages( $results, $ig );
145
		}
146
147
		// SRF Global settings
148 1
		SRFUtils::addGlobalJSVariables();
149
150
		// Display a processing image as long as the DOM is no ready
151 1
		if ( $this->params['widget'] !== '' ) {
152
			$processing = SRFUtils::htmlProcessingElement();
153
		}
154
155
		// Beautify the class selector
156 1
		$class = $this->params['widget'] ? '-' . $this->params['widget'] . ' ' : '';
157 1
		$class = $this->params['redirects'] !== '' && $this->params['overlay'] === false ? $class . ' srf-redirect' . ' ' : $class;
158 1
		$class = $this->params['class'] ? $class . ' ' . $this->params['class'] : $class;
159
160
		// Separate content from result output
161 1
		if ( !$ig->isEmpty() ) {
162
			$attribs = [
163 1
				'class' => 'srf-gallery' . $class,
164 1
				'data-redirect-type' => $redirectType,
165 1
				'data-ns-text' => $this->getFileNsTextForPageLanguage()
166
			];
167
168 1
			$html = Html::rawElement( 'div', $attribs, $processing . $ig->toHTML() );
169
		}
170
171
		// If available, create a link that points to further results
172 1
		if ( $this->linkFurtherResults( $results ) ) {
173
			$html .= $this->getLink( $results, SMW_OUTPUT_HTML )->getText( SMW_OUTPUT_HTML, $this->mLinker );
174
		}
175
176 1
		return [ $html, 'nowiki' => true, 'isHTML' => true ];
177
	}
178
179
	/**
180
	 * Handles queries where the images (and optionally their captions) are specified as properties.
181
	 *
182
	 * @since 1.5.3
183
	 *
184
	 * @param SMWQueryResult $results
185
	 * @param ImageGallery $ig
186
	 * @param string $imageProperty
187
	 * @param string $captionProperty
188
	 * @param string $redirectProperty
189
	 * @param $outputMode
190
	 */
191
	protected function addImageProperties( SMWQueryResult $results, &$ig, $imageProperty, $captionProperty, $redirectProperty, $outputMode ) {
192
		while ( /* array of SMWResultArray */
193
		$rows = $results->getNext() ) { // Objects (pages)
194
			$images = [];
195
			$captions = [];
196
			$redirects = [];
197
198
			for ( $i = 0, $n = count( $rows ); $i < $n; $i++ ) { // Properties
199
				/**
200
				 * @var SMWResultArray $resultArray
201
				 * @var SMWDataValue $dataValue
202
				 */
203
				$resultArray = $rows[$i];
204
205
				$label = $resultArray->getPrintRequest()->getMode() == SMWPrintRequest::PRINT_THIS
206
					? '-' : $resultArray->getPrintRequest()->getLabel();
207
208
				// Make sure always use real label here otherwise it results in an empty array
209
				if ( $resultArray->getPrintRequest()->getLabel() == $imageProperty ) {
210
					while ( ( $dataValue = $resultArray->getNextDataValue() ) !== false ) { // Property values
211
						if ( $dataValue->getTypeID() == '_wpg' ) {
212
							$images[] = $dataValue->getTitle();
213
						}
214
					}
215
				} elseif ( $label == $captionProperty ) {
216
					while ( ( $dataValue = $resultArray->getNextDataValue() ) !== false ) { // Property values
217
						$captions[] = $dataValue->getShortText( $outputMode, $this->getLinker( true ) );
218
					}
219
				} elseif ( $label == $redirectProperty ) {
220
					while ( ( $dataValue = $resultArray->getNextDataValue() ) !== false ) { // Property values
221
						if ( $dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_WIKIPAGE ) {
222
							$redirects[] = $dataValue->getTitle();
223
						} elseif ( $dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_URI ) {
224
							$redirects[] = $dataValue->getURL();
225
						}
226
					}
227
				}
228
			}
229
230
			// Check available matches against captions
231
			$amountMatches = count( $captions ) == count( $images );
232
			$hasCaption = $amountMatches || count( $captions ) > 0;
233
234
			// Check available matches against redirects
235
			$amountRedirects = count( $redirects ) == count( $images );
236
			$hasRedirect = $amountRedirects || count( $redirects ) > 0;
237
238
			/**
239
			 * @var Title $imgTitle
240
			 */
241
			foreach ( $images as $imgTitle ) {
242
				if ( $imgTitle->exists() ) {
243
					$imgCaption = $hasCaption ? ( $amountMatches ? array_shift( $captions ) : $captions[0] ) : '';
244
					$imgRedirect = $hasRedirect ? ( $amountRedirects ? array_shift( $redirects ) : $redirects[0] ) : '';
245
					$this->addImageToGallery( $ig, $imgTitle, $imgCaption, $imgRedirect );
246
				}
247
			}
248
		}
249
	}
250
251
	/**
252
	 * Handles queries where the result objects are image pages.
253
	 *
254
	 * @since 1.5.3
255
	 *
256
	 * @param SMWQueryResult $results
257
	 * @param ImageGallery $ig
258
	 */
259 1
	protected function addImagePages( SMWQueryResult $results, &$ig ) {
260 1
		while ( $row = $results->getNext() ) {
261
			/**
262
			 * @var SMWResultArray $firstField
263
			 */
264 1
			$firstField = $row[0];
265 1
			$nextObject = $firstField->getNextDataValue();
266
267 1
			if ( $nextObject !== false ) {
268 1
				$imgTitle = $nextObject->getTitle();
269
270
				// Ensure the title belongs to the image namespace
271 1
				if ( $imgTitle instanceof Title && $imgTitle->getNamespace() === NS_FILE ) {
0 ignored issues
show
Bug introduced by
The class Title does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
272 1
					$imgCaption = '';
273
274
					// Is there a property queried for display with ?property
275 1
					if ( isset( $row[1] ) ) {
276 1
						$imgCaption = $row[1]->getNextDataValue();
277 1
						if ( is_object( $imgCaption ) ) {
278 1
							$imgCaption = $imgCaption->getShortText( $this->outputMode, $this->getLinker( true ) );
279
						}
280
					}
281
282 1
					$this->addImageToGallery( $ig, $imgTitle, $imgCaption );
283
				}
284
			}
285
		}
286 1
	}
287
288
	/**
289
	 * Adds a single image to the gallery.
290
	 * Takes care of automatically adding a caption when none is provided and parsing it's wikitext.
291
	 *
292
	 * @since 1.5.3
293
	 *
294
	 * @param ImageGallery $ig The gallery to add the image to
295
	 * @param Title $imgTitle The title object of the page of the image
296
	 * @param string $imgCaption An optional caption for the image
297
	 * @param string $imgRedirect
298
	 */
299 1
	protected function addImageToGallery( &$ig, Title $imgTitle, $imgCaption, $imgRedirect = '' ) {
300
301 1
		if ( empty( $imgCaption ) ) {
302
			if ( $this->params['autocaptions'] ) {
303
				$imgCaption = $imgTitle->getBaseText();
304
305
				if ( !$this->params['fileextensions'] ) {
306
					$imgCaption = preg_replace( '#\.[^.]+$#', '', $imgCaption );
307
				}
308
			} else {
309
				$imgCaption = '';
310
			}
311
		} else {
312 1
			if ( $imgTitle instanceof Title && $imgTitle->getNamespace() == NS_FILE && !$this->isSpecialPage() ) {
0 ignored issues
show
Bug introduced by
The class Title does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
313 1
				$imgCaption = $ig->mParser->recursiveTagParse( $imgCaption );
314
			}
315
		}
316
		// Use image alt as helper for either text
317 1
		$imgAlt = $this->params['redirects'] === '' ? $imgCaption : $imgRedirect !== '' ? $imgRedirect : '';
318 1
		$ig->add( $imgTitle, $imgCaption, $imgAlt );
319 1
	}
320
321
	/**
322
	 * Returns the overlay setting
323
	 *
324
	 * @since 1.8
325
	 *
326
	 * @return string
327
	 */
328 1
	private function getImageOverlay() {
329 1
		if ( array_key_exists( 'overlay', $this->params ) && $this->params['overlay'] == true ) {
330
			SMWOutputs::requireResource( 'ext.srf.gallery.overlay' );
331
			return ' srf-overlay';
332
		} else {
333 1
			return '';
334
		}
335
	}
336
337
	/**
338
	 * Init carousel widget
339
	 *
340
	 * @since 1.8
341
	 *
342
	 * @return string
343
	 */
344
	private function getCarouselWidget() {
345
346
		// Set attributes for jcarousel
347
		$dataAttribs = [
348
			'wrap' => 'both', // Whether to wrap at the first/last item (or both) and jump back to the start/end.
349
			'vertical' => 'false', // Orientation: vertical = false means horizontal
350
			'rtl' => 'false', // Directionality: rtl = false means ltr
351
		];
352
353
		// Use the perrow parameter to determine the scroll sequence.
354
		if ( empty( $this->params['perrow'] ) ) {
355
			$dataAttribs['scroll'] = 1;  // default 1
356
		} else {
357
			$dataAttribs['scroll'] = $this->params['perrow'];
358
			$dataAttribs['visible'] = $this->params['perrow'];
359
		}
360
361
		$attribs = [
362
			'id' => uniqid(),
363
			'class' => 'jcarousel jcarousel-skin-smw' . $this->getImageOverlay(),
364
			'style' => 'display:none;',
365
		];
366
367
		foreach ( $dataAttribs as $name => $value ) {
368
			$attribs['data-' . $name] = $value;
369
		}
370
371
		SMWOutputs::requireResource( 'ext.srf.gallery.carousel' );
372
373
		return $attribs;
374
	}
375
376
	/**
377
	 * Init slideshow widget
378
	 *
379
	 * @since 1.8
380
	 *
381
	 * @return string
382
	 */
383
	private function getSlideshowWidget() {
384
385
		$attribs = [
386
			'id' => uniqid(),
387
			'class' => $this->getImageOverlay(),
388
			'style' => 'display:none;',
389
			'data-nav-control' => $this->params['navigation']
390
		];
391
392
		SMWOutputs::requireResource( 'ext.srf.gallery.slideshow' );
393
394
		return $attribs;
395
	}
396
397
	/**
398
	 * @see SMWResultPrinter::getParamDefinitions
399
	 *
400
	 * @since 1.8
401
	 *
402
	 * @param $definitions array of IParamDefinition
403
	 *
404
	 * @return array of IParamDefinition|array
405
	 */
406 1
	public function getParamDefinitions( array $definitions ) {
407 1
		$params = parent::getParamDefinitions( $definitions );
408
409 1
		$params['class'] = [
410
			'type' => 'string',
411
			'message' => 'srf-paramdesc-class',
412
			'default' => ''
413
		];
414
415 1
		$params['widget'] = [
416
			'type' => 'string',
417
			'default' => '',
418
			'message' => 'srf-paramdesc-widget',
419
			'values' => [ 'carousel', 'slideshow', '' ]
420
		];
421
422 1
		$params['navigation'] = [
423
			'type' => 'string',
424
			'default' => 'nav',
425
			'message' => 'srf-paramdesc-navigation',
426
			'values' => [ 'nav', 'pager', 'auto' ]
427
		];
428
429 1
		$params['overlay'] = [
430
			'type' => 'boolean',
431
			'default' => false,
432
			'message' => 'srf-paramdesc-overlay'
433
		];
434
435 1
		$params['perrow'] = [
436
			'type' => 'integer',
437
			'default' => '',
438
			'message' => 'srf_paramdesc_perrow'
439
		];
440
441 1
		$params['widths'] = [
442
			'type' => 'integer',
443
			'default' => '',
444
			'message' => 'srf_paramdesc_widths'
445
		];
446
447 1
		$params['heights'] = [
448
			'type' => 'integer',
449
			'default' => '',
450
			'message' => 'srf_paramdesc_heights'
451
		];
452
453 1
		$params['autocaptions'] = [
454
			'type' => 'boolean',
455
			'default' => true,
456
			'message' => 'srf_paramdesc_autocaptions'
457
		];
458
459 1
		$params['fileextensions'] = [
460
			'type' => 'boolean',
461
			'default' => false,
462
			'message' => 'srf_paramdesc_fileextensions'
463
		];
464
465 1
		$params['captionproperty'] = [
466
			'type' => 'string',
467
			'default' => '',
468
			'message' => 'srf_paramdesc_captionproperty'
469
		];
470
471 1
		$params['imageproperty'] = [
472
			'type' => 'string',
473
			'default' => '',
474
			'message' => 'srf_paramdesc_imageproperty'
475
		];
476
477 1
		$params['redirects'] = [
478
			'type' => 'string',
479
			'default' => '',
480
			'message' => 'srf-paramdesc-redirects'
481
		];
482
483 1
		return $params;
484
	}
485
486 1
	private function isSpecialPage() {
0 ignored issues
show
Coding Style introduced by
isSpecialPage uses the super-global variable $GLOBALS 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...
487 1
		$title = $GLOBALS['wgTitle'];
488 1
		return $title instanceof Title && $title->isSpecialPage();
0 ignored issues
show
Bug introduced by
The class Title does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
489
	}
490
491 1
	private function getFileNsTextForPageLanguage() {
0 ignored issues
show
Coding Style introduced by
getFileNsTextForPageLanguage uses the super-global variable $GLOBALS 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...
492 1
		$title = $GLOBALS['wgTitle'];
493 1
		return $title instanceof Title ? $title->getPageLanguage()->getNsText( NS_FILE ) : null;
0 ignored issues
show
Bug introduced by
The class Title does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
494
	}
495
496
}
497