Completed
Push — master ( 8d9355...4de7f8 )
by
unknown
01:45
created

lasso::wpimg_block()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 12
nop 1
dl 0
loc 24
rs 9.2248
c 0
b 0
f 0
1
<?php
2
/**
3
 * AH Editor
4
 *
5
 * @package   Lasso
6
 * @author    Nick Haskins <[email protected]>
7
 * @license   GPL-2.0+
8
 * @link      http://aesopinteractive.com
9
 * @copyright 2015-2017 Aesopinteractive 
10
 */
11
namespace lasso_public_facing;
12
/**
13
 *
14
 *
15
 * @package Lasso
16
 * @author  Nick Haskins <[email protected]>
17
 */
18
class lasso {
19
20
	/**
21
	 *
22
	 *
23
	 * @since    0.0.1
24
	 *
25
	 * @var      string
26
	 */
27
	protected $plugin_slug = 'lasso';
28
29
	/**
30
	 * Instance of this class.
31
	 *
32
	 * @since    0.0.1
33
	 *
34
	 * @var      object
35
	 */
36
	protected static $instance = null;
37
38
	/**
39
	 *
40
	 *
41
	 * @since     0.0.1
42
	 */
43
	private function __construct() {
44
45
		require_once LASSO_DIR.'/public/includes/underscore-templates.php';
46
47
		require_once LASSO_DIR.'/public/includes/editor-modules.php';
48
		require_once LASSO_DIR.'/public/includes/helpers.php';
49
		require_once LASSO_DIR.'/public/includes/editor-modules--gallery.php';
50
		require_once LASSO_DIR.'/public/includes/components.php';
51
		require_once LASSO_DIR.'/public/includes/option-engine.php';
52
		require_once LASSO_DIR.'/public/includes/wrap-shortcodes.php';
53
54
		// Activate plugin when new blog is added
55
		add_action( 'wpmu_new_blog', array( $this, 'activate_new_site' ) );
56
57
		// Load plugin text domain
58
		add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
59
		
60
		add_action( 'wp_ajax_get_aesop_component',     array( $this, 'get_aesop_component' ) );
61
		add_action( 'wp_ajax_editus_do_shortcode',     array( $this, 'editus_do_shortcode' ) );
62
        add_action( 'wp_ajax_editus_do_block',     array( $this, 'editus_do_block' ) );
63
		add_action( 'wp_ajax_editus_lock_post',     array( $this, 'editus_lock_post' ) );
64
		add_action( 'wp_ajax_editus_unlock_post',     array( $this, 'editus_unlock_post' ) );
65
		add_action( 'wp_ajax_editus_hide_tour',     array( $this, 'editus_hide_tour' ) );
66
		add_action( 'wp_ajax_editus_set_post_setting',     array( $this, 'editus_set_post_setting' ) );
67
		add_action( 'wp_ajax_editus_get_ase_options',     array( $this, 'get_ase_options' ) );
68
		add_action( 'wp_ajax_editus_delete_post',     array( $this, 'delete_post' ) );
69
		add_action( 'wp_ajax_editus_featured_img',     array( $this, 'set_featured_img' ) );
70
		add_action( 'wp_ajax_editus_del_featured_img',     array( $this, 'del_featured_img' ) );
71
        
72
        add_action( 'wp_ajax_editus_publish_post',     array( $this, 'on_publish_post' ) );
73
        
74
        add_action( 'wp_ajax_editus_create_gallery',     array( $this, 'create_gallery' ) );
75
        add_action( 'wp_ajax_editus_update_gallery',     array( $this, 'update_gallery' ) );
76
77
		// enable saving custom fields through REST API
78
		self::enable_metasave('post');
79
		self::enable_metasave('page');
80
		//enqueue assets
81
		new assets();
82
83
	}
84
85
	/**
86
	 * Return the plugin slug.
87
	 *
88
	 * @since    0.0.1
89
	 *
90
	 * @return    Plugin slug variable.
91
	 */
92
	public function get_plugin_slug() {
93
		return $this->plugin_slug;
94
	}
95
96
	/**
97
	 * Return an instance of this class.
98
	 *
99
	 * @since     0.0.1
100
	 *
101
	 * @return    object    A single instance of this class.
102
	 */
103
	public static function get_instance() {
104
105
		// If the single instance hasn't been set, set it now.
106
		if ( null == self::$instance ) {
107
			self::$instance = new self;
108
		}
109
110
		return self::$instance;
111
	}
112
113
	/**
114
	 * Fired when the plugin is activated.
115
	 *
116
	 * @since    0.0.1
117
	 *
118
	 * @param boolean $network_wide True if WPMU superadmin uses
119
	 *                                       "Network Activate" action, false if
120
	 *                                       WPMU is disabled or plugin is
121
	 *                                       activated on an individual blog.
122
	 */
123 View Code Duplication
	public static function activate( $network_wide ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
124
125
		if ( function_exists( 'is_multisite' ) && is_multisite() ) {
126
127
			if ( $network_wide  ) {
128
129
				// Get all blog ids
130
				$blog_ids = self::get_blog_ids();
131
132
				foreach ( $blog_ids as $blog_id ) {
0 ignored issues
show
Bug introduced by
The expression $blog_ids of type array|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
133
134
					switch_to_blog( $blog_id );
135
					self::single_activate();
136
				}
137
138
				restore_current_blog();
139
140
			} else {
141
				self::single_activate();
142
			}
143
144
		} else {
145
			self::single_activate();
146
		}
147
148
	}
149
150
	/**
151
	 * Fired when the plugin is deactivated.
152
	 *
153
	 * @since    0.0.1
154
	 *
155
	 * @param boolean $network_wide True if WPMU superadmin uses
156
	 *                                       "Network Deactivate" action, false if
157
	 *                                       WPMU is disabled or plugin is
158
	 *                                       deactivated on an individual blog.
159
	 */
160 View Code Duplication
	public static function deactivate( $network_wide ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
161
162
		if ( function_exists( 'is_multisite' ) && is_multisite() ) {
163
164
			if ( $network_wide ) {
165
166
				// Get all blog ids
167
				$blog_ids = self::get_blog_ids();
168
169
				foreach ( $blog_ids as $blog_id ) {
0 ignored issues
show
Bug introduced by
The expression $blog_ids of type array|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
170
171
					switch_to_blog( $blog_id );
172
					self::single_deactivate();
0 ignored issues
show
Unused Code introduced by
The call to the method lasso_public_facing\lasso::single_deactivate() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
173
174
				}
175
176
				restore_current_blog();
177
178
			} else {
179
				self::single_deactivate();
0 ignored issues
show
Unused Code introduced by
The call to the method lasso_public_facing\lasso::single_deactivate() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
180
			}
181
182
		} else {
183
			self::single_deactivate();
0 ignored issues
show
Unused Code introduced by
The call to the method lasso_public_facing\lasso::single_deactivate() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
184
		}
185
186
	}
187
188
	/**
189
	 * Fired when a new site is activated with a WPMU environment.
190
	 *
191
	 * @since    0.0.1
192
	 *
193
	 * @param int     $blog_id ID of the new blog.
194
	 */
195
	public function activate_new_site( $blog_id ) {
196
197
		if ( 1 !== did_action( 'wpmu_new_blog' ) ) {
198
			return;
199
		}
200
201
		switch_to_blog( $blog_id );
202
		self::single_activate();
203
		restore_current_blog();
204
205
	}
206
207
	/**
208
	 * Get all blog ids of blogs in the current network that are:
209
	 * - not archived
210
	 * - not spam
211
	 * - not deleted
212
	 *
213
	 * @since    0.0.1
214
	 *
215
	 * @return   array|false    The blog ids, false if no matches.
216
	 */
217
	private static function get_blog_ids() {
218
219
		global $wpdb;
220
221
		// get an array of blog ids
222
		$sql = "SELECT blog_id FROM $wpdb->blogs
223
			WHERE archived = '0' AND spam = '0'
224
			AND deleted = '0'";
225
226
		return $wpdb->get_col( $sql );
227
228
	}
229
230
	/**
231
	 * Fired for each blog when the plugin is activated.
232
	 *
233
	 * @since    0.0.1
234
	 */
235
	private static function single_activate() {
236
237
		$curr_version = get_option( 'lasso_version' );
238
239
		// update upgraded from
240
		if ( $curr_version ) {
241
			update_option( 'lasso_updated_from', $curr_version );
242
		}
243
244
		// update lasso version option
245
		update_option( 'lasso_version', LASSO_VERSION );
246
247
		// set transietn for activation welcome
248
		set_transient( '_lasso_welcome_redirect', true, 30 );
249
250
251
	}
252
253
	/**
254
	 * Fired for each blog when the plugin is deactivated.
255
	 *
256
	 * @since    0.0.1
257
	 */
258
	private static function single_deactivate() {
259
		// @TODO: Define deactivation functionality here
260
	}
261
262
	/**
263
	 * Load the plugin text domain for translation.
264
	 *
265
	 * @since    1.0.0
266
	 */
267
	public function load_plugin_textdomain() {
268
269
		$domain = $this->plugin_slug;
270
		$locale = apply_filters( 'plugin_locale', get_locale(), $domain );
271
272
		$out = load_textdomain( $domain, trailingslashit( LASSO_DIR ). 'languages/' . $domain . '-' . $locale . '.mo' );
0 ignored issues
show
Unused Code introduced by
$out is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
273
	}
274
	
275
    // new ajax function to lock post for editing
276
	public function editus_lock_post()
277
	{
278
		$post_id= $_POST["postid"];
279
		$locked = wp_check_post_lock($post_id);
280
		
281
		if (!$locked) {
282
		    wp_set_post_lock($post_id);
283
			echo "true";
284
		} else {
285
			$user_info = get_userdata($locked);
286
			echo _e( 'Post being edited by ', 'lasso' ).$user_info->first_name .  " " . $user_info->last_name;
287
		}
288
		exit;
289
	}
290
	
291
	public function editus_unlock_post()
292
	{
293
		$post_id= $_POST["postid"];
294
		$locked = wp_check_post_lock($post_id);
295
        if (!$locked) {
296
            delete_post_meta( $post_id, '_edit_lock');
297
        }
298
		echo "true";
299
		
300
		exit;
301
	}
302
	
303
	// new ajax function to update tour setting
304
	public function editus_hide_tour()
305
	{
306
		$user_id = get_current_user_ID();
307
				
308
		update_user_meta( $user_id, 'lasso_hide_tour', true );
309
		exit;
310
	}
311
	
312
	public function editus_set_post_setting()
313
	{
314
		
315
		
316
		$data = array();
317
		parse_str($_POST['data'], $data);
318
		
319
		if (!wp_verify_nonce( $data[ 'nonce' ], 'lasso-update-post-settings' )) {
320
			wp_send_json_error();
321
			exit;
322
		}
323
		
324
		$status = isset( $data['status'] ) ? $data['status'] : false;
325
		$postid = isset( $data['postid'] ) ? $data['postid'] : false;
326
		$slug   = isset( $data['story_slug'] ) ? $data['story_slug'] : false;
327
        $excerpt   = isset( $data['excerpt'] ) ? $data['excerpt'] : false;
328
	
329
330
		$args = array(
331
			'ID'   			=> (int) $postid,
332
			'post_name'  	=> $slug,
333
			'post_status' 	=> $status,
334
            'post_excerpt'  => $excerpt
335
		);
336
		
337
		
338
339
		wp_update_post( apply_filters( 'lasso_object_status_update_args', $args ) );
340
		
341
		// update categories
342
		$cats  = isset( $data['story_cats'] ) ? $data['story_cats'] : false;
343
		
344
		self::set_post_terms( $postid, $cats, 'category' );
345
		
346
		// update tags
347
		$tags = isset( $data['story_tags'] ) ? $data['story_tags'] : false;
348
		self::set_post_terms( $postid, $tags, 'post_tag' );
349
		
350
		//update date
351
		$date  = isset( $data['post_date'] ) ? $data['post_date'] : false;
352
		self::set_date( $postid, $date );
353
		
354
		do_action( 'lasso_post_updated', $postid, $slug, $status, get_current_user_ID() );
355
		$response= array(
356
			'link'   => get_permalink($postid). (($status=='publish') ? '' : '&preview=true')
357
		);
358
		wp_send_json_success($response);
359
		exit;
360
	}
361
	
362
	public static function enable_metasave($type)
363
	{
364
		register_rest_field( $type, 'metadata', array(
365
			'get_callback' => function ( $data ) {
366
				return get_post_meta( $data['id']);//, '', '' );
367
			}, 
368
			'update_callback' => function( $data, $post ) {
369
				foreach ($data as $key => $value) {
370
					update_post_meta($post->ID, $key, $value);
371
				}
372
				return true;
373
			}
374
		));
375
	}
376
	
377
	public function editus_do_shortcode()
378
	{
379
		
380
		$code= $_POST["code"];
381
		$code = str_replace('\"', '"', $code);
382
		
383
		$code_wrapped = lasso_wrap_shortcodes( $code);
384
		$out =  do_shortcode($code);
385
		if ($out != '') {
386
			$out =  do_shortcode($code_wrapped);
387
			echo $out;
388
			exit;
389
		}
390
		
391
		// do_shortcode didn't work. Try again using wp_embed
392
393
		/** @var \WP_Embed $wp_embed */
394
		global $wp_embed;
395
		$wp_embed->post_ID = $_POST["ID"];
396
		$out =$wp_embed->run_shortcode( $code_wrapped );
397
		
398
		echo $out;
399
		exit;
400
	}
401
    
402
    public function editus_do_block()
403
	{
404
		
405
		$code= $_POST["code"];
406
407
        $out = do_blocks( $code );
408
		
409
		echo $out;
410
		exit;
411
	}
412
	
413
	public function get_aesop_component()
414
	{
415
		
416
		
417
		$code= $_POST["code"];
418
		$atts = array(
419
		 );
420
		foreach ($_POST as $key => $value) {
421
			if ($key !="code" && $key !="action") {
422
				$atts[$key] = $value;
423
			}
424
		}
425
		if ($code == "aesop_video") {
426
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-video.php');
427
		    echo aesop_video_shortcode($atts);
428
		}
429
		else if ($code == "aesop_image") {
430
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-image.php');
431
		    echo aesop_image_shortcode($atts);
432
		}
433
		else if ($code == "aesop_quote") {
434
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-quote.php');
435
		    echo aesop_quote_shortcode($atts);
436
		}
437
		else if ($code == "aesop_parallax") {
438
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-parallax.php');
439
		    echo aesop_parallax_shortcode($atts);
440
		}
441
		else if ($code == "aesop_character") {
442
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-character.php');
443
		    echo aesop_character_shortcode($atts);
444
		}
445
		else if ($code == "aesop_collection") {
446
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-collections.php');
447
		    echo aesop_collection_shortcode($atts);
448
		}
449
		else if ($code == "aesop_chapter") {
450
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-heading.php');
451
		    echo aesop_chapter_shortcode($atts);
452
		}
453
		else if ($code == "aesop_content") {
454
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-cbox.php');
455
		    echo aesop_content_shortcode($atts, $atts['content_data']);
456
		}
457
		else if ($code == "aesop_gallery") {
458
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-gallery.php');
459
		    echo do_shortcode( '[aesop_gallery id="'.$atts["id"].'"]');
460
		}
461
		else if ($code == "aesop_audio") {
462
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-audio.php');
463
		    echo aesop_audio_shortcode($atts);
464
		}
465
		else if ($code == "aesop_document") {
466
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-document.php');
467
		    echo aesop_document_shortcode($atts);
468
		}
469
        /*else if ($code == "aesop_content") {
470
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-content.php');
471
		    echo aesop_content_shortcode($atts);
472
		}*/
473
        else if ($code == "aesop_wpimg") {
474
            self::wpimg($atts);
475
		}
476
		else if ($code == "aesop_wpimg-block") {
477
            self::wpimg_block($atts);
478
		}
479
		else {
480
			$code = '['.$code.' ';
481
			foreach ($atts as $key => $value) {
482
			    $code = ''.$key.'="'.$value.'" ';
483
			}
484
			$code = $code.']';
485
			echo do_shortcode($code);
486
		}
487
		echo '<p contenteditable="true"><br></p>';
488
		exit; 
489
	}
490
    
491
    public static function wpimg($atts) {
492
493
        echo '<figure data-component-type="wpimg"';
494
        
495
        $extra = "";
496
        
497
        // try to use srcset and sizes on new WP installs
498
		if ( function_exists('wp_get_attachment_image_srcset') && $attachment_id = attachment_url_to_postid( $atts['img'] ) ) {
499
			$srcset = wp_get_attachment_image_srcset( $attachment_id, 'full' );
500
			$sizes = wp_get_attachment_image_sizes( $attachment_id, 'full' );
501
            $extra = "srcset='$srcset' sizes='$sizes' ";
502
        }
503
        if ($atts['align']=="left") {
504
            $extra .= 'class="alignleft';
505
        } else if ($atts['align']=="right") {
506
            $extra .= 'class="alignright';
507
        } else {
508
            $extra .= 'class="aligncenter';
509
        }
510
        if ($atts['imgwidth'] || $atts['imgheight']) {
511
            if ($atts['imgwidth']) {
512
                $extra .= 'width:'. $atts['imgwidth'].';';
513
            }
514
            if ($atts['imgheight']) {
515
                $extra .= 'height:'. $atts['imgheight'].';';
516
            }
517
            
518
        }
519
        $extra .= '"';
520
        
521
        foreach ($atts as $key => $value) {
522
			 echo ' data-'.$key.'="'.$value.'"';
523
		}
524
        //echo ' class="wp-image- lasso--wpimg__wrap lasso-component">';
525
        echo ' class="wp-caption lasso-component">';
526
        $hrefset = false;
527
        if ($atts['link'] != '' && (!isset($atts['linkoption']) || $atts['linkoption']=="url" ))
528
        {
529
            echo '<a href="' . $atts['link'] . '">';
530
            $hrefset = true;
531
        } else if (isset($atts['linkoption']) && $atts['linkoption'] == 'img' ) {
532
            echo '<a href="' . $atts['img'] . '">';
533
            $hrefset = true;
534
        }
535
        echo '<img src="' . $atts['img'] . '" alt="'. $atts['alt']  .  '" '. $extra. '>';
536
        if ($hrefset)
537
        {
538
            echo '</a>';
539
        }
540
        if ($atts['caption'])
541
        {
542
            echo '<figcaption class="wp-caption-text">'.$atts['caption'].'</figcaption>';
543
        }
544
        echo '</figure>';
545
        echo '<p><br></p>';
546
        return;
547
    }
548
	
549
	public static function wpimg_block($atts) {
550
		$imgextra = '';
551
		if (!empty($atts['id'])) {
552
			$imgextra = 'class="wp-image-'.$atts['id'].'"';
553
		}
554
        $figclass = 'aligncenter';
0 ignored issues
show
Unused Code introduced by
$figclass is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
555
        if ($atts['align']=="left") {
556
            $figclass = 'alignleft';
557
        } else if ($atts['align']=="right") {
558
            $figclass = 'alignright';
559
        } else {
560
            $figclass = 'aligncenter';
561
        }
562
        echo '<div class="wp-block-image" data-component-type="wpimg-block">'; 
563
        echo '<figure class="'.$figclass.' size-large" data-component-type="wpimg-block">';        
564
        echo '<img src="' . $atts['img'] . '" alt="'. $atts['alt']  . '"' . $imgextra . ' ">';
565
        if ($atts['caption'])
566
        {
567
            echo '<figcaption>'.$atts['caption'].'</figcaption>';
568
        }
569
        echo '</figure></div>';
570
        echo '<p><br></p>';
571
        return;
572
    }
573
	
574
	
575
	public function get_ase_options()
576
	{
577
		$blob = lasso_editor_options_blob();
578
		$code= $_POST["component"];
579
		echo $blob[$code];
580
		exit; 
581
	}
582
	
583
	public function delete_post( ) {
584
585
		$postid = isset( $_POST['postid'] ) ? $_POST['postid'] : false;
586
587
		// bail out if the current user can't publish posts
588
		if ( !lasso_user_can( 'delete_post', $postid ) )
589
			return;
590
		
591
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_delete_post' )) {
592
			wp_send_json_error();
593
			exit;
594
		}
595
596
		$args = array(
597
			'ID'   			=> (int) $postid,
598
			'post_status' 	=> 'trash'
599
		);
600
601
		wp_update_post( apply_filters( 'lasso_object_deleted_args', $args ) );
602
603
		do_action( 'lasso_object_deleted', $postid, get_current_user_ID() );
604
605
		exit;
606
	}
