Completed
Push — master ( 593133...8c8e21 )
by Fernando
02:56
created

WETU_Importer_Tours::set_accommodation()   C

Complexity

Conditions 8
Paths 5

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 16
nc 5
nop 2
1
<?php
2
/**
3
 * @package   WETU_Importer_Tours
4
 * @author    LightSpeed
5
 * @license   GPL-3+
6
 * @link      
7
 * @copyright 2017 LightSpeed
8
 **/
9
10
class WETU_Importer_Tours extends WETU_Importer_Accommodation {
11
12
	/**
13
	 * The url to list items from WETU
14
	 *
15
	 * @since 0.0.1
16
	 *
17
	 * @var      string
18
	 */
19
	public $tab_slug = 'tour';
20
21
	/**
22
	 * The url to list items from WETU
23
	 *
24
	 * @since 0.0.1
25
	 *
26
	 * @var      string
27
	 */
28
	public $url = false;
29
30
	/**
31
	 * Holds a list of any current accommodation
32
	 *
33
	 * @since 0.0.1
34
	 *
35
	 * @var      string
36
	 */
37
	public $current_accommodation = false;
38
39
	/**
40
	 * Holds a list of any current destinations
41
	 *
42
	 * @since 0.0.1
43
	 *
44
	 * @var      string
45
	 */
46
	public $current_destinations = false;
47
48
	/**
49
	 * Options
50
	 *
51
	 * @since 0.0.1
52
	 *
53
	 * @var      string
54
	 */
55
	public $options = false;			
56
57
	/**
58
	 * Initialize the plugin by setting localization, filters, and administration functions.
59
	 *
60
	 * @since 1.0.0
61
	 *
62
	 * @access private
63
	 */
64 View Code Duplication
	public function __construct() {
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...
65
		$this->set_variables();
66
67
		add_action( 'lsx_tour_importer_admin_tab_'.$this->tab_slug, array($this,'display_page') );
68
		add_action('wp_ajax_lsx_tour_importer',array($this,'process_ajax_search'));	
69
		add_action('wp_ajax_nopriv_lsx_tour_importer',array($this,'process_ajax_search'));		
70
71
		add_action('wp_ajax_lsx_import_items',array($this,'process_ajax_import'));	
72
		add_action('wp_ajax_nopriv_lsx_import_items',array($this,'process_ajax_import'));
73
74
		$temp_options = get_option('_lsx-to_settings',false);
75
		if(false !== $temp_options && isset($temp_options[$this->plugin_slug]) && !empty($temp_options[$this->plugin_slug])){
76
			$this->options = $temp_options[$this->plugin_slug];
77
		}				
78
	}
79
80
	/**
81
	 * Sets the variables used throughout the plugin.
82
	 */
83
	public function set_variables()
84
	{
85
		parent::set_variables();
86
		if(false !== $this->api_key){
87
			$this->url = 'https://wetu.com/API/Itinerary/'.$this->api_key.'/V7/List';
88
		}
89
	}
90
91
	/**
92
	 * Display the importer administration screen
93
	 */
94
	public function display_page() {
95
        ?>
96
        <div class="wrap">
97
            <?php screen_icon(); ?>
98
99
            <?php $this->update_options_form(); ?>
100
101
            <?php $this->search_form(); ?>
102
103
			<form method="get" action="" id="posts-filter">
104
				<input type="hidden" name="post_type" class="post_type" value="<?php echo $this->tab_slug; ?>" />
105
				
106
				<p><input class="button button-primary add" type="button" value="<?php _e('Add to List','wetu-importer'); ?>" />
107
					<input class="button button-primary clear" type="button" value="<?php _e('Clear','wetu-importer'); ?>" />
108
				</p>				
109
110
				<table class="wp-list-table widefat fixed posts">
111
					<?php $this->table_header(); ?>
0 ignored issues
show
Unused Code introduced by
The call to the method WETU_Importer_Tours::table_header() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
112
				
113
					<tbody id="the-list">
114
						<tr class="post-0 type-tour status-none" id="post-0">
115
							<th class="check-column" scope="row">
116
								<label for="cb-select-0" class="screen-reader-text"><?php _e('Enter a title to search for and press enter','wetu-importer'); ?></label>
117
							</th>
118
							<td class="post-title page-title column-title">
119
								<strong>
120
									<?php _e('Enter a title to search for','wetu-importer'); ?>
121
								</strong>
122
							</td>
123
							<td class="date column-date">							
124
							</td>
125
							<td class="ssid column-ssid">
126
							</td>
127
						</tr>									
128
					</tbody>
129
130
					<?php $this->table_footer(); ?>
0 ignored issues
show
Unused Code introduced by
The call to the method WETU_Importer_Tours::table_footer() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
131
132
				</table>
133
134
				<p><input class="button button-primary add" type="button" value="<?php _e('Add to List','wetu-importer'); ?>" />
135
					<input class="button button-primary clear" type="button" value="<?php _e('Clear','wetu-importer'); ?>" />
136
				</p>
137
			</form> 
138
139
			<div style="display:none;" class="import-list-wrapper">
140
				<br />        
141
				<form method="get" action="" id="import-list">
142
143
					<div class="row">
144
						<div style="width:30%;display:block;float:left;">
145
							<h3><?php _e('What content to Sync from WETU'); ?></h3>
146
							<ul>
147
								<li><input class="content" type="checkbox" name="content[]" value="description" /> <?php _e('Description','wetu-importer'); ?></li>
148
								<li><input class="content" type="checkbox" name="content[]" value="excerpt" /> <?php _e('Excerpt','wetu-importer'); ?></li>
149
150
                                <li><input class="content" type="checkbox" name="content[]" value="price" /> <?php _e('Price','wetu-importer'); ?></li>
151
                                <li><input class="content" type="checkbox" name="content[]" value="duration" /> <?php _e('Duration','wetu-importer'); ?></li>
152
153
								<li><input class="content" type="checkbox" name="content[]" value="category" /> <?php _e('Category','wetu-importer'); ?></li>
154
155
                                <li><input class="content" type="checkbox" name="content[]" value="itineraries" /> <?php _e('Itinerary Days','wetu-importer'); ?></li>
156
157
								<?php if(class_exists('TO_Maps')){ ?>
158
                                    <li><input class="content" type="checkbox" name="content[]" value="map" /> <?php _e('Map Coordinates (generates a KML file)','wetu-importer'); ?></li>
159
								<?php } ?>
160
							</ul>
161
						</div>
162
                        <div style="width:30%;display:block;float:left;">
163
                            <h3><?php _e('Itinerary Info'); ?></h3>
164
                            <ul>
165
                                <li><input class="content" type="checkbox" name="content[]" value="itinerary_description" /> <?php _e('Description','wetu-importer'); ?></li>
166
                                <li><input class="content" type="checkbox" name="content[]" value="itinerary_gallery" /> <?php _e('Gallery','wetu-importer'); ?></li>
167
                            </ul>
168
169
                            <h4><?php _e('Additional Content'); ?></h4>
170
                            <ul>
171
                                <li><input class="content" type="checkbox" name="content[]" value="accommodation" /> <?php _e('Sync Accommodation','wetu-importer'); ?></li>
172
                                <li><input class="content" type="checkbox" name="content[]" value="destination" /> <?php _e('Sync Destinations','wetu-importer'); ?></li>
173
                            </ul>
174
                        </div>
175
                        <?php if(class_exists('TO_Team')){ ?>
176
                            <div style="width:30%;display:block;float:left;">
177
                                <h3><?php _e('Assign a Team Member'); ?></h3>
178
                                <?php $this->team_member_checkboxes(); ?>
179
                            </div>
180
                        <?php } ?>
181
182
						<br clear="both" />			
183
					</div>
184
185
186
					<h3><?php _e('Your List'); ?></h3> 
187
					<table class="wp-list-table widefat fixed posts">
188
						<?php $this->table_header(); ?>
0 ignored issues
show
Unused Code introduced by
The call to the method WETU_Importer_Tours::table_header() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
189
190
						<tbody>
191
192
						</tbody>
193
194
						<?php $this->table_footer(); ?>
0 ignored issues
show
Unused Code introduced by
The call to the method WETU_Importer_Tours::table_footer() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
195
196
					</table>
197
198
					<p><input class="button button-primary" type="submit" value="<?php _e('Sync','wetu-importer'); ?>" /></p>
199
				</form>
200
			</div>
201
202
			<div style="display:none;" class="completed-list-wrapper">
203
				<h3><?php _e('Completed'); ?></h3>
204
				<ul>
205
				</ul>
206
			</div>
207
        </div>
208
        <?php
209
	}
210
211
	/**
212
	 * search_form
213
	 */
214
	public function update_options_form() {
215
		$tours = get_transient('lsx_ti_tours');
216
		echo '<div class="wetu-status"><h3>'.__('Wetu Status','wetu-importer').' - ';
217
		if('' === $tours || false === $tours || isset($_GET['refresh_tours'])){
218
			$result = $this->update_options();
219
220
			if(true === $result){
221
			    echo '<span style="color:green;">'.esc_attr('Connected','wetu-importer').'</span>';
222
            }else{
223
			    echo '<span style="color:red;">'.wp_kses_post($result).'</span>';
224
            }
225
		}else{
226
			echo '<span style="color:green;">'.esc_attr('Connected','wetu-importer').'</span>';
227
        }
228
		echo '</h3></div>';
229
	}
230
231
	/**
232
	 * Save the list of Tours into an option
233
	 */
234
	public function update_options() {
235
		$data= file_get_contents($this->url);
236
		$tours  = json_decode($data, true);
237
238
		if(isset($tours['error'])){
239
		    return $tours['error'];
240 View Code Duplication
        }elseif (isset($tours['itineraries']) && !empty($tours['itineraries'])) {
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...
241
			set_transient('lsx_ti_tours',$tours['itineraries'],60*60*2);
242
			return true;
243
		}
244
	}
245
246
	/**
247
	 * Grab all the current tour posts via the lsx_wetu_id field.
248
	 */
249 View Code Duplication
	public function find_current_tours() {
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...
250
		global $wpdb;
251
		$return = array();
252
253
		$current_tours = $wpdb->get_results("
254
					SELECT key1.post_id,key1.meta_value
255
					FROM {$wpdb->postmeta} key1
256
257
					INNER JOIN  {$wpdb->posts} key2 
258
    				ON key1.post_id = key2.ID
259
					
260
					WHERE key1.meta_key = 'lsx_wetu_id'
261
					AND key2.post_type = 'tour'
262
263
					LIMIT 0,500
264
		");
265
		if(null !== $current_tours && !empty($current_tours)){
266
			foreach($current_tours as $tour){
267
				$return[$tour->meta_value] = $tour;
268
			}
269
		}
270
		return $return;
271
	}	
272
273
	/**
274
	 * Run through the accommodation grabbed from the DB.
275
	 */
276
	public function process_ajax_search() {
277
		$return = false;
278
279
		if(isset($_POST['action']) && $_POST['action'] === 'lsx_tour_importer' && isset($_POST['type']) && $_POST['type'] === $this->tab_slug){
280
			$tours = get_transient('lsx_ti_tours');
281
			if ( false !== $tours) {
282
283
				$searched_items = false;
284
285 View Code Duplication
				if(isset($_POST['keyword'] )) {
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...
286
					$keyphrases = $_POST['keyword'];
287
				}else{
288
					$keyphrases = array(0);
289
                }
290
291
				if(!is_array($keyphrases)){
292
					$keyphrases = array($keyphrases);
293
				}
294
				foreach($keyphrases as &$keyword){
295
					$keyword = ltrim(rtrim($keyword));
296
				}
297
298
				$post_status = false;
299
				if(in_array('publish',$keyphrases)){
300
					$post_status = 'publish';
301
				}
302
				if(in_array('pending',$keyphrases)){
303
					$post_status = 'pending';
304
				}
305
				if(in_array('draft',$keyphrases)){
306
					$post_status = 'draft';
307
				}
308
				if(in_array('import',$keyphrases)){
309
					$post_status = 'import';
310
				}
311
312
313
				if (!empty($tours)) {
314
					$current_tours = $this->find_current_tours();
315
316
					foreach($tours as $row_key => $row){
317
318
					    if(isset($row['is_disabled']) && true === $row['is_disabled']){
319
                            continue;
320
                        }
321
322
                        if('Sample' === $row['type']){
323
                            continue;
324
                        }
325
326
                        //If this is a current tour, add its ID to the row.
327
						$row['post_id'] = 0;
328
						if(false !== $current_tours && array_key_exists($row['identifier'], $current_tours)){
329
							$row['post_id'] = $current_tours[$row['identifier']]->post_id;
330
						}
331
332
						//If we are searching for
333 View Code Duplication
						if(false !== $post_status){
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...
334
335
                            if('import' === $post_status){
336
337
								if(0 !== $row['post_id']){
338
								    continue;
339
								}else{
340
									$searched_items[sanitize_title($row['name']).'-'.$row['identifier']] = $this->format_row($row);
0 ignored issues
show
Documentation introduced by
$row is of type array<string,?,{"post_id":"?"}>, 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...
341
                                }
342
343
344
                            }else{
345
346
								if(0 === $row['post_id']){
347
									continue;
348
								}else{
349
									$current_status = get_post_status($row['post_id']);
350
									if($current_status !== $post_status){
351
									    continue;
352
                                    }
353
354
								}
355
								$searched_items[sanitize_title($row['name']).'-'.$row['identifier']] = $this->format_row($row);
0 ignored issues
show
Documentation introduced by
$row is of type array<string,?,{"post_id":"?"}>, 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...
356
357
                            }
358
359
                        }else{
360
							//Search through each keyword.
361
							foreach($keyphrases as $keyphrase){
362
363
								//Make sure the keyphrase is turned into an array
364
								$keywords = explode(" ",$keyphrase);
365
								if(!is_array($keywords)){
366
									$keywords = array($keywords);
367
								}
368
369
								if($this->multineedle_stripos(ltrim(rtrim($row['name'])), $keywords) !== false){
370
									$searched_items[sanitize_title($row['name']).'-'.$row['identifier']] = $this->format_row($row);
0 ignored issues
show
Documentation introduced by
$row is of type array<string,?,{"post_id":"?"}>, 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...
371
								}
372
							}
373
                        }
374
					}		
375
				}
376
377
				if(false !== $searched_items){
378
					ksort($searched_items);
379
					$return = implode($searched_items);
380
				}
381
			}
382
			print_r($return);
383
			die();
384
		}
385
	}
386
387
	/**
388
	 * Formats the row for output on the screen.
389
	 */	
390 View Code Duplication
	public function format_row($row = false){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
391
		if(false !== $row){
392
393
			$status = 'import';
394
			if(0 !== $row['post_id']){
395
				$status = '<a href="'.admin_url('/post.php?post='.$row['post_id'].'&action=edit').'" target="_blank">'.get_post_status($row['post_id']).'</a>';
396
			}
397
398
			$row_html = '
399
			<tr class="post-'.$row['post_id'].' type-tour" id="post-'.$row['post_id'].'">
400
				<th class="check-column" scope="row">
401
					<label for="cb-select-'.$row['identifier'].'" class="screen-reader-text">'.$row['name'].'</label>
402
					<input type="checkbox" data-identifier="'.$row['identifier'].'" value="'.$row['post_id'].'" name="post[]" id="cb-select-'.$row['identifier'].'">
403
				</th>
404
				<td class="post-title page-title column-title">
405
					<strong>'.$row['name'].'</strong> - '.$status.'
406
				</td>
407
				<td class="date column-date">
408
					<abbr title="'.date('Y/m/d',strtotime($row['last_modified'])).'">'.date('Y/m/d',strtotime($row['last_modified'])).'</abbr><br>Last Modified
409
				</td>
410
				<td class="ssid column-ssid">
411
					'.$row['identifier'].'
412
				</td>
413
			</tr>';		
414
			return $row_html;
415
		}
416
	}
417
418
	/**
419
	 * Connect to wetu
420
	 */
421
	public function process_ajax_import($force = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $force 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...
422
		$return = false;
0 ignored issues
show
Unused Code introduced by
$return 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...
423
		if(isset($_POST['action']) && $_POST['action'] === 'lsx_import_items' && isset($_POST['type']) && $_POST['type'] === $this->tab_slug && isset($_POST['wetu_id'])){
424
			
425
			$wetu_id = $_POST['wetu_id'];
426
			if(isset($_POST['post_id'])){
427
				$post_id = $_POST['post_id'];	
428
			}else{
429
				$post_id = 0;
430
			}
431
432 View Code Duplication
			if(isset($_POST['content']) && is_array($_POST['content']) && !empty($_POST['content'])){
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...
433
				$content = $_POST['content'];	
434
			}else{
435
				$content = false;
436
			}
437
438
            $jdata=file_get_contents("http://wetu.com/API/Itinerary/V7/Get?id=".$wetu_id);
439
440 View Code Duplication
            if($jdata)
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...
441
            {
442
				$jdata=json_decode($jdata,true);
443
                if(!empty($jdata))
444
                {
445
                	$return = $this->import_row($jdata,$wetu_id,$post_id,$content);
446
                	$this->format_completed_row($return);
447
                }
448
            }
449
			die();
450
		}
451
452
	}
453
454
	/**
455
	 * Connect to wetu
456
     *
457
     * @param $data array
458
     * @param $wetu_id string
459
	 */
460
	public function import_row($data,$wetu_id,$id=0,$importable_content=false,$old1=false,$old2=false) {
461
        $post_name = $data_post_content = $data_post_excerpt = '';
0 ignored issues
show
Unused Code introduced by
$data_post_excerpt 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...
Unused Code introduced by
$data_post_content 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...
462
        $post = array(
463
          'post_type'		=> 'tour',
464
        );
465
466
        //Set the post_content
467
		$content_used_general_description = false;
468
        if(false !== $importable_content && in_array('description',$importable_content)){
469
            $data_post_content = '';
470
471
            if(isset($data['description'])){
472
                $data_post_content = $data['description'];
473
            }elseif(isset($data['summary'])){
474
                $data_post_content = $data['summary'];
475
                $content_used_general_description = true;
476
            }
477
            $post['post_content'] = wp_strip_all_tags($data_post_content);
478
        }
479
480
        //set the post_excerpt
481
        if(false !== $importable_content && in_array('excerpt',$importable_content)){
482
            if(isset($data['summary']) && false === $content_used_general_description){
483
                $post['post_excerpt'] = $data['summary'];
484
            }
485
        }
486
487
        //Create or update the post
488
        if(false !== $id && '0' !== $id){
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison !== seems to always evaluate to true as the types of '0' (string) and $id (integer) can never be identical. Maybe you want to use a loose comparison != instead?
Loading history...
489
            $post['ID'] = $id;
490
	        $post['post_status'] = 'pending';
491
            $id = wp_update_post($post);
492
            $prev_date = get_post_meta($id,'lsx_wetu_modified_date',true);
493
            update_post_meta($id,'lsx_wetu_modified_date',strtotime($data['last_modified']),$prev_date);
494
        }else{
495
496
            //Set the name
497
            if(isset($data['name'])){
498
                $post_name = wp_unique_post_slug(sanitize_title($data['name']),$id, 'draft', 'tour', 0);
499
            }
500
            $post['post_name'] = $post_name;
501
            $post['post_title'] = $data['name'];
502
            $post['post_status'] = 'pending';
503
            $id = wp_insert_post($post);
504
505
            //Save the WETU ID and the Last date it was modified.
506
            if(false !== $id){
507
                add_post_meta($id,'lsx_wetu_id',$wetu_id);
508
                add_post_meta($id,'lsx_wetu_modified_date',strtotime($data['last_modified']));
509
            }
510
        }
511
512
513
		//Set the price
514
		if(false !== $importable_content && in_array('price',$importable_content)){
515
			$this->set_price($data,$id);
516
		}
517
518
		//Set the Duration
519
		if(false !== $importable_content && in_array('duration',$importable_content)){
520
			$this->set_duration($data,$id);
521
		}
522
523
        if(in_array('itineraries',$importable_content) && isset($data['legs']) && !empty($data['legs'])){
524
            $this->process_itineraries($data,$id,$importable_content);
525
        }
526
527
		if(in_array('map',$importable_content) && isset($data['routes']) && !empty($data['routes'])){
528
			$this->process_map_points($data,$id);
529
		}
530
531
		//TODO Test These
532
		//Setup some default for use in the import
533 View Code Duplication
		if(false !== $importable_content && (in_array('itinerary_gallery',$importable_content) || in_array('gallery',$importable_content) || in_array('banner_image',$importable_content) || in_array('featured_image',$importable_content))){
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...
534
			$this->find_attachments($id);
535
		}
536
        //Set the featured image
537
        //TODO Test These
538
        if(false !== $importable_content && in_array('featured_image',$importable_content)){
539
            $this->set_featured_image($data,$id);
540
        }
541
542
		//TODO Test These
543
        if(false !== $importable_content && in_array('banner_image',$importable_content)){
544
            $this->set_banner_image($data,$id);
545
        }
546
547
		//TODO Test These
548
        //Import the main gallery
549
        if(false !== $importable_content && in_array('gallery',$importable_content)){
550
            $this->create_main_gallery($data,$id);
551
        }
552
553
        return $id;
554
	}
555
556
	/**
557
	 * A loop which runs through each leg on the tour.
558
	 */
559
	public function process_itineraries($data,$id,$importable_content) {
560
		$day_counter = 1;
561
562
		delete_post_meta($id,'itinerary');
563
564
		if(false !== $importable_content && in_array('accommodation',$importable_content)){
565
			delete_post_meta($id,'accommodation_to_tour');
566
		}
567
		if(false !== $importable_content && in_array('destination',$importable_content)){
568
			delete_post_meta($id,'destination_to_tour');
569
		}
570
571
		foreach($data['legs'] as $leg){
572
573
			if(isset($leg['days']) && !empty($leg['days'])){
574
575
				//Itinerary Accommodation
576
				$current_accommodation = false;
577
				if(false !== $importable_content && in_array('accommodation',$importable_content)){
578
					$current_accommodation = $this->set_accommodation($leg,$id);
579
				}
580
581
				//Itinerary Destination
582
				$current_destination = false;
583
				if(false !== $importable_content && in_array('destination',$importable_content)){
584
					$current_destination = $this->set_destination($leg,$id);;
585
				}
586
587
				//If the Nights are the same mount of days in the array,  then it isnt "By Destination"
588
				if($leg['nights'] === count($leg['days']) || 0 === $leg['itinerary_leg_id']){
589
590
					foreach($leg['days'] as $day){
591
592
						$current_day = array();
593
594
						$current_day['title'] =  esc_attr('Day ','wetu-importer').$day_counter;
595
596
						//Description
597
						if(false !== $importable_content && in_array('itinerary_description',$importable_content) && isset($day['notes']) && '' !== $day['notes']){
598
							$current_day['description'] = strip_tags($day['notes']);
599
						}else{
600
							$current_day['description'] = '';
601
						}
602
603
						//Itinerary Gallery
604
						if(false !== $importable_content && in_array('itinerary_gallery',$importable_content) && isset($day['images'])){
605
							$current_day['featured_image'] = '';
606
						}else{
607
							$current_day['featured_image'] = '';
608
						}
609
610
						//Accommodation
611
						if(false !== $current_accommodation){
612
							$current_day['accommodation_to_tour'] = array($current_accommodation);
613
						}else{
614
							$current_day['accommodation_to_tour'] = array();
615
						}
616
617
						//Destination
618
						if(false !== $current_destination){
619
							$current_day['destination_to_tour'] = array($current_destination);
620
						}else{
621
							$current_day['destination_to_tour'] = array();
622
						}
623
624
						$this->set_itinerary_day($current_day,$id);
625
						$day_counter++;
626
					}
627
628
				}else{
629
					$day_counter = $day_counter + (int)$leg['nights'];
630
				}
631
632
			}
633
		}
634
	}
635
636
	/**
637
	 * Run through your routes and save the points as a KML file.
638
	 */
639
	public function process_map_points($data,$id) {
640
641
	    if(!empty($data['routes'])){
642
643
	        delete_post_meta($id,'wetu_map_points');
644
645
	        $points = array();
646
647
	        foreach($data['routes'] as $route){
648
649
650
	            if(isset($route['points']) && '' !== $route['points']){
651
652
	                $temp_points = explode(';',$route['points']);
653
	                $point_counter = count($temp_points);
654
655
					for ($x = 0; $x <= $point_counter; $x++) {
656
					    $y = $x+1;
657
						$points[] = $temp_points[$x].','.$temp_points[$y];
658
						$x++;
659
					}
660
				}
661
            }
662
            if(!empty($points)){
663
				$this->save_custom_field(implode(' ',$points),'wetu_map_points',$id,false,true);
0 ignored issues
show
Documentation introduced by
implode(' ', $points) 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...
664
            }
665
        }
666
667
	}
668
669
	/**
670
	 * Set the Itinerary Day
671
	 */
672
	public function set_itinerary_day($day,$id) {
673
        $this->save_custom_field($day,'itinerary',$id,false,false);
674
	}
675
676
	/**
677
	 * Set the price
678
	 */
679
	public function set_price($data,$id) {
680 View Code Duplication
		if(isset($data['price']) && ''!== $data['price']){
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...
681
            $price = preg_replace("/[^0-9,.]/", "", $data['price']);
682
            $this->save_custom_field($price,'price',$id);
683
		}
684
	}
685
686
	/**
687
	 * Set the duration
688
	 */
689
	public function set_duration($data,$id) {
690 View Code Duplication
		if(isset($data['days']) && !empty($data['days'])){
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...
691
			$price = $data['days'];
692
			$price = preg_replace("/[^0-9,.]/", "", $price);
693
			$this->save_custom_field($price,'duration',$id);
694
		}
695
	}
696
697
698
	/**
699
	 * Connects the Accommodation if its available
700
	 */
701
	public function set_accommodation($day,$id) {
702
703
	    $ac_id = false;
704
		$this->current_accommodation = $this->find_current_accommodation();
0 ignored issues
show
Documentation Bug introduced by
The property $current_accommodation was declared of type string, but $this->find_current_accommodation() is of type boolean. 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...
705
		
706
		if(isset($day['content_entity_id']) && !empty($day['content_entity_id'])){
707
708
			if(false !== $this->current_accommodation && !empty($this->current_accommodation) && array_key_exists($day['content_entity_id'],$this->current_accommodation)){
709
                $ac_id = $this->current_accommodation[$day['content_entity_id']];
710
			}else{
711
				$ac_id = wp_insert_post(array(
712
                    'post_type' => 'accommodation',
713
                    'post_status' => 'draft',
714
                    'post_title' => $day['content_entity_id']
715
                ));
716
				$this->save_custom_field($day['content_entity_id'],'lsx_wetu_id',$ac_id);
717
			}
718
719
			if('' !== $ac_id && false !== $ac_id){
720
			    $this->save_custom_field($ac_id,'accommodation_to_tour',$id,false,false);
721
				$this->save_custom_field($id,'tour_to_accommodation',$ac_id,false,false);
722
            }
723
		}
724
		return $ac_id;
725
	}
726
727
	/**
728
	 * Grab all the current accommodation posts via the lsx_wetu_id field.
729
     *
730
     * @param $post_type string
731
     * @return boolean / array
732
	 */
733
	public function find_current_accommodation($post_type='accommodation') {
734
		global $wpdb;
735
		$accommodation = parent::find_current_accommodation($post_type);
736
737
		$return = false;
738
		if(!empty($accommodation)){
739
		    foreach($accommodation as $key => $acc){
740
				$return[$acc->meta_value] = $acc->post_id;
741
            }
742
        }
743
		return $return;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $return; (false) is incompatible with the return type of the parent method WETU_Importer_Accommodat...d_current_accommodation of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
744
	}
745
746
	/**
747
	 * Grab all the current accommodation posts via the lsx_wetu_id field.
748
     * @return boolean / array
749
	 */
750
	public function find_current_destinations() {
751
		return $this->find_current_accommodation('destination');
752
	}
753
754
	/**
755
	 * Connects the destinations post type
756
	 *
757
	 * @param $day array
758
	 * @param $id string
759
	 * @return boolean / string
760
	 */
761
	public function set_destination($day,$id) {
762
		$dest_id = false;
763
		$country_id = false;
764
		$this->current_destinations = $this->find_current_destinations();
0 ignored issues
show
Documentation Bug introduced by
The property $current_destinations was declared of type string, but $this->find_current_destinations() is of type boolean. 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...
765
766
		if(isset($day['destination_content_entity_id']) && !empty($day['destination_content_entity_id'])){
767
768
			if(false !== $this->current_destinations && !empty($this->current_destinations) && array_key_exists($day['destination_content_entity_id'],$this->current_destinations)){
769
				$dest_id = $this->current_destinations[$day['destination_content_entity_id']];
770
771
				$potential_id = wp_get_post_parent_id($dest_id);
772
				$country_wetu_id = get_post_meta($potential_id,'lsx_wetu_id',true);
773
				if(false !== $country_wetu_id){
774
					$this->set_country($country_wetu_id, $id);
775
                }
776
777
			}else {
778
779
				$destination_json = file_get_contents("http://wetu.com/API/Pins/".$this->api_key."/Get?ids=" . $day['destination_content_entity_id']);
780
781
				if ($destination_json) {
782
					$destination_data = json_decode($destination_json, true);
783
784
					if (!empty($destination_data) && !isset($destination_data['error'])) {
785
786
					    $destination_title = $day['destination_content_entity_id'];
787
788
					    if(isset($destination_data[0]['name'])){
789
							$destination_title = $destination_data[0]['name'];
790
                        }
791
792
					    if(isset($destination_data[0]['map_object_id']) && isset($destination_data[0]['position']['country_content_entity_id'])
793
                            && $destination_data[0]['map_object_id'] !== $destination_data[0]['position']['country_content_entity_id']){
794
795
							$country_id = $this->set_country($destination_data[0]['position']['country_content_entity_id'], $id);
796
                        }
797
798
                        $dest_post = array(
799
							'post_type' => 'destination',
800
							'post_status' => 'draft',
801
							'post_title' => $destination_title
802
						);
803
804
					    if(false !== $country_id){
805
							$dest_post['post_parent'] = $country_id;
806
                        }
807
						$dest_id = wp_insert_post($dest_post);
808
809
						$this->save_custom_field($day['destination_content_entity_id'], 'lsx_wetu_id', $dest_id);
810
					}
811
				}
812
			}
813
814 View Code Duplication
			if ('' !== $dest_id && false !== $dest_id) {
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...
815
				$this->save_custom_field($dest_id, 'destination_to_tour', $id, false, false);
816
				$this->save_custom_field($id, 'tour_to_destination', $dest_id, false, false);
817
			}
818
		}
819
		return $dest_id;
820
	}
821
	/**
822
	 * Connects the destinations post type
823
	 *
824
	 * @param $dest_id string
825
     * @param $country_id array
826
	 * @param $id string
827
	 */
828
	public function set_country($country_wetu_id, $id) {
829
	    $country_id = false;
830
		$this->current_destinations = $this->find_current_destinations();
0 ignored issues
show
Documentation Bug introduced by
The property $current_destinations was declared of type string, but $this->find_current_destinations() is of type boolean. 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...
831
832
        if (false !== $this->current_destinations && !empty($this->current_destinations) && array_key_exists($country_wetu_id, $this->current_destinations)) {
833
            $country_id = $this->current_destinations[$country_wetu_id];
834
        } else {
835
836
            $country_json = file_get_contents("http://wetu.com/API/Pins/".$this->api_key."/Get?ids=" . $country_wetu_id);
837
838
            if ($country_json) {
839
                $country_data = json_decode($country_json, true);
840
841
                if (!empty($country_data) && !isset($country_data['error'])) {
842
843
                    $country_title = $country_wetu_id;
844
                    if (isset($country_data[0]['name'])) {
845
						$country_title = $country_data[0]['name'];
846
                    }
847
848
					$country_id = wp_insert_post(array(
849
                        'post_type' => 'destination',
850
                        'post_status' => 'draft',
851
                        'post_title' => $country_title
852
                    ));
853
                    $this->save_custom_field($country_wetu_id, 'lsx_wetu_id', $country_id);
854
                }
855
            }
856
        }
857
858 View Code Duplication
        if ('' !== $country_id && false !== $country_id) {
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...
859
            $this->save_custom_field($country_id, 'destination_to_tour', $id, false, false);
860
            $this->save_custom_field($id, 'tour_to_destination', $country_id, false, false);
861
862
            return $country_id;
863
        }
864
	}
865
}
866
$wetu_importer_tours = new WETU_Importer_Tours();