Completed
Pull Request — master (#86)
by
unknown
02:03
created

Dynamic_Featured_Image::get_image_alt()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 7
cts 7
cp 1
rs 9.9332
c 0
b 0
f 0
cc 4
nc 8
nop 1
crap 4
1
<?php
2
/**
3
 * Plugin Name: Dynamic Featured Image
4
 * Plugin URI: http://wordpress.org/plugins/dynamic-featured-image/
5
 * Description: Dynamically adds multiple featured image or post thumbnail functionality to your posts, pages and custom post types.
6
 * Version: 3.7.0
7
 * Author: Ankit Pokhrel
8
 * Author URI: https://ankitpokhrel.com
9
 * License: GPL2 or later
10
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
11
 * Text Domain: dynamic-featured-image
12
 * Domain Path: /languages
13
 * GitHub Plugin URI: https://github.com/ankitpokhrel/Dynamic-Featured-Image
14
 *
15
 * @package dynamic-featured-image
16
 *
17
 * Copyright (C) 2013-2019 Ankit Pokhrel <[email protected], https://ankitpokhrel.com>
18
 *
19
 * This program is free software; you can redistribute it and/or modify
20
 * it under the terms of the GNU General Public License as published by
21
 * the Free Software Foundation; either version 3 of the License, or
22
 * (at your option) any later version.
23
 *
24
 * This program is distributed in the hope that it will be useful,
25
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27
 * GNU General Public License for more details.
28
 *
29
 * You should have received a copy of the GNU General Public License
30
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
31
 */
32
33
// Avoid direct calls to this file.
34
if ( ! defined( 'ABSPATH' ) ) {
35
    header( 'Status: 403 Forbidden' );
36
    header( 'HTTP/1.1 403 Forbidden' );
37
    exit();
38
}
39
40
/**
41
 * Dynamic Featured Image plugin main class.
42
 *
43
 * @author Ankit Pokhrel <[email protected]>
44
 * @version 3.7.0
45
 */
46
class Dynamic_Featured_Image {
47
    /**
48
     * Current version of the plugin.
49
     *
50
     * @since 3.0.0
51
     */
52
    const VERSION = '3.7.0';
53
54
    /**
55
     * Text domain.
56
     *
57
     * @since 3.6.0
58
     */
59
    const TEXT_DOMAIN = 'dynamic-featured-image';
60
61
    /**
62
     * Documentation Link.
63
     *
64
     * @since 3.6.0
65
     */
66
    const WIKI_LINK = 'https://github.com/ankitpokhrel/Dynamic-Featured-Image/wiki/';
67
68
    /**
69
     * Image upload directory.
70
     *
71
     * @var $upload_dir string
72
     */
73
    private $upload_dir;
74
75
    /**
76
     * Image upload URL.
77
     *
78
     * @var $upload_url string
79
     */
80
    private $upload_url;
81
82
    /**
83
     * Database object.
84
     *
85
     * @var $db wpdb
86
     */
87
    private $db;
88
89
    /**
90
     * Title for dfi metabox.
91
     *
92
     * @var $metabox_title string
93
     */
94
    protected $metabox_title;
95
96
    /**
97
     * Users post type filter for dfi metabox.
98
     *
99
     * @var $user_filter array
100
     */
101
    protected $user_filter;
102
103
    /**
104
     * Constructor. Hooks all interactions to initialize the class.
105
     *
106
     * @since 1.0.0
107
     * @access public
108
     * @global object $wpdb
109
     *
110
     * @see     add_action()
111
     */
112 1
    public function __construct() {
113
        // plugin update warning.
114 1
        add_action( 'in_plugin_update_message-' . plugin_basename( __FILE__ ), array( $this, 'update_notice' ) );
115
116 1
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
117 1
        add_action( 'add_meta_boxes', array( $this, 'initialize_featured_box' ) );
118 1
        add_action( 'save_post', array( $this, 'save_meta' ) );
119 1
        add_action( 'plugins_loaded', array( $this, 'load_plugin_textdomain' ) );
120
121
        // handle ajax request.
122 1
        add_action( 'wp_ajax_dfiMetaBox_callback', array( $this, 'ajax_callback' ) );
123
124
        // media uploader custom fields.
125 1
        add_filter( 'attachment_fields_to_edit', array( $this, 'media_attachment_custom_fields' ), 10, 2 );
126 1
        add_filter( 'attachment_fields_to_save', array( $this, 'media_attachment_custom_fields_save' ), 10, 2 );
127
128
        // plugin sponsors.
129 1
        new PluginSponsor();
130
131
        // get the site protocol.
132 1
        $protocol = $this->get_protocol();
133
134 1
        $this->upload_dir = wp_upload_dir();
135 1
        $this->upload_url = preg_replace( '#^https?://#', '', $this->upload_dir['baseurl'] );
136
137
        // add protocol to the upload url.
138 1
        $this->upload_url = $protocol . $this->upload_url;
139
140
        // post type filter added by user.
141 1
        $this->user_filter = array();
142
143 1
        global $wpdb;
144 1
        $this->db = $wpdb;
145 1
    }
146
147
    /**
148
     * Return site protocol.
149
     *
150
     * @since 3.5.1
151
     * @access public
152
     *
153
     * @return string
154
     */
155
    private function get_protocol() {
156
        return is_ssl() ? 'https://' : 'http://';
157
    }
158
159
    /**
160
     * Add required admin scripts.
161
     *
162
     * @since 1.0.0
163
     * @access public
164
     *
165
     * @see  wp_enqueue_style()
166
     * @see  wp_register_script()
167
     * @see  wp_enqueue_script()
168
     *
169
     * @return void
170
     */
171 1
    public function enqueue_admin_scripts() {
172
        // enqueue styles.
173 1
        wp_enqueue_style( 'style-dfi', plugins_url( '/css/style-dfi.css', __FILE__ ), array(), self::VERSION );
174
175
        // register script.
176 1
        wp_register_script( 'scripts-dfi', plugins_url( '/js/script-dfi.js', __FILE__ ), array( 'jquery' ), self::VERSION );
177
178
        // localize the script with required data.
179 1
        wp_localize_script(
180 1
            'scripts-dfi',
181 1
            'DFI_SPECIFIC',
182
            array(
183 1
                'upload_url'               => $this->upload_url,
184 1
                'metabox_title'            => __( $this->metabox_title, self::TEXT_DOMAIN ),
185 1
                'mediaSelector_title'      => __( 'Dynamic Featured Image - Media Selector', self::TEXT_DOMAIN ),
186 1
                'mediaSelector_buttonText' => __( 'Set Featured Image', self::TEXT_DOMAIN ),
187 1
                'ajax_nonce'               => wp_create_nonce( plugin_basename( __FILE__ ) ),
188
            )
189 1
        );
190
191
        // enqueue scripts.
192 1
        wp_enqueue_script( 'scripts-dfi' );
193 1
    }
194
195
    /**
196
     * Add featured meta boxes dynamically.
197
     *
198
     * @since 1.0.0
199
     * @access public
200
     * @global object $post
201
     *
202
     * @see  get_post_meta()
203
     * @see  get_post_types()
204
     * @see  add_meta_box()
205
     * @see  add_filter()
206
     *
207
     * @return void
208
     */
209
    public function initialize_featured_box() {
210
        global $post;
211
212
        // make metabox title dynamic.
213
        $this->metabox_title = apply_filters( 'dfi_set_metabox_title', __( 'Featured Image', self::TEXT_DOMAIN ) );
214
215
        $featured_data  = get_post_meta( $post->ID, 'dfiFeatured', true );
216
        $total_featured = is_array( $featured_data ) ? count( $featured_data ) : 0;
217
218
        $default_filter    = array( 'attachment', 'revision', 'nav_menu_item' );
219
        $this->user_filter = apply_filters( 'dfi_post_type_user_filter', $this->user_filter );
220
221
        $post_types = array_diff( get_post_types(), array_merge( $default_filter, $this->user_filter ) );
222
        $post_types = apply_filters( 'dfi_post_types', $post_types );
223
224
        if ( ! empty( $featured_data ) && $total_featured >= 1 ) {
225
            $i = 2;
226
            foreach ( $featured_data as $featured ) {
227
                $this->dfi_add_meta_box( $post_types, $featured, $i++ );
228
            }
229
        } else {
230
            $this->dfi_add_meta_box( $post_types );
231
        }
232
    }
233
234
    /**
235
     * Translates more than one digit number digit by digit.
236
     *
237
     * @param  int $number Integer to be translated.
238
     *
239
     * @return string Translated number
240
     */
241 3
    protected function get_number_translation( $number ) {
242 3
        if ( $number <= 9 ) {
243 2
            return __( $number, self::TEXT_DOMAIN );
244
        } else {
245 1
            $pieces = str_split( $number, 1 );
246 1
            $buffer = '';
247 1
            foreach ( $pieces as $piece ) {
248 1
                $buffer .= __( $piece, self::TEXT_DOMAIN );
249 1
            }
250
251 1
            return $buffer;
252
        }
253
    }
254
255
    /**
256
     * Adds meta boxes.
257
     *
258
     * @param  array  $post_types Post types to show featured image box.
259
     * @param  object $featured Callback arguments.
260
     * @param  int    $i Index of the featured image.
261
     *
262
     * @return void
263
     */
264
    private function dfi_add_meta_box( $post_types, $featured = null, $i = null ) {
265
        if ( ! is_null( $i ) ) {
266
            foreach ( $post_types as $type ) {
267
                add_meta_box(
268
                    'dfiFeaturedMetaBox-' . $i,
269
                    __( $this->metabox_title, self::TEXT_DOMAIN ) . ' ' . $this->get_number_translation( $i ),
270
                    array( $this, 'featured_meta_box' ),
271
                    $type,
272
                    apply_filters( 'dfi_metabox_context', 'side' ),
273
                    apply_filters( 'dfi_metabox_priority', 'low' ),
274
                    array( $featured, $i + 1 )
275
                );
276
277
                add_filter( "postbox_classes_{$type}_dfiFeaturedMetaBox-" . $i, array( $this, 'add_metabox_classes' ) );
278
            }
279
        } else {
280
            foreach ( $post_types as $type ) {
281
                add_meta_box(
282
                    'dfiFeaturedMetaBox',
283
                    __( $this->metabox_title, self::TEXT_DOMAIN ) . ' ' . __( 2, self::TEXT_DOMAIN ),
284
                    array( $this, 'featured_meta_box' ),
285
                    $type,
286
                    apply_filters( 'dfi_metabox_context', 'side' ),
287
                    apply_filters( 'dfi_metabox_priority', 'low' ),
288
                    array( null, null )
289
                );
290
291
                add_filter( "postbox_classes_{$type}_dfiFeaturedMetaBox", array( $this, 'add_metabox_classes' ) );
292
            }
293
        }
294
    }
295
296
    /**
297
     * Separate thumb and full image url from given URL string.
298
     *
299
     * @since  3.3.1
300
     *
301
     * @param  string $url_string Url string.
302
     * @param  string $state Thumb or full.
303
     *
304
     * @return string|null
305
     */
306 3
    private function separate( $url_string, $state = 'thumb' ) {
307 3
        $image_piece = explode( ',', sanitize_text_field($url_string) );
308
309 3
        if ( 'thumb' === $state ) {
310 2
            return isset( $image_piece[0] ) ? $image_piece[0] : null;
311
        }
312
313 3
        return isset( $image_piece[1] ) ? $image_piece[1] : null;
314
    }
315
316
    /**
317
     * Create a nonce field.
318
     *
319
     * @since  3.5.0
320
     *
321
     * @see  wp_nonce_field()
322
     * @see  plugin_basename()
323
     *
324
     * @codeCoverageIgnore
325
     *
326
     * @param  string $key Nonce key.
327
     *
328
     * @return string
329
     */
330
    protected function nonce_field( $key ) {
331
        return wp_nonce_field( plugin_basename( __FILE__ ), $key, true, false );
332
    }
333
334
    /**
335
     * Featured meta box as seen in the admin.
336
     *
337
     * @since 1.0.0
338
     * @access public
339
     *
340
     * @param  object $post Global post object.
341
     * @param  array  $featured Array containing featured image count.
342
     *
343
     * @throws Exception Medium size image not found.
344
     * @return void
345
     */
346 3
    public function featured_meta_box( $post, $featured ) {
347 3
        $featured_img         = sanitize_text_field($featured['args'][0]);
348 3
        $featured_id          = (int) (is_null( $featured['args'][1] ) ? 2 : --$featured['args'][1]);
349 3
        $featured_img_full    = $featured_img;
350 3
        $featured_img_trimmed = $featured_img;
351
352 3
        if ( ! is_null( $featured_img ) ) {
353 3
            $featured_img_trimmed = $this->separate( $featured_img );
354 3
            $featured_img_full    = $this->separate( $featured_img, 'full' );
355 3
        }
356
357 3
        $thumbnail     = null;
358 3
        $attachment_id = null;
359 3 View Code Duplication
        if ( ! empty( $featured_img_full ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
360 1
            $attachment_id = $this->get_image_id( $this->upload_url . $featured_img_full );
361
362 1
            $thumbnail = $this->get_image_thumb_by_attachment_id( $attachment_id, 'medium' );
363
364 1
            if ( empty( $thumbnail ) ) {
365
                // since medium sized thumbnail image is missing,
366
                // let's set full image url as thumbnail.
367
                $thumbnail = $featured_img_full;
368
            }
369 1
        }
370
371
        // Add a nonce field.
372 3
        echo $this->nonce_field( 'dfi_fimageplug-' . $featured_id ); // WPCS: XSS ok.
373 3
        echo $this->get_featured_box( $featured_img_trimmed, $featured_img, $featured_id, $thumbnail, $post->ID, $attachment_id ); // WPCS: XSS ok.
374 3
    }
375
376
    /**
377
     * Returns featured box html content.
378
     *
379
     * @since  3.1.0
380
     * @access private
381
     *
382
     * @param string $featured_img_trimmed Medium sized image.
383
     * @param string $featured_img         Full sized image.
384
     * @param string $featured_id          Featured id number for translation.
385
     * @param string $thumbnail            Thumb sized image.
386
     * @param int    $post_id              Post id.
387
     * @param int    $attachment_id        Attachment id.
388
     *
389
     * @return string Html content
390
     */
391 3
    private function get_featured_box( $featured_img_trimmed, $featured_img, $featured_id, $thumbnail, $post_id, $attachment_id ) {
392 3
		$featured_img		= sanitize_text_field($featured_img);
393 3
		$featured_id		= (int)$featured_id;
394 3
        $has_featured_image = ! empty( $featured_img_trimmed ) ? ' hasFeaturedImage' : '';
395 3
        $thumbnail          = sanitize_text_field(! is_null( $thumbnail ) ? $thumbnail : '');
396 3
        $dfi_empty          = is_null( $featured_img_trimmed ) ? 'dfiImgEmpty' : '';
397 3
        return "<a href='javascript:void(0)' class='dfiFeaturedImage{$has_featured_image}' title='" . __( 'Set Featured Image', self::TEXT_DOMAIN ) . "' data-post-id='" . $post_id . "' data-attachment-id='" . $attachment_id . "'><span class='dashicons dashicons-camera'></span></a><br/>
398 3
            <img src='" . $thumbnail . "' class='dfiImg {$dfi_empty}'/>
399
            <div class='dfiLinks'>
400 3
                <a href='javascript:void(0)' data-id='{$featured_id}' data-id-local='" . $this->get_number_translation( $featured_id + 1 ) . "' class='dfiAddNew dashicons dashicons-plus' title='" . __( 'Add New', self::TEXT_DOMAIN ) . "'></a>
401 3
                <a href='javascript:void(0)' class='dfiRemove dashicons dashicons-minus' title='" . __( 'Remove', self::TEXT_DOMAIN ) . "'></a>
402
            </div>
403
            <div class='dfiClearFloat'></div>
404 3
            <input type='hidden' name='dfiFeatured[]' value='{$featured_img}'  class='dfiImageHolder' />";
405
    }
406
407
    /**
408
     * Load new featured meta box via ajax.
409
     *
410
     * @since 1.0.0
411
     * @access public
412
     *
413
     * @return void
414
     */
415 2
    public function ajax_callback() {
416 2
        check_ajax_referer( plugin_basename( __FILE__ ), 'security' );
417
418 1
        $featured_id = isset( $_POST['id'] ) ? (int) ( wp_unslash( $_POST['id'] ) ) : null;
419
420 1
        if ( ! is_numeric( $featured_id ) ) {
421
            return;
422
        }
423
424
        // @codingStandardsIgnoreStart
425 1
        echo $this->nonce_field( 'dfi_fimageplug-' . $featured_id );
426
        ?>
427
        <a href="javascript:void(0)" class="dfiFeaturedImage"
428
           title="<?php echo __( 'Set Featured Image', self::TEXT_DOMAIN ) ?>"><span
429
                    class="dashicons dashicons-camera"></span></a><br/>
430
        <img src="" class="dfiImg dfiImgEmpty"/>
431
        <div class="dfiLinks">
432
            <a href="javascript:void(0)" data-id="<?php echo $featured_id ?>"
433
               data-id-local="<?php echo $this->get_number_translation( $featured_id + 1 ) ?>"
434
               class="dfiAddNew dashicons dashicons-plus" title="<?php echo __( 'Add New', self::TEXT_DOMAIN ) ?>"></a>
435
            <a href="javascript:void(0)" class="dfiRemove dashicons dashicons-minus"
436
               title="<?php echo __( 'Remove', self::TEXT_DOMAIN ) ?>"></a>
437
        </div>
438
        <div class="dfiClearFloat"></div>
439
        <input type="hidden" name="dfiFeatured[]" value="" class="dfiImageHolder"/>
440
        <?php
441
        // @codingStandardsIgnoreEnd
442 1
        wp_die( '' );
443
    }
444
445
    /**
446
     * Add custom class 'featured-meta-box' to meta box.
447
     *
448
     * @since 1.0.0
449
     * @access public
450
     *
451
     * @see  add_metabox_classes
452
     *
453
     * @param array $classes Classes to add in the meta box.
454
     *
455
     * @return array
456
     */
457 1
    public function add_metabox_classes( $classes ) {
458 1
        array_push( $classes, 'featured-meta-box' );
459
460 1
        return $classes;
461
    }
462
463
    /**
464
     * Add custom fields in media uploader.
465
     *
466
     * @since  3.4.0
467
     *
468
     * @param array $form_fields Fields to include in media attachment form.
469
     * @param array $post Post data.
470
     *
471
     * @return array
472
     */
473 1
    public function media_attachment_custom_fields( $form_fields, $post ) {
474 1
        $form_fields['dfi-link-to-image'] = array(
475 1
            'label' => __( 'Link to Image', self::TEXT_DOMAIN ),
476 1
            'input' => 'text',
477 1
            'value' => get_post_meta( $post->ID, '_dfi_link_to_image', true ),
478
        );
479
480 1
        return $form_fields;
481
    }
482
483
    /**
484
     * Save values of media uploader custom fields.
485
     *
486
     * @since 3.4.0
487
     *
488
     * @param array $post Post data for database.
489
     * @param array $attachment Attachment fields from $_POST form.
490
     *
491
     * @return array
492
     */
493 1
    public function media_attachment_custom_fields_save( $post, $attachment ) {
494 1
        if ( isset( $attachment['dfi-link-to-image'] ) ) {
495 1
			$attachment['dfi-link-to-image'] = sanitize_text_field($attachment['dfi-link-to-image']);
496 1
            update_post_meta( $post['ID'], '_dfi_link_to_image', $attachment['dfi-link-to-image'] );
497 1
        }
498
499 1
        return $post;
500
    }
501
502
    /**
503
     * Update featured images in the database.
504
     *
505
     * @since 1.0.0
506
     * @access public
507
     *
508
     * @see  plugin_basename()
509
     * @see  update_post_meta()
510
     * @see  current_user_can()
511
     *
512
     * @param  int $post_id Current post id.
513
     *
514
     * @return bool|null
515
     */
516 2
    public function save_meta( $post_id ) {
517
        // Check auto save.
518 2
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
519 1
            return false;
520
        }
521
522 2
        if ( ! $this->verify_nonces() ) {
523 2
            return false;
524
        }
525
526
        // Check permission before saving data.
527 1
        if ( current_user_can( 'edit_posts', $post_id ) && isset( $_POST['dfiFeatured'] ) ) { // WPCS: CSRF ok.
528 1
            $featured_images = is_array( $_POST['dfiFeatured'] ) ? $_POST['dfiFeatured'] : array(); // WPCS: sanitization ok, CSRF ok.
529
530 1
            update_post_meta( $post_id, 'dfiFeatured', $this->sanitize_array( $featured_images ) );
531 1
        }
532 1
    }
533
534
    /**
535
     * Sanitize array.
536
     *
537
     * @since 3.6.0
538
     * @access protected
539
     *
540
     * @param array $input_array Input array.
541
     *
542
     * @return array
543
     */
544 1
    protected function sanitize_array( $input_array ) {
545 1
        $sanitized = array();
546
547 1
        foreach ( $input_array as $value ) {
548 1
            $sanitized[] = sanitize_text_field( wp_unslash( $value ) );
549 1
        }
550
551 1
        return $sanitized;
552
    }
553
554
    /**
555
     * Verify metabox nonces.
556
     *
557
     * @access protected
558
     * @see  wp_verify_nonce()
559
     *
560
     * @return bool
561
     */
562
    protected function verify_nonces() {
563
        $keys = preg_grep( '/dfi_fimageplug-\d+$/', array_keys( $_POST ) ); // WPCS: CSRF ok.
564
565
        if ( empty( $keys ) ) {
566
            return false;
567
        }
568
569
        foreach ( $keys as $key ) {
570
            // Verify nonce.
571
            if ( ! isset( $_POST[ $key ] ) ||
572
                 ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[ $key ] ) ), plugin_basename( __FILE__ ) )
573
            ) {
574
                return false;
575
            }
576
        }
