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

WETU_Importer_Tours::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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
		echo '<div class="wetu-status"><h3>'.__('Wetu Status','wetu-importer').' - ';
252
		if('' === $tours || false === $tours || isset($_GET['refresh_tours'])){
253
			$result = $this->update_options();
254
255
			if(true === $result){
256
			    echo '<span style="color:green;">'.esc_attr('Connected','wetu-importer').'</span>';
257
			    if(!isset($_GET['refresh_tours'])){
258
			        echo ' - <small><a href="'.admin_url('admin.php').'?page='.$this->plugin_slug.'&tab=tour&refresh_tours=true">'.esc_attr('Refresh','wetu-importer').'</a></small>';
259
                }
260
            }else{
261
			    echo '<span style="color:red;">'.wp_kses_post($result).'</span>';
262
            }
263
		}else{
264
			echo '<span style="color:green;">'.esc_attr('Connected','wetu-importer').'</span> - <small><a href="'.admin_url('admin.php').'?page='.$this->plugin_slug.'&tab=tour&refresh_tours=true">'.esc_attr('Refresh','wetu-importer').'</a></small>';
265
        }
266
		echo '</h3></div>';
267
	}
268
269
	/**
270
	 * Save the list of Tours into an option
271
	 */
272
	public function update_options() {
273
		$data = file_get_contents( $this->url . '/V7/List?' . $this->url_qs . '&own=true&type=All' );
274
		$tours = json_decode($data, true);
275
276
		if(isset($tours['error'])){
277
		    return $tours['error'];
278 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...
279
			set_transient('lsx_ti_tours',$tours['itineraries'],60*60*2);
280
			return true;
281
		}
282
	}
283
284
	/**
285
	 * Grab all the current tour posts via the lsx_wetu_id field.
286
	 */
287 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...
288
		global $wpdb;
289
		$return = array();
290
291
		$current_tours = $wpdb->get_results("
292
					SELECT key1.post_id,key1.meta_value
293
					FROM {$wpdb->postmeta} key1
294
295
					INNER JOIN  {$wpdb->posts} key2 
296
    				ON key1.post_id = key2.ID
297
					
298
					WHERE key1.meta_key = 'lsx_wetu_id'
299
					AND key2.post_type = 'tour'
300
301
					LIMIT 0,500
302
		");
303
		if(null !== $current_tours && !empty($current_tours)){
304
			foreach($current_tours as $tour){
305
				$return[$tour->meta_value] = $tour;
306
			}
307
		}
308
		return $return;
309
	}
310
311
	/**
312
	 * Run through the accommodation grabbed from the DB.
313
	 */
314
	public function process_ajax_search() {
315
		$return = false;
316
317
		if(isset($_POST['action']) && $_POST['action'] === 'lsx_tour_importer' && isset($_POST['type']) && $_POST['type'] === $this->tab_slug){
318
319
320
			$tours = get_transient('lsx_ti_tours');
321
			if ( false !== $tours) {
322
323
				$searched_items = false;
324
325 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...
326
					$keyphrases = $_POST['keyword'];
327
				}else{
328
					$keyphrases = array(0);
329
				}
330
331
				if(!is_array($keyphrases)){
332
					$keyphrases = array($keyphrases);
333
				}
334
				foreach($keyphrases as &$keyword){
335
					$keyword = ltrim(rtrim($keyword));
336
				}
337
338
				$post_status = false;
339
				if(in_array('publish',$keyphrases)){
340
					$post_status = 'publish';
341
				}
342
				if(in_array('pending',$keyphrases)){
343
					$post_status = 'pending';
344
				}
345
				if(in_array('draft',$keyphrases)){
346
					$post_status = 'draft';
347
				}
348
				if(in_array('import',$keyphrases)){
349
					$post_status = 'import';
350
				}
351
352
353
				if (!empty($tours)) {
354
					$current_tours = $this->find_current_tours();
355
356
					foreach($tours as $row_key => $row){
357
358
						if(isset($row['is_disabled']) && true === $row['is_disabled']){
359
							continue;
360
						}
361
362
						/*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...
363
							continue;
364
						}*/
365
366
						//If this is a current tour, add its ID to the row.
367
						$row['post_id'] = 0;
368
						if(false !== $current_tours && array_key_exists($row['identifier'], $current_tours)){
369
							$row['post_id'] = $current_tours[$row['identifier']]->post_id;
370
						}
371
372
						//If we are searching for
373 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...
374
375
							if('import' === $post_status){
376
377
								if(0 !== $row['post_id']){
378
									continue;
379
								}else{
380
									$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...
381
								}
382
383
384
							}else{
385
386
								if(0 === $row['post_id']){
387
									continue;
388
								}else{
389
									$current_status = get_post_status($row['post_id']);
390
									if($current_status !== $post_status){
391
										continue;
392
									}
393
394
								}
395
								$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...
396
397
							}
398
399
						}else{
400
							//Search through each keyword.
401
							foreach($keyphrases as $keyphrase){
402
403
								//Make sure the keyphrase is turned into an array
404
								$keywords = explode(" ",$keyphrase);
405
								if(!is_array($keywords)){
406
									$keywords = array($keywords);
407
								}
408
409
								if($this->multineedle_stripos(ltrim(rtrim($row['name'])), $keywords) !== false){
410
									$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...
411
								}
412
							}
413
						}
414
					}
415
				}
416
417
				if(false !== $searched_items){
418
					ksort($searched_items);
419
					$return = implode($searched_items);
420
				}
421
			}
