PluginProbe
Import WP – CSV & XML Import Export for WordPress / 2.7.3
Import WP – CSV & XML Import Export for WordPress v2.7.3
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.3, at class/Common/Importer/ImporterManager.php

879 lines 28.1 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
585 Logger::debug('IM -import');
586 $importer = new \ImportWP\Common\Importer\Importer($config);
587 $importer->parser($parser);
588 $importer->mapper($mapper);
589 $importer->from($config_data['start']);
590 $importer->to($config_data['end']);
591 $importer->filter($importer_data->getFilters());
592 $importer->import($importer_id, $user, $state);
593 Logger::debug('IM -import_complete');
594 } catch (\Exception $e) {
595
596 // TODO: Missing template errors are currently not being logged to history, possibly others?
597 Logger::error('import -error=' . $e->getMessage(), $importer_id);
598 return $state->error($e)->get_raw();
599 }
600
601 /**
602 * @var Properties $properties
603 */
604 $properties = Container::getInstance()->get('properties');
605
606 // rotate files to not fill up server
607 $importer_data->limit_importer_files($properties->file_rotation);
608 $this->prune_importer_logs($importer_data, $properties->log_rotation);
609
610 $template->unregister_hooks();
611
612 $this->event_handler->run('importer_manager.import_shutdown', [$importer_data]);
613
614 return $state->update(function ($data) {
615 $data['duration'] = floatval($data['duration']) + Logger::timer();
616 return $data;
617 })->get_raw();
618 }
619
620 public function get_start($importer_data, $start)
621 {
622 $tmp_start = $importer_data->getStartRow();
623 if (!is_null($tmp_start) && "" !== $tmp_start) {
624 $tmp_start = intval($tmp_start);
625
626 if ($tmp_start > $start) {
627 $start = $tmp_start;
628 }
629 }
630
631 return $start;
632 }
633
634 public function get_end($importer_data, $start, $end)
635 {
636 $tmp_max_row = $importer_data->getMaxRow();
637 if (!is_null($tmp_max_row) && $tmp_max_row !== '') {
638 $tmp_end = $start + intval($tmp_max_row);
639 if ($tmp_end < $end) {
640 $end = $tmp_end;
641 }
642 }
643
644 return $end;
645 }
646
647 public function get_importer_template($id)
648 {
649 $importer_model = $this->get_importer($id);
650 $templates = $this->get_templates();
651 $template_name = $importer_model->getTemplate();
652
653 if (!isset($templates[$template_name])) {
654 $exception_msg = "Unable to locate importer template: " . $template_name;
655 Logger::error('import -get_importer_template=' . $exception_msg, $importer_model->getId());
656 throw new \Exception($exception_msg);
657 }
658
659 return $this->template_manager->load_template($templates[$template_name]);
660 }
661
662 /**
663 * Get importer mapper
664 *
665 * @param int $id
666 * @param Template $template
667 * @param Permission $permission
668 * @return MapperInterface
669 */
670 public function get_importer_mapper($id, $template, $permission = null)
671 {
672 $importer = $this->get_importer($id);
673 $mapper_name = $template->get_mapper();
674
675 $mappers = $this->get_mappers();
676 return isset($mappers[$mapper_name]) ? new $mappers[$mapper_name]($importer, $template, $permission) : false;
677 }
678
679 public function get_mappers()
680 {
681 $mappers = $this->event_handler->run('mappers.register', [[]]); // apply_filters('iwp/mappers/register', []);
682 $mappers = array_merge($mappers, [
683 'post' => PostMapper::class,
684 'user' => UserMapper::class,
685 'term' => TermMapper::class
686 ]);
687 return $mappers;
688 }
689
690 public function get_mapper($key)
691 {
692 $mappers = $this->get_mappers();
693 if (!isset($mappers[$key])) {
694 return new \WP_Error('IWP_IM_1', 'Unable to locate mapper: ' . $key);
695 }
696
697 return $mappers[$key];
698 }
699
700 public function get_templates()
701 {
702 $templates = $this->event_handler->run('templates.register', [[]]);
703 $templates = array_merge($templates, [
704 'post' => PostTemplate::class,
705 'page' => PageTemplate::class,
706 'user' => UserTemplate::class,
707 'term' => TermTemplate::class,
708 'custom-post-type' => CustomPostTypeTemplate::class,
709 ]);
710 return $templates;
711 }
712
713 public function get_template($key)
714 {
715 $templates = $this->get_templates();
716 if (!isset($templates[$key])) {
717 return new \WP_Error('IWP_IM_1', 'Unable to locate template: ' . $key);
718 }
719
720 return $templates[$key];
721 }
722
723 public function get_importer_debug_log(ImporterModel $importer_data, $page = 0, $per_page = -1)
724 {
725 $file_path = Logger::getLogFile($importer_data->getId());
726
727 $line_counter = 0;
728 $lines = [];
729 $start = $end = -1;
730
731 if ($per_page > 0) {
732 $start = ($page - 1) * $per_page;
733 $end = $start + $per_page;
734 }
735
736 if (file_exists($file_path)) {
737 $fh = fopen($file_path, 'r');
738 if ($fh !== false) {
739 while (($data = fgetcsv($fh)) !== false) {
740 if ($line_counter === $end) {
741 return $lines;
742 } elseif ($per_page === -1 || $line_counter >= $start) {
743 $lines[] = $data;
744 }
745
746 $line_counter++;
747 }
748 fclose($fh);
749 }
750 }
751 return $lines;
752 }
753
754 public function prune_importer_logs($importer_model, $limit)
755 {
756 $limit = intval($limit);
757 if ($limit <= -1) {
758 return;
759 }
760
761 $file_path = Util::get_importer_status_file_path($importer_model->getId());
762 $tmp_file_path = Util::get_importer_status_file_path($importer_model->getId()) . '.tmp';
763 $lines = $this->get_importer_logs($importer_model);
764
765 if (count($lines) > $limit) {
766
767 require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
768 require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php');
769 $fileSystemDirect = new \WP_Filesystem_Direct(false);
770
771 $fh = fopen($tmp_file_path, 'w');
772 for ($i = 0; $i < count($lines); $i++) {
773
774 if ($i < count($lines) - $limit) {
775 $log_file_path = Util::get_importer_log_file_path($importer_model->getId(), $lines[$i]['id']);
776 if ($fileSystemDirect->exists($log_file_path)) {
777
778 $fileSystemDirect->delete($log_file_path);
779
780 $tmp = $log_file_path;
781 for ($j = 0; $j < 3; $j++) {
782 $tmp = dirname($tmp);
783 $sub_files = $fileSystemDirect->dirlist($log_file_path);
784 if (empty($sub_files)) {
785 $fileSystemDirect->rmdir($tmp);
786 }
787 }
788 }
789 } else {
790 fputs($fh, json_encode($lines[$i]) . "\n");
791 }
792 }
793 fclose($fh);
794
795 if ($fileSystemDirect->move($tmp_file_path, $file_path, true)) {
796 $fileSystemDirect->delete($tmp_file_path);
797 }
798 }
799 }
800
801 public function get_importer_logs(ImporterModel $importer_data, $page = 0, $per_page = -1)
802 {
803 $file_path = Util::get_importer_status_file_path($importer_data->getId());
804
805 $line_counter = 0;
806 $lines = [];
807
808 $start = $end = -1;
809
810 if ($per_page > 0) {
811 $start = ($page - 1) * $per_page;
812 $end = $start + $per_page;
813 }
814
815 if (file_exists($file_path)) {
816 $fh = fopen($file_path, 'r');
817 if ($fh !== false) {
818 while (($data = fgets($fh)) !== false) {
819 if ($data[strlen($data) - 1] === "\n") {
820 $data = substr($data, 0, strlen($data) - 1);
821 }
822
823 if ($line_counter === $end) {
824 return $lines;
825 } elseif ($per_page === -1 || $line_counter >= $start) {
826 $lines[] = json_decode($data, true);
827 }
828
829 $line_counter++;
830 }
831 fclose($fh);
832 }
833 }
834 return $lines;
835 }
836
837 public function get_importer_log(ImporterModel $importer_data, $session_id, $page = 0, $per_page = -1)
838 {
839 $file_path = Util::get_importer_log_file_path($importer_data->getId(), $session_id);
840
841 $line_counter = 0;
842 $lines = [];
843 $start = $end = -1;
844
845 if ($per_page > 0) {
846 $start = ($page - 1) * $per_page;
847 $end = $start + $per_page;
848 }
849
850 if (file_exists($file_path)) {
851 $fh = fopen($file_path, 'r');
852 if ($fh !== false) {
853 while (($data = fgetcsv($fh)) !== false) {
854 if ($line_counter === $end) {
855 return $lines;
856 } elseif ($per_page === -1 || $line_counter >= $start) {
857 $lines[] = $data;
858 }
859
860 $line_counter++;
861 }
862 fclose($fh);
863 }
864 }
865 return $lines;
866 }
867
868 public function get_importer_status_report(ImporterModel $immpoter_data, $session)
869 {
870 $logs = $this->get_importer_logs($immpoter_data);
871 foreach ($logs as $log) {
872 if ($log && isset($log['id']) && $log['id'] === $session) {
873 return $log;
874 }
875 }
876 return false;
877 }
878 }
879