Completed
Push — master ( a8ef06...de0a9e )
by
unknown
02:00 queued 10s
created

lasso::save_gallery_options()   D

Complexity

Conditions 10
Paths 512

Size

Total Lines 61

Duplication

Lines 61
Ratio 100 %

Importance

Changes 0
Metric Value
cc 10
nc 512
nop 4
dl 61
loc 61
rs 4.1931
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_lock_post',     array( $this, 'editus_lock_post' ) );
63
		add_action( 'wp_ajax_editus_unlock_post',     array( $this, 'editus_unlock_post' ) );
64
		add_action( 'wp_ajax_editus_hide_tour',     array( $this, 'editus_hide_tour' ) );
65
		add_action( 'wp_ajax_editus_set_post_setting',     array( $this, 'editus_set_post_setting' ) );
66
		add_action( 'wp_ajax_editus_get_ase_options',     array( $this, 'get_ase_options' ) );
67
		add_action( 'wp_ajax_editus_delete_post',     array( $this, 'delete_post' ) );
68
		add_action( 'wp_ajax_editus_featured_img',     array( $this, 'set_featured_img' ) );
69
		add_action( 'wp_ajax_editus_del_featured_img',     array( $this, 'del_featured_img' ) );
70
        
71
        add_action( 'wp_ajax_editus_publish_post',     array( $this, 'on_publish_post' ) );
72
        
73
        add_action( 'wp_ajax_editus_create_gallery',     array( $this, 'create_gallery' ) );
74
        add_action( 'wp_ajax_editus_update_gallery',     array( $this, 'update_gallery' ) );
75
76
		// enable saving custom fields through REST API
77
		self::enable_metasave('post');
78
		self::enable_metasave('page');
79
		//enqueue assets
80
		new assets();
81
82
	}
83
84
	/**
85
	 * Return the plugin slug.
86
	 *
87
	 * @since    0.0.1
88
	 *
89
	 * @return    Plugin slug variable.
90
	 */
91
	public function get_plugin_slug() {
92
		return $this->plugin_slug;
93
	}
94
95
	/**
96
	 * Return an instance of this class.
97
	 *
98
	 * @since     0.0.1
99
	 *
100
	 * @return    object    A single instance of this class.
101
	 */
102
	public static function get_instance() {
103
104
		// If the single instance hasn't been set, set it now.
105
		if ( null == self::$instance ) {
106
			self::$instance = new self;
107
		}
108
109
		return self::$instance;
110
	}
111
112
	/**
113
	 * Fired when the plugin is activated.
114
	 *
115
	 * @since    0.0.1
116
	 *
117
	 * @param boolean $network_wide True if WPMU superadmin uses
118
	 *                                       "Network Activate" action, false if
119
	 *                                       WPMU is disabled or plugin is
120
	 *                                       activated on an individual blog.
121
	 */
122 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...
123
124
		if ( function_exists( 'is_multisite' ) && is_multisite() ) {
125
126
			if ( $network_wide  ) {
127
128
				// Get all blog ids
129
				$blog_ids = self::get_blog_ids();
130
131
				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...
132
133
					switch_to_blog( $blog_id );
134
					self::single_activate();
135
				}
136
137
				restore_current_blog();
138
139
			} else {
140
				self::single_activate();
141
			}
142
143
		} else {
144
			self::single_activate();
145
		}
146
147
	}
148
149
	/**
150
	 * Fired when the plugin is deactivated.
151
	 *
152
	 * @since    0.0.1
153
	 *
154
	 * @param boolean $network_wide True if WPMU superadmin uses
155
	 *                                       "Network Deactivate" action, false if
156
	 *                                       WPMU is disabled or plugin is
157
	 *                                       deactivated on an individual blog.
158
	 */
159 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...
160
161
		if ( function_exists( 'is_multisite' ) && is_multisite() ) {
162
163
			if ( $network_wide ) {
164
165
				// Get all blog ids
166
				$blog_ids = self::get_blog_ids();
167
168
				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...
169
170
					switch_to_blog( $blog_id );
171
					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...
172
173
				}
174
175
				restore_current_blog();
176
177
			} else {
178
				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...
179
			}
