Completed
Push — master ( 5c3df7...e73e89 )
by Ankit
02:03
created

Dynamic_Featured_Image::enqueue_admin_scripts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
cc 1
eloc 13
nc 1
nop 0
1
<?php
2
/**
3
 *
4
 * Plugin Name: Dynamic Featured Image
5
 * Plugin URI: http://wordpress.org/plugins/dynamic-featured-image/
6
 * Description: Dynamically adds multiple featured image or post thumbnail functionality to your posts, pages and custom post types.
7
 * Version: 3.5.2
8
 * Author: Ankit Pokhrel
9
 * Author URI: http://ankitpokhrel.com.np
10
 * License: GPL2 or later
11
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
12
 * Text Domain: dynamic-featured-image
13
 * Domain Path: /languages
14
 * GitHub Plugin URI: https://github.com/ankitpokhrel/Dynamic-Featured-Image
15
 *
16
 * @package dynamic-featured-image
17
 *
18
 * Copyright (C) 2013 Ankit Pokhrel <[email protected], http://ankitpokhrel.com.np>,
19
 *
20
 * This program is free software; you can redistribute it and/or modify
21
 * it under the terms of the GNU General Public License as published by
22
 * the Free Software Foundation; either version 3 of the License, or
23
 * (at your option) any later version.
24
 *
25
 * This program is distributed in the hope that it will be useful,
26
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28
 * GNU General Public License for more details.
29
 *
30
 * You should have received a copy of the GNU General Public License
31
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
32
 */
33
34
// Avoid direct calls to this file.
35
if ( ! defined( 'ABSPATH' ) ) {
36
    header( 'Status: 403 Forbidden' );
37
    header( 'HTTP/1.1 403 Forbidden' );
38
    exit();
39
}
40
41
/**
42
 * Dynamic Featured Image plugin main class.
43
 *
44
 * @package dynamic-featured-image
45
 * @author Ankit Pokhrel <[email protected]>
46
 * @version 3.0.1
47
 */
48
class Dynamic_Featured_Image {
49
    /**
50
     * Current version of the plugin.
51
     *
52
     * @since 3.0.0
53
     */
54
    const VERSION = '3.5.2';
55
56
    /**
57
     * Image upload directory.
58
     *
59
     * @var $__upload_dir string
60
     */
61
    private $__upload_dir;
62
63
    /**
64
     * Image upload URL.
65
     *
66
     * @var $__upload_url string
67
     */
68
    private $__upload_url;
69
70
    /**
71
     * Database object.
72
     *
73
     * @var $__db wpdb
74
     */
75
    private $__db;
76
77
    /**
78
     * Plugin text domain.
79
     *
80
     * @var $_textDomain string
81
     */
82
    protected $_textDomain;
83
84
    /**
85
     * Title for dfi metabox.
86
     *
87
     * @var $_metabox string
88
     */
89
    protected $_metabox_title;
90
91
    /**
92
     * Users post type filter for dfi metabox.
93
     *
94
     * @var $_userFilter array
95
     */
96
    protected $_userFilter;
97
98
    /**
99
     * Constructor. Hooks all interactions to initialize the class.
100
     *
101
     * @since 1.0.0
102
     * @access public
103
     * @global object $wpdb
104
     *
105
     * @see     add_action()
106
     */
107
    public function __construct() {
108
        $this->_textDomain = 'dynamic-featured-image';
109
110
        // plugin update warning.
111
        add_action( 'in_plugin_update_message-' . plugin_basename( __FILE__ ), array( $this, 'update_notice' ) );
112
113
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
114
        add_action( 'add_meta_boxes', array( $this, 'initialize_featured_box' ) );
115
        add_action( 'save_post', array( $this, 'save_meta' ) );
116
        add_action( 'plugins_loaded', array( $this, 'load_plugin_textdomain' ) );
117
118
        // handle ajax request.
119
        add_action( 'wp_ajax_dfiMetaBox_callback', array( $this, 'ajax_callback' ) );
120
121
        // add action links.
122
        add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'dfi_action_links' ) );
123
124
        // media uploader custom fields.
125
        add_filter( 'attachment_fields_to_edit', array( $this, 'media_attachment_custom_fields' ), 10, 2 );
126
        add_filter( 'attachment_fields_to_save', array( $this, 'media_attachment_custom_fields_save' ), 10, 2 );
127
128
        // get the site protocol.
129
        $protocol = $this->__get_protocol();
130
131
        $this->__upload_dir = wp_upload_dir();
