Passed
Push — master ( 4ddb5b...a3fb73 )
by Warwick
03:31
created

WETU_Importer::table_header()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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