Mini Shell

Direktori : /home/runcloud/webapps/wpdefault/import/
Upload File :
Current File : /home/runcloud/webapps/wpdefault/import/shopify-json.php

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if(file_exists("wp-load.php"))require( 'wp-load.php' );
else require( '../wp-load.php' );
define( 'SITE', get_site_url() );
define( 'DIR', "txt/" );
define( 'FILE', basename($_SERVER['SCRIPT_NAME']) );
if(!empty($_GET['file']))$file = $_GET['file'];
else $file = "products.txt";
/*
    Update Logs
    Verstion 1.1 - Date 22/11/2017
    #1 Add Remove Meta and Remove All Extra Meta
    #2 Add site delightee.com
    #3 Giảm bốt số rows trong query import
    #4 Sửa mốt số lỗi nhõ
 */
$realFile = getRealName($file);
$countFile = "c.".$realFile;
$successFile = "s.".$realFile;
$failFile = "f.".$realFile;

/*
if ( ! is_super_admin() ) {
    $url = home_url('wp-login.php?redirect_to=') . rawurlencode(SITE . $_SERVER['SCRIPT_NAME']);
    wp_redirect($url);
}
*/

if(!empty($_POST['url']) && $_POST['is'] == "oneLink"){
    $link = $_POST['url'];
    $domain = parse_url($link, PHP_URL_HOST);
    $msg = "";
    if(!empty($_POST['current'])){
        $f = fopen(DIR.$countFile, 'w');
        fwrite($f, $_POST['current']);
        fclose($f);
    }
    $json = detectDomain($link);




        //$json = reformat_input($json);

        $querystr = "
            SELECT DISTINCT meta_value
            FROM wp_postmeta
            WHERE meta_key = 'source' AND meta_value = '".$link."'
            ORDER BY meta_value ASC LIMIT 1
        ";

	    $post_source = $wpdb->get_results( $querystr, OBJECT );
		//check if exit
	    if (empty($post_source[0]->meta_value)){
	        $product_id = auto_product($json);
	    } else {
		    //$product_id = 0;
		    //exit('exits');
		    //$msg .= status_message('Product added. product ID: ' . $product_id);
	    }



        $msg .= status_message('Product added. product ID: ' . $product_id);
        /*
                auto_product_meta($product_id, $json);
                // add_post_meta($product_id, 'variations', $json["variations"]);
                foreach ($json["variations"] as $value) :
                    $value['product_name'] = $json['name'];
                    $value['option_name'] = $value['name'];
                    foreach ($value['attributes'] as $key2 => $value2) :
                        $k = strtolower($value2['name']);
                        $value[$k] = $value2['option'];
                    endforeach;
                    $var_id = auto_variations($product_id, $value);
                    $msg .= status_message('Product variation added. ID: '. $var_id . ' for product ID: ' . $product_id);
                    $next = auto_variations_meta($product_id,$var_id, $value);
                    if($next == false)break;
                endforeach;
        */
        ajax_status($_POST['url'], 1);

}
if(!empty($_POST['submit']) && $_POST['is'] == "upload"){
    $msg = "";
    $target_file = DIR . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    if (file_exists($target_file)) {
        $msg .= status_message("Sorry, file already exists.");
        $uploadOk = 0;
    }
    if($imageFileType != "txt" ) {
        $msg .= status_message("Sorry, only Txt files are allowed.");
        $uploadOk = 0;
    }
    if ($uploadOk == 0) {
        $msg .= status_message("Sorry, your file was not uploaded.");
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            $msg .= status_message("The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.");
        } else {
            $msg .= status_message("Sorry, there was an error uploading your file.");
        }
    }
}
if(!empty($_POST['submit']) && $_POST['is'] == "reset"){
    $wpdb->query("DELETE FROM $wpdb->posts WHERE `ID` > '395'; ");
    $wpdb->query("DELETE FROM $wpdb->postmeta WHERE `post_id` > '395'; ");
    $wpdb->query("DELETE FROM $wpdb->term_relationships WHERE `object_id` > '55'; ");
    $msg = status_message("Reset Done!");
}
if(!empty($_POST['submit']) && $_POST['is'] == "remove"){
    $wpdb->query("DELETE FROM $wpdb->postmeta WHERE `meta_key` IN ('_wc_average_rating','_wc_review_count','_wc_rating_count'); ");
    $msg = status_message("Remove Done!");
}
if(!empty($_POST['submit']) && $_POST['is'] == "removeAll"){
    $products = $wpdb->get_results( "SELECT ID FROM $wpdb->posts WHERE `post_type` = 'product'", ARRAY_A );
    foreach ($products as $key => $value) {
        $wpdb->query("DELETE FROM $wpdb->postmeta WHERE `post_id` = '".$value['ID']."' AND `meta_key` IN ('_regular_price','_sale_price','_sale_price_dates_from','_sale_price_dates_to','total_sales','_tax_status','_tax_class','_manage_stock','_backorders','_sold_individually','_weight','_length','_width','_height','_upsell_ids','_crosssell_ids','_purchase_note','_virtual','_downloadable','_product_image_gallery','_download_limit','_download_expiry','_stock','_stock_status','_wc_average_rating','_wc_rating_count','_wc_review_count','_downloadable_files','_product_version');");
        $subs = $wpdb->get_results( "SELECT ID FROM $wpdb->posts WHERE `post_parent` = '".$value['ID']."'", ARRAY_A );
        foreach ($subs as $key2 => $value2) {
            $wpdb->query("DELETE FROM $wpdb->postmeta WHERE `post_id` = '".$value2['ID']."' AND `meta_key` IN ('_wc_average_rating','_wc_review_count','_wc_rating_count','_product_version','_sale_price','_sale_price_dates_from','_sale_price_dates_to','total_sales','_tax_status','_tax_class','_manage_stock','_backorders','_sold_individually','_weight','_length','_width','_height','_upsell_ids','_crosssell_ids','_purchase_note','_default_attributes','_virtual','_downloadable','_product_image_gallery','_download_limit','_download_expiry','_stock','_stock_status','_wc_average_rating','_wc_rating_count','_wc_review_count','_downloadable_files');");
        }
    }
    $msg = status_message("Remove Done!");
}

