<?php
if (!defined('_VALID_MOS') && !defined('_JEXEC')) die('Direct Access to ' 
    . basename(__FILE__) . ' is not allowed.');
/**
 *
 * @package  MediaLibrary
 * @copyright 2021 Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru); Rob de Cleen(rob@decleen.com);
 * Homepage: https://ordasoft.com
 * @version: 4.6 Free
 * @license GNU General Public license version 2 or later; see LICENSE.txt
 *
 */

require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.people.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary_game.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary_music.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary_book.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary_video.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/includes/category.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.main.categories.class.php");
function print_vars($obj) {
    $arr = get_object_vars($obj);
    while (list($prop, $val) = each($arr)) if (class_exists($val)) print_vars($val);
    else echo "\t $prop = $val\n<br />";
}
function print_methods($obj) {
    $arr = get_class_methods(get_class($obj));
    foreach($arr as $method) echo "\tfunction $method()\n <br />";
}
if (PHP_VERSION >= 5) {
    // Emulate the old xslt library functions
    function xslt_create() {
        return new XsltProcessor();
    }
    function xslt_process($xsltproc, $xml_arg, $xsl_arg, $xslcontainer = null, $args = null, $params = null) {
        // Create instances of the DomDocument class
        $xml = new DomDocument;
        $xsl = new DomDocument;
        // Load the xml document and the xsl template
        $xml->load($xml_arg);
        $xsl->load($xsl_arg);
        // Load the xsl template
        $xsltproc->importStyleSheet($xsl);
        // Set parameters when defined
        if ($params) {
            foreach($params as $param => $value) {
                $xsltproc->setParameter("", $param, $value);
            }
        }
        // Start the transformation
        $processed = $xsltproc->transformToXML($xml);
        // Put the result in a file when specified
        if ($xslcontainer) {
            return @file_put_contents($xslcontainer, $processed);
        } else {
            return $processed;
        }
    }
    function xslt_free($xsltproc) {
        unset($xsltproc);
    }
}
class mosMediaLibraryImportExport {
    /**
     * Imports the lines given to this method into the database and writes a
     * table containing the information of the imported medias.
     * The imported books will be set to [not published]
     * Format: #;id;isbn;title;author;language
     * @param array lines - an array of lines read from the file
     * @param int catid - the id of the category the books should be added to
     */
    function importMediasCSV($lines, $catid) {
        global $database;
        $retVal = array();
        $i = 0;
        foreach($lines as $line) {
            $tmp = array();
            if (trim($line) == "") continue;
            $line = explode('|', $line); //edit nik  old -->, -1);
            $book = new mosMediaLibrary($database);
            $book->bookid = trim($line[0]);
            $book->isbn = $line[1];
            $book->title = $line[2];
            //$book->authors = $line[3];
            $book->manufacturer = $line[4];
            $book->catid = $catid;
            //$book->date = date("Y-m-d H:i:s");
            $book->date = $line[15];
            $book->language = $line[5]; //Language
            $book->comment = $line[16]; //Book Description
            // optimize!!!
            $tmp[0] = $i;
            $tmp[1] = trim($line[0]);
            $tmp[2] = $line[1];
            $tmp[3] = $line[2];
            $tmp[4] = $line[3];
            $tmp[5] = $line[4];
            if (!$book->check() || !$book->store()) {
                $tmp[6] = $book->getError();
            } else {
                $tmp[6] = "OK";
            }
            $book->checkin();
            $book->updateOrder("catid='$book->catid'");
            $retVal[$i] = $tmp;
            $i++;
        }
        return $retVal;
    }
    static function getXMLItemValue($item, $item_name) {
        $book_items = $item->getElementsByTagname($item_name);
        $book_item = $book_items->item(0);
        if (NULL != $book_item) return $book_item->nodeValue;
        else return "";
    }
    //****************************************************************************************
    //***********************   begin add for import XML format   ****************************
    //****************************************************************************************
    static function findCategory(&$categories, $new_category) {
        global $database;
        foreach($categories as $category) {
            if ($category->old_id == $new_category->old_id) return $category;
        }
        $new_parent_id = null;
        if ($new_category->old_parent_id != 0) {
            foreach($categories as $category) {
                if ($category->old_id == $new_category->old_parent_id) {
                    $new_parent_id = $category->id;
                    break;
                }
            }
        } else $new_parent_id = 0;
        //sanity test
        if ($new_parent_id === null) {
            //echo "error in import !"; exit;
            $new_parent_id = 0;
        }
        //$row = new mosCategory($database);
        $row = new mainMedialibraryCategories($database); //for 1.6
        $row->section = 'com_medialibrary';
        $row->parent_id = $new_parent_id;
        $row->name = $new_category->name;
        $row->title = $new_category->title;
        $row->published = $new_category->published;
        $row->ordering = $new_category->ordering;
        $row->access = $new_category->access;
        $row->description = $new_category->description;
        $row->params = $new_category->params;
        $row->langDescription = $new_category->langDescription;
        $row->associate_category = $new_category->associate_category;
        
        if (!$row->check()) {
            echo "error in import2 !";
            exit;
            exit();
        }
        if (!$row->store()) {
            echo "error in import3 !";
            exit;
            exit();
        }
        $row->updateOrder("section='com_medialibrary' AND parent_id='$row->parent_id'");
        $new_category->id = $row->id;
        $categories[] = $new_category;
        return $new_category;
    }
    