180
181
		} else {
182
			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...
183
		}
184
185
	}
186
187
	/**
188
	 * Fired when a new site is activated with a WPMU environment.
189
	 *
190
	 * @since    0.0.1
191
	 *
192
	 * @param int     $blog_id ID of the new blog.
193
	 */
194
	public function activate_new_site( $blog_id ) {
195
196
		if ( 1 !== did_action( 'wpmu_new_blog' ) ) {
197
			return;
198
		}
199
200
		switch_to_blog( $blog_id );
201
		self::single_activate();
202
		restore_current_blog();
203
204
	}
205
206
	/**
207
	 * Get all blog ids of blogs in the current network that are:
208
	 * - not archived
209
	 * - not spam
210
	 * - not deleted
211
	 *
212
	 * @since    0.0.1
213
	 *
214
	 * @return   array|false    The blog ids, false if no matches.
215
	 */
216
	private static function get_blog_ids() {
217
218
		global $wpdb;
219
220
		// get an array of blog ids
221
		$sql = "SELECT blog_id FROM $wpdb->blogs
222
			WHERE archived = '0' AND spam = '0'
223
			AND deleted = '0'";
224
225
		return $wpdb->get_col( $sql );
226
227
	}
228
229
	/**
230
	 * Fired for each blog when the plugin is activated.
231
	 *
232
	 * @since    0.0.1
233
	 */
234
	private static function single_activate() {
235
236
		$curr_version = get_option( 'lasso_version' );
237
238
		// update upgraded from
239
		if ( $curr_version ) {
240
			update_option( 'lasso_updated_from', $curr_version );
241
		}
242
243
		// update lasso version option
244
		update_option( 'lasso_version', LASSO_VERSION );
245
246
		// set transietn for activation welcome
247
		set_transient( '_lasso_welcome_redirect', true, 30 );
248
249
250
	}
251
252
	/**
253
	 * Fired for each blog when the plugin is deactivated.
254
	 *
255
	 * @since    0.0.1
256
	 */
257
	private static function single_deactivate() {
258
		// @TODO: Define deactivation functionality here
259
	}
260
261
	/**
262
	 * Load the plugin text domain for translation.
263
	 *
264
	 * @since    1.0.0
265
	 */
266
	public function load_plugin_textdomain() {
267
268
		$domain = $this->plugin_slug;
269
		$locale = apply_filters( 'plugin_locale', get_locale(), $domain );
270
271
		$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...
272
	}
273
	
274
    // new ajax function to lock post for editing
275
	public function editus_lock_post()
276
	{
277
		$post_id= $_POST["postid"];
278
		$locked = wp_check_post_lock($post_id);
279
		
280
		if (!$locked) {
281
		    wp_set_post_lock($post_id);
282
			echo "true";
283
		} else {
284
			$user_info = get_userdata($locked);
285
			echo _e( 'Post being edited by ', 'lasso' ).$user_info->first_name .  " " . $user_info->last_name;
286
		}
287
		exit;
288
	}
289
	
290
	public function editus_unlock_post()
291
	{
292
		$post_id= $_POST["postid"];
293
		$locked = wp_check_post_lock($post_id);
294
        if (!$locked) {
295
            delete_post_meta( $post_id, '_edit_lock');
296
        }
297
		echo "true";
298
		
299
		exit;
300
	}
301
	
302
	// new ajax function to update tour setting
303
	public function editus_hide_tour()
304
	{
305
		$user_id = get_current_user_ID();
306
				
307
		update_user_meta( $user_id, 'lasso_hide_tour', true );
308
		exit;
309
	}
310
	
311
	public function editus_set_post_setting()