132
        $this->__upload_url = preg_replace( '#^https?://#', '', $this->__upload_dir['baseurl'] );
133
134
        // add protocol to the upload url.
135
        $this->__upload_url = $protocol . $this->__upload_url;
136
137
        // post type filter added by user.
138
        $this->_userFilter = array();
139
140
        global $wpdb;
141
        $this->__db = $wpdb;
142
    }
143
144
    /**
145
     * Return site protocol.
146
     *
147
     * @since 3.5.1
148
     * @access public
149
     *
150
     * @return string
151
     */
152
    private function __get_protocol() {
0 ignored issues
show
Coding Style introduced by
__get_protocol uses the super-global variable $_SERVER which is generally not recommended.

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

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

// Better
class Router
{
    private $host;

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

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

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

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
153
        return ( ( ! empty( $_SERVER['HTTPS'] ) && 'off' !== $_SERVER['HTTPS'] ) ||
154
                 ( ! empty( $_SERVER['SERVER_PORT'] ) && 443 === $_SERVER['SERVER_PORT'] ) ) ? 'https://' : 'http://';
155
    }
156
157
    /**
158
     * Add required admin scripts.
159
     *
160
     * @since 1.0.0
161
     * @access public
162
     *
163
     * @see  wp_enque_style()
164
     * @see  wp_register_script()
165
     * @see  wp_enqueue_script()
166
     *
167
     * @return void
168
     */
169
    public function enqueue_admin_scripts() {
170
        // enqueue styles.
171
        wp_enqueue_style( 'style-dfi', plugins_url( '/css/style-dfi.css', __FILE__ ), array(), self::VERSION );
172
        wp_enqueue_style( 'dashicons', plugins_url( '/css/dashicons.css', __FILE__ ), array(), self::VERSION );
173
174
        // register script.
175
        wp_register_script( 'scripts-dfi', plugins_url( '/js/script-dfi.js', __FILE__ ), array( 'jquery' ), self::VERSION );
176
177
        // localize the script with required data.
178
        wp_localize_script(
179
            'scripts-dfi',
180
            'WP_SPECIFIC',
181
            array(
182
                'upload_url'               => $this->__upload_url,
183
                'metabox_title'            => __( $this->_metabox_title, $this->_textDomain ),
184
                'mediaSelector_title'      => __( 'Dynamic Featured Image - Media Selector', $this->_textDomain ),
185
                'mediaSelector_buttonText' => __( 'Set Featured Image', $this->_textDomain ),
186
            )
187
        );
188
189
        // enqueue scripts.
190
        wp_enqueue_script( 'scripts-dfi' );
191
    }
192
193
    /**
194
     * Add upgrade link.
195
     *
196
     * @access public
197
     * @since  3.5.1
198
     * @action plugin_action_links
199
     *
200
     * @codeCoverageIgnore
201
     *
202
     * @param  array $links Action links.
203
     *
204
     * @return array
205
     */
206
    public function dfi_action_links( $links ) {
207
        $upgrade_link = array(
208
            '<a href="http://ankitpokhrel.com.np/blog/downloads/dynamic-featured-image-pro/" target="_blank">Upgrade to Premium</a>'
209
        );
210
211
        return array_merge( $links, $upgrade_link );
212
    }
213
214
    /**
215
     * Add featured meta boxes dynamically.
216
     *
217
     * @since 1.0.0
218
     * @access public
219
     * @global object $post
220
     *
221
     * @see  get_post_meta()
222
     * @see  get_post_types()
223
     * @see  add_meta_box()
224
     * @see  add_filter()
225
     *
226
     * @return void
227
     */
228
    public function initialize_featured_box() {
229
        global $post;
230
231
        // make metabox title dynamic.
232
        $this->_metabox_title = apply_filters( 'dfi_set_metabox_title', __( 'Featured Image', $this->_textDomain ) );
233
234
        $featuredData  = get_post_meta( $post->ID, 'dfiFeatured', true );
235
        $totalFeatured = count( $featuredData );
236
237
        $defaultFilter     = array( 'attachment', 'revision', 'nav_menu_item' );
238
        $this->_userFilter = apply_filters( 'dfi_post_type_user_filter', $this->_userFilter );
239
        $filter            = array_merge( $defaultFilter, $this->_userFilter );
240
241
        $postTypes = get_post_types();
242
        $postTypes = array_diff( $postTypes, $filter );
243
244
        $postTypes = apply_filters( 'dfi_post_types', $postTypes );
245
246
        if ( ! empty( $featuredData ) && $totalFeatured >= 1 ) {
247
            $i = 2;
248
            foreach ( $featuredData as $featured ) {
249
                self::_dfi_add_meta_box( $postTypes, $featured, $i );
250
                $i ++;
251
            }
252
        } else {
253
            self::_dfi_add_meta_box( $postTypes );
254
        }
255
    }
256
257
    /**
258
     * Translates more than one digit number digit by digit.
259
     *
260
     * @param  int $number Integer to be translated.
261
     *
262
     * @return string Translated number
263
     */
264
    protected function _get_number_translation( $number ) {
265
        if ( $number <= 9 ) {
266
            return __( $number, $this->_textDomain );
267
        } else {
268
            $pieces = str_split( $number, 1 );
269
            $buffer = '';
270
            foreach ( $pieces as $piece ) {
271
                $buffer .= __( $piece, $this->_textDomain );
272
            }
273
274
            return $buffer;
275
        }
276
    }
277
278
    /**
279
     * Adds meta boxes.
280
     *
281
     * @param  array  $postTypes Post types to show featured image box.
282
     * @param  object $featured Callback arguments.
283
     * @param  int    $i Index of the featured image.
284
     *
285
     * @return void
286
     */
287
    private function _dfi_add_meta_box( $postTypes, $featured = null, $i = null ) {
288
        if ( ! is_null( $i ) ) {
289
            foreach ( $postTypes as $type ) {
290
                add_meta_box(
291
                    'dfiFeaturedMetaBox-' . $i,
292
                    __( $this->_metabox_title, $this->_textDomain ) . ' ' . self::_get_number_translation( $i ),
293
                    array( $this, 'featured_meta_box' ),
294
                    $type,
295
                    'side',
296
                    'low',
297
                    array( $featured, $i + 1 )
298
                );
299
                add_filter( "postbox_classes_{$type}_dfiFeaturedMetaBox-" . $i, array( $this, 'add_metabox_classes' ) );
300
            }
301
        } else {
302
            foreach ( $postTypes as $type ) {
303
                add_meta_box(
304
                    'dfiFeaturedMetaBox',
305
                    __( $this->_metabox_title, $this->_textDomain ) . ' ' . __( 2, $this->_textDomain ),
306
                    array( $this, 'featured_meta_box' ),
307
                    $type,
308
                    'side',
309
                    'low',
310
                    array( null, null )
311
                );
312
                add_filter( "postbox_classes_{$type}_dfiFeaturedMetaBox", array( $this, 'add_metabox_classes' ) );
313
            }
314
        }
315
    }
316
317
    /**
318
     * Separate thumb and full image url from given URL string.
319
     *
320
     * @since  3.3.1
321
     *
322
     * @param  string $urlString Url string.
323
     * @param  string $state Thumb or full.
324
     *
325
     * @return string|null
326
     */
327
    private function _separate( $urlString, $state = 'thumb' ) {
328
        $imagePiece = explode( ',', $urlString );
329
330
        if ( 'thumb' === $state ) {
331
            return isset( $imagePiece[0] ) ? $imagePiece[0] : null;
332
        }
333
334
        return isset( $imagePiece[1] ) ? $imagePiece[1] : null;
335
    }
336
337
    /**
338
     * Create a nonce field
339
     *
340
     * @since  3.5.0
341
     *
342
     * @see  wp_nonce_field()
343
     * @see  plugin_basename()
344
     *
345
     * @codeCoverageIgnore
346
     *
347
     * @param  string $key Nonce key.
348
     *
349
     * @return string
350
     */
351
    protected function _nonce_field( $key ) {
352
        return wp_nonce_field( plugin_basename( __FILE__ ), $key, true, false );
353
    }
354
355
    /**
356
     * Featured meta box as seen in the admin
357
     *
358
     * @since 1.0.0
359
     * @access public
360
     *
361
     * @param  object $post Global post object.
362
     * @param  array  $featured Array containing featured image count.
363
     *
364
     * @throws Exception Medium size image not found.
365
     * @return void
366
     */
367
    public function featured_meta_box( $post, $featured ) {
368
        $featuredImg        = $featured['args'][0];
369
        $featuredId         = is_null( $featured['args'][1] ) ? 2 : --$featured['args'][1];
370
        $featuredImgFull    = $featuredImg;
371
        $featuredImgTrimmed = $featuredImg;
372
373
        if ( ! is_null( $featuredImg ) ) {
374
            $featuredImgTrimmed = self::_separate( $featuredImg );
375
            $featuredImgFull    = self::_separate( $featuredImg, 'full' );
376
        }
377
378
        try {
379
            $thumbnail = $this->get_image_thumb( $this->__upload_url . $featuredImgFull, 'medium' );
380
            if ( is_null( $thumbnail ) ) {
381
                // medium sized thumbnail image is missing.
382
                throw new Exception( 'Medium size image not found', 1 );
383
            }
384
        } catch ( Exception $e ) {
385
            // since medium sized thumbnail image was not found,
386
            // let's set full image url as thumbnail.
387
            $thumbnail = $featuredImgFull;
388
        }
389
390
        // Add a nonce field.
391
        echo $this->_nonce_field( 'dfi_fimageplug-' . $featuredId );
392
        echo self::_get_featured_box( $featuredImgTrimmed, $featuredImg, $featuredId, $thumbnail, $post->ID );
393
    }
394
395
    /**
396
     * Returns featured box html content.
397
     *
398
     * @since  3.1.0
399
     * @access private
400
     *
401
     * @param  string $featuredImgTrimmed Medium sized image.
402
     * @param  string $featuredImg Full sized image.
403
     * @param  string $featuredId Attachment Id.
404
     * @param  string $thumbnail Thumb sized image.
405
     *
406
     * @return string Html content
407
     */
408
    private function _get_featured_box( $featuredImgTrimmed, $featuredImg, $featuredId, $thumbnail, $postId ) {
409
        $hasFeaturedImage = ! empty( $featuredImgTrimmed ) ? 'hasFeaturedImage' : '';
410
        $thumbnail        = ! is_null( $thumbnail ) ? $thumbnail : '';
411
        $dfiEmpty         = is_null( $featuredImgTrimmed ) ? 'dfiImgEmpty' : '';
412
413
        return "<a href='javascript:void(0)' class='dfiFeaturedImage {$hasFeaturedImage}' title='" . __( 'Set Featured Image', $this->_textDomain ) . "' data-post-id='" . $postId . "'><span class='dashicons dashicons-camera'></span></a><br/>
414
            <img src='" . $thumbnail . "' class='dfiImg {$dfiEmpty}'/>
415
            <div class='dfiLinks'>
416
                <a href='javascript:void(0)' data-id='{$featuredId}' data-id-local='" . $this->_get_number_translation( ( $featuredId + 1 ) ) . "' class='dfiAddNew dashicons dashicons-plus' title='" . __( 'Add New', $this->_textDomain ) . "'></a>
417
                <a href='javascript:void(0)' class='dfiRemove dashicons dashicons-minus' title='" . __( 'Remove', $this->_textDomain ) . "'></a>
418
            </div>
419
            <div class='dfiClearFloat'></div>
420
            <input type='hidden' name='dfiFeatured[]' value='{$featuredImg}'  class='dfiImageHolder' />";
421
    }
422
423
    /**
424
     * Load new featured meta box via ajax
425
     *
426
     * @since 1.0.0
427
     * @access public
428
     *
429
     * @return void
430
     */
431
    public function ajax_callback() {
432
        $featuredId = isset( $_POST['id'] ) ? (int) strip_tags( trim( $_POST['id'] ) ) : null;
433
434
        if ( is_null( $featuredId ) ) {
435
            return;
436
        }
437
438
        echo $this->_nonce_field( 'dfi_fimageplug-' . $featuredId );
439
        ?>
440
        <a href="javascript:void(0)" class="dfiFeaturedImage"
441
           title="<?php echo __( 'Set Featured Image', $this->_textDomain ) ?>"><span
442
                    class="dashicons dashicons-camera"></span></a><br/>
443
        <img src="" class="dfiImg dfiImgEmpty"/>
444
        <div class="dfiLinks">
445
            <a href="javascript:void(0)" data-id="<?php echo $featuredId ?>"
446
               data-id-local="<?php echo self::_get_number_translation( ( $featuredId + 1 ) ) ?>"
447
               class="dfiAddNew dashicons dashicons-plus" title="<?php echo __( 'Add New', $this->_textDomain ) ?>"></a>
448
            <a href="javascript:void(0)" class="dfiRemove dashicons dashicons-minus"
449
               title="<?php echo __( 'Remove', $this->_textDomain ) ?>"></a>
450
        </div>
451
        <div class="dfiClearFloat"></div>
452
        <input type="hidden" name="dfiFeatured[]" value="" class="dfiImageHolder"/>
453
        <?php
454
        wp_die( '' );
455
    }
456
457
    /**
458
     * Add custom class 'featured-meta-box' to meta box.
459
     *
460
     * @since 1.0.0
461
     * @access public
462
     *
463
     * @see  add_metabox_classes
464
     *
465
     * @param array $classes Classes to add in the meta box.
466
     *
467
     * @return array
468
     */
469
    public function add_metabox_classes( $classes ) {
470
        array_push( $classes, 'featured-meta-box' );
471
472
        return $classes;
473
    }
474
475
    /**
476
     * Add custom fields in media uploader.
477
     *
478
     * @since  3.4.0
479
     *
480
     * @param array $form_fields Fields to include in media attachment form.
481
     * @param array $post Post data.
482
     *
483
     * @return array
484
     */
485
    public function media_attachment_custom_fields( $form_fields, $post ) {
486
        $form_fields['dfi-link-to-image'] = array(
487
            'label' => __( 'Link to Image', $this->_textDomain ),
488
            'input' => 'text',
489
            'value' => get_post_meta( $post->ID, '_dfi_link_to_image', true ),
490
        );
491
492
        return $form_fields;
493
    }
494
495
    /**
496
     * Save values of media uploader custom fields.
497
     *
498
     * @since 3.4.0
499
     *
500
     * @param array $post Post data for database.
501
     * @param array $attachment Attachment fields from $_POST form.
502
     *
503
     * @return array
504
     */
505
    public function media_attachment_custom_fields_save( $post, $attachment ) {
506
        if ( isset( $attachment['dfi-link-to-image'] ) ) {
507
            update_post_meta( $post['ID'], '_dfi_link_to_image', $attachment['dfi-link-to-image'] );
508
        }
509
510
        return $post;
511
    }
512
513
    /**
514
     * Update featured images in the database.
515
     *
516
     * @since 1.0.0
517
     * @access public
518
     *
519
     * @see  plugin_basename()
520
     * @see  update_post_meta()
521
     * @see  current_user_can()
522
     *
523
     * @param  int $post_id Current post id.
524
     *
525
     * @return bool
526
     */
527
    public function save_meta( $post_id ) {
528
        // Check auto save.
529
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
530
            return false;
531
        }
532
533
        if ( $this->_verify_nonces() ) {
534
            // Check permission before saving data.
535
            if ( current_user_can( 'edit_posts', $post_id ) && isset( $_POST['dfiFeatured'] ) ) {
536
                update_post_meta( $post_id, 'dfiFeatured', $_POST['dfiFeatured'] );
537
            }
538
        }
539
540
        return false;
541
    }
