Commit inicial - WordPress Análisis de Precios Unitarios

- WordPress core y plugins
- Tema Twenty Twenty-Four configurado
- Plugin allow-unfiltered-html.php simplificado
- .gitignore configurado para excluir wp-config.php y uploads

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
root
2025-11-03 21:04:30 -06:00
commit a22573bf0b
24068 changed files with 4993111 additions and 0 deletions

View File

@@ -0,0 +1,564 @@
<?php
/**
* WP Ultimate CSV Importer plugin file.
*
* Copyright (C) 2010-2020, Smackcoders Inc - info@smackcoders.com
*/
namespace Smackcoders\FCSV;
require_once(__DIR__.'/../vendor/autoload.php');
use League\Csv\Writer;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
if ( ! defined( 'ABSPATH' ) )
exit; // Exit if accessed directly
class DesktopUpload implements Uploads{
private static $instance = null;
private static $smack_csv_instance = null;
private function __construct(){
add_action('wp_ajax_get_desktop',array($this,'upload_function'));
add_action('wp_ajax_oneClickUpload',array($this,'upload_function'));
add_action('wp_ajax_get_csv_delimiter', [$this, 'get_csv_delimiter']);
}
public static function getInstance() {
if (DesktopUpload::$instance == null) {
DesktopUpload::$instance = new DesktopUpload;
DesktopUpload::$smack_csv_instance = SmackCSV::getInstance();
return DesktopUpload::$instance;
}
return DesktopUpload::$instance;
}
private function convertXlsxToCsv($upload_dir_path, $event_key)
{
$spreadsheet = IOFactory::load($_FILES['csvFile']['tmp_name']);
$csv_file_path = $upload_dir_path . '/' . $event_key;
$csv_writer = new Csv($spreadsheet);
$csv_writer->setDelimiter(',');
$csv_writer->setEnclosure('"');
$csv_writer->setLineEnding("\r\n");
$csv_writer->setIncludeSeparatorLine(false);
$csv_writer->save($csv_file_path);
}
/**
* Upload file from desktop.
*/
public function upload_function(){
$this->check_upload_security();
check_ajax_referer('smack-ultimate-csv-importer', 'securekey');
global $wpdb;
$validate_instance = ValidateFile::getInstance();
$zip_instance = ZipHandler::getInstance();
$media_type = '';
if (isset($_POST['MediaType'])) {
$media_type = strtolower(sanitize_key($_POST['MediaType']));
}
global $wpdb;
$file_table_name = $wpdb->prefix ."smackcsv_file_events";
$file_name = $_FILES['csvFile']['name'];
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
if(empty($file_extension)){
$file_extension = 'xml';
}
$validate_format = $validate_instance->validate_file_format($file_name);
$response =[];
if (!extension_loaded('xml')) {
$response['success'] = false;
$response['message'] = 'The required PHP module xml is not installed. Please install it.';
echo wp_json_encode($response);
wp_die();
}
if($validate_format == 'yes'){
$upload_dir = DesktopUpload::$smack_csv_instance->create_upload_dir();
if($upload_dir){
$event_key = DesktopUpload::$smack_csv_instance->convert_string2hash_key($file_name);
if($file_extension == 'zip'){
if(!function_exists('curl_version')){
$response['success'] = false;
$response['message'] = 'Curl is not exists.Kindly install it.';
echo wp_json_encode($response);
wp_die();
}
$zip_response = [];
$path = $upload_dir . $event_key . '.zip';
$extract_path = $upload_dir . $event_key;
if(move_uploaded_file($_FILES['csvFile']['tmp_name'], $path)){
chmod($path, 0777);
$zip_result = $zip_instance->zip_upload($path , $extract_path,$event_key);
if($zip_result == 'UnSupported File Format'){
$zip_response['success'] = false;
$zip_response['message'] = "UnSupported File Format Inside Zip";
}
else{
$zip_response['success'] = true;
$zip_response['filename'] = $file_name;
$zip_response['file_type'] = 'zip';
$zip_response['info'] = $zip_result;
$zip_response['info'] = $zip_result;
$action = $_POST['action'];
if($action == 'oneClickUpload'){
$zip_response['info'] = $zip_result;
$exporter_adapter_list = array(
"core_fields" => "CORE",
"Comments" => "Comments",
"acf_fields" => "ACF",
"featured_image_meta" => "FEATURED_IMAGE_META",
"acf_pro_fields" => "ACF",
"acf_repeater_fields" => "RF",
"acf_repeater_of_repeater_fields" => "RRF",
"jet_review_fields" => "JEREVIEW",
"jet_booking_fields" => "JEBOOKING",
"jetengine_fields" => "JE",
"jetengine_rf_fields" => "JERF",
"jetenginecpt_fields" => "JECPT",
"jetenginecpt_rf_fields" => "JECPTRF",
"jetenginecct_fields" => "JECCT",
"jetenginecct_rf_fields" => "JECCTRF",
"jetenginetaxonomy_fields" => "JETAX",
"jetenginetaxonomy_rf_fields" => "JETAXRF",
"jetengine_rel_fields" => "JEREL",
"pods_fields" => "PODS",
"all_in_one_seo_fields" => "AIOSEO",
"yoast_seo_fields" => "YOASTSEO",
"wpcomplete_fields" => "WPCOMPLETE",
"seopress_fields" => "SEOPRESS",
"rank_math_fields" => "RANKMATH",
"elementor_meta_fields" => "ELEMENTOR",
"product_meta_fields" => "ECOMMETA",
"product_attr_fields" => "ATTRMETA",
"product_bundle_meta_fields" => "BUNDLEMETA",
"ppom_meta_fields" => "PPOMMETA",
"epo_meta_fields" => "EPOMETA",
"listing_meta_fields" => "LISTINGMETA",
"refund_meta_fields" => "REFUNDMETA",
"order_meta_fields" => "ORDERMETA",
"coupon_meta_fields" => "COUPONMETA",
"cctm_fields" => "CCTM",
"custom_fields_suite_fields" => "CFS",
"cmb2_fields" => "CMB2",
"billing_and_shipping_information" => "BSI",
"custom_fields_wp_members" => "WPMEMBERS",
"custom_fields_members" => "MEMBERS",
"wp_ecom_custom_fields" => "WPECOMMETA",
"terms_and_taxonomies" => "TERMS",
"wpml_fields" => "WPML",
"wordpress_custom_fields" => "CORECUSTFIELDS",
"directory_pro_fields" => "DPF",
"events_manager_fields" => "EVENTS",
"nextgen_gallery_fields" => "NEXTGEN",
"course_settings_fields" => "LPCOURSE",
"acf_flexible_fields" => "FC",
"acf_group_fields" => "GF",
"types_fields" => "TYPES",
"lesson_settings_fields" => "LPLESSON",
"curriculum_settings_fields" => "LPCURRICULUM",
"quiz_settings_fields" => "LPQUIZ",
"question_settings_fields" => "LPQUESTION",
"order_settings_fields" => "LPORDER",
"lifter_course_settings_fields" => "LIFTERCOURSE",
"lifter_review_settings_fields" => "LIFTERREVIEW",
"lifter_coupon_settings_fields" => "LIFTERCOUPON",
"lifter_lesson_settings_fields" => "LIFTERLESSON",
"course_settings_fields_stm" => "STMCOURSE",
"curriculum_settings_fields_stm" => "STMCURRICULUM",
"lesson_settings_fields_stm" => "STMLESSON",
"quiz_settings_fields_stm" => "STMQUIZ",
"order_settings_fields_stm" => "STMORDER",
"forum_attributes_fields" => "FORUM",
"topic_attributes_fields" => "TOPIC",
"reply_attributes_fields" => "REPLY",
"Polylang_settings_fields" => "POLYLANG",
"metabox_fields" => "METABOX",
"metabox_relations_fields" => "METABOXRELATION",
"metabox_group_fields" => "METABOXGROUP",
"job_listing_fields" => "JOB",
"fifu_post_settings_fields" => "FIFUPOSTS",
"fifu_page_settings_fields" => "FIFUPAGE",
"fifu_custompost_settings_fields" => "FIFUCUSTOMPOST"
);
foreach ($zip_result as $file) {
if (pathinfo($file['name'], PATHINFO_EXTENSION) === 'json') {
$json_content = file_get_contents($file['path']);
$decoded_json = json_decode($json_content, true);
function mapFields($decoded_json, $exporter_adapter_list) {
$mappedFields = [];
foreach ($decoded_json as $key => $fields) {
if (isset($exporter_adapter_list[$key])) {
$mappedKey = $exporter_adapter_list[$key]; // Get mapped value from the list
if (!isset($mappedFields[$mappedKey])) {
$mappedFields[$mappedKey] = []; // Ensure category exists
}
foreach ($fields as $fieldKey => $fieldValue) {
$mappedFields[$mappedKey][$fieldKey] = $fieldValue;
}
}
}
return json_encode($mappedFields, JSON_PRETTY_PRINT);
}
$formatted_data = [];
foreach ($decoded_json['headers']['fields'] as $field_group) {
foreach ($field_group as $key => $fields) {
if (is_array($fields)) {
foreach ($fields as $field) {
if (isset($field['name'])) {
// Assign key and value dynamically
$formatted_data[$key][$field['name']] = $field['name'];
}
}
}
}
}
$json_content = json_encode($formatted_data, JSON_PRETTY_PRINT);
$decoded_jsons = json_decode($json_content, true);
$mappedJson = mapFields($decoded_jsons, $exporter_adapter_list);
$this->save_mapping($mappedJson,$event_key,$_POST,$decoded_json);
if (is_array($decoded_json)) {
// Merge JSON key-value pairs into the response array
$zip_response = array_merge($zip_response, $decoded_json);
}
}
}
}
$zip_response['hashkey'] = $event_key;
}
}else{
$zip_response['success'] = false;
$zip_response['message'] = "Cannot download zip file";
}
if (preg_match('/^smbundle_(.*)\.zip$/', $file_name, $matches)) {
$path = $upload_dir . $event_key . '/' . $event_key;
if (file_exists($path)) {
// Get the MIME type of the file
$mime_type = mime_content_type($path); // Alternative: finfo_open(FILES)
// Get the extension based on MIME type
$extension = $this->get_extension_from_mime($mime_type);
}
$file_name = $matches[1] .'.'.$extension ;
} else {
echo "Invalid file name format";
}
$wpdb->insert( $file_table_name , array('file_name' => $file_name ,'total_rows' => $decoded_json['total_rows'],'hash_key' => $event_key , 'status' => 'Downloading', 'lock' => true) );
echo wp_json_encode($zip_response);
wp_die();
}
$upload_dir_path = $upload_dir. $event_key;
if (!is_dir($upload_dir_path)) {
wp_mkdir_p( $upload_dir_path);
}
chmod($upload_dir_path, 0777);
$wpdb->insert( $file_table_name , array('file_name' => $file_name , 'hash_key' => $event_key , 'status' => 'Downloading', 'lock' => true) );
$last_id = $wpdb->get_results("SELECT id FROM $file_table_name ORDER BY id DESC LIMIT 1",ARRAY_A);
$lastid = $last_id[0]['id'];
switch($_FILES['csvFile']['error']){
case UPLOAD_ERR_OK:
$path = $upload_dir. $event_key. '/' . $event_key;
if ($file_extension == 'xlsx' || $file_extension == 'xls') {
$this->convertXlsxToCsv($upload_dir_path, $event_key);
$file_extension = 'csv';
}
else{
if (move_uploaded_file($_FILES['csvFile']['tmp_name'], $path)) {
chmod($path, 0755);
} else {
$response['success'] = false;
$response['message'] = "Cannot download the file";
echo wp_json_encode($response);
$wpdb->get_results("UPDATE $file_table_name SET status='Download_Failed' WHERE id = '$lastid'");
}
}
$validate_file = $validate_instance->file_validation($path , $file_extension);
$file_size = filesize($path);
$filesize = $validate_instance->formatSizeUnits($file_size);
$server_software = sanitize_text_field($_SERVER['SERVER_SOFTWARE']);
if($validate_file == "yes"){
$fields = $wpdb->get_results("UPDATE $file_table_name SET status='Downloaded',`lock`=false WHERE id = '$lastid'");
$get_result = $validate_instance->import_record_function($event_key , $file_name);
if(isset($media_type) && ($media_type == 'external' || $media_type == 'local')){
$get_result['selected type'] = 'Media';
}
$response['success'] = true;
$response['filename'] = $file_name;
$response['hashkey'] = $event_key;
$response['posttype'] = $get_result['Post Type'];
$response['selectedtype'] = $get_result['selected type'];
$response['taxonomy'] = $get_result['Taxonomy'];
$response['file_type'] = $file_extension;
$response['file_size'] = $filesize;
$response['message'] = 'success';
if ($file_extension === 'csv' || $file_extension === 'tsv') {
$delimiter = $this->detect_csv_delimiter($path);
update_option("smack_csv_delimiter_{$event_key}", $delimiter);
}
echo wp_json_encode($response);
}
else{
$response['success'] = false;
$response['message'] = $validate_file;
echo wp_json_encode($response);
unlink($path);
$wpdb->get_results("UPDATE $file_table_name SET status='Download_Failed' WHERE id = '$lastid'");
}
break;
case UPLOAD_ERR_INI_SIZE:
$response['success'] = false;
$response['message'] = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
echo wp_json_encode($response);
$wpdb->get_results("UPDATE $file_table_name SET status='Download_Failed' WHERE id = '$lastid'");
break;
default:
$response['success'] = false;
$response['message'] = "Cannot download file";
echo wp_json_encode($response);
$wpdb->get_results("UPDATE $file_table_name SET status='Download_Failed' WHERE id = '$lastid'");
break;
}
}else{
$response['success'] = false;
$response['message'] = "Please create Upload folder with writable permission";
echo wp_json_encode($response);
}
}else{
$response['success'] = false;
$response['message'] = $validate_format;
echo wp_json_encode($response);
}
wp_die();
}
private function check_upload_security() {
// Security: Check nonce for CSRF protection using wp_verify_nonce
if (!wp_verify_nonce($_POST['securekey'], 'smack-ultimate-csv-importer')) {
wp_die(__('Security check failed'));
}
// Security: Check user capabilities - only administrators should access upload functionality
if (!current_user_can('manage_options')) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
}
public function save_mapping($data,$hash_key,$post,$decoded_json)
{
check_ajax_referer('smack-ultimate-csv-importer', 'securekey');
$type = $decoded_json['selectedtype'];
$map_fields = $data;
$mapping_type = 'mapping-section';
$counter = isset($counter) ? $counter : 0;
$selected_mode = 'Advanced';
global $wpdb;
if ($selected_mode == 'simpleMode') {
$fileiteration = 5;
update_option('sm_bulk_import_free_iteration_limit', $fileiteration);
$media_settings['media_handle_option'] = 'true';
$media_settings['use_ExistingImage'] = 'true';
$image_info = array(
'media_settings' => $media_settings
);
update_option('smack_image_options', $image_info);
}
$template_table_name = $wpdb->prefix . "ultimate_csv_importer_mappingtemplate";
$file_table_name = $wpdb->prefix . "smackcsv_file_events";
$mapping_filter = '';
$mapped_fields = json_decode(stripslashes($map_fields), true);
$helpers_instance = ImportHelpers::getInstance();
$response = [];
$counter = 0;
foreach ($mapped_fields as $maps) {
foreach ($maps as $header_keys => $value) {
if (strpos($header_keys, '->cus2') !== false) {
if (!empty($value)) {
$helpers_instance->write_to_customfile($value);
}
}
}
}
foreach ($mapped_fields as $key => $value) {
if ($key === 'ECOMMETA') {
$map_data[$key] = $value;
if ($has_bundlemeta) {
$map_data['BUNDLEMETA'] = $mapped_fields['BUNDLEMETA'];
}
}
elseif ($key !== 'BUNDLEMETA') {
$map_data[$key] = $value;
}
elseif($key == "ATTRMETA"){
foreach ($value as $v_key => $val) {
preg_match('/\d+/', $v_key, $matches);
$index = $matches[0] ?? $counter;
if (!isset($map_data['ATTRMETA'][$index])) {
$map_data['ATTRMETA'][$index] = [];
}
$map_data['ATTRMETA'][$index][$v_key] = $val;
}
if(is_array($map_data['ATTRMETA'])){
$map_data['ATTRMETA'] = array_values($map_data['ATTRMETA']);
}
}
}
$get_detail = $wpdb->get_results("SELECT file_name FROM $file_table_name WHERE `hash_key` = '$hash_key'");
$get_file_name = $get_detail[0]->file_name;
$get_hash = $wpdb->get_results("SELECT eventKey FROM $template_table_name");
$mapping_fields = serialize($map_data);
$time = date('Y-m-d h:i:s');
$get_file_name = $get_detail[0]->file_name;
// Using prepare to safely insert the values
if(!empty($get_hash)){
foreach ($get_hash as $hash_values) {
$inserted_hash_values[] = $hash_values->eventKey;
}
if (in_array($hash_key, $inserted_hash_values)) {
$query = $wpdb->prepare(
"UPDATE $template_table_name SET mapping = %s, mapping_filter = %s, createdtime = %s, module = %s, mapping_type = %s WHERE eventKey = %s",
$mapping_fields,
$mapping_filter,
$time,
$type,
$mapping_type,
$hash_key
);
} else {
$query = $wpdb->prepare(
"INSERT INTO $template_table_name (mapping, mapping_filter , createdtime, module, csvname, eventKey, mapping_type)
VALUES (%s, %s, %s, %s, %s, %s, %s)",
$mapping_fields,
$mapping_filter,
$time,
$type,
$get_file_name,
$hash_key,
$mapping_type
);
}
}else{
$query = $wpdb->prepare(
"INSERT INTO $template_table_name (mapping, mapping_filter , createdtime, module, csvname, eventKey, mapping_type)
VALUES (%s, %s, %s, %s, %s, %s, %s)",
$mapping_fields,
$mapping_filter,
$time,
$type,
$get_file_name,
$hash_key,
$mapping_type
);
}
$wpdb->query($query);
$fileiteration = '5';
update_option('sm_bulk_import_free_iteration_limit', $fileiteration);
$response['success'] = true;
$response['file_iteration'] = (int)$fileiteration;
}
public function get_extension_from_mime($mime_type) {
$mime_map = [
'text/csv' => 'csv',
'application/xml' => 'xml',
'text/xml' => 'xml',
'application/vnd.ms-excel' => 'xls',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
'text/tab-separated-values' => 'tsv',
];
return $mime_map[$mime_type] ?? null;
}
public static function detect_csv_delimiter($file_path) {
$delimiters = [",", ";", "\t", "|"];
$line = '';
$handle = fopen($file_path, 'r');
if ($handle) {
$line = fgets($handle);
fclose($handle);
}
$best_delimiter = ',';
$max_count = 0;
foreach ($delimiters as $delimiter) {
$fields = str_getcsv($line, $delimiter);
if (count($fields) > $max_count) {
$max_count = count($fields);
$best_delimiter = $delimiter;
}
}
return $best_delimiter;
}
public function get_csv_delimiter() {
$this->check_upload_security();
check_ajax_referer('smack-ultimate-csv-importer', 'securekey');
$event_key = sanitize_text_field($_POST['hashkey']);
$delimiter = get_option("smack_csv_delimiter_{$event_key}", ',');
wp_send_json_success([
'delimiter' => $delimiter
]);
}
}