    static function CreateOldVersionPeople(){
        global $database;
        $query = "  DELETE FROM #__medialibrary_people_connect; ";
        $database->setQuery($query);
        $database->query(); 
        $query = "  DELETE FROM #__medialibrary_people; ";
        $database->setQuery($query);
        $database->query();

        $query = "  SELECT * FROM (
                        SELECT g.id as media_id, g.studio as people_name, 'game_studio' as type, 
                                'game' as `media_type`
                            FROM #__medialibrary_game AS g 
                        UNION  SELECT m.id as media_id, m.artist as people, 'artist' as type,
                                'music' as `media_type`
                            FROM #__medialibrary_music AS m 
                        UNION  SELECT b.id as media_id, b.authors as people, 'author' as type, 
                                'book' as `media_type`
                            FROM #__medialibrary_book AS b 
                        UNION  SELECT v.id as media_id, v.studio as people, 'video_studio' as type, 
                                'video' as `media_type`
                            FROM #__medialibrary_video AS v ) other_table
                    WHERE  !ISNULL(other_table.people_name) AND other_table.people_name != ''";
        $database->setQuery($query);
        $database->query(); 
        $peoples_to_creaty = $database->loadObjectList();
        foreach($peoples_to_creaty as $people_to_creaty){
            $query = "  SELECT id  FROM #__medialibrary
                        WHERE ($people_to_creaty->media_id = media_id) AND 
                              ('$people_to_creaty->media_type' = media_type)";
            $database->setQuery($query);
            $database->query(); 
            $global_id_media = $database->loadResult();

            if (strpos($people_to_creaty->people_name,',')){
                $peoples = explode(',',$people_to_creaty->people_name);
            } else {
                $peoples = array($people_to_creaty->people_name);
            }

            foreach($peoples as $people){
                $query = "INSERT INTO #__medialibrary_people 
                                (people_name, type, associate_people, published, description, 
                                    auto_gener_description, owneremail) 
                                VALUES ('$people', '$people_to_creaty->type','' ,'1' ,'' ,'', '')";
                $database->setQuery($query);
                $database->query(); 
                $id_new_people = $database->insertid() ;
                
                $query = "INSERT INTO #__medialibrary_people_connect 
                                (fk_media_id, fk_people_id) VALUES ('$global_id_media', '$id_new_people')";
                $database->setQuery($query);
                $database->query(); 
            }
        }
                

    }
    static function updateAssociateCategories($infoArr){
        $dataToUpdate = array();
        global $database;
        for($i = 0; $i < count($infoArr); $i++){ 
            if(isset($infoArr[$i]['associate']) && $infoArr[$i]['associate']){
                $currentAssocId = array();
                $newObjAssociate = unserialize($infoArr[$i]['associate']);
                
                foreach ($newObjAssociate as $key=>$value){
                    if($value && $value != 0){
                        for($j = 0; $j < count($infoArr); $j++){
                            if(isset($infoArr[$j]['oldId']) && $infoArr[$j]['oldId'] == $value){ 
                                $newObjAssociate[$key] = $infoArr[$j]['newId'];
                                $currentAssocId[] = $infoArr[$j]['newId'];
                                break;
                            }
                        }
                    }         
                } 
                
                $newSerializAssoc = serialize($newObjAssociate);
                $currentAssocIdToString = implode(',', $currentAssocId);
                if(!isset($dataToUpdate[$newSerializAssoc])){
                    $dataToUpdate[$newSerializAssoc] = $currentAssocIdToString;
                }
            }    
        }  
        
        if(!empty($dataToUpdate)){
            foreach ($dataToUpdate as $key=>$value){
                if(isset($key) && $key !="" && isset($value) && $value !="" ){
                    $query = "UPDATE #__medialibrary_main_categories
                              SET associate_category = '$key'
                              WHERE id in ($value)";
                    $database->setQuery($query);
                    $database->query();
                }
            }
        }
    }
    static function updateAssociatePeople($infoArr){
        global $database;
        $dataToUpdate = array();
        $dataToUpdateConnect = array();
        for($i = 0; $i < count($infoArr); $i++){ 
            if(isset($infoArr[$i]['associate']) && $infoArr[$i]['associate']){
                $currentAssocId = array();
                $newObjAssociate = unserialize($infoArr[$i]['associate']);
                
                foreach ($newObjAssociate as $key=>$value){
                    if($value && $value != 0){
                        for($j = 0; $j < count($infoArr); $j++){
                            if(isset($infoArr[$j]['oldId']) && $infoArr[$j]['oldId'] == $value){ 
                                $newObjAssociate[$key] = $infoArr[$j]['newId'];
                                $currentAssocId[] = $infoArr[$j]['newId'];
                                break;
                            }
                        }
                    }         
                } 
                $dataToUpdateConnect[$infoArr[$j]['oldId']] = $infoArr[$j]['newId'] ; 
                $newSerializAssoc = serialize($newObjAssociate);
                $currentAssocIdToString = implode(',', $currentAssocId);
                if(!isset($dataToUpdate[$newSerializAssoc])){
                    $dataToUpdate[$newSerializAssoc] = $currentAssocIdToString;
                }
            }    
        }  
        if(!empty($dataToUpdate)){
            foreach ($dataToUpdate as $key=>$value){
                if(isset($key) && $key !="" && isset($value) && $value !="" ){
                    $query = "UPDATE #__medialibrary_people
                              SET associate_people = '$key'
                              WHERE id in ($value)";
                    $database->setQuery($query);
                    $database->query();
                }
            }
        }
        // print_r($dataToUpdateConnect);exit;
        // if(!empty($dataToUpdateConnect)){
        //     foreach ($dataToUpdateConnect as $key=>$value){
        //         if(isset($key) && $key !="" && isset($value) && $value !="" ){
        //             $query = "UPDATE #__medialibrary_people_connect
        //                       SET fk_people_id = $value
        //                       WHERE fk_people_id = $key";
        //             $database->setQuery($query);
        //             $database->query();
        //         }
        //     }
        // }
    }
    
     static function updateAssociateMedias($infoArr){
        $dataToUpdate = array();
        global $database;
        for($i = 0; $i < count($infoArr); $i++){ 
            if(isset($infoArr[$i]['associate']) && $infoArr[$i]['associate']){
                $currentAssocId = array();
                $newObjAssociate = unserialize($infoArr[$i]['associate']);
                foreach ($newObjAssociate as $key=>$value){
                    if($value && $value != 0){
                        for($j = 0; $j < count($infoArr); $j++){
                            if(isset($infoArr[$j]['oldId']) && $infoArr[$j]['oldId'] == $value){ 
                                $newObjAssociate[$key] = $infoArr[$j]['newId'];
                                $currentAssocId[] = $infoArr[$j]['newId'];
                                break;
                            }
                        }
                    }  
                } 
                $newSerializAssoc = serialize($newObjAssociate);
                $currentAssocIdToString = implode(',', $currentAssocId);
                if(!isset($dataToUpdate[$newSerializAssoc])){
                    $dataToUpdate[$newSerializAssoc] = $currentAssocIdToString;
                }
            }    
        }  
        if(!empty($dataToUpdate)){  
            foreach ($dataToUpdate as $key=>$value){ 
                $query = "UPDATE #__medialibrary
                          SET associate_media = '$key'
                          WHERE id in ($value) ";
                $database->setQuery($query);
                $database->query();  
            }
        }
    }
    