577
578
        return true;
579
    }
580
581
    /**
582
     * Add update notice. Displayed in plugin update page.
583
     *
584
     * @since 2.0.0
585
     * @access public
586
     *
587
     * @return void
588
     */
589 1
    public function update_notice() {
590 1
        $info = __( 'ATTENTION! Please read the <a href="' . self::WIKI_LINK . '" target="_blank">DOCUMENTATION</a> properly before update.',
591 1
        self::TEXT_DOMAIN );
592
593 1
        echo '<span style="color: red; padding: 7px 0; display: block">' . strip_tags( $info, '<a><b><i><span>' ) . '</span>'; // WPCS: XSS ok.
594 1
    }
595
596
    /**
597
     * Execute query.
598
     *
599
     * @param string $query Query to execute.
600
     *
601
     * @return null|string
602
     */
603 6
    private function execute_query( $query ) {
604 6
        return $this->db->get_var( $query );
605
    }
606
607
    /**
608
     * Get attachment id of the image by image url.
609
     *
610
     * @since 3.1.7
611
     * @access protected
612
     * @global object $wpdb
613
     *
614
     * @param  string $image_url URL of an image.
615
     *
616
     * @return string
617
     */
618 1
    protected function get_attachment_id( $image_url ) {
619 1
        return (int) $this->execute_query( $this->db->prepare( 'SELECT ID FROM ' . $this->db->posts . ' WHERE guid = %s', $image_url ) );
620
    }
