Completed
Push — master ( 3704f2...8a71c5 )
by Warwick
03:20
created

WETU_Importer_Admin::cleanup_posts()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 4
nop 0
1
<?php
2
/**
3
 * @package   WETU_Importer_Admin
4
 * @author    LightSpeed
5
 * @license   GPL-2.0+
6
 * @link      
7
 * @copyright 2016 LightSpeed
8
 **/
9
10
class WETU_Importer_Admin extends WETU_Importer {
11
12
	/**
13
	 * The previously attached images
14
	 *
15
	 * @var      array()
16
	 */
17
	public $found_attachments = array();	
18
19
	/**
20
	 * The gallery ids for the found attachements
21
	 *
22
	 * @var      array()
23
	 */
24
	public $gallery_meta = array();
25
26
	/**
27
	 * The post ids to clean up (make sure the connected items are only singular)
28
	 *
29
	 * @var      array()
30
	 */
31
	public $cleanup_posts = array();
32
33
	/**
34
	 * the featured image id
35
	 *
36
	 * @var      int
37
	 */
38
	public $featured_image = false;
39
40
	/**
41
	 * the banner image
42
	 *
43
	 * @var      int
44
	 */
45
	public $banner_image = false;	
46
47
	/**
48
	 * Initialize the plugin by setting localization, filters, and administration functions.
49
	 *
50
	 * @since 1.0.0
51
	 *
52
	 * @access private
53
	 */
54
	public function __construct() {
55
		add_action( 'admin_enqueue_scripts', array($this,'admin_scripts') ,11 );
56
		add_action( 'admin_menu', array( $this, 'register_importer_page' ),20 );
57
	}
58
59
	/**
60
	 * Registers the admin page which will house the importer form.
61
	 */
62
	public function register_importer_page() {
63
		add_submenu_page( 'tour-operator',esc_html__( 'Importer', 'tour-operator' ), esc_html__( 'Importer', 'tour-operator' ), 'manage_options', 'wetu-importer', array( $this, 'display_page' ) );
64
	}
65
66
	/**
67
	 * Enqueue the JS needed to contact wetu and return your result.
68
	 */
69
	public function admin_scripts() {
70
		if ( defined( 'WP_DEBUG' ) && true === WP_DEBUG ) {
71
			$min = '';
0 ignored issues
show
Unused Code introduced by
$min is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
72
		} else {
73
			$min = '.min';
0 ignored issues
show
Unused Code introduced by
$min is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
74
		}
75
		$min = '';
76
77
		if(is_admin() && isset($_GET['page']) && $this->plugin_slug === $_GET['page']){
78
			wp_enqueue_script( 'wetu-importers-script', WETU_IMPORTER_URL . 'assets/js/wetu-importer' . $min . '.js', array( 'jquery' ), WETU_IMPORTER_VER, true );
79
			wp_localize_script( 'wetu-importers-script', 'lsx_tour_importer_params', array(
80
			'ajax_url' => admin_url('admin-ajax.php'),
81
			) );			
82
		}
83
	}			
84
85
	/**
86
	 * Display the importer administration screen
87
	 */
88
	public function display_page() {
89
        ?>
90
        <div class="wrap">
91
            <?php screen_icon(); ?>
92
93
            <?php if(!isset($_GET['tab'])){ ?>
94
	            <h2><?php _e('Welcome to the LSX Wetu Importer','wetu-importer'); ?></h2>
95
	            <p>If this is the first time you are running the import, then follow the steps below.</p>
96
	            <ul>
97
                    <li>Step 1 - Import your <a href="<?php echo admin_url('admin.php'); ?>?page=<?php echo $this->plugin_slug; ?>&tab=tour"><?php _e('Tours','wetu-importer'); ?></a></li>
98
	            	<li>Step 2 - The tour import will have created draft <a href="<?php echo admin_url('admin.php'); ?>?page=<?php echo $this->plugin_slug; ?>&tab=accommodation"><?php _e('accommodation','wetu-importer'); ?></a> that will need to be imported.</li>
99
                    <li>Step 3 - Lastly import the <a href="<?php echo admin_url('admin.php'); ?>?page=<?php echo $this->plugin_slug; ?>&tab=destination"><?php _e('destinations','wetu-importer'); ?></a> draft posts created during the previous two steps.</li>
100
	            </ul>
101
102
		            <h3><?php _e('Additional Tools','wetu-importer'); ?></h3>
103
		            <ul>
104
		            	<li><a href="<?php echo admin_url('admin.php'); ?>?page=<?php echo $this->plugin_slug; ?>&tab=connect_accommodation"><?php _e('Connect Accommodation','wetu-importer'); ?></a> <small><?php _e('If you already have accommodation, you can "connect" it with its WETU counter part, so it works with the importer.','wetu-importer'); ?></small></li>
105
		            	<?php if(class_exists('Lsx_Banners')){ ?>
106
		            		<li><a href="<?php echo admin_url('admin.php'); ?>?page=<?php echo $this->plugin_slug; ?>&tab=banners"><?php _e('Sync High Res Banner Images','wetu-importer'); ?></a></li>
107
		            	<?php } ?>
108
		            </ul> 
109
	             	            
110
            <?php } else {
111
            	do_action('lsx_tour_importer_admin_tab_'.$_GET['tab']);
112
            } ?>
113
        </div>
114
        <?php
115
	}
116
117
	/**
118
	 * The header of the item list
119
	 */
120
	public function table_header() {
121
	?>
122
		<thead>
123
			<tr>
124
				<th style="" class="manage-column column-cb check-column" id="cb" scope="col">
125
					<label for="cb-select-all-1" class="screen-reader-text">Select All</label>
126
					<input type="checkbox" id="cb-select-all-1">
127
				</th>
128
				<th style="" class="manage-column column-title " id="title" style="width:50%;" scope="col">Title</th>
129
				<th style="" class="manage-column column-date" id="date" scope="col">Date</th>
130
				<th style="" class="manage-column column-ssid" id="ssid" scope="col">WETU ID</th>
131
			</tr>
132
		</thead>
133
	<?php 
134
	}	
135
136
	/**
137
	 * The footer of the item list
138
	 */
139
	public function table_footer() {
140
	?>
141
		<tfoot>
142
			<tr>
143
				<th style="" class="manage-column column-cb check-column" id="cb" scope="col">
144
					<label for="cb-select-all-1" class="screen-reader-text">Select All</label>
145
					<input type="checkbox" id="cb-select-all-1">
146
				</th>
147
				<th style="" class="manage-column column-title" scope="col">Title</th>
148
				<th style="" class="manage-column column-date" scope="col">Date</th>
149
				<th style="" class="manage-column column-ssid" scope="col">WETU ID</th>
150
			</tr>
151
		</tfoot>
152
	<?php 
153
	}
154
155
	/**
156
	 * set_taxonomy with some terms
157
	 */
158
	public function set_taxonomy($taxonomy,$terms,$id) {
0 ignored issues
show
Unused Code introduced by
The parameter $terms is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
159
        $result=array();
160
        if(!empty($data))
0 ignored issues
show
Bug introduced by
The variable $data seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
161
        {
162
            foreach($data as $k)
163
            {
164
                if($id)
165
                {
166
                    if(!$term = term_exists(trim($k), $tax))
167
                    {
168
                        $term = wp_insert_term(trim($k), $tax);
0 ignored issues
show
Bug introduced by
The variable $tax does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
169
                        if ( is_wp_error($term) )
170
                        {
171
                            echo $term->get_error_message();
172
                        }
173
                        else
174
                        {
175
                            wp_set_object_terms( $id, intval($term['term_id']), $taxonomy,true);
176
                        }
177
                    }
178
                    else
179
                    {
180
                        wp_set_object_terms( $id, intval($term['term_id']), $taxonomy,true);
181
                    }
182
                }
183
                else
184
                {
185
                    $result[]=trim($k);
186
                }
187
            }
188
        }
189
        return $result;
190
	}
191
192
	/**
193
	 * set_taxonomy with some terms
194
	 */
195
	public function team_member_checkboxes($selected=array()) {
196
		if(post_type_exists('team')) { ?>
197
    		<ul>
198
    			<?php
199
    				$team_args=array(
200
    					'post_type'	=>	'team',
201
    					'post_status' => 'publish',
202
    					'nopagin' => true,
203
    					'fields' => 'ids'
204
    				);
205
    				$team_members = new WP_Query($team_args);
206
    					if($team_members->have_posts()){
207
    						foreach($team_members->posts as $member){ ?>
208
    							<li><input class="team" <?php $this->checked($selected,$member); ?> type="checkbox" value="<?php echo $member; ?>" /> <?php echo get_the_title($member); ?></li>
0 ignored issues
show
Documentation introduced by
$selected is of type array, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
209
    						<?php }
210
    					}else{ ?>
211
    							<li><input class="team" type="checkbox" value="0" /> <?php _e('None','wetu-importer'); ?></li>
212
    					<?php }
213
    				?>
214
    		</ul>
215
    	<?php }		
216
	}
217
218
	/**
219
	 * set_taxonomy with some terms
220
	 */
221
	public function taxonomy_checkboxes($taxonomy=false,$selected=array()) {
222
		$return = '';
223
		if(false !== $taxonomy){
224
			$return .= '<ul>';
225
			$terms = get_terms(array('taxonomy'=>$taxonomy,'hide_empty'=>false));
226
227
			if(!is_wp_error($terms)){
228
				foreach($terms as $term){
229
					$return .= '<li><input class="'.$taxonomy.'" '.$this->checked($selected,$term->term_id,false).' type="checkbox" value="'.$term->term_id.'" /> '.$term->name.'</li>';
0 ignored issues
show
Documentation introduced by
$selected is of type array, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
230
				}
231
			}else{
232
				$return .= '<li><input type="checkbox" value="" /> '.__('None','wetu-importer').'</li>';
233
			}
234
			$return .= '</ul>';
235
		}
236
		return $return;		
237
	}
238
239
	/**
240
	 * Saves the room data
241
	 */
242
	public function save_custom_field($value=false,$meta_key,$id,$decrease=false,$unique=true) {
243
		if(false !== $value){
244
			if(false !== $decrease){
245
				$value = intval($value);
246
				$value--;
247
			}
248
			$prev = get_post_meta($id,$meta_key,true);
249
250
			if(false !== $id && '0' !== $id && false !== $prev && true === $unique){
251
				update_post_meta($id,$meta_key,$value,$prev);
252
			}else{
253
				add_post_meta($id,$meta_key,$value,$unique);
254
			}
255
		}
256
	}
257
258
	/**
259
	 * grabs any attachments for the current item
260
	 */
261
	public function find_attachments($id=false) {
262
		if(false !== $id){
263
			if(empty($this->found_attachments)){
264
265
		    	$attachments_args = array(
266
		    			'post_parent' => $id,
267
		    			'post_status' => 'inherit',
268
		    			'post_type' => 'attachment',
269
		    			'order' => 'ASC',
270
                        'nopagin' => 'true',
271
                        'posts_per_page' => '-1'
272
		    	);   	
273
		    	 
274
		    	$attachments = new WP_Query($attachments_args);
275
		    	if($attachments->have_posts()){
276
		    		foreach($attachments->posts as $attachment){
277
		    			$this->found_attachments[$attachment->ID] = str_replace(array('.jpg','.png','.jpeg'),'',$attachment->post_title);
278
		    			$this->gallery_meta[] = $attachment->ID;
279
		    		}
280
		    	}
281
			}
282
		}
283
	}
284
285
	/**
286
	 * Checks to see if an item is checked.
287
     *
288
     * @param $haystack array|string
289
     * @param $needle string
290
     * @param $echo bool
291
	 */
292 View Code Duplication
	public function checked($haystack=false,$needle='',$echo=true) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
293
	    $return = $this->itemd($haystack,$needle,'checked');
294
	    if('' !== $return) {
295
			if (true === $echo) {
296
				echo $return;
297
			} else {
298
				return $return;
299
			}
300
		}
301
	}
