Completed
Push — master ( 59f15b...3574d6 )
by Warwick
03:27
created

WETU_Importer::attach_image()   C

Complexity

Conditions 7
Paths 18

Size

Total Lines 42
Code Lines 25

Duplication

Lines 10
Ratio 23.81 %

Importance

Changes 0
Metric Value
dl 10
loc 42
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 25
nc 18
nop 3
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
	/**
151
	 * Initialize the plugin by setting localization, filters, and administration functions.
152
	 *
153
	 * @since 1.0.0
154
	 *
155
	 * @access private
156
	 */
157
	public function __construct() {
158
159
		add_action( 'admin_init', array( $this, 'compatible_version_check' ) );
160
161
		// Don't run anything else in the plugin, if we're on an incompatible PHP version
162
		if ( ! self::compatible_version() ) {
163
			return;
164
		}
165
166
		$this->set_variables();
167
168
		add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
169
		add_action( 'admin_enqueue_scripts', array($this,'admin_scripts') ,11 );
170
		add_action( 'admin_menu', array( $this, 'register_importer_page' ),20 );
171
172
		require_once(WETU_IMPORTER_PATH.'classes/class-accommodation.php');
173
		require_once(WETU_IMPORTER_PATH.'classes/class-destination.php');
174
		require_once(WETU_IMPORTER_PATH.'classes/class-tours.php');
175
176
		add_action( 'init', array( $this, 'load_class' ) );
177
178
		if('default' !== $this->tab_slug){
179
			add_action('wp_ajax_lsx_tour_importer',array($this,'process_ajax_search'));
180
			add_action('wp_ajax_nopriv_lsx_tour_importer',array($this,'process_ajax_search'));
181
182
			add_action('wp_ajax_lsx_import_items',array($this,'process_ajax_import'));
183
			add_action('wp_ajax_nopriv_lsx_import_items',array($this,'process_ajax_import'));
184
		}
185
	}
186
187
	// ACTIVATION FUNCTIONS
188
189
	/**
190
	 * Load the plugin text domain for translation.
191
	 *
192
	 * @since 1.0.0
193
	 */
194
	public function load_plugin_textdomain() {
195
		load_plugin_textdomain( 'wetu-importer', FALSE, basename( WETU_IMPORTER_PATH ) . '/languages');
196
	}
197
198
	/**
199
	 * Sets the variables used throughout the plugin.
200
	 */
201
	public function set_variables() {
202
		$this->post_types = array('accommodation','destination','tour');
203
		$temp_options = get_option('_lsx-to_settings',false);
204
205
		//Set the options.
206
		if(false !== $temp_options && isset($temp_options[$this->plugin_slug])) {
207
			$this->options = $temp_options[$this->plugin_slug];
208
209
			$this->api_key = false;
210
			$this->api_username = false;
211
			$this->api_password = false;
212
213
            if (isset($temp_options['api']['wetu_api_key']) && '' !== $temp_options['api']['wetu_api_key']) {
214
                $this->api_key = $temp_options['api']['wetu_api_key'];
215
            }
216
            if (isset($temp_options['api']['wetu_api_username']) && '' !== $temp_options['api']['wetu_api_username']) {
217
                $this->api_username = $temp_options['api']['wetu_api_username'];
218
            }
219
            if (isset($temp_options['api']['wetu_api_password']) && '' !== $temp_options['api']['wetu_api_password']) {
220
                $this->api_password = $temp_options['api']['wetu_api_password'];
221
            }
222
223
			//Set the tab slug
224
			if(isset($_GET['tab']) || isset($_POST['type'])) {
225
				if (isset($_GET['tab'])) {
226
					$this->tab_slug = $_GET['tab'];
227
				} else {
228
					$this->tab_slug = $_POST['type'];
229
				}
230
231
				//If any tours were queued
232
				$this->queued_imports = get_option('wetu_importer_que', array());
233
234
			}
235
236
			//Set the scaling options
237
            if (isset($temp_options[$this->plugin_slug]) && !empty($temp_options[$this->plugin_slug]) && isset($this->options['image_scaling'])) {
238
                $this->scale_images = true;
239
                $width = '800';
240
                if (isset($this->options['width']) && '' !== $this->options['width']) {
241
                    $width = $this->options['width'];
242
                }
243
                $height = '600';
244 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...
245
                    $height = $this->options['height'];
246
                }
247
                $cropping = 'raw';
248 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...
249
                    $cropping = $this->options['cropping'];
250
                }
251
                $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...
252
            }
