Completed
Push — development ( 57c765...cc7e24 )
by Atanas
02:18
created

Helper::get_active_sidebars()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 3
nop 0
dl 0
loc 19
rs 9.2
c 0
b 0
f 0
ccs 0
cts 11
cp 0
crap 20
1
<?php
2
3
namespace Carbon_Fields\Helper;
4
5
use Carbon_Fields\Datastore\Datastore;
6
use Carbon_Fields\Exception\Incorrect_Syntax_Exception;
7
use WP_Query;
8
9
/**
10
 * Helper functions and main initialization class.
11
 */
12
class Helper {
13
14
	/**
15
	 * Get a field from a specific container type or id
16
	 *
17
	 * @param  string  $container_type Container type to search in. Optional if $container_id is supplied
18
	 * @param  string  $container_id   Container id to search in. Optional if $container_type is supplied
19
	 * @param  string  $field_name     Field name to search for
20
	 * @return boolean
21
	 */
22
	public static function get_field( $container_type, $container_id, $field_name ) {
23
		\Carbon_Fields\Carbon_Fields::verify_fields_registered();
24
25
		$repository = \Carbon_Fields\Carbon_Fields::resolve( 'container_repository' );
26
		if ( $container_id ) {
27
			return $repository->get_field_in_container( $field_name, $container_id );
28
		}
29
		return $repository->get_field_in_containers( $field_name, $container_type );
30
	}
31
32
	/**
33
	 * Get a clone of a field with a value loaded
34
	 *
35
	 * @param  int    $object_id      Object id to get value for (e.g. post_id, term_id etc.)
36
	 * @param  string $container_type Container type to search in. Optional if $container_id is supplied
37
	 * @param  string $container_id   Container id to search in. Optional if $container_type is supplied
38
	 * @param  string $field_name     Field name to search for
39
	 * @return mixed
40
	 */
41
	public static function get_field_clone( $object_id, $container_type, $container_id, $field_name ) {
42
		$field = static::get_field( $container_type, $container_id, $field_name );
43
44
		if ( ! $field ) {
45
			return null;
46
		}
47
48
		$clone = clone $field;
49
		if ( $object_id !== null ) {
50
			$clone->get_datastore()->set_object_id( $object_id );
51
		}
52
		return $clone;
53
	}
54
55
	/**
56
	 * Get a value formatted for end-users
57
	 *
58
	 * @param  int    $object_id      Object id to get value for (e.g. post_id, term_id etc.)
59
	 * @param  string $container_type Container type to search in
60
	 * @param  string $container_id
61
	 * @param  string $field_name     Field name
62
	 * @return mixed
63
	 */
64
	public static function get_value( $object_id, $container_type, $container_id, $field_name ) {
65
		$field = static::get_field_clone( $object_id, $container_type, $container_id, $field_name );
66
67
		if ( ! $field ) {
68
			return '';
69
		}
70
71
		$field->load();
72
		return $field->get_formatted_value();
73
	}
74
75
	/**
76
	 * Set value for a field
77
	 *
78
	 * @param int    $object_id      Object id to get value for (e.g. post_id, term_id etc.)
79
	 * @param string $container_type Container type to search in
80
	 * @param string $container_id
81
	 * @param string $field_name     Field name
82
	 * @param array $value Field expects a `value_set`; Complex_Field expects a `value_tree` - refer to DEVELOPMENT.md
83
	 */
84
	public static function set_value( $object_id, $container_type, $container_id, $field_name, $value ) {
85
		$field = static::get_field_clone( $object_id, $container_type, $container_id, $field_name );
86
87
		if ( ! $field ) {
88
			$container_message = $container_id ? 'in container with id "' . $container_id . '"' : 'in containers of type "' . $container_type . '"';
89
			Incorrect_Syntax_Exception::raise( 'Could not find a field which satisfies the supplied pattern ' . $container_message . ': ' . $field_name );
90
			return;
91
		}
92
93
		$field->set_value( $value );
94
		$field->save();
95
	}
96
97
	/**
98
	 * Shorthand for get_post_meta().
99
	 * Uses the ID of the current post in the loop.
100
	 *
101
	 * @param  string $name         Field name
102
	 * @param  string $container_id
103
	 * @return mixed
104
	 */
105
	public static function get_the_post_meta( $name, $container_id = '' ) {
106
		return static::get_post_meta( get_the_ID(), $name, $container_id );
107
	}
108
109
	/**
110
	 * Get post meta field for a post.
111
	 *
112
	 * @param  int    $id           Post ID
113
	 * @param  string $name         Field name
114
	 * @param  string $container_id
115
	 * @return mixed
116
	 */
117
	public static function get_post_meta( $id, $name, $container_id = '' ) {
118
		return static::get_value( $id, 'post_meta', $container_id, $name );
119
	}
120
121
	/**
122
	 * Set post meta field for a post.
123
	 *
124
	 * @param  int    $id           Post ID
125
	 * @param  string $name         Field name
126
	 * @param  array  $value
127
	 * @param  string $container_id
128
	 */
129
	public static function set_post_meta( $id, $name, $value, $container_id = '' ) {
130
		return static::set_value( $id, 'post_meta', $container_id, $name, $value );
131
	}
132
133
	/**
134
	 * Get theme option field value.
135
	 *
136
	 * @param  string $name         Field name
137
	 * @param  string $container_id
138
	 * @return mixed
139
	 */
140
	public static function get_theme_option( $name, $container_id = '' ) {
141
		return static::get_value( null, 'theme_options', $container_id, $name );
142
	}
143
144
	/**
145
	 * Set theme option field value.
146
	 *
147
	 * @param  string $name         Field name
148
	 * @param  array  $value
149
	 * @param  string $container_id
150
	 */
151
	public static function set_theme_option( $name, $value, $container_id = '' ) {
152
		return static::set_value( null, 'theme_options', $container_id, $name, $value );
153
	}
154
155
	/**
156
	 * Get network option field value for the main site.
157
	 *
158
	 * @param  string $name         Field name
159
	 * @param  string $container_id
160
	 * @return mixed
161
	 */
162
	public static function get_the_network_option( $name, $container_id = '' ) {
163
		$id = defined( 'SITE_ID_CURRENT_SITE' ) ? SITE_ID_CURRENT_SITE : 1;
164
		return static::get_network_option( $id, $name, $container_id );
165
	}
166
167
	/**
168
	 * Get network option field value for a site.
169
	 *
170
	 * @param  string $id           Site ID
171
	 * @param  string $name         Field name
172
	 * @param  string $container_id
173
	 * @return mixed
174
	 */
175
	public static function get_network_option( $id, $name, $container_id = '' ) {
176
		return static::get_value( $id, 'network', $container_id, $name );
177
	}
178
179
	/**
180
	 * Set network option field value for a site.
181
	 *
182
	 * @param  string $id           Site ID
183
	 * @param  string $name         Field name
184
	 * @param  string $container_id
185
	 * @return mixed
186
	 */
187
	public static function set_network_option( $id, $name, $value, $container_id = '' ) {
188
		return static::set_value( $id, 'network', $container_id, $name, $value );
189
	}
190
191
	/**
192
	 * Get term meta field for a term.
193
	 *
194
	 * @param  int    $id           Term ID
195
	 * @param  string $name         Field name
196
	 * @param  string $container_id
197
	 * @return mixed
198
	 */
199
	public static function get_term_meta( $id, $name, $container_id = '' ) {
200
		return static::get_value( $id, 'term_meta', $container_id, $name );
201
	}
202
203
	/**
204
	 * Set term meta field for a term.
205
	 *
206
	 * @param  int    $id           Term ID
207
	 * @param  string $name         Field name
208
	 * @param  array  $value
209
	 * @param  string $container_id
210
	 */
211
	public static function set_term_meta( $id, $name, $value, $container_id = '' ) {
212
		return static::set_value( $id, 'term_meta', $container_id, $name, $value );
213
	}
214
215
	/**
216
	 * Get user meta field for a user.
217
	 *
218
	 * @param  int    $id           User ID
219
	 * @param  string $name         Field name
220
	 * @param  string $container_id
221
	 * @return mixed
222
	 */
223
	public static function get_user_meta( $id, $name, $container_id = '' ) {
224
		return static::get_value( $id, 'user_meta', $container_id, $name );
225
	}
226
227
	/**
228
	 * Set user meta field for a user.
229
	 *
230
	 * @param  int    $id           User ID
231
	 * @param  string $name         Field name
232
	 * @param  array  $value
233
	 * @param  string $container_id
234
	 */
235
	public static function set_user_meta( $id, $name, $value, $container_id = '' ) {
236
		return static::set_value( $id, 'user_meta', $container_id, $name, $value );
237
	}
238
239
	/**
240
	 * Get comment meta field for a comment.
241
	 *
242
	 * @param  int    $id           Comment ID
243
	 * @param  string $name         Field name
244
	 * @param  string $container_id
245
	 * @return mixed
246
	 */
247
	public static function get_comment_meta( $id, $name, $container_id = '' ) {
248
		return static::get_value( $id, 'comment_meta', $container_id, $name );
249
	}
250
251
	/**
252
	 * Set comment meta field for a comment.
253
	 *
254
	 * @param  int    $id           Comment ID
255
	 * @param  string $name         Field name
256
	 * @param  array  $value
257
	 * @param  string $container_id
258
	 */
259
	public static function set_comment_meta( $id, $name, $value, $container_id = '' ) {
260
		return static::set_value( $id, 'comment_meta', $container_id, $name, $value );
261
	}
262
263
	/**
264
	 * Get nav menu item meta field for a nav menu item.
265
	 *
266
	 * @param  int    $id           Nav menu item ID
267
	 * @param  string $name         Field name
268
	 * @param  string $container_id
269
	 * @return mixed
270
	 */
271
	public static function get_nav_menu_item_meta( $id, $name, $container_id = '' ) {
272
		return static::get_value( $id, 'nav_menu_item', $container_id, $name );
273
	}
274
275
	/**
276
	 * Set nav menu item meta field for a nav menu item.
277
	 *
278
	 * @param  int    $id           Nav menu item ID
279
	 * @param  string $name         Field name
280
	 * @param  array  $value
281
	 * @param  string $container_id
282
	 */
283
	public static function set_nav_menu_item_meta( $id, $name, $value, $container_id = '' ) {
284
		return static::set_value( $id, 'nav_menu_item', $container_id, $name, $value );
285
	}
286
287
	/**
288
	 * Recursive sorting function by array key.
289
	 *
290
	 * @param  array   &$array     The input array.
291
	 * @param  int     $sort_flags Flags for controlling sorting behavior.
292
	 * @return boolean
293
	 */
294
	public static function ksort_recursive( &$array, $sort_flags = SORT_REGULAR ) {
295
		if ( ! is_array( $array ) ) {
296
			return false;
297
		}
298
		ksort( $array, $sort_flags );
299
		foreach ( $array as $key => $value ) {
300
			self::ksort_recursive( $array[ $key ], $sort_flags );
301
		}
302
		return true;
303
	}
304
305
	/**
306
	 * Get the relation type from an array similar to how meta_query works in WP_Query
307
	 *
308
	 * @param  array         $array
309
	 * @param  array<string> $allowed_relations
310
	 * @param  string        $relation_key
311
	 * @return string
312
	 */
313
	public static function get_relation_type_from_array( $array, $allowed_relations = array( 'AND', 'OR' ), $relation_key = 'relation' ) {
314
		$allowed_relations = array_values( $allowed_relations );
315
		$allowed_relations = array_map( 'strtoupper', $allowed_relations );
316
		$relation = isset( $allowed_relations[0] ) ? $allowed_relations[0] : '';
317
318
		if ( isset( $array[ $relation_key ] ) ) {
319
			$relation = strtoupper( $array[ $relation_key ] );
320
		}
321
322 View Code Duplication
		if ( ! in_array( $relation, $allowed_relations ) ) {
323
			Incorrect_Syntax_Exception::raise( 'Invalid relation type ' . $relation . '. ' .
324
			'The rule should be one of the following: "' . implode( '", "', $allowed_relations ) . '"' );
325
		}
326
327
		return $relation;
328
	}
329
330
	/**
331
	 * Normalize a label by updating case, stripping common prefixes etc.
332
	 *
333
	 * @param  string $label
334
	 * @return string
335
	 */
336 View Code Duplication
	public static function normalize_label( $label ) {
337
		// remove the leading underscore(if it's there)
338
		$label = preg_replace( '~^_~', '', $label );
339
340
		// remove the leading "crb_"(if it's there)
341
		$label = preg_replace( '~^crb_~', '', $label );
342
343
		// split the name into words and make them capitalized
344
		$label = mb_convert_case( str_replace( '_', ' ', $label ), MB_CASE_TITLE );
345
346
		return $label;
347
	}
348
349
	/**
350
	 * Normalize a type string representing an object type
351
	 *
352
	 * @param  string $type
353
	 * @return string
354
	 */
355 View Code Duplication
	public static function normalize_type( $type ) {
356
		$normalized_type = str_replace( ' ', '_', $type );
357
		$normalized_type = preg_replace( '/[_\s]+/', '_', $normalized_type );
358
		$normalized_type = preg_replace( '/^_|_$/', '', $normalized_type );
359
		$normalized_type = strtolower( $normalized_type );
360
		return $normalized_type;
361
	}
362
363
	/**
364
	 * Convert a string representing an object type to a fully qualified class name
365
	 *
366
	 * @param  string $type
367
	 * @param  string $namespace
368
	 * @param  string $class_suffix
369
	 * @return string
370
	 */
371
	public static function type_to_class( $type, $namespace = '', $class_suffix = '' ) {
372
		$classlike_type = static::normalize_type( $type );
373
		$classlike_type = str_replace( '_', ' ', $classlike_type );
374
		$classlike_type = ucwords( $classlike_type );
375
		$classlike_type = str_replace( ' ', '_', $classlike_type );
376
377
		$class = $classlike_type . $class_suffix;
378
		if ( $namespace ) {
379
			$class = $namespace . '\\' . $class;
380
		}
381
382
		return $class;
383
	}
384
385
	/**
386
	 * Convert a string representing an object type to a fully qualified class name
387
	 *
388
	 * @param  string $class
389
	 * @param  string $class_suffix
390
	 * @return string
391
	 */
392
	public static function class_to_type( $class, $class_suffix = '' ) {
393
		$reflection = new \ReflectionClass( $class );
394
		$type = $reflection->getShortName();
395
396
		if ( $class_suffix ) {
397
			$type = preg_replace( '/(' . preg_quote( $class_suffix, '/' ) . ')$/i', '', $type );
398
		}
399
400
		$type = static::normalize_type( $type );
401
402
		return $type;
403
	}
404
405
	/**
406
	 * Get an array of sanitized html classes
407
	 *
408
	 * @param  string|array<string> $classes
409
	 * @return array<string>
410
	 */
411
	public static function sanitize_classes( $classes ) {
412
		if ( ! is_array( $classes ) ) {
413
			$classes = array_values( array_filter( explode( ' ', $classes ) ) );
414
		}
415
		$classes = array_map( 'sanitize_html_class', $classes );
416
		return $classes;
417
	}
418
419
	/**
420
	 * Check if an id or name for containers and fields is valid
421
	 *
422
	 * @param  string  $id
423
	 * @return boolean
424
	 */
425
	public static function is_valid_entity_id( $id ) {
426
		return ! empty( $id ) && preg_match( '/\A[a-z0-9_\-]+\z/', $id );
427
	}
428
429
	/**
430
	 * Return a partial regex pettern matching allowed field name characters
431
	 *
432
	 * @return string
433
	 */
434
	public static function get_field_name_characters_pattern() {
435
		return 'a-z0-9_\-';
436
	}
437
438
	/**
439
	 * Get an attachment ID given a file URL
440
	 * Modified version of https://wpscholar.com/blog/get-attachment-id-from-wp-image-url/
441
	 *
442
	 * @param  string  $url
443
	 * @return integet
444
	 */
445
	public static function get_attachment_id( $url ) {
446
		$dir = wp_upload_dir();
447
		$filename = basename( $url );
448
449
		if ( strpos( $url, $dir['baseurl'] . '/' ) === false ) {
450
			return 0;
451
		}
452
453
		$query_args = array(
454
			'post_type'   => 'attachment',
455
			'post_status' => 'inherit',
456
			'fields'      => 'ids',
457
			'meta_query'  => array(
458
				array(
459
					'value'   => $filename,
460
					'compare' => 'LIKE',
461
					'key'     => '_wp_attachment_metadata',
462
				),
463
			)
464
		);
465
		$query = new WP_Query( $query_args );
466
467
		if ( $query->have_posts() ) {
468
			foreach ( $query->posts as $post_id ) {
469
				$meta = wp_get_attachment_metadata( $post_id );
470
				$original_file = basename( $meta['file'] );
471
				$cropped_image_files = wp_list_pluck( $meta['sizes'], 'file' );
472
473
				if ( $original_file === $filename || in_array( $filename, $cropped_image_files ) ) {
474
					return intval( $post_id );
475
				}
476
			}
477
		}
478
479
		return 0;
480
	}
481
482
	/**
483
	 * Returns attachment metadata from an ID.
484
	 *
485
	 * @param  string  $id
486
	 * @param  string  $type Value Type. Can be either id or url
487
	 * @return boolean
488
	 */
489
	public static function get_attachment_metadata( $id, $type ) {
490
		$attachment_meta = array(
491
			'thumb_url'         => '',
492
			'default_thumb_url' => '',
493
			'file_ext'          => '',
494
			'file_type'         => '',
495
			'file_name'         => '',
496
			'file_url'          => '',
497
			'edit_nonce'        => '',
498
			'title'             => '',
499
			'caption'           => '',
500
			'description'       => '',
501
			'alt'               => '',
502
			'date'              => '',
503
			'filesize'          => '',
504
			'width'             => '',
505
			'height'            => '',
506
		);
507
508
		// when value_type is set to "url" the $id will hold the url, not the id
509
		if ( $type === 'url' ) {
510
			$attachment_id = static::get_attachment_id( $id );
511
512
			if ( $attachment_id === 0 ) {
513
				$attachment_meta['thumb_url'] = $id;
514
				$attachment_meta['default_thumb_url'] = $id;
515
				$attachment_meta['file_url'] = $id;
516
				return $attachment_meta;
517
			}
518
519
			$id = $attachment_id;
520
		}
521
522
		$attachment = get_post( $id );
523
524
		if ( ! $attachment ) {
525
			return $attachment_meta;
526
		}
527
528
		$meta                           = wp_get_attachment_metadata( $attachment->ID );
529
		list( $src, $width, $height )   = wp_get_attachment_image_src( $attachment->ID, 'full' );
0 ignored issues
show
Unused Code introduced by
The assignment to $src is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
530
531
		$attachment_meta['edit_nonce']  = wp_create_nonce( 'update-post_' . $id );
532
		$attachment_meta['title']       = get_the_title( $id );
533
		$attachment_meta['caption']     = get_post_field( 'post_excerpt', $id );
534
		$attachment_meta['description'] = get_post_field( 'post_content', $id );
535
		$attachment_meta['alt']         = get_post_meta( $id, '_wp_attachment_image_alt', true );
536
		$attachment_meta['date']        = mysql2date( __( 'F j, Y' ), $attachment->post_date );
537
		$attachment_meta['width']       = $width;
538
		$attachment_meta['height']      = $height;
539
		$attachment_meta['file_url']    = is_numeric( $id ) ? wp_get_attachment_url( $id ) : $id;
540
		$attachment_meta['file_name']   = basename( $attachment_meta['file_url'] );
541
		$attachment_meta['filetype']    = wp_check_filetype( $attachment_meta['file_url'] );
542
		$attachment_meta['file_ext']    = $attachment_meta['filetype']['ext']; // png, mp3, etc..
543
		$attachment_meta['file_type']   = preg_replace( '~\/.+$~', '', $attachment_meta['filetype']['type'] ); // image, video, etc..
544
545
		if ( $attachment_meta['file_type'] === 'audio' ) {
546
			$attachment_meta['artist'] = $meta['artist'];
547
			$attachment_meta['album'] = $meta['album'];
548
			$attachment_meta['length'] = $meta['length_formatted'];
549
		}
550
551
		$attachment_meta['default_thumb_url'] = wp_mime_type_icon( $id );
552
553
		if ( $attachment_meta['file_type'] == 'image' ) {
554
			$attachment_meta['thumb_url'] = $attachment_meta['file_url'];
555
556
			if ( $type == 'id' ) {
557
				$thumb_src = wp_get_attachment_image_src( $id, 'thumbnail' );
558
				$attachment_meta['thumb_url'] = $thumb_src[0];
559
			}
560
		} else {
561
			$attachment_meta['thumb_url'] = $attachment_meta['default_thumb_url'];
562
		}
563
564
		$attached_file = get_attached_file( $attachment->ID );
565
		if ( file_exists( $attached_file ) ) {
566
			$attachment_meta['filesize'] = size_format( filesize( $attached_file ) );
567
		}
568
569
		return $attachment_meta;
570
	}
571
572
	/**
573
	 * Get the current $_POST or $_GET input array with compacted input values merged in
574
	 *
575
	 * @return array
576
	 */
577
	public static function input() {
578
		$input = ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' ) ? $_POST : $_GET;
0 ignored issues
show
introduced by
Detected usage of a non-sanitized input variable: $_SERVER
Loading history...
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
579
		$input = stripslashes_deep( $input );
580
581
		if ( \Carbon_Fields\COMPACT_INPUT ) {
582
			$input = static::expand_compacted_input( $input );
583
		}
584
585
		return $input;
586
	}
587
588
	/**
589
	 * Get a copy of the passed array with compacted input values merged in
590
	 *
591
	 * @param  array $input
592
	 * @return array
593
	 */
594
	public static function expand_compacted_input( $input ) {
595
		if ( isset( $input[ \Carbon_Fields\COMPACT_INPUT_KEY ] ) ) {
596
			$json = json_decode( $input[ \Carbon_Fields\COMPACT_INPUT_KEY ], true );
597
			$input = array_merge( $input, $json );
598
		}
599
		return $input;
600
	}
601
602
	/**
603
	 * Get valid input from an input array compared to predefined options
604
	 *
605
	 * @param  array $input
606
	 * @param  array $options
607
	 * @return array
608
	 */
609
	public static function get_valid_options( $input, $options ) {
610
		// enfore comparison to be string so we do not get unexpected matches
611
		// for cases such as "string without any numbers" == 0
612
		// in array_search()
613
		$search_options = array_map( 'strval', $options );
614
615
		$valid_input = array();
616
		foreach ( $input as $raw_value ) {
617
			$index = array_search( strval( $raw_value ), $search_options, true );
618
619
			if ( $index === false ) {
620
				continue;
621
			}
622
623
			$valid_input[] = $options[ $index ];
624
		}
625
		return $valid_input;
626
	}
627
628
	/**
629
	 * Get an array of active sidebars
630
	 *
631
	 * @return array
632
	 */
633
	public static function get_active_sidebars() {
634
		global $wp_registered_sidebars;
635
636
		$sidebars = array();
637
638
		foreach ( $wp_registered_sidebars as $sidebar ) {
639
			// Check if we have inactive sidebars
640
			if ( isset( $sidebar['class'] ) && strpos( $sidebar['class'], 'inactive-sidebar' ) !== false ) {
641
				continue;
642
			}
643
644
			$sidebars[] = array(
645
				'id'   => $sidebar['id'],
646
				'name' => $sidebar['name'],
647
			);
648
		}
649
650
		return $sidebars;
651
	}
652
}
653