View File

@@ -0,0 +1,272 @@
<?php
/**
* WP Ultimate CSV Importer plugin file.
*
* Copyright (C) 2010-2020, Smackcoders Inc - info@smackcoders.com
*/
namespace Smackcoders\FCSV;
require_once(__DIR__.'/../vendor/autoload.php');
use League\Csv\Writer;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
if ( ! defined( 'ABSPATH' ) )
exit; // Exit if accessed directly
class FtpUpload implements Uploads{
private static $instance = null;
private static $smack_csv_instance = null;
private function __construct(){
add_action('wp_ajax_get_ftp_url',array($this,'upload_function'));
add_action('wp_ajax_get_ftp_details',array($this,'getFtpDetails'));
}
public static function getInstance() {
if (FtpUpload::$instance == null) {
FtpUpload::$instance = new FtpUpload;
FtpUpload::$smack_csv_instance = SmackCSV::getInstance();
return FtpUpload::$instance;
}
return FtpUpload::$instance;
}
function convertXlsxToCsv($path, $upload_dir_path,$event_key)
{
$spreadsheet = IOFactory::load($path);
$csv_file_path = $upload_dir_path . '/' . $event_key;
$csv_writer = new Csv($spreadsheet);
$csv_writer->setDelimiter(',');
$csv_writer->setEnclosure('"');
$csv_writer->setLineEnding("\r\n");
$csv_writer->setIncludeSeparatorLine(false);
$csv_writer->save($csv_file_path);
}
/**
* Security check for FTP operations
* Validates nonce and user capabilities
*/
private function check_ftp_security() {
// Security: Check nonce for CSRF protection using wp_verify_nonce
if (!wp_verify_nonce($_POST['securekey'], 'smack-ultimate-csv-importer')) {
wp_die(__('Security check failed'));
}
// Security: Check user capabilities - only administrators should access FTP functionality
if (!current_user_can('manage_options')) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
}
/**
* Upload file from FTP.
*/
public function upload_function(){
$this->check_ftp_security();
$host_name = sanitize_text_field($_POST['HostName']);
$host_port = isset($_POST['HostPort']) ? intval(sanitize_text_field($_POST['HostPort'])) : 0;
$host_username = sanitize_text_field($_POST['HostUserName']);
$host_password = sanitize_text_field($_POST['HostPassword']);
$host_path = sanitize_text_field($_POST['HostPath']);
$action = sanitize_text_field($_POST['action']);
update_option('sm_ftp_hostname', $host_name);
update_option('sm_ftp_hostport', $host_port);
update_option('sm_ftp_hostusername', $host_username);
update_option('sm_ftp_hostpath', $host_path);
update_option('sm_ftp_hostpassword', $host_password);
update_option('action', $action);
global $wpdb;
$file_table_name = $wpdb->prefix ."smackcsv_file_events";
// set up basic connection
$conn_id = ftp_connect($host_name , $host_port);
$response = [];
if(!$conn_id){
$response['success'] = false;
$response['message'] = 'FTP connection failed';
echo wp_json_encode($response);
}else{
// login with username and password
$login_result = ftp_login($conn_id, $host_username, $host_password);
$ftp_file_name = basename($host_path);
$validate_instance = ValidateFile::getInstance();
$zip_instance = ZipHandler::getInstance();
$validate_format = $validate_instance->validate_file_format($ftp_file_name);
if($validate_format == 'yes'){
$upload_dir = FtpUpload::$smack_csv_instance->create_upload_dir();
if($upload_dir){
ftp_pasv($conn_id, true);
$version = '1';
$path = explode($ftp_file_name, $host_path);
$path = isset($path[0]) ? $path[0] : '';
$file_extension = pathinfo($ftp_file_name, PATHINFO_EXTENSION);
$allowed_exts = ['csv', 'xml', 'xlsx', 'xls', 'txt', 'tsv'];
if ( ! in_array( $file_extension, $allowed_exts, true ) ) {
wp_die( __( 'Invalid file type.', 'wp-ultimate-csv-importer' ), 400 );
}
if(empty($file_extension)){
$file_extension = 'xml';
}
// if($file_extension == 'xlsx'){
// $file_extension = 'csv';
// }
$file_extn = '.' . $file_extension;
$get_local_filename = explode($file_extn, $ftp_file_name);
$local_file_name = $get_local_filename[0] . '-1' . $file_extn;
$version = '1';
$event_key = FtpUpload::$smack_csv_instance->convert_string2hash_key($local_file_name);
if($file_extension == 'zip'){
$zip_response = [];
$path = $upload_dir . $event_key . '.zip';
$extract_path = $upload_dir . $event_key;
$server_file = $host_path;
$file_extension = strtolower($file_extension);
$ftp_mode = in_array($file_extension, ['csv', 'txt']) ? FTP_ASCII : FTP_BINARY;
$ret = ftp_nb_get($conn_id, $local_file, $server_file, $ftp_mode);
$ret = ftp_nb_continue($conn_id);
if($ret == FTP_FINISHED){
chmod($path, 0777);
$zip_response['success'] = true;
$zip_response['filename'] = $ftp_file_name;
$zip_response['file_type'] = 'zip';
$zip_response['info'] = $zip_instance->zip_upload($path , $extract_path);
}else{
$zip_response['success'] = false;
$zip_response['message'] = 'Cannot Download the file , file not found';
}
echo wp_json_encode($zip_response);
wp_die();
}
$upload_dir_path = $upload_dir. $event_key;
if (!is_dir($upload_dir_path)) {
wp_mkdir_p( $upload_dir_path);
}
chmod($upload_dir_path, 0777);
$wpdb->insert( $file_table_name , array( 'file_name' => $ftp_file_name , 'hash_key' => $event_key , 'status' => 'Downloading' , 'lock' => true ) );
$last_id = $wpdb->get_results("SELECT id FROM $file_table_name ORDER BY id DESC LIMIT 1",ARRAY_A);
$lastid=$last_id[0]['id'];
$local_file = $upload_dir. $event_key .'/'. $event_key;
$server_file = $host_path;
$fs = ftp_size($conn_id , $server_file);
$file_extension = strtolower($file_extension);
$ftp_mode = in_array($file_extension, ['csv', 'txt']) ? FTP_ASCII : FTP_BINARY;
$ret = ftp_nb_get($conn_id, $local_file, $server_file, $ftp_mode);
$filesize = filesize($local_file);
if ($filesize > 1024 && $filesize < (1024 * 1024)) {
$fileSize = round(($filesize / 1024), 2) . ' kb';
} else {
if ($filesize > (1024 * 1024)) {
$fileSize = round(($filesize / (1024 * 1024)), 2) . ' mb';
} else {
$fileSize = $filesize . ' byte';
}
}
while($ret == FTP_MOREDATA){
clearstatcache();
$dld = intval($fileSize);
if($dld > 0){
$i = ($dld/$fs)*100;
$wpdb->get_results("UPDATE $file_table_name SET progress='$i' , `lock`=true WHERE id = '$lastid'");
}
$ret = ftp_nb_continue($conn_id);
}
if($ret == FTP_FINISHED){
if ($file_extension == 'xlsx' || $file_extension == 'xls') {
$this->convertXlsxToCsv($local_file ,$upload_dir_path, $event_key);
$file_extension = 'csv';
}
chmod($local_file, 0777);
$validate_file = $validate_instance->file_validation($local_file , $file_extension);
$file_size = filesize($local_file);
$files_size = $validate_instance->formatSizeUnits($file_size);
if($validate_file == "yes"){
$wpdb->get_results("UPDATE $file_table_name SET status='Downloaded',`lock`=false WHERE id = '$lastid'");
$get_result = $validate_instance->import_record_function($event_key , $ftp_file_name);
$response['success'] = true;
$response['filename'] = $ftp_file_name;
$response['hashkey'] = $event_key;
$response['posttype'] = $get_result['Post Type'];
$response['taxonomy'] = $get_result['Taxonomy'];
$response['selectedtype'] = $get_result['selected type'];
$response['file_type'] = $file_extension;
$response['file_size'] = $files_size;
$response['message'] = 'Downloaded Successfully';
if ($file_extension === 'csv' || $file_extension === 'tsv') {
$delimiter = DesktopUpload::detect_csv_delimiter($local_file);
update_option("smack_csv_delimiter_{$event_key}", $delimiter);
}
echo wp_json_encode($response);
}else{
$response['success'] = false;
$response['message'] = $validate_file;
echo wp_json_encode($response);
$upload_dir = wp_upload_dir();
$base_dir = trailingslashit($upload_dir['basedir']);
$real_base = realpath($base_dir);
$real_path = realpath($path);
if ($real_path !== false && strpos($real_path, $real_base) === 0) {
unlink($real_path); // safe delete inside uploads only
}
$wpdb->get_results("UPDATE $file_table_name SET status='Download Failed' WHERE id = '$lastid'");
}
} else {
$wpdb->get_results("UPDATE $file_table_name SET status='Download Failed' WHERE id = '$lastid'");
$response['message'] = 'Cannot Download the file , file not found';
echo wp_json_encode($response);
}
// close the connection
ftp_close($conn_id);
}else{
$response['success'] = false;
$response['message'] = "Please create Upload folder with writable permission";
echo wp_json_encode($response);
}
}else{
$response['success'] = false;
$response['message'] = $validate_format;
echo wp_json_encode($response);
}
}
wp_die();
}
public function getFtpDetails(){
$this->check_ftp_security();
$result['HostName'] = get_option('sm_ftp_hostname');
$result['HostPort'] = get_option('sm_ftp_hostport');
$result['HostUserName'] = get_option('sm_ftp_hostusername');
$result['HostPath'] = get_option('sm_ftp_hostpath');
$result['HostPassword'] = get_option('sm_ftp_hostpassword');
$result['action'] = get_option('action');
echo wp_json_encode($result);
wp_die();
}
}

