<?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.lend.php");
require_once ($mosConfig_absolute_path."/components/com_medialibrary/medialibrary.class.review.php");
if(version_compare(JVERSION, '3.0', 'lt')) {
  require_once ( JPATH_SITE .DS.'libraries'.DS.'joomla'.DS.'database'.DS.'table.php' ); 
}

/**
* Media database table class
*/
//class mosMedialibrary extends mosDBTable {
class mosMedialibrary extends JTable {//for 1.6
    /** @var int Primary key */
    var $id=null;
    /** @var int */    
    //var $catid=null;
    /** @var int */
    var $approved =null;
    /** @var string */    
    var $date=null;
    /** @var int */
    var $hits=null;
    /** @var int */
    var $ordering=null;
    /** @var int */
    var $published=null;
    /** @var boolean */
    var $checked_out=null;
    /** @var time */
    var $checked_out_time=null;
    /** @var int */
    var $archived=null;
    /** @var int */
    var $asset_id=null;
    /** @var varchar(200) */    
    var $informationFrom=null;
    /** @var varchar(3) */    
    var $fk_lendid=null;
      /** @var varchar(10) */  
    var $media_type = null;
      /** @var int(11) */  
    var $media_id = null;
    /** @var varchar(50) */    
    var $owneremail = null;
    /** @var varchar(100) */
    var $featured_clicks=null; 
    /** @var varchar(100) */
    var $featured_shows=null;
 
    var $owner_ID=0; 
    
    var $associate_media=null; 
    

    /**
    * @param database - A database connector object
    */
    function __construct( &$db ) {
    //    $this->mosDBTable( '#__medialibrary', 'id', $db );
    parent::__construct('#__medialibrary', 'id', $db);//for 1.6
    }
    
 //set book->categs array
  function setCategs(){
    $this->_db->setQuery("SELECT catid FROM #__medialibrary_categories \n".
                            "WHERE mediaid='$this->id'");
        if(version_compare(JVERSION, '3.0', 'lt')) {
      $this->categs = $this->_db->loadResultArray();
    } else {
      $this->categs = $this->_db->loadColumn();
    }
  }

//set book->peoples array
  function setPeoples(){
    $this->_db->setQuery("SELECT fk_people_id FROM #__medialibrary_people_connect \n".
              "WHERE fk_media_id='$this->id'");
    if(version_compare(JVERSION, '3.0', 'lt')) {
      $this->peoples = $this->_db->loadResultArray();
    } else {
      $this->peoples = $this->_db->loadColumn();
    }
  }