607
    
608
    /* This function doesn't actually publish post, but should be called when a post is published */
609
    public function on_publish_post( ) {
610
611
		$post_id = isset( $_POST['postid'] ) ? $_POST['postid'] : false;
612
        
613
        do_action( 'transition_post_status', 'publish', 'draft', get_post( $post_id ) );
614
615
		exit;
616
	}
617
	
618
	public function set_featured_img( ) {
619
620
		$postid  	= isset( $_POST['postid'] ) ? $_POST['postid'] : false;
621
		$image_id  	= isset( $_POST['image_id'] ) ? absint( $_POST['image_id'] ) : false;
622
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_gallery' )) {
623
			wp_send_json_error();
624
			exit;
625
		}	
626
627
		set_post_thumbnail( $postid, $image_id );
628
629
		do_action( 'lasso_featured_image_set', $postid, $image_id, get_current_user_ID() );
630
631
		exit;
632
	}
633
	
634
	public function del_featured_img( ) {
635
636
		$postid  = isset( $_POST['postid'] ) ? $_POST['postid'] : false;
637
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_gallery' )) {
638
			wp_send_json_error();
639
			exit;
640
		}	
641
642
		delete_post_thumbnail( $postid );
643
644
		do_action( 'lasso_featured_image_deleted', $postid, get_current_user_ID() );
