Completed
Push — master ( 605b3f...454469 )
by
unknown
01:28
created

lasso::editus_do_block()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 10
rs 9.9332
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
	
328
329
		$args = array(
330
			'ID'   			=> (int) $postid,
331
			'post_name'  	=> $slug,
332
			'post_status' 	=> $status
333
		);
334
		
335
		
336
337
		wp_update_post( apply_filters( 'lasso_object_status_update_args', $args ) );
338
		
339
		// update categories
340
		$cats  = isset( $data['story_cats'] ) ? $data['story_cats'] : false;
341
		
342
		self::set_post_terms( $postid, $cats, 'category' );
343
		
344
		// update tags
345
		$tags = isset( $data['story_tags'] ) ? $data['story_tags'] : false;
346
		self::set_post_terms( $postid, $tags, 'post_tag' );
347
		
348
		//update date
349
		$date  = isset( $data['post_date'] ) ? $data['post_date'] : false;
350
		self::set_date( $postid, $date );
351
		
352
		do_action( 'lasso_post_updated', $postid, $slug, $status, get_current_user_ID() );
353
		$response= array(
354
			'link'   => get_permalink($postid). (($status=='publish') ? '' : '&preview=true')
355
		);
356
		wp_send_json_success($response);
357
		exit;
358
	}
359
	
360
	public static function enable_metasave($type)
361
	{
362
		register_rest_field( $type, 'metadata', array(
363
			'get_callback' => function ( $data ) {
364
				return get_post_meta( $data['id']);//, '', '' );
365
			}, 
366
			'update_callback' => function( $data, $post ) {
367
				foreach ($data as $key => $value) {
368
					update_post_meta($post->ID, $key, $value);
369
				}
370
				return true;
371
			}
372
		));
373
	}
374
	
375
	public function editus_do_shortcode()
376
	{
377
		
378
		$code= $_POST["code"];
379
		$code = str_replace('\"', '"', $code);
380
		
381
		$code_wrapped = lasso_wrap_shortcodes( $code);
382
		$out =  do_shortcode($code);
383
		if ($out != '') {
384
			$out =  do_shortcode($code_wrapped);
385
			echo $out;
386
			exit;
387
		}
388
		
389
		// do_shortcode didn't work. Try again using wp_embed
390
391
		/** @var \WP_Embed $wp_embed */
392
		global $wp_embed;
393
		$wp_embed->post_ID = $_POST["ID"];
394
		$out =$wp_embed->run_shortcode( $code_wrapped );
395
		
396
		echo $out;
397
		exit;
398
	}
399
    
400
    public function editus_do_block()
401
	{
402
		
403
		$code= $_POST["code"];
404
405
        $out = do_blocks( $code );
406
		
407
		echo $out;
408
		exit;
409
	}
410
	
411
	public function get_aesop_component()
