GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( b3ee5f...a83cd4 )
by Brad
06:08 queued 03:01
created

functions.php ➔ foogallery_create_gallery()   B

Complexity

Conditions 6
Paths 18

Size

Total Lines 75

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 18
nop 2
dl 0
loc 75
rs 7.9232
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * FooGallery global functions
4
 *
5
 * @package   FooGallery
6
 * @author    Brad Vincent <[email protected]>
7
 * @license   GPL-2.0+
8
 * @link      https://github.com/fooplugins/foogallery
9
 * @copyright 2014 FooPlugins LLC
10
 */
11
12
/**
13
 * Returns the name of the plugin. (Allows the name to be overridden from extensions or functions.php)
14
 * @return string
15
 */
16
function foogallery_plugin_name() {
17
	return apply_filters( 'foogallery_plugin_name', 'FooGallery' );
18
}
19
20
/**
21
 * Return all the gallery templates used within FooGallery
22
 *
23
 * @return array
24
 */
25
function foogallery_gallery_templates() {
26
	return apply_filters( 'foogallery_gallery_templates', array() );
27
}
28
29
/**
30
 * Return a specific gallery template based on the slug
31
 * @param $slug
32
 *
33
 * @return bool|array
34
 */
35
function foogallery_get_gallery_template( $slug ) {
36
	foreach ( foogallery_gallery_templates() as $template ) {
37
		if ( $slug == $template['slug'] ) {
38
			return $template;
39
		}
40
	}
41
42
	return false;
43
}
44
45
/**
46
 * Return the FooGallery extension API class
47
 *
48
 * @return FooGallery_Extensions_API
49
 */
50
function foogallery_extensions_api() {
51
	return new FooGallery_Extensions_API();
52
}
53
54
/**
55
 * Returns the default gallery template
56
 *
57
 * @return string
58
 */
59
function foogallery_default_gallery_template() {
60
	return foogallery_get_setting( 'gallery_template' );
61
}
62
63
/**
64
 * Returns if gallery permalinks are enabled
65
 *
66
 * @return bool
67
 */
68
function foogallery_permalinks_enabled() {
69
	return foogallery_get_setting( 'gallery_permalinks_enabled' );
70
}
71
72
/**
73
 * Returns the gallery permalink
74
 *
75
 * @return string
76
 */
77
function foogallery_permalink() {
78
	return foogallery_get_setting( 'gallery_permalink' );
79
}
80
81
/**
82
 * Return the FooGallery saved setting, or a default value
83
 *
84
 * @param string $key The key for the setting
85
 *
86
 * @param bool $default The default if no value is saved or found
87
 *
88
 * @return mixed
89
 */
90
function foogallery_get_setting( $key, $default = false ) {
91
	$foogallery = FooGallery_Plugin::get_instance();
92
93
	return $foogallery->options()->get( $key, foogallery_get_default( $key, $default ) );
94
}
95
96
/**
97
 * Builds up a FooGallery gallery shortcode
98
 *
99
 * @param $gallery_id
100
 *
101
 * @return string
102
 */
103
function foogallery_build_gallery_shortcode( $gallery_id ) {
104
	return '[' . foogallery_gallery_shortcode_tag() . ' id="' . $gallery_id . '"]';
105
}
106
107
/**
108
 * Returns the gallery shortcode tag
109
 *
110
 * @return string
111
 */
112
function foogallery_gallery_shortcode_tag() {
113
	return apply_filters( 'foogallery_gallery_shortcode_tag', FOOGALLERY_CPT_GALLERY );
114
}
115
116
/**
117
 * Helper method for getting default settings
118
 *
119
 * @param string $key The default config key to retrieve.
120
 *
121
 * @param bool $default The default if no default is set or found
122
 *
123
 * @return string Key value on success, false on failure.
124
 */
125
function foogallery_get_default( $key, $default = false ) {
126
127
	$defaults = array(
128
		'gallery_template'           => 'default',
129
		'gallery_permalinks_enabled' => false,
130
		'gallery_permalink'          => 'gallery',
131
		'lightbox'                   => 'none',
132
		'thumb_jpeg_quality'         => '80',
133
		'thumb_resize_animations'    => true,
134
		'gallery_sorting'            => '',
135
		'datasource'				 => 'media_library'
136
	);
137
138
	// A handy filter to override the defaults
139
	$defaults = apply_filters( 'foogallery_defaults', $defaults );
140
141
	// Return the key specified.
142
	return isset($defaults[ $key ]) ? $defaults[ $key ] : $default;
143
}
144
145
/**
146
 * Returns the FooGallery Add Gallery Url within the admin
147
 *
148
 * @return string The Url to the FooGallery Add Gallery page in admin
149
 */
150
function foogallery_admin_add_gallery_url() {
151
	return admin_url( 'post-new.php?post_type=' . FOOGALLERY_CPT_GALLERY );
152
}
153
154
/**
155
 * Returns the FooGallery help page Url within the admin
156
 *
157
 * @return string The Url to the FooGallery help page in admin
158
 */
159
function foogallery_admin_help_url() {
160
	return admin_url( add_query_arg( array( 'page' => FOOGALLERY_ADMIN_MENU_HELP_SLUG ), foogallery_admin_menu_parent_slug() ) );
161
}
162
163
/**
164
 * Returns the FooGallery settings page Url within the admin
165
 *
166
 * @return string The Url to the FooGallery settings page in admin
167
 */