645
646
		exit;
647
	}
648
	
649
	/*public function revision_get( ) {
650
		$args = array();
651
		if ( isset( $_POST[ 'limit' ] ) ) {
652
			$args[ 'posts_per_page' ] = $data[ 'limit' ];
653
		}else{
654
			$args[ 'posts_per_page' ] = 6; // we start at revision 0
655
		}
656
657
		$revisions = wp_get_post_revisions( $_POST[ 'postid' ], $args  );
658
		if ( is_array( $revisions )  && ! empty( $revisions )  ) {
659
			self::set_revisions( $data[ 'postid' ], $revisions );
660
		}
661
662
		return self::$revisions;
663
	}*/
664
	
665
	public function set_post_terms( $postid, $value, $taxonomy ) {
666
		if( $value ) {
667
			$value = explode( ',', $value );
668
			$allow_new_category = lasso_editor_get_option( 'allow_new_category', 'lasso_editor' );
669
			
670
			if ($taxonomy =='category') {
671
                // convert from names to category ids
672
				$cats = array();
673
				foreach ($value as $cat) {
674
					$cat_id = get_cat_ID($cat);
675
					if ($cat_id !=0) {
676
						$cats [] = $cat_id;
677
					} else if ($allow_new_category) {
678
					    $cats [] = wp_create_category($cat);
679
					}
680
				}
681
				$value = $cats;
682
			}
683
	
684
			$result = wp_set_object_terms( $postid, $value, $taxonomy );
685
		}
686
		else  {
687
			//remove all terms from post
688
			$result = wp_set_object_terms( $postid, null, $taxonomy );
689
		}
690
691
		if ( ! is_wp_error( $result ) ) {
692
			return true;
693
		}else{
694
			return false;
695
		}
696
	}