621
622
    /**
623
     * Get image url of the image by attachment id.
624
     *
625
     * @since 2.0.0
626
     * @access public
627
     *
628
     * @see  wp_get_attachment_image_src()
629
     *
630
     * @param  int    $attachment_id attachment id of an image.
631
     * @param  string $size size of the image to fetch (thumbnail, medium, full).
632
     *
633
     * @return string
634
     */
635 1
    public function get_image_url( $attachment_id, $size = 'full' ) {
636 1
        $image_thumb = wp_get_attachment_image_src( $attachment_id, $size );
637
638 1
        return empty( $image_thumb ) ? null : sanitize_text_field( $image_thumb[0] );
639
    }
640
641
    /**
642
     * Get image thumbnail url of specific size by attachment id.
643
     *
644
     * @since 3.7.0
645
     * @access public
646
     *
647
     * @see wp_get_attachment_image_src()
648
     *
649
     * @param int $attachment_id attachment id of an image.
650
     * @param string $size size of the image to fetch (thumbnail, medium, full).
651
     *
652
     * @return string|null
653
     */
654 1
    public function get_image_thumb_by_attachment_id( $attachment_id, $size = 'thumbnail' ) {
655 1
        if ( empty( $attachment_id ) ) {
656
            return null;
657
        }
658
659 1
        $image_thumb = wp_get_attachment_image_src( $attachment_id, $size );
660
661 1
        return empty( $image_thumb ) ? null : sanitize_text_field( $image_thumb[0] );
662
    }