542
543
    /**
544
     * Verify metabox nonces.
545
     *
546
     * @access protected
547
     * @see  wp_verify_nonce()
548
     *
549
     * @return bool
550
     */
551
    protected function _verify_nonces() {
552
        $keys = array_keys( $_POST );
553
        foreach ( $keys as $key ) {
554
            if ( preg_match( '/dfi_fimageplug-\d+$/', $key ) ) {
555
                // Verify nonce.
556
                if ( ! wp_verify_nonce( $_POST[ $key ], plugin_basename( __FILE__ ) ) ) {
557
                    return false;
558
                }
559
            }
560
        }
561
562
        return true;
563
    }
564
565
    /**
566
     * Add update notice. Displayed in plugin update page.
567
     *
568
     * @since 2.0.0
569
     * @access public
570
     *
571
     * @return void
572
     */
573
    public function update_notice() {
574
        $info = __( 'ATTENTION! Please read the <a href="https://github.com/ankitpokhrel/Dynamic-Featured-Image/wiki" target="_blank">DOCUMENTATION</a> properly before update.', $this->_textDomain );
575
        echo '<div style="color:red; padding:7px 0;">' . strip_tags( $info, '<a><b><i><span>' ) . '</div>';
576
    }
577
578
    /**
579
     * Execute query.
580
     *
581
     * @param string $query Query to execute.
582
     *
583
     * @return null|string
584
     */