697
    
698
    public function create_gallery( ) {
699
700
		$postid  	= isset( $_POST['postid'] ) ? $_POST['postid'] : false;
701
        
702
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_gallery' )) {
703
			wp_send_json_error();
704
			exit;
705
		}	
706
707
		if (  ! lasso_user_can( 'publish_posts' ) ) {
708
			return false;
709
710
		}
711
712
		$gallery_ids = isset( $_POST['gallery_ids'] ) ? $_POST['gallery_ids'] : false;
713
714
		// bail if no gallery ids
715
		if ( empty( $gallery_ids ) ) {
716
			return false;
717
		}
718
719
		$type   		 = isset( $_POST['gallery_type'] ) ? $_POST['gallery_type'] : false;
720
		$edgallerytitle	 = isset( $_POST['edgallerytitle'] ) ? $_POST['edgallerytitle'] : $postid.'-'.rand();
721
722
		// insert a new gallery
723
		$args = array(
724
			'post_title'    => $edgallerytitle ,
725
			'post_status'   => 'publish',
726
			'post_type'     => 'ai_galleries'
727
		);
728
729
		$postid = wp_insert_post( apply_filters( 'lasso_insert_gallery_args', $args ) );
730
731
		// update gallery ids
732
		if ( $gallery_ids ) {
733
734
			update_post_meta( $postid, '_ase_gallery_images', $gallery_ids );
735
736
		}