253
254
		}
255
	}
256
257
	// COMPATABILITY FUNCTIONS
258
259
	/**
260
	 * On plugin activation
261
	 *
262
	 * @since 1.0.0
263
	 */
264
	public static function register_activation_hook() {
265
		self::compatible_version_check_on_activation();
266
	}
267
	
268
	/**
269
	 * Check if the PHP version is compatible.
270
	 *
271
	 * @since 1.0.0
272
	 */
273
	public static function compatible_version() {
274
		if ( version_compare( PHP_VERSION, '5.6', '<' ) ) {
275
			return false;
276
		}
277
278
		return true;
279
	}
280
	
281
	/**
282
	 * The backup sanity check, in case the plugin is activated in a weird way,
283
	 * or the versions change after activation.
284
	 *
285
	 * @since 1.0.0
286
	 */
287
	public function compatible_version_check() {
288
		if ( ! self::compatible_version() ) {
289
			if ( is_plugin_active( plugin_basename( WETU_IMPORTER_CORE ) ) ) {
290
				deactivate_plugins( plugin_basename( WETU_IMPORTER_CORE ) );
291
				add_action( 'admin_notices', array( $this, 'compatible_version_notice' ) );
292
				
293
				if ( isset( $_GET['activate'] ) ) {
294
					unset( $_GET['activate'] );
295
				}
296
			}
297
		}
298
	}
299
	
300
	/**
301
	 * Display the notice related with the older version from PHP.
302
	 *
303
	 * @since 1.0.0
304
	 */
305
	public function compatible_version_notice() {
306
		$class = 'notice notice-error';
307
		$message = esc_html__( 'Wetu Importer Plugin requires PHP 5.6 or higher.', 'wetu-importer' );
308
		printf( '<div class="%1$s"><p>%2$s</p></div>', esc_html( $class ), esc_html( $message ) );
309
	}
310
	
311
	/**
312
	 * The primary sanity check, automatically disable the plugin on activation if it doesn't
313
	 * meet minimum requirements.
314
	 *
315
	 * @since 1.0.0
316
	 */
317
	public static function compatible_version_check_on_activation() {
318
		if ( ! self::compatible_version() ) {
319
			deactivate_plugins( plugin_basename( WETU_IMPORTER_CORE ) );
320
			wp_die( esc_html__( 'Wetu Importer Plugin requires PHP 5.6 or higher.', 'wetu-importer' ) );
321
		}
322
	}
323
324
	// DISPLAY FUNCTIONS
325
326
    /*
327
     * Load the importer class you want to use
328
     */
329
    public function load_class(){
330
331
		switch($this->tab_slug){
332
			case 'accommodation':
333
				$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...
334
				break;
335
336
			case 'destination':
337
				$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...
338
				break;
339
340
			case 'tour':
341
				$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...
342
				break;
343
344
			default:
345
				$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...
346
				break;
347
		}
348
349
    }
350
351
	/**
352
	 * Registers the admin page which will house the importer form.
353
	 */
354
	public function register_importer_page() {
355
		add_submenu_page( 'tour-operator',esc_html__( 'Importer', 'tour-operator' ), esc_html__( 'Importer', 'tour-operator' ), 'manage_options', 'wetu-importer', array( $this, 'display_page' ) );
356
	}
357
358
	/**
359
	 * Enqueue the JS needed to contact wetu and return your result.
360
	 */
361
	public function admin_scripts() {
362
		if ( defined( 'WP_DEBUG' ) && true === WP_DEBUG ) {
363
			$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...
364
		} else {
365
			$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...
366
		}
367
		$min = '';
368
369
		if(is_admin() && isset($_GET['page']) && $this->plugin_slug === $_GET['page']){
370
			wp_enqueue_script( 'wetu-importers-script', WETU_IMPORTER_URL . 'assets/js/wetu-importer' . $min . '.js', array( 'jquery' ), WETU_IMPORTER_VER, true );
371
			wp_localize_script( 'wetu-importers-script', 'lsx_tour_importer_params', array(
372
				'ajax_url' => admin_url('admin-ajax.php'),
373
			) );
374
		}
375
	}
376
377
	/**
378
	 * Display the importer administration screen
379
	 */