585
    private function execute_query( $query ) {
586
        return $this->__db->get_var( $query );
587
    }
588
589
    /**
590
     * Get attachment id of the image by image url.
591
     *
592
     * @since 3.1.7
593
     * @access protected
594
     * @global object $wpdb
595
     *
596
     * @param  string $image_url URL of an image.
597
     *
598
     * @return string
599
     */
600
    protected function _get_attachment_id( $image_url ) {
601
        return self::execute_query( $this->__db->prepare( 'SELECT ID FROM ' . $this->__db->posts . ' WHERE guid = %s', $image_url ) );
602
    }
603
604
    /**
605
     * Get image url of the image by attachment id.
606
     *
607
     * @since 2.0.0
608
     * @access public
609
     *
610
     * @see  wp_get_attachment_image_src()
611
     *
612
     * @param  int    $attachment_id attachment id of an image.
613
     * @param  string $size size of the image to fetch (thumbnail, medium, full).
614
     *
615
     * @return string
616
     */
617
    public function get_image_url( $attachment_id, $size = 'full' ) {
618
        $image_thumb = wp_get_attachment_image_src( $attachment_id, $size );
619
620
        return empty( $image_thumb ) ? null : $image_thumb[0];
621
    }
622
623
    /**
624
     * Get image thumbnail url of specific size by image url.
625
     *
626
     * @since 2.0.0
627
     * @access public
628
     *
629
     * @see  get_image_id()
630
     * @see  wp_get_attachment_image_src()
631
     *
632
     * @param  string $image_url url of an image.
633
     * @param  string $size size of the image to fetch (thumbnail, medium, full).
634
     *
635
     * @return string
636
     */