737
738
		// update the gallery type
739
		if ( !empty( $type ) ) {
740
741
			update_post_meta( $postid, 'aesop_gallery_type', $type );
742
743
		}
744
745
		do_action( 'lasso_gallery_published', $postid, $gallery_ids, get_current_user_ID() );
746
747
748
		echo json_encode( array(
749
			'message' => 'gallery-created',
750
			'id' => $postid)
751
		);
752
        exit;
753
	}
754
    
755 View Code Duplication
    public function update_gallery( ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
756
        
757
		$options      = isset( $_POST['fields'] ) ? $_POST['fields'] : false;
758
        
759
		$postid   	  = !empty( $options ) ? (int) $options['id'] : false;
760
		$gallery_ids  = isset( $_POST['gallery_ids'] ) ? $_POST['gallery_ids'] : false;
761
		if ( $_POST[ 'gallery_type' ] ) {
762
			$type = $_POST[ 'gallery_type' ];
763
		}elseif ( ! empty( $options ) && $options[ 'galleryType' ] ) {
764
			$type = $options[ 'galleryType' ];
765
		}else{
766
			$type = false;
767
		}
768
769
		self::save_gallery_options( $postid, $gallery_ids, $options, $type );
770
771
        echo json_encode( array('message' => 'gallery-updated') );
772
773
        exit;
774
	}