168
function foogallery_admin_settings_url() {
169
	return admin_url( add_query_arg( array( 'page' => FOOGALLERY_ADMIN_MENU_SETTINGS_SLUG ), foogallery_admin_menu_parent_slug() ) );
170
}
171
172
/**
173
 * Returns the FooGallery extensions page Url within the admin
174
 *
175
 * @return string The Url to the FooGallery extensions page in admin
176
 */
177
function foogallery_admin_extensions_url() {
178
	return admin_url( add_query_arg( array( 'page' => FOOGALLERY_ADMIN_MENU_EXTENSIONS_SLUG ), foogallery_admin_menu_parent_slug() ) );
179
}
180
181
/**
182
 * Returns the FooGallery system info page Url within the admin
183
 *
184
 * @return string The Url to the FooGallery system info page in admin
185
 */
186
function foogallery_admin_systeminfo_url() {
187
	return admin_url( add_query_arg( array( 'page' => FOOGALLERY_ADMIN_MENU_SYSTEMINFO_SLUG ), foogallery_admin_menu_parent_slug() ) );
188
}
189
190
/**
191
 * Returns the FooGallery pricing page Url within the admin
192
 *
193
 * @return string The Url to the FooGallery pricing page in admin
194
 */
195
function foogallery_admin_pricing_url() {
196
	return admin_url( add_query_arg( array( 'page' => FOOGALLERY_ADMIN_MENU_PRICING_SLUG ), foogallery_admin_menu_parent_slug() ) );
197
}
198
199
/**
200
 * Get a foogallery template setting for the current foogallery that is being output to the frontend
201
 * @param string	$key
202
 * @param string	$default
203
 *
204
 * @return bool
205
 */
206
function foogallery_gallery_template_setting( $key, $default = '' ) {
207
	global $current_foogallery;
208
	global $current_foogallery_arguments;
209
	global $current_foogallery_template;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
210
211
	$settings_key = "{$current_foogallery_template}_{$key}";
212
213
	if ( $current_foogallery_arguments && array_key_exists( $key, $current_foogallery_arguments ) ) {
214
		//try to get the value from the arguments
215
		$value = $current_foogallery_arguments[ $key ];
216
217
	} else if ( !empty( $current_foogallery ) && $current_foogallery->settings && array_key_exists( $settings_key, $current_foogallery->settings ) ) {
218
		//then get the value out of the saved gallery settings
219
		$value = $current_foogallery->settings[ $settings_key ];
220
	} else {
221
		//otherwise set it to the default
222
		$value = $default;
223
	}
224
225
	$value = apply_filters( 'foogallery_gallery_template_setting-' . $key, $value );
226
227
	return $value;
228
}
229
230
/**
231
 * Get the admin menu parent slug
232
 * @return string
233
 */
234
function foogallery_admin_menu_parent_slug() {
235
	return apply_filters( 'foogallery_admin_menu_parent_slug', FOOGALLERY_ADMIN_MENU_PARENT_SLUG );
236
}
237
238
/**
239
 * Helper function to build up the admin menu Url
240
 * @param array $extra_args
241
 *
242
 * @return string|void
243
 */
244
function foogallery_build_admin_menu_url( $extra_args = array() ) {
245
	$url = admin_url( foogallery_admin_menu_parent_slug() );
246
	if ( ! empty( $extra_args ) ) {
247
		$url = add_query_arg( $extra_args, $url );
248
	}
249
	return $url;
250
}
251
252
/**
253
 * Helper function for adding a foogallery sub menu
254
 *
255
 * @param $menu_title
256
 * @param string $capability
257
 * @param string $menu_slug
258
 * @param $function
259
 */
260
function foogallery_add_submenu_page( $menu_title, $capability, $menu_slug, $function ) {
261
	add_submenu_page(
262
		foogallery_admin_menu_parent_slug(),
263
		$menu_title,
264
		$menu_title,
265
        apply_filters( 'foogallery_admin_menu_capability', $capability ),
266
		$menu_slug,
267
		$function
268
	);
269
}
270
271
/**
272
 * Returns all FooGallery galleries
273
 *
274
 * @return FooGallery[] array of FooGallery galleries
275
 */
276
function foogallery_get_all_galleries( $excludes = false, $extra_args = false ) {
277
	$args = array(
278
		'post_type'     => FOOGALLERY_CPT_GALLERY,
279
		'post_status'	=> array( 'publish', 'draft' ),
280
		'cache_results' => false,
281
		'nopaging'      => true,
282
	);
283
284
	if ( is_array( $excludes ) ) {
285
		$args['post__not_in'] = $excludes;
286
	}
287
288
	if ( is_array( $extra_args ) ) {
289
		$args = array_merge( $args, $extra_args );
290
	}
291
292
	$gallery_posts = get_posts( $args );
293
294
	if ( empty( $gallery_posts ) ) {
295
		return array();
296
	}
297
298
	$galleries = array();
299
300
	foreach ( $gallery_posts as $post ) {
301
		$galleries[] = FooGallery::get( $post );
302
	}
303
304
	return $galleries;
305
}
306
307
/**
308
 * Parse some content and return an array of all gallery shortcodes that are used inside it
309
 *
310
 * @param $content The content to search for gallery shortcodes
311
 *
312
 * @return array An array of all the foogallery shortcodes found in the content
313
 */