380
	public function display_page() {
381
		?>
382
        <div class="wrap">
383
			<?php screen_icon(); ?>
384
385
			<?php if(!is_object($this->current_importer)){
386
				?>
387
                <h2><?php _e('Welcome to the LSX Wetu Importer','wetu-importer'); ?></h2>
388
                <p>If this is the first time you are running the import, then follow the steps below.</p>
389
                <ul>
390
                    <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>
391
                    <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>
392
                    <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>
393
                </ul>
394
395
                <?php /*<h3><?php _e('Additional Tools','wetu-importer'); ?></h3>
396
                <ul>
397
                    <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>
398
					<?php if(class_exists('Lsx_Banners')){ ?>
399
                        <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>
400
					<?php } ?>
401
                </ul>
402
				<?php*/
403
			}else{
404
			   $this->current_importer->display_page();
405
            }; ?>
406
        </div>
407
		<?php
408
	}
409
410
	/**
411
	 * search_form
412
	 */
413
	public function search_form() {
414
		?>
415
        <form class="ajax-form" id="<?php echo $this->plugin_slug; ?>-search-form" method="get" action="tools.php" data-type="<?php echo $this->tab_slug; ?>">
416
            <input type="hidden" name="page" value="<?php echo $this->tab_slug; ?>" />
417
418
            <h3><span class="dashicons dashicons-search"></span> <?php _e('Search','wetu-importer'); ?></h3>
419
420
			<?php do_action('wetu_importer_search_form',$this); ?>
421
422
            <div class="normal-search">
423
                <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'); ?>" />
424
            </div>
425
            <div class="advanced-search hidden" style="display:none;">
426
                <p><?php _e('Enter several keywords, each on a new line.','wetu-importer'); ?></p>
427
                <textarea rows="10" cols="40" name="bulk-keywords"></textarea>
428
                <input class="button button-primary submit" type="submit" value="<?php _e('Search','wetu-importer'); ?>" />
429
            </div>
430
431
            <p>
432
                <a class="advanced-search-toggle" href="#"><?php _e('Bulk Search','wetu-importer'); ?></a> |
433
                <a class="published search-toggle" href="#publish"><?php esc_attr_e('Published','wetu-importer'); ?></a> |
434
                <a class="pending search-toggle"  href="#pending"><?php esc_attr_e('Pending','wetu-importer'); ?></a> |
435
                <a class="draft search-toggle"  href="#draft"><?php esc_attr_e('Draft','wetu-importer'); ?></a>
436
437
                <?php if('tour'===$this->tab_slug){ ?>
438
                    | <a class="import search-toggle"  href="#import"><?php esc_attr_e('WETU','wetu-importer'); ?></a>
439
                <?php }else if(!empty($this->queued_imports)) { ?>
440
                    | <a class="import search-toggle"  href="#import"><?php esc_attr_e('WETU Queue','wetu-importer'); ?></a>
441
                <?php } ?>
442
            </p>
443
444
            <div class="ajax-loader" style="display:none;width:100%;text-align:center;">
445
                <img style="width:64px;" src="<?php echo WETU_IMPORTER_URL.'assets/images/ajaxloader.gif';?>" />
446
            </div>
447
448
            <div class="ajax-loader-small" style="display:none;width:100%;text-align:center;">
449
                <img style="width:32px;" src="<?php echo WETU_IMPORTER_URL.'assets/images/ajaxloader.gif';?>" />
450
            </div>
451
        </form> 
452
		<?php
453
	}
454
455
	/**
456
	 * The header of the item list
457
	 */
458
	public function table_header() {
459
		?>
460
        <thead>
461
        <tr>
462
            <th style="" class="manage-column column-cb check-column" id="cb" scope="col">
463
                <label for="cb-select-all-1" class="screen-reader-text">Select All</label>
464
                <input type="checkbox" id="cb-select-all-1">
465
            </th>
466
            <th style="" class="manage-column column-title " id="title" style="width:50%;" scope="col">Title</th>
467
            <th style="" class="manage-column column-date" id="date" scope="col">Date</th>
468
            <th style="" class="manage-column column-ssid" id="ssid" scope="col">WETU ID</th>
469
        </tr>
470
        </thead>
471
		<?php
472
	}
473
474
	/**
475
	 * The footer of the item list
476
	 */
477
	public function table_footer() {
478
		?>
479
        <tfoot>
480
        <tr>
481
            <th style="" class="manage-column column-cb check-column" id="cb" scope="col">
482
                <label for="cb-select-all-1" class="screen-reader-text">Select All</label>
483
                <input type="checkbox" id="cb-select-all-1">
484
            </th>
485
            <th style="" class="manage-column column-title" scope="col">Title</th>
486
            <th style="" class="manage-column column-date" scope="col">Date</th>
487
            <th style="" class="manage-column column-ssid" scope="col">WETU ID</th>
488
        </tr>
489
        </tfoot>
490
		<?php
491
	}