    static function importMediasXML($files_name_pars, $catid) {
        global $database;
        $files_name_pars = file($files_name_pars);
        $files_name_pars = implode('', $files_name_pars);
        $retVal = array();
        $retValError = array();
        $new_categories = array();
        $k = 0;
        $dom = new domDocument('1.0', 'utf-8');
        $dom->loadXML($files_name_pars);
        $version = $dom->getElementsByTagName('version');
        $old_new_id_connect = array(); 
                        
        if ($version->item(0) != NULL) {
            $numversion = explode(' ', $version->item(0)->nodeValue);
            if (intval($numversion[0]) >= 1) {
                $categories_xml = $dom->getElementsByTagName('category');
                if ($categories_xml->item(0) != NULL) {
                    if ($catid === null) {
                        mosMedialibraryImportExport::remove_info();
                        for ($i = 0;$i < $categories_xml->length;$i++) {
                            $category = $categories_xml->item($i);
                            $new_category = null;
                            $new_category = new stdClass();
                            $new_category->old_id = mosMedialibraryImportExport::getXMLItemValue($category, 'id');
                            $new_category->old_parent_id = mosMedialibraryImportExport::getXMLItemValue($category,
                                    'parent_id');
                            $new_category->name = mosMedialibraryImportExport::getXMLItemValue($category, 'name');
                            $new_category->title = mosMedialibraryImportExport::getXMLItemValue($category,'title');
                            $new_category->published = mosMedialibraryImportExport::getXMLItemValue($category, 
                                    'published');
                            $new_category->ordering = mosMedialibraryImportExport::getXMLItemValue($category, 
                                    'ordering');
                            $new_category->access = mosMedialibraryImportExport::getXMLItemValue($category, 
                                    'access');
                            $new_category->description = mosMedialibraryImportExport::getXMLItemValue($category, 
                                    'description');
                            $new_category->params = mosMedialibraryImportExport::getXMLItemValue($category, 
                                    'params');
                            $new_category->langDescription = mosMedialibraryImportExport::getXMLItemValue(
                                $category, 'langDescription');
                            $new_category->associate_category = mosMedialibraryImportExport::getXMLItemValue(
                                    $category, 'associate_category');
                            $new_category = mosMedialibraryImportExport::findCategory($new_categories,
                                     $new_category);
                            $ussuesArray = array();
                            $ussuesArray["associate"] = mosMedialibraryImportExport::getXMLItemValue($category, 
                                    'associate_category');
                            $ussuesArray["oldId"] = mosMedialibraryImportExport::getXMLItemValue($category, 'id');
                            $ussuesArray["newId"] = $new_category->id;
                            $associateSaveArr[] = $ussuesArray;
                        }
                            mosMedialibraryImportExport::updateAssociateCategories($associateSaveArr); 
                    }
                } //end if exist categories
                
                $new_peoples = array();
                $have_this_authors = array();
                $peoples_xml = $dom->getElementsByTagName('people');
                $peopleAssociateSaveArr = [];
                    for ($i = 0;$i < $peoples_xml->length;$i++) {
                    $people = $peoples_xml->item($i);
                    $new_people = new mosMedialibrary_people($database);
                    $new_people->date = (mosMediaLibraryImportExport::getXMLItemValue($people, 'date'));
                    $new_people->people_name = (mosMediaLibraryImportExport::getXMLItemValue($people, 
                            'people_name'));
                    $new_people->description = (mosMediaLibraryImportExport::getXMLItemValue($people, 
                            'description'));
                    $new_people->imageURL = (mosMediaLibraryImportExport::getXMLItemValue($people, 'imageURL'));
                    $new_people->hits = (mosMediaLibraryImportExport::getXMLItemValue($people, 'hits'));
                    $new_people->published = (mosMediaLibraryImportExport::getXMLItemValue($people, 'published'));
                    $new_people->approved = (mosMediaLibraryImportExport::getXMLItemValue($people, 'approved'));
                    $new_people->associate_people = (mosMediaLibraryImportExport::getXMLItemValue($people, 
                            'associate_people'));
                    $id_people = mosMedialibraryImportExport::getXMLItemValue($people, 'id');
                    $new_people->auto_gener_description = (mosMediaLibraryImportExport::getXMLItemValue($people, 
                            'auto_gener_description'));
                    $new_people->langshow = (mosMediaLibraryImportExport::getXMLItemValue($people, 'langshow'));
                    $new_people->owneremail = (mosMediaLibraryImportExport::getXMLItemValue($people, 
                            'owneremail'));
                    $new_people->owner_id = (mosMediaLibraryImportExport::getXMLItemValue($people, 'owner_id'));
                    $new_people->type = (mosMediaLibraryImportExport::getXMLItemValue($people, 'type'));

                    $database->setQuery("SELECT id FROM #__medialibrary_people 
                                         WHERE people_name = '$new_people->people_name'");
                    $database->query(); 
                    $have_this_author = $database->loadResult();
                    if (!$have_this_author){
                        if (!$new_people->check()) {
                            $new_people->_error;
                        } else if (!$new_people->store()) {
                            if ($database->getErrorNum()) {
                                $database->stderr();
                            }
                        }
                        $ussuesArray = array();
                        $ussuesArray["associate"] = mosMedialibraryImportExport::getXMLItemValue($people, 
                                'associate_people');
                        $ussuesArray["oldId"] = mosMedialibraryImportExport::getXMLItemValue($people, 'id');
                        $ussuesArray["newId"] = $new_people->id;
                        $have_this_authors[$id_people] = $new_people->id;
                        if ($ussuesArray["associate"] != ''){
                            $peopleAssociateSaveArr[] = $ussuesArray;
                        }

                    } else {
                        $have_this_authors[$id_people] = $have_this_author;
                    }
                    $new_people->old_id = mosMedialibraryImportExport::getXMLItemValue($people, 'id');
                    $new_peoples[] = $new_people;
                    
                }
                if ($peopleAssociateSaveArr != []){
                    mosMedialibraryImportExport::updateAssociatePeople($peopleAssociateSaveArr);
                }
                
                $medias_list = $dom->getElementsByTagname('media');
                $st = $media_id = "";
                $begin = $end = $kol = 0;
                for ($i = 0;$i < $medias_list->length;$i++) {
                    $media_class = new mosMediaLibrary($database);
                    $media = $medias_list->item($i);
                    //$media_id =         $media_class->media_id = 
                        //mosMediaLibraryImportExport::getXMLItemValue($media,'media_id');
                    $media_type = $media_class->media_type = mosMediaLibraryImportExport::getXMLItemValue($media, 
                            'media_type');
                    $informationFrom = $media_class->informationFrom=mosMediaLibraryImportExport::getXMLItemValue(
                        $media, 'informationFrom');
                    $owner_ID = $media_class->owner_ID = mosMediaLibraryImportExport::getXMLItemValue($media, 
                            'owner_ID');
                    $date = $media_class->date = mosMediaLibraryImportExport::getXMLItemValue($media, 'date');
                    $approved = $media_class->approved = mosMediaLibraryImportExport::getXMLItemValue($media, 
                            'approved');
                    $published = $media_class->published = mosMediaLibraryImportExport::getXMLItemValue($media, 
                            'published');
                    $owneremail = $media_class->owneremail = mosMediaLibraryImportExport::getXMLItemValue($media, 
                            'owneremail');
                    $asset_id = $media_class->asset_id = 1;
                    $media_type_class = null;
                    $isbn = null;
                    $asin = null;
                    switch ($media_type) {
                        case 'book':
                            $books = $media->getElementsByTagname('book');
                            $book = $books->item(0);
                            $media_type_class = new mosMedialibrary_book($database);
                            $book_id = $media_type_class->book_id = (mosMediaLibraryImportExport::getXMLItemValue(
                                    $book, 'book_id'));
                            $isbn = $media_type_class->isbn = (mosMediaLibraryImportExport::getXMLItemValue($book,
                                 'isbn'));
                            $title = $media_type_class->title = (mosMediaLibraryImportExport::getXMLItemValue(
                                    $book, 'title'));
                            //$authors = $media_type_class->authors = (
                            //mosMediaLibraryImportExport::getXMLItemValue($book, 'authors'));
                            $manufacturer = $media_type_class->manufacturer = (
                                mosMediaLibraryImportExport::getXMLItemValue($book,'manufacturer'));
                            $release_date = $media_type_class->release_date = (
                                mosMediaLibraryImportExport::getXMLItemValue($book, 'release_date'));
                            $language = $media_type_class->language = (
                                mosMediaLibraryImportExport::getXMLItemValue($book, 'language'));
                            $langDescription = $media_type_class->langDescription = (
                                mosMediaLibraryImportExport::getXMLItemValue($book, 'langDescription'));
                            $rating = $media_type_class->rating = (mosMediaLibraryImportExport::getXMLItemValue(
                                    $book, 'rating'));
                            $url = $media_type_class->url = (mosMediaLibraryImportExport::getXMLItemValue($book,
                                    'url'));
                            $price = $media_type_class->price = (mosMediaLibraryImportExport::getXMLItemValue(
                                    $book, 'price'));
                            $priceunit=$media_type_class->priceunit=mosMediaLibraryImportExport::getXMLItemValue(
                                $book, 'priceunit');
                            $imageURL = $media_type_class->imageURL=(mosMediaLibraryImportExport::getXMLItemValue(
                                $book, 'imageURL'));
                            $edition = $media_type_class->edition = (mosMediaLibraryImportExport::getXMLItemValue(
                                $book, 'edition'));
                            $ebookURL = $media_type_class->ebookURL=(mosMediaLibraryImportExport::getXMLItemValue(
                                $book, 'ebookURL'));
                            $comment = $media_type_class->comment = (mosMediaLibraryImportExport::getXMLItemValue(
                                $book, 'comment'));
                            $numberOfPages = $media_type_class->numberOfPages = (
                                mosMediaLibraryImportExport::getXMLItemValue($book, 'numberOfPages'));
                            $media_class->langDescription = (mosMediaLibraryImportExport::getXMLItemValue($book, 
                                'langDescription'));
                        break;
                        case 'video':
                            $videos = $media->getElementsByTagname('video');
                            $video = $videos->item(0);
                            $media_type_class = new mosMedialibrary_video($database);
                            $video_id = $media_type_class->video_id=(mosMediaLibraryImportExport::getXMLItemValue(
                                $video, 'video_id'));
                            $asin = $media_type_class->asin = (mosMediaLibraryImportExport::getXMLItemValue(
                                    $video, 'asin'));
                            $title = $media_type_class->title = (mosMediaLibraryImportExport::getXMLItemValue(
                                    $video, 'title'));
                            $release_date = $media_type_class->release_date = (
                                    mosMediaLibraryImportExport::getXMLItemValue($video, 'release_date'));
                            $language = $media_type_class->language=(mosMediaLibraryImportExport::getXMLItemValue(
                                $video, 'language'));
                            $langDescription = $media_type_class->langDescription=(
                                mosMediaLibraryImportExport::getXMLItemValue($video, 'langDescription'));
                            $rating = $media_type_class->rating = (mosMediaLibraryImportExport::getXMLItemValue(
                                $video, 'rating'));
                            $price = $media_type_class->price = (mosMediaLibraryImportExport::getXMLItemValue(
                                $video, 'price'));
                            $priceunit = $media_type_class->priceunit=mosMediaLibraryImportExport::getXMLItemValue(
                                $video, 'priceunit');
                            $imageURL = $media_type_class->imageURL=(mosMediaLibraryImportExport::getXMLItemValue(
                                $video, 'imageURL'));
                            $url = $media_type_class->url = (mosMediaLibraryImportExport::getXMLItemValue($video, 
                                'url'));
                            $studio = $media_type_class->studio = (mosMediaLibraryImportExport::getXMLItemValue(
                                $video, 'studio'));
                            $evideoURL =$media_type_class->evideoURL=(mosMediaLibraryImportExport::getXMLItemValue(
                                $video, 'evideoURL'));
                            $comment = $media_type_class->comment = (mosMediaLibraryImportExport::getXMLItemValue(
                                $video, 'comment'));
                            $number_of_discs = $media_type_class->number_of_discs = (
                                mosMediaLibraryImportExport::getXMLItemValue($video, 'number_of_discs'));
                            $run_time = $media_type_class->run_time=(mosMediaLibraryImportExport::getXMLItemValue(
                                $video, 'run_time'));
                            $media_class->langDescription = (mosMediaLibraryImportExport::getXMLItemValue($video, 
                                'langDescription'));
                        break;
                        case 'music':
                            $musics = $media->getElementsByTagname('music');
                            $music = $musics->item(0);
                            $media_type_class = new mosMedialibrary_music($database);
                            $music_id = $media_type_class->music_id=(mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'music_id'));
                            $asin = $media_type_class->asin = (mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'asin'));
                            $title = $media_type_class->title = (mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'title'));
                            $label = $media_type_class->label = (mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'label'));
                            $release_date = $media_type_class->release_date = (
                                mosMediaLibraryImportExport::getXMLItemValue($music, 'releasedate'));
                            $language = $media_type_class->language=(mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'language'));
                            $langDescription = $media_type_class->langDescription = (
                                mosMediaLibraryImportExport::getXMLItemValue($music, 'langDescription'));
                            $number_of_discs = $media_type_class->number_of_discs = (
                                mosMediaLibraryImportExport::getXMLItemValue($music, 'number_of_discs'));
                            $rating = $media_type_class->rating = (mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'rating'));
                            $price = $media_type_class->price = (mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'price'));
                            $priceunit =$media_type_class->priceunit=mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'priceunit');
                            $imageURL = $media_type_class->imageURL=(mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'imageURL'));
                            $url = $media_type_class->URL = (mosMediaLibraryImportExport::getXMLItemValue($music, 
                                'URL'));
                            $tracklist=$media_type_class->tracklist=(mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'tracklist'));
                            $emusicURL=$media_type_class->emusicURL=(mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'emusicURL'));
                            $comment = $media_type_class->comment = (mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'comment'));
                            $binding = $media_type_class->binding = (mosMediaLibraryImportExport::getXMLItemValue(
                                $music, 'binding'));
                            $media_class->langDescription = (mosMediaLibraryImportExport::getXMLItemValue($music, 
                                'langDescription'));
                            //exit;
                            
                        break;
                        case 'game':
                            $games = $media->getElementsByTagname('game');
                            $game = $games->item(0);
                            $media_type_class = new mosMedialibrary_game($database);
                            $game_id = $media_type_class->game_id = (mosMediaLibraryImportExport::getXMLItemValue(
                                $game, 'game_id'));
                            $asin = $media_type_class->asin = (mosMediaLibraryImportExport::getXMLItemValue($game,
                             'asin'));
                            $title = $media_type_class->title = (mosMediaLibraryImportExport::getXMLItemValue(
                                $game, 'title'));
                            $studio = $media_type_class->platform = (mosMediaLibraryImportExport::getXMLItemValue(
                                $game, 'platform'));
                            $binding = $media_type_class->binding = (mosMediaLibraryImportExport::getXMLItemValue(
                                $game, 'binding'));
                            $release_date = $media_type_class->release_date = (
                                mosMediaLibraryImportExport::getXMLItemValue($game,
                             'release_date'));
                            $language = $media_type_class->language=(mosMediaLibraryImportExport::getXMLItemValue(
                                $game, 'language'));
                            $langDescription = $media_type_class->langDescription = (
                                mosMediaLibraryImportExport::getXMLItemValue($game, 'langDescription'));
                            $rating = $media_type_class->rating = (mosMediaLibraryImportExport::getXMLItemValue(
                                $game, 'rating'));
                            $price = $media_type_class->price = (mosMediaLibraryImportExport::getXMLItemValue(
                                $game, 'price'));
                            $priceunit =$media_type_class->priceunit=mosMediaLibraryImportExport::getXMLItemValue(
                                $game, 'priceunit');
                            $imageURL = $media_type_class->imageURL=(mosMediaLibraryImportExport::getXMLItemValue(
                                $game, 'imageURL'));
                            $url = $media_type_class->URL = (mosMediaLibraryImportExport::getXMLItemValue($game,
                                 'url'));
                            $egameURL = $media_type_class->egameURL=(mosMediaLibraryImportExport::getXMLItemValue(
                                $game, 'egameURL'));
                            $comment = $media_type_class->comment = (mosMediaLibraryImportExport::getXMLItemValue(
                                $game, 'comment'));
                            $media_class->langDescription = (mosMediaLibraryImportExport::getXMLItemValue($game, 
                                'langDescription'));
                        break;
                    }
                    $media_class->associate_media = mosMediaLibraryImportExport::getXMLItemValue($media, 
                        'associate_media');
                    
                    //get Category
                    if ($catid != "0" && $catid != "") {
                        $arrcatid = array();
                        $arrcatid[] = array($catid);
                        $media_class->categs = $arrcatid[0];
                        //print_r($media_class->categs);echo '   1111111111';exit;
                        
                    } else {
                        $categ = $media->getElementsByTagName('categ');
                        $arrcatid = array();
                        $j = 0;
                        foreach($categ as $cattemp) {
                            $category_media_old_id = $cattemp->nodeValue;
                            foreach($new_categories as $new_category) {
                                if ($new_category->old_id == $category_media_old_id) {
                                    $arrcatid[] = $new_category->id;
                                    $j++;
                                }
                            }
                        }
                        $media_class->categs = $arrcatid;
                    }
                    //get People
                    $people = $media->getElementsByTagName('people_connect');
                    $arrcatid2 = array();
                    $j = 0;
                    foreach($people as $peopletemp) {
                        $people_media_old_id = $peopletemp->nodeValue;
                        foreach($new_peoples as $new_people) {
                            if ($new_people->old_id == $people_media_old_id) {
                                if (isset($new_people->old_id)){
                                    $arrcatid2[] = $new_people->old_id;
                                } else {
                                    $arrcatid2[] = $new_people->id;
                                }
                                $j++;
                            }
                        }
                    }
                    $media_class->people = $arrcatid2;
                    
                    if(!isset($arrcatid[0])) {
                      continue ;
                    }
                    if (gettype($arrcatid[0]) == gettype([])){
                        $arrcatid_0 = $arrcatid[0][0];
                    } else {
                        $arrcatid_0 = $arrcatid[0];
                    }
                    //for output rezult in table
                    $tmp[0] = $i;
                    $tmp[1] = (($isbn != null) ? ($isbn) : (($asin != null) ? ($asin) : ("")));
                    $tmp[2] = $media_type;
                    $q = "SELECT title FROM #__medialibrary_main_categories where id = '$arrcatid_0'";
                    $database->setQuery($q);
                    $data_row = $database->loadRow();
                    $tmp[3] = $data_row[0];
                    $tmp[4] = $title;
                    if ($langDescription == null || $langDescription == '*' || !isset($langDescription)) {
                        $tmp[5] = "all";
                    } else {
                        $tmp[5] = $langDescription;
                    }

                    if (!$media_type_class->check()) {
                        $tmp[6] = "NO";
                        $retValError[] =  $tmp;
                        continue;
                        $tmp[6] = $media_type_class->_error;
                    } else if (!$media_type_class->store()) {
                        if ($database->getErrorNum()) {
                            $tmp[6].= $database->stderr();
                        }
                    } else {
                        $tmp[6] = "OK";
                    }
                    //if ($n == 19) {print_r($media_class);}
                    
                    

                    if ($tmp[6] == "OK") {
                        $media_class->media_id = $media_type_class->id;
                        if (!$media_class->check()) {
                            $tmp[6] = "NO";
                            $retValError[] =  $tmp;
                            continue;
                            $tmp[6] = $media_class->_error;
                        } else if (!$media_class->store()) {
                            if ($database->getErrorNum()) {
                                $tmp[6] = $database->stderr();
                            }
                        } else {
                            $tmp[6] = "OK";
                            //save categ
                            $media_class->saveCategs(); 
                            //save people
                            $media_class->savePeople($have_this_authors); 
                        }
                        if ($tmp[6] != "OK") {
                            $media_type_class->delete($media_type_class->id);
                        }
                    }
                    // var_dump($media_class) or die();
                    $media_class->checkin();

                    //$media_class->updateOrder( "catid='$media_class->catid'" );

                    $retVal[$i] = $tmp;
                    $ussuesArray = array();
                    $ussuesArray["associate"] = mosMediaLibraryImportExport::getXMLItemValue($media, 
                        'associate_media');
                    $ussuesArray["oldId"] = mosMediaLibraryImportExport::getXMLItemValue($media, 'id');
                    $ussuesArray["newId"] = $media_class->id;
                    

                    $mediaAssociateSaveArr[] = $ussuesArray;
                    
                    
                    //get Reviews
                    if ($tmp[6] == "OK" && mosMediaLibraryImportExport::getXMLItemValue($media, 'reviews') != "") {
                        $review_list = $media->getElementsByTagname('review');
                        for ($j = 0;$j < $review_list->length;$j++) {
                            $review = $review_list->item($j);
                            //get for review - fk_mediaid == #__medialibrary.id
                            $fk_mediaid = $media_class->id;
                            //get for review - fk_userid
                            $review_fk_userid = mosMediaLibraryImportExport::getXMLItemValue($review, 'fk_userid');
                            //check - exist this user or not - if don't exist set he as anonymous
                            $database->setQuery("SELECT id FROM #__users " . "\n WHERE id = " . $review_fk_userid 
                                . ";");
                            $review_fk_userid = $database->loadResult();
                            if (count($review_fk_userid) == 0) $review_fk_userid = 0;
                            //get for review - date
                            $review_date = mosMediaLibraryImportExport::getXMLItemValue($review, 'date');
                            //get for review - rating
                            $review_rating = mosMediaLibraryImportExport::getXMLItemValue($review, 'rating');
                            //get for review - title
                            $review_title = mosMediaLibraryImportExport::getXMLItemValue($review, 'title');
                            //get for review - comment
                            $review_comment = mosMediaLibraryImportExport::getXMLItemValue($review, 'comment');
                            //insert data in table _medialibrary_review
                            $database->setQuery("INSERT INTO #__medialibrary_review" 
                                . " (fk_mediaid, fk_userid, date, rating, title,
                             comment)" . 
                            " VALUES " . " (" . $fk_mediaid . ", " . $review_fk_userid . ", '" . $review_date 
                            . "'," . $review_rating . ",'" . $review_title . "', '" . $review_comment . "');");
                            $database->query();
                            
                        } //end for(...) - REVIEW
                        
                    } 
                }
                
                   
                //************************efiles ***********************
                if (mosMediaLibraryImportExport::getXMLItemValue($media, 'efiles') != "") {
                    $ebook_list = $media->getElementsByTagName('efile');
                    for ($j = 0;$j < $ebook_list->length;$j++) {
                        $efile = $ebook_list->item($j);
                        $fk_mediaid = $media_class->id;
                        $efileLoc = mosMediaLibraryImportExport::getXMLItemValue($efile, 'location');
                        $efileDesc = mosMediaLibraryImportExport::getXMLItemValue($efile, 'description');
                        //insert data in table #__booklibrary_files
                        $database->setQuery("INSERT INTO #__medialibrary_emedia_files" . 
                                            "\n (fk_emedia_id, location, description)" . 
                                            "\n VALUES " . 
                                            "\n (" . $fk_mediaid . ", '" . $efileLoc . "','" . $efileDesc . "');");
                        $database->query();
                    } //end for(...) - EFILES
                } //end if(...) - EFILES
              //********************************end efiles****************************
               
                if (mosMediaLibraryImportExport::getXMLItemValue($media, 'video_source') != "") {
            
                    $video_list = $media->getElementsByTagName('video_source');
                    for ($j = 0;$j < $video_list->length;$j++) {
                        $vfile = $video_list->item($j);
                        $fk_mediaid = $media_class->id;
                        $vfileSrc = mosMediaLibraryImportExport::getXMLItemValue($vfile, 'src');
                        $vfileType = mosMediaLibraryImportExport::getXMLItemValue($vfile, 'type');
                        $vfileMedia = mosMediaLibraryImportExport::getXMLItemValue($vfile, 'media');
                        $youtubeCode = mosMediaLibraryImportExport::getXMLItemValue($vfile, 'youtube');
                        //insert data in table #__booklibrary_video_source
                        $database->setQuery("INSERT INTO #__medialibrary_video_source" . 
                                          "\n (fk_media_id, src, type, media, youtube)" . 
                                          "\n VALUES " . 
                                          "\n (" . $fk_mediaid . ",
                                             '" . $vfileSrc . "', 
                                             '" . $vfileType . "', 
                                             '" . $vfileMedia . "', 
                                             '" . $youtubeCode . "');");
                        $database->query();
                    } //end for(...) - VIDEOS
                } //end if(...) - VIDEOS
                    
                if (mosMediaLibraryImportExport::getXMLItemValue($media, 'audio_source') != "") {
                    $audio_list = $media->getElementsByTagName('audio_source');
                    for ($j = 0;$j < $audio_list->length;$j++) {
                        $afile = $audio_list->item($j);
                        $fk_mediaid = $media_class->id;
                        $afileSrc = mosMediaLibraryImportExport::getXMLItemValue($afile, 'src');
                        $afileType = mosMediaLibraryImportExport::getXMLItemValue($afile, 'type');
                        //insert data in table #__booklibrary_audio_source
                         $database->setQuery("INSERT INTO #__medialibrary_audio_source" . 
                                            "\n (fk_media_id, src, type)" . 
                                            "\n VALUES " . 
                                            "\n (" . $fk_mediaid . ",
                                                '" . $afileSrc . "', 
                                                '" . $afileType . "');");
                        $database->query();
                    } //end for(...) - AUDIOS
                } //end if(...) - AUDIOS
                    
                if (mosMediaLibraryImportExport::getXMLItemValue($media, 'track') != "") {
                    $track_list = $media->getElementsByTagName('track');
                    for ($j = 0;$j < $track_list->length;$j++) {
                        $tfile = $track_list->item($j);
                        $fk_mediaid = $media_class->id;
                        $tfileSrc = mosMediaLibraryImportExport::getXMLItemValue($tfile, 'src');
                        $tfilekind = mosMediaLibraryImportExport::getXMLItemValue($tfile, 'kind');
                        $tfileSrclang = mosMediaLibraryImportExport::getXMLItemValue($tfile, 'scrlang');
                        $tfileLabel = mosMediaLibraryImportExport::getXMLItemValue($tfile, 'label');
                        //insert data in table #__booklibrary_audio_source

                        $database->setQuery("INSERT INTO #__medialibrary_track_source" . 
                                            "\n (fk_media_id, src, kind, scrlang, label)" . 
                                            "\n VALUES " . 
                                            "\n (" . $fk_mediaid . ",
                                             '" . $tfileSrc . "', 
                                             '" . $tfilekind . "', 
                                             '" . $tfileSrclang . "', 
                                             '" . $tfileLabel . "');");
                        $database->query();
                    } //end for(...) - TRACKS
                } //end if(...) - TRACKS
           
                $media_class->checkin();
                //$media_class->updateOrder( "catid='$media->catid'" );
                unset($tmp);
            } // end if version >2.0
            
        } // endif version in XML exist
        else { // ----- OLD VERSION------
            exit;
            $cat_list = $dom->getElementsByTagName('category');
            if ($cat_list->item(0) != NULL) { 
                mosMedialibraryImportExport::remove_info(); //С‡РёСЃС‚РёРј Р±Р°Р·Сѓ РґР°РЅРЅС‹С…
                
            }
            if ($catid === null) {
                $cat_list = $dom->getElementsByTagname('category');
                for ($i = 0;$i < $cat_list->length;$i++) {
                    $category = $cat_list->item($i);
                    $new_category = null;
                    $new_category->old_id = mosMediaLibraryImportExport::getXMLItemValue($category, 'category_id');
                    $new_category->old_parent_id = mosMediaLibraryImportExport::getXMLItemValue($category, 
                        'category_parent_id');
                    $new_category->name = mosMediaLibraryImportExport::getXMLItemValue($category, 'category_name');
                    $new_category->title=mosMediaLibraryImportExport::getXMLItemValue($category,'category_title');
                    $new_category->published = mosMediaLibraryImportExport::getXMLItemValue($category, 
                        'category_published');
                    $new_category->ordering = mosMediaLibraryImportExport::getXMLItemValue($category, 'ordering');
                    $new_category->access = mosMediaLibraryImportExport::getXMLItemValue($category, 'access');
                    $new_category->description = mosMediaLibraryImportExport::getXMLItemValue($category, 
                        'description');
                    $new_category = mosMediaLibraryImportExport::findCategory($new_categories, $new_category);
                }
            }
            $st = $mediaid = "";
            $begin = $end = $kol = 0;
            $media_list = $dom->getElementsByTagName('media');
            for ($i = 0;$i < $media_list->length;$i++) {
                $media_class = new mosMediaLibrary($database);
                $media = $media_list->item($i);
                //$media_id = $media_class->media_id = 
                //mosMediaLibraryImportExport::getXMLItemValue($media,'media_id');
                $media_type = $media_class->media_type = mosMediaLibraryImportExport::getXMLItemValue($media, 
                    'media_type');
                $informationFrom = $media_class->informationFrom = mosMediaLibraryImportExport::getXMLItemValue(
                    $media, 'informationFrom');
                $date = $media_class->date = mosMediaLibraryImportExport::getXMLItemValue($media, 'date');
                $approved = $media_class->approved = mosMediaLibraryImportExport::getXMLItemValue($media, 
                    'approved');
                $published = $media_class->published = mosMediaLibraryImportExport::getXMLItemValue($media, 
                    'published');
                $media_type_class = null;
                $isbn = null;
                $asin = null;
                switch ($media_type) {
                    case 'book':
                        $books = $media->getElementsByTagname('book');
                        $book = $books->item(0);
                        $media_type_class = new mosMedialibrary_book($database);
                        $book_id = $media_type_class->book_id = (mosMediaLibraryImportExport::getXMLItemValue(
                            $book, 'book_id'));
                        $isbn = $media_type_class->isbn = (mosMediaLibraryImportExport::getXMLItemValue($book, 
                            'isbn'));
                        $title = $media_type_class->title = (mosMediaLibraryImportExport::getXMLItemValue($book, 
                            'title'));
                        //$authors = $media_type_class->authors = (
                        //mosMediaLibraryImportExport::getXMLItemValue($book, 'authors'));
                        $manufacturer = $media_type_class->manufacturer = (
                            mosMediaLibraryImportExport::getXMLItemValue($book, 'manufacturer'));
                        $release_date = $media_type_class->release_date = (
                            mosMediaLibraryImportExport::getXMLItemValue($book, 'release_date'));
                        $language = $media_type_class->language = (mosMediaLibraryImportExport::getXMLItemValue(
                            $book, 'language'));
                        $langDescription = $media_type_class->langDescription = (
                            mosMediaLibraryImportExport::getXMLItemValue($book,'langDescription'));
                        $rating = $media_type_class->rating = (mosMediaLibraryImportExport::getXMLItemValue(
                            $book, 'rating'));
                        $url = $media_type_class->url = (mosMediaLibraryImportExport::getXMLItemValue($book, 
                            'url'));
                        $price = $media_type_class->price = (mosMediaLibraryImportExport::getXMLItemValue($book, 
                            'price'));
                        $priceunit = $media_type_class->priceunit = mosMedialibraryImportExport::getXMLItemValue(
                            $book, 'priceunit');
                        $imageURL = $media_type_class->imageURL = (mosMediaLibraryImportExport::getXMLItemValue(
                            $book, 'imageURL'));
                        $edition = $media_type_class->edition = (mosMediaLibraryImportExport::getXMLItemValue(
                            $book, 'edition'));
                        $ebookURL = $media_type_class->ebookURL = (mosMediaLibraryImportExport::getXMLItemValue(
                            $book, 'ebookURL'));
                        $comment = $media_type_class->comment = (mosMediaLibraryImportExport::getXMLItemValue(
                            $book, 'comment'));
                    break;
                    case 'video':
                        $videos = $media->getElementsByTagname('video');
                        $video = $videos->item(0);
                        $media_type_class = new mosMedialibrary_video($database);
                        $video_id = $media_type_class->video_id = (mosMediaLibraryImportExport::getXMLItemValue(
                            $video, 'video_id'));
                        $asin = $media_type_class->asin = (mosMediaLibraryImportExport::getXMLItemValue($video, 
                            'asin'));
                        $title = $media_type_class->title = (mosMediaLibraryImportExport::getXMLItemValue($video, 
                            'title'));
                        $actors = $media_type_class->actors = (mosMediaLibraryImportExport::getXMLItemValue(
                            $video, 'actors'));
                        $producers = $media_type_class->producers = (mosMediaLibraryImportExport::getXMLItemValue(
                            $video, 'producers'));
                        $release_date = $media_type_class->release_date = (
                            mosMediaLibraryImportExport::getXMLItemValue($video, 'release_date'));
                        $language = $media_type_class->language = (mosMediaLibraryImportExport::getXMLItemValue(
                            $video, 'language'));
                        $langDescription = $media_type_class->langDescription = (
                            mosMediaLibraryImportExport::getXMLItemValue($video,'langDescription'));
                        $directors = $media_type_class->directors = (mosMediaLibraryImportExport::getXMLItemValue(
                            $video, 'directors'));
                        $rating = $media_type_class->rating = (mosMediaLibraryImportExport::getXMLItemValue(
                            $video, 'rating'));
                        $price = $media_type_class->price = (mosMediaLibraryImportExport::getXMLItemValue($video, 
                            'price'));
                        $priceunit = $media_type_class->priceunit = mosMedialibraryImportExport::getXMLItemValue(
                            $video, 'priceunit');
                        $imageURL = $media_type_class->imageURL = (mosMediaLibraryImportExport::getXMLItemValue(
                            $video, 'imageURL'));
                        $url = $media_type_class->url = (mosMediaLibraryImportExport::getXMLItemValue($video, 
                            'url'));
                        $studio = $media_type_class->studio = (mosMediaLibraryImportExport::getXMLItemValue(
                            $video, 'studio'));
                        $evideoURL = $media_type_class->evideoURL = (mosMediaLibraryImportExport::getXMLItemValue(
                            $video, 'evideoURL'));
                        $comment = $media_type_class->comment = (mosMediaLibraryImportExport::getXMLItemValue(
                            $video, 'comment'));
                        $number_of_discs = $media_type_class->number_of_discs = (
                            mosMediaLibraryImportExport::getXMLItemValue($video, 
                            'number_of_discs'));
                        $run_time = $media_type_class->run_time = (mosMediaLibraryImportExport::getXMLItemValue(
                            $video, 'run_time'));
                    break;
                    case 'music':
                        $musics = $media->getElementsByTagname('music');
                        $music = $musics->item(0);
                        $media_type_class = new mosMedialibrary_music($database);
                        $music_id = $media_type_class->music_id = (mosMediaLibraryImportExport::getXMLItemValue(
                            $music, 'music_id'));
                        $asin = $media_type_class->asin = (mosMediaLibraryImportExport::getXMLItemValue($music, 
                            'asin'));
                        $title = $media_type_class->title = (mosMediaLibraryImportExport::getXMLItemValue($music, 
                            'title'));
                        $artist = $media_type_class->artist = (mosMediaLibraryImportExport::getXMLItemValue(
                            $music, 'artist'));
                        $label = $media_type_class->label = (mosMediaLibraryImportExport::getXMLItemValue($music, 
                            'label'));
                        $release_date = $media_type_class->release_date = (
                            mosMediaLibraryImportExport::getXMLItemValue($music,'release_date'));
                        $language = $media_type_class->language = (mosMediaLibraryImportExport::getXMLItemValue(
                            $music, 'language'));
                        $langDescription = $media_type_class->langDescription = (
                            mosMediaLibraryImportExport::getXMLItemValue($music, 'langDescription'));
                        $number_of_discs = $media_type_class->number_of_discs = (
                            mosMediaLibraryImportExport::getXMLItemValue($music, 'number_of_discs'));
                        $rating = $media_type_class->rating = (mosMediaLibraryImportExport::getXMLItemValue(
                            $music, 'rating'));
                        $price = $media_type_class->price = (mosMediaLibraryImportExport::getXMLItemValue($music, 
                            'price'));
                        $priceunit = $media_type_class->priceunit = mosMedialibraryImportExport::getXMLItemValue(
                            $music, 'priceunit');
                        $imageURL = $media_type_class->imageURL = (mosMediaLibraryImportExport::getXMLItemValue(
                            $music, 'imageURL'));
                        $url = $media_type_class->url = (mosMediaLibraryImportExport::getXMLItemValue($music, 
                            'url'));
                        $tracklist = $media_type_class->tracklist = (mosMediaLibraryImportExport::getXMLItemValue(
                            $music, 'tracklist'));
                        $emusicURL = $media_type_class->emusicURL = (mosMediaLibraryImportExport::getXMLItemValue(
                            $music, 'emusicURL'));
                        $comment = $media_type_class->comment = (mosMediaLibraryImportExport::getXMLItemValue(
                            $music, 'comment'));
                        $binding = $media_type_class->binding = (mosMediaLibraryImportExport::getXMLItemValue(
                            $music, 'binding'));
                    break;
                    case 'game':
                        $games = $media->getElementsByTagname('game');
                        $game = $games->item(0);
                        $media_type_class = new mosMedialibrary_game($database);
                        $game_id = $media_type_class->game_id = (mosMediaLibraryImportExport::getXMLItemValue(
                            $game, 'game_id'));
                        $asin = $media_type_class->asin = (mosMediaLibraryImportExport::getXMLItemValue($game, 
                            'asin'));
                        $title = $media_type_class->title = (mosMediaLibraryImportExport::getXMLItemValue($game, 
                            'title'));
                        $studio = $media_type_class->studio = (mosMediaLibraryImportExport::getXMLItemValue($game,
                         'studio'));
                        $binding = $media_type_class->binding = (mosMediaLibraryImportExport::getXMLItemValue($game
                            , 'binding'));
                        $release_date = $media_type_class->release_date = (
                            mosMediaLibraryImportExport::getXMLItemValue($game, 'release_date'));
                        $language = $media_type_class->language = (mosMediaLibraryImportExport::getXMLItemValue(
                            $game, 'language'));
                        $langDescription = $media_type_class->langDescription = (
                            mosMediaLibraryImportExport::getXMLItemValue($game, 'langDescription'));
                        $rating = $media_type_class->rating = (mosMediaLibraryImportExport::getXMLItemValue(
                            $game, 'rating'));
                        $price = $media_type_class->price = (mosMediaLibraryImportExport::getXMLItemValue($game, 
                            'price'));
                        $priceunit = $media_type_class->priceunit = mosMedialibraryImportExport::getXMLItemValue(
                            $game, 'priceunit');
                        $imageURL = $media_type_class->imageURL = (mosMediaLibraryImportExport::getXMLItemValue(
                            $game, 'imageURL'));
                        $url = $media_type_class->url = (mosMediaLibraryImportExport::getXMLItemValue($game, 
                            'url'));
                        $egameURL = $media_type_class->egameURL = (mosMediaLibraryImportExport::getXMLItemValue(
                            $game, 'egameURL'));
                        $comment = $media_type_class->comment = (mosMediaLibraryImportExport::getXMLItemValue(
                            $game, 'comment'));
                    break;
                }
                //get Category
                if ($catid != "0" && $catid != "") {
                    $media_class->categs = array($catid);
                    //print_r($media_class->categs);echo '   1111111111';exit;
                    
                } else { /*
                    
                    $categ = $media->getElementsByTagName('categ');
                    $arrcatid;
                    foreach ($categ as $cattemp) {                        
                    $category_media_old_id = $cattemp->nodeValue;           
                    //echo ":111111111111:" . $cattemp->nodeValue ;
                    foreach ($new_categories as $new_category){    
                    if($new_category->old_id == $category_media_old_id){
                    $arrcatid[] = $new_category->id;
                    }
                    }
                    }
                    $media_class->categs = $arrcatid;
                    //print_r($arrcatid);exit;
                    */
                }
                //for output rezult in table
                $tmp[0] = $i;
                $tmp[1] = (($isbn != null) ? ($isbn) : ((($asin != null) ? ($asin) : (""))));
                $tmp[2] = $media_type;
                $tmp[3] = $new_category->name;
                $tmp[4] = $title;
                if (!$media_type_class->check()) {
                    $tmp[6] = $media_type_class->_error;
                } else if (!$media_type_class->store()) {
                    if ($database->getErrorNum()) {
                        $tmp[6].= $database->stderr();
                    }
                } else {
                    $tmp[6] = "OK";
                }
                if ($tmp[6] == "OK") {
                    $media_class->media_id = $media_type_class->id;
                    if (!$media_class->check()) {
                        $tmp[6] = $media_class->_error;
                    } else if (!$media_class->store()) {
                        if ($database->getErrorNum()) {
                            $tmp[6] = $database->stderr();
                        }
                    } else {
                        $tmp[6] = "OK";
                        //save categ
                        $media_class->saveCategs($have_this_authors);
                    }
                    if ($tmp[6] != "OK") {
                        $media_type_class->delete($media_type_class->id);
                    }
                }
                $media_class->checkin();
                //$media_class->updateOrder( "catid='$media_class->catid'" );
                $retVal[$i] = $tmp;
                
                //get Reviews
                if ($tmp[6] == "OK" && mosMediaLibraryImportExport::getXMLItemValue($media, 'reviews') != "") {
                    $review_list = $media->getElementsByTagname('review');
                    for ($j = 0;$j < $review_list->length;$j++) {
                        $review = $review_list->item($j);
                        //get for review - fk_mediaid == #__medialibrary.id
                        $fk_mediaid = $media_class->id;
                        //get for review - fk_userid
                        $review_fk_userid = mosMediaLibraryImportExport::getXMLItemValue($review, 'fk_userid');
                        //check - exist this user or not - if don't exist set he as anonymous
                        $database->setQuery("SELECT id FROM #__users " . "\n WHERE id = " . $review_fk_userid 
                            . ";");
                        $review_fk_userid = $database->loadResult();
                        if (count($review_fk_userid) == 0) $review_fk_userid = 0;
                        //get for review - date
                        $review_date = mosMediaLibraryImportExport::getXMLItemValue($review, 'date');
                        //get for review - rating
                        $review_rating = mosMediaLibraryImportExport::getXMLItemValue($review, 'rating');
                        //get for review - title
                        $review_title = mosMediaLibraryImportExport::getXMLItemValue($review, 'title');
                        //get for review - comment
                        $review_comment = mosMediaLibraryImportExport::getXMLItemValue($review, 'comment');
                        //insert data in table _medialibrary_review
                        $database->setQuery("INSERT INTO #__medialibrary_review" 
                            . " (fk_mediaid, fk_userid, date, rating, title, comment)"
                            . " VALUES " . " (" . $fk_mediaid . ", " . $review_fk_userid . ", '" . $review_date 
                            . "'," . $review_rating . ",'"
                            . $review_title . "', '" . $review_comment . "');");
                        $database->query();
                    } //end for(...) - REVIEW
                }
            } //end for(...) - media
        }
        mosMediaLibraryImportExport::updateAssociateMedias($mediaAssociateSaveArr); 
        //exit;
        if ($retValError != []) {
            $retVal = $retValError + $retVal ;        
        } 
        return $retVal;
    }
    //*******************************************************************************
    //***********************   end add for import XML format   *********************
    //*******************************************************************************
   static function exportMediasXML($medias, $cats = '') {
        global $mosConfig_live_site, $mosConfig_absolute_path, $medialibrary_configuration, $database;
        $strXmlDoc = "";
        $strXmlDoc.= "<?xml version='1.0' encoding='utf-8' ?>\n";
        $strXmlDoc.= "<data>\n";
        $strXmlDoc.= "<version>" . $medialibrary_configuration['release']['version'] . "</version>\n";
        $strXmlDoc.= "<medias>\n";
        foreach($medias as $media) {
            $strXmlDoc.= $media->toXML2();
        }
        
        $strXmlDoc.= "</medias>\n";
        if ($cats != '') {
            $strXmlDoc.= "<categories>\n";
            foreach($cats as $cat) {
                $strXmlDoc.= "<category>\n";
                foreach($cat as $field => $value) {
                    $strXmlDoc.= '<' . $field . '><![CDATA[' . $value . ']]></' . $field . ">\n";
                }
                $strXmlDoc.= "</category>\n";
            }
            $strXmlDoc.= "</categories>\n";
        }
        $strXmlDoc.= "</data>\n";
        return $strXmlDoc;
    }
    
    function exportMediasXML11($medias) {
        global $mosConfig_live_site, $mosConfig_absolute_path, $medialibrary_configuration, $database;
        //$xmlDoc = new DOMIT_Document();
        $strXmlDoc = "";
        $strXmlDoc.= "<?xml version='1.0' encoding='UTF-8' ?>\n";
        $strXmlDoc.= "<media_data>\n";
        $strXmlDoc.= "<version>" . $medialibrary_configuration['release']['version'] . "</version>\n";
        //create and append list element
        //$categories_dom =   $xmlDoc->createElement("categories");
        $strXmlDoc.= "<categories>\n";
        //add category
        $database->setQuery("SELECT * FROM #__categories " 
                          . "WHERE section='com_medialibrary' order by parent_id, ordering; ");
        $categories = $database->loadObjectList();
        if ($cats != '') {
            foreach($categories as $category) {
                //add category
                $strXmlDoc.= "<category>\n";
                $strXmlDoc.= "<category_id>" . $category->id . "</category_id>\n";
                $strXmlDoc.= "<category_parent_id>" . $category->parent_id . "</category_parent_id>\n";
                $strXmlDoc.= "<category_name><![CDATA[" . $category->name . "]]></category_name>\n";
                $strXmlDoc.= "<category_title><![CDATA[" . $category->title . "]]></category_title>\n";
                $strXmlDoc.= "<category_section>" . $category->section . "</category_section>\n";
                $strXmlDoc.= "<category_published>" . $category->published . "</category_published>\n";
                $strXmlDoc.= "<ordering>" . $category->ordering . "</ordering>\n";
                $strXmlDoc.= "<access>" . $category->access . "</access>\n";
                $strXmlDoc.= "<description><![CDATA[" . $category->description . "]]></description>\n";
                $strXmlDoc.= "</category>\n";
            }
        }
        //create and append list element
        //$istaller_data_dom->appendChild($categories_dom);
        $strXmlDoc.= "</categories>\n";
        //create and append list element
        $strXmlDoc.= "<medias>\n";
        foreach($medias as $media) {
            $strXmlDoc.= $media->toXML2();
        }
        $strXmlDoc.= "</medias>\n";
        $strXmlDoc.= "</media_data>";
        return $strXmlDoc;
    }
    
   static function storeExportFile($data, $type) {
        global $mosConfig_live_site, $mosConfig_absolute_path, $medialibrary_configuration;

        if (version_compare(JVERSION, "1.6.0", "lt")) {
            $jdate = new JDate("Ymd_His");
            $date = $jdate->toMySQL();
        } else {
            $date = date("Ymd_His");
        }
        $fileName = "medialibrary_" . $date;
        $fileBase = "/administrator/components/com_medialibrary/exports/";
        //echo 'PRINT : '.$mosConfig_absolute_path;exit;
        //write the xml file
        $fp = fopen($mosConfig_absolute_path . $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_medialibrary/exports/";
        $InformationArray['urlBase'] = $mosConfig_live_site . $fileBase;
        $InformationArray['out_file'] = $InformationArray['xml_file'];
        $InformationArray['error'] = null;
        switch ($type) {
            case 'csv':
                $InformationArray['xslt_file'] = 'csv.xsl';
                $InformationArray['out_file'] = $fileName . '.csv';
                mosMediaLibraryImportExport::transformPHP4($InformationArray);
            break;
            default:
            break;
        }
        return $InformationArray;
    }
    function transformPHP4(&$InformationArray) {
        // create the XSLT processor^M
        $xh = xslt_create() or die("Could not create XSLT processor");
        // Process the document
        $result = xslt_process($xh, $InformationArray['fileBase'] 
            . $InformationArray['xml_file'], $InformationArray['fileBase'] .
         $InformationArray['xslt_file'], $InformationArray['fileBase'] . $InformationArray['out_file']);
        if (!$result) {
            // Something croaked. Show the error
            $InformationArray['error'] = "Cannot process XSLT document: " . xslt_errno($xh) . " " 
                . xslt_error($xh);
        }
        // Destroy the XSLT processor
        xslt_free($xh);
    }
    
    static function remove_info() {
        global $database;
        $database->setQuery('truncate #__medialibrary');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery('truncate #__medialibrary_game');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery('truncate #__medialibrary_people');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery('truncate #__medialibrary_people_connect');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery('truncate #__medialibrary_music');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery('truncate #__medialibrary_video');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery('truncate #__medialibrary_book');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery("delete from #__medialibrary_main_categories where section='com_medialibrary'");
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery('truncate #__medialibrary_review');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery('truncate #__medialibrary_categories');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery('truncate #__medialibrary_audio_source');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery('truncate #__medialibrary_emedia_files');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery('truncate #__medialibrary_track_source');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        $database->setQuery('truncate #__medialibrary_video_source');
        $database->query();
        if ($database->getErrorNum()) {
            echo $database->stderr();
            return $database->stderr();
        }
        return "";
    }
}