314
function foogallery_extract_gallery_shortcodes( $content ) {
315
	$shortcodes = array();
316
317
	$regex_pattern = foogallery_gallery_shortcode_regex();
318
	if ( preg_match_all( '/' . $regex_pattern . '/s', $content, $matches ) ) {
319
		for ( $i = 0; $i < count( $matches[0] ); ++$i ) {
320
			$shortcode = $matches[0][$i];
321
			$args = $matches[3][$i];
322
			$attribure_string = str_replace( ' ', '&', trim( $args ) );
323
			$attribure_string = str_replace( '"', '', $attribure_string );
324
			$attributes = wp_parse_args( $attribure_string );
325
			if ( array_key_exists( 'id', $attributes ) ) {
326
				$id = intval( $attributes['id'] );
327
				$shortcodes[ $id ] = $shortcode;
328
			}
329
		}
330
	}
331
332
	return $shortcodes;
333
}
334
335
/**
336
 * Build up the FooGallery shortcode regex
337
 *
338
 * @return string
339
 */
340
function foogallery_gallery_shortcode_regex() {
341
	$tag = foogallery_gallery_shortcode_tag();
342
343
	return
344
		'\\['                              	 // Opening bracket
345
		. '(\\[?)'                           // 1: Optional second opening bracket for escaping shortcodes: [[tag]]
346
		. "($tag)"                     		 // 2: Shortcode name
347
		. '(?![\\w-])'                       // Not followed by word character or hyphen
348
		. '('                                // 3: Unroll the loop: Inside the opening shortcode tag
349
		.     '[^\\]\\/]*'                   // Not a closing bracket or forward slash
350
		.     '(?:'
351
		.         '\\/(?!\\])'               // A forward slash not followed by a closing bracket
352
		.         '[^\\]\\/]*'               // Not a closing bracket or forward slash
353
		.     ')*?'
354
		. ')'
355
		. '(?:'
356
		.     '(\\/)'                        // 4: Self closing tag ...
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
357
		.     '\\]'                          // ... and closing bracket
358
		. '|'
359
		.     '\\]'                          // Closing bracket
360
		.     '(?:'
361
		.         '('                        // 5: Unroll the loop: Optionally, anything between the opening and closing shortcode tags
362
		.             '[^\\[]*+'             // Not an opening bracket
363
		.             '(?:'
364
		.                 '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
365
		.                 '[^\\[]*+'         // Not an opening bracket
366
		.             ')*+'
367
		.         ')'
368
		.         '\\[\\/\\2\\]'             // Closing shortcode tag
369
		.     ')?'
370
		. ')'
371
		. '(\\]?)';                          // 6: Optional second closing bracket for escaping shortcodes: [[tag]]
372
}
373
374
/**
375
 * Builds up a class attribute that can be used in a gallery template
376
 * @param $gallery FooGallery
377
 *
378
 * @return string the classname based on the gallery and any extra attributes
379
 */
380
function foogallery_build_class_attribute( $gallery ) {
381
382
	$classes[] = 'foogallery';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$classes was never initialized. Although not strictly required by PHP, it is generally a good practice to add $classes = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
383
	$classes[] = 'foogallery-container';
384
	$classes[] = "foogallery-{$gallery->gallery_template}";
385
386
	$num_args = func_num_args();
387
388
	if ( $num_args > 1 ) {
389
		$arg_list = func_get_args();
390
		for ( $i = 1; $i < $num_args; $i++ ) {
391
			$classes[] = $arg_list[$i];
392
		}
393
	}
394
395
	$classes = apply_filters( 'foogallery_build_class_attribute', $classes, $gallery );
396
397
	$classes = array_filter( $classes );
398
399
	return implode( ' ', $classes );
400
}
401
402
/**
403
 * Builds up a SAFE class attribute that can be used in a gallery template
404
 * @param $gallery FooGallery
405
 *
406
 * @return string the classname based on the gallery and any extra attributes
407
 */
408
function foogallery_build_class_attribute_safe( $gallery ) {
0 ignored issues
show
Unused Code introduced by
The parameter $gallery is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
409
	$args = func_get_args();
410
	$result = call_user_func_array("foogallery_build_class_attribute", $args);
411
	return esc_attr( $result );
412
}
413
414
/**
415
 * Renders an escaped class attribute that can be used directly by gallery templates
416
 *
417
 * @param $gallery FooGallery
418
 */
419
function foogallery_build_class_attribute_render_safe( $gallery ) {
0 ignored issues
show
Unused Code introduced by
The parameter $gallery is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
420
	$args = func_get_args();
421
	$result = call_user_func_array("foogallery_build_class_attribute_safe", $args);
422
	echo $result;
423
}
424
425
/**
426
 * Builds up the attributes that are appended to a gallery template container
427
 *
428
 * @param $gallery    FooGallery
429
 * @param $attributes array
430
 *
431
 * @return string
432
 */