637
    public function get_image_thumb( $image_url, $size = 'thumbnail' ) {
638
        $attachment_id = $this->get_image_id( $image_url );
639
        $image_thumb   = wp_get_attachment_image_src( $attachment_id, $size );
640
641
        return empty( $image_thumb ) ? null : $image_thumb[0];
642
    }
643
644
    /**
645
     * Gets attachment id from given image url.
646
     *
647
     * @param  string $image_url url of an image.
648
     *
649
     * @since  2.0.0
650
     * @access public
651
     *
652
     * @return int|null attachment id of an image
653
     */
654
    public function get_image_id( $image_url ) {
655
        $attachment_id = $this->_get_attachment_id( $image_url );
656
        if ( is_null( $attachment_id ) ) {
657
            // check if the image is edited image.
658
            // and try to get the attachment id.
659
            $image_url = str_replace( $this->__upload_url . '/', '', $image_url );
660
            $row       = self::execute_query( $this->__db->prepare( 'SELECT post_id FROM ' . $this->__db->postmeta . ' WHERE meta_value = %s', $image_url ) );
661
            if ( ! is_null( $row ) ) {
662
                $attachment_id = $row;
663
            }
664
        }
665
666
        return $attachment_id;
667
    }
668
669
    /**
670
     * Get image title.
671
     *
672
     * @since 2.0.0
673
     * @access public
674
     *
675
     * @param  string $image_url URL of an image.
676
     *
677
     * @return string
678
     */