492
493
	/**
494
	 * Displays the importers navigation
495
	 *
496
	 * @param $tab string
497
	 */
498
	public function navigation($tab='') {
499
		$post_types = array(
500
			'tour'              => esc_attr('Tours','wetu-importer'),
501
			'accommodation'     => esc_attr('Accommodation','wetu-importer'),
502
			'destination'       => esc_attr('Destinations','wetu-importer'),
503
		);
504
		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...
505
		foreach($post_types as $post_type => $label){
506
			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...
507
		}
508
		echo '</div><br clear="both"/></div>';
509
	}
510
511
	/**
512
	 * set_taxonomy with some terms
513
	 */
514
	public function team_member_checkboxes($selected=array()) {
515
		if(post_type_exists('team')) { ?>
516
            <ul>
517
				<?php
518
				$team_args=array(
519
					'post_type'	=>	'team',
520
					'post_status' => 'publish',
521
					'nopagin' => true,
522
					'fields' => 'ids'
523
				);
524
				$team_members = new WP_Query($team_args);
525
				if($team_members->have_posts()){
526
					foreach($team_members->posts as $member){ ?>
527
                        <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...
528
					<?php }
529
				}else{ ?>
530
                    <li><input class="team" type="checkbox" value="0" /> <?php _e('None','wetu-importer'); ?></li>
531
				<?php }
532
				?>
533
            </ul>
534
		<?php }
535
	}
536
537
538
	// GENERAL FUNCTIONS
539
540
	/**
541
	 * Checks to see if an item is checked.
542
	 *
543
	 * @param $haystack array|string
544
	 * @param $needle string
545
	 * @param $echo bool
546
	 */
547 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...
548
		$return = $this->itemd($haystack,$needle,'checked');
549
		if('' !== $return) {
550
			if (true === $echo) {
551
				echo $return;
552
			} else {
553
				return $return;
554
			}
555
		}
556
	}
557
558
	/**
559
	 * Checks to see if an item is checked.
560
	 *
561
	 * @param $haystack array|string
562
	 * @param $needle string
563
	 * @param $echo bool
564
	 */
565 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...
566
		$return = $this->itemd($haystack,$needle,'selected');
567
		if('' !== $return) {
568
			if (true === $echo) {
569
				echo $return;
570
			} else {
571
				return $return;
572
			}
573
		}
574
	}
575
576
	/**
577
	 * Checks to see if an item is selected. If $echo is false,  it will return the $type if conditions are true.
578
	 *
579
	 * @param $haystack array|string
580
	 * @param $needle string
581
	 * @param $type string
582
	 * @param $wrap bool
583
	 * @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...
584
	 */
585
	public function itemd($haystack=false,$needle='',$type='',$wrap=true) {
586
		$html = '';
587
		if('' !== $type) {
588
			if (!is_array($haystack)) {
589
				$haystack = array($haystack);
590
			}
591
			if (in_array($needle, $haystack)) {
592
				if(true === $wrap || 'true' === $wrap) {
593
					$html = $type . '="' . $type . '"';
594
				}else{
595
					$html = $type;
596
				}
597
			}
598
		}
599
		return $html;
600
601
	}
602
603
	/**
604
	 * grabs any attachments for the current item
605
	 */
606
	public function find_attachments($id=false) {
607
		if(false !== $id){
608
			if(empty($this->found_attachments)){
609
610
				$attachments_args = array(
611
					'post_parent' => $id,
612
					'post_status' => 'inherit',
613
					'post_type' => 'attachment',
614
					'order' => 'ASC',
615
					'nopagin' => 'true',
616
					'posts_per_page' => '-1'
617
				);
618
619
				$attachments = new WP_Query($attachments_args);
620
				if($attachments->have_posts()){
621
					foreach($attachments->posts as $attachment){
622
						$this->found_attachments[$attachment->ID] = str_replace(array('.jpg','.png','.jpeg'),'',$attachment->post_title);
623
						$this->gallery_meta[] = $attachment->ID;
624
					}
625
				}
626
			}
627
		}
628
	}
629
630
631
	// CUSTOM FIELD FUNCTIONS
632
633
	/**
634
	 * Saves the room data
635
	 */