663
664
    /**
665
     * Get image thumbnail url of specific size by image url.
666
     *
667
     * @since 2.0.0
668
     * @access public
669
     *
670
     * @see  get_image_id()
671
     * @see  wp_get_attachment_image_src()
672
     *
673
     * @param  string $image_url url of an image.
674
     * @param  string $size size of the image to fetch (thumbnail, medium, full).
675
     *
676
     * @return string
677
     */
678 1
    public function get_image_thumb( $image_url, $size = 'thumbnail' ) {
679 1
        $attachment_id = $this->get_image_id( $image_url );
680 1
        $image_thumb   = wp_get_attachment_image_src( $attachment_id, $size );
681
682 1
        return empty( $image_thumb ) ? null : sanitize_text_field( $image_thumb[0] );
683
    }
684
685
    /**
686
     * Gets attachment id from given image url.
687
     *
688
     * @param  string $image_url url of an image.
689
     *
690
     * @since  2.0.0
691
     * @access public
692
     *
693
     * @return int|null attachment id of an image
694
     */
695 5
    public function get_image_id( $image_url ) {
696 5
        $attachment_id = $this->get_attachment_id( $image_url );
697
698 5
        if ( is_null( $attachment_id ) ) {
699
            /*
700
             * Check if the image is an edited image.
701
             * and try to get the attachment id.
702
             */
703
704 1
            global $wp_version;
705
706 1
            if ( intval( $wp_version ) >= 4 ) {
707 1
                return attachment_url_to_postid( $image_url );
708
            }
709
710
            // Fallback.
711
            $image_url = str_replace( $this->upload_url . '/', '', $image_url );
712
713
            $row = $this->execute_query( $this->db->prepare( 'SELECT post_id FROM ' . $this->db->postmeta . ' WHERE meta_key = %s AND meta_value = %s', '_wp_attached_file', $image_url ) );
714
            if ( ! is_null( $row ) ) {
715
                $attachment_id = $row;
716
            }
717
        }
718
719 4
        return (int) $attachment_id;
720
    }