433
function foogallery_build_container_attributes_safe( $gallery, $attributes ) {
434
435
	//add the default gallery id
436
	$attributes['id'] = 'foogallery-gallery-' . $gallery->ID;
437
438
	//add the standard data-foogallery attribute so that the JS initializes correctly
439
    $attributes['data-foogallery'] = foogallery_build_container_data_options( $gallery, $attributes );
440
441
	//allow others to add their own attributes globally
442
	$attributes = apply_filters( 'foogallery_build_container_attributes', $attributes, $gallery );
443
444
	//allow others to add their own attributes for a specific gallery template
445
	$attributes = apply_filters( 'foogallery_build_container_attributes-' . $gallery->gallery_template, $attributes, $gallery );
446
447
	//clean up the attributes to make them safe for output
448
	$html = '';
449
	foreach( $attributes as $key=>$value) {
450
		$safe_value = esc_attr( $value );
451
		$html .= "{$key}=\"{$safe_value}\" ";
452
	}
453
454
	return $html;
455
}
456
457
/**
458
 * Builds up the data-foogallery attribute options that is used by the core javascript
459
 *
460
 * @param $gallery
461
 * @param $attributes
462
 *
463
 * @return string
464
 */
465
function foogallery_build_container_data_options( $gallery, $attributes ) {
466
	$options = apply_filters( 'foogallery_build_container_data_options', array(), $gallery, $attributes );
467
468
	$options = apply_filters( 'foogallery_build_container_data_options-'. $gallery->gallery_template, $options, $gallery, $attributes );
469
470
	if ( defined( 'JSON_UNESCAPED_UNICODE' ) ) {
471
		return json_encode( $options, JSON_UNESCAPED_UNICODE );
472
	} else {
473
		return json_encode( $options );
474
	}
475
}
476
477
/**
478
 * Render a foogallery
479
 *
480
 * @param       $gallery_id int The id of the foogallery you want to render
481
 * @param array $args
482
 */
483
function foogallery_render_gallery( $gallery_id, $args = array()) {
484
	//create new instance of template engine
485
	$engine = new FooGallery_Template_Loader();
486
487
	$shortcode_args = wp_parse_args( $args, array(
488
		'id' => $gallery_id
489
	) );
490
491
	$engine->render_template( $shortcode_args );
492
}
493
494
/**
495
 * Returns the available sorting options that can be chosen for galleries and albums
496
 */
497
function foogallery_sorting_options() {
498
	return apply_filters( 'foogallery_sorting_options', array(
499
		'' => __('Default', 'foogallery'),
500
		'date_desc' => __('Date created - newest first', 'foogallery'),
501
		'date_asc' => __('Date created - oldest first', 'foogallery'),
502
		'modified_desc' => __('Date modified - most recent first', 'foogallery'),
503
		'modified_asc' => __('Date modified - most recent last', 'foogallery'),
504
		'title_asc' => __('Title - alphabetically', 'foogallery'),
505
		'title_desc' => __('Title - reverse', 'foogallery'),
506
		'rand' => __('Random', 'foogallery')
507
	) );
508
}
509
510
function foogallery_sorting_get_posts_orderby_arg( $sorting_option ) {
511
	$orderby_arg = 'post__in';
512
513
	switch ( $sorting_option ) {
514
		case 'date_desc':
515
		case 'date_asc':
516
			$orderby_arg = 'date';
517
			break;
518
		case 'modified_desc':
519
		case 'modified_asc':
520
			$orderby_arg = 'modified';
521
			break;
522
		case 'title_asc':
523
		case 'title_desc':
524
			$orderby_arg = 'title';
525
			break;
526
		case 'rand':
527
			$orderby_arg = 'rand';
528
			break;
529
	}
530
531
	return apply_filters( 'foogallery_sorting_get_posts_orderby_arg', $orderby_arg, $sorting_option );
532
}
533
534
function foogallery_sorting_get_posts_order_arg( $sorting_option ) {
535
	$order_arg = 'DESC';
536
537
	switch ( $sorting_option ) {
538
		case 'date_asc':
539
		case 'modified_asc':
540
		case 'title_asc':
541
		$order_arg = 'ASC';
542
			break;
543
	}
544
545
	return apply_filters( 'foogallery_sorting_get_posts_order_arg', $order_arg, $sorting_option );
546
}
547
548
/**
549
 * @deprecated 1.4.7 Default templates loaded by default and no longer activated via extension
550
 *
551
 * Activate the default templates extension when there are no gallery templates loaded
552
 */
553
function foogallery_activate_default_templates_extension() {
554
    //no longer needed but left in case any 3rd party extensions call this function
555
    _deprecated_function( __FUNCTION__, '1.4.7' );
556
}
557
558
/**
559
 * Allow FooGallery to enqueue stylesheet and allow them to be enqueued in the head on the next page load
560
 *
561
 * @param $handle string
562
 * @param $src string
563
 * @param array $deps
564
 * @param bool $ver
565
 * @param string $media
566
 */
567
function foogallery_enqueue_style( $handle, $src, $deps = array(), $ver = false, $media = 'all' ) {
568
	wp_enqueue_style( $handle, $src, $deps, $ver, $media );
569
	do_action( 'foogallery_enqueue_style', $handle, $src, $deps, $ver, $media );
570
}
571
572
573
/**
574
 * Returns all foogallery post objects that are attached to the post
575
 *
576
 * @param $post_id int The ID of the post
577
 *
578
 * @return array List of foogallery posts.
579
 */
580
function foogallery_get_galleries_attached_to_post( $post_id ) {
581
	$gallery_ids = get_post_meta( $post_id, FOOGALLERY_META_POST_USAGE, false );
582
583
	if ( !empty( $gallery_ids ) ) {
584
		return get_posts( array(
585
			'post_type'      => array( FOOGALLERY_CPT_GALLERY, ),
586
			'post_status'    => array( 'draft', 'publish' ),
587
			'posts_per_page' => -1,
588
			'include'        => $gallery_ids
589
		) );
590
	}
591
592
	return array();
593
}
594
595
/**
596
 * Clears all css load optimization post meta
597
 */
