<?php
global $wpdb,$objCloudSlider;
$table_name = $wpdb->prefix."cloudslider";

if(isset($_POST['hidden_action']) && $_POST['hidden_action']=="ImportSlider")
{
	if ($_FILES['import_file']['tmp_name'] == '') {
		echo "<script>alert('Problem occured while uploading sample sliders. Please increase upload_max_filesize in php.ini and try again.')</script>";
	} else if($_FILES['import_file']['name']) {
        $fileName = strtolower($_FILES['import_file']['name']);
        $allowedExts = array('zip');
        $extension = explode(".", $fileName);
        $extension = end($extension);
        if(in_array($extension, $allowedExts))
        {
            $zip = new ZipArchive;
            if ($zip->open($_FILES['import_file']['tmp_name']) === TRUE) {
                $dir = CS_DIR."temp";
                if(!file_exists($dir))
                    mkdir($dir, 0777);

                $xmlfile=$zip->extractTo(CS_DIR.'temp');
                $zip->close();
            }

            $xmlfile=str_replace("zip","xml",$_FILES['import_file']['name']);
            $files=scandir(CS_DIR.'temp');

            $mytempcnt=0;
            $myfile ="";

            foreach($files as $file)
            {
                $filename = explode(".", $file);
                $fileext = $filename[count($filename)-1];

                if (file_exists($dir."/".$file) && $fileext != "xml" && $file != "." && $file != "..") {

                    if (strtolower($fileext) == 'jpg' || strtolower($fileext) == 'jpeg' || strtolower($fileext) == 'png' || strtolower($fileext) == 'gif') {
                        $img = CS_DIR.'temp/'.$file;
                        $filetype = wp_check_filetype( basename( $img ), null );

                        $wp_upload_dir = wp_upload_dir();

                        $attachment = array(
                        'guid'           => $wp_upload_dir['url'] . '/' . basename( $img ),
                        'post_mime_type' => $filetype['type'],
                        'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $img ) ),
                        'post_content'   => '',
                        'post_status'    => 'inherit'
                        );

                        $newpath=$wp_upload_dir['path'];
                        copy($img,$newpath."/". basename( $img ));

                        $attach_id = wp_insert_attachment( $attachment, $newpath."/". basename( $img ));

                        require_once( ABSPATH . 'wp-admin/includes/image.php' );

                        $attach_data = wp_generate_attachment_metadata( $attach_id, $newpath."/". basename( $img ) );
                        wp_update_attachment_metadata( $attach_id, $attach_data );

                        $mytempcnt++;
                    }
                }


                if($file!="." && $file!=".." && $fileext == "xml")
                {
                    $myfile=$file;
                }
            }

            if($myfile!="")
            {
                $xml=simplexml_load_file(CS_DIR.'temp/'.$myfile);
                foreach($xml as $slider_data)
                {

                    $sname=$slider_data->slidername;
                    $sdata=$slider_data->sliderdata;
                    $screated=$slider_data->slidercreated;
                    $smodify=$slider_data->slidermodified;
                    if($mytempcnt > 0)
                    {

                        $slider_layers = base64_decode($sdata);
                        $slider_layers = unserialize($slider_layers);
                        
                        $upload_dir = wp_upload_dir();
                        if(isset($slider_layers['settings']['loading-img']) && trim($slider_layers['settings']['loading-img']))
                        {
                            $cslimg=explode("/",$slider_layers['settings']['loading-img']);
                            $newcslimg=$upload_dir['url']."/".$cslimg[count($cslimg)-1];
                            $slider_layers['settings']['loading-img']=$newcslimg;
                        }
                        if(trim($slider_layers['settings']['img-loader']))
                        {
                            $cslimg=explode("/",$slider_layers['settings']['img-loader']);
                            $newcslimg=$upload_dir['url']."/".$cslimg[count($cslimg)-1];
                            $slider_layers['settings']['img-loader']=$newcslimg;
                        }

                        if($slider_layers['settings']['left-arrow-img'])
                        {
                            $limg=explode("/",$slider_layers['settings']['left-arrow-img']);
                            $newlimg=$upload_dir['url']."/".$limg[count($limg)-1];
                            $slider_layers['settings']['left-arrow-img']=$newlimg;
                        }
                        if($slider_layers['settings']['right-arrow-img'])
                        {
                            $rimg=explode("/",$slider_layers['settings']['right-arrow-img']);
                            $newrimg=$upload_dir['url']."/".$rimg[count($rimg)-1];
                            $slider_layers['settings']['right-arrow-img']=$newrimg;
                        }

                        if($slider_layers['settings']['left-hover-arrow-img'])
                        {
                            $lhimg=explode("/",$slider_layers['settings']['left-hover-arrow-img']);
                            $newlhimg=$upload_dir['url']."/".$lhimg[count($lhimg)-1];
                            $slider_layers['settings']['left-hover-arrow-img']=$newlhimg;

                        }
                        if($slider_layers['settings']['right-hover-arrow-img'])
                        {
                            $rhimg=explode("/",$slider_layers['settings']['right-hover-arrow-img']);
                            $newrhimg=$upload_dir['url']."/".$rhimg[count($rhimg)-1];
                            $slider_layers['settings']['right-hover-arrow-img']=$newrhimg;
                        }

                        if($slider_layers['settings']['bullet-img'])
                        {
                            $bimg=explode("/",$slider_layers['settings']['bullet-img']);
                            $newbimg=$upload_dir['url']."/".$bimg[count($bimg)-1];
                            $slider_layers['settings']['bullet-img']=$newbimg;

                        }

                        if($slider_layers['settings']['active-bullet-img'])
                        {
                            $baimg=explode("/",$slider_layers['settings']['active-bullet-img']);
                            $banewimg=$upload_dir['url']."/".$baimg[count($baimg)-1];
                            $slider_layers['settings']['active-bullet-img']=$banewimg;
                        }

                        if($slider_layers['settings']['bullet-left-container-img'])
                        {
                            $blimg=explode("/",$slider_layers['settings']['bullet-left-container-img']);
                            $blnewimg=$upload_dir['url']."/".$blimg[count($blimg)-1];
                            $slider_layers['settings']['bullet-left-container-img']=$blnewimg;
                        }

                        if($slider_layers['settings']['bullet-right-container-img'])
                        {
                            $brimg=explode("/",$slider_layers['settings']['bullet-right-container-img']);
                            $brnewimg=$upload_dir['url']."/".$brimg[count($brimg)-1];
                            $slider_layers['settings']['bullet-right-container-img']=$brnewimg;
                        }

                        if($slider_layers['settings']['no-thumb-img'])
                        {
                            $noimg=explode("/",$slider_layers['settings']['no-thumb-img']);
                            $nonewimg=$upload_dir['url']."/".$noimg[count($noimg)-1];
                            $slider_layers['settings']['no-thumb-img']=$nonewimg;
                        }

                        for($j=0;$j<sizeof($slider_layers['layers']);$j++)
                        {
                            $main_slide=$slider_layers['layers'][$j];
                            if(trim($main_slide['properties']['background'])!="")
                            {
                                $bimg=explode("/",$main_slide['properties']['background']);
                                $newimg=$upload_dir['url']."/".$bimg[count($bimg)-1];
                                $main_slide['properties']['background']= $newimg;
                            }

                            if(trim($main_slide['properties']['thumbnail'])!="")
                            {
                                $timg=explode("/",$main_slide['properties']['thumbnail']);
                                $newtimg=$upload_dir['url']."/".$timg[count($timg)-1];
                                $main_slide['properties']['thumbnail']=$newtimg;
                            }

                            if(trim($main_slide['properties']['carousel-left-arrow-img'])!="")
                            {
                                $climg=explode("/",$main_slide['properties']['carousel-left-arrow-img']);
                                $newclimg=$upload_dir['url']."/".$climg[count($climg)-1];
                                $main_slide['properties']['carousel-left-arrow-img']=$newclimg;
                            }

                            if(trim($main_slide['properties']['carousel-right-arrow-img'])!="")
                            {
                                $crimg=explode("/",$main_slide['properties']['carousel-right-arrow-img']);
                                $newcrimg=$upload_dir['url']."/".$crimg[count($crimg)-1];
                                $main_slide['properties']['carousel-right-arrow-img']=$newcrimg;
                            }


                            for($k=0;$k<sizeof($main_slide['sub_layer']);$k++)
                            {
                                $layer = $main_slide['sub_layer'][$k];

                                if(trim($layer['properties']['image'])!="")
                                {
                                    $layerimg=explode("/",$layer['properties']['image']);
                                    $newlayerimg=$upload_dir['url']."/".$layerimg[count($layerimg)-1];
                                    $layer['properties']['image']=$newlayerimg;                                        
                                }
                                $main_slide['sub_layer'][$k]=$layer;

                            }


                            $slider_layers['layers'][$j]=$main_slide;
                        }
                        $sdata=base64_encode(serialize($slider_layers));

                    }

                    $wpdb->query(
                    $wpdb->prepare("INSERT INTO $table_name
                    (name, data, created, modified,author_id,type)
                    VALUES (%s, %s, %s, %s, %d,%s)",
                    $sname,
                    $sdata,
                    $screated,
                    $smodify,
                    get_current_user_id(),
                    'save'
                    )
                    );

                }
                /*unlink(CS_DIR.'temp/'.$file);*/
            }
            $folder=CS_DIR."temp";
            $folder= deleteDirectory($folder);
        }
        else
        {
            echo "<script>document.location='admin.php?page=cloud-slider-list&message=error_import'</script>";
        }
    }
}
else if(isset($_POST['hidden_action']) && $_POST['hidden_action']=="ExportSlider")
    {
        if($_POST['export_sliders'])
        {
            ob_start();
            $dir = CS_DIR."temp";
            if(!file_exists($dir))
                mkdir($dir, 0777);


        $xml_output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        $xml_output .= "<allslider>\n";
        for($i=0; $i<sizeof($_POST['export_sliders']);$i++)
        {
            if($_POST["export_sliders"][$i]=="-1")
            {
                $filename = "CloudSlider_Export_All_Slider_".date('Y-m-d').".xml";
                $zip_filename = "CloudSlider_Export_All_Slider_".date('Y-m-d').".zip";

                $slider_data=$objCloudSlider->fnGetAllSliderData();
                foreach($slider_data as $slider)
                {
                    $xml_output .= "<slider>\n";
                    $xml_output .= "\t<sliderid>".$slider->id."</sliderid>\n";
                    $xml_output .= "\t<slidername>".stripcslashes($slider->name)."</slidername>\n";
                    if(isset($_POST["export_with_image"]))
                    {
                        $slider_layers = base64_decode($slider->data);
                        $slider_layers = unserialize($slider_layers);
                        $upload_dir = wp_upload_dir();
                        $slider_layers=$objCloudSlider->fnExportSliderData($slider_layers);
                        $new_data=base64_encode(serialize($slider_layers));
                        $xml_output .= "\t<sliderdata>".$new_data."</sliderdata>\n";
                    }
                    else
                        $xml_output .= "\t<sliderdata>".$slider->data."</sliderdata>\n";

                    $xml_output .= "\t<slidercreated>".$slider->created."</slidercreated>\n";
                    $xml_output .= "\t<slidermodified>".$slider->modified."</slidermodified>\n";
                    $xml_output .= "</slider>\n";
                }

            }
            else
            {
                $slider=$objCloudSlider->fnGetSliderData($_POST["export_sliders"][$i]);
                if(count($_POST['export_sliders'])==1)
                {
                    $filename = "CloudSlider_Export_".date('Y-m-d')."_".$slider->id.".xml";
                    $zip_filename = "CloudSlider_Export_".date('Y-m-d')."_".$slider->id.".zip";
                }
                else
                {
                    $filename = "CloudSlider_Export_".date('Y-m-d').".xml";
                    $zip_filename = "CloudSlider_Export_".date('Y-m-d').".zip";
                }

                $xml_output .= "<slider>\n";
                $xml_output .= "\t<sliderid>".$slider->id."</sliderid>\n";
                $xml_output .= "\t<slidername>".stripcslashes($slider->name)."</slidername>\n";

                if(isset($_POST["export_with_image"]))
                {
                    $slider_layers = base64_decode($slider->data);
                    $slider_layers = unserialize($slider_layers);
                    $upload_dir = wp_upload_dir();
                    $slider_layers=$objCloudSlider->fnExportSliderData($slider_layers);                    
                    $new_data=base64_encode(serialize($slider_layers));
                    $xml_output .= "\t<sliderdata>".$new_data."</sliderdata>\n";
                }
                else
                    $xml_output .= "\t<sliderdata>".$slider->data."</sliderdata>\n";

                $xml_output .= "\t<slidercreated>".$slider->created."</slidercreated>\n";
                $xml_output .= "\t<slidermodified>".$slider->modified."</slidermodified>\n";
                $xml_output .= "</slider>\n";
            }

        }
        $xml_output .= "</allslider>";

        /*echo trim($xml_output);
        header('Content-type: text/xml');
        header('Content-Disposition: attachment; filename="'.$filename.'"');*/

        $zip = new ZipArchive;
        $res = $zip->open(CS_DIR.'temp/'.$zip_filename, ZipArchive::CREATE);
        $files=scandir(CS_DIR.'temp');

        if(($key = array_search(".", $files)) !== false) {
            unset($files[$key]);
        }
        if(($key = array_search("..", $files)) !== false) {
            unset($files[$key]);
        }
        $files = array_values($files);
        $files[] = $filename;

        file_put_contents(CS_DIR."temp/".$filename, $xml_output);
        //$files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator(CS_DIR."temp"), RecursiveIteratorIterator::LEAVES_ONLY);
        //$files=scandir(CS_DIR.'temp');

        //$zip->addFile(CS_DIR."temp/test.xml",$filename);

        if ($res === TRUE) {
            foreach ($files as $name => $file)
            {
                $new_filename = substr($name,strrpos($name,'/') + 1);
                
                    /* for windows */
                    if($file!="Thumbs.db" && $file!="." && $file!=".." && strpos($file, 'zip') === false)
                    {
                        //echo $file;echo ":".$new_filename;exit;
                        $zip->addFile(CS_DIR.'temp/'.$file, $file);
                    }

                /*if(file_exists(CS_DIR."temp/".$new_filename))
                unlink(CS_DIR."temp/".$new_filename);*/
            }
            $zip->close();
        }
        $output = ob_get_contents();
        ob_end_clean();
        header('Content-type: application/zip');
        header('Content-Disposition: attachment; filename='.$zip_filename);
        readfile(CS_DIR."temp/".$zip_filename);
        $folder=CS_DIR."temp";
        $folder= deleteDirectory($folder);
        exit;
    }
}