775
    
776 View Code Duplication
    public function save_gallery_options( $postid, $gallery_ids, $options, $type = false ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
777
778
		// gallery width
779
		$gallery_width = isset( $options['width'] ) ? $options['width'] : false;
780
781
		// gallery grid item width
782
		$item_width = isset( $options['itemwidth'] ) ? $options['itemwidth'] : false;
783
784
		// caption
785
		$caption = isset( $options['caption'] ) ? $options['caption'] : false;
786
787
		// gallery transition
788
		$transition = isset( $options['transition'] ) ? $options['transition'] : false;
789
790
		// gallery transition speed
791
		$transitionSpeed = isset( $options['speed'] ) ? $options['speed'] : false;
792
793
		// gallery hide thumbs
794
		$hideThumbs = isset( $options['hideThumbs'] ) ? $options['hideThumbs'] : false;
795
796
		// photoset layout hardwired to on for now
797
		$psLayout = isset( $options['pslayout'] ) ? $options['pslayout'] : false;
798
799
		// photoset layout
800
		$psLightbox = 'on';//isset( $options['pslightbox'] ) ? $options['pslightbox'] : false;
801
		
802
		// hero gallery height
803
		$gallery_height = isset( $options['height'] ) ? $options['height'] : false;
804
805
		// update gallery ids
806
		if ( !empty( $gallery_ids ) ) {
807
808
			update_post_meta( $postid, '_ase_gallery_images', $gallery_ids );
809
810
		}
811
812
		update_post_meta( $postid, 'aesop_gallery_type', sanitize_text_field( trim( $type ) ) );
813
814
		update_post_meta( $postid, 'aesop_gallery_width', sanitize_text_field( trim( $gallery_width ) ) );
815
816
		update_post_meta( $postid, 'aesop_grid_gallery_width', sanitize_text_field( trim( $item_width ) ) );
817
818
		update_post_meta( $postid, 'aesop_gallery_caption', sanitize_text_field( trim( $caption ) ) );
819
820
		update_post_meta( $postid, 'aesop_thumb_gallery_transition', sanitize_text_field( trim( $transition ) ) );
821
822
		update_post_meta( $postid, 'aesop_thumb_gallery_transition_speed', absint( trim( $transitionSpeed ) ) );
823
824
		update_post_meta( $postid, 'aesop_thumb_gallery_hide_thumbs', sanitize_text_field( trim( $hideThumbs ) ) );
825
826
		update_post_meta( $postid, 'aesop_photoset_gallery_layout', sanitize_text_field( trim( $psLayout ) ) );
827
828
		update_post_meta( $postid, 'aesop_photoset_gallery_lightbox', sanitize_text_field( trim( $psLightbox ) ) );
829
		
830
		update_post_meta( $postid, 'aesop_hero_gallery_height', sanitize_text_field( trim( $gallery_height ) ) );
831
		
832
		//hardwired for now
833
		
834
		update_post_meta( $postid, 'aesop_hero_gallery_transition_speed', 300 );
835
836
	}