412
	{
413
		
414
		
415
		$code= $_POST["code"];
416
		$atts = array(
417
		 );
418
		foreach ($_POST as $key => $value) {
419
			if ($key !="code" && $key !="action") {
420
			    //$shortcode = $shortcode.$key.'="'.$value.'" ';
421
				$atts[$key] = $value;
422
			}
423
		}
424
		if ($code == "aesop_video") {
425
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-video.php');
426
		    echo aesop_video_shortcode($atts);
427
		}
428
		else if ($code == "aesop_image") {
429
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-image.php');
430
		    echo aesop_image_shortcode($atts);
431
		}
432
		else if ($code == "aesop_quote") {
433
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-quote.php');
434
		    echo aesop_quote_shortcode($atts);
435
		}
436
		else if ($code == "aesop_parallax") {
437
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-parallax.php');
438
		    echo aesop_parallax_shortcode($atts);
439
		}
440
		else if ($code == "aesop_character") {
441
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-character.php');
442
		    echo aesop_character_shortcode($atts);
443
		}
444
		else if ($code == "aesop_collection") {
445
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-collections.php');
446
		    echo aesop_collection_shortcode($atts);
447
		}
448
		else if ($code == "aesop_chapter") {
449
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-heading.php');
450
		    echo aesop_chapter_shortcode($atts);
451
		}
452
		else if ($code == "aesop_content") {
453
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-cbox.php');
454
		    echo aesop_content_shortcode($atts, $atts['content_data']);
455
		}
456
		else if ($code == "aesop_gallery") {
457
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-gallery.php');
458
		    echo do_shortcode( '[aesop_gallery id="'.$atts["id"].'"]');
459
		}
460
		else if ($code == "aesop_audio") {
461
		    require_once( ABSPATH . '/wp-content/plugins/aesop-story-engine/public/includes/components/component-audio.php');
462
		    echo aesop_audio_shortcode($atts);
463
		}
464
		else {
465
			$code = '['.$code.' ';
466
			foreach ($atts as $key => $value) {
467
			    $code = ''.$key.'="'.$value.'" ';
468
			}
469
			$code = $code.']';
470
			echo do_shortcode($code);
471
		    //require_once( ABSPATH . '/wp-content/plugins/aesop-events/public/includes/shortcode.php');
472
		    //echo aesop_audio_shortcode($atts);
473
		}
474
		
475
		exit; 
476
	}
477
	
478
	
479
	public function get_ase_options()
480
	{
481
		$blob = lasso_editor_options_blob();
482
		$code= $_POST["component"];
483
		echo $blob[$code];
484
		exit; 
485
	}
486
	
487
	public function delete_post( ) {
488
489
		$postid = isset( $_POST['postid'] ) ? $_POST['postid'] : false;
490
491
		// bail out if the current user can't publish posts
492
		if ( !lasso_user_can( 'delete_post', $postid ) )
493
			return;
494
		
495
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_delete_post' )) {
496
			wp_send_json_error();
497
			exit;
498
		}
499
500
		$args = array(
501
			'ID'   			=> (int) $postid,
502
			'post_status' 	=> 'trash'
503
		);
504
505
		wp_update_post( apply_filters( 'lasso_object_deleted_args', $args ) );
506
507
		do_action( 'lasso_object_deleted', $postid, get_current_user_ID() );
508
509
		exit;
510
	}
511
    
512
    /* This function doesn't actually publish post, but should be called when a post is published */
513
    public function on_publish_post( ) {
514
515
		$post_id = isset( $_POST['postid'] ) ? $_POST['postid'] : false;
516
        
517
        do_action( 'transition_post_status', 'publish', 'draft', get_post( $post_id ) );
518
519
		exit;
520
	}
521
	
522
	public function set_featured_img( ) {
523
524
		$postid  	= isset( $_POST['postid'] ) ? $_POST['postid'] : false;
525
		$image_id  	= isset( $_POST['image_id'] ) ? absint( $_POST['image_id'] ) : false;
526
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_gallery' )) {
527
			wp_send_json_error();
528
			exit;
529
		}	
530
531
		set_post_thumbnail( $postid, $image_id );
532
533
		do_action( 'lasso_featured_image_set', $postid, $image_id, get_current_user_ID() );
534
535
		exit;
536
	}
537
	
538
	public function del_featured_img( ) {
539
540
		$postid  = isset( $_POST['postid'] ) ? $_POST['postid'] : false;
541
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_gallery' )) {
542
			wp_send_json_error();
543
			exit;
544
		}	
545
546
		delete_post_thumbnail( $postid );
547
548
		do_action( 'lasso_featured_image_deleted', $postid, get_current_user_ID() );
549
550
		exit;
551
	}
552
	
553
	/*public function revision_get( ) {
554
		$args = array();
555
		if ( isset( $_POST[ 'limit' ] ) ) {
556
			$args[ 'posts_per_page' ] = $data[ 'limit' ];
557
		}else{
558
			$args[ 'posts_per_page' ] = 6; // we start at revision 0
559
		}
560
561
		$revisions = wp_get_post_revisions( $_POST[ 'postid' ], $args  );
562
		if ( is_array( $revisions )  && ! empty( $revisions )  ) {
563
			self::set_revisions( $data[ 'postid' ], $revisions );
564
		}
565
566
		return self::$revisions;
567
	}*/