function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }

    if (!is_dir($dir)) {
        return unlink($dir);
    }

    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }

        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }

    }

    return rmdir($dir);
}

function rrmdir($path) {
    return is_file($path)? @unlink($path): array_map(__NAMESPACE__ . '\rrmdir',glob($path.'/*'))==@rmdir($path);
}

function getOS()
{
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
        return true;
    else
        return false;

}

function unZipOnLinux($sourceFileName,$destinationPath){
    $unzipfile = unzip_file($sourceFileName, $destinationPath);
    //system('unzip -q '.$sourceFileName .'  -d '. $destinationPath);
}

function extractDir($zipfile, $path) {
    if (file_exists($zipfile)) {
        $files = array();
        $zip = new ZipArchive;
        if ($zip->open($zipfile) === TRUE) {
            for($i = 0; $i < $zip->numFiles; $i++) {
                $entry = $zip->getNameIndex($i);
                //Use strpos() to check if the entry name contains the directory we want to extract
                echo $entry."--";
                echo is_dir($entry)."--";
                echo strpos($entry, "image/");
                echo "<br>";
                if (strpos($entry, "image")) {

                    //Add the entry to our array if it in in our desired directory
                    $files[] = $entry;
                }
            }
            //Feed $files array to extractTo() to get only the files we want
            if ($zip->extractTo($path, $files) === TRUE) {
                return TRUE;
            } else {
                return FALSE;
            }
            $zip->close();
        } else {
            return FALSE;
        }
        exit;
    } else {
        echo "else";exit;
        return FALSE;
    }
}