636
	public function save_custom_field($value=false,$meta_key,$id,$decrease=false,$unique=true) {
637
		if(false !== $value){
638
			if(false !== $decrease){
639
				$value = intval($value);
640
				$value--;
641
			}
642
			$prev = get_post_meta($id,$meta_key,true);
643
644
			if(false !== $id && '0' !== $id && false !== $prev && true === $unique){
645
				update_post_meta($id,$meta_key,$value,$prev);
646
			}else{
647
				add_post_meta($id,$meta_key,$value,$unique);
648
			}
649
		}
650
	}
651
652
	/**
653
	 * Grabs the custom fields,  and resaves an array of unique items.
654
	 */
655
	public function cleanup_posts() {
656
		if(!empty($this->cleanup_posts)){
657
			foreach($this->cleanup_posts as $id => $key) {
658
				$prev_items = get_post_meta($id, $key, false);
659
				$new_items = array_unique($prev_items);
660
				delete_post_meta($id, $key);
661
				foreach($new_items as $new_item) {
662
					add_post_meta($id, $key, $new_item, false);
663
				}
664
			}
665
		}
666
	}
667
668
	// TAXONOMY FUNCTIONS
669
670
	/**
671
	 * set_taxonomy with some terms
672
	 */
673
	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...
674
		$result=array();
675
		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...
676
		{
677
			foreach($data as $k)
678
			{
679
				if($id)
680
				{
681
					if(!$term = term_exists(trim($k), $tax))
682
					{
683
						$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...
684
						if ( is_wp_error($term) )
685
						{
686
							echo $term->get_error_message();
687
						}
688
						else
689
						{
690
							wp_set_object_terms( $id, intval($term['term_id']), $taxonomy,true);
691
						}
692
					}
693
					else
694
					{
695
						wp_set_object_terms( $id, intval($term['term_id']), $taxonomy,true);
696
					}
697
				}
698
				else
699
				{
700
					$result[]=trim($k);
701
				}
702
			}
703
		}
704
		return $result;
705
	}
706
707
	public function set_term($id=false,$name=false,$taxonomy=false,$parent=false){
708
		if(!$term = term_exists($name, $taxonomy))
709
		{
710
			if(false !== $parent){ $parent = array('parent'=>$parent); }
711
			$term = wp_insert_term(trim($name), $taxonomy,$parent);
712
			if ( is_wp_error($term) ){echo $term->get_error_message();}
713
			else { wp_set_object_terms( $id, intval($term['term_id']), $taxonomy,true); }
714
		}
715
		else
716
		{
717
			wp_set_object_terms( $id, intval($term['term_id']), $taxonomy,true);
718
		}
719
		return $term['term_id'];
720
	}
721
722
	/**
723
	 * set_taxonomy with some terms
724
	 */
725
	public function taxonomy_checkboxes($taxonomy=false,$selected=array()) {
726
		$return = '';
727
		if(false !== $taxonomy){
728
			$return .= '<ul>';
729
			$terms = get_terms(array('taxonomy'=>$taxonomy,'hide_empty'=>false));
730
731
			if(!is_wp_error($terms)){
732
				foreach($terms as $term){
733
					$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...
734
				}
735
			}else{
736
				$return .= '<li><input type="checkbox" value="" /> '.__('None','wetu-importer').'</li>';
737
			}
738
			$return .= '</ul>';
739
		}
740
		return $return;
741
	}
742
743
	// MAP FUNCTIONS
744
	/**
745
	 * Saves the longitude and lattitude, as well as sets the map marker.
746
	 */