View File

@@ -0,0 +1,304 @@
<?php
/**
* WP Ultimate CSV Importer plugin file.
*
* Copyright (C) 2010-2020, Smackcoders Inc - info@smackcoders.com
*/
namespace Smackcoders\FCSV;
require_once(__DIR__.'/../vendor/autoload.php');
use League\Csv\Writer;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
if ( ! defined( 'ABSPATH' ) )
exit; // Exit if accessed directly
class UrlUpload implements Uploads{
private static $instance = null;
private static $smack_csv_instance = null;
private function __construct(){
add_action('wp_ajax_get_csv_url',array($this,'upload_function'));
}
public static function getInstance() {
if (UrlUpload::$instance == null) {
UrlUpload::$instance = new UrlUpload;
UrlUpload::$smack_csv_instance = SmackCSV::getInstance();
return UrlUpload::$instance;
}
return UrlUpload::$instance;
}
function convertXlsxToCsv($curlData, $upload_dir_path,$event_key)
{
// Temporary file path for downloaded XLSX
$csv_file_path = $upload_dir_path . '/' . $event_key;
$data = file_put_contents($csv_file_path, $curlData);
try {
$spreadsheet = IOFactory::load($csv_file_path);
} catch (Exception $e) {
}
// Convert to CSV
$csv_writer = new Csv($spreadsheet);
$csv_writer->setDelimiter(','); // Set delimiter (change to "\t" for tab-separated)
$csv_writer->setEnclosure('"'); // Set text enclosure character
$csv_writer->setSheetIndex(0); // Convert only the first sheet
// Save CSV file
$csv_writer->save($csv_file_path);
}
/**
* Upload file from URL.
*/
public function upload_function(){
check_ajax_referer('smack-ultimate-csv-importer', 'securekey');
$file_url = esc_url_raw($_POST['url']);
$file_url = wp_http_validate_url($file_url);
$media_type = '';
if (isset($_POST['MediaType'])) {
$media_type = sanitize_key($_POST['MediaType']);
}
if(!$file_url){
$response['success'] = false;
$response['message'] = 'Download Failed.URL is not valid.';
echo wp_json_encode($response);
die();
}
$response = [];
global $wpdb;
$file_table_name = $wpdb->prefix ."smackcsv_file_events";
if(strstr($file_url, 'https://bit.ly/')){
$file_url = $this->unshorten_bitly_url($file_url);
}
$pub = substr($file_url, strrpos($file_url, '/') + 1);
/*Added support for google addon & dropbox*/
if($pub=='pubhtml'){
$spread_sheet=substr($file_url, 0, -7);
$file_url = $spread_sheet.'pub?gid=0&single=true&output=csv';
}elseif ($pub=='edit?usp=sharing') {
$response['success'] = false;
$response['message'] = 'Update your Google sheet as Public';
echo wp_json_encode($response);
}
if(!strstr($file_url, 'https://www.dropbox.com/')) {
$file_url = $this->get_original_url($file_url);
$file_url = $file_url;
}
if(strstr($file_url, 'https://docs.google.com/')) {
$get_file_headers = get_headers($file_url, 1);
if(isset($get_file_headers['Content-Disposition'])){
$url_file_name = $this->get_filename_from_headers($get_file_headers['Content-Disposition']);
}else{
$get_file_id = explode('/', $file_url);
$external_file = 'google-sheet-' . $get_file_id[count($get_file_id) - 2];
$file_extension = explode('output=', $get_file_id[count($get_file_id) - 1]);
$file_extension = $file_extension[1];
$url_file_name = $external_file . '.' . $file_extension;
}
}elseif(strstr($file_url, 'https://www.dropbox.com/')) {
$filename = basename($file_url);
$get_local_filename = explode('?', $filename);
$url_file_name = $get_local_filename[0];
}else { # Other URL's except google spreadsheets
$supported_file = array('csv' , 'xml' ,'xlsx','zip' , 'txt','json', 'tsv');
$has_extension = explode(".", basename($file_url));
$has_file_extension = end($has_extension);
if($has_extension && in_array($has_file_extension , $supported_file)){
$url_file_name = basename($file_url);
}
else{
$get_file_headers = get_headers($file_url, 1);
if(isset($get_file_headers['Content-Disposition'])){
$url_file_name = $this->get_filename_from_headers($get_file_headers['Content-Disposition']);
}else{
if(strpos($file_url, '&type=') !== false) {
$get_extension = substr($file_url, strpos($file_url, "&type=") + 6, 3);
$url_file_name = basename($file_url) .'.'. $get_extension;
}
elseif((strpos($file_url, 'format=rss') !== false) || (strpos($file_url, '/rss') !== false)){
if(isset($get_file_headers['Content-Type'])){
$url_extension = substr($get_file_headers['Content-Type'], strpos($get_file_headers['Content-Type'], 'text/') + strlen('text/'), 3);
$url_file_name = basename($file_url) . '.' . $url_extension;
}
else{
$url_file_name = basename($file_url) . '.xml';
}
}else{
if(isset($get_file_headers['Content-Type'])){
if(is_array($get_file_headers['Content-Type']) && isset($get_file_headers['Content-Type'][0])){
if( strpos($get_file_headers['Content-Type'][0], 'text/') !== false) {
$url_extension = substr($get_file_headers['Content-Type'][0], strpos($get_file_headers['Content-Type'][0], 'text/') + strlen('text/'), 3);
}
}
else{
if( strpos($get_file_headers['Content-Type'], 'text/') !== false) {
$url_extension = substr($get_file_headers['Content-Type'], strpos($get_file_headers['Content-Type'], 'text/') + strlen('text/'), 3);
}
else{
$url_extension = substr($get_file_headers['Content-Type'], strpos($get_file_headers['Content-Type'], 'application/') + strlen('application/'), 3);
}
}
$url_file_name = basename($file_url) . '.' . $url_extension;
}
else{
$url_file_name = basename($file_url);
}
}
}
}
}
$validate_instance = ValidateFile::getInstance();
$zip_instance = ZipHandler::getInstance();
$validate_format = $validate_instance->validate_file_format($url_file_name);
if($validate_format == 'yes'){
if (!extension_loaded('curl')) {
$response['success'] = false;
$response['message'] = 'The required PHP extension cURL is not installed. Please install it.';
echo wp_json_encode($response);
wp_die();
}
$upload_dir = UrlUpload::$smack_csv_instance->create_upload_dir();
if($upload_dir){
$url_file_name = str_replace('%20', ' ', $url_file_name);
$event_key = UrlUpload::$smack_csv_instance->convert_string2hash_key($url_file_name);
$file_extension = pathinfo($url_file_name, PATHINFO_EXTENSION);
if(empty($file_extension)){
$file_extension = 'xml';
}
$upload_dir_path = $upload_dir. $event_key;
if (!is_dir($upload_dir_path)) {
wp_mkdir_p( $upload_dir_path);
}
chmod($upload_dir_path, 0777);
$wpdb->insert( $file_table_name , array( 'file_name' => $url_file_name , 'hash_key' => $event_key , 'status' => 'Downloading','lock' => true ) );
$last_id = $wpdb->get_results("SELECT id FROM $file_table_name ORDER BY id DESC LIMIT 1",ARRAY_A);
$lastid=$last_id[0]['id'];
$curlCh = curl_init();
curl_setopt($curlCh, CURLOPT_URL, $file_url);
curl_setopt($curlCh, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlCh, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curlCh, CURLOPT_FAILONERROR, true);
curl_setopt($curlCh, CURLOPT_MAXREDIRS, 10);
curl_setopt($curlCh, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curlCh, CURLOPT_CUSTOMREQUEST,'GET');
curl_setopt($curlCh, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlCh, CURLOPT_SSL_VERIFYHOST, FALSE);
$curlData = curl_exec ($curlCh);
if(curl_error($curlCh)){
$response['success'] = false;
$response['message'] = curl_error($curlCh);
echo wp_json_encode($response);
$wpdb->get_results("UPDATE $file_table_name SET status='Download_Failed' WHERE id = '$lastid'");
}else{
$path = $upload_dir. $event_key .'/'.$event_key;
if ($file_extension == 'xlsx' || $file_extension == 'xls') {
$this->convertXlsxToCsv($curlData ,$upload_dir_path, $event_key);
chmod($path, 0777);
$file_extension = 'csv';
}else{
$file = fopen($path , "w+");
fputs($file, $curlData);
chmod($path, 0777);
fclose($file);
}
$real_path = $path;
if (file_exists($real_path) && ($file_extension === 'csv' || $file_extension === 'tsv')) {
if (class_exists('\Smackcoders\FCSV\DesktopUpload')) {
$delimiter = \Smackcoders\FCSV\DesktopUpload::detect_csv_delimiter($real_path);
update_option("smack_csv_delimiter_{$event_key}", $delimiter);
}
}
$validate_file = $validate_instance->file_validation($path , $file_extension );
$file_size = filesize($path);
$filesize = $validate_instance->formatSizeUnits($file_size);
if($validate_file == "yes"){
$wpdb->get_results("UPDATE $file_table_name SET status='Downloaded',`lock`=false WHERE id = '$lastid'");
$get_result = $validate_instance->import_record_function($event_key , $url_file_name);
$template_name = substr($url_file_name, 0, strpos($url_file_name, "."));
$response['success'] = true;
$response['filename'] = $url_file_name;
$response['hashkey'] = $event_key;
$response['posttype'] = $get_result['Post Type'];
$response['taxonomy'] = $get_result['Taxonomy'];
$response['selectedtype'] = $get_result['selected type'];
$response['file_type'] = $file_extension;
$response['file_size'] = $filesize;
$response['templatename'] = $template_name;
$response['message'] = 'success';
echo wp_json_encode($response);
}
else{
$response['success'] = false;
$response['message'] = $validate_file;
echo wp_json_encode($response);
unlink($path);
$wpdb->get_results("UPDATE $file_table_name SET status='Download Failed',`lock`=true WHERE id = '$lastid'");
}
}
curl_close ($curlCh);
}else{
$response['success'] = false;
$response['message'] = "Please create Upload folder with writable permission";
echo wp_json_encode($response);
}
}else{
$response['success'] = false;
$response['message'] = $validate_format;
echo wp_json_encode($response);
}
wp_die();
}
public static function get_original_url($url)
{
$url = str_replace(' ', '%20', $url);
return $url;
}
public function get_filename_from_headers($file_full_name) {
// Extract the filename part
preg_match('/filename\*?=([^;]+)/', $file_full_name, $matches);
if (!empty($matches[1])) {
$filename = trim($matches[1], " \"");
// Handle cases with encoded filenames (filename*=UTF-8'')
if (strpos($filename, "UTF-8''") === 0) {
$filename = urldecode(substr($filename, 7)); // Decode URL-encoded filename
}
} else {
return '';
}
return $filename;
}
public function unshorten_bitly_url($url) {
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYHOST => FALSE, // suppress certain SSL errors
CURLOPT_SSL_VERIFYPEER => FALSE,
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($ch);
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
return $url;
}
}