679
    public function get_image_title( $image_url ) {
680
        return self::execute_query( $this->__db->prepare( 'SELECT post_title FROM ' . $this->__db->posts . ' WHERE guid = %s', $image_url ) );
681
    }
682
683
    /**
684
     * Get image title by id.
685
     *
686
     * @since 2.0.0
687
     * @access public
688
     *
689
     * @param  int $attachment_id Attachment id of an image.
690
     *
691
     * @return string
692
     */
693
    public function get_image_title_by_id( $attachment_id ) {
694
        return self::execute_query( $this->__db->prepare( 'SELECT post_title FROM ' . $this->__db->posts . ' WHERE ID = %d', $attachment_id ) );
695
    }
696
697
    /**
698
     * Get image caption.
699
     *
700
     * @since 2.0.0
701
     * @access public
702
     *
703
     * @param  string $image_url URL of an image.
704
     *
705
     * @return string
706
     */
707
    public function get_image_caption( $image_url ) {
708
        return self::execute_query( $this->__db->prepare( 'SELECT post_excerpt FROM ' . $this->__db->posts . ' WHERE guid = %s', $image_url ) );
709
    }
710
711
    /**
712
     * Get image caption by id.
713
     *
714
     * @since 2.0.0
715
     * @access public
716
     *
717
     * @param  int $attachment_id Attachment id of an image.
718
     *
719
     * @return string
720
     */
721
    public function get_image_caption_by_id( $attachment_id ) {
722
        return self::execute_query( $this->__db->prepare( 'SELECT post_excerpt FROM ' . $this->__db->posts . ' WHERE ID = %d', $attachment_id ) );
723
    }
724
725
    /**
726
     * Get image alternate text.
727
     *
728
     * @since 2.0.0
729
     * @access public
730
     *
731
     * @see  get_post_meta()
732
     *
733
     * @param  string $image_url URL of an image.
734
     *
735
     * @return string
736
     */