598
function foogallery_clear_all_css_load_optimizations() {
599
	delete_post_meta_by_key( FOOGALLERY_META_POST_USAGE_CSS );
600
}
601
602
/**
603
 * Performs a check to see if the plugin has been updated, and perform any housekeeping if necessary
604
 */
605
function foogallery_perform_version_check() {
606
	$checker = new FooGallery_Version_Check();
607
	$checker->perform_check();
608
}
609
610
/**
611
 * Returns the JPEG quality used when generating thumbnails
612
 *
613
 * @return int The quality value stored in settings
614
 */
615
function foogallery_thumbnail_jpeg_quality() {
616
	$quality = intval( foogallery_get_setting( 'thumb_jpeg_quality' ) );
617
618
	//check if we get an invalid value for whatever reason and if so return a default of 80
619
	if ( $quality <= 0 ) {
620
		$quality = 80;
621
	}
622
623
	return $quality;
624
}
625
626
/**
627
 * Returns the caption title source setting
628
 *
629
 * @return string
630
 */
631
function foogallery_caption_title_source() {
632
	$source = foogallery_get_setting( 'caption_title_source', 'caption' );
0 ignored issues
show
Documentation introduced by
'caption' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
633
634
	if ( empty( $source ) ) {
635
		$source = 'caption';
636
	}
637
638
	return $source;
639
}
640
641
/**
642
 * Returns the attachment caption title based on the caption_title_source setting
643
 *
644
 * @param WP_Post $attachment_post
645
 * @param bool $source
646
 *
647
 * @return string
648
 */