422
			print_r($return);
423
			die();
424
		}
425
	}
426
427
	/**
428
	 * Formats the row for output on the screen.
429
	 */	
430 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...
431
		if(false !== $row){
432
433
			$status = 'import';
434
			if(0 !== $row['post_id']){
435
				$status = '<a href="'.admin_url('/post.php?post='.$row['post_id'].'&action=edit').'" target="_blank">'.get_post_status($row['post_id']).'</a>';
436
			}
437
438
			$row_html = '
439
			<tr class="post-'.$row['post_id'].' type-tour" id="post-'.$row['post_id'].'">
440
				<th class="check-column" scope="row">
441
					<label for="cb-select-'.$row['identifier'].'" class="screen-reader-text">'.$row['name'].'</label>
442
					<input type="checkbox" data-identifier="'.$row['identifier'].'" value="'.$row['post_id'].'" name="post[]" id="cb-select-'.$row['identifier'].'">
443
				</th>
444
				<td class="post-title page-title column-title">
445
					<strong>'.$row['name'].'</strong> - '.$status.'
446
				</td>
447
				<td class="date column-date">
448
					<abbr title="'.date('Y/m/d',strtotime($row['last_modified'])).'">'.date('Y/m/d',strtotime($row['last_modified'])).'</abbr><br>Last Modified
449
				</td>
450
				<td class="ssid column-ssid">
451
					'.$row['identifier'].'
452
				</td>
453
			</tr>';		
454
			return $row_html;
455
		}
456
	}
457
458
	/**
459
	 * Connect to wetu
460
	 */
461
	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...
462
		$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...
463
464
		if(isset($_POST['action']) && $_POST['action'] === 'lsx_import_items' && isset($_POST['type']) && $_POST['type'] === $this->tab_slug && isset($_POST['wetu_id'])){
465
			
466
			$wetu_id = $_POST['wetu_id'];
467
			if(isset($_POST['post_id'])){
468
				$post_id = $_POST['post_id'];	
469
			}else{
470
				$post_id = 0;
471
			}
472
473
			delete_option('wetu_importer_tour_settings');
474 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...
475
				$content = $_POST['content'];
476
				add_option('wetu_importer_tour_settings',$content);
477
			}else{
478
				$content = false;
479
			}
480
481
            $jdata=file_get_contents("http://wetu.com/API/Itinerary/V7/Get?id=".$wetu_id);
482
483 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...
484
            {
485
				$jdata=json_decode($jdata,true);
486
                if(!empty($jdata))
487
                {
488
                	$return = $this->import_row($jdata,$wetu_id,$post_id,$content);
489
                	$this->format_completed_row($return);
490
                	$this->cleanup_posts();
491
                	$this->attach_destination_images($content);
492
                }
493
            }
494
		}
495
	}
496
497
	/**
498
	 * Connect to wetu
499
     *
500
     * @param $data array
501
     * @param $wetu_id string
502
	 */