747
	public function set_map_data($data,$id,$zoom = '10') {
748
		$longitude = $latitude = $address = false;
749
750
		if(isset($data[0]['position'])){
751
752
			if(isset($data[0]['position']['driving_latitude'])){
753
				$latitude = $data[0]['position']['driving_latitude'];
754
			}elseif(isset($data[0]['position']['latitude'])){
755
				$latitude = $data[0]['position']['latitude'];
756
			}
757
758
			if(isset($data[0]['position']['driving_longitude'])){
759
				$longitude = $data[0]['position']['driving_longitude'];
760
			}elseif(isset($data[0]['position']['longitude'])){
761
				$longitude = $data[0]['position']['longitude'];
762
			}
763
764
		}
765
		if(isset($data[0]['content']) && isset($data[0]['content']['contact_information'])){
766
			if(isset($data[0]['content']['contact_information']['address'])){
767
				$address = strip_tags($data[0]['content']['contact_information']['address']);
768
769
				$address = explode("\n",$address);
770
				foreach($address as $bitkey => $bit){
771
					$bit = ltrim(rtrim($bit));
772
					if(false === $bit || '' === $bit || null === $bit or empty($bit)){
773
						unset($address[$bitkey]);
774
					}
775
				}
776
				$address = implode(', ',$address);
777
				$address = str_replace(', , ', ', ', $address);
778
			}
779
		}
780
781
		if(false !== $longitude){
782
			$location_data = array(
783
				'address'	=>	(string)$address,
784
				'lat'		=>	(string)$latitude,
785
				'long'		=>	(string)$longitude,
786
				'zoom'		=>	(string)$zoom,
787
				'elevation'	=>	'',
788
			);
789
			if(false !== $id && '0' !== $id){
790
				$prev = get_post_meta($id,'location',true);
791
				update_post_meta($id,'location',$location_data,$prev);
792
			}else{
793
				add_post_meta($id,'location',$location_data,true);
794
			}
795
		}
796
	}
797
798
	// IMAGE FUNCTIONS
799
800
	/**
801
	 * Creates the main gallery data
802
	 */
803
	public function set_featured_image($data,$id) {
804
		if(is_array($data[0]['content']['images']) && !empty($data[0]['content']['images'])){
805
		    if('tour' === $this->tab_slug){
806
		        $key = array_rand($data[0]['content']['images']);
807
                $this->featured_image = $this->attach_image($data[0]['content']['images'][$key],$id);
808
            }else{
809
				$this->featured_image = $this->attach_image($data[0]['content']['images'][0],$id);
810
            }
811
812
813
			if(false !== $this->featured_image){
814
				delete_post_meta($id,'_thumbnail_id');
815
				add_post_meta($id,'_thumbnail_id',$this->featured_image,true);
816
817 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...
818
					add_post_meta($id,'gallery',$this->featured_image,false);
819
					$this->gallery_meta[] = $this->featured_image;
820
				}
821
			}
822
		}
823
	}
824
825
	/**
826
	 * Sets a banner image
827
	 */
828
	public function set_banner_image($data,$id) {
829
		if(is_array($data[0]['content']['images']) && !empty($data[0]['content']['images'])){
830
		    if(isset($data[0]['destination_image']) && is_array($data[0]['destination_image'])) {
831
				$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...
832
			}else{
833
				if ('tour' === $this->tab_slug) {
834
					$key = array_rand($data[0]['content']['images']);
835
					$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...
836
				} else {
837
					$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...
838
				}
839
            }
840
841
842
			if(false !== $temp_banner){
843
				$this->banner_image = $temp_banner;
844
845
				delete_post_meta($id,'image_group');
846
				$new_banner = array('banner_image'=>array('cmb-field-0'=>$this->banner_image));
847
				add_post_meta($id,'image_group',$new_banner,true);
848
849 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...
850
					add_post_meta($id,'gallery',$this->banner_image,false);
851
					$this->gallery_meta[] = $this->banner_image;
852
				}
853
			}
854
		}
855
	}
856
857
	/**
858
	 * Creates the main gallery data
859
	 */
860
	public function create_main_gallery($data,$id) {
861
862
		if(is_array($data[0]['content']['images']) && !empty($data[0]['content']['images'])){
863
			$counter = 0;
864
			foreach($data[0]['content']['images'] as $image_data){
865
				if($counter === 0 && false !== $this->featured_image){$counter++;continue;}
866
				if($counter === 1 && false !== $this->banner_image){$counter++;continue;}
867
868
				$this->gallery_meta[] = $this->attach_image($image_data,$id);
869
				$counter++;
870
			}
871
872
			if(!empty($this->gallery_meta)){
873
				delete_post_meta($id,'gallery');
874
				$this->gallery_meta = array_unique($this->gallery_meta);
875
				foreach($this->gallery_meta as $gallery_id){
876
					if(false !== $gallery_id && '' !== $gallery_id && !is_array($gallery_id)){
877
						add_post_meta($id,'gallery',$gallery_id,false);
878
					}
879
				}
880
			}
881
		}
882
	}
883
884
	/**
885
	 * search_form
886
	 */