721
722
    /**
723
     * Get image title.
724
     *
725
     * @since 2.0.0
726
     * @access public
727
     *
728
     * @param string $image_url URL of an image.
729
     *
730
     * @return string
731
     */
732 1
    public function get_image_title( $image_url ) {
733 1
        return sanitize_text_field( $this->execute_query( $this->db->prepare( 'SELECT post_title FROM ' . $this->db->posts . ' WHERE guid = %s', $image_url ) ) );
734
    }
735
736
    /**
737
     * Get image title by id.
738
     *
739
     * @since 2.0.0
740
     * @access public
741
     *
742
     * @param  int $attachment_id Attachment id of an image.
743
     *
744
     * @return string
745
     */
746 1
    public function get_image_title_by_id( $attachment_id ) {
747 1
        return sanitize_text_field( $this->execute_query( $this->db->prepare( 'SELECT post_title FROM ' . $this->db->posts . ' WHERE ID = %d', $attachment_id ) ) );
748
    }
749
750
    /**
751
     * Get image caption.
752
     *
753
     * @since 2.0.0
754
     * @access public
755
     *
756
     * @param  string $image_url URL of an image.
757
     *
758
     * @return string
759
     */
760 1
    public function get_image_caption( $image_url ) {
761 1
        return sanitize_text_field( $this->execute_query( $this->db->prepare( 'SELECT post_excerpt FROM ' . $this->db->posts . ' WHERE guid = %s', $image_url ) ) );
762
    }