503
	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...
504
        $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...
505
        $post = array(
506
          'post_type'		=> 'tour',
507
        );
508
509
        //Set the post_content
510
		$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...
511
        if(false !== $importable_content && in_array('description',$importable_content)){
512
            $data_post_content = '';
513
514
            if(isset($data['description'])){
515
                $data_post_content = $data['description'];
516
            }elseif(isset($data['summary'])){
517
                $data_post_content = $data['summary'];
518
            }
519
            $post['post_content'] = $data_post_content;
520
        }
521
522
        //Create or update the post
523
        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...
524
            $post['ID'] = $id;
525
	        $post['post_status'] = 'publish';
526
            $id = wp_update_post($post);
527
            $prev_date = get_post_meta($id,'lsx_wetu_modified_date',true);
528
            update_post_meta($id,'lsx_wetu_modified_date',strtotime($data['last_modified']),$prev_date);
529
        }else{
530
531
            //Set the name
532
            if(isset($data['name'])){
533
                $post_name = wp_unique_post_slug(sanitize_title($data['name']),$id, 'draft', 'tour', 0);
534
            }
535
            $post['post_name'] = $post_name;
536
            $post['post_title'] = $data['name'];
537
            $post['post_status'] = 'publish';
538
            $id = wp_insert_post($post);
539
540
            //Save the WETU ID and the Last date it was modified.
541
            if(false !== $id){
542
                add_post_meta($id,'lsx_wetu_id',$wetu_id);
543
                add_post_meta($id,'lsx_wetu_modified_date',strtotime($data['last_modified']));
544
            }
545
        }
546
547
548
		//Set the price
549
		if(false !== $importable_content && in_array('price',$importable_content)){
550
			$this->set_price($data,$id);
551
		}
552
553
		//Set the Duration
554
		if(false !== $importable_content && in_array('duration',$importable_content)){
555
			$this->set_duration($data,$id);
556
		}
557
558
        if(false !== $importable_content && in_array('itineraries',$importable_content) && isset($data['legs']) && !empty($data['legs'])){
559
            $this->process_itineraries($data,$id,$importable_content);
560
        }
561
562
		if(in_array('map',$importable_content) && isset($data['routes']) && !empty($data['routes'])){
563
			$this->set_map_data($data,$id);
564
		}
565
566
        return $id;
567
	}
568
569
	/**
570
	 * A loop which runs through each leg on the tour.
571
	 */
572
	public function process_itineraries($data,$id,$importable_content) {
573
		$day_counter = 1;
574
		$leg_counter = 0;
575
576
		delete_post_meta($id,'itinerary');
577
578
		if(false !== $importable_content && in_array('accommodation',$importable_content)){
579
			delete_post_meta($id,'accommodation_to_tour');
580
		}
581
		if(false !== $importable_content && in_array('destination',$importable_content)){
582
			delete_post_meta($id,'destination_to_tour');
583
			delete_post_meta($id,'departs_from');
584
			delete_post_meta($id,'ends_in');
585
		}
586
587
		$departs_from = false;
588
		$ends_in = false;
589
590
		foreach($data['legs'] as $leg){
591
592
			if(isset($leg['days']) && !empty($leg['days'])){
593
594
				//Itinerary Accommodation
595
				$current_accommodation = false;
596
				if(false !== $importable_content && in_array('accommodation',$importable_content)){
597
					$current_accommodation = $this->set_accommodation($leg,$id);
598
				}
599
600
				//Itinerary Destination
601
				$current_destination = false;
602
				if(false !== $importable_content && in_array('destination',$importable_content)){
603
					$current_destination = $this->set_destination($leg,$id,$leg_counter);
604
				}
605
606
				//If the Nights are the same mount of days in the array,  then it isnt "By Destination"
607
				if($leg['nights'] === count($leg['days']) || 0 === $leg['itinerary_leg_id']){
608
609
					foreach($leg['days'] as $day){
610
611
						$current_day = array();
612
613
						$current_day['title'] =  esc_attr('Day ','wetu-importer').$day_counter;
614
615
						//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...
616
617
						//Description
618
						if(false !== $importable_content && in_array('itinerary_description',$importable_content) && isset($day['notes'])){
619
							$current_day['description'] = $day['notes'];
620
						}else{
621
							$current_day['description'] = '';
622
						}
623
624
						//Itinerary Gallery
625
						if(false !== $importable_content && in_array('itinerary_gallery',$importable_content) && isset($day['images'])){
626
							$current_day['featured_image'] = '';
627
						}else{
628
							$current_day['featured_image'] = '';
629
						}
630
631
						//Accommodation
632
						if(false !== $current_accommodation){
633
							$current_day['accommodation_to_tour'] = array($current_accommodation);
634
						}else{
635
							$current_day['accommodation_to_tour'] = array();
636
						}
637
638
						//Destination
639
						if(false !== $current_destination){
640
							$current_day['destination_to_tour'] = array($current_destination);
641
						}else{
642
							$current_day['destination_to_tour'] = array();
643
						}
644
645
						//Included
646 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...
647
							$current_day['included'] = $day['included'];
648
						}else{
649
							$current_day['included'] = '';
650
						}
651
652
						//Excluded
653 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...
654
							$current_day['excluded'] = $day['excluded'];
655
						}else{
656
							$current_day['excluded'] = '';
657
						}
658
659
						$this->set_itinerary_day($current_day,$id);
660
						$day_counter++;
661
					}
662
663
				}else{
664
					$day_counter = $day_counter + (int)$leg['nights'];
665
				}
666
667
			}