568
	
569
	public function set_post_terms( $postid, $value, $taxonomy ) {
570
		if( $value ) {
571
			$value = explode( ',', $value );
572
			$allow_new_category = lasso_editor_get_option( 'allow_new_category', 'lasso_editor' );
573
			
574
			if ($taxonomy =='category') {
575
                // convert from names to category ids
576
				$cats = array();
577
				foreach ($value as $cat) {
578
					$cat_id = get_cat_ID($cat);
579
					if ($cat_id !=0) {
580
						$cats [] = $cat_id;
581
					} else if ($allow_new_category) {
582
					    $cats [] = wp_create_category($cat);
583
					}
584
				}
585
				$value = $cats;
586
			}
587
	
588
			$result = wp_set_object_terms( $postid, $value, $taxonomy );
589
		}
590
		else  {
591
			//remove all terms from post
592
			$result = wp_set_object_terms( $postid, null, $taxonomy );
593
		}
594
595
		if ( ! is_wp_error( $result ) ) {
596
			return true;
597
		}else{
598
			return false;
599
		}
600
	}
601
    
602
    public function create_gallery( ) {
603
604
		$postid  	= isset( $_POST['postid'] ) ? $_POST['postid'] : false;
605
        
606
		if (!wp_verify_nonce( $_POST[ 'nonce' ], 'lasso_gallery' )) {
607
			wp_send_json_error();
608
			exit;
609
		}	
610
611
		if (  ! lasso_user_can( 'publish_posts' ) ) {
612
			return false;
613
614
		}
615
616
		$gallery_ids = isset( $_POST['gallery_ids'] ) ? $_POST['gallery_ids'] : false;
617
618
		// bail if no gallery ids
619
		if ( empty( $gallery_ids ) ) {
620
			return false;
621
		}
622
623
		$type   		 = isset( $_POST['gallery_type'] ) ? $_POST['gallery_type'] : false;
624
		$edgallerytitle	 = isset( $_POST['edgallerytitle'] ) ? $_POST['edgallerytitle'] : $postid.'-'.rand();
625
626
		// insert a new gallery
627
		$args = array(
628
			'post_title'    => $edgallerytitle ,
629
			'post_status'   => 'publish',
630
			'post_type'     => 'ai_galleries'
631
		);
632
633
		$postid = wp_insert_post( apply_filters( 'lasso_insert_gallery_args', $args ) );
634
635
		// update gallery ids
636
		if ( $gallery_ids ) {
637
638
			update_post_meta( $postid, '_ase_gallery_images', $gallery_ids );
639
640
		}
641
642
		// update the gallery type
643
		if ( !empty( $type ) ) {
644
645
			update_post_meta( $postid, 'aesop_gallery_type', $type );
646
647
		}
648
649
		do_action( 'lasso_gallery_published', $postid, $gallery_ids, get_current_user_ID() );
650
651
652
		echo json_encode( array(
653
			'message' => 'gallery-created',
654
			'id' => $postid)
655
		);
656
        exit;
657
	}
658
    
659 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...
660
        
661
		$options      = isset( $_POST['fields'] ) ? $_POST['fields'] : false;
662
        
663
		$postid   	  = !empty( $options ) ? (int) $options['id'] : false;
664
		$gallery_ids  = isset( $_POST['gallery_ids'] ) ? $_POST['gallery_ids'] : false;
665
		if ( $_POST[ 'gallery_type' ] ) {
666
			$type = $_POST[ 'gallery_type' ];
667
		}elseif ( ! empty( $options ) && $options[ 'galleryType' ] ) {
668
			$type = $options[ 'galleryType' ];
669
		}else{
670
			$type = false;
671
		}
672
673
		self::save_gallery_options( $postid, $gallery_ids, $options, $type );