312
	{
313
		
314
		
315
		$data = array();
316
		parse_str($_POST['data'], $data);
317
		
318
		if (!wp_verify_nonce( $data[ 'nonce' ], 'lasso-update-post-settings' )) {
319
			wp_send_json_error();
320
			exit;
321
		}
322
		
323
		$status = isset( $data['status'] ) ? $data['status'] : false;
324
		$postid = isset( $data['postid'] ) ? $data['postid'] : false;
325
		$slug   = isset( $data['story_slug'] ) ? $data['story_slug'] : false;
326
	
327
328
		$args = array(
329
			'ID'   			=> (int) $postid,
330
			'post_name'  	=> $slug,
331
			'post_status' 	=> $status
332
		);
333
		
334
		
335
336
		wp_update_post( apply_filters( 'lasso_object_status_update_args', $args ) );
337
		
338
		// update categories
339
		$cats  = isset( $data['story_cats'] ) ? $data['story_cats'] : false;
340
		
341
		self::set_post_terms( $postid, $cats, 'category' );
342
		
343
		// update tags
344
		$tags = isset( $data['story_tags'] ) ? $data['story_tags'] : false;
345
		self::set_post_terms( $postid, $tags, 'post_tag' );
346
		
347
		//update date
348
		$date  = isset( $data['post_date'] ) ? $data['post_date'] : false;
349
		self::set_date( $postid, $date );
350
		
351
		do_action( 'lasso_post_updated', $postid, $slug, $status, get_current_user_ID() );
352
		$response= array(
353
			'link'   => get_permalink($postid). (($status=='publish') ? '' : '&preview=true')
354
		);
355
		wp_send_json_success($response);
356
		exit;
357
	}
358
	
359
	public static function enable_metasave($type)
360
	{
361
		register_rest_field( $type, 'metadata', array(
362
			'get_callback' => function ( $data ) {
363
				return get_post_meta( $data['id']);//, '', '' );
364
			}, 
365
			'update_callback' => function( $data, $post ) {
366
				foreach ($data as $key => $value) {
367
					update_post_meta($post->ID, $key, $value);
368
				}
369
				return true;
370
			}
371
		));
372
	}
373
	
374
	public function editus_do_shortcode()
375
	{
376
		
377
		$code= $_POST["code"];
378
		$code = str_replace('\"', '"', $code);
379
		
380
		$code_wrapped = lasso_wrap_shortcodes( $code);
381
		$out =  do_shortcode($code);
382
		if ($out != '') {
383
			$out =  do_shortcode($code_wrapped);
384
			echo $out;
385
			exit;
386
		}
387
		
388
		// do_shortcode didn't work. Try again using wp_embed
389
390
		/** @var \WP_Embed $wp_embed */
391
		global $wp_embed;
392
		$wp_embed->post_ID = $_POST["ID"];
393
		$out =$wp_embed->run_shortcode( $code_wrapped );
394
		
395
		echo $out;
396
		exit;
397
	}
398
	
399
	public function get_aesop_component()