View File

@@ -0,0 +1,312 @@
<?php
/**
* WP Ultimate CSV Importer plugin file.
*
* Copyright (C) 2010-2020, Smackcoders Inc - info@smackcoders.com
*/
namespace Smackcoders\FCSV;
if ( ! defined( 'ABSPATH' ) )
exit; // Exit if accessed directly
class ValidateFile {
private static $validate_instance = null;
public static function getInstance() {
if (ValidateFile::$validate_instance == null) {
ValidateFile::$validate_instance = new ValidateFile;
return ValidateFile::$validate_instance;
}
return ValidateFile::$validate_instance;
}
/**
* Checks whether given file is in supported format.
* @param string $filename - file name
* @return string
*/
public function validate_file_format($filename){
$supported_file = array('csv' , 'xml', 'zip' , 'txt' , 'xlsx' , 'xls', 'tsv');
$extension = explode(".", $filename);
$file_extension = end($extension);
if(empty($file_extension)){
$file_extension = 'xml';
}
if(!in_array($file_extension , $supported_file)){
$message = "Unsupported File Format";
}else{
$message = "yes";
}
return $message;
}
/**
* Validates the uploaded file for certain requirements.
* @param string $filepath - path to file
* @param string $file_extension - extension of file
* @return string
*/
public function file_validation($file_path , $file_extension){
$get_file = file_get_contents($file_path);
$get_memory_limit = ini_get('memory_limit');
if (preg_match('/^(\d+)(.)$/', $get_memory_limit, $matches)) {
if ($matches[2] == 'M') {
$get_memory_limit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
} else if ($matches[2] == 'K') {
$get_memory_limit = $matches[1] * 1024; // nnnK -> nnn KB
}
}
$uploaded_filesize = filesize($file_path);
$size_limit = 5242880;
$memory_limit = 419430400;
if(($uploaded_filesize > $size_limit) && ($get_memory_limit < $memory_limit)){
$message = "Please increase your php memory limit";
return $message;
}
if(function_exists('mb_check_encoding')) {
$utf_format = mb_check_encoding($get_file, 'UTF-8');
if(!$utf_format){
$message = "Your file is not in UTF-8 format";
return $message;
}
}
$get_post_max_size = $this->get_config_bytes(ini_get('post_max_size'));
if($uploaded_filesize > $get_post_max_size){
$message = "File size exceeded post maximum size";
return $message;
}
$get_php_size = $this->get_config_bytes(ini_get('upload_max_filesize'));
if($uploaded_filesize > $get_php_size){
$message = "File size exceeded PHP maximum size";
return $message;
}
else{
if($file_extension == 'csv' || $file_extension == 'txt'){
$delimiter = $this->getFileDelimiter($file_path, 5);
$validate_csv = $this->validateCSV($file_path , $delimiter);
$message = "yes";
}else{
$message = "yes";
}
return $message;
}
}
/**
* Converts filesize to bytes.
* @param string $val - path to file
* @return int
*/
public function get_config_bytes($val) {
$val = trim($val);
$last = strtolower($val[strlen($val) - 1]);
$intval = intval(trim($val));
switch ($last) {
case 'g':
$intval *= 1024;
case 'm':
$intval *= 1024;
case 'k':
$intval *= 1024;
}
return $intval;
}
/**
* Validates csv and txt files.
* @param string $file_path
* @param string $delimiter
* @return string
*/
public function validateCSV($file_path='', $delimiter=','){
if(!file_exists($file_path) || !is_readable($file_path))
return FALSE;
$header = array();
$data = array();
if($delimiter == '\t'){
$delimiter = '~';
if (($f_handle = fopen($file_path, 'r')) !== FALSE){
$temp=$file_path.'temp';
$temphandle =fopen($temp, 'w+');
chmod($temp, 0777);
while (($line = fgets($f_handle)) !== false) {
$line= str_replace("\t", '~', $line);
fwrite($temphandle, $line);
}
fclose($temphandle);
if (($handles = fopen($temp, 'r')) !== FALSE){
while (($row = fgetcsv($handles, 0, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else{
$data[] = array_combine($header, $row);
break;
}
}
$handle = fopen($file_path, 'r');
if(array_key_exists(null,$data[0])){
$valid = 'No';
}
else{
$valid = 'Yes';
}
if(empty($data[0])){
$valid = 'No';
}
}
// fclose($handle);
return $valid;
}
fclose($temphandle);
}
else{
if (($handle = fopen($file_path, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 0, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else{
$data[] = array_combine($header, $row);
break;
}
}
$handle = fopen($file_path, 'r');
if(array_key_exists(null,$data[0])){
$valid = 'No';
}else{
$valid = 'Yes';
}
if(empty($data[0])){
$valid = 'No';
}
fclose($handle);
}
return $valid;
}
}
/**
* Possible delimiters.
* @param string $file
* @param int $checkLines
* @return string
*/
public function getFileDelimiter($file, $checkLines = 2){
$file = new \SplFileObject($file);
$delimiters = array(
',',
'\t',
';',
'|',
':',
);
$results = array();
$i = 0;
while($file->valid() && $i < 1){
$line = $file->fgets();
foreach ($delimiters as $delimiter){
$regExp = '/['.$delimiter.']/';
$fields = preg_split($regExp, $line);
if(count($fields) > 1){
if(!empty($results[$delimiter])){
$results[$delimiter]++;
} else {
$results[$delimiter] = 1;
}
}
}
$i++;
}
if(!empty($results)){
$results = array_keys($results, max($results));
return $results[0];
}
else{
return true;
}
}
/**
* Converts bytes to KB, MB, GB.
* @param int $bytes
* @return string
*/
public function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824)
{
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
}
elseif ($bytes >= 1048576)
{
$bytes = number_format($bytes / 1048576, 2) . ' MB';
}
elseif ($bytes >= 1024)
{
$bytes = number_format($bytes / 1024, 2) . ' KB';
}
elseif ($bytes > 1)
{
$bytes = $bytes . ' bytes';
}
elseif ($bytes == 1)
{
$bytes = $bytes . ' byte';
}
else
{
$bytes = '0 bytes';
}
return $bytes;
}
/**
* Gets post types, selected post type.
* @param string $hashkey
* @param string $filename
* @return string
*/
public function import_record_function($hashkey , $filename){
$result = array();
$extension_instance = new ExtensionHandler;
$get_post = $extension_instance->get_import_post_types();
$get_taxo = get_taxonomies();
$import_record_post = array_keys($get_post);
$import_record_taxonomy = array_keys($get_taxo);
$get_type = $extension_instance->set_post_types($hashkey , $filename);
$result['Post Type'] = $import_record_post;
$result['Taxonomy'] = $import_record_taxonomy;
$result['selected type'] = $get_type;
return $result;
}
}

View File

@@ -0,0 +1,226 @@
<?php
/**
* WP Ultimate CSV Importer plugin file.
*
* Copyright (C) 2010-2020, Smackcoders Inc - info@smackcoders.com
*/
namespace Smackcoders\FCSV;
if ( ! defined( 'ABSPATH' ) )
exit; // Exit if accessed directly
class XmlHandler {
private static $xml_instance = null;
private $result_xml = [];
public function __construct(){
add_action('wp_ajax_get_parse_xml',array($this,'parse_xml'));
}
public static function getInstance() {
if (XmlHandler::$xml_instance == null) {
XmlHandler::$xml_instance = new XmlHandler;
return XmlHandler::$xml_instance;
}
return XmlHandler::$xml_instance;
}
public function parse_xml(){
check_ajax_referer('smack-ultimate-csv-importer', 'securekey');
$row_count = isset($_POST['row']) ? intval(sanitize_text_field($_POST['row'])) : 0;
$hash_key = sanitize_key($_POST['HashKey']);
$smack_csv_instance = SmackCSV::getInstance();
$upload_dir = $smack_csv_instance->create_upload_dir();
$upload_dir_path = $upload_dir. $hash_key;
if (!is_dir($upload_dir_path)) {
wp_mkdir_p( $upload_dir_path);
}
chmod($upload_dir_path, 0777);
$path = $upload_dir . $hash_key . '/' . $hash_key;
$response = [];
$xml = simplexml_load_file($path);
foreach($xml->children() as $child){
$child_name = $child->getName();
}
$total_xml_count = $this->get_xml_count($path , $child_name);
if($total_xml_count == 0 || $child_name == 'channel' ){
$sub_child = $this->get_child($child,$path);
$child_name = $sub_child['child_name'];
$total_xml_count = $sub_child['total_count'];
}
$doc = new \DOMDocument();
$doc->load($path);
$row = $row_count - 1;
$node = $doc->getElementsByTagName($child_name)->item($row);
$this->tableNodes($node);
$response['xml_array'] = $this->result_xml;
$response['success'] = true;
$response['total_rows'] = $total_xml_count;
echo wp_json_encode($response);
wp_die();
}
public function parse_xmls($hash_key,$line_number = null,$mode = null,$path = null){
$smack_csv_instance = SmackCSV::getInstance();
if($mode != 'CLI') {
$upload_dir = $smack_csv_instance->create_upload_dir();
$upload_dir_path = $upload_dir. $hash_key;
if (!is_dir($upload_dir_path)) {
wp_mkdir_p( $upload_dir_path);
}
chmod($upload_dir_path, 0777);
$path = $upload_dir . $hash_key . '/' . $hash_key;
}
$response = [];
$xml = simplexml_load_file($path);
foreach($xml->children() as $child){
$child_name = $child->getName();
}
$total_xml_count = $this->get_xml_count($path , $child_name);
if($total_xml_count == 0 || $child_name == 'channel'){
$sub_child = $this->get_child($child,$path);
$child_name = $sub_child['child_name'];
$total_xml_count = $sub_child['total_count'];
}
$total_xml_count = $this->get_xml_count($path , $child_name);
$doc = new \DOMDocument();
$doc->load($path);
if ($line_number !== null) {
$node = $doc->getElementsByTagName($child_name)->item((int)$line_number);
} else {
$node = $doc->getElementsByTagName($child_name)->item(0);
}
$this->tableNodes($node);
$response['xml_array'] = $this->result_xml;
$response['success'] = true;
$response['total_rows'] = $total_xml_count;
return $response;
}
public function get_child($child,$path){
foreach($child->children() as $sub_child){
$sub_child_name = $sub_child->getName();
}
$total_xml_count = $this->get_xml_count($path , $sub_child_name);
if($total_xml_count == 0 || $sub_child_name == 'channel'){
$this->get_child($sub_child,$path);
}
else{
$result['child_name'] = $sub_child_name;
$result['total_count'] = $total_xml_count;
return $result;
}
}
/**
* Parse xml file.
*/
public function parsing_xmls(){
$hash_key = sanitize_key($_POST['HashKey']);
$treetype = sanitize_text_field($_POST['treetype']);
$smack_csv_instance = SmackCSV::getInstance();
$upload_dir = $smack_csv_instance->create_upload_dir();
$upload_dir_path = $upload_dir. $hash_key;
if (!is_dir($upload_dir_path)) {
wp_mkdir_p( $upload_dir_path);
}
chmod($upload_dir_path, 0777);
$file = $upload_dir . $hash_key . '/' . $hash_key;
$id = "item";
$namespace = explode(":", $id);
if(isset($namespace[1]))
$n = $namespace[1];
else
$n = $id;
$doc = new \DOMDocument();
$doc->load($file);
$nodes=$doc->getElementsByTagName($n);
if($nodes->length < intval($_POST['pag']))
$response['message'] = "Maximum Limit Exceed!";
if(isset($_POST['pag']))
$i = intval($_POST['pag']) - 1;
else
$i = 0;
if($i < 0)
$response['message'] = "Node not available!";
while (is_object($finance = $doc->getElementsByTagName($n)->item($i))) {
if($treetype == 'table'){
$result = $this->tableNode($finance);
}
else{
$result = $this->treeNode($finance);
}
$i++;
}
}
public function tableNodes($node)
{
if($node->nodeName != '#text'){
if($node->childNodes->length != 1 && $node->nodeName != '#cdata-section'){
}
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $child){
$this->tableNodes($child);
}
if($node->hasAttributes()){
for ($i = 0; $i <= $node->attributes->length; ++$i) {
$attr_nodes = $node->attributes->item($i);
if($attr_nodes->nodeName && $attr_nodes->nodeValue)
$attrs[$node->nodeName][$attr_nodes->nodeName] = $attr_nodes->nodeValue;
}
}
if($node->nodeValue || $node->nodeValue == 0){
if($node->childNodes->length == 1){
$xml_array = array();
$xml_array['name'] = $node->nodeName;
$xml_array['node_path'] = $node->getNodePath();
$xml_array['value'] = $node->nodeValue;
array_push($this->result_xml,$xml_array);
}
}
}
}
}
/**
* Get xml rows count.
* @param string $eventFile - path to file
* @return int
*/
public function get_xml_count($eventFile , $child_name){
$doc = new \DOMDocument();
$doc->load($eventFile);
$nodes=$doc->getElementsByTagName($child_name);
$total_row_count = $nodes->length;
return $total_row_count;
}
}

