Completed
Push — master ( 019e58...ee1edc )
by
unknown
01:39
created

lasso::wpimg()   C

Complexity

Conditions 11
Paths 160

Size

Total Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
nc 160
nop 1
dl 0
loc 46
rs 6.8166
c 0
b 0
f 0

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