Completed
Push — master ( 99c38a...8d9355 )
by
unknown
01:40
created

lasso::wpimg()   F

Complexity

Conditions 17
Paths 720

Size

Total Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
nc 720
nop 1
dl 0
loc 57
rs 1.4388
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * 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 {
477
			$code = '['.$code.' ';
478
			foreach ($atts as $key => $value) {
479
			    $code = ''.$key.'="'.$value.'" ';
480
			}
481
			$code = $code.']';
482
			echo do_shortcode($code);
483
		}
484
		echo '<p contenteditable="true"><br></p>';
485
		exit; 
486
	}
487
    
488
    public static function wpimg($atts) {
489
490
        echo '<figure data-component-type="wpimg"';
491
        
492
        $extra = "";
493
        
494
        // try to use srcset and sizes on new WP installs
495
		if ( function_exists('wp_get_attachment_image_srcset') && $attachment_id = attachment_url_to_postid( $atts['img'] ) ) {
496
			$srcset = wp_get_attachment_image_srcset( $attachment_id, 'full' );
497
			$sizes = wp_get_attachment_image_sizes( $attachment_id, 'full' );
498
            $extra = "srcset='$srcset' sizes='$sizes' ";
499
        }
500
        if ($atts['align']=="left") {
501
            $extra .= 'class="alignleft';
502
        } else if ($atts['align']=="right") {
503
            $extra .= 'class="alignright';
504
        } else {
505
            $extra .= 'class="aligncenter';
506
        }
507
        if ($atts['imgwidth'] || $atts['imgheight']) {
508
            if ($atts['imgwidth']) {
509
                $extra .= 'width:'. $atts['imgwidth'].';';
510
            }
511
            if ($atts['imgheight']) {
512
                $extra .= 'height:'. $atts['imgheight'].';';
513
            }
514
            
515
        }
516
        $extra .= '"';
517
        
518
        foreach ($atts as $key => $value) {
519
			 echo ' data-'.$key.'="'.$value.'"';
520
		}
521
        //echo ' class="wp-image- lasso--wpimg__wrap lasso-component">';
522
        echo ' class="wp-caption lasso-component">';
523
        $hrefset = false;
524
        if ($atts['link'] != '' && (!isset($atts['linkoption']) || $atts['linkoption']=="url" ))
525
        {
526
            echo '<a href="' . $atts['link'] . '">';
527
            $hrefset = true;
528
        } else if (isset($atts['linkoption']) && $atts['linkoption'] == 'img' ) {
529
            echo '<a href="' . $atts['img'] . '">';
530
            $hrefset = true;
531
        }
532
        echo '<img src="' . $atts['img'] . '" alt="'. $atts['alt']  .  '" '. $extra. '>';
533
        if ($hrefset)
534
        {
535
            echo '</a>';
536
        }
537
        if ($atts['caption'])
538
        {
539
            echo '<figcaption class="wp-caption-text">'.$atts['caption'].'</figcaption>';
540
        }
541
        echo '</figure>';
542
        echo '<p> </p>';
543
        return;
544
    }
545
	
546
	
547
	public function get_ase_options()
548
	{
549
		$blob = lasso_editor_options_blob();
550
		$code= $_POST["component"];
551
		echo $blob[$code];
552
		exit; 
553
	}
554
	
555
	public function delete_post( ) {
556
557
		$postid = isset( $_POST['postid'] ) ? $_POST['postid'] : false;
558
559
		// bail out if the current user can't publish posts
560
		if ( !lasso_user_can( 'delete_post', $postid ) )
561
			return;
562
		
563
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_delete_post' )) {
564
			wp_send_json_error();
565
			exit;
566
		}
567
568
		$args = array(
569
			'ID'   			=> (int) $postid,
570
			'post_status' 	=> 'trash'
571
		);
572
573
		wp_update_post( apply_filters( 'lasso_object_deleted_args', $args ) );
574
575
		do_action( 'lasso_object_deleted', $postid, get_current_user_ID() );
576
577
		exit;
578
	}
579
    
580
    /* This function doesn't actually publish post, but should be called when a post is published */
581
    public function on_publish_post( ) {
582
583
		$post_id = isset( $_POST['postid'] ) ? $_POST['postid'] : false;
584
        
585
        do_action( 'transition_post_status', 'publish', 'draft', get_post( $post_id ) );
586
587
		exit;
588
	}
589
	
