Completed
Push — master ( a84d89...a9842c )
by Fernando
02:35
created

WETU_Importer   D

Complexity

Total Complexity 206

Size/Duplication

Total Lines 1274
Duplicated Lines 7.14 %

Coupling/Cohesion

Components 3
Dependencies 3

Importance

Changes 0
Metric Value
wmc 206
lcom 3
cbo 3
dl 91
loc 1274
rs 4
c 0
b 0
f 0

41 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 28 3
A load_plugin_textdomain() 0 3 1
F set_variables() 6 73 24
A register_activation_hook() 0 3 1
A compatible_version() 0 7 2
A compatible_version_check() 0 12 4
A compatible_version_notice() 0 5 1
A compatible_version_check_on_activation() 0 6 2
A load_class() 0 19 4
A register_importer_page() 0 3 1
B admin_scripts() 0 17 6
B display_page() 0 32 2
B search_form() 0 42 3
A table_header() 0 15 1
A table_footer() 0 15 1
A navigation() 0 17 2
B team_member_checkboxes() 0 25 4
A checked() 10 12 3
A selected() 10 12 3
B itemd() 0 18 6
B find_attachments() 0 23 5
B save_custom_field() 0 16 7
A cleanup_posts() 0 14 4
B set_taxonomy() 0 26 6
B set_term() 0 23 4
B taxonomy_checkboxes() 0 23 4
C set_map_data() 0 54 17
A set_featured_image() 0 14 4
B set_banner_image() 13 32 6
C create_main_gallery() 0 49 23
C get_scaling_url() 6 29 8
C attach_image() 10 46 8
C attach_external_image2() 15 73 11
A process_ajax_search() 0 4 1
A process_ajax_import() 0 4 1
A format_completed_row() 0 4 1
A format_error() 0 4 1
B multineedle_stripos() 0 16 5
B find_current_accommodation() 21 27 4
D set_video_data() 0 30 10
A shuffle_assoc() 0 14 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like WETU_Importer often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use WETU_Importer, and based on these observations, apply Extract Interface, too.

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