668
669
			//If we are in the first leg,  and the destination was attached then save it as the departure field.
670
			if( 0 === $leg_counter && false !== $current_destination){
671
				$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...
672
			}
673
674
			//If its the last leg then save it as the ends in.
675
			if( $leg_counter === (count($data['legs'])-2) && false !== $current_destination){
676
				$ends_in = $current_destination;
677
			}
678
			$leg_counter++;
679
		}
680
681
		if(false !== $departs_from){
682
			add_post_meta($id,'departs_from',$departs_from,true);
683
		}
684
		if(false !== $ends_in){
685
			add_post_meta($id,'ends_in',$ends_in,true);
686
		}
687
	}
688
689
	/**
690
	 * Run through your routes and save the points as a KML file.
691
	 */
692
	public function set_map_data($data,$id,$zoom=9) {
693
694
		if(!empty($data['routes'])){
695
696
			delete_post_meta($id,'wetu_map_points');
697
698
			$points = array();
699
700
			foreach($data['routes'] as $route){
701
702
703
				if(isset($route['points']) && '' !== $route['points']){
704
705
					$temp_points = explode(';',$route['points']);
706
					$point_counter = count($temp_points);
707
708
					for ($x = 0; $x <= $point_counter; $x++) {
709
						$y = $x+1;
710
						$points[] = $temp_points[$x].','.$temp_points[$y];
711
						$x++;
712
					}
713
				}
714
			}
715
			if(!empty($points)){
716
				$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...
717
			}
718
		}
719
720
	}
721
722
	// CLASS SPECIFIC FUNCTIONS
723
724
	/**
725
	 * Set the Itinerary Day
726
	 */
727
	public function set_itinerary_day($day,$id) {
728
        $this->save_custom_field($day,'itinerary',$id,false,false);
729
	}
730
731
	/**
732
	 * Set the price
733
	 */
734
	public function set_price($data,$id) {
735
	    //Price
736 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...
737
            $price = preg_replace("/[^0-9,.]/", "", $data['price']);
738
            $this->save_custom_field($price,'price',$id);
739
		}
740
741
		//Price includes
742
		if(isset($data['price_includes']) && ''!== $data['price_includes']){
743
			$this->save_custom_field($data['price_includes'],'included',$id);
744
		}
745
746
        //Price Excludes
747
		if(isset($data['price_excludes']) && ''!== $data['price_excludes']){
748
			$this->save_custom_field($data['price_excludes'],'not_included',$id);
749
		}
750
751
	}
752
753
	/**
754
	 * Set the duration
755
	 */
756
	public function set_duration($data,$id) {
757 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...
758
			$price = $data['days'];
759
			$price = preg_replace("/[^0-9,.]/", "", $price);
760
			$this->save_custom_field($price,'duration',$id);
761
		}
762
	}
763
764
	/**
765
	 * Connects the Accommodation if its available
766
	 */