649
function foogallery_get_caption_title_for_attachment($attachment_post, $source = false) {
650
	if ( false === $source ) {
651
		$source = foogallery_gallery_template_setting( 'caption_title_source', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
652
		if ( empty( $source ) || "none" === $source ) {
653
			$source = foogallery_caption_title_source();
654
		}
655
	}
656
657
	switch ( $source ) {
658
		case 'title':
659
			$caption = trim( $attachment_post->post_title );
660
			break;
661
		case 'desc':
662
			$caption = trim( $attachment_post->post_content );
663
			break;
664
		case 'alt':
665
			$caption = trim( get_post_meta( $attachment_post->ID, '_wp_attachment_image_alt', true ) );
666
			break;
667
		default:
668
			$caption = trim( $attachment_post->post_excerpt );
669
	}
670
671
	return apply_filters( 'foogallery_get_caption_title_for_attachment', $caption, $attachment_post );
672
}
673
674
/**
675
 * Returns the caption description source setting
676
 *
677
 * @return string
678
 */
679
function foogallery_caption_desc_source() {
680
	$source = foogallery_get_setting( 'caption_desc_source', 'desc' );
0 ignored issues
show
Documentation introduced by
'desc' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
681
682
	if ( empty( $source ) ) {
683
		$source = 'desc';
684
	}
685
686
	return $source;
687
}
688
689
/**
690
 * Returns the attachment caption description based on the caption_desc_source setting
691
 *
692
 * @param WP_Post $attachment_post
693
 * @param bool $source
694
 *
695
 * @return string
696
 */
697
function foogallery_get_caption_desc_for_attachment($attachment_post, $source = false) {
698
	if ( false === $source ) {
699
		$source = foogallery_gallery_template_setting( 'caption_desc_source', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
700
		if ( empty( $source ) || "none" === $source ) {
701
			$source = foogallery_caption_desc_source();
702
		}
703
	}
704
705
	switch ( $source ) {
706
		case 'title':
707
			$caption = trim( $attachment_post->post_title );
708
			break;
709
		case 'caption':
710
			$caption = trim( $attachment_post->post_excerpt );
711
			break;
712
		case 'alt':
713
			$caption = trim( get_post_meta( $attachment_post->ID, '_wp_attachment_image_alt', true ) );
714
			break;
715
		default:
716
			$caption = trim( $attachment_post->post_content );
717
	}
718
719
	return apply_filters( 'foogallery_get_caption_desc_for_attachment', $caption, $attachment_post );
720
}
721
722
/**
723
 * Runs thumbnail tests and outputs results in a table format
724
 */
725
function foogallery_output_thumbnail_generation_results() {
726
	$thumbs = new FooGallery_Thumbnails();
727
	try {
728
		$results = $thumbs->run_thumbnail_generation_tests();
729
        if ( $results['success'] ) {
730
            echo '<span style="color:#0c0">' . __('Thumbnail generation test ran successfully.', 'foogallery') . '</span>';
731
        } else {
732
            echo '<span style="color:#c00">' . __('Thumbnail generation test failed!', 'foogallery') . '</span>';
733
            var_dump( $results['error'] );
734
			var_dump( $results['file_info'] );
735
        }
736
	}
737
	catch (Exception $e) {
738
		echo 'Exception: ' . $e->getMessage();
739
	}
740
}
741
742
/**
743
 * Returns the URL to the test image
744
 *
745
 * @return string
746
 */
747
function foogallery_test_thumb_url() {
748
    return apply_filters( 'foogallery_test_thumb_url', FOOGALLERY_URL . 'assets/logo.png' );
749
}
750
751
/**
752
 * Return all the gallery datasources used within FooGallery
753
 *
754
 * @return array
755
 */
756
function foogallery_gallery_datasources() {
757
	$default_datasource = foogallery_default_datasource();
758
759
	$datasources[$default_datasource] = 'FooGalleryDatasource_MediaLibrary';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$datasources was never initialized. Although not strictly required by PHP, it is generally a good practice to add $datasources = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
760
761
	return apply_filters( 'foogallery_gallery_datasources', $datasources );
762
}
763
764
/**
765
 * Returns the default gallery datasource
766
 *
767
 * @return string
768
 */
769
function foogallery_default_datasource() {
770
	return foogallery_get_default( 'datasource', 'media_library' );
0 ignored issues
show
Documentation introduced by
'media_library' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
771
}
772
773
/**
774
 * Instantiates a FooGallery datasource based on a datasource name
775
 *
776
 * @param $datasource_name string
777
 *
778
 * @return IFooGalleryDatasource
779
 */
780
function foogallery_instantiate_datasource( $datasource_name ) {
781
	$datasources = foogallery_gallery_datasources();
782
	if ( array_key_exists( $datasource_name, $datasources ) ) {
783
		return new $datasources[$datasource_name];
784
	}
785
786
	return new FooGalleryDatasource_MediaLibrary();
787
}
788
789
/**
790
 * Returns the src to the built-in image placeholder
791
 * @return string
792
 */
793
function foogallery_image_placeholder_src() {
794
	return apply_filters( 'foogallery_image_placeholder_src', FOOGALLERY_URL . 'assets/image-placeholder.png' );
795
}
796
797
/**
798
 * Returns the image html for the built-in image placeholder
799
 *
800
 * @param array $args
801
 *
802
 * @return string
803
 */
804
function foogallery_image_placeholder_html( $args ) {
805
	if ( !isset( $args ) ) {
806
		$args = array(
807
			'width' => 150,
808
			'height' => 150
809
		);
810
	}
811
812
	$args['src'] = foogallery_image_placeholder_src();
813
	$args = array_map( 'esc_attr', $args );
814
	$html = '<img ';
815
	foreach ( $args as $name => $value ) {
816
		$html .= " $name=" . '"' . $value . '"';
817
	}
818
	$html .= ' />';
819
	return apply_filters( 'foogallery_image_placeholder_html', $html, $args );
820
}
821
822
/**
823
 * Returns the thumbnail html for the featured attachment for a gallery.
824
 * If no featured attachment can be found, then a placeholder image src is returned instead
825
 *
826
 * @param FooGallery $gallery
827
 * @param array $args
828
 *
829
 * @return string
830
 */
831
function foogallery_find_featured_attachment_thumbnail_html( $gallery, $args = null ){
832
    if ( !isset( $gallery ) || false === $gallery ) return '';
833
834
	if ( !isset( $args ) ) {
835
		$args = array(
836
			'width' => 150,
837
			'height' => 150
838
		);
839
	}
840
841
	$featuredAttachment = $gallery->featured_attachment();
842
	if ( $featuredAttachment ) {
843
		return $featuredAttachment->html_img( $args );
844
	} else {
845
		//if we have no featured attachment, then use the built-in image placeholder
846
		return foogallery_image_placeholder_html( $args );
847
	}
848
}
849
850
/**
851
 * Returns the thumbnail src for the featured attachment for a gallery.
852
 * If no featured attachment can be found, then a placeholder image src is returned instead
853
 *
854
 * @param FooGallery $gallery
855
 * @param array $args
856
 *
857
 * @return string
858
 */
859
function foogallery_find_featured_attachment_thumbnail_src( $gallery, $args = null ){
860
	if ( !isset( $gallery ) || false === $gallery ) return '';
861
862
	if ( !isset( $args ) ) {
863
		$args = array(
864
			'width' => 150,
865
			'height' => 150
866
		);
867
	}
868
869
	$featuredAttachment = $gallery->featured_attachment();
870
	if ( $featuredAttachment ) {
871
		return $featuredAttachment->html_img_src( $args );
872
	} else {
873
		//if we have no featured attachment, then use the built-in image placeholder
874
		return foogallery_image_placeholder_src();
875
	}
876
}
877
878
/**
879
 * Returns the available retina options that can be chosen
880
 */
881
function foogallery_retina_options() {
882
    return apply_filters( 'foogallery_retina_options', array(
883
        '2x' => __('2x', 'foogallery'),
884
        '3x' => __('3x', 'foogallery'),
885
        '4x' => __('4x', 'foogallery')
886
    ) );
887
}
888
889
/**
890
 * Does a full uninstall of the plugin including all data and settings!
891
 */
892
function foogallery_uninstall() {
893
894
	if ( !current_user_can( 'install_plugins' ) ) exit;
895
896
	//delete all gallery posts first
897
	global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
898
	$query = "SELECT p.ID FROM {$wpdb->posts} AS p WHERE p.post_type IN (%s)";
899
	$gallery_post_ids = $wpdb->get_col( $wpdb->prepare( $query, FOOGALLERY_CPT_GALLERY ) );
900
901
	if ( !empty( $gallery_post_ids ) ) {
902
		$deleted = 0;
903
		foreach ( $gallery_post_ids as $post_id ) {
904
			$del = wp_delete_post( $post_id );
905
			if ( false !== $del ) {
906
				++$deleted;
907
			}
908
		}
909
	}
910
911
	//delete all options
912
	if ( is_network_admin() ) {
913
		delete_site_option( FOOGALLERY_SLUG );
914
	} else {
915
		delete_option( FOOGALLERY_SLUG );
916
	}
917
	delete_option( FOOGALLERY_OPTION_VERSION );
918
	delete_option( FOOGALLERY_OPTION_THUMB_TEST );
919
	delete_option( FOOGALLERY_EXTENSIONS_SLUGS_OPTIONS_KEY );
920
	delete_option( FOOGALLERY_EXTENSIONS_LOADING_ERRORS );
921
	delete_option( FOOGALLERY_EXTENSIONS_LOADING_ERRORS_RESPONSE );
922
	delete_option( FOOGALLERY_EXTENSIONS_SLUGS_OPTIONS_KEY );
923
	delete_option( FOOGALLERY_EXTENSIONS_ACTIVATED_OPTIONS_KEY );
924
	delete_option( FOOGALLERY_EXTENSIONS_ERRORS_OPTIONS_KEY );
925
926
	//let any extensions clean up after themselves
927
	do_action( 'foogallery_uninstall' );
928
}
929
930
/**
931
 * Returns an attachment field friendly name, based on a field name that is passed in
932
 *
933
 * @param $field
934
 *
935
 * @return string
936
 */
937
function foogallery_get_attachment_field_friendly_name( $field ) {
938
	switch ( $field ) {
939
		case 'title':
940
			return __( 'Attachment Title', 'foogallery' );
941
		case 'caption':
942
			return __( 'Attachment Caption', 'foogallery' );
943
		case 'desc':
944
			return __( 'Attachment Description', 'foogallery' );
945
		case 'alt':
946
			return __( 'Attachment Alt', 'foogallery' );
947
	}
948
}
949
950
/**
951
 * Returns the fields for a specific gallery template
952
 *
953
 * @param $template mixed
954
 * @return mixed
955
 */
956
function foogallery_get_fields_for_template( $template ) {
957
958
    if ( is_string( $template ) ) {
959
        $template = foogallery_get_gallery_template( $template );
960
    }
961
962
    $fields = $template['fields'];
963
964
    // Allow for extensions to override fields for every gallery template.
965
    // Also passes the $template along so you can inspect and conditionally alter fields based on the template properties
966
    $fields = apply_filters( 'foogallery_override_gallery_template_fields', $fields, $template );
967
968
    // Allow for extensions to override fields for a specific gallery template.
969
    // Also passes the $template along so you can inspect and conditionally alter fields based on the template properties
970
    $fields = apply_filters( "foogallery_override_gallery_template_fields-{$template['slug']}", $fields, $template );
971
972
    foreach ( $fields as &$field ) {
973
        //allow for the field to be altered by extensions. Also used by the build-in fields, e.g. lightbox
974
        $field = apply_filters( 'foogallery_alter_gallery_template_field', $field, $template['slug'] );
975
    }
976
977
    return $fields;
978
}
979
980
/**
981
 * Builds default settings for the supplied gallery template
982
 *
983
 * @param $template_name
984
 * @return array
985
 */
986
function foogallery_build_default_settings_for_gallery_template( $template_name ) {
987
    $fields = foogallery_get_fields_for_template( $template_name );
988
    $settings = array();
989
990
    //loop through the fields and build up an array of keys and default values
991
    foreach( $fields as $field ) {
992
        $default = array_key_exists( 'default', $field ) ? $field['default'] : false;
993
        if ( !empty( $default ) ) {
994
            $settings["{$template_name}_{$field['id']}"] = $default;
995
        }
996
    }
997
998
    return $settings;
999
}
1000
1001
/**
1002
 * Returns the choices used for the thumb link field type
1003
 * @return array
1004
 */
1005
function foogallery_gallery_template_field_thumb_link_choices() {
1006
    return apply_filters( 'foogallery_gallery_template_field_thumb_links', array(
1007
        'image'  => __( 'Full Size Image (Lightbox)', 'foogallery' ),
1008
        'page'   => __( 'Image Attachment Page', 'foogallery' ),
1009
        'custom' => __( 'Custom URL', 'foogallery' ),
1010
        'none'   => __( 'Not linked', 'foogallery' ),
1011
    ) );
1012
}
1013
1014
/**
1015
 * Returns the choices used for the lightbox field type
1016
 * @return array
1017
 */
1018
function foogallery_gallery_template_field_lightbox_choices() {
1019
    $lightboxes = apply_filters( 'foogallery_gallery_template_field_lightboxes', array() );
1020
    $lightboxes['none'] = __( 'None', 'foogallery' );
1021
    return $lightboxes;
1022
}
1023
1024
1025
if ( !function_exists('wp_get_raw_referer') ) {
1026
	/**
1027
	 * Retrieves unvalidated referer from '_wp_http_referer' or HTTP referer.
1028
	 *
1029
	 * Do not use for redirects, use {@see wp_get_referer()} instead.
1030
	 *
1031
	 * @since 1.4.9
1032
	 * @return string|false Referer URL on success, false on failure.
1033
	 */
1034
	function wp_get_raw_referer() {
1035
		if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
1036
			return wp_unslash( $_REQUEST['_wp_http_referer'] );
1037
		} else if ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
1038
			return wp_unslash( $_SERVER['HTTP_REFERER'] );
1039
		}
1040
1041
		return false;
1042
	}
1043
}
1044
1045
/**
1046
 * Return the attachments for the currently displayed gallery
1047
 *
1048
 * @return array
1049
 */