737
    public function get_image_alt( $image_url ) {
738
        $attachment = $this->__db->get_col( $this->__db->prepare( 'SELECT ID FROM ' . $this->__db->posts . ' WHERE guid = %s', $image_url ) );
739
740
        $alt = null;
741
        if ( ! empty( $attachment ) ) {
742
            $alt = get_post_meta( $attachment[0], '_wp_attachment_image_alt' );
743
        }
744
745
        return ( is_null( $alt ) || empty( $alt ) ) ? null : $alt[0];
746
    }
747
748
    /**
749
     * Get image alternate text by attachment id.
750
     *
751
     * @since 2.0.0
752
     * @access public
753
     *
754
     * @see  get_post_meta()
755
     *
756
     * @param  int $attachment_id Attachment id of an image.
757
     *
758
     * @return string
759
     */
760
    public function get_image_alt_by_id( $attachment_id ) {
761
        $alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt' );
762
763
        return empty( $alt ) ? null : $alt[0];
764
    }
765
766
    /**
767
     * Get image description.
768
     *
769
     * @since 3.0.0
770
     * @access public
771
     *
772
     * @param  string $image_url URL of an image.
773
     *
774
     * @return string
775
     */
776
    public function get_image_description( $image_url ) {
777
        return self::execute_query( $this->__db->prepare( 'SELECT post_content FROM ' . $this->__db->posts . ' WHERE guid = %s', $image_url ) );
778
    }
779
780
    /**
781
     * Get image description by id.
782
     *
783
     * @since 3.0.0
784
     * @access public
785
     *
786
     * @param  int $attachment_id attachment id of an image.
787
     *
788
     * @return string
789
     */
790
    public function get_image_description_by_id( $attachment_id ) {
791
        return self::execute_query( $this->__db->prepare( 'SELECT post_content FROM ' . $this->__db->posts . ' WHERE ID = %d', $attachment_id ) );
792
    }
793
794
    /**
795
     * Get link to image.
796
     *
797
     * @since 3.4.0
798
     * @access public
799
     *
800
     * @param  int $attachment_id Attachment id of an image.
801
     *
802
     * @return string|null
803
     */
804
    public function get_link_to_image( $attachment_id ) {
805
        return get_post_meta( $attachment_id, '_dfi_link_to_image', true );
806
    }
807
808
    /**
809
     * Get all attachment ids of the post.
810
     *
811
     * @since 2.0.0
812
     * @access public
813
     *
814
     * @see  get_post_meta()
815
     *
816
     * @param  int $post_id id of the current post.
817
     *
818
     * @return array
819
     */
820
    public function get_post_attachment_ids( $post_id ) {
821
        $dfiImages = get_post_meta( $post_id, 'dfiFeatured', true );
822
823
        $retVal = array();
824
        if ( ! empty( $dfiImages ) && is_array( $dfiImages ) ) {
825
            foreach ( $dfiImages as $dfiImage ) {
826
                $dfiImageFull = self::_separate( $dfiImage, 'full' );
827
                $retVal[]     = $this->get_image_id( $this->__upload_url . $dfiImageFull );
828
            }
829
        }
830
831
        return $retVal;
832
    }
833
834
    /**
835
     * Fetches featured image data of nth position.
836
     *
837
     * @since  3.0.0
838
     * @access  public
839
     *
840
     * @see  get_featured_images()
841
     *
842
     * @param  int $position Position of the featured image.
843
     * @param  int $post_id Current post id.
844
     *
845
     * @return array if found, null otherwise.
846
     */
847
    public function get_nth_featured_image( $position, $post_id = null ) {
848
        if ( is_null( $post_id ) ) {
849
            global $post;
850
            $post_id = $post->ID;
851
        }
852
853
        $featured_images = $this->get_featured_images( $post_id );
854
855
        return isset( $featured_images[ $position - 2 ] ) ? $featured_images[ $position - 2 ] : null;
856
    }
857
858
    /**
859
     * Check if the image is attached with the particular post.
860
     *
861
     * @since 2.0.0
862
     * @access public
863
     *
864
     * @see  get_post_attachment_ids()
865
     *
866
     * @param  int $attachment_id Attachment id of an image.
867
     * @param  int $post_id Current post id.
868
     *
869
     * @return bool
870
     */
871
    public function is_attached( $attachment_id, $post_id ) {
872
        if ( empty( $attachment_id ) ) {
873
            return false;
874
        }
875
876
        $attachment_ids = $this->get_post_attachment_ids( $post_id );
877
878
        return in_array( $attachment_id, $attachment_ids, true ) ? true : false;
879
    }