302
303
	/**
304
	 * Checks to see if an item is checked.
305
	 *
306
	 * @param $haystack array|string
307
	 * @param $needle string
308
     * @param $echo bool
309
	 */
310 View Code Duplication
	public function selected($haystack=false,$needle='',$echo=true) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
311
		$return = $this->itemd($haystack,$needle,'selected');
312
		if('' !== $return) {
313
			if (true === $echo) {
314
				echo $return;
315
			} else {
316
				return $return;
317
			}
318
		}
319
	}
320
321
	/**
322
	 * Checks to see if an item is selected. If $echo is false,  it will return the $type if conditions are true.
323
	 *
324
	 * @param $haystack array|string
325
	 * @param $needle string
326
     * @param $type string
327
     * @param $wrap bool
328
     * @return $html string
0 ignored issues
show
Documentation introduced by
The doc-type $html could not be parsed: Unknown type name "$html" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
329
	 */
330
	public function itemd($haystack=false,$needle='',$type='',$wrap=true) {
331
		$html = '';
332
		if('' !== $type) {
333
			if (!is_array($haystack)) {
334
				$haystack = array($haystack);
335
			}
336
			if (in_array($needle, $haystack)) {
337
			    if(true === $wrap || 'true' === $wrap) {
338
					$html = $type . '"' . $type . '"';
339
				}else{
340
					$html = $type;
341
                }
342
			}
343
		}
344
        return $html;
345
346
	}