1050
function foogallery_current_gallery_attachments_for_rendering() {
1051
    global $current_foogallery;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
1052
1053
    $attachments = apply_filters( 'foogallery_gallery_attachments_override_for_rendering', false, $current_foogallery );
1054
1055
    if ( $attachments !== false) {
1056
        return $attachments;
1057
    }
1058
1059
    //by default, return all attachments
1060
    return $current_foogallery->attachments();
1061
}
1062
1063
/**
1064
 * Return attachment ID from a URL
1065
 *
1066
 * @param $url String URL to the image we are checking
1067
 *
1068
 * @return null or attachment ID
1069
 */
1070
function foogallery_get_attachment_id_by_url($url) {
1071
	global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
1072
	$query = "SELECT ID FROM {$wpdb->posts} WHERE guid=%s";
1073
	$attachment = $wpdb->get_col( $wpdb->prepare( $query, $url ) );
1074
	if ( count( $attachment ) > 0 ) {
1075
		return $attachment[0];
1076
	}
1077
	return null;
1078
}
1079
1080
/**
1081
 * Safer escaping for HTML attributes.
1082
 *
1083
 * @since 1.4.31
1084
 *
1085
 * @param string $text
1086
 * @return string
1087
 */
1088
function foogallery_esc_attr( $text ) {
1089
	$safe_text = wp_check_invalid_utf8( $text );
1090
	$safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
1091
	return $safe_text;
1092
}
1093
1094
1095
/**
1096
 * Create a FooGallery and return the ID
1097
 *
1098
 * @param $template
1099
 * @param $attachment_ids
1100
 *
1101
 * @return int
1102
 */
