PluginProbe
Export All Posts, Products, Orders & Users | WP Ultimate Exporter | WordPress CSV Export / trunk
Export All Posts, Products, Orders & Users | WP Ultimate Exporter | WordPress CSV Export vtrunk
3.0 2.24.2 2.24.1 1.7.2 1.7.3 1.7.4 1.7.5 1.7.6 1.7.7 1.7.8 1.7.9 2.0 2.0.1 2.1 2.1.1 2.1.2 2.10 2.11 2.12 2.13 2.14 2.15 2.16 2.16.1 2.16.2 All 96 releases
wp-ultimate-exporter / exportExtensions / ExportExtension.php

ExportExtension.php in Export All Posts, Products, Orders & Users | WP Ultimate Exporter | WordPress CSV Export trunk, at exportExtensions/ExportExtension.php

3,819 lines 141.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * WP Ultimate Exporter plugin file.
4 *
5 * Copyright (C) 2010-2020, Smackcoders Inc - info@smackcoders.com
6 */
7
8 namespace Smackcoders\SMEXP;
9
10 if (!defined('ABSPATH'))
11 exit; // Exit if accessed directly
12 $parent_autoload_path = WP_PLUGIN_DIR . '/wp-ultimate-csv-importer/vendor/autoload.php';
13 if (file_exists($parent_autoload_path)) {
14 require_once $parent_autoload_path;
15 }
16 use PhpOffice\PhpSpreadsheet\Spreadsheet;
17 use PhpOffice\PhpSpreadsheet\IOFactory;
18 // require_once dirname(__FILE__) . '/WPQueryExport.php';
19 // require_once dirname(__FILE__) . '/WPQueryExport.php';
20
21 $mapping_extension_candidates = array(
22 '\Smackcoders\UCI\Core\MappingExtension',
23 '\Smackcoders\WCSV\MappingExtension',
24 '\Smackcoders\FCSV\MappingExtension',
25 );
26 $parent_mapping_loaded = false;
27 foreach ($mapping_extension_candidates as $mapping_class) {
28 if (class_exists($mapping_class)) {
29 $parent_mapping_loaded = true;
30 break;
31 }
32 }
33 if (!$parent_mapping_loaded) {
34 $mapping_paths = array(
35 WP_PLUGIN_DIR . '/wp-ultimate-csv-importer/extensionModules/MappingExtension.php',
36 WP_PLUGIN_DIR . '/wp-ultimate-csv-importer-pro/extensionModules/MappingExtension.php',
37 );
38 foreach ($mapping_paths as $mapping_path) {
39 if (file_exists($mapping_path)) {
40 require_once $mapping_path;
41 break;
42 }
43 }
44 }
45
46 if (class_exists('\Smackcoders\UCI\Core\MappingExtension')) {
47 class ExportExtensionParent extends \Smackcoders\UCI\Core\MappingExtension {}
48 } elseif (class_exists('\Smackcoders\WCSV\MappingExtension')) {
49 class ExportExtensionParent extends \Smackcoders\WCSV\MappingExtension {}
50 } elseif (class_exists('\Smackcoders\FCSV\MappingExtension')) {
51 class ExportExtensionParent extends \Smackcoders\FCSV\MappingExtension {}
52 }
53
54 if (class_exists('Smackcoders\SMEXP\ExportExtensionParent')) {
55
56 class ExportExtension extends ExportExtensionParent
57 {
58 public $allacf;
59
60 public $allpodsfields;
61
62 public $alltoolsetfields;
63
64 public $typeOftypesField;
65 public $offset = 0;
66 public $checkSplit;
67 public $mode;
68 public $totalRowCount;
69 public $response = array();
70 public $headers = array();
71 public $module;
72 public $exportType = 'csv';
73 public $optionalType = null;
74 public $conditions = array();
75 public $eventExclusions = array();
76 public $fileName;
77 public $data = array();
78 public $heading = true;
79 public $delimiter = ',';
80 public $enclosure = '"';
81 public $auto_preferred = ",;\t.:|";
82 public $output_delimiter = ',';
83 public $linefeed = "\r\n";
84 public $export_mode;
85 public $export_log = array();
86 public $limit;
87 protected static $instance = null, $mapping_instance, $metabox_export, $jet_reviews_export, $jet_book_export, $jetengine_export, $export_handler, $post_export, $woocom_export, $review_export, $ecom_export, $learnpress_export, $wpquery_export, $edd_export,$surecart_export;
88 protected $plugin, $activateCrm, $crmFunctionInstance;
89 public $plugisnScreenHookSuffix = null;
90 public $random_data = '';
91
92 public static function getInstance()
93 {
94 if (null == self::$instance) {
95 self::$instance = new self;
96 ExportExtension::$export_handler = ExportHandler::getInstance();
97 ExportExtension::$post_export = PostExport::getInstance();
98 ExportExtension::$woocom_export = WooCommerceExport::getInstance();
99 ExportExtension::$review_export = CustomerReviewExport::getInstance();
100 ExportExtension::$learnpress_export = LearnPressExport::getInstance();
101 ExportExtension::$jetengine_export = JetEngineExport::getInstance();
102 ExportExtension::$jet_book_export = JetBookingExport::getInstance();
103 ExportExtension::$jet_reviews_export = JetReviewsExport::getInstance();
104 ExportExtension::$metabox_export = metabox::getInstance();
105 ExportExtension::$edd_export = EDDExport::getInstance();
106 ExportExtension::$surecart_export = SureCartExport::getInstance();
107 // ExportExtension::$wpquery_export = WPQueryExport::getInstance();
108
109 self::$instance->doHooks();
110 }
111 return self::$instance;
112 }
113
114 public function doHooks()
115 {
116 $plugin_pages = ['com.smackcoders.csvimporternew.menu'];
117 require_once WP_PLUGIN_DIR . '/wp-ultimate-exporter/wp-exp-hooks.php';
118 global $plugin_ajax_hooks;
119
120 $request_page = isset($_REQUEST['page']) ? $_REQUEST['page'] : '';
121 $request_action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
122 if (in_array($request_page, $plugin_pages) || in_array($request_action, $plugin_ajax_hooks)) {
123 add_action('wp_ajax_parse_data', array(
124 $this,
125 'parseData'
126 ));
127 add_action('wp_ajax_nopriv_parse_data', array(
128 $this,
129 'parseData'
130 ));
131 add_action('wp_ajax_total_records', array(
132 $this,
133 'totalRecords'
134 ));
135 add_action('wp_ajax_get_download', array(
136 $this,
137 'downloadFunction'
138 ));
139 }
140 }
141
142 public function downloadFunction()
143 {
144
145 check_ajax_referer('smack-ultimate-csv-importer', 'securekey');
146
147 //Vulnerability fix - Arbitrary file download
148 if (!is_user_logged_in() || !current_user_can('administrator')) {
149 wp_die('You do not have sufficient permissions to access this file.');
150 }
151
152 $file_name = sanitize_file_name($_POST['fileName'] ?? '');
153 $file_path = $_POST['filePath'] ?? '';
154 $random_folder = wp_generate_password(16, false); // 16-character random folder name
155
156 $allowed_directory = wp_upload_dir()['basedir'] . '/smack_uci_uploads/exports/'; // Example allowed directory
157
158 $real_file_path = realpath($file_path);
159 $real_allowed_directory = realpath($allowed_directory);
160
161 if (strpos($real_file_path, $real_allowed_directory) !== 0) {
162 wp_die('Invalid file path or file not found.', 'Error', ['response' => 400]);
163 }
164
165 header('Content-Description: File Transfer');
166 header('Content-Type: application/octet-stream');
167 header('Content-Disposition: attachment; filename="' . $file_name . '"');
168 header('Content-Transfer-Encoding: binary');
169 header('Expires: 0');
170 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
171 header('Pragma: public');
172 header('Content-Length: ' . filesize($real_file_path));
173 ob_clean();
174 flush();
175 readfile($real_file_path);
176 wp_die();
177
178 }
179
180 public function totalRecords()
181 {
182 // Log BEFORE nonce check to see if function is called
183 $debug_log = dirname(__FILE__) . '/debug_export.txt';
184 file_put_contents($debug_log, "=== totalRecords called at " . date('Y-m-d H:i:s') . " ===\n", FILE_APPEND);
185 file_put_contents($debug_log, "POST data: " . print_r($_POST, true) . "\n", FILE_APPEND);
186
187 if (!is_user_logged_in() || !current_user_can('manage_options')) {
188 wp_send_json_error(['message' => 'Unauthorized access.'], 403);
189 return;
190 }
191
192 check_ajax_referer('smack-ultimate-csv-importer', 'securekey');
193 global $wpdb;
194 $module = sanitize_text_field($_POST['module']);
195 $optionalType = isset($_POST['optionalType']) ? sanitize_text_field($_POST['optionalType']) : '';
196 file_put_contents(dirname(__FILE__) . '/debug_export.txt', "After nonce check - TotalRecords: $module, $optionalType\n", FILE_APPEND);
197 // Check for EDD modules first to avoid incorrect reassignment
198 if ($module == 'EDD_CUSTOMERS' || $module == 'EDD_DISCOUNTS' || $module == 'EDD_ORDERS' || $module == 'EDD_DOWNLOADS') {
199 $log_file = dirname(__FILE__) . '/smack_debug_edd.txt';
200 file_put_contents($log_file, "Entering EDD block: module=$module\n", FILE_APPEND);
201
202 // Check if EDD tables exist (more robust than class/plugin checks in AJAX)
203 $table_check = $wpdb->get_var("SHOW TABLES LIKE '{$wpdb->prefix}edd_customers'");
204 if ($table_check != $wpdb->prefix . 'edd_customers') {
205 file_put_contents($log_file, "EDD tables not found\n", FILE_APPEND);
206 echo wp_json_encode(0);
207 wp_die();
208 }
209
210 $total = 0;
211 if ($module == 'EDD_CUSTOMERS') {
212 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}edd_customers");
213 } elseif ($module == 'EDD_DISCOUNTS') {
214 if (class_exists('\\EDD\\Orders\\Order_Query')) {
215 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}edd_adjustments WHERE type = 'discount'");
216 } else {
217 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}edd_discounts");
218 }
219 } elseif ($module == 'EDD_ORDERS') {
220 if (class_exists('\\EDD\\Orders\\Order_Query')) {
221 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}edd_orders");
222 } else {
223 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}posts WHERE post_type = 'edd_payment' AND post_status != 'trash'");
224 }
225 } elseif ($module == 'EDD_DOWNLOADS') {
226 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}posts WHERE post_type = 'download' AND post_status IN ('publish','draft','future','private','pending')");
227 }
228
229 file_put_contents($log_file, "Module: $module, Count: $total\n", FILE_APPEND);
230 echo wp_json_encode((int) $total);
231 wp_die();
232 }
233 if($optionalType == 'SURECART_PRODUCTS' || $optionalType == 'SURECART_CUSTOMERS' || $optionalType == 'SURECART_COUPONS'){
234 if ($optionalType == 'SURECART_PRODUCTS') {
235 $optionalType = 'sc_product';
236 } elseif ($optionalType == 'SURECART_CUSTOMERS') {
237 $optionalType = 'sc_customer';
238 } elseif ($optionalType == 'SURECART_COUPONS') {
239 $optionalType = 'sc_coupon';
240 }
241 // error_log('this exporter called'.PHP_EOL);
242 if (is_plugin_active('surecart/surecart.php')) {
243 $model_mapping = [
244 'sc_product' => '\SureCart\Models\Product',
245 'sc_customer' => '\SureCart\Models\Customer',
246 'sc_coupon' => '\SureCart\Models\Coupon',
247 ];
248 if (array_key_exists($optionalType, $model_mapping)) {
249 $model_class = $model_mapping[$optionalType];
250 if (class_exists($model_class)) {
251 $collection = $model_class::paginate(['per_page' => 1]);
252 $response = $collection->total();
253 echo wp_json_encode($response);
254 wp_die();
255 }
256 }
257 }
258 }
259
260 if ($module == 'WooCommerceOrders') {
261 $module = 'shop_order';
262 } elseif ($module == 'WooCommerceCoupons') {
263 $module = 'shop_coupon';
264 } elseif ($module == 'WooCommerceRefunds') {
265 $module = 'shop_order_refund';
266 } elseif ($module == 'WooCommerceVariations') {
267 $module = 'product_variation';
268 } elseif ($module == 'WPeCommerceCoupons') {
269 $module = 'wpsc-coupon';
270 } elseif ($module == 'Users') {
271 $get_available_user_ids = "select DISTINCT ID from $wpdb->users u join $wpdb->usermeta um on um.user_id = u.ID";
272 $availableUsers = $wpdb->get_col($get_available_user_ids);
273 $total = count($availableUsers);
274 return $total;
275 } elseif ($module == 'Tags') {
276 $get_all_terms = get_tags('hide_empty=0');
277 return count($get_all_terms);
278 wp_die();
279 } elseif ($module == 'Categories') {
280 $get_all_terms = get_categories('hide_empty=0');
281 return count($get_all_terms);
282 wp_die();
283 } elseif ($module == 'CustomPosts' && $optionalType == 'nav_menu_item') {
284 $get_menu_ids = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}terms AS t LEFT JOIN {$wpdb->prefix}term_taxonomy AS tt ON tt.term_id = t.term_id WHERE tt.taxonomy = 'nav_menu' ", ARRAY_A);
285 echo wp_json_encode(count($get_menu_ids));
286 wp_die();
287 }
288 // Check if CustomPosts is actually an EDD module
289 elseif ($module == 'CustomPosts' && in_array($optionalType, ['EDD_CUSTOMERS', 'EDD_DISCOUNTS', 'EDD_ORDERS', 'EDD_DOWNLOADS'])) {
290 // Reassign module to the EDD type so it gets handled by the EDD logic above
291 $module = $optionalType;
292 file_put_contents(dirname(__FILE__) . '/debug_export.txt', "CustomPosts with EDD optionalType: $module\n", FILE_APPEND);
293
294 // Check if EDD tables exist
295 $table_check = $wpdb->get_var("SHOW TABLES LIKE '{$wpdb->prefix}edd_customers'");
296 if ($table_check != $wpdb->prefix . 'edd_customers') {
297 file_put_contents(dirname(__FILE__) . '/debug_export.txt', "EDD tables not found\n", FILE_APPEND);
298 echo wp_json_encode(0);
299 wp_die();
300 }
301
302 $total = 0;
303 if ($module == 'EDD_CUSTOMERS') {
304 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}edd_customers");
305 } elseif ($module == 'EDD_DISCOUNTS') {
306 if (class_exists('\\EDD\\Orders\\Order_Query')) {
307 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}edd_adjustments WHERE type = 'discount'");
308 } else {
309 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}edd_discounts");
310 }
311 } elseif ($module == 'EDD_ORDERS') {
312 if (class_exists('\\EDD\\Orders\\Order_Query')) {
313 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}edd_orders");
314 } else {
315 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}posts WHERE post_type = 'edd_payment' AND post_status != 'trash'");
316 }
317 } elseif ($module == 'EDD_DOWNLOADS') {
318 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}posts WHERE post_type = 'download' AND post_status IN ('publish','draft','future','private','pending')");
319 }
320
321 file_put_contents(dirname(__FILE__) . '/debug_export.txt', "EDD Module: $module, Count: $total\n", FILE_APPEND);
322 echo wp_json_encode((int) $total);
323 wp_die();
324 }
325 // elseif($module == 'CustomPosts' && $optionalType == 'widgets'){
326 // echo wp_json_encode(1);
327 // wp_die();
328 // }
329 else {
330 $optional_type = NULL;
331 if ($module == 'CustomPosts') {
332 $optional_type = $optionalType;
333 }
334 $module = ExportExtension::$post_export->import_post_types($module, $optional_type);
335 file_put_contents(dirname(__FILE__) . '/debug_export.txt', "PostImport: module=$module\n", FILE_APPEND);
336 }
337
338 if ($module == 'EDD_DOWNLOADS') {
339 $module = 'download';
340 }
341 if ($module == 'EDD_ORDERS') {
342 if (class_exists('\\EDD\\Orders\\Order_Query')) {
343 $module = 'edd_order';
344 } else {
345 $module = 'edd_payment';
346 }
347 }
348 if ($module == 'EDD_CUSTOMERS' || $module == 'EDD_DISCOUNTS') {
349 file_put_contents(dirname(__FILE__) . '/debug_export.txt', "Entering EDD_CUSTOMERS/DISCOUNTS block\n", FILE_APPEND);
350 if (!class_exists('Easy_Digital_Downloads')) {
351 file_put_contents(dirname(__FILE__) . '/debug_export.txt', "EDD Class not found\n", FILE_APPEND);
352 echo wp_json_encode(0);
353 wp_die();
354 }
355 if ($module == 'EDD_CUSTOMERS') {
356 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}edd_customers");
357 file_put_contents(dirname(__FILE__) . '/debug_export.txt', "EDD_CUSTOMERS count query: $total\n", FILE_APPEND);
358 } else {
359 if (class_exists('\\EDD\\Orders\\Order_Query')) {
360 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}edd_adjustments WHERE type = 'discount'");
361 } else {
362 $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}edd_discounts");
363 }
364 }
365 echo wp_json_encode((int) $total);
366 wp_die();
367 }
368 // JetBooking module logic
369 if ($module == 'JetBooking') {
370 if (!is_plugin_active('jet-booking/jet-booking.php')) {
371 echo wp_json_encode(0); // Return 0 if JetBooking plugin is not active
372 wp_die();
373 }
374
375 // Get JetBooking bookings count
376 $result = jet_abaf_get_bookings(['return' => 'arrays']);
377 $total = $result ? count($result) : 0; // Count bookings or return 0
378 echo wp_json_encode($total);
379 wp_die();
380 }
381
382 // WooCommerceCustomer module logic
383 if ($module == 'WooCommerceCustomer') {
384 $user_count = count_users();
385 $result = isset($user_count['avail_roles']['customer']) ? $user_count['avail_roles']['customer'] : 0;
386 $total = $result;
387 echo wp_json_encode($total);
388 wp_die();
389 } elseif ($module == 'JetReviews') {
390 global $wpdb;
391
392 // Verify if the JetReviews plugin is active
393 if (!is_plugin_active('jet-reviews/jet-reviews.php')) {
394 echo wp_json_encode(0);
395 wp_die();
396 }
397
398 // Query to count approved reviews
399 $query = "SELECT COUNT(*) FROM {$wpdb->prefix}jet_reviews";
400 $count = $wpdb->get_var($query);
401
402 // Ensure count is an integer and return the result
403 $count = ($count !== null) ? intval($count) : 0;
404 echo wp_json_encode($count);
405 wp_die();
406 }
407
408 if (is_plugin_active('jet-engine/jet-engine.php')) {
409 $get_slug_name = $wpdb->get_results("SELECT slug FROM {$wpdb->prefix}jet_post_types WHERE status = 'content-type'");
410 foreach ($get_slug_name as $key => $get_slug) {
411 $value = $get_slug->slug;
412 $optional_type = $value;
413 if ($optionalType == $optional_type) {
414 $table_name = 'jet_cct_' . $optional_type;
415 if (!preg_match('/^[a-zA-Z0-9_]+$/', $table_name)) {
416 echo wp_json_encode(0);
417 wp_die();
418 }
419 $get_menu = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}{$table_name}");
420 if (is_array($get_menu))
421 $total = count($get_menu);
422 else
423 $total = 0;
424 echo wp_json_encode($total);
425 wp_die();
426 }
427 }
428 }
429 $get_post_ids = "select DISTINCT ID from {$wpdb->posts}";
430 $get_post_ids .= $wpdb->prepare(" where post_type = %s", $module);
431
432 /**
433 * Check for specific status
434 */
435 if ($module == 'product' && is_plugin_active('woocommerce/woocommerce.php')) {
436 if (is_plugin_active('polylang/polylang.php') || is_plugin_active('polylang-pro/polylang.php') || is_plugin_active('polylang-wc/polylang-wc.php')) {
437 //TODO temporary fix
438 //wc_get_products only exports default language product
439 $products = "select DISTINCT ID from {$wpdb->prefix}posts";
440 $products .= $wpdb->prepare(" where post_type = %s", $module);
441 $products .= " and post_status in ('publish','draft','future','private','pending') ";
442 $products = $wpdb->get_col($products);
443
444 } else {
445 $product_statuses = array('publish', 'draft', 'future', 'private', 'pending');
446 $products = wc_get_products(array('status' => $product_statuses, 'limit' => -1));
447 }
448 $total = count($products);
449 return $total;
450
451 } elseif ($module == 'shop_order') {
452 $order_statuses = array('wc-completed','wc-cancelled','wc-on-hold','wc-processing','wc-pending','wc-refunded','wc-failed','wc-checkout-draft');
453 $args = [
454 'return' => 'ids',
455 'limit' => -1,
456 'status' => $order_statuses
457 ];
458 $orders = wc_get_orders($args);
459 $response = count($orders);
460 update_option('woocommerce_order_count', $response);
461 echo wp_json_encode($response);
462 wp_die();
463
464 } elseif ($module == 'product_variation') {
465 if (is_plugin_active('polylang/polylang.php') || is_plugin_active('polylang-pro/polylang.php') || is_plugin_active('polylang-wc/polylang-wc.php')) {
466 $extracted_ids = "select DISTINCT ID from {$wpdb->prefix}posts";
467 $extracted_ids .= $wpdb->prepare(" where post_type = %s", $module);
468 $extracted_ids .= " and post_status in ('publish','draft','future','private','pending') AND post_parent !=0";
469 $extracted_id = $wpdb->get_col($extracted_ids);
470 $extracted_ids = array();
471 //fix added for prema
472 foreach ($extracted_id as $ids) {
473 $ids = absint($ids);
474 $parent_id = $wpdb->get_var($wpdb->prepare("SELECT post_parent FROM {$wpdb->prefix}posts where ID=%d", $ids));
475 $post_status = $wpdb->get_var($wpdb->prepare("SELECT post_status FROM {$wpdb->prefix}posts where ID=%d", absint($parent_id)));
476 if (!empty($post_status)) {
477 if ($post_status != 'trash' && $post_status != 'inherit') {
478 $extracted_ids[] = $ids;
479 }
480
481 }
482
483 }
484
485 } else {
486 $product_statuses = array('publish', 'draft', 'future', 'private', 'pending');
487 $products = wc_get_products(array('status' => $product_statuses, 'limit' => -1));
488 $variable_product_ids = [];
489 foreach ($products as $product) {
490 if ($product->is_type('variable')) {
491 $variable_product_ids[] = $product->get_id();
492 }
493 }
494 $variation_count = 0;
495 $variation_ids = array();
496 foreach ($variable_product_ids as $variable_product_id) {
497 $variable_product = wc_get_product($variable_product_id);
498 $variation_ids[] = $variable_product->get_children();
499 }
500 $extracted_ids = [];
501 foreach ($variation_ids as $v_ids) {
502 foreach ($v_ids as $v_id) {
503 $extracted_ids[] = $v_id;
504 }
505 }
506 }
507
508 // $product_statuses = array('publish', 'draft', 'future', 'private', 'pending');
509 // $products = wc_get_products(array('status' => $product_statuses));
510 // $variable_product_ids = [];
511 // foreach($products as $product){
512 // if ($product->is_type('variable')) {
513 // $variable_product_ids[] = $product->get_id();
514 // }
515 // }
516 // $variation_count = 0;
517 // foreach($variable_product_ids as $variable_product_id){
518 // $variations = wc_get_products(array('parent_id' => $variable_product_id,'type' => 'variation','limit'=> -1));
519 // $variation_count += count($variations);
520 // }
521 // $total = $variation_count;
522 $total = count($extracted_ids);
523 return $total;
524 } elseif ($module == 'shop_coupon') {
525 $get_post_ids .= " and post_status in ('publish','draft','pending')";
526
527 } elseif ($module == 'shop_order_refund') {
528
529 } elseif ($module == 'forum') {
530 $get_post_ids .= " and post_status in ('publish','draft','future','private','pending','hidden')";
531 } elseif ($module == 'topic') {
532 $get_post_ids .= " and post_status in ('publish','draft','future','open','pending','closed','spam')";
533 } elseif ($module == 'reply') {
534 $get_post_ids .= " and post_status in ('publish','spam','pending')";
535 }
536 $get_post_ids .= " and post_status in ('publish','draft','future','private','pending')";
537 $get_total_row_count = $wpdb->get_col($get_post_ids);
538 $total = count($get_total_row_count);
539 return $total;
540 }
541
542 /**
543 * ExportExtension constructor.
544 * Set values into global variables based on post value
545 */
546 public function __construct()
547 {
548 $this->plugin = Plugin::getInstance();
549 }
550
551 public function parseData()
552 {
553 if (!is_user_logged_in() || !current_user_can('manage_options')) {
554 wp_send_json_error(['message' => 'Unauthorized access.'], 403);
555 return;
556 }
557
558 check_ajax_referer('smack-ultimate-csv-importer', 'securekey');
559
560 if (!empty($_POST)) {
561 $query_data = isset($_POST['query_data']) ? sanitize_text_field($_POST['query_data']) : '';
562 $type = isset($_POST['type']) ? sanitize_text_field($_POST['type']) : '';
563
564 $this->module = sanitize_text_field($_POST['module']);
565 $this->random_data = sanitize_text_field($_POST['random_data']);
566 //Whitelist of allowed export types
567 $allowed_export_types = ['csv', 'xls', 'xlsx', 'json', 'xml', 'tsv'];
568 // Sanitize and validate the export type
569 $export_type = isset($_POST['exp_type']) ? sanitize_text_field($_POST['exp_type']) : 'csv';
570 $this->exportType = in_array($export_type, $allowed_export_types) ? $export_type : 'csv';
571 $conditions = str_replace("\\", '', sanitize_text_field($_POST['conditions']));
572 $conditions = json_decode($conditions, True);
573 $conditions['specific_period']['to'] = date("Y-m-d", strtotime($conditions['specific_period']['to']));
574 $conditions['specific_period']['from'] = date("Y-m-d", strtotime($conditions['specific_period']['from']));
575 $this->conditions = isset($conditions) && !empty($conditions) ? $conditions : array();
576 if ($this->module == 'Taxonomies' || $this->module == 'CustomPosts') {
577 $this->optionalType = sanitize_text_field($_POST['optionalType']);
578 } else {
579 $this->optionalType = $this->getOptionalType($this->module);
580 }
581
582 // Reassign module for EDD types if sent as CustomPosts to ensure correct flow in exportData()
583 if ($this->module == 'CustomPosts' && in_array($this->optionalType, ['EDD_CUSTOMERS', 'EDD_DISCOUNTS', 'EDD_ORDERS', 'EDD_DOWNLOADS'])) {
584 $this->module = $this->optionalType;
585 }
586 if ($this->optionalType == 'SURECART_PRODUCTS' || $this->optionalType == 'SURECART_CUSTOMERS' || $this->optionalType == 'SURECART_COUPONS') {
587 $this->module = $this->optionalType;
588 }
589 $eventExclusions = str_replace("\\", '', sanitize_text_field(isset($_POST['eventExclusions']) ? sanitize_text_field($_POST['eventExclusions']) : ''));
590 $eventExclusions = json_decode($eventExclusions, True);
591 $this->eventExclusions = isset($eventExclusions) && !empty($eventExclusions) ? $eventExclusions : array();
592 $this->fileName = isset($_POST['fileName']) ? sanitize_text_field($_POST['fileName']) : '';
593 if (empty($_POST['offset']) || sanitize_text_field($_POST['offset']) == 'undefined') {
594 $this->offset = 0;
595 } else {
596 $this->offset = isset($_POST['offset']) ? (int) $_POST['offset'] : 0;
597 }
598 if (!empty($_POST['limit'])) {
599 $this->limit = isset($_POST['limit']) ? (int) $_POST['limit'] : 1000;
600 } else {
601 if (!empty($conditions['specific_iteration_id']['is_check']) && $conditions['specific_iteration_id']['is_check'] == 'true') {
602 $this->limit = !empty($conditions['specific_iteration_id']['iteration_id']) ? (int) $conditions['specific_iteration_id']['iteration_id'] : 0;
603 } else {
604 $this->limit = 50;
605 }
606
607 }
608 if (!empty($this->conditions['delimiter']['optional_delimiter'])) {
609 $this->delimiter = $this->conditions['delimiter']['optional_delimiter'] ? $this->conditions['delimiter']['optional_delimiter'] : ',';
610 } elseif (!empty($this->conditions['delimiter']['delimiter'])) {
611 $this->delimiter = $this->conditions['delimiter']['delimiter'] ? $this->conditions['delimiter']['delimiter'] : ',';
612 if ($this->delimiter == '{Tab}') {
613 $this->delimiter = " ";
614 } elseif ($this->delimiter == '{Space}') {
615 $this->delimiter = " ";
616 }
617 }
618
619 $this->export_mode = 'normal';
620 $this->checkSplit = isset($_POST['is_check_split']) ? sanitize_text_field($_POST['is_check_split']) : 'false';
621 if ($type == 'post') {
622 ExportExtension::$wpquery_export = new WPQueryExport();
623 ExportExtension::$wpquery_export->exportwpquery($query_data);
624 } elseif ($type == 'user') {
625 ExportExtension::$wpquery_export = new WPQueryExport();
626 ExportExtension::$wpquery_export->exportwpquery_user($query_data);
627 } elseif ($type == 'comment') {
628 ExportExtension::$wpquery_export = new WPQueryExport();
629 ExportExtension::$wpquery_export->exportwpquery_comment($query_data);
630 } else {
631 $this->exportData();
632 }
633
634 }
635 }
636
637 public function commentsCount($mode = null)
638 {
639 global $wpdb;
640 self::generateHeaders($this->module, $this->optionalType);
641 $get_comments = "select * from {$wpdb->prefix}comments";
642 // Check status
643 if ($this->conditions['specific_status']['is_check'] == 'true') {
644 if ($this->conditions['specific_status']['status'] == 'Pending')
645 $get_comments .= " where comment_approved = '0'";
646 elseif ($this->conditions['specific_status']['status'] == 'Approved')
647 $get_comments .= " where comment_approved = '1'";
648 else
649 $get_comments .= " where comment_approved in ('0','1')";
650 } else
651 $get_comments .= " where comment_approved in ('0','1')";
652 // Check for specific period
653 if ($this->conditions['specific_period']['is_check'] == 'true') {
654 if ($this->conditions['specific_period']['from'] == $this->conditions['specific_period']['to']) {
655 $get_comments .= " and comment_date >= '" . $this->conditions['specific_period']['from'] . "'";
656 } else {
657 $get_comments .= " and comment_date >= '" . $this->conditions['specific_period']['from'] . "' and comment_date <= '" . $this->conditions['specific_period']['to'] . "'";
658 }
659 }
660 // Check for specific authors
661 if ($this->conditions['specific_authors']['is_check'] == '1') {
662 if (isset($this->conditions['specific_authors']['author'])) {
663 $get_comments .= $wpdb->prepare(" and comment_author_email = %s", $this->conditions['specific_authors']['author']);
664 }
665 }
666 $get_comments .= " order by comment_ID";
667 $comments = $wpdb->get_results($get_comments);
668 $totalRowCount = count($comments);
669 return $totalRowCount;
670 }
671
672 public function getOptionalType($module)
673 {
674 if ($module == 'Tags') {
675 $optionalType = 'post_tag';
676 } elseif ($module == 'Posts') {
677 $optionalType = 'posts';
678 } elseif ($module == 'Pages') {
679 $optionalType = 'pages';
680 } elseif ($module == 'Categories') {
681 $optionalType = 'category';
682 } elseif ($module == 'Users') {
683 $optionalType = 'users';
684 } elseif ($module == 'Comments') {
685 $optionalType = 'comments';
686 } elseif ($module == 'JetBooking') {
687 $optionalType = 'JetBooking';
688 } elseif ($module == 'EDD_DOWNLOADS') {
689 $optionalType = 'download';
690 } elseif ($module == 'EDD_ORDERS') {
691 if (class_exists('\\EDD\\Orders\\Order_Query')) {
692 $optionalType = 'edd_order';
693 } else {
694 $optionalType = 'edd_payment';
695 }
696 } elseif ($module == 'EDD_CUSTOMERS') {
697 $optionalType = 'edd_customers';
698 } elseif ($module == 'EDD_DISCOUNTS') {
699 $optionalType = 'edd_discounts';
700 } elseif ($module == 'CustomerReviews') {
701 $optionalType = 'wpcr3_review';
702 } elseif ($module == 'WooCommerce' || $module == 'WooCommerceOrders' || $module == 'WooCommerceCoupons' || $module == 'WooCommerceRefunds' || $module == 'WooCommerceVariations') {
703 $optionalType = 'product';
704 } elseif ($module == 'WooCommerce') {
705 $optionalType = 'product';
706 } elseif ($module == 'WooCommerceCustomer') {
707 $optionalType = 'users';
708 } elseif ($module == 'WPeCommerce') {
709 $optionalType = 'wpsc-product';
710 } elseif ($module == 'JetReviews') {
711 $optionalType = 'JetReviews';
712 } elseif ($module == 'WPeCommerce' || $module == 'WPeCommerceCoupons') {
713 $optionalType = 'wpsc-product';
714 }
715 return $optionalType;
716 }
717
718 /**
719 * set the delimiter
720 */
721 public function setDelimiter($conditions)
722 {
723 if (isset($conditions['optional_delimiter']) && $conditions['optional_delimiter'] != '') {
724 return $conditions['optional_delimiter'];
725 } elseif (isset($conditions['delimiter']) && $conditions['delimiter'] != 'Select') {
726 if ($conditions['delimiter'] == '{Tab}')
727 return "\t";
728 elseif ($conditions['delimiter'] == '{Space}')
729 return " ";
730 else
731 return $conditions['delimiter'];
732 } else {
733 return ',';
734 }
735 }
736
737 /**
738 * Export records based on the requested module
739 */
740 public function exportData()
741 {
742 $this->mode = isset($this->mode) ? $this->mode : '';
743 switch ($this->module) {
744 case 'Posts':
745 case 'Pages':
746 case 'CustomPosts':
747 case 'WooCommerce':
748 case 'WooCommerceVariations':
749 case 'WooCommerceOrders':
750 case 'WooCommerceCoupons':
751 case 'WooCommerceRefunds':
752 case 'WPeCommerce':
753 case 'WPeCommerceCoupons':
754 self::FetchDataByPostTypes();
755 break;
756 case 'EDD_DOWNLOADS':
757 case 'EDD_CUSTOMERS':
758 case 'EDD_DISCOUNTS':
759 case 'SURECART_PRODUCTS':
760 case 'SURECART_CUSTOMERS':
761 case 'SURECART_SUBSCRIPTIONS':
762 case 'SURECART_COUPONS':
763 self::FetchDataByPostTypes();
764 break;
765 case 'Users':
766 case 'WooCommerceCustomer':
767 self::FetchUsers($this->module, $this->optionalType, $this->conditions, $this->offset, $this->limit, $this->mode);
768 break;
769 // case 'WooCommerceCustomer':
770 // ExportExtension::$wc_customer->FetchWooCommerceCustomer($this->module, $this->optionalType, $this->conditions, $this->offset, $this->limit, $this->mode);
771 // break;
772 case 'WooCommerceReviews':
773 case 'Comments':
774 self::FetchComments();
775 break;
776 case 'CustomerReviews':
777 ExportExtension::$review_export->FetchCustomerReviews($this->module, $this->optionalType, $this->conditions, $this->offset, $this->limit, $this->mode);
778 break;
779 case 'Categories':
780 ExportExtension::$post_export->FetchCategories($this->module, $this->optionalType);
781 break;
782 case 'JetBooking':
783 $result = self::FetchDataByPostTypes();
784 break;
785 case 'JetReviews':
786 $result = self::FetchDataByPostTypes($mod, $cat, $is_filter);
787 break;
788
789 case 'Tags':
790 ExportExtension::$post_export->FetchTags($this->mode, $this->module, $this->optionalType);
791 case 'Taxonomies':
792 ExportExtension::$woocom_export->FetchTaxonomies($this->module, $this->optionalType);
793 break;
794
795 }
796 }
797
798 /**
799 * Fetch users and their meta information
800 * @param $mode
801 *
802 * @return array
803 */
804 public function FetchUsers($module, $optionalType, $conditions, $offset, $limit, $mode = null)
805 {
806 global $wpdb;
807 self::generateHeaders($this->module, $this->optionalType);
808 // $get_available_user_ids = "select DISTINCT ID from {$wpdb->prefix}users u join {$wpdb->prefix}usermeta um on um.user_id = u.ID";
809
810 // // Check for specific period
811 // if ($this->conditions['specific_period']['is_check'] == 'true')
812 // {
813 // if ($this->conditions['specific_period']['from'] == $this->conditions['specific_period']['to'])
814 // {
815 // $get_available_user_ids .= " where u.user_registered >= '" . $this->conditions['specific_period']['from'] . "'";
816 // }
817 // else
818 // {
819 // $get_available_user_ids .= " where u.user_registered >= '" . $this->conditions['specific_period']['from'] . "' and u.user_registered <= '" . $this->conditions['specific_period']['to'] . " 23:00:00'";
820 // }
821 // }
822 // $availableUsers = $wpdb->get_col($get_available_user_ids);
823
824 // if (!empty($this->conditions['specific_period']['is_check']) && $this->conditions['specific_period']['is_check'] == 'true')
825 // {
826 // if ($this->conditions['specific_period']['from'] == $this->conditions['specific_period']['to'])
827 // {
828 // $availableUserss = array();
829 // foreach ($availableUsers as $user_value)
830 // {
831 // $get_user_date_time = $wpdb->get_results("SELECT user_registered FROM {$wpdb->prefix}users WHERE ID={$user_value}", ARRAY_A);
832 // $get_user_date = date("Y-m-d", strtotime($get_user_date_time[0]['user_registered']));
833 // if ($get_user_date == $this->conditions['specific_period']['from'])
834 // {
835 // $get_user_id_value[] = $user_value;
836 // }
837
838 // }
839 // $this->totalRowCount = count($get_user_id_value);
840 // $availableUserss = $get_user_id_value;
841 // }
842 // else
843 // {
844 // $this->totalRowCount = count($availableUsers);
845 // $get_available_user_ids .= " order by ID asc limit $this->offset, $this->limit";
846 // $availableUserss = $wpdb->get_col($get_available_user_ids);
847 // }
848 // }
849 // else
850 // {
851 // $this->totalRowCount = count($availableUsers);
852 // $get_available_user_ids .= " order by ID asc limit $this->offset, $this->limit";
853 // $availableUserss = $wpdb->get_col($get_available_user_ids);
854 // }
855 if ($module == 'WooCommerceCustomer') {
856 $this->module = 'Users';
857 // Get only users with the "customer" role
858 $args = [
859 'role' => 'customer',
860 'fields' => 'ID',
861 'orderby' => 'ID',
862 'order' => 'ASC'
863 ];
864
865 // Check for specific period
866 if ($this->conditions['specific_period']['is_check'] == 'true') {
867 $from = $this->conditions['specific_period']['from'];
868 $to = $this->conditions['specific_period']['to'];
869
870 if ($from == $to) {
871 $args['date_query'] = [
872 [
873 'after' => $from,
874 'inclusive' => true,
875 ]
876 ];
877 } else {
878 $args['date_query'] = [
879 [
880 'after' => $from,
881 'before' => $to . ' 23:59:59',
882 'inclusive' => true,
883 ]
884 ];
885 }
886 }
887
888 // Get customer user IDs
889 $availableUserss = get_users($args);
890 } else {
891 // Fetch all user IDs with the additional condition
892 $get_available_user_ids = "SELECT DISTINCT u.ID
893 FROM {$wpdb->prefix}users u
894 JOIN {$wpdb->prefix}usermeta um ON um.user_id = u.ID";
895
896 // Check for specific period
897 if ($this->conditions['specific_period']['is_check'] == 'true') {
898 if ($this->conditions['specific_period']['from'] == $this->conditions['specific_period']['to']) {
899 $get_available_user_ids .= " WHERE u.user_registered >= '" . esc_sql($this->conditions['specific_period']['from']) . "'";
900 } else {
901 $get_available_user_ids .= " WHERE u.user_registered >= '" . esc_sql($this->conditions['specific_period']['from']) . "'
902 AND u.user_registered <= '" . esc_sql($this->conditions['specific_period']['to']) . " 23:59:59'";
903 }
904 }
905
906 $get_available_user_ids .= " ORDER BY u.ID ASC";
907
908 $availableUserss = $wpdb->get_col($get_available_user_ids);
909 }
910
911
912 if (!empty($availableUserss)) {
913 $this->totalRowCount = count($availableUserss);
914 // Restrict the fetched users to the current batch window. Previously the
915 // full user set was returned on every batch and appended to the file,
916 // which produced duplicate user rows in batched exports.
917 $availableUserss = array_slice($availableUserss, (int) $offset, (int) $limit);
918 $whereCondition = '';
919 foreach ($availableUserss as $userId) {
920 $userId = absint($userId);
921 if ($whereCondition != '') {
922 $whereCondition = $whereCondition . ',' . $userId;
923 } else {
924 $whereCondition = $userId;
925 }
926 // Prepare the user details to be export
927 $query_to_fetch_users = "SELECT * FROM {$wpdb->prefix}users where ID in ($whereCondition);";
928 $users = $wpdb->get_results($query_to_fetch_users);
929 if (!empty($users)) {
930 foreach ($users as $userInfo) {
931 $this->data[$userId]['ID'] = $userInfo->ID;
932 foreach ($userInfo as $userKey => $userVal) {
933 $this->data[$userId][$userKey] = $userVal;
934 }
935 }
936 } else {
937 $this->data[$userId]['ID'] = $userId;
938 }
939 $userMeta = $wpdb->get_results($wpdb->prepare("SELECT user_id, meta_key, meta_value FROM {$wpdb->prefix}users wp JOIN {$wpdb->prefix}usermeta wpm ON wpm.user_id = wp.ID WHERE ID = %d", $userId));
940 $wptypesfields = get_option('wpcf-usermeta');
941 $wptypesfields = get_option('wpcf-usermeta');
942
943 if (!empty($wptypesfields)) {
944 $i = 1;
945 foreach ($wptypesfields as $key => $value) {
946 $typesf[$i] = 'wpcf-' . $key;
947 $typeOftypesField[$typesf[$i]] = $value['type'];
948 $i++;
949 }
950 }
951 if (!empty($userMeta)) {
952 foreach ($userMeta as $userMetaInfo) {
953 if ($userMetaInfo->meta_key == $wpdb->prefix . 'capabilities') {
954
955 if (is_plugin_active('members/members.php')) {
956 $data = unserialize($userMetaInfo->meta_value);
957 $roles = array_keys(array_filter($data));
958 $role = implode('|', $roles);
959 $this->data[$userId]['multi_user_role'] = $role;
960 } else {
961 $userRole = $this->getUserRole($userMetaInfo->meta_value);
962 $this->data[$userId]['role'] = $userRole;
963 }
964
965 } elseif ($userMetaInfo->meta_key == 'description') {
966 $this->data[$userId]['biographical_info'] = $userMetaInfo->meta_value;
967 } elseif ($userMetaInfo->meta_key == 'comment_shortcuts') {
968 $this->data[$userId]['enable_keyboard_shortcuts'] = $userMetaInfo->meta_value;
969 } elseif ($userMetaInfo->meta_key == 'show_admin_bar_front') {
970 $this->data[$userId]['show_toolbar'] = $userMetaInfo->meta_value;
971 } elseif ($userMetaInfo->meta_key == 'rich_editing') {
972 $this->data[$userId]['disable_visual_editor'] = $userMetaInfo->meta_value;
973 } elseif ($userMetaInfo->meta_key == 'locale') {
974 $this->data[$userId]['language'] = $userMetaInfo->meta_value;
975 } elseif (isset($typesf) && in_array($userMetaInfo->meta_key, $typesf)) {
976 $typeoftype = $typeOftypesField[$userMetaInfo->meta_key];
977 if (is_serialized($userMetaInfo->meta_value)) {
978 $typefileds = unserialize($userMetaInfo->meta_value);
979 $typedata = "";
980 foreach ($typefileds as $key2 => $value2) {
981 if (is_array($value2)) {
982 foreach ($value2 as $key3 => $value3) {
983 $typedata .= $value3 . ',';
984 }
985 } else
986 $typedata .= $value2 . ',';
987 }
988 if (preg_match('/wpcf-/', $userMetaInfo->meta_key)) {
989 $userMetaInfo->meta_key = preg_replace('/wpcf-/', '', $userMetaInfo->meta_key);
990 $this->data[$userId][$userMetaInfo->meta_key] = substr($typedata, 0, -1);
991 }
992 } elseif ($typeoftype == 'date') {
993 $this->data[$userId][$userMetaInfo->meta_key] = date('Y-m-d', $userMetaInfo->meta_value);
994 }
995 $multi_row = '_' . $userMetaInfo->meta_key . '-sort-order';
996
997 $multi_data = get_user_meta($userId, $multi_row);
998 $multi_data = $multi_data[0];
999 if (is_array($multi_data)) {
1000 foreach ($multi_data as $k => $mid) {
1001 $m_data = $this->get_common_post_metadata($mid);
1002 if ($typeoftype == 'date')
1003 $multi_data[$k] = date('Y-m-d H:i:s', $m_data['meta_value']);
1004 else
1005 $multi_data[$k] = $m_data['meta_value'];
1006 }
1007 $this->data[$userId][$userMetaInfo->meta_key] = implode('|', $multi_data);
1008 if (preg_match('/wpcf-/', $userMetaInfo->meta_key)) {
1009 $userMetaInfo->meta_key = preg_replace('/wpcf-/', '', $userMetaInfo->meta_key);
1010
1011 $this->data[$userId][$userMetaInfo->meta_key] = implode('|', $multi_data);
1012 }
1013 } else {
1014 if (preg_match('/wpcf-/', $userMetaInfo->meta_key)) {
1015 $userMetaInfo->meta_key = preg_replace('/wpcf-/', '', $userMetaInfo->meta_key);
1016 $this->data[$userId][$userMetaInfo
1017 ->meta_key] = $userMetaInfo->meta_value;
1018 }
1019 }
1020 } else {
1021
1022 $this->data[$userId][$userMetaInfo
1023 ->meta_key] = $userMetaInfo->meta_value;
1024 }
1025 }
1026 // Prepare the buddy meta details to be export
1027 if (is_plugin_active('buddypress/bp-loader.php')) {
1028 $query_to_fetch_buddy_meta = $wpdb->prepare("SELECT user_id,field_id,value,name FROM {$wpdb->prefix}bp_xprofile_data bxd inner join {$wpdb->prefix}users wp on bxd.user_id = wp.ID inner join {$wpdb->prefix}bp_xprofile_fields bxf on bxf.id = bxd.field_id where user_id=%d", $userId);
1029 $buddy = $wpdb->get_results($query_to_fetch_buddy_meta);
1030 if (!empty($buddy)) {
1031 foreach ($buddy as $buddyInfo) {
1032 foreach ($buddyInfo as $field_id => $value) {
1033 $this->data[$userId][$buddyInfo
1034 ->name] = $buddyInfo->value;
1035 }
1036 }
1037 }
1038 }
1039 ExportExtension::$post_export->getPostsMetaDataBasedOnRecordId($userId, $this->module, $this->optionalType);
1040 }
1041 }
1042 }
1043
1044 $result = self::finalDataToExport($this->data, $this->module, $this->optionalType);
1045 if ($mode == null)
1046 self::proceedExport($result);
1047 else
1048 return $result;
1049 }
1050
1051 public function mergeWithUserMeta($acf_field_values)
1052 {
1053
1054 foreach ($acf_field_values as $acf_field_value) {
1055
1056 }
1057 }
1058
1059 /**
1060 * Fetch all Comments
1061 * @param $mode
1062 *
1063 * @return array
1064 */
1065 public function FetchComments($mode = null)
1066 {
1067
1068 global $wpdb;
1069 self::generateHeaders($this->module, $this->optionalType);
1070 $get_comments = "select * from {$wpdb->prefix}comments";
1071 // Check status
1072 if (isset($this->conditions['specific_status']['is_check']) && $this->conditions['specific_status']['is_check'] == 'true') {
1073 if ($this->conditions['specific_status']['status'] == 'Pending')
1074 $get_comments .= " where comment_approved = '0'";
1075 elseif ($this->conditions['specific_status']['status'] == 'Approved')
1076 $get_comments .= " where comment_approved = '1'";
1077 else
1078 $get_comments .= " where comment_approved in ('0','1')";
1079 } else
1080 $get_comments .= " where comment_approved in ('0','1')";
1081 // Check for specific period
1082 if ($this->conditions['specific_period']['is_check'] == 'true') {
1083 if ($this->conditions['specific_period']['from'] == $this->conditions['specific_period']['to']) {
1084 $get_comments .= " and comment_date >= '" . $this->conditions['specific_period']['from'] . "'";
1085 } else {
1086 $get_comments .= " and comment_date >= '" . $this->conditions['specific_period']['from'] . "' and comment_date <= '" . $this->conditions['specific_period']['to'] . " 23:00:00'";
1087 }
1088 }
1089 // Check for specific authors
1090 if ($this->conditions['specific_authors']['is_check'] == '1') {
1091 if (isset($this->conditions['specific_authors']['author'])) {
1092 $get_comments .= $wpdb->prepare(" and comment_author_email = %s", $this->conditions['specific_authors']['author']);
1093 }
1094 }
1095
1096 if ($this->module == 'WooCommerceReviews') {
1097 $get_comments .= " and comment_type = 'review'";
1098 }
1099
1100 $comments = $wpdb->get_results($get_comments);
1101 $offset = (int) $this->offset;
1102 $limit = (int) $this->limit;
1103
1104 if (!empty($this->conditions['specific_period']['is_check']) && $this->conditions['specific_period']['is_check'] == 'true') {
1105 if ($this->conditions['specific_period']['from'] == $this->conditions['specific_period']['to']) {
1106 $limited_comments = array();
1107 foreach ($comments as $comments_value) {
1108 // $get_comment_date_time = $wpdb->get_results($wpdb->prepare("SELECT comment_date FROM {$wpdb->prefix}comments WHERE comment_id=$comments_value->comment_ID") , ARRAY_A);
1109 $get_comment_date_time = $wpdb->get_results($wpdb->prepare("SELECT comment_date FROM {$wpdb->prefix}comments WHERE comment_id = %d", $comments_value->comment_ID), ARRAY_A);
1110 $get_comment_date = date("Y-m-d", strtotime($get_comment_date_time[0]['comment_date']));
1111 if ($get_comment_date == $this->conditions['specific_period']['from']) {
1112 $get_comment_date_value[] = $comments_value;
1113 }
1114
1115 }
1116 $this->totalRowCount = count($get_comment_date_value);
1117 $limited_comments = $get_comment_date_value;
1118 } else {
1119 $this->totalRowCount = count($comments);
1120 $get_comments .= " order by comment_ID asc limit {$offset}, {$limit}";
1121 $limited_comments = $wpdb->get_results($get_comments);
1122 }
1123 } else {
1124 $this->totalRowCount = count($comments);
1125 $get_comments .= " order by comment_ID asc limit {$offset}, {$limit}";
1126 $limited_comments = $wpdb->get_results($get_comments);
1127 }
1128
1129 if (!empty($limited_comments)) {
1130 foreach ($limited_comments as $commentInfo) {
1131 $user_id = $commentInfo->user_id;
1132 if (!empty($user_id)) {
1133 $users_login = $wpdb->get_results($wpdb->prepare("SELECT user_login FROM {$wpdb->prefix}users WHERE ID = %d", $user_id));
1134 foreach ($users_login as $users_key => $users_value) {
1135 foreach ($users_value as $u_key => $u_value) {
1136 $users_id = $u_value;
1137 }
1138 }
1139 }
1140 foreach ($commentInfo as $commentKey => $commentVal) {
1141 $this->data[$commentInfo->comment_ID][$commentKey] = $commentVal;
1142 $this->data[$commentInfo->comment_ID]['user_id'] = isset($users_id) ? $users_id : '';
1143 }
1144 $get_comment_rating = get_comment_meta($commentInfo->comment_ID, 'rating', true);
1145 if (!empty($get_comment_rating)) {
1146 $this->data[$commentInfo->comment_ID]['comment_rating'] = $get_comment_rating;
1147 }
1148 }
1149 }
1150 $result = self::finalDataToExport($this->data, $this->module, $this->optionalType);
1151 if ($mode == null)
1152 self::proceedExport($result);
1153 else
1154 return $result;
1155 }
1156
1157 /**
1158 * Generate CSV headers
1159 *
1160 * @param $module - Module to be export
1161 * @param $optionalType - Exclusions
1162 */
1163 public function generateHeaders($module, $optionalType)
1164 {
1165 if ($module == 'CustomPosts' || $module == 'Taxonomies' || $module == 'Categories' || $module == 'Tags') {
1166 if (is_plugin_active('events-manager/events-manager.php') && $optionalType == 'event') {
1167 $optionalType = 'Events';
1168 } elseif (is_plugin_active('the-events-calendar/the-events-calendar.php') && $optionalType == 'tribe_events') {
1169 $optionalType = 'tribe_events';
1170 }
1171 $default = $this->get_fields($optionalType); // Call the super class function
1172
1173 } else {
1174 $default = $this->get_fields($module);
1175 }
1176 $headers = [];
1177 foreach ($default as $key => $fields) {
1178 foreach ($fields as $groupKey => $fieldArray) {
1179
1180 foreach ($fieldArray as $fKey => $fVal) {
1181 if (is_array($fVal) || is_object($fVal)) {
1182 foreach ($fVal as $rKey => $rVal) {
1183 if (!in_array($rVal['name'], $headers))
1184 $headers[] = $rVal['name'];
1185 }
1186 }
1187 }
1188
1189 }
1190 }
1191 if ($optionalType == 'elementor_library') {
1192 $headers = [];
1193 $headers = ['ID', 'Template title', 'Template content', 'Style', 'Template type', 'Created time', 'Created by', 'Template status', 'Category'];
1194 }
1195 if ($module === 'Users' || $module === 'WooCommerceCustomer') {
1196 $headers = array_values(array_diff($headers, array('ID')));
1197 array_unshift($headers, 'ID');
1198 }
1199 if (isset($this->eventExclusions['is_check']) && $this->eventExclusions['is_check'] == 'true'):
1200 $headers_with_exclusion = self::applyEventExclusion($headers, $optionalType);
1201 $this->headers = $headers_with_exclusion;
1202 else:
1203 $this->headers = $headers;
1204 endif;
1205 }
1206
1207 /**
1208 * Fetch data by requested Post types
1209 * @param $mode
1210 * @return array
1211 */
1212 public function FetchDataByPostTypes($mode = null)
1213 {
1214 $exp_module = '';
1215 if (empty($this->headers))
1216 $this->generateHeaders($this->module, $this->optionalType);
1217 $recordsToBeExport = ExportExtension::$post_export->getRecordsBasedOnPostTypes($this->module, $this->optionalType, $this->conditions, $this->offset, $this->limit, $this->headers);
1218 if (!empty($recordsToBeExport)) {
1219 foreach ($recordsToBeExport as $postId) {
1220 $exp_module = $this->module;
1221 if ($exp_module !== 'JetBooking' && $exp_module !== 'JetReviews') {
1222 $this->data[$postId] = $this->getPostsDataBasedOnRecordId($postId, $this->module);
1223 }
1224 $this->data[$postId] = $this->getPostsDataBasedOnRecordId($postId, $this->module);
1225 if ($exp_module == 'Posts' || $exp_module == 'WooCommerce' || $exp_module == 'CustomPosts' || $exp_module == 'Categories' || $exp_module == 'Tags' || $exp_module == 'Taxonomies' || $exp_module == 'Pages') {
1226 $this->getWPMLData($postId, $this->optionalType, $exp_module);
1227 }
1228
1229 if ($exp_module == 'Posts' || $exp_module == 'CustomPosts' || $exp_module == 'Pages' || $exp_module == 'WooCommerce') {
1230 if (is_plugin_active('polylang/polylang.php') || is_plugin_active('polylang-pro/polylang.php') || is_plugin_active('polylang-wc/polylang-wc.php')) {
1231 $this->getPolylangData($postId, $this->optionalType, $exp_module);
1232 }
1233 }
1234 if ($exp_module == 'CustomPosts') {
1235 if (is_plugin_active('geodirectory/geodirectory.php')) {
1236 $this->getGeoPlaceData($postId, $this->optionalType, $exp_module);
1237 }
1238 }
1239 ExportExtension::$post_export->getPostsMetaDataBasedOnRecordId($postId, $this->module, $this->optionalType);
1240 $this->getTermsAndTaxonomies($postId, $this->module, $this->optionalType);
1241 if ($this->module == 'JetBooking')
1242 ExportExtension::$jet_book_export->getJetBookingData($postId, $this->module, $this->optionalType);
1243 if ($this->module == 'JetReviews') {
1244 ExportExtension::$jet_reviews_export->getJetReviewsData($postId, $this->module, $this->optionalType);
1245 }
1246 if ($this->module == 'WooCommerce')
1247 ExportExtension::$woocom_export->getProductData($postId, $this->module, $this->optionalType);
1248 if ($this->module == 'WooCommerceRefunds')
1249 ExportExtension::$woocom_export->getWooComCustomerUser($postId, $this->module, $this->optionalType);
1250 if ($this->module == 'WooCommerceOrders')
1251 ExportExtension::$woocom_export->getWooComOrderData($postId, $this->module, $this->optionalType);
1252 if ($this->module == 'WooCommerceVariations')
1253 ExportExtension::$woocom_export->getVariationData($postId, $this->module, $this->optionalType);
1254 if ($this->module == 'WooCommerceCoupons')
1255 ExportExtension::$woocom_export->getCouponsData($postId, $this->module, $this->optionalType);
1256 if ($this->module == 'WPeCommerce')
1257 ExportExtension::$ecom_export->getEcomData($postId, $this->module, $this->optionalType);
1258 if ($this->module == 'WPeCommerceCoupons')
1259 ExportExtension::$ecom_export->getEcomCouponData($postId, $this->module, $this->optionalType);
1260 if ($this->module == 'EDD_DOWNLOADS')
1261 ExportExtension::$edd_export->getEDDDownloadDataMaster($postId);
1262 if ($this->module == 'EDD_ORDERS')
1263 ExportExtension::$edd_export->getEDDOrderDataMaster($postId);
1264 if ($this->module == 'EDD_CUSTOMERS')
1265 ExportExtension::$edd_export->getEDDCustomerDataMaster($postId);
1266 if ($this->module == 'EDD_DISCOUNTS')
1267 ExportExtension::$edd_export->getEDDDiscountDataMaster($postId);
1268
1269 if ($this->module == 'SURECART_PRODUCTS' || $this->optionalType == 'SURECART_PRODUCTS')
1270 ExportExtension::$surecart_export->getSureCartProductDataMaster($postId);
1271 if ($this->module == 'SURECART_CUSTOMERS' || $this->optionalType == 'SURECART_CUSTOMERS')
1272 ExportExtension::$surecart_export->getSureCartCustomerDataMaster($postId);
1273 if ($this->module == 'SURECART_COUPONS' || $this->optionalType == 'SURECART_COUPONS')
1274 ExportExtension::$surecart_export->getSureCartCouponDataMaster($postId);
1275
1276 if ($this->optionalType == 'lp_course')
1277 ExportExtension::$learnpress_export->getCourseData($postId);
1278 if ($this->optionalType == 'lp_lesson')
1279 ExportExtension::$learnpress_export->getLessonData($postId);
1280 if ($this->optionalType == 'lp_quiz')
1281 ExportExtension::$learnpress_export->getQuizData($postId);
1282 if ($this->optionalType == 'lp_question')
1283 ExportExtension::$learnpress_export->getQuestionData($postId);
1284 if ($this->optionalType == 'lp_order')
1285 ExportExtension::$learnpress_export->getOrderData($postId);
1286
1287 if ($this->optionalType == 'stm-courses')
1288 ExportExtension::$woocom_export->getCourseDataMasterLMS($postId);
1289
1290 if ($this->optionalType == 'stm-questions')
1291 ExportExtension::$woocom_export->getQuestionDataMasterLMS($postId);
1292
1293 if ($this->optionalType == 'stm-lessons')
1294 ExportExtension::$woocom_export->getLessonDataMasterLMS($postId);
1295 if ($this->optionalType == 'stm-orders')
1296 ExportExtension::$woocom_export->orderDataMasterLMS($postId);
1297 if ($this->optionalType == 'stm-quizzes')
1298 ExportExtension::$woocom_export->quizzDataMasterLMS($postId);
1299 if ($this->optionalType == 'elementor_library')
1300 ExportExtension::$woocom_export->elementor_export($postId);
1301 if ($this->optionalType == 'nav_menu_item')
1302 ExportExtension::$woocom_export->getMenuData($postId);
1303
1304 if ($this->optionalType == 'widgets')
1305 self::$instance->getWidgetData($postId, $this->headers);
1306 }
1307 }
1308 $exp_module = $this->module;
1309 if (is_plugin_active('jet-engine/jet-engine.php')) {
1310 global $wpdb;
1311 $get_slug_name = $wpdb->get_results("SELECT slug FROM {$wpdb->prefix}jet_post_types WHERE status = 'content-type'");
1312
1313 foreach ($get_slug_name as $key => $get_slug) {
1314 $value = $get_slug->slug;
1315 $optional_type = $value;
1316 if ($this->optionalType == $optional_type) {
1317 $table_name = 'jet_cct_' . $this->optionalType;
1318 if (!preg_match('/^[a-zA-Z0-9_]+$/', $table_name)) {
1319 continue;
1320 }
1321 $jet_offset = (int) $this->offset;
1322 $jet_limit = (int) $this->limit;
1323
1324 $jet_values = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}{$table_name} order by _ID asc limit {$jet_offset},{$jet_limit} ");
1325 if (!empty($jet_values)) {
1326 foreach ($jet_values as $jet_value) {
1327 foreach ($jet_value as $field_id => $value) {
1328 $this->data[$jet_value->_ID][$field_id] = $value;
1329
1330 }
1331 }
1332 }
1333 foreach ($this->data as $id => $value) {
1334 ExportExtension::$post_export->getPostsMetaDataBasedOnRecordId($id, $this->module, $this->optionalType);
1335 }
1336 }
1337 }
1338 $slug = $this->optionalType;
1339 $getarg = $wpdb->get_results($wpdb->prepare("SELECT args from {$wpdb->prefix}jet_post_types where slug = %s and status = 'content-type'", $slug), ARRAY_A);
1340 foreach ($getarg as $key => $value) {
1341 $arg_data = $value['args'];
1342 break;
1343 }
1344 if (!empty($arg_data)) {
1345 $arg_data = unserialize($arg_data);
1346 if (!empty($arg_data) && array_key_exists('has_single', $arg_data) && $arg_data['has_single']) {
1347 $this->data[$id]['cct_single_post_title'] = $arg_data['related_post_type_title'] ?? '';
1348 $this->data[$id]['cct_single_post_content'] = $arg_data['related_post_type_content'] ?? '';
1349 }
1350 }
1351 }
1352 /** Added post format for 'standard' property */
1353 if ($exp_module == 'Posts' || $exp_module == 'CustomPosts' || $exp_module == 'WooCommerce') {
1354 foreach ($this->data as $id => $records) {
1355 if (!array_key_exists('post_format', $records)) {
1356 $records['post_format'] = 'standard';
1357 $this->data[$id] = $records;
1358 }
1359 }
1360
1361 }
1362 if ($this->optionalType == 'course') {
1363 foreach ($this->data as $id => $records) {
1364 if (array_key_exists('_llms_instructors', $records)) {
1365 $instructor = unserialize($records['_llms_instructors']);
1366 if (is_array($instructor)) {
1367 $arr_ins = array();
1368 foreach ($instructor as $ins_val) {
1369 $arr_val = array_values($ins_val);
1370 unset($arr_val[0]);
1371 unset($arr_val[2]);
1372 $arr_ins[] = implode(',', $arr_val);
1373
1374 }
1375 $records['_llms_instructors'] = implode('|', $arr_ins);
1376 $this->data[$id] = $records;
1377
1378 }
1379
1380
1381 }
1382 }
1383 }
1384
1385
1386 /** End post format */
1387
1388 $result = self::finalDataToExport($this->data, $this->module, $this->optionalType);
1389 if ($mode == null)
1390 self::proceedExport($result);
1391 else
1392 return $result;
1393 }
1394
1395 public function getWidgetData($postId, $headers)
1396 {
1397
1398 global $wpdb;
1399 $get_sidebar_widgets = get_option('sidebars_widgets');
1400
1401 $total_footer_arr = [];
1402
1403 foreach ($get_sidebar_widgets as $footer_key => $footer_arr) {
1404 if ($footer_key != 'wp_inactive_widgets' || $footer_key != 'array_version') {
1405 if (strpos($footer_key, 'sidebar') !== false) {
1406 $get_footer = explode('-', $footer_key);
1407 $footer_number = $get_footer[1];
1408
1409 foreach ($footer_arr as $footer_values) {
1410 $total_footer_arr[$footer_values] = $footer_number;
1411 }
1412 }
1413 }
1414 }
1415
1416 foreach ($headers as $key => $value) {
1417 $get_widget_value[$value] = $wpdb->get_row("SELECT option_value FROM {$wpdb->prefix}options where option_name = '{$value}'", ARRAY_A);
1418
1419 $header_key = explode('widget_', $value);
1420
1421 if ($value == 'widget_recent-posts') {
1422 $recent_posts = unserialize($get_widget_value[$value]['option_value']);
1423 $recent_post = '';
1424 foreach ($recent_posts as $dk => $dv) {
1425 if ($dk != '_multiwidget') {
1426 $post_key = $header_key[1] . '-' . $dk;
1427 $recent_post .= $dv['title'] . ',' . $dv['number'] . ',' . $dv['show_date'] . '->' . $total_footer_arr[$post_key] . '|';
1428 }
1429 }
1430 $recent_post = rtrim($recent_post, '|');
1431 } elseif ($value == 'widget_pages') {
1432 $recent_pages = unserialize($get_widget_value[$value]['option_value']);
1433 $recent_page = '';
1434 foreach ($recent_pages as $dk => $dv) {
1435 if (isset($dv['exclude'])) {
1436 $exclude_value = str_replace(',', '/', $dv['exclude']);
1437 }
1438
1439 if ($dk != '_multiwidget') {
1440 $page_key = $header_key[1] . '-' . $dk;
1441 $recent_page .= $dv['title'] . ',' . $dv['sortby'] . ',' . $exclude_value . '->' . $total_footer_arr[$page_key] . '|';
1442 }
1443 }
1444 $recent_page = rtrim($recent_page, '|');
1445 } elseif ($value == 'widget_recent-comments') {
1446 $recent_comments = unserialize($get_widget_value[$value]['option_value']);
1447 $recent_comment = '';
1448 foreach ($recent_comments as $dk => $dv) {
1449 if ($dk != '_multiwidget') {
1450 $comment_key = $header_key[1] . '-' . $dk;
1451 $recent_comment .= $dv['title'] . ',' . $dv['number'] . '->' . $total_footer_arr[$comment_key] . '|';
1452 }
1453 }
1454 $recent_comment = rtrim($recent_comment, '|');
1455 } elseif ($value == 'widget_archives') {
1456 $recent_archives = unserialize($get_widget_value[$value]['option_value']);
1457 $recent_archive = '';
1458 foreach ($recent_archives as $dk => $dv) {
1459 if ($dk != '_multiwidget') {
1460 $archive_key = $header_key[1] . '-' . $dk;
1461 $recent_archive .= $dv['title'] . ',' . $dv['count'] . ',' . $dv['dropdown'] . '->' . $total_footer_arr[$archive_key] . '|';
1462 }
1463 }
1464 $recent_archive = rtrim($recent_archive, '|');
1465 } elseif ($value == 'widget_categories') {
1466 $recent_categories = unserialize($get_widget_value[$value]['option_value']);
1467 $recent_category = '';
1468 foreach ($recent_categories as $dk => $dv) {
1469 if ($dk != '_multiwidget') {
1470 $cat_key = $header_key[1] . '-' . $dk;
1471 $recent_category .= $dv['title'] . ',' . $dv['count'] . ',' . $dv['hierarchical'] . ',' . $dv['dropdown'] . '->' . $total_footer_arr[$cat_key] . '|';
1472 }
1473 }
1474 $recent_category = rtrim($recent_category, '|');
1475 }
1476 }
1477
1478 $this->data[$postId]['widget_recent-posts'] = $recent_post;
1479 $this->data[$postId]['widget_pages'] = $recent_page;
1480 $this->data[$postId]['widget_recent-comments'] = $recent_comment;
1481 $this->data[$postId]['widget_archives'] = $recent_archive;
1482 $this->data[$postId]['widget_categories'] = $recent_category;
1483 }
1484
1485 /**
1486 * Function used to fetch the Terms & Taxonomies for the specific posts
1487 *
1488 * @param $id
1489 * @param $type
1490 * @param $optionalType
1491 */
1492 public function getTermsAndTaxonomies($id, $type, $optionalType)
1493 {
1494 $TermsData = array();
1495
1496 if ($type == 'WooCommerce' || ($type == 'CustomPosts' && $type == 'WooCommerce')) {
1497 $type = 'product';
1498 $postTags = '';
1499 $taxonomies = get_object_taxonomies($type);
1500 $get_tags = get_the_terms($id, 'product_tag');
1501 if ($get_tags) {
1502 foreach ($get_tags as $tags) {
1503 $postTags .= $tags->name . ',';
1504 }
1505 }
1506 $postTags = substr($postTags, 0, -1);
1507 $this->data[$id]['product_tag'] = $postTags;
1508 foreach ($taxonomies as $taxonomy) {
1509 $postCategory = '';
1510 if ($taxonomy == 'product_cat' || $taxonomy == 'product_category') {
1511 $get_categories = get_the_terms($id, $taxonomy);
1512 if ($get_categories) {
1513 $postCategory = $this->hierarchy_based_term_name($get_categories, $taxonomy);
1514 // foreach($get_categories as $category){
1515 // $postCategory .= $this->hierarchy_based_term_name($category, $taxonomy) . ',';
1516 // }
1517
1518 }
1519 $postCategory = substr($postCategory, 0, -1);
1520 $this->data[$id]['product_category'] = $postCategory;
1521 } else {
1522 $get_categories = get_the_terms($id, $taxonomy);
1523 if ($get_categories) {
1524 $postCategory = $this->hierarchy_based_term_name($get_categories, $taxonomy);
1525 // foreach($get_categories as $category){
1526 // $postCategory .= $this->hierarchy_based_term_name($category, $taxonomy) . ',';
1527 // }
1528
1529 }
1530 $postCategory = substr($postCategory, 0, -1);
1531 $this->data[$id][$taxonomy] = $postCategory;
1532 }
1533 }
1534 if ($type == 'WooCommerce' && $type != 'CustomPosts') {
1535 $product = wc_get_product($id);
1536 $pro_type = $product->get_type();
1537 switch ($pro_type) {
1538 case 'simple':
1539 $product_type = 1;
1540 break;
1541 case 'grouped':
1542 $product_type = 2;
1543 break;
1544 case 'external':
1545 $product_type = 3;
1546 break;
1547 case 'variable':
1548 $product_type = 4;
1549 break;
1550 case 'subscription':
1551 $product_type = 5;
1552 break;
1553 case 'variable-subscription':
1554 $product_type = 6;
1555 break;
1556 case 'bundle':
1557 $product_type = 7;
1558 break;
1559 default:
1560 $product_type = 1;
1561 break;
1562 }
1563 $this->data[$id]['product_type'] = $product_type;
1564 }
1565
1566 //product_shipping_class
1567 $shipping = get_the_terms($id, 'product_shipping_class');
1568 if ($shipping) {
1569 $taxo_shipping = $shipping[0]->name;
1570 $this->data[$id]['product_shipping_class'] = $taxo_shipping;
1571 }
1572 //product_shipping_class
1573
1574 } else if ($type == 'WPeCommerce') {
1575 $type = 'wpsc-product';
1576 $postTags = $postCategory = '';
1577 $taxonomies = get_object_taxonomies($type);
1578 $get_tags = get_the_terms($id, 'product_tag');
1579 if ($get_tags) {
1580 foreach ($get_tags as $tags) {
1581 $postTags .= $tags->name . ',';
1582 }
1583 }
1584 $postTags = substr($postTags, 0, -1);
1585 $this->data[$id]['product_tag'] = $postTags;
1586 foreach ($taxonomies as $taxonomy) {
1587 $postCategory = '';
1588 if ($taxonomy == 'wpsc_product_category') {
1589 $get_categories = wp_get_post_terms($id, $taxonomy);
1590 if ($get_categories) {
1591 $postCategory = $this->hierarchy_based_term_name($get_categories, $taxonomy);
1592
1593 }
1594 $postCategory = substr($postCategory, 0, -1);
1595 $this->data[$id]['product_category'] = $postCategory;
1596 } else {
1597 $get_categories = wp_get_post_terms($id, $taxonomy);
1598 if ($get_categories) {
1599 $postCategory = $this->hierarchy_based_term_name($get_categories, $taxonomy);
1600
1601 }
1602 $postCategory = substr($postCategory, 0, -1);
1603 $this->data[$id]['product_category'] = $postCategory;
1604 }
1605 }
1606 } else {
1607 global $wpdb;
1608 $postTags = $postCategory = '';
1609 // $taxonomyId = $wpdb->get_col($wpdb->prepare("select term_taxonomy_id from {$wpdb->prefix}term_relationships where object_id = %d", $id));
1610 $taxonomyId = $wpdb->get_col("SELECT term_taxonomy_id FROM {$wpdb->prefix}term_relationships WHERE object_id = {$id}");
1611 $taxo = [];
1612 $termTaxonomyIds = array();
1613 foreach ($taxonomyId as $taxonomyIds) {
1614
1615 // $termTaxonomyId = $wpdb->get_results($wpdb->prepare("select term_id from {$wpdb->prefix}term_taxonomy where term_taxonomy_id = %d", $taxonomyIds));
1616 $termTaxonomyId = $wpdb->get_results("SELECT term_id FROM {$wpdb->prefix}term_taxonomy WHERE term_taxonomy_id = {$taxonomyIds}");
1617 foreach ($termTaxonomyId as $term) {
1618 $termTaxonomyIds[] = $term->term_id;
1619 }
1620 }
1621 foreach ($termTaxonomyIds as $taxonomy) {
1622
1623 $taxo[] = get_term($taxonomy);
1624 }
1625 foreach ($taxonomyId as $taxonomy) {
1626 $taxonomytypeid = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}term_taxonomy WHERE term_taxonomy_id='$taxonomy' ");
1627 if ($taxonomytypeid[0]->taxonomy == 'course_category') {
1628 $taxonomyTypeId = $wpdb->get_col($wpdb->prepare("select term_id from {$wpdb->prefix}term_taxonomy where term_taxonomy_id = %d", $taxonomytypeid[0]->term_taxonomy_id));
1629 $taxonomy_Type_Id = $taxonomyTypeId[0];
1630 $taxo0[] = get_term($taxonomy_Type_Id);
1631 }
1632 if ($taxonomytypeid[0]->taxonomy == 'course_tag') {
1633 $taxonomyTypeId1 = $wpdb->get_col($wpdb->prepare("select term_id from {$wpdb->prefix}term_taxonomy where term_taxonomy_id = %d", $taxonomytypeid[0]->term_taxonomy_id));
1634 $taxonomy_Type_Id1 = $taxonomyTypeId1[0];
1635 $taxo2[] = get_term($taxonomy_Type_Id1);
1636 }
1637 }
1638
1639 if (!empty($taxo)) {
1640 foreach ($taxo as $key => $taxo_val) {
1641 if ($taxo_val->taxonomy == 'category') {
1642 $taxo1[] = $taxo_val;
1643 }
1644 }
1645 }
1646
1647 if (!empty($taxonomyId)) {
1648 foreach ($taxonomyId as $taxonomy) {
1649 $taxonomyType = $wpdb->get_col($wpdb->prepare("select taxonomy from {$wpdb->prefix}term_taxonomy where term_taxonomy_id = %d", $taxonomy));
1650 if (!empty($taxonomyType)) {
1651 foreach ($taxonomyType as $taxanomy_name) {
1652 if ($taxanomy_name == 'category') {
1653 $termName = 'post_category';
1654 } else {
1655 $termName = $taxanomy_name;
1656 }
1657 if (in_array($termName, $this->headers)) {
1658 if ($termName != 'post_tag' && $termName != 'post_category') {
1659 $postterm1 = $postterm2 = '';
1660 $taxonomyData = $wpdb->get_col($wpdb->prepare("select name from {$wpdb->prefix}terms where term_id = %d", $taxonomy));
1661 if (!empty($taxonomyData)) {
1662
1663 if (isset($TermsData[$termName])) {
1664 $this->data[$id][$termName] = $TermsData[$termName] . ',' . $taxonomyData[0];
1665 } else {
1666 $get_exist_data = isset($this->data[$id][$termName]) ? $this->data[$id][$termName] : '';
1667 }
1668
1669 if ($get_exist_data == '') {
1670 $this->data[$id][$termName] = $taxonomyData[0];
1671 } else {
1672 $taxonomyID = $wpdb->get_col($wpdb->prepare("select term_id from {$wpdb->prefix}terms where name = %s", $taxonomyData[0]));
1673 if ($taxanomy_name == 'course_category') {
1674 foreach ($taxo0 as $taxo_key => $taxo_value) {
1675 $postterm1 .= $taxo_value->name . ',';
1676 }
1677 $this->data[$id][$termName] = rtrim($postterm1, ',');
1678 } elseif ($taxanomy_name == 'course_tag') {
1679 foreach ($taxo2 as $taxo_key1 => $taxo_value1) {
1680 $postterm2 .= $taxo_value1->name . ',';
1681 }
1682 $this->data[$id][$termName] = rtrim($postterm2, ',');
1683 } else {
1684 $postterm = substr($this->hierarchy_based_term_name($taxo, $taxanomy_name), 0, -1);
1685 $this->data[$id][$termName] = $postterm;
1686 }
1687 }
1688
1689 }
1690 } else {
1691 if (!isset($TermsData['post_tag'])) {
1692 if ($termName == 'post_tag') {
1693 $postTags = '';
1694 $get_tags = wp_get_post_tags($id, array(
1695 'fields' => 'names'
1696 ));
1697 foreach ($get_tags as $tags) {
1698 $postTags .= $tags . ',';
1699 }
1700 $postTags = substr($postTags, 0, -1);
1701 $this->data[$id][$termName] = $postTags;
1702 }
1703 if ($termName == 'post_category') {
1704 $postCategory = '';
1705 $get_categories = wp_get_post_categories($id, array(
1706 'fields' => 'names'
1707 ));
1708
1709 $postterm1 = substr($this->hierarchy_based_term_name($taxo1, $taxanomy_name), 0, -1);
1710 $this->data[$id][$termName] = $postterm1;
1711
1712 }
1713
1714 }
1715 }
1716 } else {
1717 $this->data[$id][$termName] = '';
1718 }
1719 }
1720 }
1721 }
1722 }
1723 }
1724 }
1725
1726 /**
1727 * Get user role based on the capability
1728 * @param null $capability - User capability
1729 * @return int|string - Role of the user
1730 */
1731 public function getUserRole($capability = null)
1732 {
1733 if ($capability != null) {
1734 $getRole = unserialize($capability);
1735 foreach ($getRole as $roleName => $roleStatus) {
1736 $role = $roleName;
1737 }
1738 return $role;
1739 } else {
1740 return 'subscriber';
1741 }
1742 }
1743
1744 /**
1745 * Get activated plugins
1746 * @return mixed
1747 */
1748 public function get_active_plugins()
1749 {
1750 $active_plugins = get_option('active_plugins');
1751 return $active_plugins;
1752 }
1753 public function array_to_xml($data, &$xml_data)
1754 {
1755 foreach ($data as $key => $value) {
1756 if (is_numeric($key)) {
1757 $key = 'item';
1758 }
1759 if (strpos($key, '::') !== false) {
1760 $key = str_replace('::', '_COLON_', $key);
1761 $key = str_replace(' ', '_', $key);
1762 }
1763 if (is_array($value)) {
1764 $subnode = $xml_data->addChild($key);
1765 $this->array_to_xml($value, $subnode);
1766 } else {
1767 $xml_data->addChild("$key", htmlspecialchars("$value"));
1768 }
1769 }
1770 }
1771 public function getPolylangData($id, $optional_type, $exp_module = null)
1772 {
1773 global $wpdb;
1774 global $sitepress;
1775 $post_title = '';
1776 if ($exp_module == 'Categories' || $exp_module == 'Tags' || $exp_module == 'Taxonomies') {
1777 $like = '%' . $wpdb->esc_like((string) $id) . '%';
1778 $terms = $wpdb->get_results($wpdb->prepare("select term_taxonomy_id from {$wpdb->prefix}term_taxonomy where description like %s", $like), ARRAY_A);
1779 $terms_id = json_decode(json_encode($terms), true);
1780 } else {
1781 $terms = $wpdb->get_results($wpdb->prepare("select term_taxonomy_id from {$wpdb->term_relationships} where object_id = %d order by term_taxonomy_id desc", absint($id)));
1782 $terms_id = json_decode(json_encode($terms), true);
1783 }
1784 if (is_plugin_active('polylang-pro/polylang.php')) {
1785 if ($exp_module == 'Categories' || $exp_module == 'Tags' || $exp_module == 'Taxonomies') {
1786 $get_language = pll_get_term_language($id);
1787 $get_translation = pll_get_term_translations($id);
1788 unset($get_translation[$get_language]);
1789 $this->data[$id]['language_code'] = $get_language;
1790 foreach ($get_translation as $trans_key => $trans_val) {
1791 $title = $wpdb->get_var("SELECT name FROM {$wpdb->prefix}terms where term_id=$trans_val");
1792 $post_title .= $title . ',';
1793 }
1794 $this->data[$id]['translated_taxonomy_title'] = rtrim($post_title, ',');
1795 } else {
1796 $get_language = pll_get_post_language($id);
1797 $get_translation = pll_get_post_translations($id);
1798 unset($get_translation[$get_language]);
1799 $this->data[$id]['language_code'] = $get_language;
1800 foreach ($get_translation as $trans_key => $trans_val) {
1801 $title = $wpdb->get_var("SELECT post_title FROM {$wpdb->prefix}posts where id=$trans_val");
1802 $post_title .= $title . ',';
1803 }
1804 $this->data[$id]['translated_post_title'] = rtrim($post_title, ',');
1805 }
1806 } else {
1807 foreach ($terms_id as $termkey => $termvalue) {
1808 $post_title = '';
1809 $termids = $termvalue['term_taxonomy_id'];
1810 $check = $wpdb->get_var("select taxonomy from $wpdb->term_taxonomy where term_taxonomy_id ='{$termids}'");
1811 if ($check == 'category') {
1812 $category = $wpdb->get_var("select name from $wpdb->terms where term_id ='{$termids}'");
1813 } elseif ($check == 'language') {
1814 $language = $wpdb->get_var("select description from $wpdb->term_taxonomy where term_id ='{$termids}'");
1815 $lang = unserialize($language);
1816 $langcode = explode('_', $lang['locale']);
1817 $lang_code = $langcode[0];
1818 $this->data[$id]['language_code'] = $lang_code;
1819
1820 } elseif ($check == 'term_language') {
1821 if ($exp_module == 'Categories' || $exp_module == 'Tags' || $exp_module == 'Taxonomies') {
1822 $language = $wpdb->get_var("select description from $wpdb->term_taxonomy where term_taxonomy_id ='{$termids}'");
1823 $lang = unserialize($language);
1824 $langcode = explode('_', $lang['locale']);
1825 $lang_code = $langcode[0];
1826 if (empty($this->data[$id]['language_code'])) {
1827 $this->data[$id]['language_code'] = $lang_code;
1828 }
1829
1830 }
1831 } elseif (($exp_module == 'Categories' || $exp_module == 'Tags' || $exp_module == 'Taxonomies') && $check == 'term_translations') {
1832 $description = $wpdb->get_var("select description from $wpdb->term_taxonomy where term_taxonomy_id ='{$termids}'");
1833 $desc = unserialize($description);
1834 //$post_id = is_array($desc) ? array_values($desc) : array();
1835 $post_id = is_array($desc) ? $desc : array();
1836
1837 // $postid = min($post_id);
1838 foreach ($post_id as $post_key => $post_value) {
1839 if ($id == $post_value) {
1840 $this->data[$id]['language_code'] = $post_key;
1841 unset($post_id[$post_key]);
1842 }
1843 }
1844
1845 foreach ($post_id as $trans_key => $trans_val) {
1846 $title = $wpdb->get_var("SELECT name FROM {$wpdb->prefix}terms where term_id=$trans_val");
1847 $post_title .= $title . ',';
1848 }
1849
1850 $this->data[$id]['translated_taxonomy_title'] = rtrim($post_title, ',');
1851 } elseif (($exp_module !== 'Categories' && $exp_module !== 'Tags') && $check == 'post_translations') {
1852 $description = $wpdb->get_var("select description from $wpdb->term_taxonomy where term_id ='{$termids}'");
1853 $desc = unserialize($description);
1854 $post_id = is_array($desc) ? array_values($desc) : array();
1855 // $postid = min($post_id);
1856 foreach ($post_id as $post_key => $post_value) {
1857 if ($id == $post_value) {
1858 unset($post_id[$post_key]);
1859 }
1860 }
1861 foreach ($post_id as $trans_key => $trans_val) {
1862 $post_title = $wpdb->get_var("select post_title from $wpdb->posts where ID ='{$trans_val}'");
1863 $this->data[$id]['translated_post_title'] = $post_title;
1864 }
1865 } elseif ($check == 'post_tag') {
1866 $tag = $wpdb->get_var("select name from $wpdb->terms where term_id ='{$termids}'");
1867
1868 }
1869 }
1870 }
1871 }
1872
1873 public function getGeoPlaceData($id, $optional_type, $exp_module)
1874 {
1875
1876 $post_info = geodir_get_post_info($id);
1877 foreach ($post_info as $gdKey => $gdVal) {
1878 if (!empty($gdVal)) {
1879 $this->data[$id][$gdKey] = $gdVal;
1880 }
1881 }
1882 }
1883
1884 public function getPostTypes()
1885 {
1886 $custom_array = array('post', 'page', 'wpsc-product', 'product_variation', 'shop_order', 'shop_coupon', 'shop_order_refund', 'mp_product_variation');
1887 $other_posttypes = array('attachment', 'revision', 'wpsc-product-file', 'mp_order', 'shop_webhook', 'custom_css', 'customize_changeset', 'oembed_cache', 'user_request', '_pods_template', 'wpmem_product', 'wp-types-group', 'wp-types-user-group', 'wp-types-term-group', 'gal_display_source', 'display_type', 'displayed_gallery', 'wpsc_log', 'lightbox_library', 'scheduled-action', 'cfs', '_pods_pod', '_pods_field', 'acf-field', 'acf-field-group', 'wp_block', 'ngg_album', 'ngg_gallery', 'nf_sub', 'wpcf7_contact_form', 'iv_payment', 'llms_quiz', 'llms_question', 'llms_membership', 'llms_engagement', 'llms_order', 'llms_transaction', 'llms_achievement', 'llms_my_achievement', 'llms_my_certificate', 'llms_email', 'llms_voucher', 'llms_access_plan', 'llms_form', 'section', 'llms_certificate');
1888 $importas = array(
1889 'Posts' => 'Posts',
1890 'Pages' => 'Pages',
1891 'Users' => 'Users',
1892 'Comments' => 'Comments',
1893
1894 );
1895 $all_post_types = get_post_types();
1896 array_push($all_post_types, 'widgets');
1897 // To avoid toolset repeater group fields from post types in dropdown
1898 global $wpdb;
1899 $fields = $wpdb->get_results("select meta_value from {$wpdb->prefix}postmeta where meta_key = '_wp_types_group_fields' ");
1900 foreach ($fields as $value) {
1901 $repeat_values = $value->meta_value;
1902 $types_fields = explode(',', $repeat_values);
1903
1904 foreach ($types_fields as $types_value) {
1905 $explode = explode('_', $types_value);
1906 if (count($explode) > 1) {
1907 if (in_array('repeatable', $explode)) {
1908 $name = $wpdb->get_results("SELECT post_name FROM " . $wpdb->prefix . "posts WHERE id ='{$explode[3]}'");
1909 $type_repeat_value = $name[0]->post_name;
1910
1911 if (in_array($type_repeat_value, $all_post_types)) {
1912 unset($all_post_types[$type_repeat_value]);
1913 }
1914 } else {
1915
1916 }
1917 } else {
1918
1919 }
1920 }
1921 }
1922
1923 foreach ($other_posttypes as $ptkey => $ptvalue) {
1924 if (in_array($ptvalue, $all_post_types)) {
1925 unset($all_post_types[$ptvalue]);
1926 }
1927 }
1928 foreach ($all_post_types as $key => $value) {
1929 if (!in_array($value, $custom_array)) {
1930 if (is_plugin_active('events-manager/events-manager.php') && $value == 'event') {
1931 $importas['Events'] = $value;
1932 } elseif (is_plugin_active('events-manager/events-manager.php') && $value == 'event-recurring') {
1933 $importas['Recurring Events'] = $value;
1934 } elseif (is_plugin_active('events-manager/events-manager.php') && $value == 'location') {
1935 $importas['Event Locations'] = $value;
1936 } else {
1937 $importas[$value] = $value;
1938 }
1939 $custompost[$value] = $value;
1940 }
1941 }
1942 //Ticket import
1943 if (is_plugin_active('events-manager/events-manager.php')) {
1944 $importas['Tickets'] = 'ticket';
1945 }
1946 if (is_plugin_active('wp-customer-reviews/wp-customer-reviews-3.php') || is_plugin_active('wp-customer-reviews/wp-customer-reviews.php')) {
1947 $importas['Customer Reviews'] = 'CustomerReviews';
1948 if (isset($importas['wpcr3_review'])) {
1949 unset($importas['wpcr3_review']);
1950 }
1951 }
1952
1953 // Add JetReviews if the JetReviews plugin is active
1954 if (is_plugin_active('jet-reviews/jet-reviews.php')) {
1955 $importas['JetReviews'] = 'jetreviews';
1956 }
1957 if (is_plugin_active('woocommerce/woocommerce.php')) {
1958 $importas['WooCommerce Product'] = 'WooCommerce';
1959 // $importas['WooCommerce Product Variations'] ='WooCommerceVariations';
1960 $importas['WooCommerce Orders'] = 'WooCommerceOrders';
1961 $importas['WooCommerce Customer'] = 'WooCommerceCustomer';
1962 $importas['WooCommerce Reviews'] = 'WooCommerceReviews';
1963 $importas['WooCommerce Coupons'] = 'WooCommerceCoupons';
1964 $importas['WooCommerce Refunds'] = 'WooCommerceRefunds';
1965 unset($importas['product']);
1966 }
1967 if (is_plugin_active('wp-e-commerce/wp-shopping-cart.php')) {
1968 $importas['WPeCommerce Products'] = 'WPeCommerce';
1969 $importas['WPeCommerce Coupons'] = 'WPeCommerceCoupons';
1970 }
1971 if (is_plugin_active('gravityforms/gravityforms.php')) {
1972 $importas['GFEntries'] = 'GFEntries';
1973
1974 }
1975 if (is_plugin_active('jet-engine/jet-engine.php')) {
1976 $get_slug_name = $wpdb->get_results("SELECT slug FROM {$wpdb->prefix}jet_post_types WHERE status = 'content-type'");
1977
1978 if (!empty($get_slug_name)) {
1979 foreach ($get_slug_name as $key => $get_slug) {
1980 $value = $get_slug->slug;
1981 $importas[$value] = $value;
1982 }
1983 }
1984 }
1985 if (is_plugin_active('jet-booking/jet-booking.php')) {
1986 $importas['JetBooking'] = 'JetBooking';
1987 }
1988 return $importas;
1989
1990 }
1991
1992 public function getTaxonomies()
1993 {
1994 $i = 0;
1995 foreach (get_taxonomies() as $key => $value) {
1996 $response['taxonomies'][$i] = $value;
1997 $i++;
1998 }
1999 return $response;
2000
2001 }
2002
2003 /**
2004 * Export Data
2005 * @param $data
2006 */
2007 public function proceedExport($data)
2008 {
2009 //need this revert again
2010 if (is_user_logged_in() && current_user_can('administrator')) {
2011 $upload_dir = ABSPATH . 'wp-content/uploads/smack_uci_uploads/exports/';
2012 $index_php_file = $upload_dir . 'index.php';
2013
2014 if (!file_exists($index_php_file)) {
2015 $file_content = '<?php' . PHP_EOL . '?>';
2016 file_put_contents($index_php_file, $file_content);
2017 }
2018
2019 if (empty($this->random_data)) {
2020 $random_folder = wp_generate_password(16, false); // 16-character random folder name
2021 $upload_dir = $upload_dir . $random_folder . '/';
2022 } else {
2023 $random_folder = $this->random_data;
2024 $upload_dir = $upload_dir . $random_folder . '/';
2025 }
2026 if (!is_dir($upload_dir)) {
2027 wp_mkdir_p($upload_dir);
2028 }
2029 $base_dir = wp_upload_dir();
2030 $upload_url = $base_dir['baseurl'] . '/smack_uci_uploads/exports/' . $random_folder . '/';
2031 chmod($upload_dir, 0777);
2032 }
2033
2034 if ($this->checkSplit == 'true') {
2035 $i = 1;
2036 while ($i != 0) {
2037 $file = $upload_dir . $this->fileName . '_' . $i . '.' . $this->exportType;
2038 if (file_exists($file)) {
2039 $allfiles[$i] = $file;
2040 $i++;
2041 } else
2042 break;
2043 }
2044 $fileURL = $upload_url . $this->fileName . '_' . $i . '.' . $this->exportType;
2045 } else {
2046 $file = $upload_dir . $this->fileName . '.' . $this->exportType;
2047 $fileURL = $upload_url . $this->fileName . '.' . $this->exportType;
2048 }
2049
2050 $spsize = 100;
2051 if ($this->offset == 0) {
2052 if (file_exists($file))
2053 unlink($file);
2054 }
2055
2056 $checkRun = "no";
2057 if ($this->checkSplit == 'true' && ($this->totalRowCount - $this->offset) > 0) {
2058 $checkRun = 'yes';
2059 }
2060 if ($this->checkSplit != 'true') {
2061 $checkRun = 'yes';
2062 }
2063
2064 if ($checkRun == 'yes') {
2065 $this->isPreview = $_POST['isPreview'];
2066 if ($this->exportType == 'xml') {
2067 $xml_data = new \SimpleXMLElement('<?xml version="1.0"?><data></data>');
2068
2069
2070 // Check if preview is true
2071 if ($this->isPreview === 'true') {
2072
2073 $limitedData = array_slice($data, 0, 10);
2074 $this->array_to_xml($limitedData, $xml_data);
2075 $dom = new \DOMDocument('1.0', 'UTF-8');
2076 $dom->preserveWhiteSpace = false;
2077 $dom->formatOutput = true;
2078 $dom->loadXML($xml_data->asXML());
2079
2080 echo $dom->saveXML();
2081 wp_die();
2082 } else {
2083 $this->array_to_xml($data, $xml_data);
2084 $result = $xml_data->asXML($file);
2085 }
2086 } elseif ($this->exportType == 'tsv') {
2087 $files = fopen($file, "w");
2088 $headers = array_keys(reset($data)); // Get the keys from the first post
2089 fputcsv($files, $headers, "\t");
2090
2091 foreach ($data as $row) {
2092 fputcsv($files, $row, "\t"); // Use tab as delimiter
2093 }
2094
2095 if ($this->isPreview === 'true') {
2096 $privewJson = array_slice($data, 0, 10);
2097 $jsonData = json_encode($privewJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
2098
2099 $data = json_decode($jsonData, true);
2100
2101 // Get headers from the first item
2102 $headers = array_keys($data[0]);
2103
2104 // Slice first 10 items (or less if not available)
2105 $first10 = array_slice($data, 0, 10);
2106
2107 // Convert each item to a row of values
2108 $rows = array_map(function ($item) use ($headers) {
2109 return array_map(fn($key) => $item[$key], $headers);
2110 }, $first10);
2111
2112 // Final result: headers + first 10 rows
2113 $result = array_merge([$headers], $rows);
2114
2115 // Preview as JSON
2116 header('Content-Type: application/json');
2117 echo json_encode($result, JSON_PRETTY_PRINT);
2118 wp_die();
2119 }
2120
2121 } else {
2122 if ($this->exportType == 'json') {
2123 $csvData = json_encode($data);
2124
2125 if ($this->isPreview === 'true') {
2126
2127 $privewJson = array_slice($data, 0, 10);
2128 header('Content-Type: application/json; charset=utf-8');
2129 echo json_encode($privewJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
2130 wp_die();
2131 }
2132 } else {
2133 $csvData = $this->unParse($data, $this->headers);
2134
2135 // Check if migration is true
2136 if ($this->isPreview === 'true') {
2137 $privewJson = array_slice($data, 0, 10);
2138 $jsonData = json_encode($privewJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
2139
2140 $data = json_decode($jsonData, true);
2141
2142 // Get headers from the first item
2143 $headers = array_keys($data[0]);
2144
2145 // Slice first 10 items (or less if not available)
2146 $first10 = array_slice($data, 0, 10);
2147
2148 // Convert each item to a row of values
2149 $rows = array_map(function ($item) use ($headers) {
2150 return array_map(fn($key) => $item[$key], $headers);
2151 }, $first10);
2152
2153 // Final result: headers + first 10 rows
2154 $result = array_merge([$headers], $rows);
2155
2156 // Preview as JSON
2157 header('Content-Type: application/json');
2158 echo json_encode($result, JSON_PRETTY_PRINT);
2159 wp_die();
2160 }
2161 }
2162 try {
2163
2164 file_put_contents($file, $csvData, FILE_APPEND | LOCK_EX);
2165
2166 } catch (\Exception $e) {
2167 // TODO - write exception in log
2168
2169 }
2170 }
2171
2172 }
2173
2174 $this->offset = $this->offset + $this->limit;
2175
2176 $filePath = $upload_dir . $this->fileName . '.' . $this->exportType;
2177 $filename = $fileURL;
2178 if (($this->offset) > ($this->totalRowCount) && $this->checkSplit == 'true') {
2179 $allfiles[$i] = $file;
2180 $zipname = $upload_dir . $this->fileName . '.' . 'zip';
2181 $zip = new \ZipArchive;
2182 $zip->open($zipname, \ZipArchive::CREATE);
2183 foreach ($allfiles as $allfile) {
2184 $newname = str_replace($upload_dir, '', $allfile);
2185 $zip->addFile($allfile, $newname);
2186 }
2187 $zip->close();
2188 $fileURL = $upload_url . $this->fileName . '.' . 'zip';
2189 foreach ($allfiles as $removefile) {
2190 unlink($removefile);
2191 }
2192 $filename = $upload_url . $this->fileName . '.' . 'zip';
2193 }
2194
2195 // Define the export file (CSV or other type)
2196 $file = $upload_dir . $this->fileName . '.' . $this->exportType;
2197 $allfiles[] = $file;
2198 $this->isMigration = $_POST['isMigrate'];
2199 // Check if migration is true
2200 if ($this->isMigration === 'true' && (($this->offset) > ($this->totalRowCount))) {
2201
2202 $module = $this->module;
2203 // Create JSON file
2204 $headers = self::generateHeaders($this->module, $this->optionalType);
2205 if ($module == 'CustomPosts' || $module == 'Taxonomies' || $module == 'Categories' || $module == 'Tags') {
2206 if (is_plugin_active('events-manager/events-manager.php') && $optionalType == 'event') {
2207 $optionalType = 'Events';
2208 }
2209 $default = $this->get_fields($optionalType); // Call the super class function
2210
2211 } else {
2212 $default = $this->get_fields($module);
2213 }
2214
2215
2216 function transformFieldsArray($fieldsArray)
2217 {
2218 $csv_fields = [];
2219 $fields = [];
2220
2221 foreach ($fieldsArray as $fieldGroup) {
2222 $groupKey = key($fieldGroup); // Get the group name (e.g., "core_fields", "terms_and_taxonomies")
2223 $groupFields = [];
2224
2225 foreach ($fieldGroup[$groupKey] as $field) {
2226 $groupFields[] = [
2227 'label' => $field['label'],
2228 'name' => $field['name']
2229 ];
2230 $csv_fields[] = $field['name']; // Collect all field names for CSV
2231 }
2232
2233 $fields[] = [$groupKey => $groupFields];
2234 }
2235
2236 return [
2237 'csv_fields' => array_values(array_unique($csv_fields)), // Ensure unique field names
2238 'fields' => $fields
2239 ];
2240 }
2241
2242
2243 $fieldsArray = $default['fields'];
2244 $headers = transformFieldsArray($fieldsArray);
2245
2246
2247 $jsonFile = $upload_dir . $this->fileName . '.json';
2248
2249 if ($this->exportType == 'json') {
2250 $jsonFile = $upload_dir . $this->fileName . 'config' . '.json';
2251 } else {
2252 $jsonFile = $upload_dir . $this->fileName . '.json';
2253 }
2254
2255 $postTypes = $this->getPostTypes();
2256
2257 $import_record_post = array_keys($postTypes);
2258 // if(is_plugin_active('woocommerce/woocommerce.php')){
2259 // $importas = [
2260 // 'WooCommerce' => 'WooCommerce Product' ,
2261 // //'WooCommerce Product Variations' , 'WooCommerceVariations',
2262 // 'WooCommerceOrders' => 'WooCommerce Orders' ,
2263 // 'WooCommerceCustomer' => 'WooCommerce Customer' ,
2264 // 'WooCommerceReviews' => 'WooCommerce Reviews' ,
2265 // 'WooCommerceCoupons' => 'WooCommerce Coupons' ,
2266 // 'WooCommerceRefunds' => 'WooCommerce Refunds' ,
2267 // ];
2268
2269 // if (isset($importas[$this->module])) {
2270 // $this->module = $importas[$this->module];
2271 // }
2272
2273 // }
2274
2275
2276
2277
2278
2279 $taxonomies = $this->getTaxonomies();
2280 $jsonData = [
2281 'file_name' => $this->fileName,
2282 'total_rows' => $this->totalRowCount,
2283 'selectedtype' => $this->module,
2284 'optionalType' => $this->optionalType,
2285 'headers' => $headers,
2286 'export_time' => date('Y-m-d H:i:s'),
2287 'status' => 'completed',
2288 'posttype' => $import_record_post,
2289 'taxonomy' => $taxonomies['taxonomies'],
2290 'currentuser' => 'administrator',
2291 'get_key' => false,
2292 'show_template' => false,
2293 'file_iteration' => 5,
2294 'MediaType' => 'Local',
2295 'update_fields' => ['ID', 'post_title', 'post_name'],
2296 'use_ExistingImage' => true,
2297 'media_handle_option' => true,
2298 'postContent_image_option' => false,
2299 'highspeed' => false,
2300 'mappingFilterCheck' => false
2301 ];
2302
2303 file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT));
2304
2305 // Add JSON file to the list of files to zip
2306 $allfiles[] = $jsonFile;
2307
2308 // Create ZIP file (smbundle_ prefix)
2309 $zipname = $upload_dir . 'smbundle_' . $this->fileName . '.zip';
2310 $zip = new \ZipArchive;
2311
2312 if ($zip->open($zipname, \ZipArchive::CREATE) === true) {
2313 foreach ($allfiles as $allfile) {
2314 // Ensure only CSV, JSON, or related export files are included
2315 if (preg_match('/\.(csv|json|xml|xls|xlsx|tsv' . preg_quote($this->exportType, '/') . ')$/', $allfile)) {
2316 $newname = str_replace($upload_dir, '', $allfile);
2317 $zip->addFile($allfile, $newname);
2318 }
2319 }
2320 $zip->close();
2321 }
2322
2323 $zipURL = $upload_url . 'smbundle_' . $this->fileName . '.zip';
2324
2325 // Remove original files after zipping
2326 foreach ($allfiles as $removefile) {
2327 //unlink($removefile);
2328 }
2329
2330 $filename = $upload_dir . 'smbundle_' . $this->fileName . '.zip';
2331
2332 $responseTojQuery = array(
2333 'success' => true,
2334 'new_offset' => $this->offset,
2335 'limit' => $this->limit,
2336 'total_row_count' => $this->totalRowCount,
2337 'exported_file' => $fileURL,
2338 'zip_file' => $zipURL,
2339 'exported_path' => $filename,
2340 'export_type' => $this->exportType
2341 );
2342 echo wp_json_encode($responseTojQuery);
2343 wp_die();
2344 }
2345 //}
2346
2347 if ($this->checkSplit == 'true' && !($this->offset) > ($this->totalRowCount)) {
2348 $responseTojQuery = array(
2349 'success' => false,
2350 'new_offset' => $this->offset,
2351 'limit' => $this->limit,
2352 'total_row_count' => $this->totalRowCount,
2353 'exported_file' => $zipname,
2354 'exported_path' => $zipname,
2355 'export_type' => $this->exportType
2356 );
2357 } elseif ($this->checkSplit == 'true' && (($this->offset) > ($this->totalRowCount))) {
2358 if ($this->exportType == 'xls' || $this->exportType == 'xlsx') {
2359 // Convert CSV to XLS or XLSX depending on the export type
2360 $newpath = str_replace('.csv', '.' . $this->exportType, $filePath);
2361 $newfilename = str_replace('.csv', '.' . $this->exportType, $fileURL);
2362 if ($this->exportType == 'xlsx') {
2363 $reader = IOFactory::createReader('Xlsx');
2364 } else {
2365 $reader = IOFactory::createReader('Xls');
2366 }
2367 if (file_exists($filePath)) {
2368 $objPHPExcel = $reader->load($filePath);
2369 $spreadsheet = new Spreadsheet(); // Create new Spreadsheet object
2370 if ($this->exportType == 'xlsx') {
2371 $objWriter = IOFactory::createWriter($spreadsheet, 'Xlsx');
2372 } else {
2373 $objWriter = IOFactory::createWriter($spreadsheet, 'Xls');
2374 }
2375 $objWriter->save($newpath);
2376 }
2377
2378 // Response after conversion
2379 $responseTojQuery = array(
2380 'success' => true,
2381 'new_offset' => $this->offset,
2382 'limit' => $this->limit,
2383 'total_row_count' => $this->totalRowCount,
2384 'exported_file' => $newfilename,
2385 'exported_path' => $newpath,
2386 'export_type' => $this->exportType
2387 );
2388 } else {
2389 // If export type is neither XLS nor XLSX, return original file
2390 $responseTojQuery = array(
2391 'success' => true,
2392 'new_offset' => $this->offset,
2393 'limit' => $this->limit,
2394 'total_row_count' => $this->totalRowCount,
2395 'exported_file' => $fileURL,
2396 'exported_path' => $fileURL,
2397 'export_type' => $this->exportType
2398 );
2399 }
2400 } elseif (!(($this->offset) > ($this->totalRowCount))) {
2401 $responseTojQuery = array(
2402 'success' => false,
2403 'new_offset' => $this->offset,
2404 'limit' => $this->limit,
2405 'total_row_count' => $this->totalRowCount,
2406 // 'exported_file' => $random_folder.'/'.$filename,
2407 // 'exported_path' => $random_folder.'/'.$filePath,
2408 'exported_file' => $filename,
2409 'exported_path' => $filePath,
2410 'export_type' => $this->exportType,
2411 'random_data' => $random_folder
2412 );
2413 } else {
2414 // General case where we perform export
2415 if ($this->exportType == 'xls' || $this->exportType == 'xlsx') {
2416 // Convert CSV to XLS or XLSX depending on the export type
2417 $newpath = str_replace('.csv', '.' . $this->exportType, $filePath);
2418 $newfilename = str_replace('.csv', '.' . $this->exportType, $fileURL);
2419
2420 // Load the CSV and save as XLS or XLSX based on export type
2421 $reader = IOFactory::createReader('Csv');
2422 $objPHPExcel = $reader->load($filePath);
2423 if ($this->exportType == 'xls') {
2424 // If export type is XLS, save it as XLS
2425 $objWriter = IOFactory::createWriter($objPHPExcel, 'Xls');
2426 } else {
2427 // If export type is XLSX, save it as XLSX
2428 $objWriter = IOFactory::createWriter($objPHPExcel, 'Xlsx');
2429 }
2430 $objWriter->save($newpath);
2431
2432 $responseTojQuery = array(
2433 'success' => true,
2434 'new_offset' => $this->offset,
2435 'limit' => $this->limit,
2436 'total_row_count' => $this->totalRowCount,
2437 'exported_file' => $newfilename,
2438 'exported_path' => $newpath,
2439 'export_type' => $this->exportType
2440 );
2441 } else {
2442 // If export type is neither XLS nor XLSX, return original file
2443 $responseTojQuery = array(
2444 'success' => true,
2445 'new_offset' => $this->offset,
2446 'limit' => $this->limit,
2447 'total_row_count' => $this->totalRowCount,
2448 'exported_file' => $filename,
2449 'exported_path' => $filePath,
2450 'export_type' => $this->exportType
2451 );
2452 }
2453 }
2454 // $responseTojQuery["file_path"]=WP_PLUGIN_DIR . '/wp-ultimate-exporter/download.php';
2455 if ($this->export_mode == 'normal') {
2456 echo wp_json_encode($responseTojQuery);
2457 wp_die();
2458 } elseif ($this->export_mode == 'FTP') {
2459 $this->export_log = $responseTojQuery;
2460 }
2461 }
2462
2463 /**
2464 * Fetch ACF field information to be export
2465 * @param $recordId - Id of the Post (or) Page (or) Product (or) User
2466 */
2467 public function FetchACFData($recordId)
2468 {
2469
2470 }
2471
2472 /**
2473 * Get post data based on the record id
2474 * @param $id - Id of the records
2475 * @return array - Data based on the requested id.
2476 */
2477 public function getPostsDataBasedOnRecordId($id, $module = null)
2478 {
2479 global $wpdb;
2480 $PostData = array();
2481 $query1 = $wpdb->prepare("SELECT wp.* FROM {$wpdb->prefix}posts wp where ID=%d", $id);
2482 $result_query1 = $wpdb->get_results($query1);
2483 if (!empty($result_query1)) {
2484 foreach ($result_query1 as $posts) {
2485 if ($posts->post_type == 'event' || $posts->post_type == 'event-recurring') {
2486
2487 $loc = get_post_meta($id, '_location_id', true);
2488 $event_id = get_post_meta($id, '_event_id', true);
2489 $res = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}em_locations WHERE location_id='$loc' ");
2490
2491 if ($res) {
2492 foreach ($res as $location) {
2493 unset($location->post_content);
2494 $posts = array_merge((array) $posts, (array) $location);
2495 }
2496 }
2497
2498 $ticket = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}em_tickets WHERE event_id='$event_id' ");
2499
2500 $ticket[0] = isset($ticket[0]) ? $ticket[0] : '';
2501 $ticket_meta = $ticket[0];
2502 if (isset($ticket_meta->{'ticket_meta'})) {
2503 $ticket_meta_value = $ticket_meta->{'ticket_meta'};
2504 }
2505 $ticket_meta_value = isset($ticket_meta_value) ? $ticket_meta_value : '';
2506 $ticket_value = unserialize($ticket_meta_value);
2507 if (isset($ticket_id)) {
2508 $ticket_values = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}em_tickets WHERE ticket_id='$ticket_id' ");
2509 }
2510 $count = count($ticket);
2511 if ($count > 1) {
2512 $ticknamevalue = '';
2513 $tickidvalue = '';
2514 $eventidvalue = '';
2515 $tickdescvalue = '';
2516 $tickpricevalue = '';
2517 $tickstartvalue = '';
2518 $tickendvalue = '';
2519 $tickminvalue = '';
2520 $tickmaxvalue = '';
2521 $tickspacevalue = '';
2522 $tickmemvalue = '';
2523 $tickmemrolevalue = '';
2524 $tickguestvalue = '';
2525 $tickreqvalue = '';
2526 $tickparvalue = '';
2527 $tickordervalue = '';
2528 $tickmetavalue = '';
2529 $tickstartdays = '';
2530 $tickenddays = '';
2531 $tickstarttime = '';
2532 $tickendtime = '';
2533 $t = 0;
2534
2535 foreach ($ticket as $tic => $ticval) {
2536 $ticknamevalue .= $ticval->ticket_name . ', ';
2537 $tickidvalue .= $ticval->ticket_id . ', ';
2538 $eventidvalue .= $ticval->event_id . ', ';
2539 $tickdescvalue .= $ticval->ticket_description . ', ';
2540 $tickpricevalue .= $ticval->ticket_price . ', ';
2541 $tickstartvalue .= $ticval->ticket_start . ', ';
2542 $tickendvalue .= $ticval->ticket_end . ', ';
2543 $tickminvalue .= $ticval->ticket_min . ', ';
2544 $tickmaxvalue .= $ticval->ticket_max . ', ';
2545 $tickspacevalue .= $ticval->ticket_spaces . ', ';
2546 $tickmemvalue .= $ticval->ticket_members . ', ';
2547 $tickmemroles = unserialize($ticval->ticket_members_roles);
2548 $tickmemroleval = implode('| ', (array) $tickmemroles);
2549 $tickmemrolevalue .= $tickmemroleval . ', ';
2550
2551
2552 $tickguestvalue .= $ticval->ticket_guests . ', ';
2553 $tickreqvalue .= $ticval->ticket_required . ', ';
2554 $tickparvalue .= $ticval->ticket_parent . ', ';
2555 $tickordervalue .= $ticval->ticket_order . ', ';
2556 $tickmetavalue .= $ticval->ticket_meta . ', ';
2557 $ticket[$t] = isset($ticket[$t]) ? $ticket[$t] : '';
2558 $ticket_meta = $ticket[$t];
2559 if (isset($ticket_meta->{'ticket_meta'})) {
2560 $ticket_meta_value = $ticket_meta->{'ticket_meta'};
2561 }
2562 $ticket_meta_value = isset($ticket_meta_value) ? $ticket_meta_value : '';
2563 if (!empty($ticket_meta_value)) {
2564 $ticket_value = unserialize($ticket_meta_value);
2565 }
2566
2567 foreach ($ticket_value as $tickval => $val) {
2568 $tickstartdays .= $val['start_days'] . ', ';
2569 $tickenddays .= $val['end_days'] . ', ';
2570 $tickstarttime .= $val['start_time'] . ', ';
2571 $tickendtime .= $val['end_time'] . ', ';
2572 }
2573
2574 $ticknamevalues = rtrim($ticknamevalue, ', ');
2575 $tickidvalues = rtrim($tickidvalue, ', ');
2576 $eventidvalues = rtrim($eventidvalue, ', ');
2577 $tickdescvalues = rtrim($tickdescvalue, ', ');
2578 $tickpricevalues = rtrim($tickpricevalue, ', ');
2579 $tickstartvalues = rtrim($tickstartvalue, ', ');
2580 $tickendvalues = rtrim($tickendvalue, ', ');
2581 $tickminvalues = rtrim($tickminvalue, ', ');
2582 $tickmaxvalues = rtrim($tickmaxvalue, ', ');
2583 $tickspacevalues = rtrim($tickspacevalue, ', ');
2584 $tickmemvalues = rtrim($tickmemvalue, ', ');
2585 $tickmemrolevalues = rtrim($tickmemrolevalue, ', ');
2586 $tickguestvalues = rtrim($tickguestvalue, ', ');
2587 $tickreqvalues = rtrim($tickreqvalue, ', ');
2588 $tickparvalues = rtrim($tickparvalue, ', ');
2589 $tickordervalues = rtrim($tickordervalue, ', ');
2590 $tickmetavalues = rtrim($tickmetavalue, ', ');
2591 $tickstartdaysvalues = rtrim($tickstartdays, ', ');
2592 $tickenddaysvalues = rtrim($tickenddays, ', ');
2593 $tickstarttimevalues = rtrim($tickstarttime, ', ');
2594 $tickendtimevalues = rtrim($tickendtime, ', ');
2595
2596
2597 $tic_key1 = array('ticket_id', 'event_id', 'ticket_name', 'ticket_description', 'ticket_price', 'ticket_start', 'ticket_end', 'ticket_min', 'ticket_max', 'ticket_spaces', 'ticket_members', 'ticket_members_roles', 'ticket_guests', 'ticket_required', 'ticket_parent', 'ticket_order', 'ticket_meta', 'start_days', 'end_days', 'start_time', 'end_time');
2598 $tic_val1 = array($tickidvalues, $eventidvalues, $ticknamevalues, $tickdescvalues, $tickpricevalues, $tickstartvalues, $tickendvalues, $tickminvalues, $tickmaxvalues, $tickspacevalues, $tickmemvalues, $tickmemrolevalues, $tickguestvalues, $tickreqvalues, $tickparvalues, $tickordervalues, $tickmetavalues, $tickstartdaysvalues, $tickenddaysvalues, $tickstarttimevalues, $tickendtimevalues);
2599
2600 $tickets1 = array_combine($tic_key1, $tic_val1);
2601 $posts = array_merge((array) $posts, (array) $tickets1);
2602 $ticket_start[] = $ticval->ticket_start;
2603
2604 $ticket_start_date = '';
2605 $ticket_start_time = '';
2606 foreach ($ticket_start as $loc => $locval) {
2607 $date = strtotime($locval);
2608 $ticket_start_date .= date('Y-m-d', $date) . ', ';
2609
2610 $ticket_start_time .= date('H:i:s', $date) . ', ';
2611
2612
2613 }
2614 $ticket_start_times = rtrim($ticket_start_time, ', ');
2615 $ticket_start_dates = rtrim($ticket_start_date, ', ');
2616 $ticket_end[] = trim($ticval->ticket_end);
2617 $ticket_end_time = '';
2618 $ticket_end_date = '';
2619 foreach ($ticket_end as $loc => $locvalend) {
2620 if (isset($locvalend) && !empty($locvalend)) {
2621 $time = strtotime($locvalend);
2622 $ticket_end_date .= date('Y-m-d', $time) . ', ';
2623 $ticket_end_time .= date('H:i:s', $time) . ', ';
2624 }
2625
2626 }
2627 if (isset($ticket_start_date) && !empty($ticket_start_date)) {
2628 $ticket_end_times = rtrim($ticket_end_time, ', ');
2629 $ticket_end_dates = rtrim($ticket_end_date, ', ');
2630 $tic_key = array('ticket_start_date', 'ticket_start_time', 'ticket_end_date', 'ticket_end_time');
2631 $tic_val = array($ticket_start_dates, $ticket_start_times, $ticket_end_dates, $ticket_end_times);
2632 $tickets = array_combine($tic_key, $tic_val);
2633 $posts = array_merge((array) $posts, (array) $tickets);
2634 }
2635
2636 }
2637
2638 } else {
2639 foreach ($ticket as $tic => $ticval) {
2640 $posts = array_merge((array) $posts, (array) $ticval);
2641 if (isset($ticval->ticket_start)) {
2642 $ticket_start = $ticval->ticket_start;
2643 }
2644 if (is_array($ticket_value)) {
2645 foreach ($ticket_value as $tick => $val) {
2646 $posts = array_merge((array) $posts, (array) $val);
2647 }
2648 }
2649 if (isset($ticket_start) && ($ticket_start != null)) {
2650 $date = strtotime($ticket_start);
2651 $ticket_start_date = date('Y-m-d', $date);
2652 $ticket_start_time = date('H:i:s', $date);
2653 $ticket_end = $ticval->ticket_end;
2654 $time = strtotime($ticket_end);
2655 $ticket_end_date = date('Y-m-d', $time);
2656 $ticket_end_time = date('H:i:s', $time);
2657 $tic_key = array('ticket_start_date', 'ticket_start_time', 'ticket_end_date', 'ticket_end_time');
2658 $tic_val = array($ticket_start_date, $ticket_start_time, $ticket_end_date, $ticket_end_time);
2659 $tickets = array_combine($tic_key, $tic_val);
2660 $posts = array_merge((array) $posts, (array) $tickets);
2661
2662 }
2663 }
2664 }
2665
2666 }
2667
2668 //pods export
2669 $post_type = isset($posts->post_type) ? $posts->post_type : '';
2670 $p_type = $post_type;
2671 $posid = $wpdb->get_results("SELECT ID FROM {$wpdb->prefix}posts where post_name='$p_type' and post_type='_pods_pod'");
2672 foreach ($posid as $podid) {
2673 $pods_id = $podid->ID;
2674 $storage = $wpdb->get_results("SELECT meta_value FROM {$wpdb->prefix}postmeta where post_id=$pods_id AND meta_key='storage'");
2675 foreach ($storage as $pod_storage) {
2676 $pod_stype = $pod_storage->meta_value;
2677 }
2678 }
2679 if (isset($pod_stype) && $pod_stype == 'table') {
2680 $tab = 'pods_' . $p_type;
2681 $tab_val = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}$tab where id=$id");
2682 foreach ($tab_val as $table_key => $table_val) {
2683 $posts = array_merge((array) $posts, (array) $table_val);
2684 }
2685 }
2686
2687 foreach ($posts as $post_key => $post_value) {
2688 if ($post_key == 'post_status') {
2689 if (is_sticky($id)) {
2690 $PostData[$post_key] = 'Sticky';
2691 $post_status = 'Sticky';
2692 } else {
2693 $PostData[$post_key] = $post_value;
2694 $post_status = $post_value;
2695 }
2696 } else {
2697 $PostData[$post_key] = $post_value;
2698 }
2699 if ($post_key == 'post_password') {
2700 if ($post_value) {
2701 $PostData['post_status'] = "{" . $post_value . "}";
2702 } else {
2703 $PostData['post_status'] = $post_status;
2704 }
2705 }
2706
2707 if ($post_key == 'post_author') {
2708 $user_info = get_userdata($post_value);
2709 $PostData['post_author'] = $user_info->user_login;
2710 }
2711 }
2712 }
2713 }
2714
2715 return $PostData;
2716 }
2717
2718 public function getWPMLData($id, $optional_type, $exp_module)
2719 {
2720 global $wpdb;
2721 global $sitepress;
2722 if ($sitepress != null) {
2723 $icl_translation_table = $wpdb->prefix . 'icl_translations';
2724
2725 $get_element_type = 'post_' . $optional_type;
2726 $args = array('element_id' => $id, 'element_type' => $get_element_type);
2727 $get_language_code = apply_filters('wpml_element_language_code', null, $args);
2728 $get_source_language = $wpdb->get_var("select source_language_code from {$icl_translation_table} where element_id ='{$id}' and language_code ='{$get_language_code}'");
2729
2730 $this->data[$id]['language_code'] = $get_language_code;
2731
2732 $get_trid = apply_filters('wpml_element_trid', NULL, $id, $get_element_type);
2733 $translations_query = $wpdb->prepare(
2734 "SELECT element_id
2735 FROM {$wpdb->prefix}icl_translations
2736 WHERE trid = %d
2737 AND language_code != %s",
2738 $get_trid,
2739 $get_language_code
2740 );
2741 $element_id = $wpdb->get_results($translations_query);
2742 $translated_post_title = '';
2743 foreach ($element_id as $translation) {
2744 $element_id = $translation->element_id;
2745 if (trim($exp_module) == 'Posts' || trim($exp_module) == 'Pages') {
2746 $element_title = $wpdb->get_var("select post_title from $wpdb->posts where ID ='{$element_id}'");
2747 $translated_post_title .= $element_title . ",";
2748 }
2749 }
2750 $this->data[$id]['translated_post_title'] = rtrim($translated_post_title, ",");
2751
2752
2753
2754 return $this->data[$id];
2755 }
2756 }
2757
2758 public function getAttachment($id)
2759 {
2760 global $wpdb;
2761 $get_attachment = $wpdb->prepare("select guid from {$wpdb->prefix}posts where ID = %d AND post_type = %s", $id, 'attachment');
2762 $attachment = $wpdb->get_results($get_attachment);
2763 $attachment_file = $attachment[0]->guid;
2764 return $attachment_file;
2765
2766 }
2767
2768 public function getRepeater($parent)
2769 {
2770 global $wpdb;
2771 $get_fields = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}posts where post_parent = %d", $parent), ARRAY_A);
2772 $i = 0;
2773 foreach ($get_fields as $key => $value) {
2774 $array[$i] = $value['post_excerpt'];
2775 $i++;
2776 }
2777 return $array;
2778 }
2779
2780 /**
2781 * Get types fields
2782 * @return array - Types fields
2783 */
2784 public function getTypesFields()
2785 {
2786 $getWPTypesFields = get_option('wpcf-fields');
2787 $typesFields = array();
2788 if (!empty($getWPTypesFields) && is_array($getWPTypesFields)) {
2789 foreach ($getWPTypesFields as $fKey) {
2790 $typesFields[$fKey['meta_key']] = $fKey['name'];
2791 }
2792 }
2793 return $typesFields;
2794 }
2795
2796 /**
2797 * Final data to be export
2798 * @param $data - Data to be export based on the requested information
2799 * @return array - Final data to be export
2800 */
2801 public function finalDataToExport($data, $module = false, $optionalType = false)
2802 {
2803 global $wpdb;
2804 $result = array();
2805 foreach ($this->headers as $key => $value) {
2806 if (empty($value)) {
2807 unset($this->headers[$key]);
2808 }
2809 }
2810 // Fetch Category Custom Field Values
2811 if ($module) {
2812 if ($module == 'Categories') {
2813 return $this->fetchCategoryFieldValue($data, $this->module);
2814 }
2815 }
2816 foreach ($data as $recordId => $rowValue) {
2817 $optional_type = '';
2818 if (is_plugin_active('jet-engine/jet-engine.php')) {
2819 global $wpdb;
2820 $get_slug_name = $wpdb->get_results("SELECT slug FROM {$wpdb->prefix}jet_post_types WHERE status = 'content-type'");
2821 foreach ($get_slug_name as $key => $get_slug) {
2822 $value = $get_slug->slug;
2823 $optionaltype = $value;
2824 if ($optionalType == $optionaltype) {
2825 $optional_type = $optionaltype;
2826 }
2827 }
2828 }
2829
2830 foreach ($this->headers as $htemp => $hKey) {
2831 if (is_array($rowValue) && array_key_exists($hKey, $rowValue) && (!empty($rowValue[$hKey]))) {
2832
2833 if (!empty($optional_type) && $optionalType == $optional_type) {
2834 if (is_plugin_active('jet-engine/jet-engine.php')) {
2835 $result = $this->getJetCCTValue($data, $optionalType);
2836 if (is_array($result)) {
2837 return $result;
2838 } else {
2839 $result[$recordId][$hKey] = $this->returnMetaValueAsCustomerInput($rowValue[$hKey], $hKey);
2840 return $result;
2841 }
2842 }
2843 } else {
2844 $result[$recordId][$hKey] = $this->returnMetaValueAsCustomerInput($rowValue[$hKey], $hKey);
2845 }
2846 } else {
2847 $key = $hKey;
2848 $rowValue['post_type'] = isset($rowValue['post_type']) ? $rowValue['post_type'] : '';
2849 // Replace the third party plugin name from the fieldname
2850 $key = $this->replace_prefix_aioseop_from_fieldname($key);
2851 $key = $this->replace_prefix_yoast_wpseo_from_fieldname($key);
2852 $key = $this->replace_prefix_wpcf_from_fieldname($key);
2853 $key = $this->replace_prefix_wpsc_from_fieldname($key);
2854 $key = $this->replace_underscore_from_fieldname($key);
2855 $key = $this->replace_wpcr3_from_fieldname($key);
2856 // Change fieldname depends on the post type
2857 $key = $this->change_fieldname_depends_on_post_type($rowValue['post_type'], $key);
2858
2859 if (isset($rowValue['wpcr3_' . $key])) {
2860 $rowValue[$key] = $this->returnMetaValueAsCustomerInput($rowValue['wpcr3_' . $key], $hKey);
2861 } else if (is_plugin_active('slim-seo/slim-seo.php')) {
2862
2863 $slimseo_keys = ['title', 'description', 'canonical', 'noindex', 'nofollow', 'redirect', 'facebook_image', 'twitter_image'];
2864
2865 if (in_array($key, $slimseo_keys)) {
2866
2867 $slim_seo_meta = get_post_meta($recordId, 'slim_seo', true);
2868
2869 if (empty($slim_seo_meta)) {
2870 $rowValue[$key] = '';
2871 } else {
2872 if (is_serialized($slim_seo_meta)) {
2873 $slim_seo_meta = maybe_unserialize($slim_seo_meta);
2874 }
2875
2876 if (in_array($key, ['facebook_image', 'twitter_image']) && is_array($slim_seo_meta[$key])) {
2877 $rowValue[$key] = isset($slim_seo_meta[$key]['url']) ? $slim_seo_meta[$key]['url'] : '';
2878 } else {
2879 $rowValue[$key] = isset($slim_seo_meta[$key]) ? $slim_seo_meta[$key] : '';
2880 }
2881
2882 }
2883
2884 $result[$recordId][$key] = $rowValue[$key];
2885 continue;
2886 }
2887 } else if (is_plugin_active('listeo-core/listeo-core.php')) {
2888
2889 $listeo_keys = [
2890 'listeo_core_avatar_id',
2891 'listeo_verified_user',
2892 'phone',
2893 'twitter',
2894 'facebook',
2895 'linkedin',
2896 'instagram',
2897 'youtube',
2898 'skype',
2899 'whatsapp',
2900 'stripe_user_id'
2901 ];
2902
2903 if (in_array($key, $listeo_keys)) {
2904
2905 $meta_value = get_user_meta($recordId, $key, true);
2906
2907 if ($key === 'listeo_core_avatar_id') {
2908 if (!empty($meta_value) && is_numeric($meta_value)) {
2909 $rowValue[$key] = wp_get_attachment_url($meta_value);
2910 } else {
2911 $rowValue[$key] = '';
2912 }
2913
2914 } elseif ($key === 'listeo_verified_user') {
2915 $rowValue[$key] = $meta_value ?: '';
2916
2917 } else {
2918 $rowValue[$key] = $meta_value ?: '';
2919 }
2920
2921 $result[$recordId][$key] = $rowValue[$key];
2922 continue;
2923 }
2924 } else {
2925 if (isset($rowValue['_yoast_wpseo_' . $key])) { // Is available in yoast plugin
2926 $rowValue[$key] = $this->returnMetaValueAsCustomerInput($rowValue['_yoast_wpseo_' . $key]);
2927 } else if (isset($rowValue['_aioseop_' . $key])) { // Is available in all seo plugin
2928 $rowValue[$key] = $this->returnMetaValueAsCustomerInput($rowValue['_aioseop_' . $key]);
2929 } else if (isset($rowValue['_' . $key])) { // Is wp custom fields
2930 $rowValue[$key] = $this->returnMetaValueAsCustomerInput($rowValue['_' . $key], $hKey);
2931 } else if ($fieldvalue = $this->getWoocommerceMetaValue($key, $rowValue['post_type'], $rowValue)) {
2932 $rowValue[$key] = $fieldvalue;
2933 } else if (isset($rowValue['ID']) && $aioseo_field_value = $this->getaioseoFieldValue($rowValue['ID'])) {
2934 $rowValue['og_title'] = $aioseo_field_value[0]->og_title;
2935 $rowValue['og_description'] = $aioseo_field_value[0]->og_description;
2936 $rowValue['custom_link'] = $aioseo_field_value[0]->canonical_url;
2937 $rowValue['og_image_type'] = $aioseo_field_value[0]->og_image_type;
2938 $rowValue['og_image_custom_url'] = $aioseo_field_value[0]->og_image_custom_url;
2939 $rowValue['og_image_custom_fields'] = $aioseo_field_value[0]->og_image_custom_fields;
2940 $rowValue['og_video'] = $aioseo_field_value[0]->og_video;
2941 $rowValue['og_object_type'] = $aioseo_field_value[0]->og_object_type;
2942 $value = $aioseo_field_value[0]->og_article_tags;
2943 $article_tags = json_decode($value);
2944 $og_article_tags = $article_tags[0]->value;
2945 $rowValue['og_article_tags'] = $og_article_tags;
2946 $rowValue['og_article_section'] = $aioseo_field_value[0]->og_article_section;
2947 $rowValue['twitter_use_og'] = $aioseo_field_value[0]->twitter_use_og;
2948 $rowValue['twitter_card'] = $aioseo_field_value[0]->twitter_card;
2949 $rowValue['twitter_image_type'] = $aioseo_field_value[0]->twitter_image_type;
2950 $rowValue['twitter_image_custom_url'] = $aioseo_field_value[0]->twitter_image_custom_url;
2951 $rowValue['twitter_image_custom_fields'] = $aioseo_field_value[0]->twitter_image_custom_fields;
2952 $rowValue['twitter_title'] = $aioseo_field_value[0]->twitter_title;
2953 $rowValue['twitter_description'] = $aioseo_field_value[0]->twitter_description;
2954 $rowValue['robots_default'] = $aioseo_field_value[0]->robots_default;
2955 // $rowValue['robots_noindex'] = $aioseo_field_value[0]->robots_noindex;
2956 $rowValue['robots_noarchive'] = $aioseo_field_value[0]->robots_noarchive;
2957 $rowValue['robots_nosnippet'] = $aioseo_field_value[0]->robots_nosnippet;
2958 // $rowValue['robots_nofollow'] = $aioseo_field_value[0]->robots_nofollow;
2959 $rowValue['robots_noimageindex'] = $aioseo_field_value[0]->robots_noimageindex;
2960 $rowValue['noodp'] = $aioseo_field_value[0]->robots_noodp;
2961 $rowValue['robots_notranslate'] = $aioseo_field_value[0]->robots_notranslate;
2962 $rowValue['robots_max_snippet'] = $aioseo_field_value[0]->robots_max_snippet;
2963 $rowValue['robots_max_videopreview'] = $aioseo_field_value[0]->robots_max_videopreview;
2964 $rowValue['robots_max_imagepreview'] = $aioseo_field_value[0]->robots_max_imagepreview;
2965 $rowValue['aioseo_title'] = $aioseo_field_value[0]->title;
2966 $rowValue['aioseo_description'] = $aioseo_field_value[0]->description;
2967 $key = $aioseo_field_value[0]->keyphrases;
2968
2969 $key1 = json_decode($key);
2970 $rowValue['keyphrases'] = $key1
2971 ->focus->keyphrase;
2972 } else {
2973 $rowValue[$key] = isset($rowValue[$key]) ? $rowValue[$key] : '';
2974 $rowValue[$key] = $this->returnMetaValueAsCustomerInput($rowValue[$key], $hKey);
2975 }
2976 }
2977 global $wpdb;
2978 //Added for user export
2979 if ($key == 'user_login') {
2980 $wpsc_query = $wpdb->prepare("select ID from {$wpdb->prefix}users where user_login =%s", $rowValue['user_login']);
2981 $wpsc_meta = $wpdb->get_results($wpsc_query, ARRAY_A);
2982 }
2983 if (isset($rowValue['_bbp_forum_type']) && ($rowValue['_bbp_forum_type'] == 'forum' || $rowValue['_bbp_forum_type'] == 'category')) {
2984 if ($key == 'Visibility') {
2985 $rowValue[$key] = $rowValue['post_status'];
2986 }
2987 if ($key == 'bbp_moderators') {
2988 $get_forum_moderator_ids = $wpdb->get_results("SELECT meta_value FROM {$wpdb->prefix}postmeta WHERE post_id = $recordId AND meta_key = '_bbp_moderator_id' ", ARRAY_A);
2989 $forum_moderators = '';
2990 foreach ($get_forum_moderator_ids as $get_moderator_id) {
2991 $forum_user_meta = get_user_by('id', $get_moderator_id['meta_value']);
2992 $forum_user = $forum_user_meta
2993 ->data->user_login;
2994 $forum_moderators .= $forum_user . ',';
2995 }
2996
2997 $rowValue[$key] = rtrim($forum_moderators, ',');
2998 }
2999
3000 }
3001 if ($key == 'topic_status' || $key == 'author' || $key == 'topic_type') {
3002 $rowValue['topic_status'] = $rowValue['post_status'];
3003 $rowValue['author'] = $rowValue['post_author'];
3004 if ($key == 'topic_type') {
3005 $Topictype = get_post_meta($rowValue['_bbp_forum_id'], '_bbp_sticky_topics');
3006 $topic_types = get_option('_bbp_super_sticky_topics');
3007 $rowValue['topic_type'] = 'normal';
3008 if ($Topictype) {
3009 foreach ($Topictype as $t_type) {
3010 if ($t_type['0'] == $recordId) {
3011 $rowValue['topic_type'] = 'sticky';
3012 }
3013 }
3014 } elseif (!empty($topic_types)) {
3015 foreach ($topic_types as $top_type) {
3016 if ($top_type == $rowValue['ID']) {
3017 $rowValue['topic_type'] = 'super sticky';
3018 }
3019 }
3020 }
3021 }
3022 }
3023 if ($key == 'reply_status' || $key == 'reply_author') {
3024 $rowValue['reply_status'] = $rowValue['post_status'];
3025 $rowValue['reply_author'] = $rowValue['post_author'];
3026 }
3027 if (array_key_exists($hKey, $rowValue)) {
3028 $result[$recordId][$hKey] = $rowValue[$hKey];
3029 } else {
3030 $result[$recordId][$hKey] = '';
3031 }
3032 }
3033 }
3034 }
3035 return $result;
3036 }
3037
3038 function get_common_post_metadata($meta_id)
3039 {
3040 global $wpdb;
3041 $mdata = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}usermeta WHERE umeta_id = %d", $meta_id), ARRAY_A);
3042 return $mdata[0];
3043 }
3044
3045 function get_common_unserialize($serialize_data)
3046 {
3047
3048 return json_decode($serialize_data, true);
3049 }
3050
3051 /**
3052 * Create CSV data from array
3053 * @param array $data 2D array with data
3054 * @param array $fields field names
3055 * @param bool $append if true, field names will not be output
3056 * @param bool $is_php if a php die() call should be put on the first
3057 * line of the file, this is later ignored when read.
3058 * @param null $delimiter field delimiter to use
3059 * @return string CSV data (text string)
3060 */
3061 public function unParse($data = array(), $fields = array(), $append = false, $is_php = false, $delimiter = null)
3062 {
3063 if (!is_array($data) || empty($data))
3064 $data = &$this->data;
3065 if (!is_array($fields) || empty($fields))
3066 $fields = &$this->titles;
3067 if ($delimiter === null)
3068 $delimiter = $this->delimiter;
3069
3070 $string = ($is_php) ? "<?php header('Status: 403'); die(' '); ?>" . $this->linefeed : '';
3071 $entry = array();
3072
3073 // create heading
3074 if ($this->offset == 0 || $this->checkSplit == 'true') {
3075 if ($this->heading && !$append && !empty($fields)) {
3076 foreach ($fields as $key => $value) {
3077 $entry[] = $this->_enclose_value($value);
3078 }
3079 $string .= implode($delimiter, $entry) . $this->linefeed;
3080 $entry = array();
3081 }
3082 }
3083
3084 // create data
3085 foreach ($data as $key => $row) {
3086 foreach ($row as $field => $value) {
3087 $entry[] = $this->_enclose_value($value);
3088 }
3089 $string .= implode($delimiter, $entry) . $this->linefeed;
3090 $entry = array();
3091 }
3092 return $string;
3093 }
3094
3095 /**
3096 * Enclose values if needed
3097 * - only used by unParse()
3098 * @param null $value
3099 * @return mixed|null|string
3100 */
3101 public function _enclose_value($value = null)
3102 {
3103 if ($value !== null && $value != '') {
3104 $delimiter = preg_quote($this->delimiter, '/');
3105 $enclosure = preg_quote($this->enclosure, '/');
3106
3107 if (is_array($value) && isset($value[0]) && $value[0] == '=') {
3108 $value = "'" . $value; // Fix for the comma-separated vulnerabilities.
3109 }
3110 // Add a check to ensure $value is not an object
3111 if (
3112 isset($value) && is_string($value) && preg_match("/" . $delimiter . "|" . $enclosure . "|\n|\r/i", $value) ||
3113 !is_object($value) && isset($value[0]) && ($value[0] == ' ' || isset($value) && substr($value, -1) == ' ')
3114 ) {
3115 // Handle enclosure
3116 $value = str_replace($this->enclosure, $this->enclosure . $this->enclosure, $value);
3117 $value = $this->enclosure . $value . $this->enclosure;
3118 } else {
3119 if (is_string($value) || is_numeric($value)) {
3120 $value = $this->enclosure . $value . $this->enclosure;
3121 } else {
3122 $value = '';
3123 }
3124 }
3125 }
3126 return $value;
3127 }
3128
3129 /**
3130 * Apply exclusion before export
3131 * @param $headers - Apply exclusion headers
3132 * @return array - Available headers after applying the exclusions
3133 */
3134 public function applyEventExclusion($headers, $optionalType)
3135 {
3136 $header_exclusion = array();
3137 $exclusion = $this->eventExclusions['exclusion_headers']['header'];
3138 $this->eventExclusions['exclusion_headers']['header'] = $exclusion;
3139 $required_header = $this->eventExclusions['exclusion_headers']['header'];
3140
3141 if ($optionalType == 'elementor_library') {
3142 $required_head = array();
3143
3144 if (isset($required_header['ID'])) {
3145 $required_head['ID'] = $required_header['ID'];
3146 }
3147 if (isset($required_header['Template title'])) {
3148 $required_head['Template title'] = $required_header['Template title'];
3149 }
3150 if (isset($required_header['Template content'])) {
3151 $required_head['Template content'] = $required_header['Template content'];
3152 }
3153 if (isset($required_header['Style'])) {
3154 $required_head['Style'] = $required_header['Style'];
3155 }
3156 if (isset($required_header['Template type'])) {
3157 $required_head['Template type'] = $required_header['Template type'];
3158 }
3159 if (isset($required_header['Created time'])) {
3160 $required_head['Created time'] = $required_header['Created time'];
3161 }
3162 if (isset($required_header['Template status'])) {
3163 $required_head['Template status'] = $required_header['Template status'];
3164 }
3165 if (isset($required_header['Category'])) {
3166 $required_head['Category'] = $required_header['Category'];
3167 }
3168 if (isset($required_header['Created by'])) {
3169 $required_head['Created by'] = $required_header['Created by'];
3170 }
3171 if (!empty($required_head)) {
3172 foreach ($headers as $hVal) {
3173 if (array_key_exists($hVal, $required_head)) {
3174 $header_exclusion[] = $hVal;
3175 }
3176 }
3177 return $header_exclusion;
3178 } else {
3179 return $headers;
3180 }
3181 } else {
3182 if (!empty($required_header)) {
3183 foreach ($headers as $hVal) {
3184 if (array_key_exists($hVal, $required_header)) {
3185 $header_exclusion[] = $hVal;
3186 }
3187 }
3188 return $header_exclusion;
3189 } else {
3190 return $headers;
3191 }
3192 }
3193 }
3194
3195 public function replace_prefix_aioseop_from_fieldname($fieldname)
3196 {
3197 if (preg_match('/_aioseop_/', $fieldname)) {
3198 return preg_replace('/_aioseop_/', '', $fieldname);
3199 }
3200
3201 return $fieldname;
3202 }
3203 public function getaioseoFieldValue($post_id)
3204 {
3205 if (is_plugin_active('all-in-one-seo-pack/all_in_one_seo_pack.php') || is_plugin_active('all-in-one-seo-pack-pro/all_in_one_seo_pack.php')) {
3206 global $wpdb;
3207 $aioseo_slug = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}aioseo_posts WHERE post_id=%d", absint($post_id)));
3208 return $aioseo_slug;
3209 }
3210
3211 }
3212
3213 public function replace_prefix_pods_from_fieldname($fieldname)
3214 {
3215 if (preg_match('/_pods_/', $fieldname)) {
3216 return preg_replace('/_pods_/', '', $fieldname);
3217 }
3218
3219 return $fieldname;
3220 }
3221
3222 public function replace_prefix_yoast_wpseo_from_fieldname($fieldname)
3223 {
3224
3225 if (preg_match('/_yoast_wpseo_/', $fieldname)) {
3226 $fieldname = preg_replace('/_yoast_wpseo_/', '', $fieldname);
3227
3228 if ($fieldname == 'focuskw') {
3229 $fieldname = 'focus_keyword';
3230 } else if ($fieldname == 'bread-crumbs-title') { // It is comming as bctitle nowadays
3231 $fieldname = 'bctitle';
3232 } elseif ($fieldname == 'metadesc') {
3233 $fieldname = 'meta_desc';
3234 }
3235 }
3236
3237 return $fieldname;
3238 }
3239
3240 public function replace_prefix_wpcf_from_fieldname($fieldname)
3241 {
3242 if (preg_match('/_wpcf/', $fieldname)) {
3243 return preg_replace('/_wpcf/', '', $fieldname);
3244 }
3245
3246 return $fieldname;
3247 }
3248
3249 public function replace_prefix_wpsc_from_fieldname($fieldname)
3250 {
3251 if (preg_match('/_wpsc_/', $fieldname)) {
3252 return preg_replace('/_wpsc_/', '', $fieldname);
3253 }
3254
3255 return $fieldname;
3256 }
3257
3258 public function replace_wpcr3_from_fieldname($fieldname)
3259 {
3260 if (preg_match('/wpcr3_/', $fieldname)) {
3261 $fieldname = preg_replace('/wpcr3_/', '', $fieldname);
3262 }
3263
3264 return $fieldname;
3265 }
3266
3267 public function change_fieldname_depends_on_post_type($post_type, $fieldname)
3268 {
3269 if ($post_type == 'wpcr3_review') {
3270 switch ($fieldname) {
3271 case 'ID':
3272 return 'review_id';
3273 case 'post_status':
3274 return 'status';
3275 case 'post_content':
3276 return 'review_text';
3277 case 'post_date':
3278 return 'date_time';
3279 default:
3280 return $fieldname;
3281 }
3282 }
3283 if ($post_type == 'shop_order_refund') {
3284 switch ($fieldname) {
3285 case 'ID':
3286 return 'REFUNDID';
3287 default:
3288 return $fieldname;
3289 }
3290 } else if ($post_type == 'shop_order') {
3291 switch ($fieldname) {
3292 case 'ID':
3293 return 'ORDERID';
3294 case 'post_status':
3295 return 'order_status';
3296 case 'post_excerpt':
3297 return 'customer_note';
3298 case 'post_date':
3299 return 'order_date';
3300 default:
3301 return $fieldname;
3302 }
3303 } else if ($post_type == 'shop_coupon') {
3304 switch ($fieldname) {
3305 case 'ID':
3306 return 'COUPONID';
3307 case 'post_status':
3308 return 'coupon_status';
3309 case 'post_excerpt':
3310 return 'description';
3311 case 'post_date':
3312 return 'coupon_date';
3313 case 'post_title':
3314 return 'coupon_code';
3315 default:
3316 return $fieldname;
3317 }
3318 } else if ($post_type == 'product_variation') {
3319 switch ($fieldname) {
3320 case 'ID':
3321 return 'VARIATIONID';
3322 case 'post_parent':
3323 return 'PRODUCTID';
3324 case 'sku':
3325 return 'VARIATIONSKU';
3326 default:
3327 return $fieldname;
3328 }
3329 }
3330
3331 return $fieldname;
3332 }
3333
3334 public function replace_underscore_from_fieldname($fieldname)
3335 {
3336 if (preg_match('/_/', $fieldname)) {
3337 $fieldname = preg_replace('/^_/', '', $fieldname);
3338 }
3339
3340 return $fieldname;
3341 }
3342
3343 public function fetchCategoryFieldValue($categories)
3344 {
3345
3346 global $wpdb;
3347 $bulk_category = [];
3348
3349 foreach ($categories as $category_id => $category) {
3350 $term_meta = get_term_meta($category_id);
3351 $single_category = [];
3352 foreach ($this->headers as $header) {
3353
3354 if ($header == 'name') {
3355 $cato[] = get_term($category_id);
3356 $single_category[$header] = $this->hierarchy_based_term_cat_name($cato, 'category');
3357 continue;
3358 }
3359
3360 if (array_key_exists($header, $category)) {
3361 $single_category[$header] = $category[$header];
3362 } else {
3363 if (isset($term_meta[$header])) {
3364 $single_category[$header] = $this->returnMetaValueAsCustomerInput($term_meta[$header]);
3365 } else {
3366 $single_category[$header] = null;
3367 }
3368 }
3369 }
3370 array_push($bulk_category, $single_category);
3371 }
3372 return $bulk_category;
3373 }
3374 public function getJetCCTValue($data, $type, $data_type = false)
3375 {
3376 global $wpdb;
3377 $jet_data = $this->JetEngineCCTFields($type);
3378 $darray_value = array();
3379 $darray2 = array();
3380 $cct_rel = [];
3381
3382 foreach ($data as $key => $dvalue) {
3383 $get_guid = '';
3384 $select_value = '';
3385 $checkbox_key_value = '';
3386 $checkbox_key_value1 = '';
3387 foreach ($dvalue as $dkey => $value) {
3388 if ($dkey == '_ID') {
3389 $darray[$dkey] = $value;
3390 } elseif ($dkey == 'cct_status') {
3391 $darray[$dkey] = $value;
3392 }
3393
3394 //JET CCT Relation
3395 if (!empty($jet_data)) {
3396 if (in_array($dkey, $this->headers) && !array_key_exists($dkey, $jet_data['JECCT'])) {
3397 $cct_rel[$key][$dkey] = $data[$key][$dkey];
3398 }
3399
3400 if (array_key_exists($dkey, $jet_data['JECCT'])) {
3401 if (empty($value)) {
3402 $darray1[$jet_data['JECCT'][$dkey]['name']] = $value;
3403 } else {
3404 if ($jet_data['JECCT'][$dkey]['type'] == 'text') {
3405 $darray1[$jet_data['JECCT'][$dkey]['name']] = $value;
3406 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'textarea') {
3407 $darray1[$jet_data['JECCT'][$dkey]['name']] = $value;
3408 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'colorpicker') {
3409 $darray1[$jet_data['JECCT'][$dkey]['name']] = $value;
3410 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'iconpicker') {
3411 $darray1[$jet_data['JECCT'][$dkey]['name']] = $value;
3412 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'radio') {
3413 $darray1[$jet_data['JECCT'][$dkey]['name']] = $value;
3414 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'number') {
3415 $darray1[$jet_data['JECCT'][$dkey]['name']] = $value;
3416 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'wysiwyg') {
3417 $value = preg_replace('/\s+/', ' ', $value);
3418
3419 // Minify the HTML content
3420 $value = trim($value);
3421 $darray1[$jet_data['JECCT'][$dkey]['name']] = $value;
3422 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'switcher') {
3423 $darray1[$jet_data['JECCT'][$dkey]['name']] = $value;
3424 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'time') {
3425 $darray1[$jet_data['JECCT'][$dkey]['name']] = $value;
3426 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'media') {
3427 if (is_numeric($value)) {
3428 if ($value != 0) {
3429 $get_guid_name = $wpdb->get_results($wpdb->prepare("SELECT guid FROM {$wpdb->prefix}posts WHERE id = %d", absint($value)));
3430 foreach ($get_guid_name as $media_key => $value) {
3431 $darray1[$jet_data['JECCT'][$dkey]['name']] = $value->guid;
3432 }
3433 } else {
3434
3435 $darray1[$jet_data['JECCT'][$dkey]['name']] = $value;
3436 }
3437 } elseif (is_serialized($value)) {
3438 $media_value = unserialize($value);
3439 $darray1[$jet_data['JECCT'][$dkey]['name']] = $media_value['url'];
3440 } else {
3441 $media_field_val = $value;
3442 $darray1[$jet_data['JECCT'][$dkey]['name']] = $media_field_val;
3443 }
3444 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'gallery') {
3445 $get_meta_list = explode(',', $value);
3446 $get_guid = '';
3447 foreach ($get_meta_list as $get_meta) {
3448 if (is_numeric($get_meta)) {
3449 $get_guid_name = $wpdb->get_results($wpdb->prepare("SELECT guid FROM {$wpdb->prefix}posts WHERE id = %d", absint($get_meta)));
3450 foreach ($get_guid_name as $gallery_key => $value) {
3451 $get_guid .= $value->guid . ',';
3452 }
3453 } elseif (is_serialized($get_meta)) {
3454 $gal_value = unserialize($get_meta);
3455 foreach ($gal_value as $gal_key1 => $gal_val) {
3456 $get_guid .= $gal_val['url'] . ',';
3457 }
3458 } else {
3459 $get_guid .= $get_meta . ',';
3460 }
3461 }
3462 $darray1[$jet_data['JECCT'][$dkey]['name']] = rtrim($get_guid, ',');
3463 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'date') {
3464 if (!empty($value)) {
3465 if (strpos($value, '-') !== FALSE) {
3466 $date_value = $value;
3467 } else {
3468 $date_value = date('Y-m-d', $value);
3469 }
3470 }
3471 $darray1[$jet_data['JECCT'][$dkey]['name']] = $date_value;
3472 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'datetime-local') {
3473 if (!empty($value)) {
3474 if (strpos($value, '-') !== FALSE) {
3475 $datetime_value = $value;
3476 } else {
3477 $datetime_value = date('Y-m-d H:i', $value);
3478 }
3479 $datetime_value = str_replace(' ', 'T', $datetime_value);
3480 }
3481 $darray1[$jet_data['JECCT'][$dkey]['name']] = $datetime_value;
3482 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'checkbox') {
3483 if ($jet_data['JECCT'][$dkey]['is_array'] == 1) {
3484 $checkbox_value = unserialize($value);
3485 if (is_array($checkbox_value)) {
3486 $darray1[$jet_data['JECCT'][$dkey]['name']] = implode(',', $checkbox_value);
3487 } else {
3488 $darray1[$jet_data['JECCT'][$dkey]['name']] = ''; // or handle as needed
3489 }
3490 } else {
3491 $checkbox_value = unserialize($value);
3492 $checkbox_key_value = '';
3493 foreach ($checkbox_value as $check_key => $check_val) {
3494 if ($check_val == 'true') {
3495 $checkbox_key_value .= $check_key . ',';
3496 }
3497 }
3498 $darray1[$jet_data['JECCT'][$dkey]['name']] = rtrim($checkbox_key_value, ',');
3499 }
3500 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'posts') {
3501 if (is_serialized($value)) {
3502 $jet_posts = unserialize($value);
3503 $jet_posts_value = '';
3504 foreach ($jet_posts as $posts_key => $post_val) {
3505 $query = "SELECT post_title FROM {$wpdb->prefix}posts WHERE id ='{$post_val}' AND post_status='publish'";
3506 $name = $wpdb->get_results($query);
3507 if (!empty($name)) {
3508 $jet_posts_value .= $name[0]->post_title . ',';
3509 }
3510 }
3511 $post_names = rtrim($jet_posts_value, ',');
3512 } else {
3513 $query = "SELECT post_title FROM {$wpdb->prefix}posts WHERE id ='{$value}' AND post_status='publish'";
3514 $name = $wpdb->get_results($query);
3515 if (!empty($name)) {
3516 $post_names = $name[0]->post_title;
3517 }
3518 }
3519 $darray1[$jet_data['JECCT'][$dkey]['name']] = $post_names;
3520 } elseif ($jet_data['JECCT'][$dkey]['type'] == 'select') {
3521 if (is_serialized($value)) {
3522 $select_value = '';
3523 $gal_value = unserialize($value);
3524 foreach ($gal_value as $select_key => $gal_val) {
3525 $select_value .= $gal_val . ',';
3526 }
3527 } else {
3528 $select_val = $value;
3529 $select_value = $select_val;
3530 }
3531
3532 $darray1[$jet_data['JECCT'][$dkey]['name']] = rtrim($select_value, ',');
3533 }
3534 }
3535 }
3536
3537 }
3538 }
3539 if (!empty($darray1) && empty($darray2)) {
3540 $data_array_values = array_merge($darray, $darray1);
3541 } elseif (empty($darray1) && !empty($darray2)) {
3542 $data_array_values = array_merge($darray, $darray2);
3543 } else if (!empty($darray1) && !empty($darray2)) {
3544 $data_array_values = array_merge($darray, $darray1, $darray2);
3545 }
3546
3547 $darray_value[$key] = $data_array_values;
3548 }
3549 //CCT Relation
3550 if (!empty($cct_rel) && !empty($darray_value)) {
3551 foreach ($cct_rel as $id => $value) {
3552 unset($value['_ID']);
3553 unset($value['cct_status']);
3554 $get_val = $darray_value[$id];
3555 $all_data[$id] = array_merge($get_val, $value);
3556 }
3557 $darray_value = $all_data;
3558 }
3559 //End CCT Relation
3560 //For correct the CSV columns
3561 foreach ($this->headers as $row_header) {
3562 foreach ($darray_value as $key => $value) {
3563 if (!empty($value)) {
3564 if (array_key_exists($row_header, $value)) {
3565 $new_data[$key][$row_header] = $value[$row_header];
3566 } else {
3567 $new_data[$key][$row_header] = $value[$row_header];
3568 }
3569 }
3570 }
3571 }
3572 $darray_value = $new_data;
3573 //added
3574 if (!empty($darray_value)) {
3575 return $darray_value;
3576 } else {
3577 return;
3578 }
3579 }
3580 public function JetEngineCCTFields($type)
3581 {
3582 global $wpdb;
3583 $jet_field = array();
3584 $customFields = [];
3585 $get_meta_fields = $wpdb->get_results($wpdb->prepare("select id, meta_fields from {$wpdb->prefix}jet_post_types where slug = %s and status = %s", $type, 'content-type'));
3586
3587 if (!empty($get_meta_fields)) {
3588 $unserialized_meta = maybe_unserialize($get_meta_fields[0]->meta_fields);
3589
3590 foreach ($unserialized_meta as $jet_key => $jet_value) {
3591 $customFields["JECCT"][$jet_value['name']]['label'] = $jet_value['title'];
3592 $customFields["JECCT"][$jet_value['name']]['name'] = $jet_value['name'];
3593 $customFields["JECCT"][$jet_value['name']]['type'] = $jet_value['type'];
3594 $customFields["JECCT"][$jet_value['name']]['options'] = isset($jet_value['options']) ? $jet_value['options'] : '';
3595 $customFields["JECCT"][$jet_value['name']]['is_multiple'] = isset($jet_value['is_multiple']) ? $jet_value['is_multiple'] : '';
3596 $customFields["JECCT"][$jet_value['name']]['is_array'] = isset($jet_value['is_array']) ? $jet_value['is_array'] : '';
3597 $jet_field[] = $jet_value['name'];
3598 }
3599 }
3600 return $customFields;
3601 }
3602
3603 public function returnMetaValueAsCustomerInput($meta_value, $header = false)
3604 {
3605 if ($header == 'rating_data') {
3606 return $meta_value;
3607 }
3608 if ($header != 'jet_abaf_price' && $header != 'jet_abaf_custom_schedule' && $header != 'jet_abaf_configuration' && $header != '_elementor_css' && $header != '_elementor_controls_usage' && $header != 'elementor_library_category' && $header != '_elementor_page_assets' && $header != '_elementor_page_settings' && $header != '_elementor_data') {
3609
3610 if (is_array($meta_value)) {
3611 $meta_value = $meta_value[0];
3612 if (!empty($meta_value)) {
3613 if (is_serialized($meta_value)) {
3614 return json_decode($meta_value, true);
3615 } else if (is_array($meta_value)) {
3616 return implode('|', $meta_value);
3617 } else if (is_string($meta_value)) {
3618 return $meta_value;
3619 } else if ($this->isJSON($meta_value) === true) {
3620 return json_decode($meta_value);
3621 }
3622
3623 return $meta_value;
3624 }
3625
3626 return $meta_value;
3627 } else {
3628 if (is_serialized($meta_value)) {
3629 $meta_value = unserialize($meta_value);
3630 if (is_array($meta_value)) {
3631 $meta_value = array_map('strval', $meta_value);
3632 return implode('|', $meta_value);
3633 }
3634 return $meta_value;
3635 } else if (is_array($meta_value)) {
3636 return implode('|', $meta_value);
3637 } else if (is_string($meta_value)) {
3638 return $meta_value;
3639 } else if ($this->isJSON($meta_value) === true) {
3640 return json_decode($meta_value);
3641 }
3642 }
3643 } elseif ($header == '_elementor_data') {
3644 $meta_value = base64_encode($meta_value);
3645 }
3646
3647
3648 return $meta_value;
3649 }
3650
3651 public function isJSON($meta_value)
3652 {
3653 $json = json_decode($meta_value);
3654 return $json && $meta_value != $json;
3655 }
3656
3657 public function hierarchy_based_term_name($term, $taxanomy_type)
3658 {
3659
3660 $tempo = array();
3661 $termo = '';
3662 $i = 0;
3663 foreach ($term as $termkey => $terms) {
3664 $tempo[] = $terms->name;
3665 $temp_hierarchy_terms = [];
3666
3667 if (!empty($terms->parent)) {
3668 $temp1 = $terms->name;
3669 $i++;
3670
3671 $termexp = explode(',', $termo);
3672
3673 $termo = implode(',', $termexp);
3674 $temp_hierarchy_terms[] = $terms->name;
3675 $hierarchy_terms = $this->call_back_to_get_parent($terms->parent, $taxanomy_type, $tempo, $temp_hierarchy_terms);
3676 $parent_name = get_term($terms->parent);
3677 $termo .= $this->split_terms_by_arrow($hierarchy_terms, $parent_name->name) . ',';
3678
3679 } else {
3680
3681 if (in_array($terms->name, $tempo)) {
3682
3683 $termo .= $terms->name . ',';
3684
3685 }
3686 }
3687 }
3688 return $termo;
3689
3690 }
3691
3692 public function hierarchy_based_term_cat_name($term, $taxanomy_type)
3693 {
3694 $tempo = array();
3695 $termo = '';
3696 foreach ($term as $terms) {
3697 $tempo[] = $terms->name;
3698 $temp_hierarchy_terms = [];
3699 if (!empty($terms->parent)) {
3700 $temp_hierarchy_terms[] = $terms->name;
3701 $hierarchy_terms = $this->call_back_to_get_parent($terms->parent, $taxanomy_type, $tempo, $temp_hierarchy_terms);
3702 $parent_name = get_term($terms->parent);
3703 $termo = $this->split_terms_by_arrow($hierarchy_terms, $parent_name->name);
3704
3705 } else {
3706 $termo = $terms->name;
3707
3708 }
3709 }
3710 return $termo;
3711 }
3712 public function call_back_to_get_parent($term_id, $taxanomy_type, $tempo, $temp_hierarchy_terms = [])
3713 {
3714 $term = get_term($term_id, $taxanomy_type);
3715 if (!empty($term->parent)) {
3716 if (in_array($term->name, $tempo)) {
3717
3718 $temp_hierarchy_terms[] = $term->name;
3719
3720 $temp_hierarchy_terms = $this->call_back_to_get_parent($term->parent, $taxanomy_type, $tempo, $temp_hierarchy_terms);
3721 } else {
3722 $temp_hierarchy_terms[] = '';
3723
3724 $temp_hierarchy_terms = $this->call_back_to_get_parent($term->parent, $taxanomy_type, $tempo, $temp_hierarchy_terms);
3725 }
3726
3727 } else {
3728 if (in_array($term->name, $tempo)) {
3729 $temp_hierarchy_terms[] = $term->name;
3730 } else {
3731 $temp_hierarchy_terms[] = '';
3732 }
3733 }
3734 return $temp_hierarchy_terms;
3735 }
3736 // public function call_back_to_get_parent($term_id, $taxanomy_type, $temp_hierarchy_terms = []){
3737 // $term = get_term($term_id, $taxanomy_type);
3738 // if(!empty($term->parent)){
3739 // $temp_hierarchy_terms[] = $term->name;
3740 // $temp_hierarchy_terms = $this->call_back_to_get_parent($term->parent, $taxanomy_type, $temp_hierarchy_terms);
3741 // }else{
3742 // $temp_hierarchy_terms[] = $term->name;
3743 // }
3744 // return $temp_hierarchy_terms;
3745 // }
3746 public function split_terms_by_arrow($hierarchy_terms, $termParentName)
3747 {
3748
3749 krsort($hierarchy_terms);
3750 $terms_value = $termParentName . '>' . $hierarchy_terms[0];
3751 //return implode('>', $hierarchy_terms);
3752 return $terms_value;
3753 }
3754
3755 public function getWoocommerceMetaValue($fieldname, $post_type, $post)
3756 {
3757 $post_type = isset($post_type) ? $post_type : '';
3758 if ($post_type == 'shop_order_refund') {
3759 switch ($fieldname) {
3760 case 'REFUNDID':
3761 return $post['ID'];
3762 default:
3763 return $post[$fieldname];
3764 }
3765 } else if ($post_type == 'shop_order') {
3766 switch ($fieldname) {
3767 case 'ORDERID':
3768 return $post['ID'];
3769 case 'order_status':
3770 return $post['post_status'];
3771 case 'customer_note':
3772 return $post['post_excerpt'];
3773 case 'order_date':
3774 return $post['post_date'];
3775 default:
3776 return $post[$fieldname];
3777 }
3778 } else if ($post_type == 'shop_coupon') {
3779 switch ($fieldname) {
3780 case 'COUPONID':
3781 return $post['ID'];
3782 case 'coupon_status':
3783 return $post['post_status'];
3784 case 'description':
3785 return $post['post_excerpt'];
3786 case 'coupon_date':
3787 return $post['post_date'];
3788 case 'coupon_code':
3789 return $post['post_title'];
3790 case 'expiry_date':
3791 if (isset($post['date_expires'])) {
3792 $timeinfo = date('m/d/Y', $post['date_expires']);
3793 }
3794 $timeinfo = isset($timeinfo) ? $timeinfo : '';
3795 return $timeinfo;
3796 default:
3797 return $post[$fieldname];
3798 }
3799 } else if ($post_type == 'product_variation') {
3800 switch ($fieldname) {
3801 case 'VARIATIONID':
3802 return $post['ID'];
3803 case 'PRODUCTID':
3804 return $post['post_parent'];
3805 case 'VARIATIONSKU':
3806 return $post['sku'];
3807 default:
3808 return $post[$fieldname];
3809 }
3810 }
3811 return false;
3812 }
3813
3814 }
3815
3816 return new exportExtension();
3817 }
3818
3819