400
	{
401
		
402
		
403
		$code= $_POST["code"];
404
		$atts = array(
405
		 );
406
		foreach ($_POST as $key => $value) {
407
			if ($key !="code" && $key !="action") {
408
			    //$shortcode = $shortcode.$key.'="'.$value.'" ';
409
				$atts[$key] = $value;
410
			}
411
		}
412
		if ($code == "aesop_video") {
413
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-video.php');
414
		    echo aesop_video_shortcode($atts);
415
		}
416
		else if ($code == "aesop_image") {
417
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-image.php');
418
		    echo aesop_image_shortcode($atts);
419
		}
420
		else if ($code == "aesop_quote") {
421
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-quote.php');
422
		    echo aesop_quote_shortcode($atts);
423
		}
424
		else if ($code == "aesop_parallax") {
425
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-parallax.php');
426
		    echo aesop_parallax_shortcode($atts);
427
		}
428
		else if ($code == "aesop_character") {
429
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-character.php');
430
		    echo aesop_character_shortcode($atts);
431
		}
432
		else if ($code == "aesop_collection") {
433
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-collections.php');
434
		    echo aesop_collection_shortcode($atts);
435
		}
436
		else if ($code == "aesop_chapter") {
437
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-heading.php');
438
		    echo aesop_chapter_shortcode($atts);
439
		}
440
		else if ($code == "aesop_content") {
441
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-cbox.php');
442
		    echo aesop_content_shortcode($atts, $atts['content_data']);
443
		}
444
		else if ($code == "aesop_gallery") {
445
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-gallery.php');
446
		    echo do_shortcode( '[aesop_gallery id="'.$atts["id"].'"]');
447
		}
448
		else if ($code == "aesop_audio") {
449
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-audio.php');
450
		    echo aesop_audio_shortcode($atts);
451
		}
452
		else {
453
			$code = '['.$code.' ';
454
			foreach ($atts as $key => $value) {
455
			    $code = ''.$key.'="'.$value.'" ';
456
			}
457
			$code = $code.']';
458
			echo do_shortcode($code);
459
		    //require_once( ABSPATH . '/wp-content/plugins/aesop-events/public/includes/shortcode.php');
460
		    //echo aesop_audio_shortcode($atts);
461
		}
462
		
463
		exit; 
464
	}
465
	
466
	
467
	public function get_ase_options()
468
	{
469
		$blob = lasso_editor_options_blob();
470
		$code= $_POST["component"];
471
		echo $blob[$code];
472
		exit; 
473
	}
474
	
475
	public function delete_post( ) {
476
477
		$postid = isset( $_POST['postid'] ) ? $_POST['postid'] : false;
478
479
		// bail out if the current user can't publish posts
480
		if ( !lasso_user_can( 'delete_post', $postid ) )
481
			return;
482
		
483
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_delete_post' )) {
484
			wp_send_json_error();
485
			exit;
486
		}
487
488
		$args = array(
489
			'ID'   			=> (int) $postid,
490
			'post_status' 	=> 'trash'
491
		);
492
493
		wp_update_post( apply_filters( 'lasso_object_deleted_args', $args ) );
494
495
		do_action( 'lasso_object_deleted', $postid, get_current_user_ID() );
496
497
		exit;
498
	}
499
    
500
    /* This function doesn't actually publish post, but should be called when a post is published */
501
    public function on_publish_post( ) {
502
503
		$post_id = isset( $_POST['postid'] ) ? $_POST['postid'] : false;
504
        
505
        do_action( 'transition_post_status', 'publish', 'draft', get_post( $post_id ) );
506
507
		exit;
508
	}
509
	
510
	public function set_featured_img( ) {
511
512
		$postid  	= isset( $_POST['postid'] ) ? $_POST['postid'] : false;
513
		$image_id  	= isset( $_POST['image_id'] ) ? absint( $_POST['image_id'] ) : false;
514
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_gallery' )) {
515
			wp_send_json_error();
516
			exit;
517
		}	
518
519
		set_post_thumbnail( $postid, $image_id );
520
521
		do_action( 'lasso_featured_image_set', $postid, $image_id, get_current_user_ID() );
522
523
		exit;
524
	}
525
	
526
	public function del_featured_img( ) {
527
528
		$postid  = isset( $_POST['postid'] ) ? $_POST['postid'] : false;
529
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_gallery' )) {
530
			wp_send_json_error();
531
			exit;
532
		}	
533
534
		delete_post_thumbnail( $postid );
535
536
		do_action( 'lasso_featured_image_deleted', $postid, get_current_user_ID() );
537
538
		exit;
539
	}
540
	
541
	/*public function revision_get( ) {
542
		$args = array();
543
		if ( isset( $_POST[ 'limit' ] ) ) {
544
			$args[ 'posts_per_page' ] = $data[ 'limit' ];
545
		}else{
546
			$args[ 'posts_per_page' ] = 6; // we start at revision 0
547
		}
548
549
		$revisions = wp_get_post_revisions( $_POST[ 'postid' ], $args  );
550
		if ( is_array( $revisions )  && ! empty( $revisions )  ) {
551
			self::set_revisions( $data[ 'postid' ], $revisions );
552
		}
553
554
		return self::$revisions;
555
	}*/