763
764
    /**
765
     * Get image caption by id.
766
     *
767
     * @since 2.0.0
768
     * @access public
769
     *
770
     * @param  int $attachment_id Attachment id of an image.
771
     *
772
     * @return string
773
     */
774 1
    public function get_image_caption_by_id( $attachment_id ) {
775 1
        return sanitize_text_field( $this->execute_query( $this->db->prepare( 'SELECT post_excerpt FROM ' . $this->db->posts . ' WHERE ID = %d', $attachment_id ) ) );
776
    }
777
778
    /**
779
     * Get image alternate text.
780
     *
781
     * @since 2.0.0
782
     * @access public
783
     *
784
     * @see  get_post_meta()
785
     *
786
     * @param  string $image_url URL of an image.
787
     *
788
     * @return string
789
     */
790 1
    public function get_image_alt( $image_url ) {
791 1
        $attachment = $this->db->get_col( $this->db->prepare( 'SELECT ID FROM ' . $this->db->posts . ' WHERE guid = %s', $image_url ) );
792
793 1
        $alt = null;
794 1
        if ( ! empty( $attachment ) ) {
795 1
            $alt = get_post_meta( $attachment[0], '_wp_attachment_image_alt' );
796 1
        }
797
798 1
        return ( is_null( $alt ) || empty( $alt ) ) ? null : sanitize_text_field($alt[0]);
799
    }