767
	public function set_accommodation($day,$id) {
768
769
	    $ac_id = false;
770
		$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...
771
		
772
		if(isset($day['content_entity_id']) && !empty($day['content_entity_id'])){
773
774
			if(false !== $this->current_accommodation && !empty($this->current_accommodation) && array_key_exists($day['content_entity_id'],$this->current_accommodation)){
775
                $ac_id = $this->current_accommodation[$day['content_entity_id']];
776
			}else{
777
				$ac_id = wp_insert_post(array(
778
                    'post_type' => 'accommodation',
779
                    'post_status' => 'draft',
780
                    'post_title' => $day['content_entity_id']
781
                ));
782
				$this->save_custom_field($day['content_entity_id'],'lsx_wetu_id',$ac_id);
783
			}
784
785
			if('' !== $ac_id && false !== $ac_id){
786
			    $this->save_custom_field($ac_id,'accommodation_to_tour',$id,false,false);
787
				$this->save_custom_field($id,'tour_to_accommodation',$ac_id,false,false);
788
            }
789
		}
790
		return $ac_id;
791
	}
792
793
	/**
794
	 * Grab all the current accommodation posts via the lsx_wetu_id field.
795
     *
796
     * @param $post_type string
797
     * @return boolean / array
798
	 */
799
	public function find_current_accommodation($post_type='accommodation') {
800
		global $wpdb;
801
		$accommodation = parent::find_current_accommodation($post_type);
802
803
		$return = false;
804
		if(!empty($accommodation)){
805
		    foreach($accommodation as $key => $acc){
806
				$return[$acc->meta_value] = $acc->post_id;
807
            }
808
        }
809
		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...
810
	}
811
812
	/**
813
	 * Grab all the current accommodation posts via the lsx_wetu_id field.
814
     * @return boolean / array
815
	 */
816
	public function find_current_destinations() {
817
		return $this->find_current_accommodation('destination');
818
	}
819
820
	/**
821
	 * Connects the destinations post type
822
	 *
823
	 * @param $day array
824
	 * @param $id string
825
	 * @return boolean / string
826
	 */
827
	public function set_destination($day,$id,$leg_counter) {
828
		$dest_id = false;
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(isset($day['destination_content_entity_id']) && !empty($day['destination_content_entity_id'])){
833
834
			if(false !== $this->current_destinations && !empty($this->current_destinations) && array_key_exists($day['destination_content_entity_id'],$this->current_destinations)){
835
				$dest_id = $this->current_destinations[$day['destination_content_entity_id']];
836
837
				//Check if there is a country asigned.
838
				$potential_id = wp_get_post_parent_id($dest_id);
839
				$country_wetu_id = get_post_meta($potential_id,'lsx_wetu_id',true);
840
				if(false !== $country_wetu_id){
841
					$country_id = $this->set_country($country_wetu_id, $id);
842
                }
843
844
			}else {
845
846
				$destination_json = file_get_contents("http://wetu.com/API/Pins/".$this->api_key."/Get?ids=" . $day['destination_content_entity_id']);
847
848
				if ($destination_json) {
849
					$destination_data = json_decode($destination_json, true);
850
851
					if (!empty($destination_data) && !isset($destination_data['error'])) {
852
853
					    $destination_title = $day['destination_content_entity_id'];
854
855
					    if(isset($destination_data[0]['name'])){
856
							$destination_title = $destination_data[0]['name'];
857
                        }
858
859
					    if(isset($destination_data[0]['map_object_id']) && isset($destination_data[0]['position']['country_content_entity_id'])
860
                            && $destination_data[0]['map_object_id'] !== $destination_data[0]['position']['country_content_entity_id']){
861
862
							$country_id = $this->set_country($destination_data[0]['position']['country_content_entity_id'], $id);
863
                        }
864
865
                        $dest_post = array(
866
							'post_type' => 'destination',
867
							'post_status' => 'draft',
868
							'post_title' => $destination_title
869
						);
870
871
					    if(false !== $country_id){
872
							$dest_post['post_parent'] = $country_id;
873
                        }
874
						$dest_id = wp_insert_post($dest_post);
875
876
						//Make sure we register the
877
						$this->current_destinations[$day['destination_content_entity_id']] = $dest_id;
878
879
						$this->save_custom_field($day['destination_content_entity_id'], 'lsx_wetu_id', $dest_id);
880
					}
881
				}
882
			}
883
884
			if ('' !== $dest_id && false !== $dest_id) {
885
				$this->save_custom_field($dest_id, 'destination_to_tour', $id, false, false);
886
				$this->save_custom_field($id, 'tour_to_destination', $dest_id, false, false);
887
				$this->cleanup_posts[$dest_id] = 'tour_to_destination';
888
889
				// Save the first destination so we can grab the tour featured image and banner
890
				if(0 === $leg_counter){
891
				    $this->destination_images[$id] = array($dest_id,$day['destination_content_entity_id']);
892
                }
893
894
				//Add this relation info so we can make sure certain items are set as countries.
895
				if(0 !== $country_id && false !== $country_id){
896
                    $this->relation_meta[$dest_id] = $country_id;
897
					$this->relation_meta[$country_id] = 0;
898
                }else{
899
					$this->relation_meta[$dest_id] = 0;
900
                }
901
			}
902
		}
903
		return $dest_id;
904
	}