837
	
838
	function getEnglishMonthName($foreignMonthName){
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
839
840
		  setlocale(LC_ALL, 'en_US');
841
842
		  $month_numbers = range(1,12);
843
844
		  foreach($month_numbers as $month)
845
			$english_months[] = strftime('%B',mktime(0,0,0,$month,1,2011));
0 ignored issues
show
Coding Style Comprehensibility introduced by
$english_months was never initialized. Although not strictly required by PHP, it is generally a good practice to add $english_months = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
846
847
		  setlocale(LC_ALL, get_locale());
848
849
		  foreach($month_numbers as $month)
850
			$foreign_months[] = utf8_encode(strftime('%B',mktime(0,0,0,$month,1,2011)));
0 ignored issues
show
Coding Style Comprehensibility introduced by
$foreign_months was never initialized. Although not strictly required by PHP, it is generally a good practice to add $foreign_months = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
851
852
		  return str_replace($foreign_months, $english_months, $foreignMonthName);
0 ignored issues
show
Bug introduced by
The variable $english_months does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $foreign_months does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
853
	}
854
855
856
	
857
	public function set_date( $postid, $value) {
858
		if( $value ) {
859
			$value = self::getEnglishMonthName($value)." ".date("H:i:s", current_time( 'timestamp', 1 ));
860
            wp_update_post(
861
				array (
862
					'ID'            => $postid, // ID of the post to update
863
					'post_date'     => date( 'Y-m-d H:i:s',  strtotime($value) ),
864
					'post_date_gmt'     => gmdate( 'Y-m-d H:i:s',  strtotime($value) ),
865
				)
866
			);
867
		}
868
	}
869
}
870