File "t9_eshopimport.php"
Full Path: /www/wwwroot/shphe-en.com/wp-content/plugins/t9_eshopimport/t9_eshopimport.php
File size: 16.2 KB
MIME-type: --
Charset: utf-8
<?php
/**
* Plugin Name: GD-Shop input
* Plugin URI: http://www.goodao.cn/
* Description: GD-Shop input
* Version: 1.1.00
* Author: GD-Shop input
* Author URI: http://www.goodao.cn/
*/
error_reporting(E_ERROR | E_WARNING | E_PARSE);
@set_time_limit(1000);
@set_magic_quotes_runtime(0);
if (!defined('IMPORT_PATH')) define('IMPORT_PATH', plugin_dir_path(__FILE__));
add_action('admin_menu', 't9_init');
function t9_init() {
add_menu_page('数据导入', '数据导入', 7, 't9_eshopimport');
add_submenu_page('t9_eshopimport', '数据导入', '数据导入', 7, 't9_eshopimport', 'data_import');
}
function getFile($dir) {
$dp = opendir($dir);
$fileArr = array();
while (!false == $curFile = readdir($dp)) {
if ($curFile != "." && $curFile != ".." && $curFile != "") {
if (is_dir($curFile)) {
$fileArr = getFile($dir . "/" . $curFile);
} else {
$fileArr[] = $dir . "/" . $curFile;
}
}
}
return $fileArr;
}
function data_import() {
echo "<script language='javascript'>
function redirect(url) {
location.href = url;
}
function addtext(data) {
$('#file').append(data);
document.getElementById('update_tips').scrollTop = document.getElementById('update_tips').scrollHeight;
}
</script>";
global $wpdb;
$iPage_size = 5000;
$dir = IMPORT_PATH . "/upload/";
$displaymain = true;
if ($_REQUEST['action'] == 'import') {
if (empty($_GET['ipage']) || $_GET['ipage'] < 0) {
$ipage = 1;
} else {
$ipage = $_GET['ipage'];
}
$offset = $iPage_size * ($ipage - 1);
$file_name = $_REQUEST['file_name'];
$post_type = $_REQUEST['post_type'] ? $_REQUEST['post_type'] : 'post';
$file_path = $dir . $file_name;
$csv_obj = new SplFileObject($file_path, 'rb');
$csv_obj->seek(filesize($file_path));
$all_rows = $csv_obj->key();
$ipage_count = ceil($all_rows / $iPage_size);
$result_arr = csv_get_lines($file_path, $iPage_size, $offset);
echo '<div class="update-nag">开始导入第' . ($offset) . '行到' . $iPage_size * ($ipage) . '行数据!<br></div><br>';
echo '<div class="sbs" id="update_tips" style="height:430px; overflow:auto;background:#ffffff;padding:20px 15px;"><ul id="file" class="sbul"></ul></div>';
$unique = false;
$val = array();
foreach ($result_arr as $key => $val) {
$category = explode('|', $val[1]);
$catids = array();
foreach ($category as $catname) {
$catid = get_catid($catname);
$catids[] = $catid;
}
//$val[5] = $val[5]?$val[5]:date("Y-m-d H:i:s");
$val[5] = date("Y-m-d H:i:s",time()-3600*24);
$my_post = array(
'post_title' => str_replace('"','',$val[0]),
'post_content' => str_replace('""','"',str_replace('""""','""',$val[2])),
'post_type' => $post_type,
'post_status' => 'publish',
'post_author' => 34,
'post_category' => $catids,
'post_date'=> $val[5]
);
//print_r($my_post);exit;
$post_id = wp_insert_post($my_post);
$pics = $pic = $product_gallery = array();
$filename = '';
$pics = explode("|", $val[3]);
if (is_array($pics)) {
foreach ($pics as $pic) {
$filename = $pic;
$parent_post_id = $post_id;
$filetype = wp_check_filetype(basename($filename) , null);
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($filename) ,
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)) ,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $filename, $parent_post_id);
$product_gallery[] = $attach_id;
}
add_post_meta($post_id, 'product_gallery', $product_gallery);
$tags = explode("|", $val[4]);
wp_set_post_tags($post_id, $tags, true);
}
add_post_meta($post_id, 'ad_xh', $val[6], $unique);
add_post_meta($post_id, '_ad_xh', 'field_5bdbf45af017b', $unique);
add_post_meta($post_id, 'ad_jyms', $val[7], $unique);
add_post_meta($post_id, '_ad_jyms', 'ad_jyms', $unique);
add_post_meta($post_id, 'rfidinfo', $val[7], $unique);
add_post_meta($post_id, '_rfidinfo', 'rfidinfo', $unique);
echo '<script type="text/javascript">addtext("<li><a href=\'#\'>' . $my_post['post_title'] . '</a><span style=\'color:green\'>导入成功...</span></li>");</script>';
}
$inext_page = $ipage + 1;
$url_forward = 'admin.php?page=t9_eshopimport&action=import&post_type=' . $post_type . '&file_name=' . $file_name . '&ipage=' . (int)$inext_page;
if ($ipage < $ipage_count) {
echo '<div class="update-nag">开始导入下页数据!3s后跳转!</div>';
echo '<script language="javascript">setTimeout("redirect(\'' . $url_forward . '\')",3000);</script>';
} else {
unset($csv_obj);
$csv = IMPORT_PATH . "upload/" . $file_name;
$res = @unlink($csv);
if ($res) {
echo '<div class="update-nag">删除文件成功!</div>';
} else {
echo '<div class="update-nag">删除文件失败!</div>';
}
echo '<div class="update-nag">全部数据导入完毕!</div>';
echo '<script language="javascript">alert("全部数据导入完毕!")</script>';
}
} else {
if ($_REQUEST['dosubmit']) {
if (is_dir($dir) == false) {
mkdir($dir, 0777);
}
$post_type = $_REQUEST['post_type'] ? $_REQUEST['post_type'] : 'post';
$file_type = pathinfo($_FILES["csv_file"]["name"], PATHINFO_EXTENSION);
if ($file_type == 'zip') {
$csv_filename = "csv_" . date("Ymdhis", time()) . ".zip";
require_once (IMPORT_PATH . 'inc/zip.class.php');
$zip_path = IMPORT_PATH . "upload/" . $csv_filename;
move_uploaded_file($_FILES["csv_file"]["tmp_name"], $zip_path);
$archive = new Zip();
$archive->extra($zip_path, IMPORT_PATH . "upload/");
unlink($zip_path);
$files = getFile(IMPORT_PATH . "upload");
$dir = substr($files[0], 0, strrpos($files[0], '/', true));
$csv_filename = str_replace($dir . "/", '', $files[0]);
} else {
$csv_filename = "csv_" . date("Ymdhis", time()) . ".csv";
move_uploaded_file($_FILES["csv_file"]["tmp_name"], IMPORT_PATH . "/upload/" . $csv_filename);
}
echo '<div class="update-nag">上传成功!<br /><a class="" href="admin.php?page=t9_eshopimport&action=import&post_type=' . $post_type . '&file_name=' . $csv_filename . '">点击导入</a></div>';
} else {
$post_types = get_post_types();
unset($post_types['attachment']);
unset($post_types[page]);
unset($post_types[revision]);
unset($post_types[nav_menu_item]);
unset($post_types[acf]);
unset($post_types[wpcf7_contact_form]);
unset($post_types[dw_license]);
unset($post_types[help]);
unset($post_types[admin]);
unset($post_types[ad_img]);
unset($post_types[download]);
unset($post_types[pdf]);
unset($post_types[certificate]);
unset($post_types[video]);
unset($post_types[skype]);
foreach ($post_types as $post_type) {
$pt_option.= '<option value="' . $post_type . '">' . $post_type . '</option>';
}
echo '<div class="wrap d_wrap entry">
<table style="padding:20px 0 0 0;">
<tr>
<td style="color:red;">
CSV文件导入 (文件格式请联系谷道科技客服获取, 请勿乱提交CSV文件导入, 数据出错后果自负!)
</td>
</tr>
<tr>
<td style="height:50px;">
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="csv_file" size="50" maxlength="100000" />
<!-- 发布类型:<select id="" name="post_type">' . $pt_option . '</select> -->
<input type="submit" name="dosubmit" value="点击上传" class="button button-primary"/>
</form> </td>
</tr>
</table>
</div>';
}
}
}
function csv_get_lines($csvfile, $lines, $offset = 0) {
if (!$fp = fopen($csvfile, 'r')) {
return false;
}
$i = $j = 0;
while (false !== ($line = fgets($fp))) {
if ($i++ < $offset) {
continue;
}
break;
}
$data = array();
while (($j++ < $lines) && !feof($fp)) {
$data[] = fgetcsv($fp);
}
fclose($fp);
return $data;
}
function get_catid($cat_name) {
$rid = get_cat_ID($cat_name);
if ($rid != 0) {
$catid = $rid;
} else {
$catid = wp_create_category($cat_name);
}
return $catid;
}
//产品分类
add_action( 'wp_ajax_nopriv_get_products_category', 'get_products_category' );
add_action( 'wp_ajax_get_products_category', 'get_products_category' );
function get_products_category() {
global $wpdb;
set_time_limit(60);
$categories = get_hierarchical_categories('category');
echo json_encode(['status'=>200,'data'=>$categories]);exit;
}
//新闻分类
add_action( 'wp_ajax_nopriv_get_news_category', 'get_news_category' );
add_action( 'wp_ajax_get_news_category', 'get_news_category' );
function get_news_category() {
global $wpdb;
set_time_limit(60);
$categories = get_hierarchical_categories('news_catalog');
echo json_encode(['status'=>200,'data'=>$categories]);exit;
}
//产品分类新增
add_action( 'wp_ajax_nopriv_add_products_category', 'add_products_category' );
add_action( 'wp_ajax_add_products_category', 'add_products_category' );
function add_products_category() {
global $wpdb;
set_time_limit(60);
$name = isset($_REQUEST['name'])?trim($_REQUEST['name']):'';
$parent = isset($_REQUEST['parent'])?$_REQUEST['parent']:0;
$category_id = wp_create_category($name,$parent);
if ($category_id && !is_wp_error($category_id)) {
echo json_encode(['status'=>200,'data'=>'','message'=>'sucess']);
} else {
echo json_encode(['status'=>1,'data'=>'','message'=>'failed']);
}exit;
}
//新闻分类新增
add_action( 'wp_ajax_nopriv_add_news_category', 'add_news_category' );
add_action( 'wp_ajax_add_news_category', 'add_news_category' );
function add_news_category() {
global $wpdb;
set_time_limit(60);
$name = isset($_REQUEST['name'])?trim($_REQUEST['name']):'';
$parent = isset($_REQUEST['parent'])?$_REQUEST['parent']:0;
$slug = sanitize_title($name);
$category_id = wp_insert_term($name,'news_catalog',array(
'description' => '',
'slug' => $slug,
'parent' => $parent
));
if ($category_id && !is_wp_error($category_id)) {
echo json_encode(['status'=>200,'data'=>'','message'=>'sucess']);
} else {
echo json_encode(['status'=>1,'data'=>'','message'=>'failed']);
}exit;
}
//新增产品
add_action( 'wp_ajax_nopriv_add_products', 'add_products' );
add_action( 'wp_ajax_add_products', 'add_products' );
function add_products() {
global $wpdb;
set_time_limit(60);
$name = isset($_REQUEST['title'])?trim($_REQUEST['title']):'';
$cate_id = isset($_REQUEST['cate_id'])?$_REQUEST['cate_id']:0;
$content = isset($_REQUEST['content'])?$_REQUEST['content']:'';
$short_description = isset($_REQUEST['short_description'])?$_REQUEST['short_description']:'';
$image = isset($_REQUEST['images'])?$_REQUEST['images']:'';
file_put_contents(__DIR__.'/data.log',json_encode($_REQUEST).PHP_EOL,FILE_APPEND);
//echo json_encode($ar);exit;
$product_gallery = [];
if($image){
$images = explode(',',$image);
foreach ($images as $v){
$product_gallery[] = download_image_from_url($v);
}
}
$cate_ids = explode(',',$cate_id);
$new_post = array(
'post_title' => $name,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 34,
'post_date' => date("Y-m-d H:i:s",time()-8*3600-30),
'post_date_gmt' => date("Y-m-d H:i:s",time()-8*3600-30),
'post_category' => $cate_ids
);
$post_id = wp_insert_post( $new_post );
if ($post_id) {
if($product_gallery){
update_post_meta($post_id, "product_gallery", $product_gallery);
}
if($short_description){
update_post_meta($post_id, "short_description", $short_description);
}
echo json_encode(['status'=>200,'data'=>$post_id,'message'=>'sucess']);
} else {
echo json_encode(['status'=>1,'data'=>'','message'=>'failed']);
}exit;
}
//新增新闻
add_action( 'wp_ajax_nopriv_add_news_api', 'add_news_api' );
add_action( 'wp_ajax_add_news_api', 'add_news_api' );
function add_news_api() {
global $wpdb;
set_time_limit(60);
$name = isset($_REQUEST['title'])?trim($_REQUEST['title']):'';
$cate = isset($_REQUEST['cate'])?$_REQUEST['cate']:'';
$content = isset($_REQUEST['content'])?$_REQUEST['content']:'';
$image = isset($_REQUEST['image'])?$_REQUEST['image']:'';
file_put_contents(__DIR__.'/data.log',json_encode($_REQUEST).PHP_EOL,FILE_APPEND);
$img_id = '';
if($image){
$img_id = download_image_from_url($image);
}
$new_post = array(
'post_title' => $name,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 34,
'post_type' => 'news',
'post_date' => date("Y-m-d H:i:s",time()-8*3600-30),
'post_date_gmt' => date("Y-m-d H:i:s",time()-8*3600-30)
);
$post_id = wp_insert_post( $new_post );
if ($post_id) {
if($cate){
$cats = explode(',',$cate);
$result = wp_set_object_terms($post_id, $cats, 'news_catalog');
}
if($img_id){
update_post_meta($post_id, "news_img", $img_id);
}
echo json_encode(['status'=>200,'data'=>'','message'=>'sucess']);
} else {
echo json_encode(['status'=>1,'data'=>'','message'=>'failed']);
}exit;
}
//从URL下载图片到媒体库
function download_image_from_url($image_url, $title = '') {
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
// 临时下载文件
$tmp_file = download_url($image_url);
if (is_wp_error($tmp_file)) {
return $tmp_file;
}
// 准备文件数组
$file_array = array(
'name' => basename($image_url),
'tmp_name' => $tmp_file
);
// 处理上传
$attachment_id = media_handle_sideload($file_array, 0, $title);
// 清理临时文件
@unlink($tmp_file);
if (is_wp_error($attachment_id)) {
return $attachment_id;
}
return $attachment_id;
}
//获取有层级的分类
function get_hierarchical_categories($taxonomy='category',$parent_id = 0) {
$args = array(
'taxonomy' => $taxonomy,
'parent' => $parent_id,
'hide_empty' => false,
);
$categories = get_categories($args);
if (empty($categories)) {
return array();
}
$result = array();
foreach ($categories as $category) {
$category_data = array(
'id' => $category->term_id,
'name' => $category->name,
'slug' => $category->slug,
//'count' => $category->count,
'parent' => $category->parent,
'children' => get_hierarchical_categories($taxonomy,$category->term_id)
);
if(!in_array($category->slug,['featured','featured-products'])){
$result[] = $category_data;
}
}
return $result;
}
?>