674
675
        echo json_encode( array('message' => 'gallery-updated') );
676
677
        exit;
678
	}
679
    
680 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...
681
682
		// gallery width
683
		$gallery_width = isset( $options['width'] ) ? $options['width'] : false;
684
685
		// gallery grid item width
686
		$item_width = isset( $options['itemwidth'] ) ? $options['itemwidth'] : false;
687
688
		// caption
689
		$caption = isset( $options['caption'] ) ? $options['caption'] : false;
690
691
		// gallery transition
692
		$transition = isset( $options['transition'] ) ? $options['transition'] : false;
693
694
		// gallery transition speed
695
		$transitionSpeed = isset( $options['speed'] ) ? $options['speed'] : false;
696
697
		// gallery hide thumbs
698
		$hideThumbs = isset( $options['hideThumbs'] ) ? $options['hideThumbs'] : false;
699
700
		// photoset layout hardwired to on for now
701
		$psLayout = isset( $options['pslayout'] ) ? $options['pslayout'] : false;
702
703
		// photoset layout
704
		$psLightbox = 'on';//isset( $options['pslightbox'] ) ? $options['pslightbox'] : false;
705
		
706
		// hero gallery height
707
		$gallery_height = isset( $options['height'] ) ? $options['height'] : false;
708
709
		// update gallery ids
710
		if ( !empty( $gallery_ids ) ) {
711
712
			update_post_meta( $postid, '_ase_gallery_images', $gallery_ids );
713
714
		}
715
716
		update_post_meta( $postid, 'aesop_gallery_type', sanitize_text_field( trim( $type ) ) );
717
718
		update_post_meta( $postid, 'aesop_gallery_width', sanitize_text_field( trim( $gallery_width ) ) );
719
720
		update_post_meta( $postid, 'aesop_grid_gallery_width', sanitize_text_field( trim( $item_width ) ) );
721
722
		update_post_meta( $postid, 'aesop_gallery_caption', sanitize_text_field( trim( $caption ) ) );
723
724
		update_post_meta( $postid, 'aesop_thumb_gallery_transition', sanitize_text_field( trim( $transition ) ) );
725
726
		update_post_meta( $postid, 'aesop_thumb_gallery_transition_speed', absint( trim( $transitionSpeed ) ) );
727
728
		update_post_meta( $postid, 'aesop_thumb_gallery_hide_thumbs', sanitize_text_field( trim( $hideThumbs ) ) );
729
730
		update_post_meta( $postid, 'aesop_photoset_gallery_layout', sanitize_text_field( trim( $psLayout ) ) );
731
732
		update_post_meta( $postid, 'aesop_photoset_gallery_lightbox', sanitize_text_field( trim( $psLightbox ) ) );
733
		
734
		update_post_meta( $postid, 'aesop_hero_gallery_height', sanitize_text_field( trim( $gallery_height ) ) );
735
		
736
		//hardwired for now
737
		
738
		update_post_meta( $postid, 'aesop_hero_gallery_transition_speed', 300 );
739
740
	}
741
	
742
	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...
743
744
		  setlocale(LC_ALL, 'en_US');
745
746
		  $month_numbers = range(1,12);
747
748
		  foreach($month_numbers as $month)
749
			$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...
750
751
		  setlocale(LC_ALL, get_locale());
752
753
		  foreach($month_numbers as $month)
754
			$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...
755
756
		  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...
757
	}
758
759
760
	
761
	public function set_date( $postid, $value) {
762
		if( $value ) {
763
			$value = self::getEnglishMonthName($value)." ".date("H:i:s", current_time( 'timestamp', 1 ));
764
            wp_update_post(
765
				array (
766
					'ID'            => $postid, // ID of the post to update
767
					'post_date'     => date( 'Y-m-d H:i:s',  strtotime($value) ),
768
					'post_date_gmt'     => gmdate( 'Y-m-d H:i:s',  strtotime($value) ),
769
				)
770
			);
771
		}
772
	}
773
}
774