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

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