556
	
557
	public function set_post_terms( $postid, $value, $taxonomy ) {
558
		if( $value ) {
559
			$value = explode( ',', $value );
560
			$allow_new_category = lasso_editor_get_option( 'allow_new_category', 'lasso_editor' );
561
			
562
			if ($taxonomy =='category') {
563
                // convert from names to category ids
564
				$cats = array();
565
				foreach ($value as $cat) {
566
					$cat_id = get_cat_ID($cat);
567
					if ($cat_id !=0) {
568
						$cats [] = $cat_id;
569
					} else if ($allow_new_category) {
570
					    $cats [] = wp_create_category($cat);
571
					}
572
				}
573
				$value = $cats;
574
			}
575
	
576
			$result = wp_set_object_terms( $postid, $value, $taxonomy );
577
		}
578
		else  {
579
			//remove all terms from post
580
			$result = wp_set_object_terms( $postid, null, $taxonomy );
581
		}
582
583
		if ( ! is_wp_error( $result ) ) {
584
			return true;
585
		}else{
586
			return false;
587
		}
588
	}
589
    
590
    public function create_gallery( ) {
591
592
		$postid  	= isset( $_POST['postid'] ) ? $_POST['postid'] : false;
593
        
594
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_gallery' )) {
595
			wp_send_json_error();
596
			exit;
597
		}	
598
599
		if (  ! lasso_user_can( 'publish_posts' ) ) {
600
			return false;
601
602
		}
603
604
		$gallery_ids = isset( $_POST['gallery_ids'] ) ? $_POST['gallery_ids'] : false;
605
606
		// bail if no gallery ids
607
		if ( empty( $gallery_ids ) ) {
608
			return false;
609
		}
610
611
		$type   		 = isset( $_POST['gallery_type'] ) ? $_POST['gallery_type'] : false;
612
		$edgallerytitle	 = isset( $_POST['edgallerytitle'] ) ? $_POST['edgallerytitle'] : $postid.'-'.rand();
613
614
		// insert a new gallery
615
		$args = array(
616
			'post_title'    => $edgallerytitle ,
617
			'post_status'   => 'publish',
618
			'post_type'     => 'ai_galleries'
619
		);
620
621
		$postid = wp_insert_post( apply_filters( 'lasso_insert_gallery_args', $args ) );
622
623
		// update gallery ids
624
		if ( $gallery_ids ) {
625
626
			update_post_meta( $postid, '_ase_gallery_images', $gallery_ids );
627
628
		}
629
630
		// update the gallery type
631
		if ( !empty( $type ) ) {
632
633
			update_post_meta( $postid, 'aesop_gallery_type', $type );
634
635
		}
636
637
		do_action( 'lasso_gallery_published', $postid, $gallery_ids, get_current_user_ID() );
638
639
640
		echo json_encode( array(
641
			'message' => 'gallery-created',
642
			'id' => $postid)
643
		);
644
        exit;
645
	}
646
    
647 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...
648
        
649
		$options      = isset( $_POST['fields'] ) ? $_POST['fields'] : false;
650
        
651
		$postid   	  = !empty( $options ) ? (int) $options['id'] : false;
652
		$gallery_ids  = isset( $_POST['gallery_ids'] ) ? $_POST['gallery_ids'] : false;
653
		if ( $_POST[ 'gallery_type' ] ) {
654
			$type = $_POST[ 'gallery_type' ];
655
		}elseif ( ! empty( $options ) && $options[ 'galleryType' ] ) {
656
			$type = $options[ 'galleryType' ];
657
		}else{
658
			$type = false;
659
		}
660
661
		self::save_gallery_options( $postid, $gallery_ids, $options, $type );
662
663
        echo json_encode( array('message' => 'gallery-updated') );
664
665
        exit;
666
	}