800
801
    /**
802
     * Get image alternate text by attachment id.
803
     *
804
     * @since 2.0.0
805
     * @access public
806
     *
807
     * @see  get_post_meta()
808
     *
809
     * @param  int $attachment_id Attachment id of an image.
810
     *
811
     * @return string
812
     */
813 1
    public function get_image_alt_by_id( $attachment_id ) {
814 1
        $alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt' );
815
816 1
        return empty( $alt ) ? null : sanitize_text_field($alt[0]);
817
    }
818
819
    /**
820
     * Get image description.
821
     *
822
     * @since 3.0.0
823
     * @access public
824
     *
825
     * @param  string $image_url URL of an image.
826
     *
827
     * @return string
828
     */
829 1
    public function get_image_description( $image_url ) {
830 1
        return sanitize_text_field( $this->execute_query( $this->db->prepare( 'SELECT post_content FROM ' . $this->db->posts . ' WHERE guid = %s', $image_url ) ) );
831
    }
832
833
    /**
834
     * Get image description by id.
835
     *
836
     * @since 3.0.0
837
     * @access public
838
     *
839
     * @param  int $attachment_id attachment id of an image.
840
     *
841
     * @return string
842
     */
843 1
    public function get_image_description_by_id( $attachment_id ) {
844 1
        return sanitize_text_field( $this->execute_query( $this->db->prepare( 'SELECT post_content FROM ' . $this->db->posts . ' WHERE ID = %d', $attachment_id ) ) );
845
    }
846
847
    /**
848
     * Get link to image.
849
     *
850
     * @since 3.4.0
851
     * @access public
852
     *
853
     * @param  int $attachment_id Attachment id of an image.
854
     *
855
     * @return string|null
856
     */
857 1
    public function get_link_to_image( $attachment_id ) {
858 1
        return sanitize_text_field( get_post_meta( $attachment_id, '_dfi_link_to_image', true ) );
859
    }
860
861
    /**
862
     * Get all attachment ids of the post.
863
     *
864
     * @since 2.0.0
865
     * @access public
866
     *
867
     * @see  get_post_meta()
868
     *
869
     * @param  int $post_id id of the current post.
870
     *
871
     * @return array
872
     */