905
906
	/**
907
	 * Connects the destinations post type
908
	 *
909
	 * @param $dest_id string
910
     * @param $country_id array
911
	 * @param $id string
912
     *
913
     * @return string
914
	 */
915
	public function set_country($country_wetu_id, $id) {
916
	    $country_id = false;
917
		$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...
918
919
        if (false !== $this->current_destinations && !empty($this->current_destinations) && array_key_exists($country_wetu_id, $this->current_destinations)) {
920
            $country_id = $this->current_destinations[$country_wetu_id];
921
        } else {
922
923
            $country_json = file_get_contents("http://wetu.com/API/Pins/".$this->api_key."/Get?ids=" . $country_wetu_id);
924
925
            if ($country_json) {
926
                $country_data = json_decode($country_json, true);
927
928
                if (!empty($country_data) && !isset($country_data['error'])) {
929
930
					//Format the title of the destination if its available,  otherwise default to the WETU ID.
931
                    $country_title = $country_wetu_id;
932
                    if (isset($country_data[0]['name'])) {
933
						$country_title = $country_data[0]['name'];
934
                    }
935
936
					$country_id = wp_insert_post(array(
937
                        'post_type' => 'destination',
938
                        'post_status' => 'draft',
939
                        'post_title' => $country_title
940
                    ));
941
					//add the country to the current destination stack
942
					$this->current_destinations[$country_wetu_id] = $country_id;
943
944
					//Save the wetu field
945
                    $this->save_custom_field($country_wetu_id, 'lsx_wetu_id', $country_id);
946
                }
947
            }
948
        }
949
950
        if ('' !== $country_id && false !== $country_id) {
951
            $this->save_custom_field($country_id, 'destination_to_tour', $id, false, false);
952
            $this->save_custom_field($id, 'tour_to_destination', $country_id, false, false);
953
			$this->cleanup_posts[$country_id] = 'tour_to_destination';
954
955
            return $country_id;
956
        }
957
	}
958
959
	/**
960
	 * Connects the destinations post type
961
	 *
962
	 * @param $dest_id string
963
	 * @param $country_id array
964
	 * @param $id string
965
	 *
966
	 * @return string
967
	 */
968
	public function attach_destination_images($importable_content=array()) {
969
	    if(false !== $this->destination_images){
970
971
	        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...
972
973
				$url = 'https://wetu.com/API/Pins/' . $this->api_key;
974
				$url_qs = '';
975
976
				$jdata = file_get_contents($url . '/Get?' . $url_qs . '&ids=' . $destination[1]);
977
				if ($jdata) {
978
					$adata = json_decode($jdata, true);
979
980
					if (!empty($adata)) {
981
						$this->find_attachments($destination[0]);
982
983
						//Set the featured image
984
						if (false !== $importable_content && in_array('featured_image', $importable_content)) {
985
							$this->set_featured_image($adata, $tour);
986
						}
987
						if (false !== $importable_content && in_array('banner_image', $importable_content)) {
988
							$this->set_banner_image($adata, $tour);
989
						}
990
					}
991
				}
992
            }
993
        }
994
	}
995
}