590
	public function set_featured_img( ) {
591
592
		$postid  	= isset( $_POST['postid'] ) ? $_POST['postid'] : false;
593
		$image_id  	= isset( $_POST['image_id'] ) ? absint( $_POST['image_id'] ) : false;
594
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_gallery' )) {
595
			wp_send_json_error();
596
			exit;
597
		}	
598
599
		set_post_thumbnail( $postid, $image_id );
600
601
		do_action( 'lasso_featured_image_set', $postid, $image_id, get_current_user_ID() );
602
603
		exit;
604
	}
605
	
606
	public function del_featured_img( ) {
607
608
		$postid  = isset( $_POST['postid'] ) ? $_POST['postid'] : false;
609
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_gallery' )) {
610
			wp_send_json_error();
611
			exit;
612
		}	
613
614
		delete_post_thumbnail( $postid );
615
616
		do_action( 'lasso_featured_image_deleted', $postid, get_current_user_ID() );
617
618
		exit;
619
	}
620
	
621
	/*public function revision_get( ) {
622
		$args = array();
623
		if ( isset( $_POST[ 'limit' ] ) ) {
624
			$args[ 'posts_per_page' ] = $data[ 'limit' ];
625
		}else{
626
			$args[ 'posts_per_page' ] = 6; // we start at revision 0
627
		}
628
629
		$revisions = wp_get_post_revisions( $_POST[ 'postid' ], $args  );
630
		if ( is_array( $revisions )  && ! empty( $revisions )  ) {
631
			self::set_revisions( $data[ 'postid' ], $revisions );
632
		}
633
634
		return self::$revisions;
635
	}*/
636
	
637
	public function set_post_terms( $postid, $value, $taxonomy ) {
638
		if( $value ) {
639
			$value = explode( ',', $value );
640
			$allow_new_category = lasso_editor_get_option( 'allow_new_category', 'lasso_editor' );
641
			
642
			if ($taxonomy =='category') {
643
                // convert from names to category ids
644
				$cats = array();
645
				foreach ($value as $cat) {
646
					$cat_id = get_cat_ID($cat);
647
					if ($cat_id !=0) {
648
						$cats [] = $cat_id;
649
					} else if ($allow_new_category) {
650
					    $cats [] = wp_create_category($cat);
651
					}
652
				}
653
				$value = $cats;
654
			}
655
	
656
			$result = wp_set_object_terms( $postid, $value, $taxonomy );
657
		}
658
		else  {
659
			//remove all terms from post
660
			$result = wp_set_object_terms( $postid, null, $taxonomy );
661
		}
662
663
		if ( ! is_wp_error( $result ) ) {
664
			return true;
665
		}else{
666
			return false;
667
		}
668
	}
669
    
670
    public function create_gallery( ) {
671
672
		$postid  	= isset( $_POST['postid'] ) ? $_POST['postid'] : false;
673
        
674
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_gallery' )) {
675
			wp_send_json_error();
676
			exit;
677
		}	
678
679
		if (  ! lasso_user_can( 'publish_posts' ) ) {
680
			return false;
681
682
		}
683
684
		$gallery_ids = isset( $_POST['gallery_ids'] ) ? $_POST['gallery_ids'] : false;
685
686
		// bail if no gallery ids
687
		if ( empty( $gallery_ids ) ) {
688
			return false;
689
		}
690
691
		$type   		 = isset( $_POST['gallery_type'] ) ? $_POST['gallery_type'] : false;
692
		$edgallerytitle	 = isset( $_POST['edgallerytitle'] ) ? $_POST['edgallerytitle'] : $postid.'-'.rand();
693
694
		// insert a new gallery
695
		$args = array(
696
			'post_title'    => $edgallerytitle ,
697
			'post_status'   => 'publish',
698
			'post_type'     => 'ai_galleries'
699
		);
700
701
		$postid = wp_insert_post( apply_filters( 'lasso_insert_gallery_args', $args ) );
702
703
		// update gallery ids
704
		if ( $gallery_ids ) {
705
706
			update_post_meta( $postid, '_ase_gallery_images', $gallery_ids );
707
708
		}
709
710
		// update the gallery type
711
		if ( !empty( $type ) ) {
712
713
			update_post_meta( $postid, 'aesop_gallery_type', $type );
714
715
		}
716
717
		do_action( 'lasso_gallery_published', $postid, $gallery_ids, get_current_user_ID() );
718
719
720
		echo json_encode( array(
721
			'message' => 'gallery-created',
722
			'id' => $postid)
723
		);
724
        exit;
725
	}
726
    
727 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...
728
        
729
		$options      = isset( $_POST['fields'] ) ? $_POST['fields'] : false;
730
        