880
881
    /**
882
     * Retrieve featured images for specific post(s).
883
     *
884
     * @since 2.0.0
885
     * @access public
886
     *
887
     * @see  get_post_meta()
888
     *
889
     * @param  integer $post_id id of the current post.
890
     *
891
     * @return array
892
     */
893
    public function get_featured_images( $post_id = null ) {
894
        if ( is_null( $post_id ) ) {
895
            global $post;
896
            $post_id = $post->ID;
897
        }
898
899
        $dfiImages = get_post_meta( $post_id, 'dfiFeatured', true );
900
901
        $retImages = array();
902
        if ( ! empty( $dfiImages ) && is_array( $dfiImages ) ) {
903
            $dfiImages = array_filter( $dfiImages );
904
905
            $count = 0;
906
            foreach ( $dfiImages as $dfiImage ) {
907
                $dfiImageTrimmed = self::_separate( $dfiImage );
908
                $dfiImageFull    = self::_separate( $dfiImage, 'full' );
909
910
                try {
911
                    $retImages[ $count ]['thumb']         = $this->_get_real_upload_path( $dfiImageTrimmed );
912
                    $retImages[ $count ]['full']          = $this->_get_real_upload_path( $dfiImageFull );
913
                    $retImages[ $count ]['attachment_id'] = $this->get_image_id( $retImages[ $count ]['full'] );
914
915
                } catch ( Exception $e ) {
916
                    /* Ignore the exception and continue with other featured images */
917
                }
918
919
                $count ++;
920
            }
921
        }
922
923
        return $retImages;
924
    }
925
926
    /**
927
     * Check to see if the upload url is already available in path.
928
     *
929
     * @since  3.1.14
930
     * @access protected
931
     *
932
     * @param  string $img Uploaded image.
933
     *
934
     * @return string
935
     */
936
    protected function _get_real_upload_path( $img ) {
937
        // check if upload path is already attached.
938
        if ( false !== strpos( $img, $this->__upload_url ) || preg_match( '/https?:\/\//', $img ) ) {
939
            return $img;
940
        }
941
942
        return $this->__upload_url . $img;
943
    }
944
945
    /**
946
     * Retrieve featured images for specific post(s) including the default Featured Image.
947
     *
948
     * @since 3.1.7
949
     * @access public
950
     *
951
     * @see  $this->get_featured_images()
952
     *
953
     * @param int $post_id Current post id.
954
     *
955
     * @return array An array of images or an empty array on failure
956
     */
957
    public function get_all_featured_images( $post_id = null ) {
958
        if ( is_null( $post_id ) ) {
959
            global $post;
960
            $post_id = $post->ID;
961
        }
962
963
        $thumbnail_id = get_post_thumbnail_id( $post_id );
964
965
        $featured_image_array = array();
966
        if ( ! empty( $thumbnail_id ) ) {
967
            $featured_image         = array(
968
                'thumb'         => wp_get_attachment_thumb_url( $thumbnail_id ),
969
                'full'          => wp_get_attachment_url( $thumbnail_id ),
970
                'attachment_id' => $thumbnail_id,
971
            );
972
            $featured_image_array[] = $featured_image;
973
        }
974
975
        $dfiImages = $this->get_featured_images( $post_id );
976
977
        $all_featured_images = array_merge( $featured_image_array, $dfiImages );
978
979
        return $all_featured_images;
980
    }
981
982
    /**
983
     * Load the plugin's textdomain hooked to 'plugins_loaded'.
984
     *
985
     * @since 1.0.0
986
     * @access public
987
     *
988
     * @see    load_plugin_textdomain()
989
     * @see    plugin_basename()
990
     * @action plugins_loaded
991
     *
992
     * @codeCoverageIgnore
993
     *
994
     * @return    void
995
     */
996
    public function load_plugin_textdomain() {
997
        load_plugin_textdomain(
998
            $this->_textDomain,
999
            false,
1000
            dirname( plugin_basename( __FILE__ ) ) . '/languages/'
1001
        );
1002
    }
1003
}
1004
1005
/**
1006
 * Instantiate the main class.
1007
 *
1008
 * @since 1.0.0
1009
 * @access public
1010
 *
1011
 * @var object $dynamic_featured_image holds the instantiated class {@uses Dynamic_Featured_Image}
1012
 */
1013
global $dynamic_featured_image;
1014
$dynamic_featured_image = new Dynamic_Featured_Image();
1015