View File

@@ -0,0 +1,179 @@
<?php
/**
* WP Ultimate CSV Importer plugin file.
*
* Copyright (C) 2010-2020, Smackcoders Inc - info@smackcoders.com
*/
namespace Smackcoders\FCSV;
if ( ! defined( 'ABSPATH' ) )
exit; // Exit if accessed directly
class ZipHandler {
private static $instance = null;
private static $smack_csv_instance = null;
public static function getInstance() {
if (ZipHandler::$instance == null) {
ZipHandler::$instance = new ZipHandler;
ZipHandler::$smack_csv_instance = SmackCSV::getInstance();
return ZipHandler::$instance;
}
return ZipHandler::$instance;
}
/**
* Extracts zip file.
* @param string $path
* @param string $extract_path
* @return string
*/
public function zip_upload($path , $extract_path , $event_key =''){
if (class_exists('ZipArchive')) {
$zip = new \ZipArchive;
$res = $zip->open($path);
if ($res === TRUE) {
$response = $this->wp_csv_importer_generate_content($zip, $extract_path,$event_key);
if($response == "UnSupported File Format"){
//rmdir($extract_path);
unlink($path);
}
} else {
$response = 'Error Occured while extracting zip file.';
}
}else{
$response = 'ZipArchive class not exists';
}
return $response;
}
/**
* Uploads zip file
* @param string $zip
* @param string $dir
* @return string
*/
public function wp_csv_importer_generate_content($zip, $dir,$event_key=''){
$get_upload_dir = wp_upload_dir();
$supported_formats = array('csv', 'xml', 'txt', 'json');
$check_for_extracted_files = false;
for($i = 0; $i < $zip->numFiles; $i++)
{
$filterfiles = $zip->getNameIndex($i);
$file_extension = pathinfo($filterfiles, PATHINFO_EXTENSION);
if (in_array($file_extension, $supported_formats)){
$zip->extractTo($dir,$filterfiles);
chmod($dir , 0777);
$check_for_extracted_files = true;
}
if (!empty($event_key)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') {
$old_file_path = $dir . '/' . $file; // Full path of the old file
if (is_file($old_file_path)) { // Ensure it's a file
$file_info = wp_check_filetype($old_file_path); // Check file type
$extension = pathinfo($old_file_path, PATHINFO_EXTENSION); // Get file extension
// Check file type based on extension
$allowed_extensions = ['csv', 'xml', 'xlsx', 'xls', 'tsv'];
if (in_array(strtolower($extension), $allowed_extensions)) {
$random_key = $event_key; // Generate a unique random key
$new_file_name = $random_key; // Save file without extension
$new_file_path = $dir . '/' . $new_file_name; // Update path
// Rename the file securely
if (rename($old_file_path, $new_file_path)) {
// echo "File renamed successfully: $old_file_path to $new_file_path\n";
} else {
// echo "Failed to rename: $old_file_path\n";
}
}
}
}
}
}
}
if($check_for_extracted_files){
$filesAndFoldersPath = array();
$zipExtractFolder = $dir;
$get_upload_dirpath = $get_upload_dir['basedir'];
$get_upload_dirurl = $get_upload_dir['baseurl'];
$filesList = $this->wp_csv_importer_fetch_all_files($zipExtractFolder);
$content = [];
foreach($filesList as $singleFile){
$get_file_name = explode('/',$singleFile);
$c = count($get_file_name);
$temp_file_name = $get_file_name[$c - 1];
$file_extension = pathinfo($temp_file_name, PATHINFO_EXTENSION);
if(empty($file_extension)){
$file_extension = 'xml';
}
if($file_extension == 'xlsx'){
$file_extension = 'csv';
}
$getFileRealPath = explode($get_upload_dirpath,$singleFile);
$getFileRealPath = $get_upload_dirurl.$getFileRealPath[1];
$file_names = array("name"=>'' , "path"=>'');
$file_names['name'] .= $temp_file_name;
$file_names['path'] .= $getFileRealPath;
array_push($content , $file_names);
}
}
else{
$content = "UnSupported File Format";
}
$zip->close();
return $content;
}
/**
* Fetches all files from zip.
* @param string $dir
* @return string
*/
public function wp_csv_importer_fetch_all_files($dir){
$root = scandir($dir);
foreach($root as $value)
{
if($value === '.' || $value === '..')
continue;
if(is_file("$dir/$value")) {
$files[] = "$dir/$value";continue;
}
foreach($this->wp_csv_importer_fetch_all_files("$dir/$value") as $value)
{
$files[] = $value;
}
}
return $files;
}
}