887
	public function get_scaling_url($args=array()) {
888
889
		$defaults = array(
890
			'width' => '640',
891
			'height' => '480',
892
			'cropping' => 'c'
893
		);
894
		if(false !== $this->options){
895
			if(isset($this->options['width']) && '' !== $this->options['width']){
896
				$defaults['width'] = $this->options['width'];
897
			}
898
899 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...
900
				$defaults['height'] = $this->options['height'];
901
			}
902
903 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...
904
				$defaults['cropping'] = $this->options['cropping'];
905
			}
906
		}
907
		$args = wp_parse_args($args,$defaults);
908
909
		$cropping = $args['cropping'];
910
		$width = $args['width'];
911
		$height = $args['height'];
912
913
		return 'https://wetu.com/ImageHandler/'.$cropping.$width.'x'.$height.'/';
914
915
	}
916
917
	/**
918
	 * Attaches 1 image
919
	 */
920
	public function attach_image($v=false,$parent_id,$image_sizes=false){
921
		if(false !== $v){
922
			$temp_fragment = explode('/',$v['url_fragment']);
923
			$url_filename = $temp_fragment[count($temp_fragment)-1];
924
			$url_filename = str_replace(array('.jpg','.png','.jpeg'),'',$url_filename);
925
			$url_filename = trim($url_filename);
926
			$url_filename = str_replace(" ",'_',$url_filename);
927
928
			if(in_array($url_filename,$this->found_attachments)){
929
				return array_search($url_filename,$this->found_attachments);
930
			}
931
932
			$postdata=array();
933
			if(empty($v['label']))
934
			{
935
				$v['label']='';
936
			}
937 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...
938
			{
939
				$desc=wp_strip_all_tags($v['description']);
940
				$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...
941
			}
942 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...
943
			{
944
				$desc=wp_strip_all_tags($v['section']);
945
				$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...
946
			}
947
948
			$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...
949
			//Resizor - add option to setting if required
950
			$fragment = str_replace(' ','%20',$v['url_fragment']);
951
			$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...
952
			$attachID = $this->attach_external_image2($url,$parent_id,'',$v['label'],$postdata);
953
954
			//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...
955
			if($attachID!=NULL)
956
			{
957
				return $attachID;
958
			}
959
		}
960
		return 	false;
961
	}
962
963
	public function attach_external_image2( $url = null, $post_id = null, $thumb = null, $filename = null, $post_data = array() ) {
964
965
		if ( !$url || !$post_id ) { return new WP_Error('missing', "Need a valid URL and post ID..."); }
966
967
		require_once(ABSPATH . 'wp-admin/includes/file.php');
968
		require_once(ABSPATH . 'wp-admin/includes/media.php');
969
		require_once(ABSPATH . 'wp-admin/includes/image.php');
970
		// Download file to temp location, returns full server path to temp file
971
		//$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...
972
973
		//var_dump($tmp);
974
		$tmp = tempnam("/tmp", "FOO");
975
976
		$image = file_get_contents($url);
977
		file_put_contents($tmp, $image);
978
		chmod($tmp,'777');
979
980
		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
981
		$url_filename = basename($matches[0]);
982
		$url_filename=str_replace('%20','_',$url_filename);
983
		// extract filename from url for title
984
		$url_type = wp_check_filetype($url_filename);                                           // determine file type (ext and mime/type)
985
986
		// override filename if given, reconstruct server path
987
		if ( !empty( $filename ) && " " != $filename )
988
		{
989
			$filename = sanitize_file_name($filename);
990
			$tmppath = pathinfo( $tmp );
991
992
			$extension = '';
993
			if(isset($tmppath['extension'])){
994
				$extension = $tmppath['extension'];
995
			}
996
997
			$new = $tmppath['dirname'] . "/". $filename . "." . $extension;
998
			rename($tmp, $new);                                                                 // renames temp file on server
999
			$tmp = $new;                                                                        // push new filename (in path) to be used in file array later
1000
		}
1001
1002
		// assemble file data (should be built like $_FILES since wp_handle_sideload() will be using)
1003
		$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...
1004
1005 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...
1006
		{
1007
			$file_array['name'] = $filename . "." . $url_type['ext'];                           // user given filename for title, add original URL extension
1008
		}
1009
		else
1010
		{
1011
			$file_array['name'] = $url_filename;                                                // just use original URL filename
1012
		}
1013
1014
		// set additional wp_posts columns
1015 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...
1016
		{
1017
1018
			$url_filename=str_replace('%20',' ',$url_filename);
1019
1020
			$post_data['post_title'] = basename($url_filename, "." . $url_type['ext']);         // just use the original filename (no extension)
1021
		}
1022
1023
		// make sure gets tied to parent
1024
		if ( empty( $post_data['post_parent'] ) )
1025
		{
1026
			$post_data['post_parent'] = $post_id;
1027
		}
1028
1029
		// required libraries for media_handle_sideload
1030
1031
		// do the validation and storage stuff
1032
		$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
1033
1034
		// If error storing permanently, unlink
1035
		if ( is_wp_error($att_id) )
1036
		{
1037
			unlink($file_array['tmp_name']);   // clean up
1038
			return false; // output wp_error
1039
			//return $att_id; // output wp_error
1040
		}
1041
1042
		return $att_id;
1043
	}