347
348
	/**
349
	 * Displays the importers navigation
350
	 *
351
	 * @param $tab string
352
	 */
353
	public function navigation($tab='') {
354
        $post_types = array(
355
            'tour'              => esc_attr('Tours','wetu-importer'),
356
            'accommodation'     => esc_attr('Accommodation','wetu-importer'),
357
            'destination'       => esc_attr('Destinations','wetu-importer'),
358
        );
359
360
361
		echo '<div class="wet-navigation"><div class="subsubsub"><a class="'.$this->itemd($tab,'','current',false).'" href="'.admin_url('admin.php').'?page='.$this->plugin_slug.'">'.esc_attr('Home','wetu-importer').'</a>';
0 ignored issues
show
Documentation introduced by
$tab is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
362
		foreach($post_types as $post_type => $label){
363
		    echo ' | <a class="'.$this->itemd($tab,$post_type,'current',false).'" href="'.admin_url('admin.php').'?page='.$this->plugin_slug.'&tab='.$post_type.'">'.$label.'</a>';
0 ignored issues
show
Documentation introduced by
$tab is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
364
        }
365
        echo '</div><br clear="both"/></div>';
366
	}
367
368
	/**
369
	 * Grabs the custom fields,  and resaves an array of unique items.
370
	 */
371
	public function cleanup_posts() {
372
	    if(!empty($this->cleanup_posts)){
373
	        foreach($this->cleanup_posts as $id => $key) {
374
				$prev_items = get_post_meta($id, $key, false);
375
				$new_items = array_unique($prev_items);
376
				delete_post_meta($id, $key);
377
				foreach($new_items as $new_item) {
378
					add_post_meta($id, $key, $new_item, false);
379
				}
380
			}
381
        }
382
	}
383
}
384
$wetu_importer_admin = new WETU_Importer_Admin();