1103
function foogallery_create_gallery( $template, $attachment_ids ) {
1104
1105
	if ( empty( $template ) ) {
1106
		$template = foogallery_default_gallery_template();
1107
	}
1108
1109
	//create an empty foogallery
1110
	$foogallery_args = array(
1111
		'post_title'  => 'Demo Gallery',
1112
		'post_type'   => FOOGALLERY_CPT_GALLERY,
1113
		'post_status' => 'publish',
1114
	);
1115
	$gallery_id = wp_insert_post( $foogallery_args );
1116
1117
	//set a gallery template
1118
	add_post_meta( $gallery_id, FOOGALLERY_META_TEMPLATE, $template, true );
1119
1120
	$settings = array();
1121
1122
	//set default settings if there are any, and also if the template is the same as the default
1123
	if ( foogallery_default_gallery_template() === $template ) {
1124
		$default_gallery_id = foogallery_get_setting( 'default_gallery_settings' );
1125
		if ( $default_gallery_id ) {
1126
			$settings = get_post_meta( $default_gallery_id, FOOGALLERY_META_SETTINGS, true );
1127
			add_post_meta( $this->foogallery_id, FOOGALLERY_META_SETTINGS, $settings, true );
0 ignored issues
show
Bug introduced by
The variable $this does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1128
		}
1129
	}
1130
1131
	if ( empty( $settings) ) {
1132
		switch ( $template ) {
1133
			case 'masonry':
1134
				$settings = array(
1135
					'foogallery_items_view' => 'preview',
1136
					'masonry_alignment' =>'fg-center',
1137
					'masonry_border_size' =>'fg-border-thin',
1138
					'masonry_caption_desc_source' =>'',
1139
					'masonry_caption_title_source' =>'',
1140
					'masonry_captions_limit_length' =>'',
1141
					'masonry_custom_settings' =>'',
1142
					'masonry_drop_shadow' =>'fg-shadow-outline',
1143
					'masonry_filtering_type' =>'',
1144
					'masonry_gutter_width' =>'10',
1145
					'masonry_hover_effect_caption_visibility' =>'fg-captions-bottom',
1146
					'masonry_hover_effect_color' =>'',
1147
					'masonry_hover_effect_icon' =>'fg-hover-zoom',
1148
					'masonry_hover_effect_preset' =>'fg-custom',
1149
					'masonry_hover_effect_scale' =>'',
1150
					'masonry_hover_effect_transition' =>'fg-hover-fade',
1151
					'masonry_inner_shadow' =>'',
1152
					'masonry_layout' =>'fixed',
1153
					'masonry_lazyload' =>'',
1154
					'masonry_lightbox' =>'foobox',
1155
					'masonry_loaded_effect' =>'fg-loaded-fade-in',
1156
					'masonry_loading_icon' =>'fg-loading-default',
1157
					'masonry_paging_type' =>'',
1158
					'masonry_rounded_corners' =>'',
1159
					'masonry_state' =>'no',
1160
					'masonry_theme' =>'fg-dark',
1161
					'masonry_thumbnail_link' =>'image',
1162
					'masonry_thumbnail_width' =>'250',
1163
					'masonry_video_autoplay' =>'yes',
1164
					'masonry_video_hover_icon' =>'fg-video-default',
1165
					'masonry_video_size' =>'640x360',
1166
					'masonry_video_sticky_icon' =>'',
1167
				);
1168
		}
1169
	}
1170
1171
	add_post_meta( $gallery_id, FOOGALLERY_META_SETTINGS, $settings, true );
1172
1173
	$attachments = explode( ',', $attachment_ids );
1174
	update_post_meta( $gallery_id, FOOGALLERY_META_ATTACHMENTS, $attachments );
1175
1176
	return $gallery_id;
1177
}