667
    
668 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...
669
670
		// gallery width
671
		$gallery_width = isset( $options['width'] ) ? $options['width'] : false;
672
673
		// gallery grid item width
674
		$item_width = isset( $options['itemwidth'] ) ? $options['itemwidth'] : false;
675
676
		// caption
677
		$caption = isset( $options['caption'] ) ? $options['caption'] : false;
678
679
		// gallery transition
680
		$transition = isset( $options['transition'] ) ? $options['transition'] : false;
681
682
		// gallery transition speed
683
		$transitionSpeed = isset( $options['speed'] ) ? $options['speed'] : false;
684
685
		// gallery hide thumbs
686
		$hideThumbs = isset( $options['hideThumbs'] ) ? $options['hideThumbs'] : false;
687
688
		// photoset layout hardwired to on for now
689
		$psLayout = isset( $options['pslayout'] ) ? $options['pslayout'] : false;
690
691
		// photoset layout
692
		$psLightbox = 'on';//isset( $options['pslightbox'] ) ? $options['pslightbox'] : false;
693
		
694
		// hero gallery height
695
		$gallery_height = isset( $options['height'] ) ? $options['height'] : false;
696
697
		// update gallery ids
698
		if ( !empty( $gallery_ids ) ) {
699
700
			update_post_meta( $postid, '_ase_gallery_images', $gallery_ids );
701
702
		}
703
704
		update_post_meta( $postid, 'aesop_gallery_type', sanitize_text_field( trim( $type ) ) );
705
706
		update_post_meta( $postid, 'aesop_gallery_width', sanitize_text_field( trim( $gallery_width ) ) );
707
708
		update_post_meta( $postid, 'aesop_grid_gallery_width', sanitize_text_field( trim( $item_width ) ) );
709
710
		update_post_meta( $postid, 'aesop_gallery_caption', sanitize_text_field( trim( $caption ) ) );
711
712
		update_post_meta( $postid, 'aesop_thumb_gallery_transition', sanitize_text_field( trim( $transition ) ) );
713
714
		update_post_meta( $postid, 'aesop_thumb_gallery_transition_speed', absint( trim( $transitionSpeed ) ) );
715
716
		update_post_meta( $postid, 'aesop_thumb_gallery_hide_thumbs', sanitize_text_field( trim( $hideThumbs ) ) );
717
718
		update_post_meta( $postid, 'aesop_photoset_gallery_layout', sanitize_text_field( trim( $psLayout ) ) );
719
720
		update_post_meta( $postid, 'aesop_photoset_gallery_lightbox', sanitize_text_field( trim( $psLightbox ) ) );
721
		
722
		update_post_meta( $postid, 'aesop_hero_gallery_height', sanitize_text_field( trim( $gallery_height ) ) );
723
		
724
		//hardwired for now
725
		
726
		update_post_meta( $postid, 'aesop_hero_gallery_transition_speed', 300 );
727
728
	}
729
	
730
	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...
731
732
		  setlocale(LC_ALL, 'en_US');
733
734
		  $month_numbers = range(1,12);
735
736
		  foreach($month_numbers as $month)
737
			$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...
738
739
		  setlocale(LC_ALL, get_locale());
740
741
		  foreach($month_numbers as $month)
742
			$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...
743
744
		  return str_replace($foreign_months, $english_months, $foreignMonthName);
0 ignored issues
show
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...
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...
745
	}
746
747
748
	
749
	public function set_date( $postid, $value) {
750
		if( $value ) {
751
			$value = self::getEnglishMonthName($value)." ".date("H:i:s", current_time( 'timestamp', 1 ));
752
            wp_update_post(
753
				array (
754
					'ID'            => $postid, // ID of the post to update
755
					'post_date'     => date( 'Y-m-d H:i:s',  strtotime($value) ),
756
					'post_date_gmt'     => gmdate( 'Y-m-d H:i:s',  strtotime($value) ),
757
				)
758
			);
759
		}
760
	}
761
}
762