PluginProbe
Import WP – CSV & XML Import Export for WordPress / 2.7.7
Import WP – CSV & XML Import Export for WordPress v2.7.7
2.15.1 2.15.0 2.14.24 2.14.23 2.7.0 2.7.1 2.7.10 2.7.11 2.7.12 2.7.13 2.7.14 2.7.2 2.7.3 2.7.4 2.7.5 2.7.6 2.7.7 2.7.8 2.7.9 2.8.0 2.8.1 2.8.2 2.8.3 2.9.0 2.9.1 All 144 releases
jc-importer / class / Common / Importer / ImporterManager.php

ImporterManager.php in Import WP – CSV & XML Import Export for WordPress 2.7.7, at class/Common/Importer/ImporterManager.php

881 lines 28.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace ImportWP\Common\Importer;
4
5 use ImportWP\Common\Filesystem\Filesystem;
6 use ImportWP\Common\Importer\Config\Config;
7 use ImportWP\Common\Importer\File\CSVFile;
8 use ImportWP\Common\Importer\File\XMLFile;
9 use ImportWP\Common\Importer\Mapper\PostMapper;
10 use ImportWP\Common\Importer\Mapper\TermMapper;
11 use ImportWP\Common\Importer\Mapper\UserMapper;
12 use ImportWP\Common\Importer\Parser\CSVParser;
13 use ImportWP\Common\Importer\Parser\XMLParser;
14 use ImportWP\Common\Importer\Permission\Permission;
15 use ImportWP\Common\Importer\State\ImporterState;
16 use ImportWP\Common\Importer\Template\CustomPostTypeTemplate;
17 use ImportWP\Common\Importer\Template\PageTemplate;
18 use ImportWP\Common\Importer\Template\PostTemplate;
19 use ImportWP\Common\Importer\Template\Template;
20 use ImportWP\Common\Importer\Template\TemplateManager;
21 use ImportWP\Common\Importer\Template\TermTemplate;
22 use ImportWP\Common\Importer\Template\UserTemplate;
23 use ImportWP\Common\Model\ImporterModel;
24 use ImportWP\Common\Properties\Properties;
25 use ImportWP\Common\Util\Logger;
26 use ImportWP\Common\Util\Util;
27 use ImportWP\Container;
28 use ImportWP\EventHandler;
29
30 class ImporterManager
31 {
32
33 /**
34 * @var Filesystem
35 */
36 private $filesystem;
37
38 /**
39 * @var TemplateManager $template_manager
40 */
41 private $template_manager;
42
43 /**
44 * @var EventHandler $event_handler
45 */
46 protected $event_handler;
47
48 public function __construct(Filesystem $filesystem, TemplateManager $template_manager, EventHandler $event_handler)
49 {
50 $this->filesystem = $filesystem;
51 $this->template_manager = $template_manager;
52 $this->event_handler = $event_handler;
53 }
54
55 /**
56 * Get Importers
57 *
58 * @return ImporterModel[]
59 */
60 public function get_importers()
61 {
62
63 $result = array();
64 $query = new \WP_Query(array(
65 'post_type' => IWP_POST_TYPE,
66 'posts_per_page' => -1,
67 ));
68
69 foreach ($query->posts as $post) {
70 $result[] = $this->get_importer($post);
71 }
72 return $result;
73 }
74
75 /**
76 * Get Importer
77 *
78 * @param int $id
79 * @return ImporterModel
80 */
81 public function get_importer($id)
82 {
83 if ($id instanceof ImporterModel) {
84 return $id;
85 }
86
87 if (IWP_POST_TYPE !== get_post_type($id)) {
88 return false;
89 }
90
91 return new ImporterModel($id, $this->is_debug());
92 }
93
94 public function is_debug()
95 {
96
97 if (defined('IWP_DEBUG') && true === IWP_DEBUG) {
98 return true;
99 }
100
101 $uninstall_enabled = get_option('iwp_settings');
102 if (isset($uninstall_enabled['debug']) && true === $uninstall_enabled['debug']) {
103 return true;
104 }
105
106 return false;
107 }
108
109 public function set_current_user($id)
110 {
111 $importer_model = $this->get_importer($id);
112 $user_id = $importer_model->getUserId();
113
114 Logger::write('set_current_user -user=' . $user_id, $importer_model->getId());
115
116 if ($user_id) {
117 return wp_set_current_user($user_id);
118 }
119
120 return false;
121 }
122
123 /**
124 * Delete Importer
125 *
126 * @param int $id
127 * @return void
128 */
129 public function delete_importer($id)
130 {
131 $importer = $this->get_importer($id);
132 $importer->delete();
133 }
134
135 public function get_file($id)
136 {
137 $importer = $this->get_importer($id);
138 $config = $this->get_config($importer);
139 $parser = $importer->getParser();
140
141 if ('xml' === $parser) {
142 return $this->get_xml_file($importer, $config);
143 } elseif ('csv' === $parser) {
144 return $this->get_csv_file($importer, $config);
145 }
146
147 return false;
148 }
149
150 public function get_csv_file($id, $config)
151 {
152 $importer = $this->get_importer($id);
153 $file = new CSVFile($importer->getFile(), $config);
154 $file->setDelimiter($importer->getFileSetting('delimiter'));
155 $file->setEnclosure($importer->getFileSetting('enclosure'));
156 return $file;
157 }
158
159 public function get_xml_file($id, $config)
160 {
161 $importer = $this->get_importer($id);
162 $file = new XMLFile($importer->getFile(), $config);
163 $file->setRecordPath($importer->getFileSetting('base_path'));
164 return $file;
165 }
166
167 public function preview_csv_file($id, $fields = [], $row = 0)
168 {
169 $importer = $this->get_importer($id);
170 $config = $this->get_config($importer, true);
171
172 $file = $this->get_csv_file($importer, $config);
173 $parser = new CSVParser($file);
174
175 $record = $parser->getRecord($row);
176
177 return $record->queryGroup(['fields' => $fields]);
178 }
179
180 public function preview_xml_file($id, $fields = [], $row = 0)
181 {
182 $importer = $this->get_importer($id);
183 $config = $this->get_config($importer, true);
184
185 $file = $this->get_xml_file($importer, $config);
186 $parser = new XMLParser($file);
187
188 $record = $parser->getRecord($row);
189 return $record->queryGroup(['fields' => $fields]);
190 }
191
192 public function process_csv_file($id, $delimiter, $enclosure, $tmp = false)
193 {
194 $importer = $this->get_importer($id);
195 $config = $this->get_config($importer->getId(), $tmp);
196
197 $file = $this->get_csv_file($importer, $config);
198 $file->setDelimiter($delimiter);
199 $file->setEnclosure($enclosure);
200 $file->processing(true);
201
202 if (empty($importer->getMap())) {
203
204 // we are on first file import
205 $headings = str_getcsv($file->getRecord(0), $file->getDelimiter(), $file->getEnclosure());
206 $headings = array_map('trim', $headings);
207
208 $template = $this->get_importer_template($id);
209 $field_map = $template->generate_field_map($headings, $importer);
210 $field_map = apply_filters('iwp/importer/generate_field_map', $field_map, $headings, $importer);
211
212 $map = $field_map['map'];
213 foreach ($map as $key => $value) {
214 $importer->setMap($key, $value);
215 }
216
217 $enabled = $field_map['enabled'];
218 foreach ($enabled as $enabled_field) {
219 $importer->setEnabled($enabled_field);
220 }
221
222 // Disabled due to testing:
223 // https://localdev/wp-admin/tools.php?page=importwp&edit=29&step=1
224 //
225 // a:9:{s:8:"template";s:19:"woocommerce-product";s:13:"template_type";s:0:"";s:4:"file";a:2:{s:2:"id";i:9;s:8:"settings";a:6:{s:9:"enclosure";s:1:""";s:9:"delimiter";s:1:",";s:13:"show_headings";b:1;s:5:"setup";b:0;s:5:"count";i:2;s:9:"processed";b:1;}}s:10:"datasource";a:2:{s:4:"type";s:5:"local";s:8:"settings";a:2:{s:10:"remote_url";s:0:"";s:9:"local_url";s:48:"/var/www/html/wp-content/uploads/exportwp/30.csv";}}s:6:"parser";s:3:"csv";s:3:"map";a:0:{}s:7:"enabled";a:0:{}s:11:"permissions";a:0:{}s:8:"settings";a:4:{s:9:"post_type";a:2:{i:0;s:7:"product";i:1;s:17:"product_variation";}s:12:"unique_field";a:3:{i:0;s:2:"ID";i:1;s:4:"_sku";i:2;s:9:"post_name";}s:9:"start_row";N;s:7:"max_row";N;}}
226 //
227 $importer->save();
228 }
229
230 return $file->getRecordCount();
231 }
232
233 public function process_xml_file($id, $tmp = false)
234 {
235
236 $importer = $this->get_importer($id);
237 $config = $this->get_config($importer->getId(), $tmp);
238
239 $filePath = $importer->getFile();
240 $file = new XMLFile($filePath, $config);
241 $file->processing(true);
242 $nodes = $file->get_node_list();
243 $results = [];
244
245 foreach ($nodes as $node) {
246 $config = $this->get_config($importer->getId(), $tmp);
247 $file = new XMLFile($filePath, $config);
248 $file->setRecordPath($node);
249 // TODO: Seperate record count, to when a node has been selected.
250 $results[$node] = 0; //$file->getRecordCount();
251 }
252
253 return $results;
254 }
255
256 /**
257 * Link import file to importer via post meta
258 *
259 * @param ImporterModel $id
260 * @param string $file_path
261 * @return integer Id of inserted file
262 */
263 public function link_importer_file($id, $file_path)
264 {
265 $importer = $this->get_importer($id);
266 $index = get_post_meta($importer->getId(), '_importer_files', true);
267 if (!$index) {
268 $index = 1;
269 }
270
271 $index++;
272
273 update_post_meta($importer->getId(), '_importer_files', $index);
274 update_post_meta($importer->getId(), '_importer_file_' . $index, $file_path);
275 return $index;
276 }
277
278 public function get_importer_file_prefix($importer)
279 {
280 $importer = $this->get_importer($importer);
281
282 $file_index = get_post_meta($importer->getId(), '_importer_files', true);
283 if (!$file_index) {
284 $file_index = 1;
285 }
286 $file_index++;
287
288 return $importer->getId() . '-' . intval($file_index) . '-';
289 }
290
291 public function upload_file($id, $file)
292 {
293 $importer = $this->get_importer($id);
294 Logger::setId($importer->getId());
295
296 $allowed_file_types = $this->event_handler->run('importer.allowed_file_types', [$importer->getAllowedFileTypes()]);
297 $result = $this->filesystem->upload_file($file, $allowed_file_types);
298
299 if (is_wp_error($result)) {
300 return $result;
301 }
302
303 $attachment_id = $this->insert_file_attachment($importer, $result['dest'], $result['type']);
304 if (is_wp_error($attachment_id)) {
305 return $attachment_id;
306 }
307
308 return $attachment_id;
309 }
310
311 public function remote_file($id, $source, $filetype = null)
312 {
313 $importer = $this->get_importer($id);
314 Logger::setId($importer->getId());
315
316 $allowed_file_types = $this->event_handler->run('importer.allowed_file_types', [$importer->getAllowedFileTypes()]);
317 $prefix = $this->get_importer_file_prefix($importer);
318 $result = $this->filesystem->download_file($source, $filetype, $allowed_file_types, null, $prefix);
319
320 if (is_wp_error($result)) {
321 return $result;
322 }
323
324 $attachment_id = $this->insert_file_attachment($importer, $result['dest'], $result['type']);
325 if (is_wp_error($attachment_id)) {
326 return $attachment_id;
327 }
328
329 return $attachment_id;
330 }
331
332 public function local_file($id, $source)
333 {
334 $importer = $this->get_importer($id);
335 Logger::setId($importer->getId());
336
337 $allowed_file_types = $this->event_handler->run('importer.allowed_file_types', [$importer->getAllowedFileTypes()]);
338 $prefix = $this->get_importer_file_prefix($importer);
339 $result = $this->filesystem->copy_file($source, $allowed_file_types, null, $prefix);
340
341 if (is_wp_error($result)) {
342 return $result;
343 }
344
345 $attachment_id = $this->insert_file_attachment($importer, $result['dest'], $result['type']);
346 if (is_wp_error($attachment_id)) {
347 return $attachment_id;
348 }
349
350 return $attachment_id;
351 }
352
353 /**
354 * Add uploaded file to importer
355 *
356 * Insert file record in database, set as current import file.
357 *
358 * @param integer|ImporterModel $id Importer to attach file
359 * @param string $file_path File location on server
360 * @param string $file_type Type of file
361 *
362 * @return \WP_Error|int Id of file
363 */
364 private function insert_file_attachment($id, $file_path, $file_type)
365 {
366 $importer_model = $this->get_importer($id);
367 Logger::setId($importer_model->getId());
368
369 // Allow the modification of file path
370 $file_path = wp_normalize_path($file_path);
371 $file_path = apply_filters('iwp/importer/file_uploaded/file_path', $file_path, $importer_model);
372
373 $file_id = $this->link_importer_file($id, $file_path);
374 if (!$file_id) {
375 return new \WP_Error('IWP_IM_01', 'Unable to link importer file');
376 }
377
378 if (is_null($importer_model->getParser())) {
379 $importer_model->setParser($file_type);
380 }
381
382 $importer_model->setFileId($file_id);
383 $importer_model->save();
384
385 do_action('iwp/importer/file_uploaded', $file_path, $importer_model);
386
387 return $file_id;
388 }
389
390 /**
391 * Clear config files
392 *
393 * @param int $id
394 * @return void
395 */
396 public function clear_config_files($id, $tmp = false, $all = true)
397 {
398 $config_path = $this->get_config_path($id, $tmp);
399 if (file_exists($config_path)) {
400
401 unlink($config_path);
402 if (true === $all) {
403 foreach (glob($config_path . '*') as $file) {
404
405 // don't remove status file
406 if (basename($file) === basename($config_path) . '.status') {
407 continue;
408 }
409
410 unlink($file);
411 }
412 }
413 }
414 }
415
416 public function get_config($importer, $tmp = false)
417 {
418 $config_path = $this->get_config_path($importer, $tmp);
419 $config = new Config($config_path);
420
421
422 $importer = $this->get_importer($importer);
423 $file_encoding = $importer->getFileSetting('file_encoding');
424
425 // file encoding
426 $config->set('file_encoding', apply_filters('iwp/importer/file_encoding', $file_encoding, $importer));
427
428 return $config;
429 }
430
431 public function get_session_path($id, $session, $max_depth = 4)
432 {
433 $base = $this->filesystem->get_temp_directory() . DIRECTORY_SEPARATOR;
434
435 $base .= str_pad($id, 2, STR_PAD_LEFT) . DIRECTORY_SEPARATOR;
436 if (!file_exists($base)) {
437 if (!is_writable(dirname($base)) || !mkdir($base)) {
438 throw new \Exception("Unable to create directory: " . $base);
439 }
440 }
441
442 for ($i = 0; $i < ceil(strlen($session) / 2); $i++) {
443 $base .= substr($session, $i * 2, 2) . DIRECTORY_SEPARATOR;
444 if (!file_exists($base)) {
445
446 if (!is_writable(dirname($base)) || !mkdir($base)) {
447 throw new \Exception("Unable to create directory: " . $base);
448 }
449 }
450
451 if ($i >= $max_depth - 2) {
452 break;
453 }
454 }
455 return $base;
456 }
457
458 public function get_config_path($id, $tmp = false, $session_id = null)
459 {
460 $importer = $this->get_importer($id);
461
462 $key = 'config-%d.json';
463 if ($tmp) {
464 $key = 'temp-config-%d.json';
465 }
466
467 $base = !is_null($session_id) ? $this->get_session_path($id, $session_id) : $this->filesystem->get_temp_directory() . DIRECTORY_SEPARATOR;
468
469 return $base . sprintf($key, $importer->getId());
470 }
471
472 public function import($id, $user, $session = null)
473 {
474 Logger::timer();
475
476 $importer_data = $this->get_importer($id);
477 $importer_id = $importer_data->getId();
478
479 $config_data = get_site_option('iwp_importer_config_' . $importer_id, []);
480
481 $this->event_handler->run('importer_manager.import', [$importer_data]);
482
483 $state = new ImporterState($importer_id, $user);
484
485 try {
486
487 Logger::debug('IM -init_state');
488 $state->init($session);
489
490 if ($state->has_status('init')) {
491 Logger::debug('IM -clear_config_files');
492 $this->clear_config_files($importer_id, false, true);
493 $config_data['features'] = [
494 'session_table' => true
495 ];
496 }
497
498 Logger::debug('IM -get_config');
499 $config = $this->get_config($importer_data);
500
501 // template
502 Logger::debug('IM -get_importer_template');
503 $template = $this->get_importer_template($importer_data);
504
505 Logger::debug('IM -register_hooks');
506 $template->register_hooks($importer_data);
507
508 // permission
509 Logger::debug('IM -permissions');
510 $permission = new Permission($importer_data);
511
512 // mapper
513 Logger::debug('IM -get_importer_mapper');
514 $mapper = $this->get_importer_mapper($importer_data, $template, $permission);
515
516 if ($state->has_status('init')) {
517
518 Logger::debug('IM -generate_config');
519
520 $config_data['data'] = $template->config_field_map($importer_data->getMap());
521 $config->set('data', $config_data['data']);
522
523 $config_data['id'] = $state->get_session();
524
525 // This is used for storing version on imported records
526 update_post_meta($importer_id, '_iwp_session', $config_data['id']);
527
528 // Increase Version
529 $version = get_post_meta($importer_id, '_iwp_version', true);
530 if ($version !== false) {
531 $version++;
532 } else {
533 $version = 0;
534 }
535 update_post_meta($importer_id, '_iwp_version', $version);
536 $config_data['version'] = $version;
537 }
538
539 $start = 0;
540
541 // get parser
542 if ($importer_data->getParser() === 'csv') {
543 Logger::debug('IM -get_csv_file');
544 $file = $this->get_csv_file($importer_data, $config);
545 Logger::debug('IM -load_parser');
546 $parser = new CSVParser($file);
547 if (true === $importer_data->getFileSetting('show_headings')) {
548 $start = 1;
549 }
550 } elseif ($importer_data->getParser() === 'xml') {
551 Logger::debug('IM -get_xml_file');
552 $file = $this->get_xml_file($importer_data, $config);
553 Logger::debug('IM -load_parser');
554 $parser = new XMLParser($file);
555 } else {
556 $parser = apply_filters('iwp/importer/init_parser', false, $importer_data, $config);
557 }
558
559 if ($state->has_status('init')) {
560
561 Logger::debug('IM -get_record_count');
562 $end = $parser->file()->getRecordCount();
563
564 $config_data['start'] = $this->get_start($importer_data, $start);
565 $config_data['end'] = $this->get_end($importer_data, $config_data['start'], $end);
566
567 update_site_option('iwp_importer_config_' . $importer_id, $config_data);
568
569 Logger::debug('IM -update_state');
570 $state->update(function ($state) use ($config_data) {
571
572 Logger::debug('IM -update_state=running');
573
574 $state['id'] = $config_data['id'];
575 $state['status'] = 'running';
576 $state['progress']['import']['start'] = $config_data['start'];
577 $state['progress']['import']['end'] = $config_data['end'];
578 return $state;
579 });
580
581 Logger::debug('IM -write_status_session_to_file');
582 Util::write_status_session_to_file($id, $state);
583
584 do_action('iwp/importer/init', $importer_data);
585 }
586
587 Logger::debug('IM -import');
588 $importer = new \ImportWP\Common\Importer\Importer($config);
589 $importer->parser($parser);
590 $importer->mapper($mapper);
591 $importer->from($config_data['start']);
592 $importer->to($config_data['end']);
593 $importer->filter($importer_data->getFilters());
594 $importer->import($importer_id, $user, $state);
595 Logger::debug('IM -import_complete');
596 } catch (\Exception $e) {
597
598 // TODO: Missing template errors are currently not being logged to history, possibly others?
599 Logger::error('import -error=' . $e->getMessage(), $importer_id);
600 return $state->error($e)->get_raw();
601 }
602
603 /**
604 * @var Properties $properties
605 */
606 $properties = Container::getInstance()->get('properties');
607
608 // rotate files to not fill up server
609 $importer_data->limit_importer_files($properties->file_rotation);
610 $this->prune_importer_logs($importer_data, $properties->log_rotation);
611
612 $template->unregister_hooks();
613
614 $this->event_handler->run('importer_manager.import_shutdown', [$importer_data]);
615
616 return $state->update(function ($data) {
617 $data['duration'] = floatval($data['duration']) + Logger::timer();
618 return $data;
619 })->get_raw();
620 }
621
622 public function get_start($importer_data, $start)
623 {
624 $tmp_start = $importer_data->getStartRow();
625 if (!is_null($tmp_start) && "" !== $tmp_start) {
626 $tmp_start = intval($tmp_start);
627
628 if ($tmp_start > $start) {
629 $start = $tmp_start;
630 }
631 }
632
633 return $start;
634 }
635
636 public function get_end($importer_data, $start, $end)
637 {
638 $tmp_max_row = $importer_data->getMaxRow();
639 if (!is_null($tmp_max_row) && $tmp_max_row !== '') {
640 $tmp_end = $start + intval($tmp_max_row);
641 if ($tmp_end < $end) {
642 $end = $tmp_end;
643 }
644 }
645
646 return $end;
647 }
648
649 public function get_importer_template($id)
650 {
651 $importer_model = $this->get_importer($id);
652 $templates = $this->get_templates();
653 $template_name = $importer_model->getTemplate();
654
655 if (!isset($templates[$template_name])) {
656 $exception_msg = "Unable to locate importer template: " . $template_name;
657 Logger::error('import -get_importer_template=' . $exception_msg, $importer_model->getId());
658 throw new \Exception($exception_msg);
659 }
660
661 return $this->template_manager->load_template($templates[$template_name]);
662 }
663
664 /**
665 * Get importer mapper
666 *
667 * @param int $id
668 * @param Template $template
669 * @param Permission $permission
670 * @return MapperInterface
671 */
672 public function get_importer_mapper($id, $template, $permission = null)
673 {
674 $importer = $this->get_importer($id);
675 $mapper_name = $template->get_mapper();
676
677 $mappers = $this->get_mappers();
678 return isset($mappers[$mapper_name]) ? new $mappers[$mapper_name]($importer, $template, $permission) : false;
679 }
680
681 public function get_mappers()
682 {
683 $mappers = $this->event_handler->run('mappers.register', [[]]); // apply_filters('iwp/mappers/register', []);
684 $mappers = array_merge($mappers, [
685 'post' => PostMapper::class,
686 'user' => UserMapper::class,
687 'term' => TermMapper::class
688 ]);
689 return $mappers;
690 }
691
692 public function get_mapper($key)
693 {
694 $mappers = $this->get_mappers();
695 if (!isset($mappers[$key])) {
696 return new \WP_Error('IWP_IM_1', 'Unable to locate mapper: ' . $key);
697 }
698
699 return $mappers[$key];
700 }
701
702 public function get_templates()
703 {
704 $templates = $this->event_handler->run('templates.register', [[]]);
705 $templates = array_merge($templates, [
706 'post' => PostTemplate::class,
707 'page' => PageTemplate::class,
708 'user' => UserTemplate::class,
709 'term' => TermTemplate::class,
710 'custom-post-type' => CustomPostTypeTemplate::class,
711 ]);
712 return $templates;
713 }
714
715 public function get_template($key)
716 {
717 $templates = $this->get_templates();
718 if (!isset($templates[$key])) {
719 return new \WP_Error('IWP_IM_1', 'Unable to locate template: ' . $key);
720 }
721
722 return $templates[$key];
723 }
724
725 public function get_importer_debug_log(ImporterModel $importer_data, $page = 0, $per_page = -1)
726 {
727 $file_path = Logger::getLogFile($importer_data->getId());
728
729 $line_counter = 0;
730 $lines = [];
731 $start = $end = -1;
732
733 if ($per_page > 0) {
734 $start = ($page - 1) * $per_page;
735 $end = $start + $per_page;
736 }
737
738 if (file_exists($file_path)) {
739 $fh = fopen($file_path, 'r');
740 if ($fh !== false) {
741 while (($data = fgetcsv($fh)) !== false) {
742 if ($line_counter === $end) {
743 return $lines;
744 } elseif ($per_page === -1 || $line_counter >= $start) {
745 $lines[] = $data;
746 }
747
748 $line_counter++;
749 }
750 fclose($fh);
751 }
752 }
753 return $lines;
754 }
755
756 public function prune_importer_logs($importer_model, $limit)
757 {
758 $limit = intval($limit);
759 if ($limit <= -1) {
760 return;
761 }
762
763 $file_path = Util::get_importer_status_file_path($importer_model->getId());
764 $tmp_file_path = Util::get_importer_status_file_path($importer_model->getId()) . '.tmp';
765 $lines = $this->get_importer_logs($importer_model);
766
767 if (count($lines) > $limit) {
768
769 require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
770 require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php');
771 $fileSystemDirect = new \WP_Filesystem_Direct(false);
772
773 $fh = fopen($tmp_file_path, 'w');
774 for ($i = 0; $i < count($lines); $i++) {
775
776 if ($i < count($lines) - $limit) {
777 $log_file_path = Util::get_importer_log_file_path($importer_model->getId(), $lines[$i]['id']);
778 if ($fileSystemDirect->exists($log_file_path)) {
779
780 $fileSystemDirect->delete($log_file_path);
781
782 $tmp = $log_file_path;
783 for ($j = 0; $j < 3; $j++) {
784 $tmp = dirname($tmp);
785 $sub_files = $fileSystemDirect->dirlist($log_file_path);
786 if (empty($sub_files)) {
787 $fileSystemDirect->rmdir($tmp);
788 }
789 }
790 }
791 } else {
792 fputs($fh, json_encode($lines[$i]) . "\n");
793 }
794 }
795 fclose($fh);
796
797 if ($fileSystemDirect->move($tmp_file_path, $file_path, true)) {
798 $fileSystemDirect->delete($tmp_file_path);
799 }
800 }
801 }
802
803 public function get_importer_logs(ImporterModel $importer_data, $page = 0, $per_page = -1)
804 {
805 $file_path = Util::get_importer_status_file_path($importer_data->getId());
806
807 $line_counter = 0;
808 $lines = [];
809
810 $start = $end = -1;
811
812 if ($per_page > 0) {
813 $start = ($page - 1) * $per_page;
814 $end = $start + $per_page;
815 }
816
817 if (file_exists($file_path)) {
818 $fh = fopen($file_path, 'r');
819 if ($fh !== false) {
820 while (($data = fgets($fh)) !== false) {
821 if ($data[strlen($data) - 1] === "\n") {
822 $data = substr($data, 0, strlen($data) - 1);
823 }
824
825 if ($line_counter === $end) {
826 return $lines;
827 } elseif ($per_page === -1 || $line_counter >= $start) {
828 $lines[] = json_decode($data, true);
829 }
830
831 $line_counter++;
832 }
833 fclose($fh);
834 }
835 }
836 return $lines;
837 }
838
839 public function get_importer_log(ImporterModel $importer_data, $session_id, $page = 0, $per_page = -1)
840 {
841 $file_path = Util::get_importer_log_file_path($importer_data->getId(), $session_id);
842
843 $line_counter = 0;
844 $lines = [];
845 $start = $end = -1;
846
847 if ($per_page > 0) {
848 $start = ($page - 1) * $per_page;
849 $end = $start + $per_page;
850 }
851
852 if (file_exists($file_path)) {
853 $fh = fopen($file_path, 'r');
854 if ($fh !== false) {
855 while (($data = fgetcsv($fh)) !== false) {
856 if ($line_counter === $end) {
857 return $lines;
858 } elseif ($per_page === -1 || $line_counter >= $start) {
859 $lines[] = $data;
860 }
861
862 $line_counter++;
863 }
864 fclose($fh);
865 }
866 }
867 return $lines;
868 }
869
870 public function get_importer_status_report(ImporterModel $immpoter_data, $session)
871 {
872 $logs = $this->get_importer_logs($immpoter_data);
873 foreach ($logs as $log) {
874 if ($log && isset($log['id']) && $log['id'] === $session) {
875 return $log;
876 }
877 }
878 return false;
879 }
880 }
881