<?php
defined('_JEXEC') or die('Restricted access');

/**
* @package OS CCK
* @copyright OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Roman Akoev (akoevroman@gmail.com)
* @link http://ordasoft.com/cck-content-construction-kit-for-joomla.html
* @description OrdaSoft Content Construction Kit
*/


class AdminImportExport
{
    static $parentChildAsoocArray = array();


    static function import() {
        global $os_cck_configuration, $entities_type, $entityFieldLists;

        $database = new os_cckDb();
                $db = $database;
        $step = protectInjectionWithoutQuote('step',1);
            // var_dump($step);
        if($step == 2){
            $tmp_file_path = protectInjectionWithoutQuote('tmp_file_path','', 'STRING');
            if($tmp_file_path == '' && $_FILES['importData']['type'] != 'application/zip' && $_FILES['importData']['type'] != 'text/xml' && $_FILES['importData']['type'] != 'application/x-zip-compressed')
            {
                $data['error'] = 'Incorrect file format';
                AdminViewImportExport::import($step,$data);
            }else{
                if($tmp_file_path == ''){
                    $tmp_file_path = JPATH_SITE . '/tmp/' . $_FILES['importData']['name'];
                    move_uploaded_file($_FILES['importData']['tmp_name'], $tmp_file_path);
                }
                $extractPathFiles = JPATH_COMPONENT_SITE.'/'.$os_cck_configuration->get('filehosting_folder', 'files') . '/';
                $zip = new ZipArchive;
                $extract = $zip->open($tmp_file_path);
                for ($i = 0; $i < $zip->numFiles; $i++) {
                    $filename = $zip->getNameIndex($i);

                    // ...
                }
                $zip_file_name = protectInjectionWithoutQuote('zip_file_name','', 'STRING');
                if($zip_file_name == ''){
                    $zip_file_name = $_FILES['importData']['name'];
                }
                // var_dump($zip_file_name);
                $zip_file_name_arr = explode('/', $zip_file_name);
                $zip_file_name_arr_length = count($zip_file_name_arr);
                $zip_file_name_arr[$zip_file_name_arr_length - 1] = $filename;
                
                $xml_file_name = implode('/', $zip_file_name_arr);
                if ($extract === TRUE) {
                      
                    $zip->extractTo($extractPathFiles, $xml_file_name);

                }

                $dom = new domDocument('1.0', 'utf-8');
                $dom->load($extractPathFiles . '/' . $xml_file_name);

                $entities_list = $dom->getElementsByTagname('entities');
                $entity_arr = array();
                foreach($entities_list as $entity){
                    $entity_dom = $entity->getElementsByTagname('entity');

                    foreach($entity_dom as $entity_temp){
                        // $entity_temp = $entity_dom->item(0);
                        $entity_childs = $entity_temp->childNodes;

                        $old_eid = 0;
                        
                        foreach($entity_childs as $key => $val){
                            
                            if(property_exists($val, 'tagName')){
                                $prop = $val->tagName;
                                if($prop == 'eid'){
                                    $old_eid = $val->nodeValue;
                                    continue;
                                }elseif($prop == 'name'){
                                    $entity_arr[$old_eid] = $val->nodeValue;
                                    continue;
                                }
                            }
                            
                        }

                    }
                }
                // var_dump($zip); exit;
                $zip->close();
                // var_dump($entity_arr); exit;
                if(count($entity_arr) == 1 && $entity_arr[$old_eid] == 'os-library'){
                    $query = "SELECT eid FROM #__os_cck_entity WHERE name='os-library' LIMIT 0,1";
                    $db->setQuery($query);
                    $existing_eid = $db->loadResult();

                    if($existing_eid) {
                        $step = 3;
                    }
                }
                
            }
        }
        if($step === 1){
                        $query = "SELECT eid, name FROM #__os_cck_entity";
                        $database->setQuery($query);
                        $entities_list = $database->loadObjectList('eid');
                        
                        
                        $entities_opt = array();
                        foreach($entities_list as $entity){
                            $entities_opt[] = JHTML::_('select.option',$entity->eid, $entity->name);
                        }

                        $query = "SELECT lid, title, fk_eid, type FROM #__os_cck_layout ORDER BY type, title";
                        $database->setQuery($query);
                        $layouts_lists = $database->loadObjectList();

                        $layouts_opts = array();
                        foreach($layouts_lists as $layout){
                            $layouts_opts[$layout->fk_eid][] = JHTML::_('select.option',$layout->lid, $layout->title);
                        }
                        $layouts_lists_arr = array();
                        foreach($layouts_lists as $layout){
                            $layouts_lists_arr[$layout->fk_eid][] = $layout;
                        }
                        
                        $query = "SELECT ei.eiid, ei.title, ei.fk_eid, ei.fk_lid FROM #__os_cck_entity_instance as ei 
                                LEFT JOIN #__os_cck_layout as l ON l.lid = ei.fk_lid WHERE l.type='add_instance' ORDER BY ei.title";
                        $database->setQuery($query);
                        $instancies_lists = $database->loadObjectList();
                        // var_dump($instancies_lists);
                        $instancies_lists_arr = array();
                        foreach($instancies_lists as $instance){
                            $instancies_lists_arr[$instance->fk_eid][] = $instance;
                        }
                        $instancies_opts = array();
                        foreach($instancies_lists as $instance){
                            $instancies_opts[$instance->fk_eid][] = JHTML::_('select.option',$instance->eiid, $instance->title);
                        }
                        // var_dump($instancies_opts); exit;
                        $data = array();
                        $data['entities_opt'] = $entities_opt;
                        $data['layouts_opt'] = $layouts_opts; 
                        $data['layouts_lists'] = $layouts_lists_arr; 
                        $data['instancies_lists'] = $instancies_lists_arr; 
                        $data['instancies_opts'] = $layouts_lists_arr; 
                        $data['entities_list'] = $entities_list; 

                        $elements_opt = array();
                        $elements_opt[] = JHTML::_('select.option','entity', 'Entity+Fields (Important!)');
                        $elements_opt[] = JHTML::_('select.option','categories', 'Categories');
                        $elements_opt[] = JHTML::_('select.option','coupons', 'Coupons');
                        $elements_opt[] = JHTML::_('select.option','orders', 'Orders');
                        $elements_opt[] = JHTML::_('select.option','layouts', 'Layouts');
                        $elements_opt[] = JHTML::_('select.option','instancies', 'Instancies(impossible without layouts)');
                        $elements_opt[] = JHTML::_('select.option','reviews', 'Reviews(impossible without layouts)');
                        $elements_opt[] = JHTML::_('select.option','requests', 'Requests(impossible without layouts)');
                        $elements_opt[] = JHTML::_('select.option','files', 'Files(images,attached files)');
                        
                        $data['elements_opt'] = $elements_opt;

                        $export_type_opt = array();
                        $export_type_opt[] = JHTML::_('select.option','all', 'All');
                        $export_type_opt[] = JHTML::_('select.option','custom', 'Custom');
                        $data['export_type_opt'] = $export_type_opt;
            AdminViewImportExport::import1($step, $data);

        }elseif($step == 2){
            $tmp_file_path = protectInjectionWithoutQuote('tmp_file_path','', 'STRING');
            // var_dump($tmp_file_path);
            if($tmp_file_path == '' && $_FILES['importData']['type'] != 'application/zip' && $_FILES['importData']['type'] != 'text/xml' && $_FILES['importData']['type'] != 'application/x-zip-compressed')
            {
                $data['error'] = 'Incorrect file format';
                AdminViewImportExport::import($step,$data);
            }else{
                if($tmp_file_path == ''){
                    $tmp_file_path = JPATH_SITE . '/tmp/' . $_FILES['importData']['name'];
                    move_uploaded_file($_FILES['importData']['tmp_name'], $tmp_file_path);
                }
                $extractPathFiles = JPATH_COMPONENT_SITE.'/'.$os_cck_configuration->get('filehosting_folder', 'files') . '/';
                $zip = new ZipArchive;
                // var_dump($tmp_file_path);
                $extract = $zip->open($tmp_file_path);
                // var_dump($zip);
                // var_dump($zip->numFiles);
                for ($i = 0; $i < $zip->numFiles; $i++) {
                    // var_dump($zip->getNameIndex($i));
                    $filename = $zip->getNameIndex($i);

                    // ...
                }
                $zip_file_name = protectInjectionWithoutQuote('zip_file_name','', 'STRING');
                if($zip_file_name == ''){
                    $zip_file_name = $_FILES['importData']['name'];
                }
                // var_dump($zip_file_name);
                $zip_file_name_arr = explode('/', $zip_file_name);
                $zip_file_name_arr_length = count($zip_file_name_arr);
                $zip_file_name_arr[$zip_file_name_arr_length - 1] = $filename;
                
                $xml_file_name = implode('/', $zip_file_name_arr);
//                var_dump($xml_file_name);
                if ($extract === TRUE) {
                      
                    $zip->extractTo($extractPathFiles, $xml_file_name);

                }

                $dom = new domDocument('1.0', 'utf-8');
                $dom->load($extractPathFiles . '/' . $xml_file_name);

                $entities_list = $dom->getElementsByTagname('entities');
                $entity_arr = array();
                foreach($entities_list as $entity){
                    $entity_dom = $entity->getElementsByTagname('entity');

                    foreach($entity_dom as $entity_temp){
                        // $entity_temp = $entity_dom->item(0);
                        $entity_childs = $entity_temp->childNodes;

                        $old_eid = 0;
                        
                        foreach($entity_childs as $key => $val){
                            
                            if(property_exists($val, 'tagName')){
                                $prop = $val->tagName;
                                if($prop == 'eid'){
                                    $old_eid = $val->nodeValue;
                                    continue;
                                }elseif($prop == 'name'){
                                    $entity_arr[$old_eid] = $val->nodeValue;
                                    continue;
                                }
//                                        var_dump($val->tagName);
//                                        var_dump($val->nodeValue);
                            }
                            
                        }

                    }
                }
                // var_dump($zip); exit;
                $zip->close();

                $query = "SELECT eid, name FROM #__os_cck_entity";
                $db->setQuery($query);
                $existing_entities = $db->loadAssocList('eid', 'name');
                // var_dump($existing_entities);
                AdminViewImportExport::importStepTwo($entity_arr,$tmp_file_path,$existing_entities,$zip_file_name);
                // var_dump($entity_arr); exit;
            }
        }elseif($step == 3){
//                    var_dump($_FILES['importData']['type']); exit;

            if(!isset($tmp_file_path)){
                $tmp_file_path = protectInjectionWithoutQuote('tmp_file_path','', 'STRING');
            }
            
            if(!isset($existing_eid) || !$existing_eid){
                $entity_export_type = protectInjectionWithoutQuote('entity_export_type',array(), 'ARRAY');
                $entity_merge = protectInjectionWithoutQuote('entity_merge',array(), 'ARRAY');
                $layout_opt = protectInjectionWithoutQuote('layout_opt',array(), 'ARRAY');
                $field_opt = protectInjectionWithoutQuote('field_opt',array(), 'ARRAY');
            }else{
                $entity_export_type = array();
                $entity_export_type[$old_eid] = 'merge';
                $entity_merge = array();
                $entity_merge[$old_eid] = $existing_eid;
                $layout_opt = array();
                $layout_opt[$old_eid] = 'merge';
                $field_opt = array();
                $field_opt[$old_eid] = 'merge';
            }
            // var_dump($entity_export_type);
            // echo '111111111111'; exit;
            // if($_FILES['importData']['type'] != 'application/zip' && $_FILES['importData']['type'] != 'text/xml' && $_FILES['importData']['type'] != 'application/x-zip-compressed')
            // {
            //     $data['error'] = 'Incorrect file format';
            //     AdminViewImportExport::import($step,$data);
            // }else{
                
                $extractPathFiles = JPATH_COMPONENT_SITE.'/'.$os_cck_configuration->get('filehosting_folder', 'files') . '/';
//                $extractPathXml = JPATH_COMPONENT_SITE.'/files';
                $extractPathImages = JPATH_ROOT.'/images';
                $extractPathGalleryZip = JPATH_COMPONENT_SITE.'/files/gallery.zip';
                

                
                
                
            //    var_dump($_FILES); exit;
                $zip = new ZipArchive;
                try {
                    $extract = $zip->open($tmp_file_path);
                } catch (Exception $e) {
                    echo $e->getMessage();
                    
                    exit;
                }
                
            //    var_dump($zip); exit;
                
                for ($i = 0; $i < $zip->numFiles; $i++) {
                    $filename = $zip->getNameIndex($i);

                    // ...
                }
                $zip_file_name = protectInjectionWithoutQuote('zip_file_name','', 'STRING');
                $zip_file_name_arr = explode('/', $zip_file_name);
                $zip_file_name_arr_length = count($zip_file_name_arr);
                if(isset($filename))
                $zip_file_name_arr[$zip_file_name_arr_length - 1] = $filename;
                
                $xml_file_name = implode('/', $zip_file_name_arr);
//                var_dump($xml_file_name);
                  if ($extract === TRUE) {
                      
                      $zip->extractTo($extractPathFiles, $xml_file_name);

                  }
//                var_dump($zip); exit;
                            $retVal = array();
                            $k = 0;
                            $new_categories = array();
                            $new_relate_ids = array();

                            $dom = new domDocument('1.0', 'utf-8');
                            if(file_exists($extractPathFiles . '/' . $xml_file_name)){
                                $dom->load($extractPathFiles . '/' . $xml_file_name);
                            }else{

                            }
                            
                            
                            $entities_list = $dom->getElementsByTagname('entities');
                            $entities_list2 = $dom->getElementsByTagname('entities');

                            $associateSaveArr = array();
                            $fieldsAssocArr = array();
                            $entityAssocArr = array();
                            $parentChildArr = array();
                            $instanceRequestsArr = array();
                            $instanciesAssocArr = array();
                            $contentInstancesPriceAssocArr = array();
                            $layoutAssocGlobalArr = array();
                            $notCreatedLayoutArr = array();
                            foreach($entities_list as $entity){
                                $entity_dom = $entity->getElementsByTagname('entity');

                                foreach($entity_dom as $entity_temp){
                                    // $entity_temp = $entity_dom->item(0);
                                    $entity_childs = $entity_temp->childNodes;

                                    // var_dump($entity_childs); exit;
    //                                $entity_dom = $entity->nodeValue;
                                    $new_entity = new os_cckEntity($db->_db);
                                    $old_eid = 0;
                                    $entity_conf = array();
                                    foreach($entity_childs as $key => $val){
                                        
                                        if(property_exists($val, 'tagName')){

                                            $prop = $val->tagName;
                                            // var_dump($prop);
                                            if($prop == 'eid'){
                                                $old_eid = $val->nodeValue;
                                                continue;
                                            }elseif($prop == 'fields' || $prop == 'layouts' || $prop == 'instancies' || $prop == 'typeAlias'){
                                                continue;
                                            }elseif($prop == 'entity_conf'){
                                                $entity_conf = json_decode($val->nodeValue, true);
                                                continue;
                                            }
                                            $new_entity->$prop = $val->nodeValue;
    //                                        var_dump($val->tagName);
    //                                        var_dump($val->nodeValue);
                                        }
                                        
                                    }
                                    if($entity_export_type[$old_eid] == 'new'){
                                        if($new_entity::is_entity_name_exist($new_entity->name)){
                                            $new_entity->name = substr($new_entity->name,0,15) . '_2_'.rand();
                                            if(strlen($new_entity->name) > 32){
                                                $new_name = mb_substr($new_entity->name, 0, 31);
                                                $new_entity->name = $new_name;
                                            }
                                        }

                                       // var_dump($new_entity); exit;
                                        $new_entity->check();
                                        $new_entity->store();
                                        
                                    
                                        AdminEntity::setEntitySettings($entity_conf, $new_entity);
                                        $entityAssocArr[$old_eid] = $new_entity->eid;
                                        // $ussuesArray["oldId"] = $old_eid;
                                        // $ussuesArray["newId"] = $new_entity->eid;
                                        $new_eid = $new_entity->eid;
                                        // $new_eid = 4;
                                    }elseif($entity_export_type[$old_eid] == 'merge'){
                                        $entityAssocArr[$old_eid] = $entity_merge[$old_eid];
                                        $new_eid = $old_eid;
                                    }else{
                                        continue;
                                    }
//                                    $associateSaveArr[] = $ussuesArray;
                                }
                            }

                            foreach($entities_list2 as $entity){
// echo "<br><br> Start import entity: "; flush();  if( ob_get_level() > 0 ) ob_flush(); //fix error: Maximum execution time 
set_time_limit( 300 );

                                $entity_dom = $entity->getElementsByTagname('entity');
                                
                                foreach($entity_dom as $entity_temp){
                                    $entity_childs = $entity_temp->childNodes;
                                    $old_eid = 0;
                                    foreach($entity_childs as $key => $val){
                                        
                                        if(property_exists($val, 'tagName')){
                                            $prop = $val->tagName;
                                            if($prop == 'eid'){
                                                $old_eid = $val->nodeValue;
                                                continue;
                                            }
                                        }
                                        
                                    }
                                    if(!isset($entityAssocArr[$old_eid])) continue 2;
                                    $new_eid = $entityAssocArr[$old_eid];

                                $fields_dom = $entity_temp->getElementsByTagname('fields');

                                if($fields_dom->length > 0) {

                                    $fields_temp = $fields_dom->item(0);

                                    $fields = $fields_temp->getElementsByTagname('field');
                                    $fields2 = $fields_temp->getElementsByTagname('field');
                                    $first_field = true;
                                    $old_max_fid = 0;
                                    foreach ($fields2 as $key => $val) {
                                        $dom_fileld = $val->childNodes;
                                        foreach ($dom_fileld as $k => $v) {
                                            if (property_exists($v, 'tagName')) {
                                                
                                                if ($v->tagName == 'fid') {
                                                    if($v->nodeValue > $old_max_fid){
                                                        $old_max_fid = $v->nodeValue;
                                                    }
                                                }
                                            }
                                        }
                                    }

// echo "<br> Start import fields: "; flush();  if( ob_get_level() > 0 ) ob_flush(); //fix error: Maximum execution time 
set_time_limit( 300 );
                                    
                                    // var_dump($old_max_fid); exit;
                                    $newFieldsIdsArr = array();
                                    foreach ($fields as $key => $val) {
                                        $dom_fileld = $val->childNodes;
                                        $field = new os_cckEntityField($db->_db);
                                        $old_fid = 0;
                                        $old_eid = 0;
                                        // var_dump($dom_fileld);
                                        foreach ($dom_fileld as $k => $v) {
                                            if (property_exists($v, 'tagName')) {
                                                $prop = $v->tagName;
                                                if ($v->tagName == 'fid') {
                                                    $old_fid = $v->nodeValue;
                                                    continue;
                                                }
                                                if ($v->tagName == 'fk_eid') {
                                                    $field->fk_eid = $entityAssocArr[$v->nodeValue];
                                                    $old_eid = $v->nodeValue;
                                                } else {
                                                    $field->$prop = $v->nodeValue;
                                                }
                                        //    var_dump($v->tagName);
                                        //    var_dump($v->nodeValue);
                                            }
                                        }
                                        $new_field = true;
                                        $old_field = new stdClass();
                                        // var_dump($entity_export_type[$old_eid]);
                                        if($entity_export_type[$old_eid] == 'merge' && $field_opt[$old_eid] == 'merge'){
                                            // echo '111111111111';
                                            foreach($entityFieldLists[$field->fk_eid] as $temp_field){
                                                if($temp_field->field_type ==  $field->field_type && $temp_field->field_name ==  $field->field_name){
                                                    $new_field = false;
                                                    $old_field = $temp_field;
                                                }
                                            }
                                        }
                                        // var_dump($new_field);
                                        if($entity_export_type[$old_eid] == 'new' || $new_field){
                                            $field->check();
                                            // var_dump($field);
                                            if($first_field){
                                                $query = "SELECT fid FROM #__os_cck_entity_field ORDER BY fid DESC LIMIT 0, 1";
                                                $db->setQuery($query);
                                                $pot_fid = $db->loadResult();
                                                if($pot_fid < $old_max_fid){
                                                    $new_pot_fid = $old_max_fid +1;
                                                    $new_db_field_name = $field->field_type . '_' . $new_pot_fid;
                                                    
                                                    $query = "INSERT INTO `#__os_cck_entity_field`(`fid`, `fk_eid`, `asset_id`, `field_name`, `field_type`, `module`, `published`, `show_in_instance_menu`, `db_field_name`, `params`) 
                                                    VALUES ('$new_pot_fid','$field->fk_eid','$field->asset_id','$field->field_name','$field->field_type','$field->module','$field->published','$field->show_in_instance_menu','$new_db_field_name', " . $db->quote($field->params) . ")";
                                                    $db->setQuery($query);
                                                    $db->execute();

                                                    // $query = "ALTER TABLE `#__os_cck_content_entity_$field->fk_eid` ADD `$field->field_type_$new_pot_fid` VARCHAR(255) NULL DEFAULT NULL AFTER `fk_eiid`";
                                                    // $db->setQuery($query);
                                                    // $db->execute();
                                                    
                                                    $field->load($new_pot_fid);
                                                    
                                                    $field->_addField();
                                                }else{
                                                    $field->store();
                                                }
                                                $first_field = false;
                                            }else{
                                                $field->store();
                                            }

                                            $fieldAssoc = array();
                                            $fieldAssoc['old_fid'] = $old_fid;
                                            $fieldAssoc['new_fid'] = $field->fid;
                                            $fieldAssoc['field_type'] = $field->field_type;
                                            $fieldAssoc['field_type_old_fid'] = $field->field_type."_".$old_fid;
                                            $fieldAssoc['field_type_old_fid_'] = $fieldAssoc['field_type_old_fid']."_";
                                            $fieldAssoc['{|field_type_old_fid|}'] = '{|'.$fieldAssoc['field_type_old_fid'].'|}';
                                            $fieldAssoc['instance.field_type_old_fid '] = 'instance.'.$fieldAssoc['field_type_old_fid'].' ';
                                            $fieldAssoc['instance.field_type_old_fid='] = 'instance.'.$fieldAssoc['field_type_old_fid'].'=';
                                            $fieldAssoc['instance.field_type_old_fid<'] = 'instance.'.$fieldAssoc['field_type_old_fid'].'<';
                                            $fieldAssoc['instance.field_type_old_fid>'] = 'instance.'.$fieldAssoc['field_type_old_fid'].'>';
                                            $fieldAssoc['_field_type_old_fid'] = '_'.$fieldAssoc['field_type_old_fid'].'>';

                                            //$fieldsAssocArr[] = $fieldAssoc; old andrew commen
                                            $fieldsAssocArr[$old_fid] = $fieldAssoc; //amdrew added
                                            $newFieldsIdsArr[] = $field->fid ;
                                        }else{
                                            $fieldAssoc = array();
                                            $fieldAssoc['old_fid'] = $old_fid;
                                            $fieldAssoc['new_fid'] = $old_field->fid;
                                            $fieldAssoc['field_type'] = $old_field->field_type;
                                            $fieldAssoc['field_type_old_fid'] = $field->field_type."_".$old_fid;
                                            $fieldAssoc['field_type_old_fid_'] = $fieldAssoc['field_type_old_fid']."_";
                                            $fieldAssoc['{|field_type_old_fid|}'] = '{|'.$fieldAssoc['field_type_old_fid'].'|}';
                                            $fieldAssoc['instance.field_type_old_fid '] = 'instance.'.$fieldAssoc['field_type_old_fid'].' ';
                                            $fieldAssoc['instance.field_type_old_fid='] = 'instance.'.$fieldAssoc['field_type_old_fid'].'=';
                                            $fieldAssoc['instance.field_type_old_fid<'] = 'instance.'.$fieldAssoc['field_type_old_fid'].'<';
                                            $fieldAssoc['instance.field_type_old_fid>'] = 'instance.'.$fieldAssoc['field_type_old_fid'].'>';
                                            $fieldAssoc['_field_type_old_fid'] = '_'.$fieldAssoc['field_type_old_fid'].'>';                                            
                                            //$fieldsAssocArr[] = $fieldAssoc; old andrew commen
                                            $fieldsAssocArr[$old_fid] = $fieldAssoc; //andrew added
                                        }
                                        
                                //    var_dump($field);W
                                        
                                    }
                                }

// echo "<br> Start build child fields: "; flush();  if( ob_get_level() > 0 ) ob_flush(); //fix error: Maximum execution time 
set_time_limit( 300 );
                                //update "child_select" for "text_select_list" fields
                                {
                                    $query = "select fid, params from #__os_cck_entity_field where field_type = 'text_select_list' ";
                                    $db->setQuery($query);
                                    $fields = $db->loadObjectList();

                                    foreach ($fields as $field){
                                        $query_fields_update = "";

                                        if( !in_array($field->fid, $newFieldsIdsArr ) ) continue; //this field not in this import inserted
                                        
                                        $fParams = json_decode($field->params);
                                        $old_child_select = $fParams->child_select;

                                        $field_have_child = false;
                                        // PregExp : digitals before | (not 0) ;or digitals after  | (not 0 )
                                        // preg_match("/([1-9]\d*\|)|(\|[1-9])/", $fParams->get('child_select',''),$matches ) ; if( count($matches) > 0)...
                                        if( preg_match("/([1-9]\d*\|)|(\|[1-9])/", $old_child_select ) ){
                                          $field_have_child = true;
                                        }
                                        //if not have child , check next field"
                                        if( !$field_have_child ) continue;

                                        $old_child_ids_arr = explode('|',$old_child_select); 

                                        $new_child_ids_arr = array();
                                        foreach($old_child_ids_arr as $old_fid ){
                                            if( !isset($fieldsAssocArr[$old_fid]) ) continue; //this field not in this import inserted

                                            $new_child_ids_arr[] =  $fieldsAssocArr[$old_fid]['new_fid']; 
                                        }
                                        
                                        if( count($new_child_ids_arr) == 0 ) continue; //to next field
                                        
                                        $new_child_select = implode('|',$new_child_ids_arr);

                                        $fParams->child_select = $new_child_select;

                                        $query_fields_update .= " UPDATE #__os_cck_entity_field SET ";
                                        $query_fields_update .= " params = " . $db->quote( json_encode($fParams) ) . " ";
                                        $query_fields_update .= " where fid = " . $field->fid . "; ";

                                        if(!empty($query_fields_update)){
                                            $db->setQuery($query_fields_update);
                                            try {
                                                $db->execute();
                                            } catch (Exception $e) {
                                                echo $e->getMessage();
                                                echo $query_fields_update;
                                                exit;
                                            }
                                        }
                                    }
                                }
                                
// echo "<br> Start import layouts: "; flush();  if( ob_get_level() > 0 ) ob_flush(); //fix error: Maximum execution time 
set_time_limit( 300 );
                                $layouts_dom = $entity_temp->getElementsByTagname('layouts');
                                if($layouts_dom->length > 0) {
                                    $layouts_temp = $layouts_dom->item(0);
                                    $layouts = $layouts_temp->getElementsByTagname('layout');
                                    $max_lid = 0;
                                    foreach ($layouts as $key => $val) {
                                        $dom_layouts = $val->childNodes;
                                        foreach ($dom_layouts as $k => $v) {
                                            if (property_exists($v, 'tagName')) {
                                                $prop = $v->tagName;
                                                if ($v->tagName == 'lid') {
                                                    if($v->nodeValue > $max_lid){
                                                        $max_lid = $v->nodeValue;
                                                    }
                                                    
                                                    continue;
                                                }
                                            }
                                        }
                                        
                                    }
                                }

                                $first_layout = true;
                                $layouts_dom = $entity_temp->getElementsByTagname('layouts');
                                if($layouts_dom->length > 0) {
                                    $layouts_temp = $layouts_dom->item(0);
                                    $layouts = $layouts_temp->getElementsByTagname('layout');
                                    $layoutAssocArr = array();
                                    $layoutHtmlArr = array();
                                    foreach ($layouts as $key => $val) {
                                        $dom_layouts = $val->childNodes;
                                        $layout = new os_cckLayout($db->_db);
                                        $layout_html = '';
                                        $old_lid = 0;
                                        $old_eid = 0;
                                        foreach ($dom_layouts as $k => $v) {
                                            if (property_exists($v, 'tagName')) {
                                                $prop = $v->tagName;
                                                if ($v->tagName == 'lid') {
                                                    $old_lid = $v->nodeValue;
                                                    continue;
                                                }
                                                if ($v->tagName == 'fk_eid') {
                                                    if($v->nodeValue != '-1'){
                                                        $layout->fk_eid = $entityAssocArr[$v->nodeValue];
                                                        $old_eid = $v->nodeValue;
                                                    }else{
                                                        $layout->fk_eid = $v->nodeValue;
                                                        $entityAssocArr['-1'] = '-1';
                                                        $old_eid = $v->nodeValue;
                                                    }
                                                } elseif ($v->tagName == 'params' || $v->tagName == 'pdf_structure' || $v->tagName == 'custom_fields') {
//                                                try {
                                                    
//                                                }catch (Exception $e){
//                                                    $uns = json_decode($v->nodeValue);
//                                                }
//                                                if(!$uns){
//                                                    echo str_replace(PHP_EOL, '', $v->nodeValue); exit;
//                                                }
                                                    if ($v->tagName == 'params' || $v->tagName == 'custom_fields') {
                                                        $uns = json_decode($v->nodeValue, true);
                                                        $layout->$prop = serialize(self::replaceFieldMasks($fieldsAssocArr, $uns));
                                                    }else{
                                                        $uns = json_decode($v->nodeValue, null);
                                                        $layout->$prop = json_encode(self::replaceFieldMasks($fieldsAssocArr, $uns));
                                                    }
//                                                var_dump($v->nodeValue);
//                                                 var_dump($uns);
                                                    
                                                } elseif ($v->tagName == 'layout_html') {

                                                    $layout_html = self::replaceFieldMasksLayoutHtml($fieldsAssocArr, $v->nodeValue);
                                                } else {
                                                    $layout->$prop = $v->nodeValue;
                                                }

                                                // var_dump($v->tagName);
                                                // var_dump($v->nodeValue);
                                            }
                                        }

                                        $new_layout = true;
                                        $old_layout = new os_cckLayout($db->_db);
                                        // var_dump($old_eid);
                                        if((isset($entity_export_type[$old_eid]) && $entity_export_type[$old_eid] == 'merge' && $layout_opt[$old_eid] == 'merge') || $old_eid == '-1'){
                                            $query = "SELECT lid FROM #__os_cck_layout WHERE title='".$layout->title."' AND type='".$layout->type."' AND fk_eid=".$layout->fk_eid." LIMIT 0,1";
                                            $db->setQuery($query);
                                            $new_lid = $db->loadResult();
                                            if($new_lid){
                                                $new_layout = false;
                                                $old_layout->load($new_lid);
                                            }
                                            
                                        }
                                        
                                        if(($old_eid == '-1' || $entity_export_type[$old_eid] == 'new') || $new_layout){
                                            if($first_layout){
                                                $query = "SELECT lid FROM #__os_cck_layout ORDER BY lid DESC LIMIT 0, 1";
                                                $db->setQuery($query);
                                                $pot_lid = $db->loadResult();
                                                if($pot_lid < $max_lid){
                                                    $new_pot_lid = $max_lid +1;
                                                    // $new_db_field_name = $field->field_type . '_' . $new_pot_fid;
                                                    
                                                    $query = "INSERT INTO `#__os_cck_layout`(`lid`, `title`, `alias`, `fk_eid`, `type`, `params`, `checked_out_time`, `checked_out`, `published`, `approved`, `created`, `changed`, `custom_fields`, `mail`, `pdf_structure`, `associate_layout`, `language`) 
                                                    VALUES ('$new_pot_lid',".$db->quote($layout->title).",".$db->quote($layout->alias).",".$db->quote($layout->fk_eid).",".$db->quote($layout->type).",".$db->quote($layout->params).",".$db->quote($layout->checked_out_time).",".$db->quote($layout->checked_out).",".$db->quote($layout->published).",".$db->quote($layout->approved).",".$db->quote($layout->created).",".$db->quote($layout->changed).",".$db->quote($layout->custom_fields).",".$db->quote($layout->mail).",".$db->quote($layout->pdf_structure).",".$db->quote($layout->associate_layout).",".$db->quote($layout->language).")";
                                                    $db->setQuery($query);
                                                    // echo $query; exit;
                                                    $db->execute();

                                                    // $query = "ALTER TABLE `#__os_cck_content_entity_$field->fk_eid` ADD `$field->field_type_$new_pot_fid` VARCHAR(255) NULL DEFAULT NULL AFTER `fk_eiid`";
                                                    // $db->setQuery($query);
                                                    // $db->execute();
                                                    
                                                    $layout->load($new_pot_lid);
                                                    
                                                    
                                                }else{
                                                    $layout->store();
                                                }
                                                $first_layout = false;
                                            }else{
                                                $layout->store();
                                            }
                                            // $layout->store();

                                            $query = "INSERT INTO #__os_cck_layout_html(fk_lid,layout_html,bootstrap)" .
                                                "\n VALUE(" . $layout->lid . ",'" . $layout_html . "','3')";
                                            $db->setQuery($query);
                                            $db->execute();

                                            $query = "INSERT INTO #__os_cck_layout_html(fk_lid,layout_html,bootstrap)" .
                                                "\n VALUE(" . $layout->lid . ",'','2')";

                                            $db->setQuery($query);
                                            $db->execute();


                                            $layoutAssoc = array();
                                            $layoutAssoc['old_lid'] = $old_lid;
                                            $layoutAssoc['new_lid'] = $layout->lid;
                                            //$layoutAssocArr[] = $layoutAssoc; //andrew comment
                                            $layoutAssocArr[$old_lid] = $layoutAssoc; //andrew add
                                            $layoutAssocGlobalArr[$old_lid] = $layout->lid;
                                            $layoutHtmlArr[$layout->lid] = $layout_html;
                                        }else{
                                            $layoutAssoc = array();
                                            $layoutAssoc['old_lid'] = $old_lid;
                                            $layoutAssoc['new_lid'] = $old_layout->lid;
                                            //$layoutAssocArr[] = $layoutAssoc; //andrew comment
                                            $layoutAssocArr[$old_lid] = $layoutAssoc; //andrew add
                                            $layoutAssocGlobalArr[$old_lid] = $old_layout->lid;
                                            $layoutHtmlArr[$layout->lid] = $old_layout->getLayoutHtml('3');
                                            $notCreatedLayoutArr[] = $old_layout->lid;
                                        }


                                        // var_dump($layout);
                                    }
                                }

// echo "<br> Start import instancies: "; flush();  if( ob_get_level() > 0 ) ob_flush(); //fix error: Maximum execution time 
set_time_limit( 300 );
                                $instancies_dom = $entity_temp->getElementsByTagname('instancies');
                                if($instancies_dom->length > 0) {
                                    $instancies_temp = $instancies_dom->item(0);
                                    $instancies = $instancies_temp->getElementsByTagname('instance');
                                    $parent_child_old_arr = array();
                                    foreach ($instancies as $key => $val) {
                                        // var_dump($key);
                                        // var_dump($val);
                                        $dom_instancies = $val->childNodes;

                                        $instance_content_prices = $val->getElementsByTagname('instance_content_price');
                                        $instance_content_files = $val->getElementsByTagname('instance_file');
                                        $instance_content_audio = $val->getElementsByTagname('instance_audio_source');
                                        $instance_content_video = $val->getElementsByTagname('instance_video_source');
                                        $instance_content_track = $val->getElementsByTagname('instance_track_source');
                                        $instance_parent = $val->getElementsByTagname('instance_parent');
                                        $instance_request = $val->getElementsByTagname('instance_request');
//                                        var_dump($instance_request);
                                        // var_dump($instance_content_prices->length);
                                        $instance = new os_cckEntityInstance($db->_db);
                                        // $layout_html = '';
                                        $old_eiid = 0;
                                        foreach ($dom_instancies as $k => $v) {
                                            // var_dump($k);
                                            // var_dump($v);
                                            if (property_exists($v, 'tagName')) {
                                                $prop = $v->tagName;
                                                // var_dump($prop);
                                                if ($v->tagName == 'eiid') {
                                                    $old_eiid = $v->nodeValue;
                                                    continue;
                                                }
                                                if ($v->tagName == 'fk_eid') {
                                                    $instance->fk_eid = $entityAssocArr[$v->nodeValue];
                                                } elseif ($v->tagName == 'fk_lid') {
                                                    $instance->$prop = self::getAssocLid($layoutAssocArr, $v->nodeValue);
                                                } elseif ($prop == 'instance_content') {
                                                    $instance_content_temp = $v->childNodes;
                                                    $instance_data = array();

                                                    foreach ($instance_content_temp as $instance_content_k => $instance_content_v) {
                                                        if ($instance_content_v instanceof DOMElement) {

                                                            if ($instance_content_v->tagName == 'ceid' || stripos($instance_content_v->tagName, 'categoryfield') !== false) continue;
                                                            if ($instance_content_v->tagName == 'fk_eiid') {
                                                                $old_eiid = $instance_content_v->nodeValue;
                                                                continue;
                                                            }
                                                            // var_dump(self::replaceFieldMasks($fieldsAssocArr, $instance_content_v->tagName));
                                                            $instance_data[self::replaceFieldMasks($fieldsAssocArr, $instance_content_v->tagName)] = $instance_content_v->nodeValue;
                                                            // $instance->_field_list = $entitty->getFieldList($layout->layout_html);
                                                            // $instance->_field_list = array_merge($instance->_field_list, $select_list);
                                                            // var_dump($instance_content_v);
                                                        }
                                                        // var_dump($instance_content_k);
                                                        // var_dump($instance_content_v);
                                                        // var_dump($instance_content_v instanceof DOMElement);
                                                    }
                                                    // var_dump($data); exit;
                                                } elseif ($prop == 'instance_content_price') {
                                                    $instance_content_temp = $v->childNodes;
                                                    $instance_price_data = array();
                                                    foreach ($instance_content_temp as $instance_content_k => $instance_content_v) {
                                                        // var_dump($instance_content_v);
                                                        if ($instance_content_v instanceof DOMElement) {

                                                            if ($instance_content_v->tagName == 'ceid' || $instance_content_v->tagName == 'fk_eiid') continue;

                                                            // var_dump(self::replaceFieldMasks($fieldsAssocArr, $instance_content_v->tagName));
                                                            $instance_price_data[self::replaceFieldMasks($fieldsAssocArr, $instance_content_v->tagName)] = $instance_content_v->nodeValue;
                                                            // $instance->_field_list = $entitty->getFieldList($layout->layout_html);
                                                            // $instance->_field_list = array_merge($instance->_field_list, $select_list);
                                                            // var_dump($instance_content_v);
                                                        }
                                                    }
                                                } elseif ($prop == 'instance_file' || $prop == 'instance_parent' || $prop == 'quantity' || $prop == 'instance_request') {

                                                } else {
                                                    $instance->$prop = $v->nodeValue;
                                                }


                                                // var_dump($v->tagName);
                                                // var_dump($v->nodeValue);
                                            }
                                        }
                                        // $instance->_field_list = $new_entity->getFieldList($layoutHtmlArr[self::getAssocLid($layoutAssocArr, $v->nodeValue)]);
                                        // var_dump($instance_price_data); exit;
//                                    $instance->bind($data);
                                        try {
                                            $instance->store();
                                        } catch (Exception $e) {
                                            var_dump($instance);
                                            var_dump($e);
                                            echo $e->getMessage();
                                            exit;
                                        }
                                        

                                        $instanciesAssocArr[$old_eiid] = $instance->eiid;
                                        $instance_files_data = array();
                                        $filesAssocArr = array();
                                        if ($instance_content_files->length > 0) {
                                            foreach ($instance_content_files as $key => $instance_content_file) {
                                                // var_dump($key);
                                                $dom_instance_file = $instance_content_file->childNodes;
                                                $old_file_id = 0;
                                                foreach ($dom_instance_file as $k => $v) {
                                                    if ($v instanceof DOMElement) {
                                                        if ($v->tagName == 'fid') {
                                                            $old_file_id = $v->nodeValue;
                                                        } else {
                                                            $instance_files_data[$key][$v->tagName] = $v->nodeValue;
                                                        }
                                                        // var_dump($k);
                                                        // var_dump($v);
                                                    }
                                                }

                                                $query = "INSERT INTO #__os_cck_files ";
                                                $params_arr = array();
                                                $value_arr = array();
                                                foreach ($instance_files_data[$key] as $k => $v) {
                                                    $params_arr[] = $k;
                                                    $value_arr[] = '"' . $v . '"';
                                                }
                                                $query .= '(' . implode(',', $params_arr) . ') VALUE (' . implode(',', $value_arr) . ')';
                                                $db->setQuery($query);
                                                $db->execute();


                                                $new_file_id = $db->insertid();
                                                $filesAssocArr[$old_file_id] = $new_file_id;

                                            }
                                        }
                                        
                                        
                                        $instance_audio_data = array();
                                        $audioAssocArr = array();
                                        if ($instance_content_audio->length > 0) {
                                            foreach ($instance_content_audio as $key => $instance_content_aud) {
                                                $dom_instance_audio = $instance_content_aud->childNodes;

                                                foreach ($dom_instance_audio as $k => $v) {
                                                    if ($v instanceof DOMElement) {
                                                        if ($v->tagName == 'fk_fid') {
                                                            $instance_audio_data[$key][$v->tagName] = self::getAssocFid($fieldsAssocArr, $v->nodeValue);
                                                        } elseif ($v->tagName == 'fk_eiid') {
                                                            $instance_audio_data[$key][$v->tagName] = $instance->eiid;
                                                        } else {
                                                            $instance_audio_data[$key][$v->tagName] = $v->nodeValue;
                                                        }
                                                    }
                                                }

                                                $query = "INSERT INTO #__os_cck_audio_source ";
                                                $params_arr = array();
                                                $value_arr = array();
                                                foreach ($instance_audio_data[$key] as $k => $v) {
                                                    if ($k == 'id') continue;
                                                    if (($k == 'fk_fid' && $v == '') || ($k == 'sequence_number' && $v == '')) {
                                                        $v = '0';
                                                    }
                                                    $params_arr[] = $k;
                                                    $value_arr[] = '"' . $v . '"';
                                                }
                                                $query .= '(' . implode(',', $params_arr) . ') VALUE (' . implode(',', $value_arr) . ')';
                                                $db->setQuery($query);
                                                try {
                                                    $db->execute();
                                                } catch (Exception $e) {
                                                    echo $e->getMessage();
                                                    echo $query;
                                                    exit;
                                                }
                                            }
                                        }
// echo ":9999999999999999999999999:";
// print_r($query);
// exit;  


                                        $instance_video_data = array();
                                        $videoAssocArr = array();
                                        if ($instance_content_video->length > 0) {
                                            foreach ($instance_content_video as $key => $instance_content_vid) {
                                                $dom_instance_video = $instance_content_vid->childNodes;
                                                foreach ($dom_instance_video as $k => $v) {
                                                    if ($v instanceof DOMElement) {
                                                        if ($v->tagName == 'id') {
                                                            $old_video_id = $v->nodeValue;
                                                        } elseif ($v->tagName == 'fk_fid') {
                                                            $instance_video_data[$key][$v->tagName] = self::getAssocFid($fieldsAssocArr, $v->nodeValue);
                                                        } elseif ($v->tagName == 'fk_eiid') {
                                                            $instance_video_data[$key][$v->tagName] = $instance->eiid;
                                                        } else {
                                                            $instance_video_data[$key][$v->tagName] = $v->nodeValue;
                                                        }
                                                    }
                                                }

                                                $query = "INSERT INTO #__os_cck_video_source ";
                                                $params_arr = array();
                                                $value_arr = array();
                                                foreach ($instance_video_data[$key] as $k => $v) {
                                                    if (($k == 'fk_fid' && $v == '') ) {
                                                        $v = '0';
                                                    }
                                                    $params_arr[] = $k;
                                                    $value_arr[] = '"' . $v . '"';
                                                }

                                                $query .= '(' . implode(',', $params_arr) . ') VALUE (' . implode(',', $value_arr) . ')';
                                                $db->setQuery($query);
                                                $db->execute();
                                                $new_video_id = $db->insertid();
                                                $videoAssocArr[$old_video_id] = $new_video_id;
                                            }
                                        }
                                      

                                        $instance_track_data = array();
                                        if ($instance_content_track->length > 0) {
                                            foreach ($instance_content_track as $key => $instance_content_tr) {
                                                $dom_instance_track = $instance_content_tr->childNodes;
                                                foreach ($dom_instance_track as $k => $v) {
                                                    if ($v instanceof DOMElement) {
                                                        if ($v->tagName == 'id') {

                                                        } elseif ($v->tagName == 'fk_fid') {
                                                            $instance_track_data[$key][$v->tagName] = self::getAssocFid($fieldsAssocArr, $v->nodeValue);
                                                        } elseif ($v->tagName == 'fk_video_id') {
                                                            if(isset($videoAssocArr[$v->nodeValue]) ) 
                                                                $instance_track_data[$key][$v->tagName] = $videoAssocArr[$v->nodeValue];
                                                            else $instance_track_data[$key][$v->tagName] = 0;
                                                        } elseif ($v->tagName == 'fk_eiid') {
                                                            $instance_track_data[$key][$v->tagName] = $instance->eiid;
                                                        } else {
                                                            $instance_track_data[$key][$v->tagName] = $v->nodeValue;
                                                        }
                                                    }
                                                }

                                                $query = "INSERT INTO #__os_cck_track_source "; 
                                                $params_arr = array();
                                                $value_arr = array();
                                                foreach ($instance_track_data[$key] as $k => $v) {
                                                    if ( ($k == 'fk_fid' && $v == '') 
                                                        || ($k == 'fk_video_id' && $v == '') 
                                                        || ($k == 'sequence_number' && $v == '') 
                                                    ) {
                                                        $v = '0';
                                                    }

                                                    $params_arr[] = $k;
                                                    $value_arr[] = '"' . $v . '"';
                                                }
                                                $query .= '(' . implode(',', $params_arr) . ') VALUE (' . implode(',', $value_arr) . ')';
                                                $db->setQuery($query);
                                                $db->execute();
                                            }
                                        }


                                        $instance_price_data = array();
                                        if ($instance_content_prices->length > 0) {
                                            foreach ($instance_content_prices as $key => $instance_content_price) {
                                                // var_dump($key);
                                                $dom_instance_price = $instance_content_price->childNodes;
                                                foreach ($dom_instance_price as $k => $v) {
                                                    if ($v instanceof DOMElement) {
                                                        if ($v->tagName == 'price_id') {
                                                            // continue;
                                                            $instance_price_data[$key]['old_price_id'] = $v->nodeValue;
                                                        } elseif ($v->tagName == 'fk_eid') {
                                                            $instance_price_data[$key][$v->tagName] = $entityAssocArr[$v->nodeValue];
                                                            $new_eid = $entityAssocArr[$v->nodeValue];
                                                        } elseif ($v->tagName == 'fk_eiid') {
                                                            $instance_price_data[$key][$v->tagName] = $instance->eiid;
                                                        } elseif ($v->tagName == 'fk_fid') {
                                                            // var_dump($v->nodeValue);
                                                            $instance_price_data[$key][$v->tagName] = self::getAssocFid($fieldsAssocArr, $v->nodeValue);
                                                        } else {
                                                            $instance_price_data[$key][$v->tagName] = $v->nodeValue;
                                                        }
                                                        // var_dump($k);
                                                        // var_dump($v);
                                                    }
                                                }

                                                // var_dump($dom_instance_price);
                                            }
                                        }
                                        // var_dump($instance_price_data);
                                        // exit;
                                        if (isset($instance_data) && !empty($instance_data)) {
                                            $query = "UPDATE #__os_cck_content_entity_$new_eid SET ";
                                            // var_dump($instance_data);
                                            $params_arr = array();
                                            foreach ($instance_data as $k => $v) {
                                                if ((stripos($k, 'imagefield_') !== false && stripos($k, '_fid') !== false) ||
                                                    (stripos($k, 'filefield_') !== false && stripos($k, '_fid') !== false) ||
                                                    (stripos($k, 'galleryfield_') !== false && stripos($k, '_fid') !== false)) {

                                                    if ($v != '' && isset($filesAssocArr[$v])) {
                                                        $v = $filesAssocArr[$v];
                                                    }
                                                }
                                                if ($v == '') {
                                                    continue;
                                                }
                                                $params_arr[] = " $k = " . $db->quote($v, true) . " ";
                                            }
                                            // var_dump($params_arr);
                                            if(!empty($params_arr)){
                                                $query .= implode(',', $params_arr);
                                                $query .= " WHERE fk_eiid = $instance->eiid";
                                                $db->setQuery($query);
                                                try {
                                                    $db->execute();
                                                } catch (Exception $e) {
                                                    var_dump($fieldsAssocArr);
                                                    var_dump($instance_data);
                                                    echo $e->getMessage();
                                                    echo $query;
                                                    exit;
                                                }
                                            }
                                        }



                                        if (!empty($instance_price_data)) {
                                            foreach ($instance_price_data as $single_price) {
                                                $query = "INSERT INTO #__os_cck_content_instances_price ";
                                                $params_arr = array();
                                                $value_arr = array();
                                                foreach ($single_price as $k => $v) {
                                                    if( $k == 'old_price_id'){
                                                        $old_price_id = $v ;
                                                        continue;
                                                    }
                                                    $params_arr[] = $k;
                                                    $value_arr[] = '"' . $v . '"';
                                                }
                                                $query .= '(' . implode(',', $params_arr) . ') VALUE (' . implode(',', $value_arr) . ')';
                                                $db->setQuery($query);
                                                $db->execute();
                                    
                                                $new_price_id = $db->insertid();
                                                $contentInstancesPriceAssocArr[$old_price_id] = $new_price_id;

                                            }
                                        }

                                        if (!empty($instance_parent)) {

                                            foreach ($instance_parent as $single_parent) {
                                                $dom_single_parent = $single_parent->childNodes;
                                                $parentChildArrTemp = array();
                                                foreach ($dom_single_parent as $k => $v) {
                                                    if ($v instanceof DOMElement) {
                                                        $parentChildArrTemp[$v->tagName] = $v->nodeValue;
//                                                     var_dump($k);
//                                                     var_dump($v);
                                                    }
                                                }
                                                if (!empty($parentChildArrTemp)) {
                                                    $parentChildArr[] = $parentChildArrTemp;
                                                }
//                                            var_dump($single_parent);
//                                            $query = "INSERT INTO #__os_cck_content_instances_price ";
//                                            $params_arr = array();
//                                            $value_arr = array();
//                                            foreach($single_parent as $k => $v){
//                                                $params_arr[] = $k;
//                                                $value_arr[] = '"'.$v.'"';
//                                            }
//                                            var_dump($single_parent->nodeValue);
//                                            var_dump($value_arr);

//                                            $query .= '('.implode(',', $params_arr).') VALUE ('. implode(',', $value_arr).')';
//                                            $db->setQuery($query);
//                                            $db->execute();
                                            }
                                        }
                                        
                                        
                                        if ($instance_request->length > 0) {
                                            foreach ($instance_request as $key => $request){
                                                $dom_request = $request->childNodes;
                                                $instanceRequestsArrTemp = array();
                                                foreach ($dom_request as $k => $v) {
                                                    if ($v instanceof DOMElement) {
                                                        
                                                        $instanceRequestsArrTemp[$key][$v->tagName] = $v->nodeValue;

                                                    }
                                                }
                                                if (!empty($instanceRequestsArrTemp)) {
                                                    $instanceRequestsArr[] = $instanceRequestsArrTemp;
                                                }
//                                                var_dump($request);
                                            }

                                        }
                                        
//                                        if (!empty($instance_request)) {
//
//                                            foreach ($instance_request as $single_request) {
//                                                $dom_single_request = $single_request->childNodes;
//                                                $instanceRequestsArrTemp = array();
//                                                foreach ($dom_single_parent as $k => $v) {
//                                                    if ($v instanceof DOMElement) {
//                                                        $instanceRequestsArrTemp[$v->tagName] = $v->nodeValue;
////                                                     var_dump($k);
////                                                     var_dump($v);
//                                                    }
//                                                }
//                                                if (!empty($instanceRequestsArrTemp)) {
//                                                    $instanceRequestsArr[] = $instanceRequestsArrTemp;
//                                                }
////                                            
//                                            }
//                                        }


                                        // $instance_content_temp = $val->item(0);
                                        // var_dump($instance_content_temp); exit;
                                        // $instance_content_dom = $instance_content_temp->getElementsByTagname('instance_content');
                                        // var_dump($instance_content_dom);
                                        // $instance_content_temp = $instancies->item(0);
                                        // $instancies = $instancies->getElementsByTagname('instance');
                                        // var_dump($instance);
                                    }
                                }
                                }
//                                var_dump($instancies);
                            }

                            $parentChildAssocArr = array();
                        //    var_dump($parentChildArr);
                            if(!empty($parentChildArr)){
                                // echo '111111111111111111111';
                                $i = 0;
                                foreach ($parentChildArr as $pCh){

                                    // var_dump($pCh);
                                    if(isset($instanciesAssocArr[$pCh['fid_child']])){
                                        // echo '222222222222';
                                        $parentChildAssocArr[$i][$pCh['media_type']] = array();
                                        $parentChildAssocArr[$i][$pCh['media_type']]['fid_parent'] = $instanciesAssocArr[$pCh['fid_parent']];
                                        $parentChildAssocArr[$i][$pCh['media_type']]['fid_child'] = $instanciesAssocArr[$pCh['fid_child']];

                                        $media_type = str_replace('e-p-ch-', '', $pCh['media_type']);
                                        $media_type = explode('_', $media_type);
                                        $new_media_type = 'e-p-ch-' . $entityAssocArr[$media_type[0]] . '_' . $media_type[1];
                                        $parentChildAssocArr[$i][$pCh['media_type']]['media_type'] = $new_media_type;
                                    }else{
                                        $parentChildAssocArr[$i][$pCh['media_type']] = array();
                                        $parentChildAssocArr[$i][$pCh['media_type']]['fid_parent'] = $pCh['fid_parent'];
                                        $parentChildAssocArr[$i][$pCh['media_type']]['fid_child'] = $pCh['fid_child'];

                                        $media_type = str_replace('e-p-ch-', '', $pCh['media_type']);
                                        $media_type = explode('_', $media_type);
                                        $new_media_type = 'e-p-ch-' . $entityAssocArr[$media_type[0]] . '_' . $media_type[1];
                                        $parentChildAssocArr[$i][$pCh['media_type']]['media_type'] = $new_media_type;
                                    }
                                //    var_dump($new_media_type);
                                    $i++;
                                }
                            }
                            
                            $query = '';
                            if(!empty($instanceRequestsArr)){
                                foreach($instanceRequestsArr as $inst_req){
                                    if(is_array($inst_req)){
                                        foreach($inst_req as $temp_req){
                                            $fid_parent = (isset($instanciesAssocArr[$temp_req['fid_parent']])) ? $instanciesAssocArr[$temp_req['fid_parent']] : false;
                                            $fid_child = (isset($instanciesAssocArr[$temp_req['fid_child']])) ? $instanciesAssocArr[$temp_req['fid_child']] : false;
                                            $media_type = $temp_req['media_type'];
                                            if(!$fid_parent || !$fid_child) continue;
                                            
                                            
                                            if($query ===  "")  $query = "INSERT INTO #__os_cck_child_parent_connect(fid_parent,fid_child,media_type) VALUE(" . $fid_parent . "," . $fid_child . ",'" . $media_type . "')";
                                            else $query = $query .",(" . $fid_parent . "," . $fid_child . ",'" . $media_type . "')";
                                            
//                                            var_dump($fid_parent);
//                                            var_dump($fid_child);
                                            
                                            
                                        }
                                        if($query !==  "" && strlen($query) > 50000 )  {
                                            $db->setQuery($query);
                                            $db->execute();
                                            $query = "" ;
                                        }
                                    }
                                    
                                }
                                
                                
                            }
//                            var_dump($query);
                            if($query !==  "")  {
                                try {
                                    $db->setQuery($query);
                                    $db->execute();
                                } catch (Exception $exc) {
                                    echo $query; exit;
                                }

                                
                                $query = "" ;
                            }
//                            var_dump($instanceRequestsArr); exit;
                            
        //                     ini_set('xdebug.var_display_max_depth', -1);
        // ini_set('xdebug.var_display_max_children', -1);
        // ini_set('xdebug.var_display_max_data', -1);
        //                     var_dump($parentChildAssocArr);

                            foreach($entityAssocArr as $old_entity => $new_entity){

                                $query = "SELECT l.lid, l.type, l.params, l.custom_fields, lh.layout_html, l.title FROM #__os_cck_layout as l 
                                            LEFT JOIN #__os_cck_layout_html as lh ON l.lid = lh.fk_lid
                                            WHERE l.fk_eid = '$new_entity' AND (l.type = 'add_instance' OR l.type = 'instance' OR l.type = 'search') AND lh.bootstrap = '3'";
                                $db->setQuery($query);
                                try {
                                    $layouts = $db->loadObjectList();
                                }catch (Exception $e){
                                    echo $query;
                                    exit;
                                }
                                if(!empty($layouts)){
                                    foreach ($layouts as $lay){
                                        
                                        $lParams = unserialize($lay->params);
                                        // var_dump($lParams);
                                        $new_lParams = $lParams;
                                        $lay->layout_html = urldecode($lay->layout_html);
                                        $child_entities = (isset($lParams['child_entities'])) ? $lParams['child_entities'] : '';
                                        $new_child_enteties = $child_entities;
                                        // var_dump($lay);
                                        
                                        if(!empty($child_entities)) {
                                            
                                            foreach ($child_entities as $key => $child_entity){
                                                
                                                if(is_object($child_entity)) $child_entity = (array) $child_entity;
//                                                var_dump($child_entity);
                                                $new_child_entity = $child_entity;
                                                if($lay->type == 'add_instance'){
                                                    if(is_array($child_entity)){
                                                        $old_mask = $child_entity['data_field_name'];
                                                        // var_dump($child_entity);
                                                    }else{
                                                        $old_mask = $child_entity->data_field_name;
                                                        // var_dump($child_entity); exit;
                                                        // continue;
                                                    }
                                                    // $old_mask = $child_entity['data_field_name'];

                                                }elseif($lay->type == 'instance' || $lay->type == 'search'){
                                                    if(is_array($child_entity)){
                                                        if(isset($child_entity['child_eiid'])){
                                                            $old_mask = $child_entity['child_eiid'];
                                                        }else{
                                                            $old_mask = $child_entity['data_field_name'];
                                                        }
                                                        // var_dump($child_entity);
                                                    }else{
                                                        continue;
                                                    }
                                                }
                                                // if($lay->title == 'Show mark'){
                                                //     var_dump($parentChildAssocArr);
                                                //     // var_dump($parentChildAssocArr);
                                                // }
                                                // var_dump($parentChildAssocArr);

                                                foreach($parentChildAssocArr as $key2 => $pCh){
                                                    if(!isset($parentChildAssocArr[$key2][$old_mask]) && isset($entityAssocArr[$child_entity['childEntityId']])){
                                                        
                                                        
                                                        $media_type = str_replace('e-p-ch-', '', $old_mask);
                                                        $media_type = explode('_', $media_type);
                                                        $new_media_type = 'e-p-ch-' . $entityAssocArr[$media_type[0]] . '_' . $media_type[1];
                                                        $parentChildAssocArr[$key2][$old_mask]['media_type'] = $new_media_type;

                                                        
                                                    }
                                                
                                                    if(stripos($lay->layout_html, '{|'.$old_mask) !== false && isset($parentChildAssocArr[$key2][$old_mask])){
                                                        // if($lay->title == 'Show mark'){
                                                        //     var_dump($old_mask);
                                                        //     var_dump($parentChildAssocArr[$key2][$old_mask]);
                                                        // }
    //                                                    echo '111111111111111111'; exit;
                                                        if($lay->type == 'add_instance'){
                                                            $lay->layout_html = str_replace('hide-child-entity-alias-'.$old_mask, 'hide-child-entity-alias-'.$parentChildAssocArr[$key2][$old_mask]['media_type'], $lay->layout_html);
                                                            $lay->layout_html = str_replace('entityid="'.$child_entity['childEntityId'].'"', 'entityid="'.$entityAssocArr[$child_entity['childEntityId']].'"', $lay->layout_html);
                                                            $old_fids = explode(',', $child_entity['childEntityFields']);
                                                            $new_fids = array();
                                                            if(!empty($old_fids)){
                                                                foreach ($old_fids as $old_fid){
                                                                    $new_fid = $old_fid;
                                                                    foreach ($fieldsAssocArr as $fa){
                                                                        if($fa['old_fid'] == $old_fid){
                                                                            $new_fid = $fa['new_fid'];
                                                                        }
                                                                    }
                                                                    $new_fids[] = $new_fid;
                                                                }
                                                            }
                                                            if(!empty($new_fids)){
                                                                $new_fids = implode(',', $new_fids);
                                                            }
                                                            $lay->layout_html = str_replace('child_entity="'.$child_entity['childEntityFields'].'"', 'child_entity="'.$new_fids.'"', $lay->layout_html);
                                                            $lay->layout_html = str_replace('data-field-name="'.$old_mask.'"', 'data-field-name="'.$parentChildAssocArr[$key2][$old_mask]['media_type'].'"', $lay->layout_html);
                                                            $lay->layout_html = str_replace($old_mask.'_', $parentChildAssocArr[$key2][$old_mask]['media_type'].'_', $lay->layout_html);
                                                            $lay->layout_html = str_replace('{|'.$old_mask.'|}', '{|'.$parentChildAssocArr[$key2][$old_mask]['media_type'].'|}', $lay->layout_html);
                                                            $lay->layout_html = str_replace('fi_Params_'.$old_mask, 'fi_Params_'.$parentChildAssocArr[$key2][$old_mask]['media_type'], $lay->layout_html);
                                                            $new_child_entity['childEntityId'] = $entityAssocArr[$child_entity['childEntityId']];
                                                            $new_child_entity['childEntityFields'] = $new_fids;
                                                            $new_child_entity['data_field_name'] = $parentChildAssocArr[$key2][$old_mask]['media_type'];
                                                            $new_child_entity['entity_alias'] = $child_entity['entity_alias'];
                                                            $new_child_enteties[$key] = $new_child_entity;
                                                            $new_fParams = array();
                                                            foreach ($new_lParams['fields'] as $k => $lp){
                                                        //    var_dump($k);
                                                        //    var_dump($old_mask);
                                                                if(stripos($k, 'order_by_'.$old_mask) !== false) {
                                                                    $new_lp = self::replaceFieldMasks($fieldsAssocArr, $lp);
                                                                    $new_key = str_replace('_'.$old_mask, '_'.$parentChildAssocArr[$key2][$old_mask]['media_type'], $k);
                                                                    $new_fParams[$new_key] = $new_lp;
                                                                }elseif(stripos($k, '_'.$old_mask) !== false){
                                                                    $new_key = str_replace('_'.$old_mask, '_'.$parentChildAssocArr[$key2][$old_mask]['media_type'], $k);
                                                                    $new_fParams[$new_key] = $lp;
                                                                }elseif(stripos($k, $old_mask.'_') !== false){
                                                                    $new_key = str_replace($old_mask.'_', $parentChildAssocArr[$key2][$old_mask]['media_type'].'_', $k);
                                                                    $new_fParams[$new_key] = $lp;
                                                                }elseif($k == $old_mask){
                                                                    $new_key = str_replace($old_mask, $parentChildAssocArr[$key2][$old_mask]['media_type'], $k);
                                                                    $new_fParams[$new_key] = $lp;
                                                                }else{
                                                                    $new_fParams[$k] = $lp;
                                                                }
                                                            }
                                                            $new_lParams['fields'] = $new_fParams;
                                                        }elseif($lay->type == 'instance' || $lay->type == 'search'){
                                                            $old_fid = $child_entity['childEntityFields'];
                                                            $new_fid = $old_fid;
                                                            foreach ($fieldsAssocArr as $fa){
                                                                if($fa['old_fid'] == $old_fid){
                                                                    $new_fid = $fa['new_fid'];
                                                                }
                                                            }
                                                            $tmp_old_mask = substr($old_mask, 0, strlen($old_mask) - strlen('_'.$old_fid));
                                                            
                                                            if(strripos($old_mask, '_'.$old_fid) == strlen($old_mask) - strlen('_'.$old_fid) && substr_count($tmp_old_mask, "_") > 0){
                                                                $old_show_mask = $old_mask;
                                                            }else{
                                                                $old_show_mask = $old_mask . '_' . $old_fid;
                                                            }
                                                            
                                                            $new_show_mask = $parentChildAssocArr[$key2][$old_mask]['media_type'] . '_' . $new_fid;
                                                            // if($lay->title == 'Show training - menu'){
                                                            //     // var_dump($parentChildAssocArr);
                                                            //     echo '111111111111111';
                                                            //     var_dump($old_show_mask);
                                                            //     var_dump($new_show_mask);
                                                            //     var_dump(strripos($old_mask, '_'.$old_fid));
                                                            //     var_dump(strlen($old_mask));
                                                            //     // var_dump($parentChildAssocArr);
                                                            // }
                                                            // var_dump($old_show_mask);
                                                            // var_dump($new_show_mask);
                                                            $lay->layout_html = str_replace('hide-child-entity-alias-'.$old_show_mask, 'hide-child-entity-alias-'.$new_show_mask, $lay->layout_html);
                                                            $lay->layout_html = str_replace('hide-field-name-'.$old_show_mask, 'hide-field-name-'.$new_show_mask, $lay->layout_html);
                                                            $lay->layout_html = str_replace('entityid="'.$child_entity['childEntityId'].'"', 'entityid="'.$entityAssocArr[$child_entity['childEntityId']].'"', $lay->layout_html);

                                                            $lay->layout_html = str_replace('child_entity="'.$old_fid.'"', 'child_entity="'.$new_fid.'"', $lay->layout_html);
                                                            $lay->layout_html = str_replace('data-field-name="'.$old_show_mask.'"', 'data-field-name="'.$new_show_mask.'"', $lay->layout_html);
                                                            $lay->layout_html = str_replace('child_eiid="'.$old_mask.'"', 'child_eiid="'.$parentChildAssocArr[$key2][$old_mask]['media_type'].'"', $lay->layout_html);
                                                            $lay->layout_html = str_replace('fi_Params_'.$old_show_mask, 'fi_Params_'.$new_show_mask, $lay->layout_html);
                                                            $lay->layout_html = str_replace('fi_'.$old_show_mask.'_', 'fi_'.$new_show_mask.'_', $lay->layout_html);
                                                            $lay->layout_html = str_replace('{|'.$old_show_mask.'|}', '{|'.$new_show_mask.'|}', $lay->layout_html);
                                                            $new_child_entity['childEntityId'] = $entityAssocArr[$child_entity['childEntityId']];
                                                            $new_child_entity['childEntityFields'] = $new_fid;
                                                            $new_child_entity['data_field_name'] = $new_show_mask;
                                                            $new_child_entity['child_eiid'] = $parentChildAssocArr[$key2][$old_mask]['media_type'];
                                                            $new_child_enteties[$key] = $new_child_entity;
                                                            $new_fParams = array();
                                                            
                                                            foreach ($new_lParams['fields'] as $k => $lp){
                                                                // var_dump($k);
                                                                // var_dump($old_show_mask);
                                                                if(stripos($k, '_'.$old_show_mask) !== false){
                                                                    $new_key = str_replace('_'.$old_show_mask, '_'.$new_show_mask, $k);
                                                                    $new_fParams[$new_key] = $lp;
                                                                }elseif(stripos($k, $old_show_mask.'_') !== false){
                                                                    $new_key = str_replace($old_show_mask.'_', $new_show_mask.'_', $k);
                                                                    $new_fParams[$new_key] = $lp;
                                                                }elseif($k == $old_show_mask){
                                                                    $new_key = str_replace($old_show_mask, $new_show_mask, $k);
                                                                    $new_fParams[$new_key] = $lp;
                                                                }else{
                                                                    $new_fParams[$k] = $lp;
                                                                }
                                                            }
                                                            $new_lParams['fields'] = $new_fParams;
                                                        }
                                                    }
                                                }
                                            }

//                                            var_dump($child_entities);
                                            // foreach ($parentChildAssocArr as $old_meta_type => $newPCh) {

                                            // }
                                            foreach($new_child_enteties as $k => $new_child_entiti){
                                                $new_child_enteties[$k] = (object)$new_child_entiti;
                                            }

//                                            foreach ($new_lParams as $k => $lp){
//                                                if(stripos($k, 'e-p-ch') !== false){
//                                                    var_dump($k);
//                                                    var_dump($fp);
//                                                }
//                                            }

                                            $new_lParams['child_entities'] = $new_child_enteties;
                                            
                                            $lParams = serialize($new_lParams);
                                            $query = "UPDATE #__os_cck_layout SET params=".$db->quote($lParams)." WHERE lid=$lay->lid";
                                            $db->setQuery($query);
                                            try {
                                                $db->execute();
                                            } catch (Exception $e) {
                                                // var_dump($new_lParams);
                                                echo $db->getQuery();
                                                echo $query;
                                                exit;
                                            }

                                            $query = "UPDATE #__os_cck_layout_html SET layout_html='".urlencode($lay->layout_html)."' WHERE fk_lid=$lay->lid AND bootstrap = '3'";
                                            $db->setQuery($query);
                                            $db->execute();
                                        }

                                      
                                    }
                                }

                            }

                            // var_dump($parentChildAssocArr);
                            $query = "" ;
                            foreach($parentChildAssocArr as $key => $pCh){
                                foreach ($pCh as $parentChildAssocSingle){
                                    if(isset($parentChildAssocSingle['fid_parent'])) {
                                        if($query ===  "")  $query = "INSERT INTO #__os_cck_child_parent_connect(fid_parent,fid_child,media_type) VALUE(" . $parentChildAssocSingle['fid_parent'] . "," . $parentChildAssocSingle['fid_child'] . ",'" . $parentChildAssocSingle['media_type'] . "')";
                                        else $query = $query .",(" . $parentChildAssocSingle['fid_parent'] . "," . $parentChildAssocSingle['fid_child'] . ",'" . $parentChildAssocSingle['media_type'] . "')";
                                    }


                                }
                                if($query !==  "" && strlen($query) > 50000 )  {
                                    $db->setQuery($query);
                                    $db->execute();
                                    $query = "" ;
                                }
                            }
                            
                            if($query !==  "" )  {
                                $db->setQuery($query);
                                $db->execute();
                            }
                            
                            
                            //replace old to new Layout_id
                            foreach($entityAssocArr as $old_entity => $new_entity) {
                                $query = "SELECT l.lid, l.params, lh.layout_html, l.custom_fields FROM #__os_cck_layout as l 
                                                        LEFT JOIN #__os_cck_layout_html as lh ON l.lid = lh.fk_lid
                                                        WHERE l.fk_eid = '$new_entity' AND lh.bootstrap = '3'";
                                $db->setQuery($query);
                                try {
                                    $layouts = $db->loadObjectList();
                                } catch (Exception $e) {
                                    echo $query;
                                    exit;
                                }
                                if(!empty($layouts)){
                                    foreach($layouts as $lay){
                                        if(in_array($lay->lid, $notCreatedLayoutArr)) continue;
                                        $lay->layout_html = urldecode($lay->layout_html);
                                        $lParams = unserialize($lay->params);
                                        $show_request_layout_button_name = (isset($lParams['views']['show_request_layout_button_name'])) ? $lParams['views']['show_request_layout_button_name'] : array();
                                        $show_request_layout_alias = (isset($lParams['views']['show_request_layout_alias'])) ? $lParams['views']['show_request_layout_alias'] : array();
                                        $request_layout_php_show = (isset($lParams['views']['request_layout_php_show'])) ? $lParams['views']['request_layout_php_show'] : array();
                                        $show_request_layout = (isset($lParams['views']['show_request_layout'])) ? $lParams['views']['show_request_layout'] : array();
                                        $show_type_request_layout = (isset($lParams['views']['show_type_request_layout'])) ? $lParams['views']['show_type_request_layout'] : array();
                                        $request_layout_sql_show = (isset($lParams['views']['request_layout_sql_show'])) ? $lParams['views']['request_layout_sql_show'] : array();
                                        $sql_where_type = (isset($lParams['views']['sql_where_type'])) ? $lParams['views']['sql_where_type'] : array();
                                        $custom_code = unserialize($lay->custom_fields);
//                                        if(!empty($custom_code)){
//                                            var_dump($custom_code); //exit;
//                                        }
//                                        $layout_params['custom_fields']
                                        
                                        $replaced_layouts = array();
                                        
                                        foreach($layoutAssocGlobalArr as $old_lid => $new_lid){
                                            if(in_array($old_lid, $replaced_layouts)) continue;

                                            if(!in_array($old_lid, $replaced_layouts) && isset($lParams['views']['auto_custom_'.$old_lid])){
                                                $lParams['views']['auto_custom_'.$new_lid] = $lParams['views']['auto_custom_'.$old_lid];
                                                unset($lParams['views']['auto_custom_'.$old_lid]);

                                            }
                                            if(isset($lParams['views']['instance_grid_'.$old_lid])){
                                                $lParams['views']['instance_grid_'.$new_lid] = $lParams['views']['instance_grid_'.$old_lid];
                                                unset($lParams['views']['instance_grid_'.$old_lid]);
                                                $replaced_layouts[] = $new_lid;
                                            }
                                            if(isset($lParams['views']['count_inst_columns_'.$old_lid])){
                                                $lParams['views']['count_inst_columns_'.$new_lid] = $lParams['views']['count_inst_columns_'.$old_lid];
                                                unset($lParams['views']['count_inst_columns_'.$old_lid]);
                                            }
                                            if(isset($lParams['views']['lay_min_width_'.$old_lid])){
                                                $lParams['views']['lay_min_width_'.$new_lid] = $lParams['views']['lay_min_width_'.$old_lid];
                                                unset($lParams['views']['lay_min_width_'.$old_lid]);
                                            }
                                            if(isset($lParams['views']['space_between_'.$old_lid])){
                                                $lParams['views']['space_between_'.$new_lid] = $lParams['views']['space_between_'.$old_lid];
                                                unset($lParams['views']['space_between_'.$old_lid]);
                                            }
                                            if(isset($lParams['views']['resolition_one_'.$old_lid])){
                                                $lParams['views']['resolition_one_'.$new_lid] = $lParams['views']['resolition_one_'.$old_lid];
                                                unset($lParams['views']['resolition_one_'.$old_lid]);
                                            }
                                            if(isset($lParams['views']['resolition_two_'.$old_lid])){
                                                $lParams['views']['resolition_two_'.$new_lid] = $lParams['views']['resolition_two_'.$old_lid];
                                                unset($lParams['views']['resolition_two_'.$old_lid]);
                                            }
                                            if(isset($lParams['views']['resolition_three_'.$old_lid])){
                                                $lParams['views']['resolition_three_'.$new_lid] = $lParams['views']['resolition_three_'.$old_lid];
                                                unset($lParams['views']['resolition_three_'.$old_lid]);
                                            }
                                            if(isset($lParams['views']['resolition_four_'.$old_lid])){
                                                $lParams['views']['resolition_four_'.$new_lid] = $lParams['views']['resolition_four_'.$old_lid];
                                                unset($lParams['views']['resolition_four_'.$old_lid]);
                                            }
                                            if(isset($lParams['fields']['Params_l'.$old_lid])){
                                                $lParams['fields']['Params_l'.$new_lid] = $lParams['fields']['Params_l'.$old_lid];
                                                unset($lParams['fields']['Params_l'.$old_lid]);
                                            }
                                        }
                                        $new_show_request_layout_button_name = array();
                                        foreach($show_request_layout_button_name as $lid => $val){
                                            if(isset($layoutAssocGlobalArr[$lid])){
//                                                var_dump($layoutAssocGlobalArr[$lid]);
//                                                var_dump($val);
                                                $new_show_request_layout_button_name[$layoutAssocGlobalArr[$lid]] = $val;
                                            }
                                        }

                                        $new_show_request_layout_alias = array();
                                        foreach($show_request_layout_alias as $lid => $val){
                                            if(isset($layoutAssocGlobalArr[$lid])){
                                                $new_show_request_layout_alias[$layoutAssocGlobalArr[$lid]] = $val;
                                                $lay->layout_html = str_replace($lid . '-label-hidden', $layoutAssocGlobalArr[$lid] . '-label-hidden', $lay->layout_html);
                                                $lay->layout_html = str_replace('data-field-name="' . $lid . '"', 'data-field-name="' . $layoutAssocGlobalArr[$lid] . '"', $lay->layout_html);
                                                $lay->layout_html = str_replace('{|l-' . $lid . '|}', '{|l-' . $layoutAssocGlobalArr[$lid] . '|}', $lay->layout_html);
                                                $lay->layout_html = str_replace('fi_Params_l' . $lid, 'fi_Params_l' . $layoutAssocGlobalArr[$lid], $lay->layout_html);
                                            }
                                        }

                                        $new_request_layout_php_show = array();
                                        foreach($request_layout_php_show as $lid => $val){
                                            if(isset($layoutAssocGlobalArr[$lid])){
                                                $new_request_layout_php_show[$layoutAssocGlobalArr[$lid]] = $val;
                                            }
                                        }

                                        $new_request_layout_sql_show = array();
                                        foreach($request_layout_sql_show as $lid => $val){
                                            if(isset($layoutAssocGlobalArr[$lid])){
                                                $new_request_layout_sql_show[$layoutAssocGlobalArr[$lid]] = $val;
                                            }
                                        }

                                        $new_sql_where_type = array();
                                        foreach($sql_where_type as $lid => $val){
                                            if(isset($layoutAssocGlobalArr[$lid])){
                                                $new_sql_where_type[$layoutAssocGlobalArr[$lid]] = $val;
                                            }
                                        }
                                        
                                        $new_show_request_layout = array();
                                        foreach($show_request_layout as $lid => $val){
                                            if(isset($layoutAssocGlobalArr[$lid])){
                                                $new_show_request_layout[$layoutAssocGlobalArr[$lid]] = $val;

                                            }
                                        }

                                        $new_show_type_request_layout = array();
                                        foreach($show_type_request_layout as $lid => $val){
                                            if(isset($layoutAssocGlobalArr[$lid])){
                                                $new_show_type_request_layout[$layoutAssocGlobalArr[$lid]] = $val;
                                            }
                                        }
                                        
                                        $new_custom_code = array();
                                        if(!empty($custom_code)){
                                            foreach($custom_code as $custom_code_key => $cc){
                                                $custom_code_text = $cc['custom_code_field_'.$custom_code_key.'_custom_code'];
                                                preg_match_all('#{|layout_id-[0-9]*|}#', $custom_code_text, $matches);
                                                if(!empty($matches)){
                                                    foreach ($matches as $res){
                                                        foreach($res as $str){
                                                            if(stripos($str, 'layout_id') !== false){
                                                                $str_arr = explode('-', $str);
                                                                if(isset($layoutAssocArr[$str_arr[1]])){
                                                                    $custom_code_text = str_replace('{|layout_id-'.$str_arr[1].'|}', '{|layout_id-'.$layoutAssocArr[$str_arr[1]]['new_lid'].'|}', $custom_code_text);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                                preg_match_all('#{|instance_id-[0-9]*|}#', $custom_code_text, $matches);
                                                if(!empty($matches)){
                                                    foreach ($matches as $res){
                                                        foreach($res as $str){
                                                            if(stripos($str, 'instance_id') !== false){
                                                                $str_arr = explode('-', $str);
                                                                if(isset($instanciesAssocArr[$str_arr[1]])){
                                                                    $custom_code_text = str_replace('{|instance_id-'.$str_arr[1].'|}', '{|instance_id-'.$instanciesAssocArr[$str_arr[1]].'|}', $custom_code_text);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                                preg_match_all('#{|category_id-[0-9]*|}#', $custom_code_text, $matches);
                                                if(!empty($matches)){
                                                    foreach ($matches as $res){
                                                        foreach($res as $str){
                                                            if(stripos($str, 'category_id') !== false){
                                                                $str_arr = explode('-', $str);
                                                                if(isset($categoriesAssocArr[$str_arr[1]])){
                                                                    $custom_code_text = str_replace('{|category_id-'.$str_arr[1].'|}', '{|category_id-'.$categoriesAssocArr[$str_arr[1]].'|}', $custom_code_text);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                $custom_code[$custom_code_key]['custom_code_field_'.$custom_code_key.'_custom_code'] = $custom_code_text;
                                                $new_custom_code[$custom_code_key] = $custom_code[$custom_code_key];
                                            }
                                            
                                            
                                            
                                        }

                                        $new_custom_code = serialize($new_custom_code);
//$custom_code = unserialize($lay->custom_fields);
                                        if(isset($lParams['views']['show_request_layout_button_name'])){
                                            $lParams['views']['show_request_layout_button_name'] = $new_show_request_layout_button_name;
                                        }
                                        if(isset($lParams['views']['show_request_layout_alias'])){
                                            $lParams['views']['show_request_layout_alias'] = $new_show_request_layout_alias;
                                        }
                                        if(isset($lParams['views']['request_layout_php_show'])){
                                            $lParams['views']['request_layout_php_show'] = $new_request_layout_php_show;
                                        }
                                        if(isset($lParams['views']['request_layout_sql_show'])){
                                            $lParams['views']['request_layout_sql_show'] = $new_request_layout_sql_show;
                                        }
                                        if(isset($lParams['views']['sql_where_type'])){
                                            $lParams['views']['sql_where_type'] = $new_sql_where_type;
                                        }
                                        
                                        if(isset($lParams['views']['show_request_layout'])){
                                            $lParams['views']['show_request_layout'] = $new_show_request_layout;
                                        }
                                        if(isset($lParams['views']['show_type_request_layout'])){
                                            $lParams['views']['show_type_request_layout'] = $new_show_type_request_layout;
                                        }
                                        
                                        if(isset($lParams['views']['all_instance_layout']) && $lParams['views']['all_instance_layout'] != -1 && isset($layoutAssocGlobalArr[$lParams['views']['all_instance_layout']]) && $layoutAssocGlobalArr[$lParams['views']['all_instance_layout']]){
                                            // if(isset($lParams['views']['all_instance_layout'])){
                                            //     var_dump($lParams['views']['all_instance_layout']);
                                            //     var_dump($layoutAssocGlobalArr[$lParams['views']['all_instance_layout']]);
                                            // }
                                            $lParams['views']['all_instance_layout'] = $layoutAssocGlobalArr[$lParams['views']['all_instance_layout']];
                                        }
                                        if(isset($lParams['views']['instance_layout']) && $lParams['views']['instance_layout'] != -1 && isset($layoutAssocGlobalArr[$lParams['views']['instance_layout']]) && $layoutAssocGlobalArr[$lParams['views']['instance_layout']]){
                                            $lParams['views']['instance_layout'] = $layoutAssocGlobalArr[$lParams['views']['instance_layout']];
                                        }
                                        if(isset($lParams['views']['subcategories_layout']) && $lParams['views']['subcategories_layout'] != -1 && isset($layoutAssocGlobalArr[$lParams['views']['subcategories_layout']]) && $layoutAssocGlobalArr[$lParams['views']['subcategories_layout']]){
                                            $lParams['views']['subcategories_layout'] = $layoutAssocGlobalArr[$lParams['views']['subcategories_layout']];
                                        }
                                        foreach ($lParams['fields'] as $k => $f){
                                            if( ( stripos($k, '_instance_layout') !== false 
                                                || stripos($k, '_category_layout') !== false 
                                                || (stripos($k, '_cck_pdf_button') !== false) && $k != 'access_cck_pdf_button' ) ){
                                                if(isset($layoutAssocGlobalArr[$f])){
                                                    $lParams['fields'][$k] = $layoutAssocGlobalArr[$f];
                                                }
                                            }elseif(stripos($k, '_php_show') && !is_array($f) && $f != ''){
                                                $f = self::replaceFieldMasks($fieldsAssocArr, $f);
                                                if(isset($layoutAssocGlobalArr[$f])){
                                                    $lParams['fields'][$k] = $layoutAssocGlobalArr[$f];
                                                }
                                            }
                                        }
                                        $lParams = serialize($lParams);
                                        $query = "UPDATE #__os_cck_layout SET params=".$db->Quote($lParams).", custom_fields=".$db->Quote($new_custom_code)." WHERE lid=$lay->lid";
                                        $db->setQuery($query);

                                        try {
                                            $db->execute();
                                        }catch (Exception $e){
                                            echo $query; exit;
                                        }

                                        $query = "UPDATE #__os_cck_layout_html SET layout_html='".urlencode($lay->layout_html)."' WHERE fk_lid=$lay->lid AND bootstrap = '3'";
                                        $db->setQuery($query);
                                        $db->execute();
//                                        var_dump($new_show_request_layout_button_name);
                                    }
                                }
                            }

// echo "<br> Start import categories: "; flush();  if( ob_get_level() > 0 ) ob_flush(); //fix error: Maximum execution time 
set_time_limit( 300 );
                            $categories_list = $dom->getElementsByTagname('categories');
                            $categories_temp = $categories_list->item(0);
                            if($categories_temp){
                                $categories = $categories_temp->getElementsByTagname('category');
                                $categoriesAssocArr = array();
                                $categoriesParentAssocArr = array();
                                foreach($categories as $key => $val){
                                    $dom_category = $val->childNodes;
                                    $category = new os_cckCategory($db->_db);
                                    $old_category_id = 0;
                                    $old_parent_category = 0;
                                    $old_entity = true;
                                    foreach($dom_category as $k => $v){
                                        if(property_exists($v, 'tagName')){
                                            $prop = $v->tagName;
                                            if($v->tagName == 'cid'){
                                                $old_category_id = $v->nodeValue;
                                                continue;
                                            }
                                            if($v->tagName == 'parent_id'){
                                                $old_parent_category = $v->nodeValue;
                                                continue;
                                            }
                                            if($v->tagName == 'fk_eid' && $v->nodeValue != 0){
                                                if($v->nodeValue == '0'){
                                                    $category->fk_eid = $v->nodeValue;
                                                }elseif(!isset($entityAssocArr[$v->nodeValue])){
                                                    $old_entity = false;
                                                }else{
                                                    $category->fk_eid = $entityAssocArr[$v->nodeValue];
                                                }
                                                
                                            }elseif($v->tagName == 'typeAlias'){
                                                continue;
                                            }else{
                                                $category->$prop = $v->nodeValue;
                                            }
                                        }
                                    }
                                    if(!$old_entity) continue;
                                    $category->check();
                                    $category->store();
                                    $categoriesAssocArr[$old_category_id] = $category->cid;
                                    $categoriesParentAssocArr[$old_category_id] = $old_parent_category;
                                }

                                if(!empty($categoriesParentAssocArr)){
                                    foreach ($categoriesParentAssocArr as $old_cat => $old_parent_cat){
                                        if($old_parent_cat != 0){
                                            $new_parent_cat = $categoriesAssocArr[$old_parent_cat];
                                            $new_cat = $categoriesAssocArr[$old_cat];

                                            $query = "UPDATE #__os_cck_categories SET parent_id=$new_parent_cat WHERE cid=$new_cat";
                                            $db->setQuery($query);
                                            $db->execute();
                                        }
                                    }
                                }

                                $categories_connect_list = $dom->getElementsByTagname('categories_connect');
                                $categories_connect_temp = $categories_connect_list->item(0);
                                
                                if($categories_connect_temp){
                                    $categories_connect = $categories_connect_temp->getElementsByTagname('single_connect');
                                }else{
                                    $categories_connect = array();
                                }

                                foreach ($categories_connect as $key => $val){
                                    $dom_categories_connect = $val->childNodes;
                                    $new_fk_eiid = 0;
                                    $new_fk_cid = 0;

                                    foreach($dom_categories_connect as $k => $v){
                                        if(property_exists($v, 'tagName')){

                                            if($v->tagName == 'fk_eiid'){
                                                if(isset($instanciesAssocArr[$v->nodeValue])){
                                                    $new_fk_eiid = $instanciesAssocArr[$v->nodeValue];
                                                }else{
                                                    $new_fk_eiid = '';
                                                }

                                            }
                                            if($v->tagName == 'fk_cid'){
                                                if(isset($categoriesAssocArr[$v->nodeValue])){
                                                    $new_fk_cid = $categoriesAssocArr[$v->nodeValue];
                                                }
                                            }
                                        }
                                    }
                                    if($new_fk_eiid > 0 && $new_fk_cid > 0){
                                        $query = "INSERT INTO #__os_cck_categories_connect (fk_eiid,fk_cid) VALUE('".$new_fk_eiid."','".$new_fk_cid."')";
                                        $db->setQuery($query);
                                        $db->execute();
                                    }
                                }
                            }

                            $coupons_list = $dom->getElementsByTagname('coupons');
                            $coupons_temp = $coupons_list->item(0);
                            if($coupons_temp){
                                $coupons = $coupons_temp->getElementsByTagname('coupon');
                                $couponsAssocArr = array();
                                foreach($coupons as $key => $val){
                                    $dom_coupon = $val->childNodes;
                                    $coupon = new os_cckCoupons($db->_db);
                                    $old_coupon_id = 0;
                                    foreach($dom_coupon as $k => $v){
                                        if(property_exists($v, 'tagName')){
                                            $prop = $v->tagName;
                                            if($v->tagName == 'coup_id'){
                                                $old_coupon_id = $v->nodeValue;
                                                continue;
                                            }

                                            if($v->tagName == 'entities' && $v->nodeValue != 0){
                                                if($v->nodeValue == ',-1,'){
                                                    $coupon->entities = $v->nodeValue;
                                                }else{
                                                    $old_eids = explode(',', $v->nodeValue );
                                                    $new_eids = array();
                                                    if(!empty($old_eids)){
                                                        foreach ($old_eids as $old_eid){
                                                            if( $old_eid === 0 || $old_eid == -1 ) {
                                                                $new_eids[] = $old_eid ;
                                                                continue;   
                                                            }
                                                            if( empty($old_eid) ) continue ;
                                                            if(isset($entityAssocArr[$old_eid]) ) $new_eids[] = $entityAssocArr[$old_eid] ;
                                                        }
                                                    }
                                                    if(!empty($new_eids)){
                                                        $new_eids = implode(',', $new_eids);
                                                    }
                                                    $coupon->entities = $new_eids;
                                                }
                                            }elseif($v->tagName == 'category_ids' && $v->nodeValue != 0){
                                                if($v->nodeValue == '' || $v->nodeValue == ',0,' ){
                                                    $coupon->category_ids = $v->nodeValue;
                                                }else{
                                                    $old_cids = explode(',', $v->nodeValue );
                                                    $new_cids = array();
                                                    if(!empty($old_cids)){
                                                        foreach ($old_cids as $old_cid){
                                                            if( $old_cid === 0 || $old_cid == -1 ) {
                                                                $new_cids[] = $old_cid ;
                                                                continue;   
                                                            }
                                                            if( empty($old_cid) ) continue ;
                                                            if(isset($categoriesAssocArr[$old_cid]) ) $new_cids[] = $categoriesAssocArr[$old_cid] ;
                                                        }
                                                    }
                                                    if(!empty($new_cids)){
                                                        $new_cids = implode(',', $new_cids);
                                                    }
                                                    $coupon->category_ids = $new_cids;
                                                }
                                            }elseif($v->tagName == 'typeAlias'){ 
                                                continue;
                                            }else{
                                                $coupon->$prop = $v->nodeValue;
                                            }
                                        }
                                    }

                                    $coupon->check();
                                    $coupon->store();
                                    $couponsAssocArr[$old_coupon_id] = $coupon->coup_id;
                                }
                            }


                            $rents_list = $dom->getElementsByTagname('rents');
                            $rents_temp = $rents_list->item(0);
                            if($rents_temp){
                                $rents = $rents_temp->getElementsByTagname('rent');
                                foreach($rents as $key => $val){
                                    $dom_rent = $val->childNodes;
                                    $rent = new mosCCK_rent($db->_db);
                                    foreach($dom_rent as $k => $v){
                                        if(property_exists($v, 'tagName')){
                                            $prop = $v->tagName;
                                            if($v->tagName == 'id'){
                                                continue;
                                            }elseif( $v->tagName == 'fk_eiid' || $v->tagName == 'request_id' ){
                                                if(isset($instanciesAssocArr[$v->nodeValue])){
                                                    $new_fk_eiid = $instanciesAssocArr[$v->nodeValue];
                                                }else{
                                                    $new_fk_eiid = '0';
                                                }
                                                $rent->$prop = $new_fk_eiid;
                                            }elseif( $v->tagName == 'rent_return' || $v->tagName == 'rent_until' || $v->tagName == 'rent_from' ){
                                                if(isset($v->nodeValue) && !empty($v->nodeValue) ){
                                                    $new_value = $v->nodeValue;
                                                }else{
                                                    //Value = 'NULL';
                                                    continue;    
                                                }
                                                $rent->$prop = $new_value;
                                                
                                            }elseif($v->tagName == 'typeAlias'){ 
                                                continue;
                                            }else{
                                                $rent->$prop = $v->nodeValue;
                                            }
                                        }
                                    }
                                    $rent->check();
                                    $rent->store();
                                }
                            }

                            $orders_list = $dom->getElementsByTagname('orders');
                            $orders_temp = $orders_list->item(0);
                            $ordersAssocArr = array();
                            if($orders_temp){
                                $orders = $orders_temp->getElementsByTagname('order');
                                $order_data = array();
                                foreach($orders as $key => $val){
                                    $dom_order = $val->childNodes;
                                    $old_order_id = 0;
                                    foreach($dom_order as $k => $v){
                                        if(property_exists($v, 'tagName')){
                                            if($v->tagName == 'id'){
                                                $old_order_id = $v->nodeValue;
                                                continue;
                                            }else if($v->tagName == 'fk_instance_id' || $v->tagName == 'fk_request_id' ){
                                                if(isset($instanciesAssocArr[$v->nodeValue])){
                                                    $new_fk_eiid = $instanciesAssocArr[$v->nodeValue];
                                                }else{
                                                    $new_fk_eiid = '0';
                                                }
                                                $order_data[$key][$v->tagName] = $new_fk_eiid;
                                            }else if($v->tagName == 'quantity'  ){
                                                if( $v->nodeValue > 0 ){
                                                    $new_value = $v->nodeValue;
                                                }else{
                                                    $new_value = '0';
                                                }
                                                $order_data[$key][$v->tagName] = $new_value;
                                            } else {
                                                $order_data[$key][$v->tagName] = $v->nodeValue;
                                            }
                                        }
                                    }
                                    $query = "INSERT INTO #__os_cck_orders ";
                                    $params_arr = array();
                                    $value_arr = array();
                                    foreach ($order_data[$key] as $k => $v) {
                                        $params_arr[] = $k;
                                        $value_arr[] = '"' . $v . '"';
                                    }
                                    $query .= '(' . implode(',', $params_arr) . ') VALUE (' . implode(',', $value_arr) . ')';
                                    $db->setQuery($query);
                                    $db->execute();


                                    $new_order_id = $db->insertid();
                                    $ordersAssocArr[$old_order_id] = $new_order_id;
                                }
                                unset($orders);
                                unset($order_data);
                                unset($params_arr);
                                unset($value_arr);
                            }


                            $orders_list = $dom->getElementsByTagname('orders_details');
                            $orders_temp = $orders_list->item(0);
                            if($orders_temp){
                                $orders = $orders_temp->getElementsByTagname('order_detail');
                                $order_data = array();
                                foreach($orders as $key => $val){
                                    $dom_order = $val->childNodes;
                                    foreach($dom_order as $k => $v){
                                        if(property_exists($v, 'tagName')){
                                            if($v->tagName == 'id'){
                                                $old_order_id = $v->nodeValue;
                                                continue;
                                            }else if($v->tagName == 'fk_instance_id' ){
                                                if(isset($instanciesAssocArr[$v->nodeValue])){
                                                    $new_fk_eiid = $instanciesAssocArr[$v->nodeValue];
                                                }else{
                                                    $new_fk_eiid = '0';
                                                }
                                                $order_data[$key][$v->tagName] = $new_fk_eiid;
                                            }else if($v->tagName == 'fk_order_id' ){
                                                if(isset($ordersAssocArr[$v->nodeValue])){
                                                    $new_fk_oid = $ordersAssocArr[$v->nodeValue];
                                                }else{
                                                    $new_fk_oid = '0';
                                                }
                                                $order_data[$key][$v->tagName] = $new_fk_oid;
                                            }else if( $v->tagName == 'order_price' || $v->tagName == 'quantity'  ){
                                                if( $v->nodeValue > 0 ){
                                                    $new_value = $v->nodeValue;
                                                }else{
                                                    $new_value = '0';
                                                }
                                                $order_data[$key][$v->tagName] = $new_value;
                                            }  else {
                                                $order_data[$key][$v->tagName] = $v->nodeValue;
                                            }
                                        }  
                                    }
                                    $query = "INSERT INTO #__os_cck_orders_details ";
                                    $params_arr = array();
                                    $value_arr = array();
                                    foreach ($order_data[$key] as $k => $v) {
                                        $params_arr[] = $k;
                                        $value_arr[] = "'" . $v . "'";
                                    }
                                    $query .= '(' . implode(',', $params_arr) . ') VALUE (' . implode(',', $value_arr) . ')';
                                    $db->setQuery($query);
                                    $db->execute();
                                }
                                unset($orders);
                                unset($order_data);
                                unset($params_arr);
                                unset($value_arr);
                            }

                            $orders_list = $dom->getElementsByTagname('orders_prices');
                            $orders_temp = $orders_list->item(0);
                            if($orders_temp){
                                $orders = $orders_temp->getElementsByTagname('order_price');
                                $order_data = array();
                                foreach($orders as $key => $val){
                                    $dom_order = $val->childNodes;
                                    foreach($dom_order as $k => $v){
                                        if(property_exists($v, 'tagName')){
                                            if($v->tagName == 'id'){
                                                $old_order_id = $v->nodeValue;
                                                continue;
                                            }else if($v->tagName == 'fk_order_id' ){
                                                if(isset($ordersAssocArr[$v->nodeValue])){
                                                    $new_fk_oid = $ordersAssocArr[$v->nodeValue];
                                                }else{
                                                    $new_fk_oid = '0';
                                                }
                                                $order_data[$key][$v->tagName] = $new_fk_oid;
                                            }else if($v->tagName == 'fk_price_id' ){
                                                if(isset($contentInstancesPriceAssocArr[$v->nodeValue])){
                                                    $new_fk_price_id = $contentInstancesPriceAssocArr[$v->nodeValue];
                                                }else{
                                                    $new_fk_price_id = '0';
                                                }
                                                $order_data[$key][$v->tagName] = $new_fk_price_id;
                                            }else if($v->tagName == 'fk_eid' ){
                                                if(isset($entityAssocArr[$v->nodeValue])){
                                                    $new_fk_eid = $entityAssocArr[$v->nodeValue];
                                                }else{
                                                    $new_fk_eid = '0';
                                                }
                                                $order_data[$key][$v->tagName] = $new_fk_eid;
                                            }else if($v->tagName == 'fk_eiid' ){
                                                if(isset($instanciesAssocArr[$v->nodeValue])){
                                                    $new_fk_eiid = $instanciesAssocArr[$v->nodeValue];
                                                }else{
                                                    $new_fk_eiid = '0';
                                                }
                                                $order_data[$key][$v->tagName] = $new_fk_eiid;
                                            }else if($v->tagName == 'fk_fid' ){
                                                $new_fk_fid = self::getAssocFid($fieldsAssocArr, $v->nodeValue);
                                                if( empty($new_fk_fid) ) $new_fk_fid = 0 ;
                                                $order_data[$key][$v->tagName] = $new_fk_fid;
                                            } else {
                                                $order_data[$key][$v->tagName] = $v->nodeValue;
                                            }
                                        }
                                    }
                                    $query = "INSERT INTO #__os_cck_orders_price ";
                                    $params_arr = array();
                                    $value_arr = array();
                                    foreach ($order_data[$key] as $k => $v) {
                                        $params_arr[] = $k;
                                        $value_arr[] = '"' . $v . '"';
                                    }
                                    $query .= '(' . implode(',', $params_arr) . ') VALUE (' . implode(',', $value_arr) . ')';
                                    $db->setQuery($query);
                                    try{
                                        $db->execute();
                                    }catch (RuntimeException $e) {
                                        echo "Sql errors1: ". $query ;
                                        echo $e->getMessage();
                                    }



                                }
                                unset($orders);
                                unset($order_data);
                                unset($params_arr);
                                unset($value_arr);
                            }                            



                            $galleryFolderAssocArr = array();
                            $imagesOldPath = array();
                            $videosOldPath = array();
                            $audiosOldPath = array();
                            $tracksOldPath = array();
                            $filesOldPath = array();
                            for ($i = 0; $i < $zip->numFiles; $i++) {
                                $filename = $zip->getNameIndex($i);
                                $filename_array = explode('/', $filename);
                                if(stripos($filename_array[0], 'com_os_cck') !== false && isset($filename_array[1]) && ($filename_array[1] == 'thumbnail' || $filename_array[1] == 'original')){
                                    $old_fid = str_replace('com_os_cck', '', $filename_array[0]);
                                    $new_fid = 0;
                                    foreach($fieldsAssocArr as $field){
                                        if($field['old_fid'] == $old_fid){
                                            $new_fid = $field['new_fid'];
                                        }
                                    }
                                    if($new_fid == 0) continue;
//                                    var_dump($galleryFolderAssocArr);
//                                    var_dump($galleryFolderAssocArr[$filename_array[0]]);
                                    if(!isset($galleryFolderAssocArr[$filename_array[0]])) {
                                        $galleryFolderAssocArr[$filename_array[0]] = str_replace($old_fid, $new_fid, $filename_array[0]);
                                    }
//                                    var_dump($galleryFolderAssocArr[$filename_array[0]]);
//                                    var_dump($extractPathImages . '/' . implode('/', $filename_array));
                                    $zip->extractTo($extractPathImages . '/temp', $filename);

                                }elseif($filename_array[0] == 'audio'){
                                    $zip->extractTo($extractPathFiles, $filename);
                                    $audiosOldPath[] = $filename;
                                }elseif($filename_array[0] == 'video'){
                                    $zip->extractTo($extractPathFiles, $filename);
                                    $videosOldPath[] = $filename;
                                }elseif($filename_array[0] == 'images'){
                                    $zip->extractTo($extractPathFiles, $filename);
                                    $imagesOldPath[] = $filename;
                                }elseif($filename_array[0] == 'track'){
                                    $zip->extractTo($extractPathFiles, $filename);
                                    $tracksOldPath[] = $filename;
                                }elseif($filename_array[0] == 'files'){
                                    $zip->extractTo($extractPathFiles, $filename);
                                    $filesOldPath[] = $filename_array[1];
                                    rename($extractPathFiles . '/' . $filename, $extractPathFiles . '/' . $filename_array[1]);
                                }elseif(stripos($filename_array[0], 'entity_files_') !== false){
                                    $entity_file_id = str_replace('entity_files_', '', $filename_array[0]);
                                    if(!isset($entityAssocArr[$entity_file_id])) continue;
                                    $new_entity_file_id = $entityAssocArr[$entity_file_id];
                                    $zip->extractTo($extractPathFiles . 'temp/', $filename);
                                    if( file_exists($extractPathFiles . 'temp/' . $filename) && is_file($extractPathFiles . 'temp/' . $filename ) ){
                                       rename($extractPathFiles . 'temp/' . $filename, $extractPathFiles . 'entity_files_' . $new_entity_file_id . '/' . $filename_array[1]);
                                    }
                                    
                                }elseif(stripos($filename_array[0], 'os-cck') !== false){
                                    if($extractPathImages[0] == '/'){
                                        $tempExtractPathImages = mb_substr( $extractPathImages, 1);
                                    }else{
                                        $tempExtractPathImages = $extractPathImages;
                                    }
                                    
                                    $zip->extractTo($tempExtractPathImages, $filename);
                                    
                                    if(!file_exists($extractPathImages.'/'.$filename)){
                                        $zip->extractTo($extractPathImages, $filename);
                                    }
                                }

                            }

//                            var_dump($galleryFolderAssocArr);
                            if(!empty($galleryFolderAssocArr)){
                                foreach($galleryFolderAssocArr as $key => $val){
//                                    var_dump($extractPathImages . '/temp/' . $key);
//                                    var_dump(file_exists('/' . $extractPathImages . '/temp/' . $key));
//                                        var_dump($extractPathImages . '/' . $val);
                                    if(file_exists($extractPathImages . '/temp/' . $key)){
                                        
                                        rcopy($extractPathImages . '/temp/' . $key, $extractPathImages . '/' . $val);
                                    }
                                }
                            }
//                            exit;
                            if(file_exists($extractPathImages . '/temp')){
                                recursiveRemoveDir($extractPathImages . '/temp');
                            }
                            if(!empty($audiosOldPath)){
                                foreach ($audiosOldPath as $audio){
                                    $query = "SELECT id, src FROM #__os_cck_audio_source WHERE src IN ('$audio')";
                                    $db->setQuery($query);
                                    $audios = $db->loadObjectList();

                                    if(!empty($audios)){
                                        foreach ($audios as $val){
                                            $val_arr = explode('/', $val->src);
                                            if($val_arr[2] != $os_cck_configuration->get('filehosting_folder', 'files')){
                                                $val_arr[2] = $os_cck_configuration->get('filehosting_folder', 'files');
                                                $query = "UPDATE #__os_cck_audio_source SET src = '" . implode('/', $val_arr) . "' WHERE id = $val->id";
                                                $db->setQuery($query);
                                                $db->execute();
                                            }
                                        }
                                    }
                                }
                            }
                            if(!empty($imagesOldPath)){
                                foreach ($imagesOldPath as $image){
                                    $query = "SELECT fid, filepath FROM #__os_cck_files WHERE filepath IN ('$image')";
                                    $db->setQuery($query);
                                    $images = $db->loadObjectList();

                                    if(!empty($images)){
                                        foreach ($images as $val){
                                            $val_arr = explode('/', $val->filepath);
                                            if($val_arr[2] != $os_cck_configuration->get('filehosting_folder', 'files')){
                                                $val_arr[2] = $os_cck_configuration->get('filehosting_folder', 'files');
                                                $query = "UPDATE #__os_cck_files SET filepath = '" . implode('/', $val_arr) . "' WHERE fid = $val->fid";
                                                $db->setQuery($query);
                                                $db->execute();
                                            }
                                        }
                                    }
                                }
                            }

                            if(!empty($filesOldPath)){
                                foreach ($filesOldPath as $file){
                                    $query = "SELECT fid, filepath FROM #__os_cck_files WHERE filepath IN ('$file')";
                                    $db->setQuery($query);
                                    $files = $db->loadObjectList();

                                    if(!empty($files)){
                                        foreach ($files as $val){
                                            $val_arr = explode('/', $val->filepath);
                                            if($val_arr[2] != $os_cck_configuration->get('filehosting_folder', 'files')){
                                                $val_arr[2] = $os_cck_configuration->get('filehosting_folder', 'files');
                                                $query = "UPDATE #__os_cck_files SET filepath = '" . implode('/', $val_arr) . "' WHERE fid = $val->fid";
                                                $db->setQuery($query);
                                                $db->execute();
                                            }
                                        }
                                    }
                                }
                            }

                            if(!empty($videosOldPath)){
                                foreach ($videosOldPath as $video){
                                    $query = "SELECT id, src FROM #__os_cck_video_source WHERE src IN ('$video')";
                                    $db->setQuery($query);
                                    $videos = $db->loadObjectList();

                                    if(!empty($videos)){
                                        foreach ($videos as $val){
                                            $val_arr = explode('/', $val->src);
                                            if($val_arr[2] != $os_cck_configuration->get('filehosting_folder', 'files')){
                                                $val_arr[2] = $os_cck_configuration->get('filehosting_folder', 'files');
                                                $query = "UPDATE #__os_cck_video_source SET src = '" . implode('/', $val_arr) . "' WHERE id = $val->id";
                                                $db->setQuery($query);
                                                $db->execute();
                                            }
                                        }
                                    }
                                }
                            }

                            if(!empty($tracksOldPath)){
                                foreach ($tracksOldPath as $track){
                                    $query = "SELECT id, src FROM #__os_cck_video_source WHERE src IN ('$track')";
                                    $db->setQuery($query);
                                    $tracks = $db->loadObjectList();

                                    if(!empty($tracks)){
                                        foreach ($tracks as $val){
                                            $val_arr = explode('/', $val->src);
                                            if($val_arr[2] != $os_cck_configuration->get('filehosting_folder', 'files')){
                                                $val_arr[2] = $os_cck_configuration->get('filehosting_folder', 'files');
                                                $query = "UPDATE #__os_cck_video_source SET src = '" . implode('/', $val_arr) . "' WHERE id = $val->id";
                                                $db->setQuery($query);
                                                $db->execute();
                                            }
                                        }
                                    }
                                }
                            }
                            // var_dump($zip); exit;
                            if($zip->filename){
                                $zip->close();
                            }else{
                                
                            }
                            JFile::delete($tmp_file_path);
            AdminViewImportExport::import($step,$data);
            // }

        }

    }


        static function export(){
            global $db, $app, $input, $entities_type, $os_cck_configuration, $entityFieldLists, $cck_entity_configuration;
            $db = new os_cckDb();
    //            var_dump($cck_entity_configuration); exit;
            $eids = $input->get('entity', array(), 'ARRAY');
            $elements = $input->get('elements', array(), 'ARRAY');
            
            $export_type = $input->get('export_type', 'all', 'STRING');
            $selected_layouts = $input->get('layouts', array(), 'ARRAY');
            $selected_instancies = $input->get('instancies', array(), 'ARRAY');
            
            // var_dump($selected_instancies); exit;
            $cart_export = false;
            if($export_type == 'all'){
                $query = "SELECT eid FROM #__os_cck_entity";
                $db->setQuery($query);
                $eids = $db->loadColumn();
            }
            // var_dump($eids); exit;

            $fileName = "os_cck_" . date("Ymd_His");
            $fileBase = "/administrator/components/com_os_cck/exports/";


            $zip = new ZipArchive(); //Создаём объект для работы с ZIP-архивами
            $zip->open(JPATH_SITE . $fileBase . $fileName . ".zip", ZIPARCHIVE::CREATE); //Открываем (создаём) архив archive.zip


            $gallery_fields_array = array();
            $images_array = array();
            $files_array = array();
            $audio_array = array();
            $videos_array = array();
            $tracks_array = array();

            $order = array("\r\n", "\n", "\r");
            $strXmlDoc = "";
            $strXmlDoc.= "<?xml version='1.0' encoding='utf-8' ?>\n";
            $strXmlDoc.= "<cck_data>\n";
            $strXmlDoc.= "<version>" . checkOsCckVersionNumber() . "</version>\n";


            $strXmlDocEntity = "";
            $strXmlDoc.= "<entities>\n";
            foreach($eids as $eid){
                $entity = new os_cckEntity($db->_db);
                $entity->load($eid);
                $entity_conf = $cck_entity_configuration[$eid];


                $strXmlDoc.= "<entity>\n";
                foreach($entity as $field => $value) {
                    if($field == '_entity_name') continue;
                    $strXmlDoc.= '<' . $field . '><![CDATA[' . $value . ']]></' . $field . ">\n";
                }
                $strXmlDoc.= '<entity_conf><![CDATA[' . json_encode($entity_conf) . ']]></entity_conf>\n';


    //            $strXmlDoc .= $strXmlDocEntity;
                if($entities_type[$eid] == 'os_cck_entity') {
                    $strXmlDocFields = "";
                    $field_list = $entity->getFieldList();
                    $image_file_fields = array();
                    if (!empty($field_list)) {
                        $strXmlDocFields .= "<fields>\n";
                        foreach ($field_list as $field) {
                            if ($field->field_type == 'filefield' || $field->field_type == 'imagefield') {
                                $image_file_fields[] = $field;
                            }
                            if ($field->field_type == 'galleryfield') {

                                $gallery_fields_array[] = $field->fid;
                            }

                            $strXmlDocFields .= "<field>\n";
                            foreach ($field as $key => $val) {
                                $strXmlDocFields .= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . ">\n";
                            }
                            $strXmlDocFields .= "</field>\n";
                        }
                        $strXmlDocFields .= "</fields>\n";
                    }
                    $strXmlDoc .= $strXmlDocFields;
                }
                $child_entety_array = array();
                // if($export_type == 'all' || in_array('layouts', $elements)){
                if($export_type != 'all' && isset($elements['instancies']) && $elements['instancies'] == 'on' && isset($selected_instancies[$eid]) && !empty($selected_instancies[$eid])){
                    $select_entity_inst = implode(',', $selected_instancies[$eid]);
                    $query = "SELECT ei.fk_lid FROM #__os_cck_entity_instance as ei "
                    . "LEFT JOIN #__os_cck_layout as l ON ei.fk_lid=l.lid "
                    . "WHERE ei.fk_eid=$eid AND ei.eiid IN (".$select_entity_inst.")" ;
                    $db->setQuery($query);
                    $inst_layouts = $db->loadColumn();
                    if(!empty($inst_layouts)){
                        $inst_layouts = array_unique($inst_layouts);

                        foreach($inst_layouts as $inst_lay){
                            if(!in_array($inst_lay, $selected_layouts[$eid])){
                                $selected_layouts[$eid][] = $inst_lay;
                            }
                        }
                    }
                }
                if($export_type != 'all' && isset($elements['reviews']) && $elements['reviews'] == 'on'){
                    
                    $query = "SELECT ei.fk_lid FROM #__os_cck_entity_instance as ei "
                    . "LEFT JOIN #__os_cck_layout as l ON ei.fk_lid=l.lid "
                    . "WHERE ei.fk_eid=$eid AND l.type='review_instance'" ;
                    $db->setQuery($query);
                    $inst_layouts = $db->loadColumn();
                    if(!empty($inst_layouts)){
                        $inst_layouts = array_unique($inst_layouts);

                        foreach($inst_layouts as $inst_lay){
                            if(!in_array($inst_lay, $selected_layouts[$eid])){
                                $selected_layouts[$eid][] = $inst_lay;
                            }
                        }
                    }
                }
                if($export_type != 'all' && isset($elements['requests']) && $elements['requests'] == 'on'){
                    
                    $query = "SELECT ei.fk_lid FROM #__os_cck_entity_instance as ei "
                    . "LEFT JOIN #__os_cck_layout as l ON ei.fk_lid=l.lid "
                    . "WHERE ei.fk_eid=$eid AND (l.type='request_instance' OR l.type='buy_request_instance' OR l.type='rent_request_instance')" ;
                    $db->setQuery($query);
                    $inst_layouts = $db->loadColumn();
                    if(!empty($inst_layouts)){
                        $inst_layouts = array_unique($inst_layouts);

                        foreach($inst_layouts as $inst_lay){
                            if(!in_array($inst_lay, $selected_layouts[$eid])){
                                $selected_layouts[$eid][] = $inst_lay;
                            }
                        }
                    }
                }
                if($export_type == 'all' || (isset($elements['layouts']) && $elements['layouts'] == 'on' && isset($selected_layouts[$eid]) && !empty($selected_layouts[$eid]))){

                    if($export_type == 'all'){
                        $query = "SELECT * FROM #__os_cck_layout WHERE fk_eid=$eid";
                        $db->setQuery($query);
                        $layouts = $db->loadObjectList();
                    }else{
                        $query = "SELECT * FROM #__os_cck_layout WHERE fk_eid=$eid AND lid IN (".implode(',', $selected_layouts[$eid]).")";
                        $db->setQuery($query);
                        $layouts = $db->loadObjectList();
                    }
                    
                    if($export_type == 'all' && !$cart_export){
                        $query = "SELECT * FROM #__os_cck_layout WHERE fk_eid=-1";
                        $db->setQuery($query);
                        $cart_layouts = $db->loadObjectList();
                    }elseif(isset($selected_layouts['-1']) && !empty($selected_layouts['-1']) && !$cart_export){
                        $query = "SELECT * FROM #__os_cck_layout WHERE fk_eid=-1 AND lid IN (".implode(',', $selected_layouts['-1']).")";
                        $db->setQuery($query);
                        $cart_layouts = $db->loadObjectList();
                    }else{
                        $cart_layouts = array();
                    }
                    
                    $strXmlDocLayouts = "";
                    if(!empty($layouts) || !empty($cart_layouts)){
                        $strXmlDocLayouts.= "<layouts>\n";
                        foreach($layouts as $layout){
                            $layout_params = unserialize($layout->params);
    //                            var_dump($layout_params['child_entities']);
                            $child_entities = (isset($layout_params['child_entities'])) ? $layout_params['child_entities'] : array();
                            if(!empty($child_entities)){
    //                                var_dump($child_entities); exit;
                                $child_entety_array[$layout->lid] = $child_entities;
                            }
                            $layout_html = "";
                            $query = "SELECT layout_html FROM #__os_cck_layout_html WHERE fk_lid=$layout->lid AND bootstrap=3";
                            $db->setQuery($query);
                            $layout_html = $db->loadResult();
                            $strXmlDocLayouts.= "<layout>\n";
                            foreach ($layout as $key => $val){
//                                if($key == 'pdf_structure') continue;
                                if (($key == 'params' && $val != '') || ($key == 'custom_fields' && $val != '')) {
                                    $string_val = json_encode(unserialize($val));
                                }else{
                                    $string_val = $val;
                                }
                                $strXmlDocLayouts.= '<' . $key . '><![CDATA[' . $string_val . ']]></' . $key . ">\n";
                            }
                            $strXmlDocLayouts.= '<layout_html><![CDATA[' . $layout_html . ']]></layout_html>\n';
                            $strXmlDocLayouts.= "</layout>\n";
                        }
                        foreach($cart_layouts as $layout){
                            $layout_params = unserialize($layout->params);
    //                            var_dump($layout_params['child_entities']);
                            $child_entities = (isset($layout_params['child_entities'])) ? $layout_params['child_entities'] : array();
                            if(!empty($child_entities)){
    //                                var_dump($child_entities); exit;
                                $child_entety_array[$layout->lid] = $child_entities;
                            }
                            $layout_html = "";
                            $query = "SELECT layout_html FROM #__os_cck_layout_html WHERE fk_lid=$layout->lid AND bootstrap=3";
                            $db->setQuery($query);
                            $layout_html = $db->loadResult();
                            $strXmlDocLayouts.= "<layout>\n";
                            foreach ($layout as $key => $val){
//                                if($key == 'pdf_structure') continue;
                                if (($key == 'params' && $val != '') || ($key == 'custom_fields' && $val != '')) {
                                    $string_val = json_encode(unserialize($val));
                                }else{
                                    $string_val = $val;
                                }
                                $strXmlDocLayouts.= '<' . $key . '><![CDATA[' . $string_val . ']]></' . $key . ">\n";
                            }
                            $strXmlDocLayouts.= '<layout_html><![CDATA[' . $layout_html . ']]></layout_html>\n';
                            $strXmlDocLayouts.= "</layout>\n";
                        }
                        $strXmlDocLayouts.= "</layouts>\n";
                    }
                    if($export_type == 'all' && !$cart_export){
                        $cart_export = true;
                    }
                    $strXmlDoc .= $strXmlDocLayouts;
                }

                if($entities_type[$eid] == 'os_cck_entity') {
                    if ($export_type == 'all' || (isset($elements['instancies']) && $elements['instancies'] == 'on') || (isset($elements['reviews']) && $elements['reviews'] == 'on') || (isset($elements['requests']) && $elements['requests'] == 'on')) {
                        $lay_type_and = 'AND';
                        $lay_type_arr = array();
                        $inst_lay_type = '';
                        if($export_type == 'all'){
                            $lay_type_arr[] = "l.type='add_instance'";
                            $lay_type_arr[] = "l.type='review_instance'";
                            $lay_type_arr[] = "l.type='request_instance'";
                            $lay_type_arr[] = "l.type='buy_request_instance'";
                            $lay_type_arr[] = "l.type='rent_request_instance'";
                        }else{
                            foreach ($elements as $element => $on) {
                                if ($element == 'instancies' && $on == 'on') {
                                    $inst_lay_type = "l.type='add_instance'";
                                } elseif ($element == 'reviews' && $on == 'on') {
                                    $lay_type_arr[] = "l.type='review_instance'";
                                } elseif ($element == 'requests' && $on == 'on') {
                                    $lay_type_arr[] = "l.type='request_instance'";
                                    $lay_type_arr[] = "l.type='buy_request_instance'";
                                    $lay_type_arr[] = "l.type='rent_request_instance'";
                                }
                            }
                        }
                        $instancies = array();
                        if(!empty($lay_type_arr)){
                            $lay_type_and .= '(' . implode(' OR ', $lay_type_arr) . ')';
                            $query = "SELECT ei.* FROM #__os_cck_entity_instance as ei "
                                . "LEFT JOIN #__os_cck_layout as l ON ei.fk_lid=l.lid "
                                . "WHERE ei.fk_eid=$eid " . $lay_type_and;
                            $db->setQuery($query);
                            $instancies = $db->loadObjectList();
                        }
                        $instancies2 = array();
                        if($inst_lay_type != '' && isset($selected_instancies[$eid]) && !empty($selected_instancies[$eid])){

                            $select_entity_inst = implode(',', $selected_instancies[$eid]);
                            $query = "SELECT ei.* FROM #__os_cck_entity_instance as ei "
                            . "LEFT JOIN #__os_cck_layout as l ON ei.fk_lid=l.lid "
                            . "WHERE ei.fk_eid=$eid AND $inst_lay_type AND ei.eiid IN (".$select_entity_inst.")" ;
                            $db->setQuery($query);
                            $instancies2 = $db->loadObjectList();
                        }
                        $instancies = array_merge($instancies, $instancies2);
    //                    echo $query;
    //                    var_dump($instancies); exit;
                        $strXmlDocInstacies = "";

                        if (!empty($instancies)) {
                            $strXmlDocInstacies .= "<instancies>\n";
                            foreach ($instancies as $instance) {
                                $instance_obj = new os_cckEntityInstance($db->_db);
                                $instance_obj->load($instance->eiid);
                                //                        var_dump($instance_obj);
                                $strXmlDocInstacies .= "<instance>\n";
                                foreach ($instance as $key => $val) {
                                    $strXmlDocInstacies .= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . ">\n";
                                }

                                if (!empty($child_entety_array)) {
                                    if (isset($child_entety_array[$instance_obj->fk_lid])) {
                                        foreach ($child_entety_array[$instance_obj->fk_lid] as $child_entety) {
                                            $query = "SELECT * FROM #__os_cck_child_parent_connect WHERE media_type='$child_entety->data_field_name' AND fid_parent='$instance_obj->eiid'";
                                            $db->setQuery($query);
                                            $p_ch = $db->loadObjectList();
                                            if (!empty($p_ch)) {
                                                foreach ($p_ch as $temp_p_ch) {
                                                    $strXmlDocInstacies .= "<instance_parent>\n";
                                                    foreach ($temp_p_ch as $k => $v) {
                                                        $strXmlDocInstacies .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . ">\n";
                                                    }
                                                    $strXmlDocInstacies .= "</instance_parent>";
                                                }
                                            }
                                            
                                        }
    //                                    var_dump($child_entety_array[$instance_obj->fk_lid]); exit;
                                    }

                                }
                                
                                $query = "SELECT * FROM #__os_cck_child_parent_connect WHERE media_type='instance' AND fid_parent='$instance_obj->eiid'";
                                $db->setQuery($query);
                                $requests = $db->loadObjectList();

                                if(!empty($requests)){
                                    foreach ($requests as $request) {
                                        $strXmlDocInstacies .= "<instance_request>\n";
                                        foreach ($request as $k => $v) {
                                            $strXmlDocInstacies .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . ">\n";
                                        }
                                        $strXmlDocInstacies .= "</instance_request>";
                                    }

                                }

                                $query = "SELECT * FROM #__os_cck_content_entity_$eid WHERE fk_eiid=$instance->eiid";
                                $db->setQuery($query);
                                $instance_content = $db->loadObjectList();


                                if (is_array($instance_content)) {
                                    $strXmlDocInstacies .= '<instance_content>';
                                    if (isset($instance_content[0])) {
                                        foreach ($instance_content[0] as $k => $v) {
                                            $strXmlDocInstacies .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . ">\n";
                                        }
                                    }
                                    $strXmlDocInstacies .= '</instance_content>';
                                }

                                $query = "SELECT * FROM #__os_cck_content_instances_price WHERE fk_eiid=$instance->eiid";
                                $db->setQuery($query);
                                $instance_content_price = $db->loadObjectList();
                                if (is_array($instance_content_price)) {
                                    //                            var_dump($instance_content_price); exit;

                                    foreach ($instance_content_price as $k => $v) {
                                        $strXmlDocInstacies .= '<instance_content_price>';
                                        foreach ($v as $k2 => $v2) {
                                            $strXmlDocInstacies .= '<' . $k2 . '><![CDATA[' . $v2 . ']]></' . $k2 . ">\n";
                                        }
                                        $strXmlDocInstacies .= '</instance_content_price>';
                                    }

                                }

                                $query = "SELECT * FROM #__os_cck_audio_source WHERE fk_eiid=$instance->eiid";
                                $db->setQuery($query);
                                $instance_audio_source = $db->loadObjectList();
                                if (is_array($instance_audio_source)) {

                                    foreach ($instance_audio_source as $k => $v) {
                                        $strXmlDocInstacies .= '<instance_audio_source>';
                                        foreach ($v as $k2 => $v2) {
                                            if ($k2 == 'src' && file_exists(JPATH_SITE . '/' . $v2)) {
                                                $audio_array[] = JPATH_SITE . '/' . $v2;
                                            }
                                            $strXmlDocInstacies .= '<' . $k2 . '><![CDATA[' . $v2 . ']]></' . $k2 . ">\n";
                                        }
                                        $strXmlDocInstacies .= '</instance_audio_source>';
                                    }

                                }

                                $query = "SELECT * FROM #__os_cck_video_source WHERE fk_eiid=$instance->eiid";
                                $db->setQuery($query);
                                $instance_video_source = $db->loadObjectList();
                                if (is_array($instance_video_source)) {

                                    foreach ($instance_video_source as $k => $v) {

                                        $strXmlDocInstacies .= '<instance_video_source>';
                                        foreach ($v as $k2 => $v2) {
                                            if ($k2 == 'src' && file_exists(JPATH_SITE . '/' . $v2)) {
                                                $videos_array[] = JPATH_SITE . '/' . $v2;
                                            }
                                            $strXmlDocInstacies .= '<' . $k2 . '><![CDATA[' . $v2 . ']]></' . $k2 . ">\n";
                                        }
                                        $strXmlDocInstacies .= '</instance_video_source>';
                                    }

                                }

                                $query = "SELECT * FROM #__os_cck_track_source WHERE fk_eiid=$instance->eiid";
                                $db->setQuery($query);
                                $instance_track_source = $db->loadObjectList();
                                if (is_array($instance_track_source)) {

                                    foreach ($instance_track_source as $k => $v) {

                                        $strXmlDocInstacies .= '<instance_track_source>';
                                        foreach ($v as $k2 => $v2) {
                                            if ($k2 == 'src' && file_exists(JPATH_SITE . '/' . $v2)) {
                                                $tracks_array[] = JPATH_SITE . '/' . $v2;
                                            }
                                            $strXmlDocInstacies .= '<' . $k2 . '><![CDATA[' . $v2 . ']]></' . $k2 . ">\n";
                                        }
                                        $strXmlDocInstacies .= '</instance_track_source>';
                                    }

                                }

                                if (!empty($image_file_fields)) {
                                    foreach ($image_file_fields as $field) {
                                        $query = "SELECT DISTINCT f.* FROM #__os_cck_files as f "
                                            . "LEFT JOIN #__os_cck_content_entity_$eid as ce ON ce." . $field->db_field_name . "_fid = f.fid "
                                            . "WHERE ce.fk_eiid=$instance->eiid";
                                        $db->setQuery($query);
                                        $instance_file = $db->loadObjectList();

                                        if (!empty($instance_file)) {
                                            $strXmlDocInstacies .= '<instance_file>';
                                            foreach ($instance_file[0] as $k => $v) {
                                                if ($k == 'filepath' && file_exists(JPATH_SITE . $v)) {
                                                    $images_array[] = JPATH_SITE . $v;
                                                }
                                                $strXmlDocInstacies .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . ">\n";
                                            }
                                            $strXmlDocInstacies .= '</instance_file>';
                                        }

                                    }
                                }

                                //                        var_dump($instance_content);
                                $strXmlDocInstacies .= "</instance>\n";
                            }
                            $strXmlDocInstacies .= "</instancies>\n";
                            //                    print_r($strXmlDocInstacies);
                        }
                        $strXmlDoc .= $strXmlDocInstacies;
                    }
                }
                $strXmlDoc.= "</entity>\n";
            }
            $strXmlDoc.= "</entities>\n";
            
            $strXmlDocCategories = '';
            if($export_type == 'all' || (isset($elements['categories']) && $elements['categories'] == 'on')){
                if( (isset($elements['categories']) && $elements['categories'] == 'on') ){
                    $eids_in = implode(', ', $eids) . ', 0';
                    $query = "SELECT * FROM #__os_cck_categories WHERE fk_eid IN($eids_in)";
                }else{
                    $query = "SELECT * FROM #__os_cck_categories ";
                }
                $db->setQuery($query);
                $categories = $db->loadObjectList();

                if(!empty($categories)) {
                    $cat_ids = array();
                    $strXmlDocCategories.= "<categories>\n";
                    foreach ($categories as $category) {
                        $category_obj = new os_cckCategory($db->_db);
                        $category_obj->load($category->cid);
                        $cat_ids[] = $category->cid;
                        $strXmlDocCategories.= "<category>\n";
                        foreach ($category_obj as $key => $val){
                            $strXmlDocCategories.= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . ">\n";
                        }
                        $strXmlDocCategories.= "</category>\n";
                    }
                    $strXmlDocCategories.= "</categories>\n";
                    $query = "SELECT * FROM #__os_cck_categories_connect WHERE fk_cid IN(".implode(', ', $cat_ids).")";
                    $db->setQuery($query);
                    $cat_connect = $db->loadObjectList();
                    if(!empty($cat_connect)){
                        $strXmlDocCategories.= "<categories_connect>\n";
                        foreach ($cat_connect as $single_connect){
                            $strXmlDocCategories.= "<single_connect>\n";
                            foreach ($single_connect as $key => $val) {
                                $strXmlDocCategories .= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . ">\n";
                            }
                            $strXmlDocCategories.= "</single_connect>\n";
                        }
                        $strXmlDocCategories.= "</categories_connect>\n";
                    }
                }
            }

            $strXmlDocCoupons = '';
            if($export_type == 'all' || (isset($elements['coupons']) && $elements['coupons'] == 'on')){
                $query = "SELECT * FROM #__os_cck_coupons ";
                $db->setQuery($query);
                $coupons = $db->loadObjectList();
                if(!empty($coupons)) {
                    $strXmlDocCoupons.= "<coupons>\n";
                    foreach ($coupons as $coupon) {
                        $coupon_obj = new os_cckCoupons($db->_db);
                        $coupon_obj->load($coupon->coup_id);
                        $strXmlDocCoupons.= "<coupon>\n";
                        foreach ($coupon_obj as $key => $val){
                            $strXmlDocCoupons.= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . ">\n";
                        }
                        $strXmlDocCoupons.= "</coupon>\n";
                    }
                    $strXmlDocCoupons.= "</coupons>\n";
                }
            }

            $strXmlDocRents = '';
            if($export_type == 'all' || (isset($elements['requests']) && $elements['requests'] == 'on')){
                $query = "SELECT * FROM #__os_cck_rent ";
                $db->setQuery($query);
                $rents = $db->loadObjectList();
                if(!empty($rents)) {
                    $strXmlDocRents.= "<rents>\n";
                    foreach ($rents as $rent) {
                        $rent_obj = new mosCCK_rent($db->_db);
                        $rent_obj->load($rent->id);
                        $strXmlDocRents.= "<rent>\n";
                        foreach ($rent_obj as $key => $val){
                            $strXmlDocRents.= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . ">\n";
                        }
                        $strXmlDocRents.= "</rent>\n";
                    }
                    $strXmlDocRents.= "</rents>\n";
                }
            }



            $strXmlDocOrders = '';
            if($export_type == 'all' || (isset($elements['orders']) && $elements['orders'] == 'on')){
                $query = "SELECT * FROM #__os_cck_orders ";
                $db->setQuery($query);
                $orders = $db->loadObjectList();
                if(!empty($orders)) {
                    $strXmlDocOrders.= "<orders>\n";
                    foreach ($orders as $order) {
                        $strXmlDocOrders.= "<order>\n";
                        foreach ($order as $key => $val){
                            $strXmlDocOrders.= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . ">\n";
                        }
                        $strXmlDocOrders.= "</order>\n";
                    }
                    $strXmlDocOrders.= "</orders>\n";
                }

                $query = "SELECT * FROM #__os_cck_orders_details ";
                $db->setQuery($query);
                $orders = $db->loadObjectList();
                if(!empty($orders)) {
                    $strXmlDocOrders.= "<orders_details>\n";
                    foreach ($orders as $order) {
                        $strXmlDocOrders.= "<order_detail>\n";
                        foreach ($order as $key => $val){
                            $strXmlDocOrders.= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . ">\n";
                        }
                        $strXmlDocOrders.= "</order_detail>\n";
                    }
                    $strXmlDocOrders.= "</orders_details>\n";
                }

                $query = "SELECT * FROM #__os_cck_orders_price ";
                $db->setQuery($query);
                $orders = $db->loadObjectList();
                if(!empty($orders)) {
                    $strXmlDocOrders.= "<orders_prices>\n";
                    foreach ($orders as $order) {
                        $strXmlDocOrders.= "<order_price>\n";
                        foreach ($order as $key => $val){
                            $strXmlDocOrders.= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . ">\n";
                        }
                        $strXmlDocOrders.= "</order_price>\n";
                    }
                    $strXmlDocOrders.= "</orders_prices>\n";
                }

            }            

            if($export_type == 'all' || (isset($elements['files']) && $elements['files'] == 'on')){
                if (!empty($gallery_fields_array)){
                    foreach ($gallery_fields_array as $gallery_field){
                        if(file_exists(JPATH_SITE . '/images/com_os_cck'.$gallery_field)){
                            $rootPath = JPATH_SITE . '/images/';
                            $files = new RecursiveIteratorIterator(
                                new RecursiveDirectoryIterator($rootPath),
                                RecursiveIteratorIterator::LEAVES_ONLY
                            );

                            foreach ($files as $name => $file)
                            {

                                if(stripos($name, 'com_os_cck'.$gallery_field) == false) continue;
                                // Skip directories (they would be added automatically)
                                if (!$file->isDir())
                                {
                                    // Get real and relative path for current file
                                    $filePath = $file->getRealPath();
                                    $relativePath = substr($filePath, strlen($rootPath));
                                    $relativePath = str_replace('\\', '/', $relativePath);
                                    
                                    $content = file_get_contents($filePath);
                                    $zip->addFromString($relativePath, $content);
                                    // Add current file to archive
//                                    $zip->addFile($filePath, $relativePath);
                                }
                            }
    //                            $zip->addFile(JPATH_SITE . '/images/com_os_cck'.$gallery_field);
                        }
                    }
                }

                foreach($eids as $eid){
                    if(file_exists(JPATH_SITE . '/components/com_os_cck/files/entity_files_'.$eid)){
                        $entity_files = scandir(JPATH_SITE . '/components/com_os_cck/files/entity_files_'.$eid);
                        if(!empty($entity_files)){
                            foreach($entity_files as $file){
                                if($file == '.' || $file == '..') continue;

                                $zip->addFile(JPATH_SITE . '/components/com_os_cck/files/entity_files_'.$eid.'/'.$file, 'entity_files_'.$eid.'/'.$file);
                            }
                        }
                    }
                }
                $files = scandir(JPATH_SITE . '/images/os-cck');
                if(!empty($files)){
                    foreach($files as $file){
                        if($file == '.' || $file == '..') continue;
                        $zip->addFile(JPATH_SITE . '/images/os-cck/'.$file, 'os-cck/'.$file);
                    }
                }
            }

            if(!empty($audio_array)){
                foreach($audio_array as $audio){
                    $file_name_array = explode('/', $audio);
                    $file_name_array = array_reverse($file_name_array);
                    if($file_name_array[0] != ''){
                        $zip->addFile($audio, 'audio/'.$file_name_array[0]);
                    }
                }
            }

            if(!empty($videos_array)){
                foreach($videos_array as $video){
                    $file_name_array = explode('/', $video);
                    $file_name_array = array_reverse($file_name_array);
                    if($file_name_array[0] != ''){
                        $zip->addFile($video, 'video/'.$file_name_array[0]);
                    }
                }
            }
            
            if(!empty($tracks_array)){
                foreach($tracks_array as $track){
                    $file_name_array = explode('/', $track);
                    $file_name_array = array_reverse($file_name_array);
                    if($file_name_array[0] != ''){
                        $zip->addFile($track, 'track/'.$file_name_array[0]);
                    }
                }
            }

            if(!empty($images_array)){
                foreach($images_array as $file){
                    $file_name_array = explode('/', $file);
                    $file_name_array = array_reverse($file_name_array);

                    if($file_name_array[1]== 'images') {
                        if (file_exists($file) )
                            $zip->addFile($file, 'images/' . $file_name_array[0]);
                    }else{
                        if (file_exists($file) )
                            $zip->addFile($file, 'files/' . $file_name_array[0]);
                    }
                }
            }
            
            $strXmlDoc .= $strXmlDocCategories;
            $strXmlDoc .= $strXmlDocCoupons;
            $strXmlDoc .= $strXmlDocRents;
            $strXmlDoc .= $strXmlDocOrders;            
            $strXmlDoc.= "</cck_data>\n";

            $InformationArray = self :: storeExportFile($strXmlDoc);
    //            $zip->addFile("index.php");
    //            $zip->addFile("styles/style.css");

            if (file_exists(JPATH_ADMINISTRATOR . "/components/com_os_cck/exports/" . $InformationArray['xml_file']) )
                $zip->addFile(JPATH_ADMINISTRATOR . "/components/com_os_cck/exports/" . $InformationArray['xml_file'], $InformationArray['xml_file']);
            $zip->close();
            $InformationArray['xml_file'] = $fileName . ".zip";
            $InformationArray['out_file'] = $fileName . ".zip";
            AdminViewImportExport::showExportResult($InformationArray, 'com_os_cck');
        }
        
        static function storeExportFile($data) {

//            global $mosConfig_live_site, $mosConfig_absolute_path, $realestatemanager_configuration;
            $fileName = "os_cck_" . date("Ymd_His");
            $fileBase = "administrator/components/com_os_cck/exports/";

            //write the xml file
            $fp = fopen(JPATH_SITE . '/' . $fileBase . $fileName . ".xml", "w", 0); #open for writing

            fwrite($fp, $data); #write all of $data to our opened file
            fclose($fp); #close the file
            $InformationArray = array();
            $InformationArray['xml_file'] = $fileName . '.xml';
            $InformationArray['log_file'] = $fileName . '.log';
            $InformationArray['fileBase'] = "file://" . getcwd() . "/components/com_os_cck/exports/";
            $InformationArray['urlBase'] = JUri::root() . $fileBase;
            $InformationArray['out_file'] = $InformationArray['xml_file'];
            $InformationArray['error'] = new stdClass();

            
            return $InformationArray;
        }
        
        static function getXMLItemValue($item, $item_name) {
            $house_items = $item->getElementsByTagname($item_name);

            $house_item = $house_items->item(0);

            if (NULL != $house_item)
                return $house_item->nodeValue;
            else
                return "";
        }

        static function replaceFieldMasks($fieldsAssocArr, $field){
            // ini_set('memory_limit', '-1');
//             var_dump($field);
            if(is_array($field)){
                foreach($field as $key => $f){
                    // var_dump($key);
                    // var_dump($f);
                    if($key === 'child_entities'){
                        if(!empty($f)){

                        }
                        
                    }else{
                        $new_key = self::replaceFieldMasks($fieldsAssocArr, $key);
                        unset($field[$key]);
                        $field[$new_key] = self::replaceFieldMasks($fieldsAssocArr, $f);

                    }
                }
                return $field;
            }elseif(is_object($field)){
                foreach($field as $key => $f){
//                    var_dump($key);
                    // $new_key = self::replaceFieldMasks($fieldsAssocArr, $key);
                    // unset($field[$key]);
                    // $field[$new_key] = self::replaceFieldMasks($fieldsAssocArr, $f);
                }
                return $field;
            }else{
                // $replaced_fields = array();
                // var_dump($field);
                // var_dump($fieldsAssocArr);
                foreach ($fieldsAssocArr as $val){
                    // if(!empty($replaced_fields)){
                    //     var_dump($replaced_fields);
                    // }
                    // if(in_array($val['old_fid'], $replaced_fields)) continue;
//                    if($val['field_type'] == 'galleryfield' ) {
//                        var_dump(stripos($val['field_type'] . '_' .$val['old_fid'] . '_', $field) !== false);
//                    }
                        // if(stripos($field, 'data') !== false){
                        //     var_dump($field);
                        // }
                        if ($field && ($field == $val['field_type'] . '_' . $val['old_fid'] || stripos($field, $val['field_type'] . '_' . $val['old_fid'] . '_') !== false 
                        || stripos($field, '{|' . $val['field_type'] . '_' . $val['old_fid'] . '|}') !== false  || stripos($field, 'instance.' . $val['field_type'] . '_' . $val['old_fid'] . ' ') !== false 
                        || stripos($field, 'instance.' . $val['field_type'] . '_' . $val['old_fid'] . '=') !== false || stripos($field, 'instance.' . $val['field_type'] . '_' . $val['old_fid'] . '<') !== false 
                        || stripos($field, 'instance.' . $val['field_type'] . '_' . $val['old_fid'] . '>') !== false 
                        || (stripos($field, '_'.$val['field_type'] . '_' . $val['old_fid']) !== false && (stripos($field, '_'.$val['field_type'] . '_' . $val['old_fid']) +1 + strlen($val['field_type'] . '_' . $val['old_fid'])) == strlen($field)))) {
                            $field = str_replace($val['field_type'] . '_' . $val['old_fid'], $val['field_type'] . '_' . $val['new_fid'], $field);
                            // $replaced_fields[] = $val['new_fid'];
                        }
//                    text_textfield_2818_instance_layout
                        // var_dump('{|f-' .$val['old_fid']);
                        // var_dump(stripos($field, '{|f-' .$val['old_fid']));
//                    if(stripos())
//                    if($field == $val['old_fid']){
//                        $field = $val['new_fid'];
//                    }
                        if($field && (stripos($field, 'price.fk_fid=' . $val['old_fid'] . ' ') !== false || stripos($field, 'price.fk_fid= ' . $val['old_fid'] . ' ') !== false)){
                            $field = str_replace('price.fk_fid=' . $val['old_fid'] . ' ', 'price.fk_fid=' . $val['new_fid'] . ' ', $field);
                            $field = str_replace('price.fk_fid= ' . $val['old_fid'] . ' ', 'price.fk_fid=' . $val['new_fid'] . ' ', $field);
                        }
                        if($field){
                            $field = str_replace('{|f-' . $val['old_fid'] .'|}', '{|f-' . $val['new_fid'].'|}', $field);
                        }
                            
//                    var_dump($field);
                }
                return $field;    
            }
            
        }
        
//         static function replaceFieldMasks($fieldsAssocArr, $field){

//             if( !isset($field) || count($fieldsAssocArr) < 1 ) return $field ;

//             // ini_set('memory_limit', '-1');
// //             var_dump($field);
//             if(is_array($field)){
//                 foreach($field as $key => $f){
//                     // var_dump($key);
//                     // var_dump($f);
//                     if($key === 'child_entities'){
//                         if(!empty($f)){

//                         }
                        
//                     }else{
//                         $new_key = self::replaceFieldMasks($fieldsAssocArr, $key);
//                         unset($field[$key]);
//                         $field[$new_key] = self::replaceFieldMasks($fieldsAssocArr, $f);

//                     }
//                 }
//                 return $field;
//             }elseif(is_object($field)){

//                 //foreach($field as $key => $f){
// //                    var_dump($key);
//                     // $new_key = self::replaceFieldMasks($fieldsAssocArr, $key);
//                     // unset($field[$key]);
//                     // $field[$new_key] = self::replaceFieldMasks($fieldsAssocArr, $f);
//                 //}
//                 return $field;
//             }else{
//                 // $replaced_fields = array();
//                 // var_dump($field);
//                 // var_dump($fieldsAssocArr);
//                 foreach ($fieldsAssocArr as $val){
//                     if(stripos($field, $val['field_type'] ) === false 
//                         && stripos($field, 'price.fk_fid=' ) === false 
//                         && stripos($field, '{|f-' ) === false 
//                     ) continue ;
//                     // if(!empty($replaced_fields)){
//                     //     var_dump($replaced_fields);
//                     // }
//                     // if(in_array($val['old_fid'], $replaced_fields)) continue;
// //                    if($val['field_type'] == 'galleryfield' ) {
// //                        var_dump(stripos($val['field_type'] . '_' .$val['old_fid'] . '_', $field) !== false);
// //                    }
//                         // if(stripos($field, 'data') !== false){
//                         //     var_dump($field);
//                         // }

//                         if ($field 
//                             && ($field == $val['field_type_old_fid'] 
//                                 || stripos($field, $val['field_type_old_fid_'] ) !== false 
//                                 || stripos($field, $val['{|field_type_old_fid|}'] ) !== false  
//                                 || stripos($field, $val['instance.field_type_old_fid ']) !== false 
//                                 || stripos($field, $val['instance.field_type_old_fid=']) !== false 
//                                 || stripos($field, $val['instance.field_type_old_fid<']) !== false 
//                                 || stripos($field, $val['instance.field_type_old_fid>']) !== false 
//                                 || (stripos($field, $val['_field_type_old_fid'] ) !== false 
//                                     && (stripos($field, $val['_field_type_old_fid'] ) +1 + strlen($val['field_type_old_fid'] )) == strlen($field)))) {
//                             $field = str_replace($val['field_type_old_fid'] , $val['field_type'] . '_' . $val['new_fid'], $field);
//                             // $replaced_fields[] = $val['new_fid'];
//                         }
// //                    text_textfield_2818_instance_layout
//                         // var_dump('{|f-' .$val['old_fid']);
//                         // var_dump(stripos($field, '{|f-' .$val['old_fid']));
// //                    if(stripos())
// //                    if($field == $val['old_fid']){
// //                        $field = $val['new_fid'];
// //                    }
//                         if($field && (stripos($field, 'price.fk_fid=' . $val['old_fid'] . ' ') !== false || stripos($field, 'price.fk_fid= ' . $val['old_fid'] . ' ') !== false)){
//                             $field = str_replace('price.fk_fid=' . $val['old_fid'] . ' ', 'price.fk_fid=' . $val['new_fid'] . ' ', $field);
//                             $field = str_replace('price.fk_fid= ' . $val['old_fid'] . ' ', 'price.fk_fid=' . $val['new_fid'] . ' ', $field);
//                         }
//                         if($field){
//                             $field = str_replace('{|f-' . $val['old_fid'] .'|}', '{|f-' . $val['new_fid'].'|}', $field);
//                         }
                            
// //                    var_dump($field);
//                 }
//                 return $field;    
//             }
            
//         }
        static function replaceFieldMasksLayoutHtml($fieldsAssocArr, $field){
         
            $field = urldecode($field);
            if(is_array($field)){
                foreach($field as $key => $f){
                    $new_key = self::replaceFieldMasks($fieldsAssocArr, $key);
                    unset($field[$key]);
                    $field[$new_key] = self::replaceFieldMasks($fieldsAssocArr, $f);
                }
                return $field;
            }else{
                
                foreach ($fieldsAssocArr as $val){
                    if(stripos($field, $val['field_type'] ) === false 
                        && stripos($field, '{|f-' ) === false 
                        && stripos($field, 'fid="' ) === false 
                    ) continue ;

                    $field = str_replace($val['field_type_old_fid'] . '-', $val['field_type'] . '_' .$val['new_fid'] . '-', $field);
                    $field = str_replace($val['field_type_old_fid'] . '"', $val['field_type'] . '_' .$val['new_fid'] . '"', $field);
                    $field = str_replace($val['field_type_old_fid_'], $val['field_type'] . '_' .$val['new_fid'] . '_', $field);
                    // var_dump('fid="' .$val['old_fid'] . '"');
                    // var_dump(stripos($field, 'fid="' .$val['old_fid'] . '"'));
                    $field = str_replace('{|f-' .$val['old_fid'].'|}', '{|f-' .$val['new_fid'].'|}', $field);
                    $field = str_replace('{|f-parent-' .$val['old_fid'].'|}', '{|f-parent-' .$val['new_fid'].'|}', $field);
                    $field = str_replace('fid="' .$val['old_fid'] . '"', 'fid="' .$val['new_fid'] . '"', $field);
                }
                return urlencode($field);
            }
            
        }

        static function getAssocLid($layoutAssocArr, $old_lid){
            //andrew comment:
            // foreach($layoutAssocArr as $layout){
            //     if($layout['old_lid'] == $old_lid) return $layout['new_lid'];    
            // }
            //return false;
            //andrew added:
            return array_key_exists($old_lid, $layoutAssocArr) ? $layoutAssocArr[$old_lid]['new_lid'] :  false;
        }

        static function getAssocFid($fieldsAssocArr, $old_fid){
            //andrew comment:
            // foreach($fieldsAssocArr as $field){
            //     if($field['old_fid'] == $old_fid) return $field['new_fid'];    
            // }
            // return false;
            //andrew added:
            return array_key_exists($old_fid, $fieldsAssocArr) ? $fieldsAssocArr[$old_fid]['new_fid'] :  false;
        }

        static function importJsLibrary()
        {
            global $db;
            $db = new os_cckDb();
            $config = JFactory::getConfig();
            $path = $config->get('tmp_path').'/importJsLibrary.zip';
            $data = file_get_contents('php://input');
            $obj = json_decode($data);
            // $obj = null;
            if(!$obj){
                echo json_encode(array("success"=>false, "error"=>cck_lang_text('COM_OS_CCK_LABEL_IMPORT_LIBRARY_ERROR_JS')));
                exit;
            }
            $method = $obj->method;
            // var_dump($obj);
            $mask = $obj->mask;


            $data = $method($obj->package);
            // var_dump($data); exit;
            $file = fopen($path, "w+");
            fputs($file, $data);
            fclose($file);


            $prop_arr = array();
            if($mask == 'cck_os_library' || $mask == 'cck_os_library_free'){
                
                $extractPathFiles = $config->get('tmp_path') . '/';
                $zip = new ZipArchive;
                // var_dump($tmp_file_path);
                $extract = $zip->open($path);
                // var_dump($zip);
                // var_dump($zip->numFiles);
                for ($i = 0; $i < $zip->numFiles; $i++) {
                    // var_dump($zip->getNameIndex($i));
                    $filename = $zip->getNameIndex($i);

                    // ...
                }
                // $zip_file_name = protectInjectionWithoutQuote('zip_file_name','', 'STRING');
                // if($zip_file_name == ''){
                    $zip_file_name = 'importJsLibrary.zip';
                // }
                // var_dump($zip_file_name);
                $zip_file_name_arr = explode('/', $zip_file_name);
                $zip_file_name_arr_length = count($zip_file_name_arr);
                $zip_file_name_arr[$zip_file_name_arr_length - 1] = $filename;
                
                $xml_file_name = implode('/', $zip_file_name_arr);
//                var_dump($xml_file_name);
                if ($extract === TRUE) {
                      
                    $zip->extractTo($extractPathFiles, $xml_file_name);

                }

                $dom = new domDocument('1.0', 'utf-8');
                $dom->load($extractPathFiles . '/' . $xml_file_name);

                $entities_list = $dom->getElementsByTagname('entities');
                $entity_arr = array();
                foreach($entities_list as $entity){
                    $entity_dom = $entity->getElementsByTagname('entity');

                    foreach($entity_dom as $entity_temp){
                        // $entity_temp = $entity_dom->item(0);
                        $entity_childs = $entity_temp->childNodes;

                        $old_eid = 0;
                        
                        foreach($entity_childs as $key => $val){
                            
                            if(property_exists($val, 'tagName')){
                                $prop = $val->tagName;
                                if($prop == 'eid'){
                                    $old_eid = $val->nodeValue;
                                    continue;
                                }elseif($prop == 'name'){
                                    $entity_arr[$old_eid] = $val->nodeValue;
                                    continue;
                                }
//                                        var_dump($val->tagName);
//                                        var_dump($val->nodeValue);
                            }
                            
                        }

                    }
                }
                $query = "SELECT eid FROM #__os_cck_entity WHERE name='os-library' LIMIT 0,1";
                $db->setQuery($query);
                $existing_eid = $db->loadResult();

                if($existing_eid && count($entity_arr) == 1 && $entity_arr[$old_eid] == 'os-library'){
                    $prop_arr['old_eid'] = $old_eid;
                    $prop_arr['ext_eid'] = $existing_eid;
                    $prop_arr['entity_export_type'][$old_eid] = 'merge';
                    $prop_arr['entity_merge'][$old_eid] = $existing_eid;
                    $prop_arr['layout_opt'][$old_eid] = 'merge';
                    $prop_arr['field_opt'][$old_eid] = 'merge';
                }
                // var_dump($zip); exit;
                $zip->close();

                // $query = "SELECT eid, name FROM #__os_cck_entity";
                // $db->setQuery($query);
                // $existing_entities = $db->loadAssocList('eid', 'name');
            }
            

            echo json_encode(array("success"=>true, "tmp_file_path"=>$path, 'zip_file_name'=>'importJsLibrary.zip', 'prop_arr' => $prop_arr));
            // if (JVERSION >= '4.0.0') {
            //     $archive = new Joomla\Archive\Zip();
            //     $archive->extract($path, $config->get('tmp_path').'/pkg_os_cck_pro');
            // } else {
            //     JArchive::extract($path, $config->get('tmp_path').'/pkg_os_cck_pro');
            // }

            // $installer = JInstaller::getInstance();
            // $result = $installer->update($config->get('tmp_path').'/pkg_os_cck_pro');
            // JFile::delete($path);
            // JFolder::delete($config->get('tmp_path').'/pkg_os_cck_pro');
            exit;
        }


        static function csv_import(){
            global $db, $app, $doc;
            $db = new os_cckDb();
            $doc->addStyleSheet("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");
            $tmp_file_path = protectInjectionWithoutQuote('tmp_file_path','', 'STRING');
            $step = protectInjectionWithoutQuote('step',1);
            $separator = protectInjectionWithoutQuote('separator', ',', 'STRING');
            if($step == 1){
                $query = "SELECT eid, name FROM #__os_cck_entity WHERE type='os_cck_entity'";
                $db->setQuery($query);
                $existing_entities = $db->loadAssocList('eid', 'name');


            }elseif($step == 2){
            
                if($tmp_file_path == '' && $_FILES['importData']['type'] != 'text/csv')
                {
                    $data['error'] = 'Incorrect file format';
                    AdminViewImportExport::import($step,$data);
                }else{
                    if($tmp_file_path == ''){
                        $tmp_file_path = JPATH_SITE . '/tmp/' . $_FILES['importData']['name'];
                        move_uploaded_file($_FILES['importData']['tmp_name'], $tmp_file_path);
                    }
                    

                    $handle = fopen($tmp_file_path,'r');
                    $data = fgetcsv($handle, null, $separator);
                    // var_dump($data); exit;

                    $query = "SELECT eid, name FROM #__os_cck_entity WHERE type='os_cck_entity'";
                    $db->setQuery($query);
                    $existing_entities = $db->loadAssocList('eid', 'name');

                    if(empty($existing_entities)){
                        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ENTITY"));
                        return;
                    }
                    
                    AdminViewImportExport::importCsvStepTwo($data, $existing_entities, $tmp_file_path, $separator);
                    // var_dump(count($data));

                    // $row = 1;
                    // if (($handle = fopen($tmp_file_path, "r")) !== FALSE) {
                    //     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    //         $num = count($data);
                    //         echo "<p> $num полей в строке $row: <br /></p>\n";
                    //         $row++;
                    //         for ($c=0; $c < $num; $c++) {
                    //             echo $data[$c] . "<br />\n";
                    //         }
                    //     }
                    //     fclose($handle);
                    // }
                }
            }elseif($step == 3){
                $select_entity = protectInjectionWithoutQuote('entity');
                $entity = new os_cckEntity($db->_db);
                $entity->load($select_entity);

                $handle = fopen($tmp_file_path,'r');
                $data = fgetcsv($handle, null, $separator);

                AdminViewImportExport::importCsvStepThree($data, $entity, $tmp_file_path);
                
                // var_dump($select_entity); exit;
            }elseif($step == 4){
                
                $eid = protectInjectionWithoutQuote('eid');
                $first_row = protectInjectionWithoutQuote('first_row');
                $entity = new os_cckEntity($db->_db);
                $entity->load($eid);
                
                // var_dump($first_row); exit;
                $query = "SELECT lid FROM #__os_cck_layout WHERE type='add_instance' AND fk_eid='$eid' LIMIT 0,1";
                $db->setQuery($query);
                $lid = $db->loadResult();
                // var_dump($_REQUEST);
                $selected_field = protectInjectionWithoutQuote('selected_field', array(), 'ARRAY');
                $textfield_separator = protectInjectionWithoutQuote('textfield_separator');
                $textfield_sequence_number = protectInjectionWithoutQuote('textfield_sequence_number', array(), 'ARRAY');
                // var_dump($separator);
                // var_dump($textfield_separator);
                // var_dump($selected_field); exit;
                
                
                $row = 1;
                // var_dump(($handle = fopen($tmp_file_path, "r")) !== FALSE); exit;
                if (($handle = fopen($tmp_file_path, "r")) !== FALSE) {
                    while (($data = fgetcsv($handle, null, $separator)) !== FALSE) {
                        // var_dump($row)
                        $num = count($data);
                        if($row == 1 && $first_row != '1'){
                            $row++;
                            continue;
                        }
                        
                        $instance_data = array();

                        for ($c=0; $c < $num; $c++) {
                            // var_dump($textfield_separator[$c]);
                            if(isset($selected_field[$c]) && $selected_field[$c] != '' && !is_array($selected_field[$c])){
                                if(!isset($instance_data[$selected_field[$c]])){
                                    $instance_data[$selected_field[$c]] = array();
                                }
                                // var_dump($selected_field[$c]); exit;
                                if(!isset($instance_data[$selected_field[$c]][$textfield_sequence_number[$c]])){
                                    $instance_data[$selected_field[$c]][$textfield_sequence_number[$c]] = $data[$c] . $textfield_separator[$c];
                                }else{
                                    $instance_data[$selected_field[$c]][] = $data[$c] . $textfield_separator[$c];
                                }
                            }
                            // echo $data[$c] . "<br />\n";
                        }
                        // var_dump($instance_data);
                        $instanceAPI = new os_cckAPIInstance($db->_db, $eid);
                        $instanceAPI->fk_eid = $eid;
                        $instanceAPI->fk_lid = $lid;
                        $instanceAPI->title = '';
                        $instanceAPI->created = get_curent_site_time();
                        $instanceAPI->changed = "0000-00-00 00:00:00";
                        $instanceAPI->checked_out_time = "0000-00-00 00:00:00";
                        $instanceAPI->bind($instance_data);
                        $instanceAPI->store();
                    // var_dump($instanceAPI); exit;

                    //     if(false){
                    //     $query = '';
                        
                    //     // var_dump($instance_data);
                    //     // var_dump($instance->eiid);
                    //     // exit;
                    //     if(!empty($instance_data) && count($instance_data) > 0 && $instance->eiid ){
                    //         foreach($instance_data as $key => $value){
                    //             if(count($value) == 1){
                    //                  $instance_data[$key][0] = $value[1];
                    //                  unset($instance_data[$key][1]);
                    //             }else{
                    //                 ksort($value);
                    //                 $temp_val = $value;
                                    
                    //                 // var_dump($value); exit;
                    //                 if(stripos($key, 'text_textfield') !== false){
                    //                     $temp_val = implode('', $temp_val);
                    //                     // var_dump($temp_val);
                    //                     if(strlen($temp_val) > 255){
                    //                         $temp_val = substr($temp_val, 0, 254);
                    //                     }
                    //                     $instance_data[$key][0] = $temp_val;
                    //                 }else{
                    //                     $instance_data[$key] = $temp_val;
                    //                 }

                                    
                    //             }
                    //         }
                    //         // var_dump($instance_data); exit;
                    //         $update_and = '';
                    //         $query = "UPDATE #__os_cck_content_entity_$eid SET ";

                    //         foreach($instance_data as $key => $value){
                    //             if(stripos($key, 'galleryfield') === false){
                    //                 $value = $value[0];
                    //             }
                    //             if(stripos($key, 'imagefield') !== false  || stripos($key, 'filefield') !== false){
                    //                 // if( $query != "UPDATE #__os_cck_content_entity_$eid SET " && stripos($key, 'pricefield') === false) $query .= ", ";
                    //                 $file_headers = @get_headers($value);    
                    //                 if (stripos($file_headers[0],"404 Not Found") >0  || (stripos($file_headers[0], "302 Found") > 0 && stripos($file_headers[7],"404 Not Found") > 0)) {
                    //                     // return false;
                    //                 }else{
                    //                     if(stripos($key, 'imagefield') !== false){
                    //                         // $url = 'http://img.yandex.net/i/www/logo.png';
                    //                         // /home/vlados/public_html/joomla42/components/com_os_cck/files/images

                    //                         $file_inf = pathinfo($value);
   
                    //                         if(!isset($file_inf['extension'])) continue;
                                            
                    //                         $file_name = $file_inf['filename'];
                    //                         $file_name = str_replace('imagefield', $key, $file_name);
                    //                         $file_type = '.' . $file_inf['extension'];
                                            
                    //                         // var_dump($key);
                    //                         // var_dump($file_name);
                    //                         $path = JPATH_SITE . '/components/com_os_cck/files/images/'.$file_name.$file_type;
                    //                         file_put_contents($path, file_get_contents($value));
                    //                         $value = '/components/com_os_cck/files/images/'.$file_name.$file_type;
                    //                     }elseif(stripos($key, 'filefield') !== false){
                    //                         $file_inf = pathinfo($value);
   
                    //                         if(!isset($file_inf['extension'])) continue;
                                            
                    //                         $file_name = $file_inf['filename'];
                    //                         $file_name = str_replace('imagefield', $key, $file_name);
                    //                         $file_type = '.' . $file_inf['extension'];
                                            
                    //                         // var_dump($key);
                    //                         // var_dump($file_name);
                    //                         $path = JPATH_SITE . '/components/com_os_cck/files/images/'.$file_name.$file_type;
                    //                         file_put_contents($path, file_get_contents($value));
                    //                         $value = '/components/com_os_cck/files/'.$file_name.$file_type;
                    //                     }
                    //                     // var_dump($value);
                    //                 }
                    //             }elseif(stripos($key, 'galleryfield') !== false){
                    //                 // $aaaa = '[{"file":"hansel-2022-10-21.png","alt":"","name":""},{"file":"2023-01-28-17-41-431.png","alt":"","name":""},{"file":"2023-02-04-13-28-131.png","alt":"","name":""},{"file":"2023-02-06-17-38-241.png","alt":"","name":""},{"file":"photo-2023-02-07-14-32-18.jpg","alt":"","name":""}]';
                    //                 // if( $query != "UPDATE #__os_cck_content_entity_$eid SET " && stripos($key, 'pricefield') === false) $query .= ", ";
                    //                 if(!is_array($value)){
                    //                     $temp_val = json_decode($value);
                    //                 }else{
                    //                     if(count($value) == 1){
                    //                         $temp_json_decode_val = json_decode($value[0]);
                    //                         if(is_array( $temp_json_decode_val)){
                    //                             $temp_val = $temp_json_decode_val;
                    //                         }else{
                    //                             $temp_val = $value;
                    //                         }
                    //                         // var_dump( $temp_json_decode_val);
                    //                     }else{
                    //                         $temp_val = $value;
                    //                     }
                    //                     // $temp_val = $value;
                    //                 }
                    //                 // var_dump($temp_val);
                    //                 $fid = substr($key, strripos($key, '_')+1);
                    //                 // var_dump($temp_val); exit;
                    //                 $new_val = array();
                    //                 if($temp_val && !empty($temp_val)){
                    //                     // echo '222222222222'; exit;
                    //                     foreach($temp_val as $gal_row){
                    //                         if(is_object($gal_row)){
                    //                             $file = $gal_row->file;
                    //                         }else{
                    //                             $file = $gal_row;
                    //                             $gal_row = new stdClass();
                    //                             $gal_row->alt = '';
                    //                             $gal_row->name = '';
                    //                         }
                                            
                    //                         if($file != ''){
                    //                             $file_headers = @get_headers($file);
                    //                             // var_dump($file_headers);
                    //                             if (!is_bool($file_headers) && (stripos($file_headers[0],"404 Not Found") >0  || (stripos($file_headers[0], "302 Found") > 0 && stripos($file_headers[7],"404 Not Found") > 0))) {
                    //                                 // return false;
                    //                             }else{
                    //                                 $file_inf = pathinfo($file);
   
                    //                                 if(!isset($file_inf['extension'])) continue;
                                                    
                    //                                 $file_name = $file_inf['filename'];
                                                    
                                                    
                    //                                 // $file_name = str_replace('imagefield', $key, $file_name);
                    //                                 $file_type = '.' . $file_inf['extension'];
                    //                                 $gall_path = JPATH_SITE . '/images/com_os_cck'.$fid.'/original/'.$file_name.$file_type;
                    //                                 if(file_exists($gall_path)){
                    //                                     $file_name = $file_name . rand();
                    //                                 }
                                                    
                    //                                 // var_dump($gall_path);
                    //                                 // var_dump($file_name);
                    //                                 $path = JPATH_SITE . '/images/com_os_cck'.$fid.'/original/'.$file_name.$file_type;
                    //                                 $path_thmb = JPATH_SITE . '/images/com_os_cck'.$fid.'/thumbnail/'.$file_name.$file_type;
                    //                                 // var_dump($file);
                    //                                 file_put_contents($path, file_get_contents($file));
                    //                                 file_put_contents($path_thmb, file_get_contents($file));
                    //                                 $gal_row->file = $file_name.$file_type;
                    //                                 $new_val[] = $gal_row;
                    //                             }
                    //                         }
                    //                         // var_dump($new_val);
                    //                     }
                    //                     $value = json_encode($new_val);
                    //                     // var_dump($value); exit;
                    //                 }else{
                    //                     // $new_val[] = array();
                    //                     // var_dump($value); exit;
                    //                     if($value != ''){
                    //                         $file_headers = @get_headers($value);
                    //                         if (stripos($file_headers[0],"404 Not Found") >0  || (stripos($file_headers[0], "302 Found") > 0 && stripos($file_headers[7],"404 Not Found") > 0)) {
                    //                             // return false;
                    //                         }else{
                    //                             $gal_row = new stdClass();
                    //                             $gal_row->alt = '';
                    //                             $gal_row->name = '';
                    //                             $file_inf = pathinfo($value);

                    //                             if(!isset($file_inf['extension'])) continue;
                                                
                    //                             $file_name = $file_inf['filename'];
                                                
                                                
                    //                             // $file_name = str_replace('imagefield', $key, $file_name);
                    //                             $file_type = '.' . $file_inf['extension'];
                    //                             $gall_path = JPATH_SITE . '/images/com_os_cck'.$fid.'/original/'.$file_name.$file_type;
                    //                             if(file_exists($gall_path)){
                    //                                 $file_name = $file_name . rand();
                    //                             }
                                                
                    //                             // var_dump($gall_path);
                    //                             // var_dump($file_name);
                    //                             $path = JPATH_SITE . '/images/com_os_cck'.$fid.'/original/'.$file_name.$file_type;
                    //                             $path_thmb = JPATH_SITE . '/images/com_os_cck'.$fid.'/thumbnail/'.$file_name.$file_type;
                    //                             file_put_contents($path, file_get_contents($value));
                    //                             file_put_contents($path_thmb, file_get_contents($value));
                    //                             $gal_row->file = $file_name.$file_type;
                    //                             // var_dump($gal_row);
                    //                             $new_val[] = $gal_row;
                    //                         }
                    //                     }
                    //                     $value = json_encode($new_val);
                                        
                    //                     // var_dump($value ); exit;
                    //                 }
                    //                 // exit;
                    //                 // var_dump(json_decode($aaaa)); exit;
                    //                 // $file_inf = pathinfo($value);

                    //                 // if(!isset($file_inf['extension'])) continue;
                                    
                    //                 // $file_name = $file_inf['filename'];
                    //                 // $file_name = str_replace('imagefield', $key, $file_name);
                    //                 // $file_type = '.' . $file_inf['extension'];
                                    
                    //                 // // var_dump($key);
                    //                 // // var_dump($file_name);
                    //                 // $path = JPATH_SITE . '/components/com_os_cck/files/images/'.$file_name.$file_type;
                    //                 // file_put_contents($path, file_get_contents($value));
                    //                 // $value = '/components/com_os_cck/files/'.$file_name.$file_type;
                    //             }elseif(stripos($key, 'videofield') !== false){
                    //                 $temp_val = json_decode($value);
                    //                 // var_dump($temp_val); exit;
                    //                 $new_val = array();
                    //                 if(is_array($temp_val) && !empty($temp_val)){
                    //                     for($j = 0; $j < count($temp_val); $j++){
                    //                         $val = $temp_val[$j];
                    //                     // foreach($temp_val as $key1 => $val){
                    //                         if($j == 0){
                    //                             if(!empty($val)){
                                                    
                    //                                 foreach($val as $key2 => $video){
                    //                                     if(property_exists($video, 'src') && $video->src != '' && $video->type != ''){
                    //                                         $file_headers = @get_headers($video->src);
                    //                                         if (stripos($file_headers[0],"404 Not Found") >0  || (stripos($file_headers[0], "302 Found") > 0 && stripos($file_headers[7],"404 Not Found") > 0)) {
                    //                                             // return false;
                    //                                         }else{
                    //                                             $file_inf = pathinfo($video->src);
            
                    //                                             if(!isset($file_inf['extension'])) continue;
                                                                
                    //                                             $file_name = $file_inf['filename'];
                                                                
                                                                
                    //                                             // $file_name = str_replace('imagefield', $key, $file_name);
                    //                                             $file_type = '.' . $file_inf['extension'];
                    //                                             $gall_path = JPATH_SITE . '/components/com_os_cck/files/video/'.$file_name.$file_type;
                    //                                             if(file_exists($gall_path)){
                    //                                                 $file_name = $file_name . rand();
                    //                                             }
                                                                
                    //                                             // var_dump($gall_path);
                    //                                             // var_dump($file_name);
                    //                                             $path = JPATH_SITE . '/components/com_os_cck/files/video/'.$file_name.$file_type;
                                                                
                    //                                             file_put_contents($path, file_get_contents($video->src));
                                                                
                    //                                             $temp_val[$j][$key2]->src = '/components/com_os_cck/files/video/'.$file_name.$file_type;
                    //                                             // $new_val[] = $video->src;
                    //                                         }
                    //                                     }
                                                        
                    //                                 }
                    //                             }
                                                
                    //                         }elseif($j == 1){
                    //                             if(!empty($val)){
                                                    
                    //                                 foreach($val as $key2 => $track){
                    //                                     if(property_exists($track, 'src') && $track->src != ''){
                    //                                         $file_headers = @get_headers($track->src);
                    //                                         if (stripos($file_headers[0],"404 Not Found") >0  || (stripos($file_headers[0], "302 Found") > 0 && stripos($file_headers[7],"404 Not Found") > 0)) {
                    //                                             // return false;
                    //                                         }else{
                    //                                             $file_inf = pathinfo($track->src);
            
                    //                                             if(!isset($file_inf['extension'])) continue;
                                                                
                    //                                             $file_name = $file_inf['filename'];
                                                                
                                                                
                    //                                             // $file_name = str_replace('imagefield', $key, $file_name);
                    //                                             $file_type = '.' . $file_inf['extension'];
                    //                                             $gall_path = JPATH_SITE . '/components/com_os_cck/files/track/'.$file_name.$file_type;
                    //                                             if(file_exists($gall_path)){
                    //                                                 $file_name = $file_name . rand();
                    //                                             }
                                                                
                    //                                             // var_dump($gall_path);
                    //                                             // var_dump($file_name);
                    //                                             $path = JPATH_SITE . '/components/com_os_cck/files/track/'.$file_name.$file_type;
                                                                
                    //                                             file_put_contents($path, file_get_contents($track->src));
                                                                
                    //                                             $temp_val[$j][$key2]->src = '/components/com_os_cck/files/track/'.$file_name.$file_type;
                    //                                             // $new_val[] = $video->src;
                    //                                         }
                    //                                     }
                                                        
                    //                                 }
                    //                             }
                    //                         }
                    //                     }
                    //                 }
                    //                 $value = $temp_val;
                                    
                    //             }elseif(stripos($key, 'audiofield') !== false){
                    //                 $temp_val = json_decode($value);
                    //                 // var_dump($temp_val); exit;
                    //                 $new_val = array();
                    //                 if(is_array($temp_val) && !empty($temp_val)){
                    //                     foreach($temp_val as $key1 => $val){
                                            
                                               
                    //                         if(property_exists($val, 'src') && $val->src != '' && $val->type != ''){
                    //                             $file_headers = @get_headers($val->src);
                    //                             if (stripos($file_headers[0],"404 Not Found") >0  || (stripos($file_headers[0], "302 Found") > 0 && stripos($file_headers[7],"404 Not Found") > 0)) {
                    //                                 // return false;
                    //                             }else{
                    //                                 $file_inf = pathinfo($val->src);

                    //                                 if(!isset($file_inf['extension'])) continue;
                                                    
                    //                                 $file_name = $file_inf['filename'];
                                                    
                                                    
                    //                                 // $file_name = str_replace('imagefield', $key, $file_name);
                    //                                 $file_type = '.' . $file_inf['extension'];
                    //                                 $gall_path = JPATH_SITE . '/components/com_os_cck/files/audio/'.$file_name.$file_type;
                    //                                 if(file_exists($gall_path)){
                    //                                     $file_name = $file_name . rand();
                    //                                 }
                                                    
                    //                                 // var_dump($gall_path);
                    //                                 // var_dump($file_name);
                    //                                 $path = JPATH_SITE . '/components/com_os_cck/files/audio/'.$file_name.$file_type;
                                                    
                    //                                 file_put_contents($path, file_get_contents($val->src));
                                                    
                    //                                 $temp_val[$key1]->src = 'components/com_os_cck/files/audio/'.$file_name.$file_type;
                    //                                 // $new_val[] = $video->src;
                    //                             }
                    //                         }
                                                    
                                                
                                            
                                            
                    //                     }
                    //                 }
                    //                 $value = $temp_val;
                                    
                    //             }elseif(stripos($key, 'categoryfield') !== false){
                    //                 // var_dump($value);
                    //                 if($value != ''){
                    //                     $category_query = "SELECT cid FROM #__os_cck_categories WHERE title='$value'";
                    //                     $db->setQuery($category_query);
                    //                     $cid = $db->loadResult();

                    //                     if(!$cid){
                    //                         $category = new os_cckCategory($db->_db);
                    //                         $category->title = $value;
                    //                         $category->checked_out_time = '0000-00-00 00:00:00';
                    //                         $category->name = $value;
                    //                         // $category->name = $value;
                    //                         $category->section = 'com_os_cck';
                    //                         $category->parent_id = 0;
                    //                         $category->fk_eid = 0;
                    //                         $category->description = '';
                    //                         $category->params = '1';
                    //                         $category->published = '1';
                    //                         // var_dump($category); exit;
                    //                         if (!$category->store()) {
                    //                             echo "<script> alert('" . addslashes($category->getError()) . "'); window.history.go(-1); </script>\n";
                    //                             exit();
                    //                         }
                    //                         // $category->store();

                    //                         $value = $category->cid;

                    //                         $cat_con_query = "INSERT INTO #__os_cck_categories_connect (`fk_eiid`, `fk_cid`) VALUES ('".$instance->eiid."', '".$category->cid."');";
                    //                         $db->setQuery($cat_con_query);
                    //                         $db->execute();


                    //                     }else{
                    //                         $value = $cid;
                    //                         $cat_con_query = "INSERT INTO #__os_cck_categories_connect (`fk_eiid`, `fk_cid`) VALUES ('".$instance->eiid."', '".$cid."');";
                    //                         $db->setQuery($cat_con_query);
                    //                         $db->execute();
                    //                     }
                    //                     // var_dump($value);
                    //                 }
                    //             }else{
                    //                 // echo '1111111111111111<br>';
                    //                 // var_dump($key);
                                    
                    //             }

                    //             if( $query != "UPDATE #__os_cck_content_entity_$eid SET " && stripos($key, 'pricefield') === false){
                    //                 $temp_query = strrev($query);
                    //                 // echo $query . '<br>';
                    //                 if(stripos($temp_query, ', ') !== 0 && stripos($temp_query, ',') !== 0 && stripos($temp_query, ' ,') !== 0){
                    //                     $query .= ", ";
                    //                 }

                                     
                    //             }
                    //             if(stripos($key, 'imagefield') !== false  || stripos($key, 'filefield') !== false || stripos($key, 'galleryfield') !== false){

                    //                 $query .= " " . $key . "_data=".$db->Quote($value)." ";
                    //                 // if(stripos($key, 'galleryfield') !== false){
                    //                 //     $query .= ", ";
                    //                 // }
                    //             }elseif(stripos($key, 'videofield') !== false){
                    //                 // var_dump($value); exit;
                    //                 $fid = str_replace('videofield_', '', $key);
                                    
                    //                 if(!empty($value)){
                    //                     for($j = 0; $j < count($value); $j++){
                    //                         $temp_val = $value[$j];
                    //                         if($j == 0){
                    //                             if(!empty($temp_val)){
                    //                                 foreach($temp_val as $video){
                    //                                     $video_query = "INSERT INTO `#__os_cck_video_source` (`fk_eiid`, `fk_fid`, `src`, `type`, `media`, `youtube`) VALUE ('$instance->eiid', '$fid', " . $db->Quote(($video->src) ? $video->src : '') . ", '$video->type', '$video->media', '$video->youtube')";
                                                        
                    //                                     $db->setQuery($video_query);
                    //                                     try{
                    //                                         $db->execute();
                    //                                     }catch (RuntimeException $e) {
                    //                                         echo $video_query;
                    //                                         echo $e->getMessage();
                    //                                     }
                                                        
                    //                                 }
                    //                             }
                    //                         }elseif($j == 1){
                    //                             if(!empty($temp_val)){
                    //                                 foreach($temp_val as $track){
                    //                                     $sequence_number = (is_int($track->sequence_number)) ? $track->sequence_number : 0;
                    //                                     // var_dump($sequence_number);
                    //                                     $video_query = "INSERT INTO `#__os_cck_track_source` ".
                    //                                         " (`fk_eiid`,`fk_fid`, `fk_video_id`, `sequence_number`, `src`, `kind`, `scrlang`, `label`) VALUE ('$instance->eiid', '$fid', '$track->fk_video_id', '$sequence_number', " . $db->Quote(($track->src) ? $track->src : '') . ", '$track->kind', '$track->scrlang', '$track->label')";
                    //                                     $db->setQuery($video_query);
                    //                                     try{
                    //                                         $db->execute();
                    //                                     }catch (RuntimeException $e) {
                    //                                         echo $video_query;
                    //                                         echo $e->getMessage();
                    //                                     }
                                                        
                    //                                 }
                    //                             }
                    //                         }
                    //                     }
                    //                 }
                    //             }elseif(stripos($key, 'audiofield') !== false){
                    //                 $fid = str_replace('audiofield_', '', $key);
                                    
                    //                 if(!empty($value)){
                    //                     foreach($value as $temp_val){
                    //                         $audio_query = "INSERT INTO `#__os_cck_audio_source` (`fk_eiid`, `fk_fid`, `sequence_number`, `src`, `type`) VALUE ('$instance->eiid', '$fid', ". $db->Quote(($temp_val->sequence_number) ? $temp_val->sequence_number : '0') . "," . $db->Quote(($temp_val->src) ? $temp_val->src : '') . ", '$temp_val->type')";
                    //                         $db->setQuery($audio_query);
                    //                         try{
                    //                             $db->execute();
                    //                         }catch (RuntimeException $e) {
                    //                             echo $audio_query;
                    //                             echo $e->getMessage();
                    //                         }
                    //                     }
                    //                 }
                    //             }elseif(stripos($key, 'pricefield') !== false){

                    //                 $temp_val = json_decode($value);
                    //                 // var_dump($temp_val); exit;
                    //                 $temp_key = trim($key, "'");

                    //                 if(stripos($temp_key, 'pricefield_number') !== false){
                    //                     $fid = str_replace('pricefield_number_', '', $temp_key);    
                    //                 }elseif(stripos($temp_key, 'pricefield_radio_buttons') !== false){
                    //                     $fid = str_replace('pricefield_radio_buttons_', '', $temp_key);    
                    //                 }elseif(stripos($temp_key, 'pricefield_select_list') !== false){
                    //                     $fid = str_replace('pricefield_select_list_', '', $temp_key);    
                    //                 }
                    //                 // var_dump($instance->fk_eid); exit;
                    //                 if(is_array($temp_val) && !empty($temp_val)){
                    //                     foreach($temp_val as $temp_price){
                    //                         $price_query = "INSERT INTO `#__os_cck_content_instances_price` (`fk_eid`, `fk_eiid`, `fk_fid`, `price_name`, `price_value`, `quantity`, `ordering`) 
                    //                         VALUE ('$instance->fk_eid', '$instance->eiid', '$fid', '$temp_price->price_name', '$temp_price->price_value', '$temp_price->quantity', '$temp_price->ordering')";

                    //                         $db->setQuery($price_query);
                    //                         try{
                    //                             $db->execute();
                    //                         } catch (RuntimeException $e) {
                    //                             ini_set('xdebug.var_display_max_depth', -1);
                    //                             ini_set('xdebug.var_display_max_children', -1);
                    //                             ini_set('xdebug.var_display_max_data', -1);
                    //                             var_dump($price_query) ;
                    //                             var_dump($instance->fk_eid);
                    //                             echo $e->getMessage();
                    //                             exit;
                    //                         }
                    //                     }
                    //                 }elseif(is_string($temp_val) || is_int($temp_val)){
                    //                     $price_query = "INSERT INTO `#__os_cck_content_instances_price` (`fk_eid`, `fk_eiid`, `fk_fid`, `price_name`, `price_value`, `quantity`, `ordering`) 
                    //                         VALUE ('$instance->fk_eid', '$instance->eiid', '$fid', '$temp_val', '$temp_val', '-1', '0')";

                    //                     $db->setQuery($price_query);
                    //                     try{
                    //                         $db->execute();
                    //                     } catch (RuntimeException $e) {
                    //                         ini_set('xdebug.var_display_max_depth', -1);
                    //                         ini_set('xdebug.var_display_max_children', -1);
                    //                         ini_set('xdebug.var_display_max_data', -1);
                    //                         var_dump($price_query) ;
                    //                         var_dump($instance->fk_eid);
                    //                         echo $e->getMessage();
                    //                         exit;
                    //                     }
                    //                 }

                    //                 // var_dump($temp_val);
                    //             }elseif(stripos($key, 'locationfield') !== false){
                    //                 if($value != ''){
                    //                     $temp_lalue = json_decode($value);
                    //                     if(is_array($temp_lalue)){
                    //                         $temp_lalue = $temp_lalue[0];
                    //                     }

                    //                     if(is_object($temp_lalue)){
                    //                         $vlat = (isset($temp_lalue->vlat)) ? $temp_lalue->vlat : 0;
                    //                         $vlong = (isset($temp_lalue->vlong)) ? $temp_lalue->vlong : 0;
                    //                         $zoom = (isset($temp_lalue->zoom)) ? $temp_lalue->zoom : 0;
                    //                         $address = (isset($temp_lalue->address)) ? $temp_lalue->address : '';
                    //                         $country = (isset($temp_lalue->country)) ? $temp_lalue->country : '';
                    //                         $region = (isset($temp_lalue->region)) ? $temp_lalue->region : '';
                    //                         $city = (isset($temp_lalue->city)) ? $temp_lalue->city : '';
                    //                         $zipcode = (isset($temp_lalue->zipcode)) ? $temp_lalue->zipcode : '';
                    //                         // var_dump(" ".$key."_vlat='" . $vlat . "' , ");
                    //                         $query .= " ".$key."_vlat='" . $vlat . "' , ";
                    //                         $query .= " ".$key."_vlong='" . $vlong ."' , ";
                    //                         $query .= " ".$key."_zoom='" . $zoom  ."' , ";
                    //                         $query .= " ".$key."_address='" . $address ."' , ";
                    //                         $query .= " ".$key."_country='" . $country ."' , ";
                    //                         $query .= " ".$key."_region='" . $region ."' , ";
                    //                         $query .= " ".$key."_city='" . $city ."' , ";
                    //                         $query .= " ".$key."_zipcode='" . $zipcode ."'";
                    //                         // echo $query;
                    //                     }
                    //                     // var_dump($temp_lalue); exit;
                    //                 }else{
                    //                     $query .= " ".$key."_vlat='0' , ";
                    //                     $query .= " ".$key."_vlong='0' , ";
                    //                     $query .= " ".$key."_zoom='0' , ";
                    //                     $query .= " ".$key."_address='' , ";
                    //                     $query .= " ".$key."_country='' , ";
                    //                     $query .= " ".$key."_region='' , ";
                    //                     $query .= " ".$key."_city='' , ";
                    //                     $query .= " ".$key."_zipcode=''";
                    //                 }
                    //             }else{
                    //                 // var_dump($key);
                    //                 $key_string = trim($key, "'");
                    //                 $query .= " $key_string=".$db->Quote($value)." ";
                    //             }
                                
                    //         }
                    //         // exit;
                    //         $query = trim($query);
                    //         if((strlen($query)-1) == strripos($query, ',')){
                    //             $query = trim($query, ',');
                    //         }
                    //         // var_dump(strlen($query));
                    //         // var_dump(strripos($query, ','));
                    //         // var_dump($query);
                    //         if( $query != "UPDATE #__os_cck_content_entity_$eid SET"){
                    //             $query .= " WHERE fk_eiid=$instance->eiid;" ;
                    //         }

                    //     }
                    //     // var_dump($query); exit;
                    //     if($query != '' && $query != "UPDATE #__os_cck_content_entity_$eid SET"){
                    //         $db->setQuery($query);
                    //         try{
                    //             $db->execute();
                    //         } catch (RuntimeException $e) {
                    //             ini_set('xdebug.var_display_max_depth', -1);
                    //             ini_set('xdebug.var_display_max_children', -1);
                    //             ini_set('xdebug.var_display_max_data', -1);
                    //             var_dump($query) ;
                    //             echo $e->getMessage();
                    //             exit;
                    //         }
                    //     }
                    // }
                        // var_dump($instance_data);
                    }
                    fclose($handle);
                }
                // exit;
                JFile::delete($tmp_file_path);
                AdminViewImportExport::import('3');
                // var_dump($_REQUEST); exit;
            }
        }

        static function csv_export(){
            global $entityFieldLists, $db;
            $db = new os_cckDb();
            $step = protectInjectionWithoutQuote('step', 2);
            
            
            if($step == 2){
                $enteties = protectInjectionWithoutQuote('entity', array(), 'ARRAY');
                $fieldSelectOpt = array();
                if(!empty($enteties)){
                    foreach($enteties as $eid){
                        // var_dump($eid);
                        foreach($entityFieldLists[$eid] as $field){
                            $fieldSelectOpt[$eid][] = JHTML::_('select.option',$field->fid, $field->field_name);
                        }
                    }
                }

                AdminViewImportExport::exportCsvStepTwo($fieldSelectOpt, $enteties);
            }elseif($step == 3){
                $fields = protectInjectionWithoutQuote('fields', array(), 'ARRAY');
                $list_for_csv = array();

                // var_dump($fields);
                foreach($fields as $eid => $field_arr){
                    // var_dump($entityFieldLists[$eid]);
                    foreach($field_arr as $fid){
                        $field = $entityFieldLists[$eid][$fid];
                        $list_for_csv[0][] = $field->field_name;

                    }
                    
                    $entity = new os_cckEntity($db->_db);
                    $entity->load($eid);

                    $query = "SELECT ei.eiid FROM #__os_cck_entity_instance as ei
                    LEFT JOIN #__os_cck_layout as l ON l.lid=ei.fk_lid
                    WHERE ei.fk_eid=$eid AND l.type='add_instance'";
                    $db->setQuery($query);
                    $eiids = $db->loadObjectList();


                    if(!empty($eiids)){
                        foreach($eiids as $eiid){
                            // var_dump($eiid);
                            $entityInstance = new os_cckEntityInstance($db->_db);
                            $entityInstance->load($eiid->eiid);
                            foreach($field_arr as $fid){
                                $value = $entityInstance->getFieldValue($entityFieldLists[$eid][$fid]);
                                
                                if($entityFieldLists[$eid][$fid]->field_type == 'imagefield' || $entityFieldLists[$eid][$fid]->field_type == 'filefield'){
                                    $value[0]->data = JURI::root() . $value[0]->data;
                                }elseif($entityFieldLists[$eid][$fid]->field_type == 'galleryfield'){
                                    if($value[0]->data != ''){
                                        $temp_val = json_decode($value[0]->data);
                                        if(!empty($temp_val)){
                                            foreach($temp_val as $key_row => $row){
                                                $temp_val[$key_row]->file = JURI::root() . 'images/com_os_cck' . $fid. '/original/'.$row->file;
                                            }
                                        }
                                        $value[0]->data = json_encode($temp_val);
                                        // var_dump($temp_val);
                                    }
                                    // var_dump($value); exit;
                                }elseif($entityFieldLists[$eid][$fid]->field_type == 'categoryfield'){
                                    $temp_val = array();
                                    if(count($value) > 1){
                                        foreach($value as $temp_val_obj){
                                            $temp_val[] = $temp_val_obj->title;
                                        }
                                        $temp_val = json_encode($temp_val);
                                    }else{
                                        $temp_val = $value[0]->title;
                                    }
                                    $value[0]->data = $temp_val;
                                }elseif($entityFieldLists[$eid][$fid]->field_type == 'videofield'){
                                    if(is_array($value) && !empty($value)){
                                        foreach($value as $key1 => $temp_vid){
                                            if(!empty($temp_vid)){
                                                foreach($temp_vid as $key2 => $vid){
                                                    // var_dump($vid->src != '');
                                                    if(property_exists($vid, 'src') && $vid->src != ''&& stripos($vid->src, 'http') === false){
                                                        $value[$key1][$key2]->src = JURI::root() . $vid->src;
                                                    }
                                                    
                                                }
                                            }
                                            
                                        }

                                        
                                    } 
                                    $temp_value = array();
                                    $temp_data = new stdClass();
                                    $temp_data->data = json_encode($value);
                                    $temp_value[] = $temp_data;
                                    $value = $temp_value;
                                    // var_dump($value);
                                    // exit;
                                }elseif($entityFieldLists[$eid][$fid]->field_type == 'audiofield'){
                                    if(is_array($value) && !empty($value)){
                                        foreach($value as $key1 => $temp_val){
                                            if($temp_val->src != '' && stripos($temp_val->src, 'http') === false){
                                                $value[$key1]->src = JURI::root() . $temp_val->src;
                                            }
                                        }
                                    }
                                    $temp_value = array();
                                    $temp_data = new stdClass();
                                    $temp_data->data = json_encode($value);
                                    $temp_value[] = $temp_data;
                                    $value = $temp_value;
                                    // var_dump($value); exit;
                                }elseif(stripos($entityFieldLists[$eid][$fid]->field_type, 'pricefield') !== false){
                                    // var_dump($value);
                                    // if(is_array($value) && !empty($value)){
                                    //     foreach($value as $key1 => $temp_val){
                                    //         if($temp_val->src != '' && stripos($temp_val->src, 'http') === false){
                                    //             $value[$key1]->src = JURI::root() . $temp_val->src;
                                    //         }
                                    //     }
                                    // }
                                    $temp_value = array();
                                    $temp_data = new stdClass();
                                    $temp_data->data = json_encode($value);
                                    $temp_value[] = $temp_data;
                                    $value = $temp_value;
                                    // var_dump($value); exit;
                                }elseif($entityFieldLists[$eid][$fid]->field_type == 'locationfield'){
                                    // if(is_array($value) && !empty($value)){
                                    //     foreach($value as $key1 => $temp_val){
                                    //         if($temp_val->src != '' && stripos($temp_val->src, 'http') === false){
                                    //             $value[$key1]->src = JURI::root() . $temp_val->src;
                                    //         }
                                    //     }
                                    // }
                                    $temp_value = array();
                                    $temp_data = new stdClass();
                                    $temp_data->data = json_encode($value);
                                    $temp_value[] = $temp_data;
                                    $value = $temp_value;
                                    // var_dump($value); exit;
                                }
                                
                                if(isset($value[0]) && property_exists($value[0], 'data')){
                                    $list_for_csv[$eiid->eiid][] = $value[0]->data;      
                                }else{
                                    $list_for_csv[$eiid->eiid][] = '';
                                }
                            }
                            // exit;

                        }
                    }

                    // var_dump($eiids);
                }
                $fileName = "os_cck_" . date("Ymd_His");
                $fileBase = "administrator/components/com_os_cck/exports/";

                //write the csv file
                $fp = fopen(JPATH_SITE . '/' . $fileBase . $fileName . ".csv", "w", 0); #open for writing

                foreach ($list_for_csv as $fields) {
                    fputcsv($fp, $fields);
                }
                
                fclose($fp);
                $InformationArray = array('urlBase' => JURI::root() . $fileBase, 'out_file' => $fileName . '.csv');
                AdminViewImportExport::showExportResult($InformationArray, 'com_os_cck');
                // var_dump($_REQUEST); exit;
            }
            // var_dump($fieldSelectOpt); exit;
        }

}


