Passed
Push — master ( f00970...13e5ed )
by Warwick
03:05
created

WETU_Importer_Tours::set_destination()   D

Complexity

Conditions 20
Paths 61

Size

Total Lines 83
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 83
rs 4.8715
c 0
b 0
f 0
cc 20
eloc 44
nc 61
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 {
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
	 * The query string url to list items from WETU
32
	 *
33
	 * @since 0.0.1
34
	 *
35
	 * @var      string
36
	 */
37
	public $url_qs = false;
38
39
	/**
40
	 * Holds a list of any current accommodation
41
	 *
42
	 * @since 0.0.1
43
	 *
44
	 * @var      string
45
	 */
46
	public $current_accommodation = false;
47
48
	/**
49
	 * Holds a list of any current destinations
50
	 *
51
	 * @since 0.0.1
52
	 *
53
	 * @var      string
54
	 */
55
	public $current_destinations = false;
56
57
	/**
58
	 * Holds a list of the destination and the image it needs to grab.
59
	 *
60
	 * @since 0.0.1
61
	 *
62
	 * @var      string
63
	 */
64
	public $destination_images = false;
65
66
	/**
67
	 * Options
68
	 *
69
	 * @since 0.0.1
70
	 *
71
	 * @var      string
72
	 */
73
	public $options = false;
74
75
	/**
76
	 * The fields you wish to import
77
	 *
78
	 * @since 0.0.1
79
	 *
80
	 * @var      string
81
	 */
82
	public $tour_options = false;
83
84
	/**
85
	 * Initialize the plugin by setting localization, filters, and administration functions.
86
	 *
87
	 * @since 1.0.0
88
	 *
89
	 * @access private
90
	 */
91
	public function __construct() {
92
		$this->set_variables();
93
	}
94
95
	/**
96
	 * Sets the variables used throughout the plugin.
97
	 */
98
	public function set_variables()
99
	{
100
	    parent::set_variables();
101
102
		if ( false !== $this->api_username && false !== $this->api_password ) {
103
			$this->url    = 'https://wetu.com/API/Itinerary/';
104
			$this->url_qs = 'username=' . $this->api_username . '&password=' . $this->api_password;
105
		} elseif ( false !== $this->api_key ) {
106
			$this->url    = 'https://wetu.com/API/Itinerary/' . $this->api_key;
107
			$this->url_qs = '';
108
		}
109
110
		$temp_options = get_option('_lsx-to_settings',false);
111
		if(false !== $temp_options && isset($temp_options[$this->plugin_slug]) && !empty($temp_options[$this->plugin_slug])){
112
			$this->options = $temp_options[$this->plugin_slug];
113
		}
114
115
		$tour_options = get_option('wetu_importer_tour_settings',false);
116
		if(false !== $tour_options){
117
			$this->tour_options = $tour_options;
118
		}
119
	}
120
121
	/**
122
	 * Display the importer administration screen
123
	 */
124
	public function display_page() {
125
        ?>
126
        <div class="wrap">
127
			<?php $this->navigation('tour'); ?>
128
129
            <?php $this->update_options_form(); ?>
130
131
            <?php $this->search_form(); ?>
132
133
			<form method="get" action="" id="posts-filter">
134
				<input type="hidden" name="post_type" class="post_type" value="<?php echo $this->tab_slug; ?>" />
135
				
136
				<p><input class="button button-primary add" type="button" value="<?php _e('Add to List','wetu-importer'); ?>" />
137
					<input class="button button-primary clear" type="button" value="<?php _e('Clear','wetu-importer'); ?>" />
138
				</p>				
139
140
				<table class="wp-list-table widefat fixed posts">
141
					<?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...
142
				
143
					<tbody id="the-list">
144
						<tr class="post-0 type-tour status-none" id="post-0">
145
							<th class="check-column" scope="row">
146
								<label for="cb-select-0" class="screen-reader-text"><?php _e('Enter a title to search for and press enter','wetu-importer'); ?></label>
147
							</th>
148
							<td class="post-title page-title column-title">
149
								<strong>
150
									<?php _e('Enter a title to search for','wetu-importer'); ?>
151
								</strong>
152
							</td>
153
							<td class="date column-date">							
154
							</td>
155
							<td class="ssid column-ssid">
156
							</td>
157
						</tr>									
158
					</tbody>
159
160
					<?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...
161
162
				</table>
163
164
				<p><input class="button button-primary add" type="button" value="<?php _e('Add to List','wetu-importer'); ?>" />
165
					<input class="button button-primary clear" type="button" value="<?php _e('Clear','wetu-importer'); ?>" />
166
				</p>
167
			</form>
168
169
			<div style="display:none;" class="import-list-wrapper">
170
				<br />        
171
				<form method="get" action="" id="import-list">
172
173
					<div class="row">
174
						<div class="settings-all" style="width:30%;display:block;float:left;">
175
							<h3><?php _e('What content to Sync from WETU'); ?></h3>
176
							<ul>
177
                                <li><input class="content select-all" <?php $this->checked($this->tour_options,'all'); ?> type="checkbox"name="content[]"  value="all" /> <?php _e('Select All','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
178
								<li><input class="content" <?php $this->checked($this->tour_options,'description'); ?> type="checkbox" name="content[]" value="description" /> <?php _e('Description','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
179
								<li><input class="content" <?php $this->checked($this->tour_options,'excerpt'); ?> type="checkbox" name="content[]" value="excerpt" /> <?php _e('Excerpt','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
180
181
                                <li><input class="content" <?php $this->checked($this->tour_options,'price'); ?> type="checkbox" name="content[]" value="price" /> <?php _e('Price','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
182
                                <li><input class="content" <?php $this->checked($this->tour_options,'duration'); ?> type="checkbox" name="content[]" value="duration" /> <?php _e('Duration','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
183
184
								<li><input class="content" <?php $this->checked($this->tour_options,'category'); ?> type="checkbox" name="content[]" value="category" /> <?php _e('Category','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
185
186
                                <li><input class="content" <?php $this->checked($this->tour_options,'itineraries'); ?> type="checkbox" name="content[]" value="itineraries" /> <?php _e('Itinerary Days','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
187
188
								<?php /*if(class_exists('LSX_TO_Maps')){ ?>
0 ignored issues
show
Unused Code Comprehensibility introduced by
83% 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...
189
                                    <li><input class="content" <?php $this->checked($this->tour_options,'map'); ?> type="checkbox" name="content[]" value="map" /> <?php _e('Map Coordinates (generates a KML file)','wetu-importer'); ?></li>
190
								<?php }*/ ?>
191
							</ul>
192
						</div>
193
                        <div class="settings-all" style="width:30%;display:block;float:left;">
194
                            <h3><?php _e('Itinerary Info'); ?></h3>
195
                            <ul>
196
                                <li><input class="content" <?php $this->checked($this->tour_options,'itinerary_description'); ?> type="checkbox" name="content[]" value="itinerary_description" /> <?php _e('Description','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
197
                                <li><input class="content" <?php $this->checked($this->tour_options,'itinerary_included'); ?> type="checkbox" name="content[]" value="itinerary_included" /> <?php _e('Included','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
198
                                <li><input class="content" <?php $this->checked($this->tour_options,'itinerary_excluded'); ?> type="checkbox" name="content[]" value="itinerary_excluded" /> <?php _e('Excluded','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
199
                            </ul>
200
201
                            <h4><?php _e('Additional Content'); ?></h4>
202
                            <ul>
203
                                <li><input class="content" <?php $this->checked($this->tour_options,'accommodation'); ?> type="checkbox" name="content[]" value="accommodation" /> <?php _e('Sync Accommodation','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
204
                                <li><input class="content" <?php $this->checked($this->tour_options,'destination'); ?> type="checkbox" name="content[]" value="destination" /> <?php _e('Sync Destinations','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
205
                                <li><input class="content" <?php $this->checked($this->tour_options,'featured_image'); ?> type="checkbox" name="content[]" value="featured_image" /> <?php _e('Featured Image','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
206
                                <li><input class="content" <?php $this->checked($this->tour_options,'banner_image'); ?> type="checkbox" name="content[]" value="banner_image" /> <?php _e('Banner Image','wetu-importer'); ?></li>
0 ignored issues
show
Documentation introduced by
$this->tour_options 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...
207
                            </ul>
208
                        </div>
209
                        <?php if(class_exists('LSX_TO_Team')){ ?>
210
                            <div style="width:30%;display:block;float:left;">
211
                                <h3><?php _e('Assign a Team Member'); ?></h3>
212
                                <?php $this->team_member_checkboxes($this->tour_options); ?>
0 ignored issues
show
Documentation introduced by
$this->tour_options is of type string, 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...
213
                            </div>
214
                        <?php } ?>
215
216
						<br clear="both" />			
217
					</div>
218
219
220
					<h3><?php _e('Your List'); ?></h3>
221
                    <p><input class="button button-primary" type="submit" value="<?php _e('Sync','wetu-importer'); ?>" /></p>
222
					<table class="wp-list-table widefat fixed posts">
223
						<?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...
224
225
						<tbody>
226
227
						</tbody>
228
229
						<?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...
230
231
					</table>
232
233
					<p><input class="button button-primary" type="submit" value="<?php _e('Sync','wetu-importer'); ?>" /></p>
234
				</form>
235
			</div>
236
237
			<div style="display:none;" class="completed-list-wrapper">
238
				<h3><?php _e('Completed','wetu-importer'); ?> - <small><?php _e('Import your','wetu-importer'); ?> <a href="<?php echo admin_url('admin.php'); ?>?page=<?php echo $this->plugin_slug; ?>&tab=accommodation"><?php _e('accommodation'); ?></a> <?php _e('next','wetu-importer'); ?></small></h3>
239
				<ul>
240
				</ul>
241
			</div>
242
        </div>
243
        <?php
244
	}
245
246
	/**
247
	 * search_form
248
	 */
249
	public function update_options_form() {
250
		$tours = get_transient('lsx_ti_tours');
251
252
		echo '<div class="wetu-status tour-wetu-status"><h3>'.__('Wetu Status','wetu-importer').' - ';
253
		if('' === $tours || false === $tours || isset($_GET['refresh_tours'])){
254
			$result = $this->update_options();
255
256
			if(true === $result){
257
			    echo '<span style="color:green;">'.esc_attr('Connected','wetu-importer').'</span>';
258
                echo ' - <small><a href="#">'.esc_attr('Refresh','wetu-importer').'</a></small>';
259
            }else{
260
			    echo '<span style="color:red;">'.wp_kses_post($result).'</span>';
261
            }
262
		}else{
263
			echo '<span style="color:green;">'.esc_attr('Connected','wetu-importer').'</span> - <small><a href="#">'.esc_attr('Refresh','wetu-importer').'</a></small>';
264
        }
265
		echo '</h3>';
266
267
		$form_options = get_option('lsx_ti_tours_api_options');
268
		if(false === $form_options){
269
			$form_options = array(0);
270
        }
271
		?>
272
        <form method="get" class="tour-refresh-form" action="<?php echo admin_url('admin.php'); ?>">
273
274
            <input type="hidden" name="page" value="<?php echo $this->plugin_slug; ?>" />
275
            <input type="hidden" name="tab" value="tour" />
276
            <input type="hidden" name="refresh_tours" value="true" />
277
278
            <p class="tour-search-options">
279
                <label for="own"><input class="content" <?php if(in_array('own',$form_options)){ echo 'checked'; } ?> type="checkbox" name="own" value="true" /> <?php esc_html_e('Own Tours','wetu-importer'); ?> </label>
280
            </p>
281
282
            <p class="tour-search-options">
283
                <label for="type"><input class="content" <?php if(in_array('allitineraries',$form_options)){ echo 'checked'; } ?> type="radio" name="type[]" value="allitineraries" /> <?php _e('All','wetu-importer'); ?></label>
284
                <label for="type"><input class="content" <?php if(in_array('sample',$form_options)){ echo 'checked'; } ?> type="radio" name="type[]" value="sample" /> <?php _e('Sample','wetu-importer'); ?></label>
285
                <label for="type"><input class="content" <?php if(in_array('personal',$form_options)){ echo 'checked'; } ?> type="radio" name="type[]" value="personal" /> <?php _e('Personal','wetu-importer'); ?></label>
286
            </p>
287
288
            <p><input class="button button-primary submit" type="submit" value="<?php echo esc_attr('Refresh Tours','wetu-importer'); ?>"></p>
289
        </form>
290
<br />
291
		<?php
292
		echo '</div>';
293
	}
294
295
	/**
296
	 * Save the list of Tours into an option
297
	 */
298
	public function update_options() {
299
300
	    $own = '';
0 ignored issues
show
Unused Code introduced by
$own 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...
301
	    $options = array();
302
303
	    delete_option('lsx_ti_tours_api_options');
304
305
	    if(isset($_GET['own'])){
306
			$this->url_qs .= '&own=true';
307
			$options[] = 'own';
308
        }
309
310
		if(isset($_GET['type'])){
311
			$this->url_qs .= '&type='.implode('',$_GET['type']);
312
			$options[] = implode('',$_GET['type']);
313
		}
314
315
		$this->url_qs .= '&results=2000';
316
317
		add_option('lsx_ti_tours_api_options',$options);
318
319
		$data = file_get_contents( $this->url . '/V7/List?' . $this->url_qs );
320
321
		$tours = json_decode($data, true);
322
323
		if(isset($tours['error'])){
324
		    return $tours['error'];
325 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...
326
			set_transient('lsx_ti_tours',$tours['itineraries'],60*60*2);
327
			return true;
328
		}
329
	}
330
331
	/**
332
	 * Grab all the current tour posts via the lsx_wetu_id field.
333
	 */
334 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...
335
		global $wpdb;
336
		$return = array();
337
338
		$current_tours = $wpdb->get_results("
339
					SELECT key1.post_id,key1.meta_value
340
					FROM {$wpdb->postmeta} key1
341
342
					INNER JOIN  {$wpdb->posts} key2 
343
    				ON key1.post_id = key2.ID
344
					
345
					WHERE key1.meta_key = 'lsx_wetu_id'
346
					AND key2.post_type = 'tour'
347
348
					LIMIT 0,500
349
		");
350
		if(null !== $current_tours && !empty($current_tours)){
351
			foreach($current_tours as $tour){
352
				$return[$tour->meta_value] = $tour;
353
			}
354
		}
355
		return $return;
356
	}
357
358
	/**
359
	 * Run through the accommodation grabbed from the DB.
360
	 */
361
	public function process_ajax_search() {
362
		$return = false;
363
364
		if(isset($_POST['action']) && $_POST['action'] === 'lsx_tour_importer' && isset($_POST['type']) && $_POST['type'] === $this->tab_slug){
365
366
367
			$tours = get_transient('lsx_ti_tours');
368
			if ( false !== $tours) {
369
370
				$searched_items = false;
371
372 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...
373
					$keyphrases = $_POST['keyword'];
374
				}else{
375
					$keyphrases = array(0);
376
				}
377
378
				if(!is_array($keyphrases)){
379
					$keyphrases = array($keyphrases);
380
				}
381
				foreach($keyphrases as &$keyword){
382
					$keyword = ltrim(rtrim($keyword));
383
				}
384
385
				$post_status = false;
386
				if(in_array('publish',$keyphrases)){
387
					$post_status = 'publish';
388
				}
389
				if(in_array('pending',$keyphrases)){
390
					$post_status = 'pending';
391
				}
392
				if(in_array('draft',$keyphrases)){
393
					$post_status = 'draft';
394
				}
395
				if(in_array('import',$keyphrases)){
396
					$post_status = 'import';
397
				}
398
399
400
				if (!empty($tours)) {
401
					$current_tours = $this->find_current_tours();
402
403
					foreach($tours as $row_key => $row){
404
405
						if(isset($row['is_disabled']) && true === $row['is_disabled']){
406
							continue;
407
						}
408
409
						/*if('Sample' === $row['type']){
0 ignored issues
show
Unused Code Comprehensibility introduced by
71% 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...
410
							continue;
411
						}*/
412
413
						//If this is a current tour, add its ID to the row.
414
						$row['post_id'] = 0;
415
						if(false !== $current_tours && array_key_exists($row['identifier'], $current_tours)){
416
							$row['post_id'] = $current_tours[$row['identifier']]->post_id;
417
						}
418
419
						//If we are searching for
420
						if(false !== $post_status){
421
422
							if('import' === $post_status){
423
424
								if(0 !== $row['post_id']){
425
									continue;
426
								}else{
427
									$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...
428
								}
429
430
431
							}else{
432
433
								if(0 === $row['post_id']){
434
									continue;
435
								}else{
436
									$current_status = get_post_status($row['post_id']);
437
									if($current_status !== $post_status){
438
										continue;
439
									}
440
441
								}
442
								$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...
443
444
							}
445
446
						}else{
447
							//Search through each keyword.
448
							foreach($keyphrases as $keyphrase){
449
450
								//Make sure the keyphrase is turned into an array
451
								$keywords = explode(" ",$keyphrase);
452
								if(!is_array($keywords)){
453
									$keywords = array($keywords);
454
								}
455
456
								if($this->multineedle_stripos(ltrim(rtrim($row['name'])), $keywords) !== false){
457
									$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...
458
								}
459
							}
460
						}
461
					}
462
				}
463
464
				if(false !== $searched_items){
465
					ksort($searched_items);
466
					$return = implode($searched_items);
467
				}
468
			}
469
			print_r($return);
470
			die();
471
		}
472
	}
473
474
	/**
475
	 * Formats the row for output on the screen.
476
	 */	
477 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...
478
		if(false !== $row){
479
480
			$status = 'import';
481
			if(0 !== $row['post_id']){
482
				$status = '<a href="'.admin_url('/post.php?post='.$row['post_id'].'&action=edit').'" target="_blank">'.get_post_status($row['post_id']).'</a>';
483
			}
484
485
			$row_html = '
486
			<tr class="post-'.$row['post_id'].' type-tour" id="post-'.$row['post_id'].'">
487
				<th class="check-column" scope="row">
488
					<label for="cb-select-'.$row['identifier'].'" class="screen-reader-text">'.$row['name'].'</label>
489
					<input type="checkbox" data-identifier="'.$row['identifier'].'" value="'.$row['post_id'].'" name="post[]" id="cb-select-'.$row['identifier'].'">
490
				</th>
491
				<td class="post-title page-title column-title">
492
					<strong>'.$row['name'].'</strong> - '.$status.'
493
				</td>
494
				<td class="date column-date">
495
					<abbr title="'.date('Y/m/d',strtotime($row['last_modified'])).'">'.date('Y/m/d',strtotime($row['last_modified'])).'</abbr><br>Last Modified
496
				</td>
497
				<td class="ssid column-ssid">
498
					'.$row['identifier'].'
499
				</td>
500
			</tr>';		
501
			return $row_html;
502
		}
503
	}
504
505
	/**
506
	 * Connect to wetu
507
	 */
508
	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...
509
		$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...
510
511
		if(isset($_POST['action']) && $_POST['action'] === 'lsx_import_items' && isset($_POST['type']) && $_POST['type'] === $this->tab_slug && isset($_POST['wetu_id'])){
512
			
513
			$wetu_id = $_POST['wetu_id'];
514
			if(isset($_POST['post_id'])){
515
				$post_id = $_POST['post_id'];	
516
			}else{
517
				$post_id = 0;
518
			}
519
520
			delete_option('wetu_importer_tour_settings');
521 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...
522
				$content = $_POST['content'];
523
				add_option('wetu_importer_tour_settings',$content);
524
			}else{
525
				$content = false;
526
			}
527
528
            $jdata=file_get_contents("http://wetu.com/API/Itinerary/V7/Get?id=".$wetu_id);
529
530 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...
531
            {
532
				$jdata=json_decode($jdata,true);
533
                if(!empty($jdata))
534
                {
535
                	$return = $this->import_row($jdata,$wetu_id,$post_id,$content);
536
                	$this->format_completed_row($return);
537
					$this->save_queue();
538
                	$this->cleanup_posts();
539
                	$this->attach_destination_images($content);
540
                }
541
            }
542
		}
543
	}
544
545
	/**
546
	 * Connect to wetu
547
     *
548
     * @param $data array
549
     * @param $wetu_id string
550
	 */
551
	public function import_row($data,$wetu_id,$id=0,$importable_content=false,$old1=false,$old2=false) {
0 ignored issues
show
Unused Code introduced by
The parameter $old1 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...
Unused Code introduced by
The parameter $old2 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...
552
        $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...
553
        $post = array(
554
          'post_type'		=> 'tour',
555
        );
556
557
        //Set the post_content
558
		$content_used_general_description = false;
0 ignored issues
show
Unused Code introduced by
$content_used_general_description 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...
559
        if(false !== $importable_content && in_array('description',$importable_content)){
560
            $data_post_content = '';
561
562
            if(isset($data['description'])){
563
                $data_post_content = $data['description'];
564
            }elseif(isset($data['summary'])){
565
                $data_post_content = $data['summary'];
566
            }
567
            $post['post_content'] = $data_post_content;
568
        }
569
570
        //Create or update the post
571
        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...
572
            $post['ID'] = $id;
573
	        $post['post_status'] = 'publish';
574
            $id = wp_update_post($post);
575
            $prev_date = get_post_meta($id,'lsx_wetu_modified_date',true);
576
            update_post_meta($id,'lsx_wetu_modified_date',strtotime($data['last_modified']),$prev_date);
577
        }else{
578
579
            //Set the name
580
            if(isset($data['name'])){
581
                $post_name = wp_unique_post_slug(sanitize_title($data['name']),$id, 'draft', 'tour', 0);
582
            }
583
            $post['post_name'] = $post_name;
584
            $post['post_title'] = $data['name'];
585
            $post['post_status'] = 'publish';
586
            $id = wp_insert_post($post);
587
588
            //Save the WETU ID and the Last date it was modified.
589
            if(false !== $id){
590
                add_post_meta($id,'lsx_wetu_id',$wetu_id);
591
                add_post_meta($id,'lsx_wetu_modified_date',strtotime($data['last_modified']));
592
            }
593
        }
594
595
596
		//Set the price
597
		if(false !== $importable_content && in_array('price',$importable_content)){
598
			$this->set_price($data,$id);
599
		}
600
601
		//Set the Duration
602
		if(false !== $importable_content && in_array('duration',$importable_content)){
603
			$this->set_duration($data,$id);
604
		}
605
606
        if(false !== $importable_content && in_array('itineraries',$importable_content) && isset($data['legs']) && !empty($data['legs'])){
607
            $this->process_itineraries($data,$id,$importable_content);
608
        }
609
610
		if(in_array('map',$importable_content) && isset($data['routes']) && !empty($data['routes'])){
611
			$this->set_map_data($data,$id);
612
		}
613
614
        return $id;
615
	}
616
617
	/**
618
	 * A loop which runs through each leg on the tour.
619
	 */
620
	public function process_itineraries($data,$id,$importable_content) {
621
		$day_counter = 1;
622
		$leg_counter = 0;
623
624
		delete_post_meta($id,'itinerary');
625
626
		if(false !== $importable_content && in_array('accommodation',$importable_content)){
627
			delete_post_meta($id,'accommodation_to_tour');
628
		}
629
		if(false !== $importable_content && in_array('destination',$importable_content)){
630
			delete_post_meta($id,'destination_to_tour');
631
			delete_post_meta($id,'departs_from');
632
			delete_post_meta($id,'ends_in');
633
		}
634
635
		$departs_from = false;
636
		$ends_in = false;
637
638
		foreach($data['legs'] as $leg){
639
640
			if(isset($leg['days']) && !empty($leg['days'])){
641
642
				//Itinerary Accommodation
643
				$current_accommodation = false;
644
				if(false !== $importable_content && in_array('accommodation',$importable_content)){
645
					$current_accommodation = $this->set_accommodation($leg,$id);
646
				}
647
648
				//Itinerary Destination
649
				$current_destination = false;
650
				if(false !== $importable_content && in_array('destination',$importable_content)){
651
					$current_destination = $this->set_destination($leg,$id,$leg_counter);
652
				}
653
654
				//If the Nights are the same mount of days in the array,  then it isnt "By Destination"
655
				if($leg['nights'] === count($leg['days']) || 0 === $leg['itinerary_leg_id']){
656
657
					foreach($leg['days'] as $day){
658
659
						$current_day = array();
660
661
						$current_day['title'] =  esc_attr('Day ','wetu-importer').$day_counter;
662
663
						//print_r('<pre>');print_r($day['notes']);print_r('</pre>');
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% 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...
664
665
						//Description
666
						if(false !== $importable_content && in_array('itinerary_description',$importable_content) && isset($day['notes'])){
667
							$current_day['description'] = $day['notes'];
668
						}else{
669
							$current_day['description'] = '';
670
						}
671
672
						//Itinerary Gallery
673
						if(false !== $importable_content && in_array('itinerary_gallery',$importable_content) && isset($day['images'])){
674
							$current_day['featured_image'] = '';
675
						}else{
676
							$current_day['featured_image'] = '';
677
						}
678
679
						//Accommodation
680
						if(false !== $current_accommodation){
681
							$current_day['accommodation_to_tour'] = array($current_accommodation);
682
						}else{
683
							$current_day['accommodation_to_tour'] = array();
684
						}
685
686
						//Destination
687
						if(false !== $current_destination){
688
							$current_day['destination_to_tour'] = array($current_destination);
689
						}else{
690
							$current_day['destination_to_tour'] = array();
691
						}
692
693
						//Included
694 View Code Duplication
						if(false !== $importable_content && in_array('itinerary_included',$importable_content) && isset($day['included']) && '' !== $day['included']){
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...
695
							$current_day['included'] = $day['included'];
696
						}else{
697
							$current_day['included'] = '';
698
						}
699
700
						//Excluded
701 View Code Duplication
						if(false !== $importable_content && in_array('itinerary_excluded',$importable_content) && isset($day['excluded']) && '' !== $day['excluded']){
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...
702
							$current_day['excluded'] = $day['excluded'];
703
						}else{
704
							$current_day['excluded'] = '';
705
						}
706
707
						$this->set_itinerary_day($current_day,$id);
708
						$day_counter++;
709
					}
710
711
				}else{
712
					$day_counter = $day_counter + (int)$leg['nights'];
713
				}
714
715
			}
716
717
			//If we are in the first leg,  and the destination was attached then save it as the departure field.
718
			if( 0 === $leg_counter && false !== $current_destination){
719
				$departs_from = $current_destination;
0 ignored issues
show
Bug introduced by
The variable $current_destination does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
720
			}
721
722
			//If its the last leg then save it as the ends in.
723
			if( $leg_counter === (count($data['legs'])-2) && false !== $current_destination){
724
				$ends_in = $current_destination;
725
			}
726
			$leg_counter++;
727
		}
728
729
		if(false !== $departs_from){
730
			add_post_meta($id,'departs_from',$departs_from,true);
731
		}
732
		if(false !== $ends_in){
733
			add_post_meta($id,'ends_in',$ends_in,true);
734
		}
735
	}
736
737
	/**
738
	 * Run through your routes and save the points as a KML file.
739
	 */
740
	public function set_map_data($data,$id,$zoom=9) {
741
742
		if(!empty($data['routes'])){
743
744
			delete_post_meta($id,'wetu_map_points');
745
746
			$points = array();
747
748
			foreach($data['routes'] as $route){
749
750
751
				if(isset($route['points']) && '' !== $route['points']){
752
753
					$temp_points = explode(';',$route['points']);
754
					$point_counter = count($temp_points);
755
756
					for ($x = 0; $x <= $point_counter; $x++) {
757
						$y = $x+1;
758
						$points[] = $temp_points[$x].','.$temp_points[$y];
759
						$x++;
760
					}
761
				}
762
			}
763
			if(!empty($points)){
764
				$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...
765
			}
766
		}
767
768
	}
769
770
	// CLASS SPECIFIC FUNCTIONS
771
772
	/**
773
	 * Set the Itinerary Day
774
	 */
775
	public function set_itinerary_day($day,$id) {
776
        $this->save_custom_field($day,'itinerary',$id,false,false);
777
	}
778
779
	/**
780
	 * Set the price
781
	 */
782
	public function set_price($data,$id) {
783
	    //Price
784 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...
785
            $price = preg_replace("/[^0-9,.]/", "", $data['price']);
786
            $this->save_custom_field($price,'price',$id);
787
		}
788
789
		//Price includes
790
		if(isset($data['price_includes']) && ''!== $data['price_includes']){
791
			$this->save_custom_field($data['price_includes'],'included',$id);
792
		}
793
794
        //Price Excludes
795
		if(isset($data['price_excludes']) && ''!== $data['price_excludes']){
796
			$this->save_custom_field($data['price_excludes'],'not_included',$id);
797
		}
798
799
	}
800
801
	/**
802
	 * Set the duration
803
	 */
804
	public function set_duration($data,$id) {
805 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...
806
			$price = $data['days'];
807
			$price = preg_replace("/[^0-9,.]/", "", $price);
808
			$this->save_custom_field($price,'duration',$id);
809
		}
810
	}
811
812
	/**
813
	 * Connects the Accommodation if its available
814
	 */
815
	public function set_accommodation($day,$id) {
816
817
	    $ac_id = false;
818
		$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...
819
		
820
		if(isset($day['content_entity_id']) && !empty($day['content_entity_id'])){
821
822
			if(false !== $this->current_accommodation && !empty($this->current_accommodation) && array_key_exists($day['content_entity_id'],$this->current_accommodation)){
823
                $ac_id = $this->current_accommodation[$day['content_entity_id']];
824
			}else{
825
				$ac_id = wp_insert_post(array(
826
                    'post_type' => 'accommodation',
827
                    'post_status' => 'draft',
828
                    'post_title' => $day['content_entity_id']
829
                ));
830
				$this->save_custom_field($day['content_entity_id'],'lsx_wetu_id',$ac_id);
831
			}
832
833
			if('' !== $ac_id && false !== $ac_id){
834
			    $this->save_custom_field($ac_id,'accommodation_to_tour',$id,false,false);
835
				$this->save_custom_field($id,'tour_to_accommodation',$ac_id,false,false);
836
837
				$this->queue_item($ac_id);
838
            }
839
		}
840
		return $ac_id;
841
	}
842
843
	/**
844
	 * Grab all the current accommodation posts via the lsx_wetu_id field.
845
     *
846
     * @param $post_type string
847
     * @return boolean / array
848
	 */
849
	public function find_current_accommodation($post_type='accommodation') {
850
		global $wpdb;
851
		$accommodation = parent::find_current_accommodation($post_type);
852
853
		$return = false;
854
		if(!empty($accommodation)){
855
		    foreach($accommodation as $key => $acc){
856
				$return[$acc->meta_value] = $acc->post_id;
857
            }
858
        }
859
		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::find_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...
860
	}
861
862
	/**
863
	 * Grab all the current accommodation posts via the lsx_wetu_id field.
864
     * @return boolean / array
865
	 */
866
	public function find_current_destinations() {
867
		return $this->find_current_accommodation('destination');
868
	}
869
870
	/**
871
	 * Connects the destinations post type
872
	 *
873
	 * @param $day array
874
	 * @param $id string
875
	 * @return boolean / string
876
	 */
877
	public function set_destination($day,$id,$leg_counter) {
878
		$dest_id = false;
879
		$country_id = false;
880
		$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...
881
882
		if(isset($day['destination_content_entity_id']) && !empty($day['destination_content_entity_id'])){
883
884
			if(false !== $this->current_destinations && !empty($this->current_destinations) && array_key_exists($day['destination_content_entity_id'],$this->current_destinations)){
885
				$dest_id = $this->current_destinations[$day['destination_content_entity_id']];
886
887
				//Check if there is a country asigned.
888
				$potential_id = wp_get_post_parent_id($dest_id);
889
				$country_wetu_id = get_post_meta($potential_id,'lsx_wetu_id',true);
890
				if(false !== $country_wetu_id){
891
					$country_id = $this->set_country($country_wetu_id, $id);
892
                }
893
894
			}else {
895
896
				$destination_json = file_get_contents("http://wetu.com/API/Pins/".$this->api_key."/Get?ids=" . $day['destination_content_entity_id']);
897
898
				if ($destination_json) {
899
					$destination_data = json_decode($destination_json, true);
900
901
					if (!empty($destination_data) && !isset($destination_data['error'])) {
902
903
					    $destination_title = $day['destination_content_entity_id'];
904
905
					    if(isset($destination_data[0]['name'])){
906
							$destination_title = $destination_data[0]['name'];
907
                        }
908
909
					    if(isset($destination_data[0]['map_object_id']) && isset($destination_data[0]['position']['country_content_entity_id'])
910
                            && $destination_data[0]['map_object_id'] !== $destination_data[0]['position']['country_content_entity_id']){
911
912
							$country_id = $this->set_country($destination_data[0]['position']['country_content_entity_id'], $id);
913
                        }
914
915
                        $dest_post = array(
916
							'post_type' => 'destination',
917
							'post_status' => 'draft',
918
							'post_title' => $destination_title
919
						);
920
921
					    if(false !== $country_id){
922
							$dest_post['post_parent'] = $country_id;
923
                        }
924
						$dest_id = wp_insert_post($dest_post);
925
926
						//Make sure we register the
927
						$this->current_destinations[$day['destination_content_entity_id']] = $dest_id;
928
929
						$this->save_custom_field($day['destination_content_entity_id'], 'lsx_wetu_id', $dest_id);
930
					}
931
				}
932
			}
933
934
			if ('' !== $dest_id && false !== $dest_id) {
935
				$this->save_custom_field($dest_id, 'destination_to_tour', $id, false, false);
936
				$this->save_custom_field($id, 'tour_to_destination', $dest_id, false, false);
937
938
				//Save the item to display in the queue
939
				$this->queue_item($dest_id);
940
941
				//Save the item to clean up the amount of connections.
942
                $this->cleanup_posts[$dest_id] = 'tour_to_destination';
943
944
				// Save the first destination so we can grab the tour featured image and banner
945
				if(0 === $leg_counter){
946
				    $this->destination_images[$id] = array($dest_id,$day['destination_content_entity_id']);
947
                }
948
949
				//Add this relation info so we can make sure certain items are set as countries.
950
				if(0 !== $country_id && false !== $country_id){
951
                    $this->relation_meta[$dest_id] = $country_id;
952
					$this->relation_meta[$country_id] = 0;
953
                }else{
954
					$this->relation_meta[$dest_id] = 0;
955
                }
956
			}
957
		}
958
		return $dest_id;
959
	}
960
961
	/**
962
	 * Connects the destinations post type
963
	 *
964
	 * @param $dest_id string
965
     * @param $country_id array
966
	 * @param $id string
967
     *
968
     * @return string
969
	 */
970
	public function set_country($country_wetu_id, $id) {
971
	    $country_id = false;
972
		$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...
973
974
        if (false !== $this->current_destinations && !empty($this->current_destinations) && array_key_exists($country_wetu_id, $this->current_destinations)) {
975
            $country_id = $this->current_destinations[$country_wetu_id];
976
        } else {
977
978
            $country_json = file_get_contents("http://wetu.com/API/Pins/".$this->api_key."/Get?ids=" . $country_wetu_id);
979
980
            if ($country_json) {
981
                $country_data = json_decode($country_json, true);
982
983
                if (!empty($country_data) && !isset($country_data['error'])) {
984
985
					//Format the title of the destination if its available,  otherwise default to the WETU ID.
986
                    $country_title = $country_wetu_id;
987
                    if (isset($country_data[0]['name'])) {
988
						$country_title = $country_data[0]['name'];
989
                    }
990
991
					$country_id = wp_insert_post(array(
992
                        'post_type' => 'destination',
993
                        'post_status' => 'draft',
994
                        'post_title' => $country_title
995
                    ));
996
					//add the country to the current destination stack
997
					$this->current_destinations[$country_wetu_id] = $country_id;
998
999
					//Save the wetu field
1000
                    $this->save_custom_field($country_wetu_id, 'lsx_wetu_id', $country_id);
1001
                }
1002
            }
1003
        }
1004
1005
        if ('' !== $country_id && false !== $country_id) {
1006
            $this->save_custom_field($country_id, 'destination_to_tour', $id, false, false);
1007
            $this->save_custom_field($id, 'tour_to_destination', $country_id, false, false);
1008
			$this->queue_item($country_id);
1009
			$this->cleanup_posts[$country_id] = 'tour_to_destination';
1010
1011
            return $country_id;
1012
        }
1013
	}
1014
1015
	/**
1016
	 * Connects the destinations post type
1017
	 *
1018
	 * @param $dest_id string
1019
	 * @param $country_id array
1020
	 * @param $id string
1021
	 *
1022
	 * @return string
1023
	 */
1024
	public function attach_destination_images($importable_content=array()) {
1025
	    if(false !== $this->destination_images){
1026
1027
	        foreach($this->destination_images as $tour => $destination){
0 ignored issues
show
Bug introduced by
The expression $this->destination_images of type string is not traversable.
Loading history...
1028
1029
				$url = 'https://wetu.com/API/Pins/' . $this->api_key;
1030
				$url_qs = '';
1031
1032
				$jdata = file_get_contents($url . '/Get?' . $url_qs . '&ids=' . $destination[1]);
1033
				if ($jdata) {
1034
					$adata = json_decode($jdata, true);
1035
1036
					if (!empty($adata)) {
1037
						$this->find_attachments($destination[0]);
1038
1039
						//Set the featured image
1040
						if (false !== $importable_content && in_array('featured_image', $importable_content)) {
1041
							$this->set_featured_image($adata, $tour);
1042
						}
1043
						if (false !== $importable_content && in_array('banner_image', $importable_content)) {
1044
							$this->set_banner_image($adata, $tour);
1045
						}
1046
					}
1047
				}
1048
            }
1049
        }
1050
	}
1051
1052
	/**
1053
	 * Que an item to be saved.
1054
	 *
1055
	 * @param   $id     int
1056
	 */
1057
	public function queue_item($id) {
1058
		if(is_array($this->import_queue) && !in_array($id,$this->import_queue)){
1059
			$this->import_queue[] = $id;
1060
		}else{
1061
			$this->import_queue[] = $id;
1062
		}
1063
	}
1064
1065
	/**
1066
	 * Saves the queue to the option.
1067
	 */
1068
	public function save_queue() {
1069
1070
		if(!empty($this->import_queue)) {
1071
			if (!empty($this->queued_imports)) {
1072
				$saved_imports = array_merge($this->queued_imports,$this->import_queue);
1073
1074
			}else{
1075
				$saved_imports = $this->import_queue;
1076
			}
1077
			delete_option('wetu_importer_que');
1078
			if(!empty($saved_imports)){
1079
				$saved_imports = array_unique($saved_imports);
1080
				update_option('wetu_importer_que',$saved_imports);
1081
			}
1082
		}
1083
	}
1084
}