873 2
    public function get_post_attachment_ids( $post_id ) {
874 2
        $dfi_images = get_post_meta( $post_id, 'dfiFeatured', true );
875 2
        $ret_val    = array();
876
877 2 View Code Duplication
        if ( ! empty( $dfi_images ) && is_array( $dfi_images ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
878 2
            foreach ( $dfi_images as $dfi_image ) {
879 2
                $dfi_image_full = $this->separate( $dfi_image, 'full' );
880 2
                $ret_val[]      = (int) $this->get_image_id( $this->upload_url . $dfi_image_full );
881 2
            }
882 2
        }
883 2
		$ret_val = $this->sanitize_array( $ret_val );
884 2
        return $ret_val;
885
    }
886
887
    /**
888
     * Get real post id.
889
     *
890
     * @since 3.6.0
891
     * @access protected
892
     *
893
     * @param int|null $post_id Post id.
894
     *
895
     * @return int|null
896
     */
897 6
    protected function get_real_post_id( $post_id = null ) {
898 6
        if ( ! is_null( $post_id ) && is_numeric( $post_id ) ) {
899 5
            return $post_id;
900
        }
901
902 3
        global $post;
903
904 3
        return $post->ID;
905
    }
906
907
    /**
908
     * Fetches featured image data of nth position.
909
     *
910
     * @since  3.0.0
911
     * @access  public
912
     *
913
     * @see  get_featured_images()
914
     *
915
     * @param  int $position Position of the featured image.
916
     * @param  int $post_id Current post id.
917
     *
918
     * @return array if found, null otherwise.
919
     */
920 2
    public function get_nth_featured_image( $position, $post_id = null ) {
921 2
        $post_id = $this->get_real_post_id( ( $post_id ) );
922
923 2
        $featured_images = $this->get_featured_images( $post_id );
924
925 2
        return isset( $featured_images[ $position - 2 ] ) ?  sanitize_text_field( $featured_images[ $position - 2 ] ) : null;
926
    }
927
928
    /**
929
     * Check if the image is attached with the particular post.
930
     *
931
     * @since 2.0.0
932
     * @access public
933
     *
934
     * @see  get_post_attachment_ids()
935
     *
936
     * @param  int $attachment_id Attachment id of an image.
937
     * @param  int $post_id Current post id.
938
     *
939
     * @return bool
940
     */
941 1
    public function is_attached( $attachment_id, $post_id ) {
942 1
        if ( empty( $attachment_id ) ) {
943
            return false;
944
        }
945
946 1
        $attachment_ids = $this->get_post_attachment_ids( $post_id );
947
948 1
        return in_array( $attachment_id, $attachment_ids, true ) ? true : false;
949
    }
950
951
    /**
952
     * Retrieve featured images for specific post(s).
953
     *
954
     * @since 2.0.0
955
     * @access public
956
     *
957
     * @see get_post_meta()
958
     *
959
     * @param  int $post_id id of the current post.
960
     *
961
     * @return array
962
     */
963 7
    public function get_featured_images( $post_id = null ) {
964 7
        $post_id    = $this->get_real_post_id( $post_id );
965 7
        $dfi_images = get_post_meta( $post_id, 'dfiFeatured', true );
966 7
        $ret_images = array();
967
968 7
        if ( ! empty( $dfi_images ) && is_array( $dfi_images ) ) {
969 7
            $dfi_images = array_filter( $dfi_images );
970
971 7
            $count = 0;
972 7
            foreach ( $dfi_images as $dfi_image ) {
973 7
                $dfi_image_trimmed = $this->separate( $dfi_image );
974 7
                $dfi_image_full    = $this->separate( $dfi_image, 'full' );
975
976
                try {
977 7
                    $ret_images[ $count ]['thumb']         = $this->get_real_upload_path( $dfi_image_trimmed );
978 7
                    $ret_images[ $count ]['full']          = $this->get_real_upload_path( $dfi_image_full );
979 7
                    $ret_images[ $count ]['attachment_id'] = $this->get_image_id( $ret_images[ $count ]['full'] );
980 7
					$ret_images[ $count ] 				   = $this->sanitize_array($ret_images[ $count ]);
981 7
                } catch ( Exception $e ) {
982
                    /* Ignore the exception and continue with other featured images */
983
                }
984
985 7
                $count ++;
986 7
            }
987 7
        }
988
989 7
        return $ret_images;
990
    }
991
992
    /**
993
     * Check to see if the upload url is already available in path.
994
     *
995
     * @since  3.1.14
996
     * @access protected
997
     *
998
     * @param  string $img Uploaded image.
999
     *
1000
     * @return string
1001
     */
1002 2
    protected function get_real_upload_path( $img ) {
1003
        // check if upload path is already attached.
1004 2
        if ( false !== strpos( $img, $this->upload_url ) || preg_match( '/https?:\/\//', $img ) ) {
1005 2
            return $img;
1006
        }
1007
1008 2
        return sanitize_text_field($this->upload_url . $img);
1009
    }
1010
1011
    /**
1012
     * Retrieve featured images for specific post(s) including the default Featured Image.
1013
     *
1014
     * @since 3.1.7
1015
     * @access public
1016
     *
1017
     * @see  $this->get_featured_images()
1018
     *
1019
     * @param int $post_id Current post id.
1020
     *
1021
     * @return array An array of images or an empty array on failure
1022
     */
1023 2
    public function get_all_featured_images( $post_id = null ) {
1024 2
        $post_id      = $this->get_real_post_id( $post_id );
1025 2
        $thumbnail_id = get_post_thumbnail_id( $post_id );
1026 2
        $all_images   = array();
1027
1028 2
        if ( ! empty( $thumbnail_id ) ) {
1029
            $featured_image         = array(
1030 2
                'thumb'         => wp_get_attachment_thumb_url( $thumbnail_id ),
1031 2
                'full'          => wp_get_attachment_url( $thumbnail_id ),
1032 2
                'attachment_id' => $thumbnail_id,
1033 2
            );
1034
1035 2
            $all_images[] = $featured_image;
1036 2
        }
1037
1038 2
        return array_merge( $all_images, $this->get_featured_images( $post_id ) );
1039
    }
1040
1041
    /**
1042
     * Load the plugin's textdomain hooked to 'plugins_loaded'.
1043
     *
1044
     * @since 1.0.0
1045
     * @access public
1046
     *
1047
     * @see    load_plugin_textdomain()
1048
     * @see    plugin_basename()
1049
     * @action plugins_loaded
1050
     *
1051
     * @codeCoverageIgnore
1052
     *
1053
     * @return void
1054
     */
1055
    public function load_plugin_textdomain() {
1056
        load_plugin_textdomain(
1057
            self::TEXT_DOMAIN,
1058
            false,
1059
            dirname( plugin_basename( __FILE__ ) ) . '/languages/'
1060
        );
1061
    }
1062
}
1063
1064
// Sponsors who support this plugin.
1065
include 'sponsors.php';
1066
1067
/**
1068
 * Instantiate the main class.
1069
 *
1070
 * @since 1.0.0
1071
 * @access public
1072
 *
1073
 * @var object $dynamic_featured_image holds the instantiated class {@uses Dynamic_Featured_Image}
1074
 */
1075
global $dynamic_featured_image;
1076
$dynamic_featured_image = new Dynamic_Featured_Image();
1077