  //check access to book
    function getAccessMedia(){

      if(!isset($this->categs)) $this->setCategs();
      $categoriesid=implode(',',$this->categs);
      if(!$categoriesid){return;}
      $this->_db->setQuery("SELECT params FROM #__medialibrary_main_categories 
                            WHERE id IN ($categoriesid)");
      if(version_compare(JVERSION, '3.0', 'lt')) {
      $accesses=$this->_db->loadResultArray();
      } else {
        $accesses=$this->_db->loadColumn();
      }
      foreach($accesses as $key=>$access){
          if($access=='') $accesses[$key]='-2';
      }
      return implode(',',$accesses);
  }
  //save array media->categs do #__medialibrary_categories
  function saveCategs(){
    $values = array();
    $categories=$this->categs;
    foreach($categories as $category){
      $values[]='('.$this->id.','.$category.')';
    }
    $queryvalue = implode(', ',$values);
    if($values){
      $this->_db->setQuery("DELETE FROM #__medialibrary_categories \n".
                           "WHERE mediaid=".$this->id);
      $this->_db->query();
      $this->_db->setQuery("INSERT INTO #__medialibrary_categories (mediaid,catid) VALUES $queryvalue");
      $this->_db->query();
    }
    echo $this->_db->getErrorMsg();
  }

function savePeople($have_this_authors){
    $values = array();
    $peoples = $this->people;
    foreach($peoples as $people){
        $values[]='('.$this->id.','.$have_this_authors[$people].')';

    }
    $queryvalue = implode(', ',$values);
    if($values){
        $this->_db->setQuery("DELETE FROM #__medialibrary_people_connect \n".
                             "WHERE fk_media_id=".$this->id);
        $this->_db->query();
        $this->_db->setQuery("INSERT INTO #__medialibrary_people_connect (fk_media_id ,fk_people_id ) 
                              VALUES $queryvalue");
        $this->_db->query();
    }
      echo $this->_db->getErrorMsg();
}

    /**
    * @param string - Target search string
    * not used at the moment
    */
//    function search( $text, $state='', $sectionPrefix='' ) {
//        $text = trim( $text );
//        /** if ($text == '') { **/
//            return array();
//        /**}
        
//        $this->_db->setQuery( "SELECT date AS created, title,"
//        . "\n    author,  '1' AS browsernav, '{$sectionPrefix}Books' AS section"
//        . "\nFROM #__medialibrary WHERE (title LIKE '%$text%' OR author LIKE '%$text%'"
//        . "\n)"
//        . "\n ORDER BY created DESC"
//        );
        
//        return $this->_db->loadObjectList(); **/
//    }
    
    function getReviews(){
        $this->_db->setQuery("SELECT * FROM #__medialibrary_review 
                              WHERE published=1 AND fk_mediaid='$this->id' 
                              ORDER BY id");
                            if(version_compare(JVERSION, '3.0', 'lt')) {
        $tmp = $this->_db->loadResultArray();        
              } else {
                $tmp = $this->_db->loadColumn();
              }
        $retVal = array();        
        for($i = 0, $j = count($tmp); $i < $j; $i++ ){
            $help = new mosMediaLibrary_review($this->_db);
            $help->load(intval($tmp[$i]));
            $retVal[$i] = $help;
        }    
    
    //$retVal = $this->_db->setQuery("SELECT * FROM #__medialibrary_review WHERE published=1 
    //AND fk_mediaid='$this->id' ORDER BY id")->loadObjectList();
        return $retVal;    
    }
    
    function getLend(){
        $lend = null;
        if($this->fk_lendid != null && $this->fk_lendid != 0){
            $lend = new mosMediaLibrary_lend($this->_db);
            // load the row from the db table
            $lend->load(intval($this->fk_lendid));
        }
        return $lend;
    }
    
    function getAllLends($exclusion=""){
        $this->_db->setQuery("SELECT id FROM #__medialibrary_lend \n".
                            "WHERE fk_mediaid='$this->id' " . $exclusion . " AND lend_return IS NULL ORDER BY id");
        if(version_compare(JVERSION, '3.0', 'lt')) {
        $tmp = $this->_db->loadResultArray();    
        } else {
            $tmp = $this->_db->loadColumn();
        }
          
        $retVal = array();        
        for($i = 0, $j = count($tmp); $i < $j; $i++ ){
            $help = new mosMediaLibrary_lend($this->_db);
            $help->load(intval($tmp[$i]));
            $retVal[$i] = $help;
        }        
        return $retVal;    
    }

    function getAllLendRequests($exclusion=""){
        $this->_db->setQuery("SELECT id FROM #__medialibrary_lend_request \n".
                            "WHERE fk_mediaid='$this->id'" . $exclusion . " ORDER BY id");
                            if(version_compare(JVERSION, '3.0', 'lt')) {
        $tmp = $this->_db->loadResultArray();    
              } else {
                $tmp = $this->_db->loadColumn();
              }
        $retVal = array();        
        for($i = 0, $j = count($tmp); $i < $j; $i++ ){
            $help = new mosMediaLibrary_lend_request($this->_db);
            $help->load(intval($tmp[$i]));
            $retVal[$i] = $help;
        }        
        return $retVal;    
    }


    function toXML3($xmlDoc){
        
        //create and append name element 
        $retVal = $xmlDoc->createElement("media"); 
        
        $media_id = $xmlDoc->createElement("media_id");
        $media_id->appendChild($xmlDoc->createTextNode($this->media_id));
        $retVal->appendChild( $media_id);
        
        $media_type = $xmlDoc->createElement("media_type");
        $media_type->appendChild($xmlDoc->createTextNode($this->media_type) );
        $retVal->appendChild( $media_type);
        
        $informationFrom = $xmlDoc->createElement("informationFrom");
        $informationFrom->appendChild($xmlDoc->createTextNode($this->informationFrom));
        $retVal->appendChild( $informationFrom);

    $date = $xmlDoc->createElement("date");
    $date->appendChild($xmlDoc->createTextNode($this->date));
    $retVal->appendChild( $date);

    $approved  = $xmlDoc->createElement("approved ");
    $approved ->appendChild($xmlDoc->createTextNode($this->approved ));
    $retVal->appendChild( $approved  );

    $published = $xmlDoc->createElement("published");
    $published->appendChild($xmlDoc->createTextNode($this->published));
    $retVal->appendChild( $published );

    $owneremail = $xmlDoc->createElement("owneremail");
    $owneremail->appendChild($xmlDoc->createCDATASection($this->owneremail));
    $retVal->appendChild( $owneremail );

    $owner_ID = $xmlDoc->createElement("owner_ID");
    $owner_ID->appendChild($xmlDoc->createTextNode($this->owner_ID));
    $retVal->appendChild($owner_ID);
    
    //add category
    $this->_db->setQuery("SELECT * FROM #__medialibrary_main_categories ".
              "WHERE id=".$this->catid . " ; " );
    $tmp = $this->_db->loadObjectList();   

    //print_r($tmp);

    $category = $xmlDoc->createElement("category_entity");

    $category_id = $xmlDoc->createElement("category_id");
    $category_id->appendChild($xmlDoc->createTextNode($tmp[0]->id));
    $category->appendChild( $category_id );

    $category_parent_id = $xmlDoc->createElement("category_parent_id");
    $category_parent_id->appendChild($xmlDoc->createTextNode($tmp[0]->parent_id));
    $category->appendChild( $category_parent_id );

    $category_name = $xmlDoc->createElement("category_name");
    $category_name->appendChild($xmlDoc->createTextNode($tmp[0]->name));
    $category->appendChild( $category_name );

    $category_title = $xmlDoc->createElement("category_title");
    $category_title->appendChild($xmlDoc->createTextNode($tmp[0]->title));
    $category->appendChild( $category_title );

    $category_section = $xmlDoc->createElement("category_section");
    $category_section->appendChild($xmlDoc->createTextNode($tmp[0]->section));
    $category->appendChild( $category_section );

    $category_published = $xmlDoc->createElement("category_published");
    $category_published->appendChild($xmlDoc->createTextNode($tmp[0]->published));
    $category->appendChild( $category_published );

    $category_ordering =  $xmlDoc->createElement("ordering");
    $category_ordering->appendChild($xmlDoc->createTextNode($category->ordering));
    $category_dom->appendChild( $category_ordering );

    $category_access =  $xmlDoc->createElement("access");
    $category_access->appendChild($xmlDoc->createTextNode($category->access));
    $category_dom->appendChild( $category_access );

    $category_description =  $xmlDoc->createElement("description");
    $category_description->appendChild($xmlDoc->createCDATASection($category->description));
    $category_dom->appendChild( $category_description );

    $retVal->appendChild( $category);
        
    //add media type
    switch ($this->media_type)
    {
      case 'book':
        $media_class = new mosMedialibrary_book($this->_db);
        $media_class->load($this->media_id);
        $media_class_xml = $media_class->toXML($xmlDoc);
        $retVal->appendChild( $media_class_xml);
        break;
      case 'video':
        $media_class = new mosMedialibrary_video($this->_db);
        $media_class->load($this->media_id);
        $media_class_xml = $media_class->toXML($xmlDoc);
        $retVal->appendChild( $media_class_xml);
        break;
      case 'music':
        $media_class = new mosMedialibrary_music($this->_db);
        $media_class->load($this->media_id);
        $media_class_xml = $media_class->toXML($xmlDoc);
        $retVal->appendChild( $media_class_xml);
        break;
      case 'game':
        $media_class = new mosMedialibrary_game($this->_db);
        $media_class->load($this->media_id);
        $media_class_xml = $media_class->toXML($xmlDoc);
        $retVal->appendChild( $media_class_xml);
        break;
    }


/*            $lends_data = $this->getLend();
            $exclusion = "";
            
            $lends = $xmlDoc->createElement("lends");
            $lends_data = $this->getAllLends($exclusion);;
            
            foreach($lends_data as $lend_data){
                $lends->appendChild($lend_data->toXML( $xmlDoc));
            }
            $retVal->appendChild( $lends);
        
            $lendrequests = $xmlDoc->createElement("lendrequests");
            $lendrequests_data = $this->getAllLendRequests($exclusion);
            foreach($lendrequests_data as $lendrequest_data){
                $lendrequests->appendChild($lendrequest_data->toXML( $xmlDoc));
            }
            $retVal->appendChild( $lendrequests);
*/
            $reviews = $xmlDoc->createElement("reviews");
            $reviews_data = $this->getReviews();
            foreach($reviews_data as $review_data){
                $reviews->appendChild($review_data->toXML( $xmlDoc));
            }
            $retVal->appendChild( $reviews);    
        
        return $retVal;
    }

    function getEfiles() {
        $this->_db->setQuery("SELECT * FROM #__medialibrary_emedia_files \n" . 
                             "WHERE fk_emedia_id = '$this->id'");
        $this->efiles = $this->_db->loadObjectList();
    }
    function getVideos() {
        $this->_db->setQuery("SELECT * FROM #__medialibrary_video_source \n" . 
                             "WHERE fk_media_id='$this->id'");
        $this->vfiles = $this->_db->loadObjectList();
    }
    function getAudios() {
        $this->_db->setQuery("SELECT * FROM #__medialibrary_audio_source \n" . 
                             "WHERE fk_media_id='$this->id'");
        $this->afiles = $this->_db->loadObjectList();
    }
    function getTracks() {
        $this->_db->setQuery("SELECT * FROM #__medialibrary_track_source \n" . 
                             "WHERE fk_media_id='$this->id'");
        $this->tfiles = $this->_db->loadObjectList();
    }
    

function toXML2(){

        $retVal = "<media>\n";
        $retVal .= "<id>" . $this->id . "</id>\n";
        $retVal .= "<media_id>" . $this->media_id . "</media_id>\n";
        $retVal .= "<media_type>" . $this->media_type . "</media_type>\n";
        $retVal .= "<informationFrom>" . $this->informationFrom . "</informationFrom>\n";
        $retVal .= "<date>" . $this->date . "</date>\n";
        $retVal .= "<approved>" . $this->approved . "</approved>\n";
        $retVal .= "<published>" . $this->published . "</published>\n";
        $retVal .= "<owner_ID>" . $this->owner_ID . "</owner_ID>\n";
        $retVal .= "<associate_media>" . $this->associate_media . "</associate_media>\n";
        
        
        
        
        //$retVal .= "<langDescription>" . $this->langDescription . "</langDescription>\n";
        //add category
/*      $this->_db->setQuery("SELECT * FROM #__categories ".
                      "WHERE id=".$this->catid . " ; " );
            $tmp = $this->_db->loadObjectList();   */

        //$retVal .= "<category_entity>\n";
        //$retVal .= "<category_id>" . $this->catid . "</category_id>\n";
    
/*          $retVal .= "<category_parent_id>" . $tmp[0]->parent_id . "</category_parent_id>\n";
            $retVal .= "<category_name><![CDATA[" . $tmp[0]->name . "]]></category_name>\n";
            $retVal .= "<category_title><![CDATA[" . $tmp[0]->title . "]]></category_title>\n";
            $retVal .= "<category_section>" . $tmp[0]->section . "</category_section>\n";
            $retVal .= "<category_published>" . $tmp[0]->published . "</category_published>\n";
            $retVal .= "<ordering>" . $tmp[0]->ordering . "</ordering>\n";
            $retVal .= "<access>" . $tmp[0]->access . "</access>\n";
            $retVal .= "<description><![CDATA[" . $tmp[0]->description . "]]></description>\n";
*/
            //$retVal .= "</category_entity>\n";

            

        switch ($this->media_type)
        {
          case 'book':
            $media_class = new mosMedialibrary_book($this->_db);
            $media_class->load($this->media_id);
            $retVal .= $media_class->toXML2();
            break;
          case 'video':
            $media_class = new mosMedialibrary_video($this->_db);
            $media_class->load($this->media_id);
            $retVal .= $media_class->toXML2();
            break;
          case 'music':
            $media_class = new mosMedialibrary_music($this->_db);
            $media_class->load($this->media_id);
            $retVal .= $media_class->toXML2();
            break;
          case 'game':
            $media_class = new mosMedialibrary_game($this->_db);
            $media_class->load($this->media_id);
            $retVal .= $media_class->toXML2();
            break;
        }

        $retVal .= "<reviews>";
        $reviews = $this->getReviews();
        foreach ($reviews as $review){
          $retVal .= $review->toXML2();
        }
        $retVal .= "</reviews>\n";

        $retVal .= "<categs>\n";
        $this->setCategs();
        $categs = $this->categs;
        //var_dump($this->categs);exit;
        foreach ($categs as $categ){
          //echo $this->id,':';var_dump($categ);echo ";";
          $retVal .= "<categ>".$categ."</categ>";
        }
        $retVal .= "</categs>\n";

        $retVal .= "<peoples_connect>\n";
        $this->setPeoples();
        $peoples = $this->peoples;

        foreach ($peoples as $item){
          $retVal .= "<people_connect>".$item."</people_connect>";
        }
        $retVal .= "</peoples_connect>\n";      

        $retVal.= "<efiles>\n";
        $this->getEfiles();
        $efiles = $this->efiles;
        foreach($efiles as $efile) {
            $retVal.= "<efile>";
            $retVal.= "<id>" . $efile->id . "</id>";
            $retVal.= "<fk_emedia_id>" . $efile->fk_emedia_id . "</fk_emedia_id>";
            $retVal.= "<location>" . str_replace('&', '&amp;', $efile->location) . "</location>";
            $retVal.= "<description>" . $efile->description . "</description>";
            $retVal.= "</efile>";
        }
        $retVal.= "</efiles>\n";
        
        $retVal.= "<videos_source>\n";
        $this->getVideos();
        $vfiles = $this->vfiles;
        foreach($vfiles as $vfile) {
            $retVal.= "<video_source>";
            $retVal.= "<id>" . $vfile->id . "</id>";
            $retVal.= "<fk_media_id>" . $vfile->fk_media_id . "</fk_media_id>";
            $retVal.= "<src>" . str_replace('&', '&amp;', $vfile->src) . "</src>";
            $retVal.= "<type>" . $vfile->type . "</type>";
            $retVal.= "<media>" . $vfile->media . "</media>";
            $retVal.= "<youtube>" . $vfile->youtube . "</youtube>";
            $retVal.= "</video_source>";
        }
        $retVal.= "</videos_source>\n";
        
        $retVal.= "<audios_source>\n";
        $this->getAudios();
        $afiles = $this->afiles;
        foreach($afiles as $afile) {
            $retVal.= "<audio_source>";
            $retVal.= "<id>" . $afile->id . "</id>";
            $retVal.= "<fk_media_id>" . $afile->fk_media_id . "</fk_media_id>";
            $retVal.= "<src>" . str_replace('&', '&amp;', $afile->src) . "</src>";
            $retVal.= "<type>" . $afile->type . "</type>";
            $retVal.= "</audio_source>";
        }
        $retVal.= "</audios_source>\n";
        
        $retVal.= "<tracks>\n";
        $this->getTracks();
        $tfiles = $this->tfiles;
        foreach($tfiles as $tfile) {
            $retVal.= "<track>";
            $retVal.= "<id>" . $tfile->id . "</id>";
            $retVal.= "<fk_media_id>" . $tfile->fk_media_id . "</fk_media_id>";
            $retVal.= "<src>" . str_replace('&', '&amp;', $tfile->src) . "</src>";
            $retVal.= "<kind>" . $tfile->kind . "</kind>";
            $retVal.= "<scrlang>" . $tfile->scrlang . "</scrlang>";
            $retVal.= "<label>" . $tfile->label . "</label>";
            $retVal.= "</track>";
        }
        $retVal.= "</tracks>\n";
        $retVal .= "</media>\n";
        return $retVal;
    }
}
