Passed
Push — master ( 4e63e0...484f95 )
by Warwick
02:58
created

WETU_Importer::load_class()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.0534
c 0
b 0
f 0
cc 4
eloc 14
nc 4
nop 0
1
<?php
2
/**
3
 * @package   WETU_Importer
4
 * @author    LightSpeed
5
 * @license   GPL-2.0+
6
 * @link      
7
 * @copyright 2016 LightSpeed
8
 **/
9
10
class WETU_Importer {
11
	
12
	/**
13
	 * Holds class instance
14
	 *
15
	 * @since 1.0.0
16
	 *
17
	 * @var      object|Module_Template
18
	 */
19
	protected static $instance = null;
20
21
	/**
22
	 * The slug for this plugin
23
	 *
24
	 * @since 0.0.1
25
	 *
26
	 * @var      string
27
	 */
28
	public $plugin_slug = 'wetu-importer';
29
30
	/**
31
	 * The url to list items from WETU
32
	 *
33
	 * @since 0.0.1
34
	 *
35
	 * @var      string
36
	 */
37
	public $tab_slug = 'default';
38
39
	/**
40
	 * The options for the plugin
41
	 *
42
	 * @since 0.0.1
43
	 *
44
	 * @var      string
45
	 */
46
	public $options = false;
47
48
	/**
49
	 * The url to import images from WETU
50
	 *
51
	 * @since 0.0.1
52
	 *
53
	 * @var      string
54
	 */
55
	public $import_scaling_url = false;		
56
57
	/**
58
	 * scale the images on import or not
59
	 *
60
	 * @since 0.0.1
61
	 *
62
	 * @var      boolean
63
	 */
64
	public $scale_images = false;
65
66
	/**
67
	 * The WETU API Key
68
	 */
69
	public $api_key = false;
70
71
	/**
72
	 * The WETU API Username
73
	 */
74
	public $api_username = false;
75
76
	/**
77
	 * The WETU API Password
78
	 */
79
	public $api_password = false;
80
81
	/**
82
	 * The post types this works with.
83
	 */
84
	public $post_types = array();
85
86
	/**
87
	 * The previously attached images
88
	 *
89
	 * @var      array()
90
	 */
91
	public $found_attachments = array();
92
93
	/**
94
	 * The gallery ids for the found attachements
95
	 *
96
	 * @var      array()
97
	 */
98
	public $gallery_meta = array();
99
100
	/**
101
	 * The post ids to clean up (make sure the connected items are only singular)
102
	 *
103
	 * @var      array()
104
	 */
105
	public $cleanup_posts = array();
106
107
	/**
108
	 * A post => parent relationship array.
109
	 *
110
	 * @var      array()
111
	 */
112
	public $relation_meta = array();
113
114
	/**
115
	 * the featured image id
116
	 *
117
	 * @var      int
118
	 */
119
	public $featured_image = false;
120
121
	/**
122
	 * the banner image
123
	 *
124
	 * @var      int
125
	 */
126
	public $banner_image = false;
127
128
	/**
129
	 * Holds the current import to display
130
	 *
131
	 * @var      int
132
	 */
133
	public $current_importer = false;
134
135
	/**
136
	 * if you ran a tour import then you will have accommodation and destination queued to sync as well.
137
	 *
138
	 * @var      int
139
	 */
140
	public $queued_imports = array();
141
142
	/**
143
	 * An Array to hold the items to queue
144
	 *
145
	 * @var      int
146
	 */
147
	public $import_queue = array();
148
149
	/**
150
	 * Holds the current post that is being imported. Use to check the content and excerpt.
151
	 *
152
	 * @var      int
153
	 */
154
	public $current_post = false;
155
156
	/**
157
	 * Initialize the plugin by setting localization, filters, and administration functions.
158
	 *
159
	 * @since 1.0.0
160
	 *
161
	 * @access private
162
	 */
163
	public function __construct() {
164
165
		add_action( 'admin_init', array( $this, 'compatible_version_check' ) );
166
167
		// Don't run anything else in the plugin, if we're on an incompatible PHP version
168
		if ( ! self::compatible_version() ) {
169
			return;
170
		}
171
172
		$this->set_variables();
173
174
		add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
175
		add_action( 'admin_enqueue_scripts', array($this,'admin_scripts') ,11 );
176
		add_action( 'admin_menu', array( $this, 'register_importer_page' ),20 );
177
178
		require_once(WETU_IMPORTER_PATH.'classes/class-accommodation.php');
179
		require_once(WETU_IMPORTER_PATH.'classes/class-destination.php');
180
		require_once(WETU_IMPORTER_PATH.'classes/class-tours.php');
181
182
		add_action( 'init', array( $this, 'load_class' ) );
183
184
		if('default' !== $this->tab_slug){
185
			add_action('wp_ajax_lsx_tour_importer',array($this,'process_ajax_search'));
186
			add_action('wp_ajax_nopriv_lsx_tour_importer',array($this,'process_ajax_search'));
187
188
			add_action('wp_ajax_lsx_import_items',array($this,'process_ajax_import'));
189
			add_action('wp_ajax_nopriv_lsx_import_items',array($this,'process_ajax_import'));
190
		}
191
	}
192
193
	// ACTIVATION FUNCTIONS
194
195
	/**
196
	 * Load the plugin text domain for translation.
197
	 *
198
	 * @since 1.0.0
199
	 */
200
	public function load_plugin_textdomain() {
201
		load_plugin_textdomain( 'wetu-importer', FALSE, basename( WETU_IMPORTER_PATH ) . '/languages');
202
	}
203
204
	/**
205
	 * Sets the variables used throughout the plugin.
206
	 */
207
	public function set_variables() {
208
		$this->post_types = array('accommodation','destination','tour');
209
		$temp_options = get_option('_lsx-to_settings',false);
210
211
		//Set the options.
212
		if(false !== $temp_options && isset($temp_options[$this->plugin_slug])) {
213
			$this->options = $temp_options[$this->plugin_slug];
214
215
			$this->api_key = false;
216
			$this->api_username = false;
217
			$this->api_password = false;
218
219
            if(!defined('WETU_API_KEY')) {
220
221
				if (isset($temp_options['api']['wetu_api_key']) && '' !== $temp_options['api']['wetu_api_key']) {
222
					$this->api_key = $temp_options['api']['wetu_api_key'];
223
				}
224
				if (isset($temp_options['api']['wetu_api_username']) && '' !== $temp_options['api']['wetu_api_username']) {
225
					$this->api_username = $temp_options['api']['wetu_api_username'];
226
				}
227
				if (isset($temp_options['api']['wetu_api_password']) && '' !== $temp_options['api']['wetu_api_password']) {
228
					$this->api_password = $temp_options['api']['wetu_api_password'];
229
				}
230
			}else{
231
				$this->api_key = WETU_API_KEY;
232
            }
233
234
			//Set the tab slug
235
			if(isset($_GET['tab']) || isset($_POST['type'])) {
236
				if (isset($_GET['tab'])) {
237
					$this->tab_slug = $_GET['tab'];
238
				} else {
239
					$this->tab_slug = $_POST['type'];
240
				}
241
242
				//If any tours were queued
243
				$this->queued_imports = get_option('wetu_importer_que', array());
244
245
			}
246
247
			//Set the scaling options
248
            if (isset($temp_options[$this->plugin_slug]) && !empty($temp_options[$this->plugin_slug]) && isset($this->options['image_scaling'])) {
249
                $this->scale_images = true;
250
                $width = '1024';
251
                if (isset($this->options['width']) && '' !== $this->options['width']) {
252
                    $width = $this->options['width'];
253
                }
254
                $height = '768';
255 View Code Duplication
                if (isset($this->options['height']) && '' !== $this->options['height']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
256
                    $height = $this->options['height'];
257
                }
258
                $cropping = 'w';
259 View Code Duplication
                if (isset($this->options['cropping']) && '' !== $this->options['cropping']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
260
                    $cropping = $this->options['cropping'];
261
                }
262
                $this->image_scaling_url = 'https://wetu.com/ImageHandler/' . $cropping . $width . 'x' . $height . '/';
0 ignored issues
show
Bug introduced by
The property image_scaling_url does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
263
            }
264
265
		}
266
	}
267
268
	// COMPATABILITY FUNCTIONS
269
270
	/**
271
	 * On plugin activation
272
	 *
273
	 * @since 1.0.0
274
	 */
275
	public static function register_activation_hook() {
276
		self::compatible_version_check_on_activation();
277
	}
278
	
279
	/**
280
	 * Check if the PHP version is compatible.
281
	 *
282
	 * @since 1.0.0
283
	 */
284
	public static function compatible_version() {
285
		if ( version_compare( PHP_VERSION, '5.6', '<' ) ) {
286
			return false;
287
		}
288
289
		return true;
290
	}
291
	
292
	/**
293
	 * The backup sanity check, in case the plugin is activated in a weird way,
294
	 * or the versions change after activation.
295
	 *
296
	 * @since 1.0.0
297
	 */
298
	public function compatible_version_check() {
299
		if ( ! self::compatible_version() ) {
300
			if ( is_plugin_active( plugin_basename( WETU_IMPORTER_CORE ) ) ) {
301
				deactivate_plugins( plugin_basename( WETU_IMPORTER_CORE ) );
302
				add_action( 'admin_notices', array( $this, 'compatible_version_notice' ) );
303
				
304
				if ( isset( $_GET['activate'] ) ) {
305
					unset( $_GET['activate'] );
306
				}
307
			}
308
		}
309
	}
310
	
311
	/**
312
	 * Display the notice related with the older version from PHP.
313
	 *
314
	 * @since 1.0.0
315
	 */
316
	public function compatible_version_notice() {
317
		$class = 'notice notice-error';
318
		$message = esc_html__( 'Wetu Importer Plugin requires PHP 5.6 or higher.', 'wetu-importer' );
319
		printf( '<div class="%1$s"><p>%2$s</p></div>', esc_html( $class ), esc_html( $message ) );
320
	}
321
	
322
	/**
323
	 * The primary sanity check, automatically disable the plugin on activation if it doesn't
324
	 * meet minimum requirements.
325
	 *
326
	 * @since 1.0.0
327
	 */
328
	public static function compatible_version_check_on_activation() {
329
		if ( ! self::compatible_version() ) {
330
			deactivate_plugins( plugin_basename( WETU_IMPORTER_CORE ) );
331
			wp_die( esc_html__( 'Wetu Importer Plugin requires PHP 5.6 or higher.', 'wetu-importer' ) );
332
		}
333
	}
334
335
	// DISPLAY FUNCTIONS
336
337
    /*
338
     * Load the importer class you want to use
339
     */
340
    public function load_class(){
341
342
		switch($this->tab_slug){
343
			case 'accommodation':
344
				$this->current_importer = new WETU_Importer_Accommodation();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \WETU_Importer_Accommodation() of type object<WETU_Importer_Accommodation> is incompatible with the declared type integer of property $current_importer.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
345
				break;
346
347
			case 'destination':
348
				$this->current_importer = new WETU_Importer_Destination();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \WETU_Importer_Destination() of type object<WETU_Importer_Destination> is incompatible with the declared type integer of property $current_importer.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
349
				break;
350
351
			case 'tour':
352
				$this->current_importer = new WETU_Importer_Tours();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \WETU_Importer_Tours() of type object<WETU_Importer_Tours> is incompatible with the declared type integer of property $current_importer.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
353
				break;
354
355
			default:
356
				$this->current_importer = false;
0 ignored issues
show
Documentation Bug introduced by
The property $current_importer was declared of type integer, but false is of type false. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
357
				break;
358
		}
359
360
    }
361
362
	/**
363
	 * Registers the admin page which will house the importer form.
364
	 */
365
	public function register_importer_page() {
366
		add_submenu_page( 'tour-operator',esc_html__( 'Importer', 'tour-operator' ), esc_html__( 'Importer', 'tour-operator' ), 'manage_options', 'wetu-importer', array( $this, 'display_page' ) );
367
	}
368
369
	/**
370
	 * Enqueue the JS needed to contact wetu and return your result.
371
	 */
372
	public function admin_scripts() {
373
		if ( defined( 'WP_DEBUG' ) && true === WP_DEBUG ) {
374
			$min = '';
0 ignored issues
show
Unused Code introduced by
$min 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...
375
		} else {
376
			$min = '.min';
0 ignored issues
show
Unused Code introduced by
$min 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...
377
		}
378
		$min = '';
379
380
		if(is_admin() && isset($_GET['page']) && $this->plugin_slug === $_GET['page']){
381
			wp_enqueue_script( 'wetu-importers-script', WETU_IMPORTER_URL . 'assets/js/wetu-importer' . $min . '.js', array( 'jquery' ), WETU_IMPORTER_VER, true );
382
			wp_localize_script( 'wetu-importers-script', 'lsx_tour_importer_params', array(
383
				'ajax_url' => admin_url('admin-ajax.php'),
384
			) );
385
		}
386
	}
387
388
	/**
389
	 * Display the importer administration screen
390
	 */
391
	public function display_page() {
392
		?>
393
        <div class="wrap">
394
			<?php screen_icon(); ?>
395
396
			<?php if(!is_object($this->current_importer)){
397
				?>
398
                <h2><?php _e('Welcome to the LSX Wetu Importer','wetu-importer'); ?></h2>
399
                <p>If this is the first time you are running the import, then follow the steps below.</p>
400
                <ul>
401
                    <li>Step 1 - Import your <a href="<?php echo admin_url('admin.php'); ?>?page=<?php echo $this->plugin_slug; ?>&tab=tour"><?php _e('Tours','wetu-importer'); ?></a></li>
402
                    <li>Step 2 - The tour import will have created draft <a href="<?php echo admin_url('admin.php'); ?>?page=<?php echo $this->plugin_slug; ?>&tab=accommodation"><?php _e('accommodation','wetu-importer'); ?></a> that will need to be imported.</li>
403
                    <li>Step 3 - Lastly import the <a href="<?php echo admin_url('admin.php'); ?>?page=<?php echo $this->plugin_slug; ?>&tab=destination"><?php _e('destinations','wetu-importer'); ?></a> draft posts created during the previous two steps.</li>
404
                </ul>
405
406
                <?php /*<h3><?php _e('Additional Tools','wetu-importer'); ?></h3>
407
                <ul>
408
                    <li><a href="<?php echo admin_url('admin.php'); ?>?page=<?php echo $this->plugin_slug; ?>&tab=connect_accommodation"><?php _e('Connect Accommodation','wetu-importer'); ?></a> <small><?php _e('If you already have accommodation, you can "connect" it with its WETU counter part, so it works with the importer.','wetu-importer'); ?></small></li>
409
					<?php if(class_exists('Lsx_Banners')){ ?>
410
                        <li><a href="<?php echo admin_url('admin.php'); ?>?page=<?php echo $this->plugin_slug; ?>&tab=banners"><?php _e('Sync High Res Banner Images','wetu-importer'); ?></a></li>
411
					<?php } ?>
412
                </ul>
413
				<?php*/
414
			}else{
415
			   $this->current_importer->display_page();
416
            }; ?>
417
        </div>
418
		<?php
419
	}
420
421
	/**
422
	 * search_form
423
	 */
424
	public function search_form() {
425
		?>
426
        <form class="ajax-form" id="<?php echo $this->plugin_slug; ?>-search-form" method="get" action="tools.php" data-type="<?php echo $this->tab_slug; ?>">
427
            <input type="hidden" name="page" value="<?php echo $this->tab_slug; ?>" />
428
429
            <h3><span class="dashicons dashicons-search"></span> <?php _e('Search','wetu-importer'); ?></h3>
430
431
			<?php do_action('wetu_importer_search_form',$this); ?>
432
433
            <div class="normal-search">
434
                <input pattern=".{3,}" placeholder="3 characters minimum" class="keyword" name="keyword" value=""> <input class="button button-primary submit" type="submit" value="<?php _e('Search','wetu-importer'); ?>" />
435
            </div>
436
            <div class="advanced-search hidden" style="display:none;">
437
                <p><?php _e('Enter several keywords, each on a new line.','wetu-importer'); ?></p>
438
                <textarea rows="10" cols="40" name="bulk-keywords"></textarea>
439
                <input class="button button-primary submit" type="submit" value="<?php _e('Search','wetu-importer'); ?>" />
440
            </div>
441
442
            <p>
443
                <a class="advanced-search-toggle" href="#"><?php _e('Bulk Search','wetu-importer'); ?></a> |
444
                <a class="published search-toggle" href="#publish"><?php esc_attr_e('Published','wetu-importer'); ?></a> |
445
                <a class="pending search-toggle"  href="#pending"><?php esc_attr_e('Pending','wetu-importer'); ?></a> |
446
                <a class="draft search-toggle"  href="#draft"><?php esc_attr_e('Draft','wetu-importer'); ?></a>
447
448
                <?php if('tour'===$this->tab_slug){ ?>
449
                    | <a class="import search-toggle"  href="#import"><?php esc_attr_e('WETU','wetu-importer'); ?></a>
450
                <?php }else if(!empty($this->queued_imports)) { ?>
451
                    | <a class="import search-toggle"  href="#import"><?php esc_attr_e('WETU Queue','wetu-importer'); ?></a>
452
                <?php } ?>
453
            </p>
454
455
            <div class="ajax-loader" style="display:none;width:100%;text-align:center;">
456
                <img style="width:64px;" src="<?php echo WETU_IMPORTER_URL.'assets/images/ajaxloader.gif';?>" />
457
            </div>
458
459
            <div class="ajax-loader-small" style="display:none;width:100%;text-align:center;">
460
                <img style="width:32px;" src="<?php echo WETU_IMPORTER_URL.'assets/images/ajaxloader.gif';?>" />
461
            </div>
462
        </form> 
463
		<?php
464
	}
465
466
	/**
467
	 * The header of the item list
468
	 */
469
	public function table_header() {
470
		?>
471
        <thead>
472
        <tr>
473
            <th style="" class="manage-column column-cb check-column" id="cb" scope="col">
474
                <label for="cb-select-all-1" class="screen-reader-text">Select All</label>
475
                <input type="checkbox" id="cb-select-all-1">
476
            </th>
477
            <th style="" class="manage-column column-title " id="title" style="width:50%;" scope="col">Title</th>
478
            <th style="" class="manage-column column-date" id="date" scope="col">Date</th>
479
            <th style="" class="manage-column column-ssid" id="ssid" scope="col">WETU ID</th>
480
        </tr>
481
        </thead>
482
		<?php
483
	}
484
485
	/**
486
	 * The footer of the item list
487
	 */
488
	public function table_footer() {
489
		?>
490
        <tfoot>
491
        <tr>
492
            <th style="" class="manage-column column-cb check-column" id="cb" scope="col">
493
                <label for="cb-select-all-1" class="screen-reader-text">Select All</label>
494
                <input type="checkbox" id="cb-select-all-1">
495
            </th>
496
            <th style="" class="manage-column column-title" scope="col">Title</th>
497
            <th style="" class="manage-column column-date" scope="col">Date</th>
498
            <th style="" class="manage-column column-ssid" scope="col">WETU ID</th>
499
        </tr>
500
        </tfoot>
501
		<?php
502
	}
503
504
	/**
505
	 * Displays the importers navigation
506
	 *
507
	 * @param $tab string
508
	 */
509
	public function navigation($tab='') {
510
		$post_types = array(
511
			'tour'              => esc_attr('Tours','wetu-importer'),
512
			'accommodation'     => esc_attr('Accommodation','wetu-importer'),
513
			'destination'       => esc_attr('Destinations','wetu-importer'),
514
		);
515
		echo '<div class="wet-navigation"><div class="subsubsub"><a class="'.$this->itemd($tab,'','current',false).'" href="'.admin_url('admin.php').'?page='.$this->plugin_slug.'">'.esc_attr('Home','wetu-importer').'</a>';
0 ignored issues
show
Documentation introduced by
$tab is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
516
		foreach($post_types as $post_type => $label){
517
			echo ' | <a class="'.$this->itemd($tab,$post_type,'current',false).'" href="'.admin_url('admin.php').'?page='.$this->plugin_slug.'&tab='.$post_type.'">'.$label.'</a>';
0 ignored issues
show
Documentation introduced by
$tab is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
518
		}
519
		echo '</div><br clear="both"/></div>';
520
	}
521
522
	/**
523
	 * set_taxonomy with some terms
524
	 */
525
	public function team_member_checkboxes($selected=array()) {
526
		if(post_type_exists('team')) { ?>
527
            <ul>
528
				<?php
529
				$team_args=array(
530
					'post_type'	=>	'team',
531
					'post_status' => 'publish',
532
					'nopagin' => true,
533
					'fields' => 'ids'
534
				);
535
				$team_members = new WP_Query($team_args);
536
				if($team_members->have_posts()){
537
					foreach($team_members->posts as $member){ ?>
538
                        <li><input class="team" <?php $this->checked($selected,$member); ?> type="checkbox" value="<?php echo $member; ?>" /> <?php echo get_the_title($member); ?></li>
0 ignored issues
show
Documentation introduced by
$selected is of type array, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
539
					<?php }
540
				}else{ ?>
541
                    <li><input class="team" type="checkbox" value="0" /> <?php _e('None','wetu-importer'); ?></li>
542
				<?php }
543
				?>
544
            </ul>
545
		<?php }
546
	}
547
548
549
	// GENERAL FUNCTIONS
550
551
	/**
552
	 * Checks to see if an item is checked.
553
	 *
554
	 * @param $haystack array|string
555
	 * @param $needle string
556
	 * @param $echo bool
557
	 */
558 View Code Duplication
	public function checked($haystack=false,$needle='',$echo=true) {
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...
559
		$return = $this->itemd($haystack,$needle,'checked');
560
		if('' !== $return) {
561
			if (true === $echo) {
562
				echo $return;
563
			} else {
564
				return $return;
565
			}
566
		}
567
	}
568
569
	/**
570
	 * Checks to see if an item is checked.
571
	 *
572
	 * @param $haystack array|string
573
	 * @param $needle string
574
	 * @param $echo bool
575
	 */
576 View Code Duplication
	public function selected($haystack=false,$needle='',$echo=true) {
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...
577
		$return = $this->itemd($haystack,$needle,'selected');
578
		if('' !== $return) {
579
			if (true === $echo) {
580
				echo $return;
581
			} else {
582
				return $return;
583
			}
584
		}
585
	}
586
587
	/**
588
	 * Checks to see if an item is selected. If $echo is false,  it will return the $type if conditions are true.
589
	 *
590
	 * @param $haystack array|string
591
	 * @param $needle string
592
	 * @param $type string
593
	 * @param $wrap bool
594
	 * @return $html string
0 ignored issues
show
Documentation introduced by
The doc-type $html could not be parsed: Unknown type name "$html" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
595
	 */
596
	public function itemd($haystack=false,$needle='',$type='',$wrap=true) {
597
		$html = '';
598
		if('' !== $type) {
599
			if (!is_array($haystack)) {
600
				$haystack = array($haystack);
601
			}
602
			if (in_array($needle, $haystack)) {
603
				if(true === $wrap || 'true' === $wrap) {
604
					$html = $type . '="' . $type . '"';
605
				}else{
606
					$html = $type;
607
				}
608
			}
609
		}
610
		return $html;
611
612
	}
613
614
	/**
615
	 * grabs any attachments for the current item
616
	 */
617
	public function find_attachments($id=false) {
618
		if(false !== $id){
619
			if(empty($this->found_attachments)){
620
621
				$attachments_args = array(
622
					'post_parent' => $id,
623
					'post_status' => 'inherit',
624
					'post_type' => 'attachment',
625
					'order' => 'ASC',
626
					'nopagin' => 'true',
627
					'posts_per_page' => '-1'
628
				);
629
630
				$attachments = new WP_Query($attachments_args);
631
				if($attachments->have_posts()){
632
					foreach($attachments->posts as $attachment){
633
						$this->found_attachments[$attachment->ID] = str_replace(array('.jpg','.png','.jpeg'),'',$attachment->post_title);
634
						$this->gallery_meta[] = $attachment->ID;
635
					}
636
				}
637
			}
638
		}
639
	}
640
641
642
	// CUSTOM FIELD FUNCTIONS
643
644
	/**
645
	 * Saves the room data
646
	 */
647
	public function save_custom_field($value=false,$meta_key,$id,$decrease=false,$unique=true) {
648
		if(false !== $value){
649
			if(false !== $decrease){
650
				$value = intval($value);
651
				$value--;
652
			}
653
			$prev = get_post_meta($id,$meta_key,true);
654
655
			if(false !== $id && '0' !== $id && false !== $prev && true === $unique){
656
				update_post_meta($id,$meta_key,$value,$prev);
657
			}else{
658
				add_post_meta($id,$meta_key,$value,$unique);
659
			}
660
		}
661
	}
662
663
	/**
664
	 * Grabs the custom fields,  and resaves an array of unique items.
665
	 */
666
	public function cleanup_posts() {
667
		if(!empty($this->cleanup_posts)){
668
			foreach($this->cleanup_posts as $id => $key) {
669
				$prev_items = get_post_meta($id, $key, false);
670
				$new_items = array_unique($prev_items);
671
				delete_post_meta($id, $key);
672
				foreach($new_items as $new_item) {
673
					add_post_meta($id, $key, $new_item, false);
674
				}
675
			}
676
		}
677
	}
678
679
	// TAXONOMY FUNCTIONS
680
681
	/**
682
	 * set_taxonomy with some terms
683
	 */
684
	public function set_taxonomy($taxonomy,$terms,$id) {
0 ignored issues
show
Unused Code introduced by
The parameter $terms is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
685
		$result=array();
686
		if(!empty($data))
0 ignored issues
show
Bug introduced by
The variable $data seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
687
		{
688
			foreach($data as $k)
689
			{
690
				if($id)
691
				{
692
					if(!$term = term_exists(trim($k), $tax))
693
					{
694
						$term = wp_insert_term(trim($k), $tax);
0 ignored issues
show
Bug introduced by
The variable $tax does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
695
						if ( is_wp_error($term) )
696
						{
697
							echo $term->get_error_message();
698
						}
699
						else
700
						{
701
							wp_set_object_terms( $id, intval($term['term_id']), $taxonomy,true);
702
						}
703
					}
704
					else
705
					{
706
						wp_set_object_terms( $id, intval($term['term_id']), $taxonomy,true);
707
					}
708
				}
709
				else
710
				{
711
					$result[]=trim($k);
712
				}
713
			}
714
		}
715
		return $result;
716
	}
717
718
	public function set_term($id=false,$name=false,$taxonomy=false,$parent=false){
719
		if(!$term = term_exists($name, $taxonomy))
720
		{
721
			if(false !== $parent){ $parent = array('parent'=>$parent); }
722
			$term = wp_insert_term(trim($name), $taxonomy,$parent);
723
			if ( is_wp_error($term) ){echo $term->get_error_message();}
724
			else { wp_set_object_terms( $id, intval($term['term_id']), $taxonomy,true); }
725
		}
726
		else
727
		{
728
			wp_set_object_terms( $id, intval($term['term_id']), $taxonomy,true);
729
		}
730
		return $term['term_id'];
731
	}
732
733
	/**
734
	 * set_taxonomy with some terms
735
	 */
736
	public function taxonomy_checkboxes($taxonomy=false,$selected=array()) {
737
		$return = '';
738
		if(false !== $taxonomy){
739
			$return .= '<ul>';
740
			$terms = get_terms(array('taxonomy'=>$taxonomy,'hide_empty'=>false));
741
742
			if(!is_wp_error($terms)){
743
				foreach($terms as $term){
744
					$return .= '<li><input class="'.$taxonomy.'" '.$this->checked($selected,$term->term_id,false).' type="checkbox" value="'.$term->term_id.'" /> '.$term->name.'</li>';
0 ignored issues
show
Documentation introduced by
$selected is of type array, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
745
				}
746
			}else{
747
				$return .= '<li><input type="checkbox" value="" /> '.__('None','wetu-importer').'</li>';
748
			}
749
			$return .= '</ul>';
750
		}
751
		return $return;
752
	}
753
754
	// MAP FUNCTIONS
755
	/**
756
	 * Saves the longitude and lattitude, as well as sets the map marker.
757
	 */
758
	public function set_map_data($data,$id,$zoom = '10') {
759
		$longitude = $latitude = $address = false;
760
761
		if(isset($data[0]['position'])){
762
763
			if(isset($data[0]['position']['driving_latitude'])){
764
				$latitude = $data[0]['position']['driving_latitude'];
765
			}elseif(isset($data[0]['position']['latitude'])){
766
				$latitude = $data[0]['position']['latitude'];
767
			}
768
769
			if(isset($data[0]['position']['driving_longitude'])){
770
				$longitude = $data[0]['position']['driving_longitude'];
771
			}elseif(isset($data[0]['position']['longitude'])){
772
				$longitude = $data[0]['position']['longitude'];
773
			}
774
775
		}
776
		if(isset($data[0]['content']) && isset($data[0]['content']['contact_information'])){
777
			if(isset($data[0]['content']['contact_information']['address'])){
778
				$address = strip_tags($data[0]['content']['contact_information']['address']);
779
780
				$address = explode("\n",$address);
781
				foreach($address as $bitkey => $bit){
782
					$bit = ltrim(rtrim($bit));
783
					if(false === $bit || '' === $bit || null === $bit or empty($bit)){
784
						unset($address[$bitkey]);
785
					}
786
				}
787
				$address = implode(', ',$address);
788
				$address = str_replace(', , ', ', ', $address);
789
			}
790
		}
791
792
		if(false !== $longitude){
793
			$location_data = array(
794
				'address'	=>	(string)$address,
795
				'lat'		=>	(string)$latitude,
796
				'long'		=>	(string)$longitude,
797
				'zoom'		=>	(string)$zoom,
798
				'elevation'	=>	'',
799
			);
800
			if(false !== $id && '0' !== $id){
801
				$prev = get_post_meta($id,'location',true);
802
				update_post_meta($id,'location',$location_data,$prev);
803
			}else{
804
				add_post_meta($id,'location',$location_data,true);
805
			}
806
		}
807
	}
808
809
	// IMAGE FUNCTIONS
810
811
	/**
812
	 * Creates the main gallery data
813
	 */
814
	public function set_featured_image($data,$id) {
815
		if(is_array($data[0]['content']['images']) && !empty($data[0]['content']['images'])){
816
		    if('tour' === $this->tab_slug){
817
		        $key = array_rand($data[0]['content']['images']);
818
                $this->featured_image = $this->attach_image($data[0]['content']['images'][$key],$id);
819
            }else{
820
				$this->featured_image = $this->attach_image($data[0]['content']['images'][0],$id);
821
            }
822
823
824
			if(false !== $this->featured_image){
825
				delete_post_meta($id,'_thumbnail_id');
826
				add_post_meta($id,'_thumbnail_id',$this->featured_image,true);
827
828 View Code Duplication
				if(!empty($this->gallery_meta) && !in_array($this->featured_image,$this->gallery_meta)){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
829
					add_post_meta($id,'gallery',$this->featured_image,false);
830
					$this->gallery_meta[] = $this->featured_image;
831
				}
832
			}
833
		}
834
	}
835
836
	/**
837
	 * Sets a banner image
838
	 */
839
	public function set_banner_image($data,$id) {
840
		if(is_array($data[0]['content']['images']) && !empty($data[0]['content']['images'])){
841
		    if(isset($data[0]['destination_image']) && is_array($data[0]['destination_image'])) {
842
				$temp_banner = $this->attach_image($data[0]['destination_image'], $id, array('width' => '1920', 'height' => '600', 'cropping' => 'c'));
0 ignored issues
show
Documentation introduced by
array('width' => '1920',...00', 'cropping' => 'c') is of type array<string,string,{"wi...","cropping":"string"}>, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
843
			}else{
844
				if ('tour' === $this->tab_slug) {
845
					$key = array_rand($data[0]['content']['images']);
846
					$temp_banner = $this->attach_image($data[0]['content']['images'][$key], $id, array('width' => '1920', 'height' => '600', 'cropping' => 'c'));
0 ignored issues
show
Documentation introduced by
array('width' => '1920',...00', 'cropping' => 'c') is of type array<string,string,{"wi...","cropping":"string"}>, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
847
				} else {
848
					$temp_banner = $this->attach_image($data[0]['content']['images'][1], $id, array('width' => '1920', 'height' => '600', 'cropping' => 'c'));
0 ignored issues
show
Documentation introduced by
array('width' => '1920',...00', 'cropping' => 'c') is of type array<string,string,{"wi...","cropping":"string"}>, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
849
				}
850
            }
851
852
853
			if(false !== $temp_banner){
854
				$this->banner_image = $temp_banner;
855
856
				delete_post_meta($id,'image_group');
857
				$new_banner = array('banner_image'=>array('cmb-field-0'=>$this->banner_image));
858
				add_post_meta($id,'image_group',$new_banner,true);
859
860 View Code Duplication
				if(!empty($this->gallery_meta) && !in_array($this->banner_image,$this->gallery_meta)){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
861
					add_post_meta($id,'gallery',$this->banner_image,false);
862
					$this->gallery_meta[] = $this->banner_image;
863
				}
864
			}
865
		}
866
	}
867
868
	/**
869
	 * Creates the main gallery data
870
	 */
871
	public function create_main_gallery($data,$id) {
872
873
		if(is_array($data[0]['content']['images']) && !empty($data[0]['content']['images'])){
874
			$counter = 0;
875
			foreach($data[0]['content']['images'] as $image_data){
876
				if($counter === 0 && false !== $this->featured_image){$counter++;continue;}
877
				if($counter === 1 && false !== $this->banner_image){$counter++;continue;}
878
879
				$this->gallery_meta[] = $this->attach_image($image_data,$id);
880
				$counter++;
881
			}
882
883
			if(!empty($this->gallery_meta)){
884
				delete_post_meta($id,'gallery');
885
				$this->gallery_meta = array_unique($this->gallery_meta);
886
				foreach($this->gallery_meta as $gallery_id){
887
					if(false !== $gallery_id && '' !== $gallery_id && !is_array($gallery_id)){
888
						add_post_meta($id,'gallery',$gallery_id,false);
889
					}
890
				}
891
			}
892
		}
893
	}
894
895
	/**
896
	 * search_form
897
	 */
898
	public function get_scaling_url($args=array()) {
899
900
		$defaults = array(
901
			'width' => '1024',
902
			'height' => '768',
903
			'cropping' => 'w'
904
		);
905
		if(false !== $this->options){
906
			if(isset($this->options['width']) && '' !== $this->options['width']){
907
				$defaults['width'] = $this->options['width'];
908
			}
909
910 View Code Duplication
			if(isset($this->options['height']) && '' !== $this->options['height']){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
911
				$defaults['height'] = $this->options['height'];
912
			}
913
914 View Code Duplication
			if(isset($this->options['cropping']) && '' !== $this->options['cropping']){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
915
				$defaults['cropping'] = $this->options['cropping'];
916
			}
917
		}
918
		$args = wp_parse_args($args,$defaults);
919
920
		$cropping = $args['cropping'];
921
		$width = $args['width'];
922
		$height = $args['height'];
923
924
		return 'https://wetu.com/ImageHandler/'.$cropping.$width.'x'.$height.'/';
925
	}
926
927
	/**
928
	 * Attaches 1 image
929
	 */
930
	public function attach_image($v=false,$parent_id,$image_sizes=false){
931
		if(false !== $v){
932
			$temp_fragment = explode('/',$v['url_fragment']);
933
			$url_filename = $temp_fragment[count($temp_fragment)-1];
934
			$url_filename = str_replace(array('.jpg','.png','.jpeg'),'',$url_filename);
935
			$url_filename = trim($url_filename);
936
			$url_filename = str_replace(" ",'_',$url_filename);
937
938
			if(in_array($url_filename,$this->found_attachments)){
939
				return array_search($url_filename,$this->found_attachments);
940
			}
941
942
			$postdata=array();
943
			if(empty($v['label']))
944
			{
945
				$v['label']='';
946
			}
947 View Code Duplication
			if(!empty($v['description']))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
948
			{
949
				$desc=wp_strip_all_tags($v['description']);
950
				$posdata=array('post_excerpt'=>$desc);
0 ignored issues
show
Unused Code introduced by
$posdata 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...
951
			}
952 View Code Duplication
			if(!empty($v['section']))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
953
			{
954
				$desc=wp_strip_all_tags($v['section']);
955
				$posdata=array('post_excerpt'=>$desc);
0 ignored issues
show
Unused Code introduced by
$posdata 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...
956
			}
957
958
			$attachID=NULL;
0 ignored issues
show
Unused Code introduced by
$attachID 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...
959
			//Resizor - add option to setting if required
960
			$fragment = str_replace(' ','%20',$v['url_fragment']);
961
			$url = $this->get_scaling_url($image_sizes).$fragment;
0 ignored issues
show
Documentation introduced by
$image_sizes is of type boolean, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
962
963
			$attachID = $this->attach_external_image2($url,$parent_id,'',$v['label'],$postdata);
964
965
			//echo($attachID.' add image');
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
966
			if($attachID!=NULL)
967
			{
968
				return $attachID;
969
			}
970
		}
971
		return 	false;
972
	}
973
974
	public function attach_external_image2( $url = null, $post_id = null, $thumb = null, $filename = null, $post_data = array() ) {
975
976
		if ( !$url || !$post_id ) { return new WP_Error('missing', "Need a valid URL and post ID..."); }
977
978
		require_once(ABSPATH . 'wp-admin/includes/file.php');
979
		require_once(ABSPATH . 'wp-admin/includes/media.php');
980
		require_once(ABSPATH . 'wp-admin/includes/image.php');
981
		// Download file to temp location, returns full server path to temp file
982
		//$tmp = download_url( $url );
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
983
984
		//var_dump($tmp);
985
		$tmp = tempnam("/tmp", "FOO");
986
987
		$image = file_get_contents($url);
988
		file_put_contents($tmp, $image);
989
		chmod($tmp,'777');
990
991
		preg_match('/[^\?]+\.(tif|TIFF|jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG|pdf|PDF|bmp|BMP)/', $url, $matches);    // fix file filename for query strings
992
		$url_filename = basename($matches[0]);
993
		$url_filename=str_replace('%20','_',$url_filename);
994
		// extract filename from url for title
995
		$url_type = wp_check_filetype($url_filename);                                           // determine file type (ext and mime/type)
996
997
		// override filename if given, reconstruct server path
998
		if ( !empty( $filename ) && " " != $filename )
999
		{
1000
			$filename = sanitize_file_name($filename);
1001
			$tmppath = pathinfo( $tmp );
1002
1003
			$extension = '';
1004
			if(isset($tmppath['extension'])){
1005
				$extension = $tmppath['extension'];
1006
			}
1007
1008
			$new = $tmppath['dirname'] . "/". $filename . "." . $extension;
1009
			rename($tmp, $new);                                                                 // renames temp file on server
1010
			$tmp = $new;                                                                        // push new filename (in path) to be used in file array later
1011
		}
1012
1013
		// assemble file data (should be built like $_FILES since wp_handle_sideload() will be using)
1014
		$file_array['tmp_name'] = $tmp;                                                         // full server path to temp file
0 ignored issues
show
Coding Style Comprehensibility introduced by
$file_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $file_array = 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...
1015
1016 View Code Duplication
		if ( !empty( $filename) && " " != $filename )
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
1017
		{
1018
			$file_array['name'] = $filename . "." . $url_type['ext'];                           // user given filename for title, add original URL extension
1019
		}
1020
		else
1021
		{
1022
			$file_array['name'] = $url_filename;                                                // just use original URL filename
1023
		}
1024
1025
		// set additional wp_posts columns
1026 View Code Duplication
		if ( empty( $post_data['post_title'] ) )
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
1027
		{
1028
1029
			$url_filename=str_replace('%20',' ',$url_filename);
1030
1031
			$post_data['post_title'] = basename($url_filename, "." . $url_type['ext']);         // just use the original filename (no extension)
1032
		}
1033
1034
		// make sure gets tied to parent
1035
		if ( empty( $post_data['post_parent'] ) )
1036
		{
1037
			$post_data['post_parent'] = $post_id;
1038
		}
1039
1040
		// required libraries for media_handle_sideload
1041
1042
		// do the validation and storage stuff
1043
		$att_id = media_handle_sideload( $file_array, $post_id, null, $post_data );             // $post_data can override the items saved to wp_posts table, like post_mime_type, guid, post_parent, post_title, post_content, post_status
1044
1045
		// If error storing permanently, unlink
1046
		if ( is_wp_error($att_id) )
1047
		{
1048
			unlink($file_array['tmp_name']);   // clean up
1049
			return false; // output wp_error
1050
			//return $att_id; // output wp_error
1051
		}
1052
1053
		return $att_id;
1054
	}
1055
1056
1057
	// AJAX FUNCTIONS
1058
	/**
1059
	 * Run through the accommodation grabbed from the DB.
1060
	 */
1061
	public function process_ajax_search() {
1062
	    $this->current_importer->process_ajax_search();
0 ignored issues
show
Bug introduced by
The method process_ajax_search cannot be called on $this->current_importer (of type integer).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1063
		die();
1064
	}
1065
1066
	/**
1067
	 * Connect to wetu
1068
	 */
1069
	public function process_ajax_import() {
1070
		$this->current_importer->process_ajax_import();
0 ignored issues
show
Bug introduced by
The method process_ajax_import cannot be called on $this->current_importer (of type integer).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1071
		die();
1072
	}
1073
1074
	/**
1075
	 * Formats the row for the completed list.
1076
	 */
1077
	public function format_completed_row($response){
1078
		echo '<li class="post-'.$response.'"><span class="dashicons dashicons-yes"></span> <a target="_blank" href="'.get_permalink($response).'">'.get_the_title($response).'</a></li>';
1079
	}
1080
1081
	/**
1082
	 * Formats the error.
1083
	 */
1084
	public function format_error($response){
1085
		echo '<li class="post-error"><span class="dashicons dashicons-no"></span>'.$response.'</li>';
1086
	}
1087
1088
	/**
1089
	 * Does a multine search
1090
	 */
1091
	public function multineedle_stripos($haystack, $needles, $offset=0) {
1092
		$found = false;
1093
		$needle_count = count($needles);
1094
		foreach($needles as $needle) {
1095
			if(false !== stripos($haystack, $needle, $offset)){
1096
				$found[] = true;
1097
			}
1098
		}
1099
		if(false !== $found && $needle_count === count($found)){
1100
			return true;
1101
		}else{
1102
			return false;
1103
		}
1104
	}
1105
1106
	/**
1107
	 * Grab all the current accommodation posts via the lsx_wetu_id field.
1108
	 */
1109 View Code Duplication
	public function find_current_accommodation($post_type='accommodation') {
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...
1110
		global $wpdb;
1111
		$return = array();
1112
1113
		$current_accommodation = $wpdb->get_results("
1114
					SELECT key1.post_id,key1.meta_value
1115
					FROM {$wpdb->postmeta} key1
1116
1117
					INNER JOIN  {$wpdb->posts} key2 
1118
    				ON key1.post_id = key2.ID
1119
					
1120
					WHERE key1.meta_key = 'lsx_wetu_id'
1121
					AND key2.post_type = '{$post_type}'
1122
1123
					LIMIT 0,5000
1124
		");
1125
		if(null !== $current_accommodation && !empty($current_accommodation)){
1126
			foreach($current_accommodation as $accom){
1127
				$return[$accom->meta_value] = $accom;
1128
			}
1129
		}
1130
		return $return;
1131
	}
1132
1133
	/**
1134
	 * Set the Video date
1135
	 */
1136
	public function set_video_data($data,$id) {
1137
		if(!empty($data[0]['content']['youtube_videos']) && is_array($data[0]['content']['youtube_videos'])){
1138
			$videos = false;
1139
1140
			foreach($data[0]['content']['youtube_videos'] as $video){
1141
				$temp_video = array();
1142
1143
				if(isset($video['label'])){
1144
					$temp_video['title'] = $video['label'];
1145
				}
1146
				if(isset($video['description'])){
1147
					$temp_video['description'] = strip_tags($video['description']);
1148
				}
1149
				if(isset($video['url'])){
1150
					$temp_video['url'] = $video['url'];
1151
				}
1152
				$temp_video['thumbnail'] = '';
1153
				$videos[] = $temp_video;
1154
			}
1155
1156
			if(false !== $id && '0' !== $id){
1157
				delete_post_meta($id, 'videos');
1158
			}
1159
			foreach($videos as $video){
0 ignored issues
show
Bug introduced by
The expression $videos of type false is not traversable.
Loading history...
1160
				add_post_meta($id,'videos',$video,false);
1161
			}
1162
		}
1163
	}
1164
1165
1166
}
1167
$wetu_importer = new WETU_Importer();
1168