if(!empty($_POST['submit']) && $_POST['is'] == "xmlToTxt" && !empty($_POST['url'])){
    $url = $_POST['url'];
    $domain = parse_url($url, PHP_URL_HOST);
    $fileName = basename($url);
    if(strpos($fileName, '?') !== false){
        $fileNames = explode('?', $fileName);
        $fileName = str_replace(".xml", "", $fileNames[0]);
    }
    $txtName = $domain.".".$fileName.'.txt';
    $data = getPage($url);
    $datas = explode("<loc>", $data);
    $log = "";
    foreach ($datas as $key => $value) {
        if(strpos($value, "products") !== false){
            $locs = explode("</loc>", $value);
            $log .= trim($locs[0])."\n";
        }
    }
    if (!file_exists(DIR.$txtName)) {
        writeline(DIR.$txtName,trim($log));
    }
    $msg = status_message("Convert Complete!");
}
if(!empty($_POST['submit']) && $_POST['is'] == "fixDefault"){
    $msg = "";
    $products = $wpdb->get_results( "SELECT ID FROM $wpdb->posts WHERE `post_type` = 'product'", ARRAY_A );
    $default = array();
    foreach ($products as $key => $value) {
        $updateID = $value["ID"];
        $nextID = $value["ID"] + 1;
        $oneRow = $wpdb->get_results( "SELECT * FROM $wpdb->postmeta WHERE `post_id` = '$nextID' AND `meta_key` LIKE 'attribute_%'", ARRAY_A );
        foreach ($oneRow as $key2 => $value2) {
            if(!empty($value2['meta_value'])){
                $meta_key = str_replace("attribute_", "", $value2['meta_key']);
                $default[$meta_key] = $value2['meta_value'];
            }
        }
        $finalDefault = serialize($default);
        $wpdb->update(
            $wpdb->postmeta,
            array( 'meta_value' => $finalDefault ),
            array( 'post_id' => $updateID, 'meta_key' => '_default_attributes' )
        );
        $msg .= status_message("Product $updateID updated!");
    }
    $msg .= status_message("Job Done!");
}
?><!DOCTYPE html>
<html lang="en" class="no-js">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link href='//fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <style type="text/css">
        .form-style-8{font-family: 'Open Sans Condensed', arial, sans; padding: 30px; background: #FFFFFF; margin: 10px auto; box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.22); -moz-box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.22); -webkit-box-shadow:  0px 0px 15px rgba(0, 0, 0, 0.22); }
        .form-style-8 h2 {background: #4D4D4D; text-transform: uppercase; font-family: 'Open Sans Condensed', sans-serif; color: #fff; font-size: 20px; font-weight: bold; padding: 20px; margin: -30px -30px 30px -30px; letter-spacing: 2px; }
        .form-style-8 input[type="datetime"], .form-style-8 input[type="email"], .form-style-8 input[type="number"], .form-style-8 input[type="search"], .form-style-8 input[type="time"], .form-style-8 input[type="url"], .form-style-8 input[type="password"], .form-style-8 select {box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; outline: none; display: block; width: 100%; padding: 7px; border: none; border-bottom: 1px solid #ddd; background: transparent; margin-bottom: 10px; font: 16px Arial, Helvetica, sans-serif; height: 45px; }
        .form-style-8 textarea {resize: none; overflow-y: scroll; display: block; width: 100%; margin-bottom: 10px; height: 150px; }
        #fixDefault textarea, #success textarea, #fail textarea {resize: none; overflow-y: scroll; display: block; width: 100%; height: 500px; font-size: 90%; padding: 5px; border: none; }
        .form-style-8 input[type="button"],.form-style-8 button, .form-style-8 input[type="submit"]{-moz-box-shadow: inset 0px 1px 0px 0px #45D6D6; -webkit-box-shadow: inset 0px 1px 0px 0px #45D6D6; box-shadow: inset 0px 1px 0px 0px #45D6D6; background-color: #2CBBBB; border: 1px solid #27A0A0; display: inline-block; cursor: pointer; color: #FFFFFF; font-family: 'Open Sans Condensed', sans-serif; font-size: 14px; padding: 8px 18px; text-decoration: none; text-transform: uppercase; }
        .form-style-8 input[type="button"]:hover, .form-style-8 input[type="submit"]:hover {background:linear-gradient(to bottom, #34CACA 5%, #30C9C9 100%); background-color:#34CACA; }
        div#bar {box-sizing: border-box; height: 50px; box-shadow: 0px 1px 4px green; margin: 20px 0; position: relative; }
        div#process {position: absolute; top: 0; left: 0; height: 50px; width: 100%; background-color: rgba(79, 175, 76, 0.7); }
        div#percent {position: absolute; top: 4px; left: 10px; color: #fff; z-index: 100; font-weight: bold; font-size: 26px; background-color: rgba(0,0,0,0.2); border-radius: 10px; padding: 2px 10px; }
        button#get {background-color: cornflowerblue; }
        input.info {text-align: right;border: none; padding: 10px; margin: 20px 20px 0 0; box-sizing: border-box; box-shadow: 2px 3px 3px #ccc; color: #fff; font-weight: bold; }
        input#total-success {background-color: lightseagreen; }
        label.total-success::before {content: "Success: ";}
        input#total-fail {background-color: indianred; }
        label.total-fail::before {content: "Fail: ";}
        input#total-current {background-color: coral; }
        label.total-current::before {content: "Current: ";}
        label {left: 10px; position: relative; color: white; font-weight: bold; width: 0px; display: inline-block; }
    </style>
</head>
<body>
<div class="w3-sidebar w3-bar-block w3-light-grey w3-card" style="width:130px">
    <h5 class="w3-bar-item">Menu</h5>
    <button class="w3-bar-item w3-button tablink <?=isDisplayRed("oneLink");?>" onclick="openTab(event, 'oneLink')">One Link</button>
    <button class="w3-bar-item w3-button tablink <?=isDisplayRed("listLink");?>" onclick="openTab(event, 'listLink')">Multi Link</button>
    <button class="w3-bar-item w3-button tablink <?=isDisplayRed("upFile");?>" onclick="openTab(event, 'upFile')">Upload File</button>
    <button class="w3-bar-item w3-button tablink <?=isDisplayRed("fixDefault");?>" onclick="openTab(event, 'fixDefault')">Fix Default</button>
    <button class="w3-bar-item w3-button tablink <?=isDisplayRed("xmlToTxt");?>" onclick="openTab(event, 'xmlToTxt')">Xml2Txt</button>
    <button class="w3-bar-item w3-button tablink" onclick="openTab(event, 'success')">Success</button>
    <button class="w3-bar-item w3-button tablink" onclick="openTab(event, 'fail')">Fail</button>
    <button class="w3-bar-item w3-button tablink <?=isDisplayRed("remove");?>" onclick="openTab(event, 'remove')">RemoveMeta</button>
    <button class="w3-bar-item w3-button tablink <?=isDisplayRed("removeAll");?>" onclick="openTab(event, 'removeAll')">Remove All</button>
    <button class="w3-bar-item w3-button tablink <?=isDisplayRed("reset");?>" onclick="openTab(event, 'reset')">Reset</button>
</div>

<div style="margin-left:130px">

    <div id="oneLink" class="w3-container city" <?=isDisplay('oneLink');?>>
        <div class="form-style-8">
            <h2>Import post from Colorfest to Woo Shop!</h2>
            <form action="" method="POST">
                <input type="hidden" name="is" value="oneLink" />
                <input type="url" name="url" placeholder="Url" />
                <input type="submit" value="Import!" name="submit"/>
            </form>
            <?php echo ($msg != "" && $_POST['is'] == "oneLink")?str_replace("\r\n", "<br />\r\n", $msg):""; ?>
        </div>
    </div>
    <div id="listLink" class="w3-container city" <?=isDisplay('listLink');?>>
        <div class="form-style-8">
            <b>&lt; Soruce &gt;</b>
            <select name="source" id="source">
                <?php
                if ($handle = opendir(DIR)) {
                    while (false !== ($entry = readdir($handle))) {
                        $ext = substr($entry, 0, 2);
                        if ($entry != "." && $entry != ".." && $ext != 'c.' && $ext != 's.' && $ext != 'f.' ) {
                            if($entry == $file)
                                echo "<option value='".$entry."' selected>".$entry."</option>";
                            else
                                echo "<option value='".$entry."'>".$entry."</option>";
                        }
                    }
                    closedir($handle);
                }
                ?>
            </select>
            <b>&lt; Start At &gt;</b>
            <input type="number" name="start" id="start" placeholder="Current running" value="<?php if(file_exists(DIR.$countFile))echo file_get_contents(DIR.$countFile);else echo 0; ?>" />
            <b>&lt; LIST URL &gt;</b>
            <textarea id="listurl" placeholder="List Url"><?php
                $ls = file(DIR.$file);
                foreach ($ls as $k => $l) {
                    echo $l;
                }
                ?>
                    </textarea>
            <b>&lt; RESULT &gt;</b>
            <textarea id="result"></textarea>
            <label for="total-success" class="total-success"></label><input type="text" class="info" id="total-success" value="0" />
            <label for="total-fail" class="total-fail"></label><input type="text" class="info" id="total-fail" value="0" />
            <label for="total-current" class="total-current"></label><input type="text" class="info" id="total-current" value="0" />
            <div id="bar"><div id="percent">0%</div><div id="process"></div></div>
            <button id="get">Get IT!</button>
            <button id="stop">Stop!</button>
        </div>
    </div>

    <div id="upFile" class="w3-container city" <?=isDisplay('upload');?>>
        <div class="form-style-8">
            <h2>Select txt file to upload!</h2>
            <form action="" method="post" enctype="multipart/form-data">
                <input type="hidden" name="is" value="upload" />
                <input type="file" name="fileToUpload" id="fileToUpload">
                <input type="submit" value="Upload!" name="submit">
            </form>
            <?php echo ($msg != "" && $_POST['is'] == "upload")?$msg:""; ?>
        </div>
    </div>

    <div id="fixDefault" class="w3-container city" <?=isDisplay('fixDefault');?>>
        <div class="form-style-8">
            <h2>Fix Default Attributes, Set All Default Using First Variations!</h2>
            <form action="" method="POST">
                <input type="hidden" name="is" value="fixDefault"/>
                <input type="submit" value="FixIt!"  name="submit"/>
            </form>
            <?php echo ($msg != "" && $_POST['is'] == "fixDefault")?"<textarea style='height:400px;margin-top: 10px;'>$msg</textarea>":""; ?>
        </div>
    </div>
    <div id="xmlToTxt" class="w3-container city" <?=isDisplay('xmlToTxt');?>>
        <div class="form-style-8">
            <h2>Convert sitemap XML to TXT!</h2>
            <form action="" method="POST">
                <input type="hidden" name="is" value="xmlToTxt" />
                <input type="url" name="url" placeholder="Url" />
                <input type="submit" value="Convert!" name="submit"/>
            </form>
            <?php echo ($msg != "" && $_POST['is'] == "xmlToTxt")?$msg:""; ?>
        </div>
    </div>

    <div id="success" class="w3-container city" style="display:none">
        <h2>Success URL</h2>
        <textarea><?php if(file_exists(DIR.$successFile))echo file_get_contents(DIR.$successFile); ?></textarea>
    </div>

    <div id="fail" class="w3-container city" style="display:none">
        <h2>Fail URL</h2>
        <textarea><?php if(file_exists(DIR.$failFile))echo file_get_contents(DIR.$failFile); ?></textarea>
    </div>

    <div id="remove" class="w3-container city" <?=isDisplay('remove');?>>
        <div class="form-style-8">
            <h2>Remove Extra Meta In Database (_wc_average_rating, _wc_review_count, _wc_rating_count)!</h2>
            <form action="" method="POST">
                <input type="hidden" name="is" value="remove" />
                <input type="submit" value="Remove!"  name="submit"/>
            </form>
            <?php echo ($msg != "" && $_POST['is'] == "remove")?$msg:""; ?>
        </div>
    </div>

    <div id="removeAll" class="w3-container city" <?=isDisplay('removeAll');?>>
        <div class="form-style-8">
            <h2>Remove All Extra Meta In Database (All Extra)!</h2>
            <form action="" method="POST">
                <input type="hidden" name="is" value="removeAll" />
                <input type="submit" value="RemoveAll!"  name="submit"/>
            </form>
            <?php echo ($msg != "" && $_POST['is'] == "removeAll")?$msg:""; ?>
        </div>
    </div>

    <div id="reset" class="w3-container city" <?=isDisplay('reset');?>>
        <div class="form-style-8">
            <h2>Reset Database Only for Vinh!</h2>
            <form action="" method="POST">
                <input type="hidden" name="is" value="reset" />
                <input type="submit" value="Reset!"  name="submit"/>
            </form>
            <?php echo ($msg != "" && $_POST['is'] == "reset")?$msg:""; ?>
        </div>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    function openTab(evt, tabName) {
        var i, x, tablinks;
        x = document.getElementsByClassName("city");
        for (i = 0; i < x.length; i++) {
            x[i].style.display = "none";
        }
        tablinks = document.getElementsByClassName("tablink");
        for (i = 0; i < x.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(" w3-red", "");
        }
        document.getElementById(tabName).style.display = "block";
        evt.currentTarget.className += " w3-red";
    }
</script>
<script type="text/javascript">
    var jqXHR;
    var isStop = false;
    $(function(){
        $('#source').on('change', function () {
            var url = $(this).val();
            if (url) {
                window.location = "?file="+url;
            }
            return false;
        });
    });
    $("button#stop").click(function(){ isStop = true; jqXHR.abort(); console.log(isStop + " Stop HERE!")});
    $('button#get').on('click', function () {
        var tmplist = $('#listurl').val().trim();
        var list = tmplist.split("\n");
        processTasks(list);
    });
    $('button#reset').on('click', function () {
        $('#listurl').val('');
        $('#result').val('');
        $('#total-success').val('0');
        $('#total-fail').val('0');
        $('#total-current').val('0');
    });
    function processTasks(tasks){
        var percent = 0;
        var index = $("#start").val();
        function nextTask() {
            if (index < tasks.length) {
                jqXHR = $.ajax({
                    url: '<?=FILE;?>?file=<?=$realFile;?>',
                    type: 'POST',
                    data: { url: tasks[index].trim(), is: "oneLink", current: index },
                    dataType: 'json',
                    success: function(result) {
                        ++index;
                        // process ajax results here
                        $("#total-current").val(parseInt($("#total-current").val()) + 1);
                        $("#start").val(parseInt($("#start").val()) + 1);
                        if(result.error == 1){
                            $("#total-success").val(parseInt($("#total-success").val()) + 1);
                        }
                        if(result.error == 2){
                            $("#total-fail").val(parseInt($("#total-fail").val()) + 1);
                        }
                        percent = (index / tasks.length) * 100;
                        $("#result").val(result.data + $("#result").val());
                        document.getElementById('process').style.width = percent + '%';
                        document.getElementById('percent').innerText = percent + '%' + "("+ index + "/" + tasks.length +")";
                        // do next ajax call
                        if(isStop == false)nextTask();
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        ++index;
                        $("#result").val(tasks[index].trim() + "\n" + $("#result").val());
                        if(isStop == false)nextTask();
                    }
                });
            }
        }
        if(isStop == false)nextTask();
    }
</script>
</body>
</html>
<?php
/**
 * function sử lý source
 */
function reformat_input($json){
    $temp_json = $json;
    unset($temp_json['attributes']);
    foreach ($json['attributes'] as $key => $value) {
        $k = strtolower($value['name']);
        $temp_json['attributes'][$k] = $value;
    }
    return $temp_json;
}


function detectDomain($url){
    $domain = parse_url($url, PHP_URL_HOST);


    $proxys = array(
        'xemphim.tv',
        'pl.tclup.com',
        'vignetteshirt.com',
        'amarosie.com'
    );

    $proxy = $proxys[array_rand($proxys)];
    $data = file_get_contents('http://'.$proxy.'/proxy.php?url='.strtok($url, '?').'.json');

	return json_decode($data, true);
    //return gerenalArray($url, $data);

}


function gerenalArray($url, $meta){
    /** Sự lý json */
    //$meta = file_get_contents('http://xemphim.tv/proxy.php?url='.$url);

    $json = json_decode( htmlspecialchars_decode($meta), true );
    if(strpos($meta, "Page temporarily unavailable") !== false){
        ajax_status("Content Empty - IP BLOCKED - " . $url, 2);
        return;
    }
    if(empty($json)){
        //ajax_status("Json Empty - " . $url, 2);
        return;
    }
    $json = $json['product'];

    $product["vendor"] = $json['vendor'];
    $product["name"] = $json['title'];
    $product["tags"] = ''; //$json['tags'];
    $product["image"] = strtok($json['image']['src'], '?');
    $attributes = array();
    foreach ($json['options'] as $key => $value) :
        $attributes[$key]['name'] = $value['name'];
        $attributes[$key]['position'] = $key;
        $attributes[$key]['is_visible'] = true;
        $attributes[$key]['is_variation'] = true;
        $attributes[$key]['value'] = $value;
    endforeach;

    $tmp_opts = array();
    foreach ($json['options'] as $key => $value) :
        foreach ($value['values'] as $key2 => $value2) :
            $tmp_opts[$key][$value2] = 1;
        endforeach;
    endforeach;

    foreach ($tmp_opts as $key => $value) :
        $val = array();
        foreach ($value as $subkey => $subvalue) :
            $val[] = $subkey;
        endforeach;
        $tmpName = strtolower($attributes[$key]['name']);
        $default_attributes[$tmpName] = $val[0];
        $attributes[$key]["value"] = implode(" | ", $val);
    endforeach;

    //$product['default_attributes'] = $default_attributes;
    $product['variations'] = array();
    foreach ($json['variants'] as $key => $var) {
        $image_id = $var['image_id'];
        $image_array_key = array_find_deeps($json['images'], $image_id)[0];
        // echo $image_array_key;
        $product['variations'][$key]['sku'] = $var['sku'];
        $product['variations'][$key]['name'] = $var['title'];
        $product['variations'][$key]['regular_price'] = str_replace("..",".",stringInserts($var['price'], '.', -2));
        $product['variations'][$key]['image'] = strtok($json['images'][$image_array_key]['src'], '?');
        $atts = array();
        for($i = 0; $i < 4; $i++)
        {
            $j = $i + 1;
            if(!empty($var['option'.$j])){
                $atts[$i]['name'] = $attributes[$i]['name'];
                $atts[$i]['option'] = $var['option'.$j];
            }
        }

        $product['variations'][$key]['attributes'] = $atts;

        $attributes_name = array();
        foreach ($json['options'] as $key => $value) :
            $style_value = strtolower($value['name']);
            $attributes_name[$style_value]['name'] = $value['name'];
            $attributes_name[$style_value]['position'] = $key;
            $attributes_name[$style_value]['value'] = implode(" | ", $value['values']);
            $attributes_name[$style_value]['is_visible'] = true;
            $attributes_name[$style_value]['is_variation'] = true;

        endforeach;

        $product['attributes'] = $attributes_name;

    }
    return $product;
}


function array_find_deeps($array, $search, $keys = array())
{
    foreach($array as $key => $value) {
        if (is_array($value)) {
            $sub = array_find_deeps($value, $search, array_merge($keys, array($key)));
            if (count($sub)) {
                return $sub;
            }
        } elseif ($value === $search) {
            return array_merge($keys, array($key));
        }
    }

    return array();
}

function stringInserts($str, $insertstr, $pos)
{
    $str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
    return $str;
}
/**
 * function bộ trợ
 */
function getRealName($file){
    $ext = substr($file, 0, 2);
    if($ext == 'c.' || $ext == 's.' || $ext == 'f.')return substr($file, 2);
    else return $file;
}
function status_message( $message ) {
    return $message . "\r\n";
}
function ajax_status($message, $error = 1){
    global $successFile, $failFile;
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        if($error == 1){
            $m = "Success";
            writeline(DIR.$successFile, $message);
        }else{
            $m = "Fail";
            writeline(DIR.$failFile, $message);
        }
        die(json_encode(array('data' => "[".date("H:i:s")."] - $m - ". $message ."\n", 'error' => $error)));
    }else{
        if(strpos($message, "SKU") !== false || strpos($message, "Empty") !== false)status_error($message);
        return $message . "\r\n";
    }
}
function isDisplay($div){
    if(empty($_POST['is']) && $div == 'listLink')
        echo 'style="display:block"';
    else if(@$_POST['is'] == $div)
        echo 'style="display:block"';
    else
        echo 'style="display:none"';
}
function isDisplayRed($div){
    if(empty($_POST['is']) && $div == 'listLink')
        echo 'w3-red';
    else if($_POST['is'] == $div)
        echo 'w3-red';
    else
        echo '';

}
function writeline($file, $str){
    if(file_exists($file)){
        $f = fopen($file, 'a+');
        fwrite($f, $str."\n");
        fclose($f);
    }else{
        $f = fopen($file, 'w');
        fwrite($f, $str."\n");
        fclose($f);
    }
    return $str;
}
function status_error( $message ) {
    echo "<div style='position: absolute;bottom: 5px; background: lightpink; width: 100%; padding: 5px 145px;'>".$message."</div>";
}
function return_status_message( $message, $error = 0 ) {
    return json_encode(array('error' => $error, 'data' => "[".date("H:i:s")."] - ". $message ."\n"));
}
/*
function giua($a,$b,$c){
    $a = explode($a, $c);
    $b = explode($b, $a[1]);
    return trim($b[0]);
}
*/
function parse_json( $file ) {
    $json = json_decode( file_get_contents( $file ), true );
    if ( is_array( $json ) && !empty( $json ) ) :
        return $json['data'];
    else :
        die( 'An error occurred while parsing ' . $file . ' file.' );
    endif;
}
function khongdau($str){
    $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
    $str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
    $str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
    $str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
    $str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
    $str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
    $str = preg_replace("/(đ)/", 'd', $str);
    $str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
    $str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
    $str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
    $str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
    $str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
    $str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
    $str = preg_replace("/(Đ)/", 'D', $str);
    $str = str_replace("/", "", str_replace("&*#39;","",$str));
    $str = str_replace("  ", " ", $str);
    $str = str_replace(" ", "-", $str);
    return strtolower(trim($str));
}
function getPage($url, $header = 0){
    $curl = curl_init();
    if(strstr($url,"://")){
        curl_setopt ($curl, CURLOPT_REFERER, $url);
    }
    curl_setopt ($curl, CURLOPT_URL, $url);
    curl_setopt ($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt ($curl, CURLOPT_USERAGENT, sprintf("Mozilla/%d.0",rand(4,5)));
    curl_setopt ($curl, CURLOPT_HEADER, (int)$header);
    curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
    $html = curl_exec ($curl);
    curl_close ($curl);
    return $html;
}


/**
 * Auto Post Product
 * @param  array $input (name, description)
 * @return int          product_id
 */
function auto_product($input){
    global $wpdb;
    $data = array(
        'post_author' => 1,
        'post_content' => '',
        'post_content_filtered' => '',
        'post_title' => $input['product']['title'],
        'post_excerpt' => '',
        'post_status' => 'publish',
        'post_type' => 'product',
        'post_category' => array(),
        'comment_status' => 'open',
        'ping_status' => 'closed',
        'post_password' => '',
        'to_ping' =>  '',
        'pinged' => '',
        'post_parent' => 0,
        'menu_order' => 0,
        'guid' => '',
        'import_id' => 0,
        'context' => '',
    );
    $input['product']['body_html'] = '';
    $input['product']['tags'] = '';
    $product_id = wp_insert_post( $data, $wp_error );
//     wp_set_object_terms($product_id , explode(',', $input['product']['tags']), 'product_tag', false);
    wp_set_object_terms($product_id, 'mmolazi', 'product_type'); // mmolazi for shopify json
    add_post_meta($product_id, '_price', $input['product']['variants'][0]['price'], true);
    add_post_meta($product_id, 'source', $_POST['url'], true);
//     add_post_meta($product_id, 'json_shopify', $input, true);
    add_post_meta($product_id, 'json_shopify', json_encode($input, JSON_HEX_QUOT), true);
    /** auto make wp_term_relationships */
    //$wpdb->insert( $wpdb->term_relationships, array('object_id' => $product_id, 'term_taxonomy_id' => 4, 'term_order' => 0) );
    return $product_id;
}
/**
 * Auto Post Meta for product only
 * @param  int      $product_id   product id from auto_product
 * @param  array    $input ((array)default_attributes, (array)variations)
 * @return [type]   none
 */


if ( SHORTINIT )
    return false;