731
		$postid   	  = !empty( $options ) ? (int) $options['id'] : false;
732
		$gallery_ids  = isset( $_POST['gallery_ids'] ) ? $_POST['gallery_ids'] : false;
733
		if ( $_POST[ 'gallery_type' ] ) {
734
			$type = $_POST[ 'gallery_type' ];
735
		}elseif ( ! empty( $options ) && $options[ 'galleryType' ] ) {
736
			$type = $options[ 'galleryType' ];
737
		}else{
738
			$type = false;
739
		}
740
741
		self::save_gallery_options( $postid, $gallery_ids, $options, $type );
742
743
        echo json_encode( array('message' => 'gallery-updated') );
744
745
        exit;
746
	}
747
    
748 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...
749
750
		// gallery width
751
		$gallery_width = isset( $options['width'] ) ? $options['width'] : false;
752
753
		// gallery grid item width
754
		$item_width = isset( $options['itemwidth'] ) ? $options['itemwidth'] : false;
755
756
		// caption
757
		$caption = isset( $options['caption'] ) ? $options['caption'] : false;
758
759
		// gallery transition
760
		$transition = isset( $options['transition'] ) ? $options['transition'] : false;
761
762
		// gallery transition speed
763
		$transitionSpeed = isset( $options['speed'] ) ? $options['speed'] : false;
764
765
		// gallery hide thumbs
766
		$hideThumbs = isset( $options['hideThumbs'] ) ? $options['hideThumbs'] : false;
767
768
		// photoset layout hardwired to on for now
769
		$psLayout = isset( $options['pslayout'] ) ? $options['pslayout'] : false;
770
771
		// photoset layout
772
		$psLightbox = 'on';//isset( $options['pslightbox'] ) ? $options['pslightbox'] : false;
773
		
774
		// hero gallery height
775
		$gallery_height = isset( $options['height'] ) ? $options['height'] : false;
776
777
		// update gallery ids
778
		if ( !empty( $gallery_ids ) ) {
779
780
			update_post_meta( $postid, '_ase_gallery_images', $gallery_ids );
781
782
		}
783
784
		update_post_meta( $postid, 'aesop_gallery_type', sanitize_text_field( trim( $type ) ) );
785
786
		update_post_meta( $postid, 'aesop_gallery_width', sanitize_text_field( trim( $gallery_width ) ) );
787
788
		update_post_meta( $postid, 'aesop_grid_gallery_width', sanitize_text_field( trim( $item_width ) ) );
789
790
		update_post_meta( $postid, 'aesop_gallery_caption', sanitize_text_field( trim( $caption ) ) );
791
792
		update_post_meta( $postid, 'aesop_thumb_gallery_transition', sanitize_text_field( trim( $transition ) ) );
793
794
		update_post_meta( $postid, 'aesop_thumb_gallery_transition_speed', absint( trim( $transitionSpeed ) ) );
795
796
		update_post_meta( $postid, 'aesop_thumb_gallery_hide_thumbs', sanitize_text_field( trim( $hideThumbs ) ) );
797
798
		update_post_meta( $postid, 'aesop_photoset_gallery_layout', sanitize_text_field( trim( $psLayout ) ) );
799
800
		update_post_meta( $postid, 'aesop_photoset_gallery_lightbox', sanitize_text_field( trim( $psLightbox ) ) );
801
		
802
		update_post_meta( $postid, 'aesop_hero_gallery_height', sanitize_text_field( trim( $gallery_height ) ) );
803
		
804
		//hardwired for now
805
		
806
		update_post_meta( $postid, 'aesop_hero_gallery_transition_speed', 300 );
807
808
	}
809
	
810
	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...
811
812
		  setlocale(LC_ALL, 'en_US');
813
814
		  $month_numbers = range(1,12);
815
816
		  foreach($month_numbers as $month)
817
			$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...
818
819
		  setlocale(LC_ALL, get_locale());
820
821
		  foreach($month_numbers as $month)
822
			$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...
823
824
		  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...
825
	}
826
827
828
	
829
	public function set_date( $postid, $value) {
830
		if( $value ) {
831
			$value = self::getEnglishMonthName($value)." ".date("H:i:s", current_time( 'timestamp', 1 ));
832
            wp_update_post(
833
				array (
834
					'ID'            => $postid, // ID of the post to update
835
					'post_date'     => date( 'Y-m-d H:i:s',  strtotime($value) ),
836
					'post_date_gmt'     => gmdate( 'Y-m-d H:i:s',  strtotime($value) ),
837
				)
838
			);
839
		}
840
	}
841
}
842