1044
1045
1046
	// AJAX FUNCTIONS
1047
	/**
1048
	 * Run through the accommodation grabbed from the DB.
1049
	 */
1050
	public function process_ajax_search() {
1051
	    $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...
1052
		die();
1053
	}
1054
1055
	/**
1056
	 * Connect to wetu
1057
	 */
1058
	public function process_ajax_import() {
1059
		$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...
1060
		die();
1061
	}
1062
1063
	/**
1064
	 * Formats the row for the completed list.
1065
	 */
1066
	public function format_completed_row($response){
1067
		echo '<li class="post-'.$response.'"><span class="dashicons dashicons-yes"></span> <a target="_blank" href="'.get_permalink($response).'">'.get_the_title($response).'</a></li>';
1068
	}
1069
1070
	/**
1071
	 * Formats the error.
1072
	 */
1073
	public function format_error($response){
1074
		echo '<li class="post-error"><span class="dashicons dashicons-no"></span>'.$response.'</li>';
1075
	}
1076
1077
	/**
1078
	 * Does a multine search
1079
	 */
1080
	public function multineedle_stripos($haystack, $needles, $offset=0) {
1081
		$found = false;
1082
		$needle_count = count($needles);
1083
		foreach($needles as $needle) {
1084
			if(false !== stripos($haystack, $needle, $offset)){
1085
				$found[] = true;
1086
			}
1087
		}
1088
		if(false !== $found && $needle_count === count($found)){
1089
			return true;
1090
		}else{
1091
			return false;
1092
		}
1093
	}
1094
1095
	/**
1096
	 * Grab all the current accommodation posts via the lsx_wetu_id field.
1097
	 */
1098 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...
1099
		global $wpdb;
1100
		$return = array();
1101
1102
		$current_accommodation = $wpdb->get_results("
1103
					SELECT key1.post_id,key1.meta_value
1104
					FROM {$wpdb->postmeta} key1
1105
1106
					INNER JOIN  {$wpdb->posts} key2 
1107
    				ON key1.post_id = key2.ID
1108
					
1109
					WHERE key1.meta_key = 'lsx_wetu_id'
1110
					AND key2.post_type = '{$post_type}'
1111
1112
					LIMIT 0,5000
1113
		");
1114
		if(null !== $current_accommodation && !empty($current_accommodation)){
1115
			foreach($current_accommodation as $accom){
1116
				$return[$accom->meta_value] = $accom;
1117
			}
1118
		}
1119
		return $return;
1120
	}
1121
1122
	/**
1123
	 * Set the Video date
1124
	 */
1125
	public function set_video_data($data,$id) {
1126
		if(!empty($data[0]['content']['youtube_videos']) && is_array($data[0]['content']['youtube_videos'])){
1127
			$videos = false;
1128
1129
			foreach($data[0]['content']['youtube_videos'] as $video){
1130
				$temp_video = array();
1131
1132
				if(isset($video['label'])){
1133
					$temp_video['title'] = $video['label'];
1134
				}
1135
				if(isset($video['description'])){
1136
					$temp_video['description'] = strip_tags($video['description']);
1137
				}
1138
				if(isset($video['url'])){
1139
					$temp_video['url'] = $video['url'];
1140
				}
1141
				$temp_video['thumbnail'] = '';
1142
				$videos[] = $temp_video;
1143
			}
1144
1145
			if(false !== $id && '0' !== $id){
1146
				delete_post_meta($id, 'videos');
1147
			}
1148
			foreach($videos as $video){
0 ignored issues
show
Bug introduced by
The expression $videos of type false is not traversable.
Loading history...
1149
				add_post_meta($id,'videos',$video,false);
1150
			}
1151
		}
1152
	}
1153
1154
1155
}
1156
$wetu_importer = new WETU_Importer();
1157