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

/**
 *
 * @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
 *
 */



/*function check(){
    jimport('joomla.filter.output');
    $alias = JFilterOutput::stringURLSafe($this->title);
    //$alias = JOutputFilter::stringURLSafe($this->title);
    if (empty($this->alias) || $this->alias === $alias){
        $this->alias = $alias;
    }
}*/

function MediaLibraryBuildRoute(&$query){ //what writting
    // print_r($query);exit;
    global $array_MediaLibraryBuildRoute;
  // print_r("start MediaLibraryBuildRoute");
  // print_r($query);
    $yo = 0;
    // if ($query['lang'] != 'en-GB') {
    //     exit;
    //     print_r($query);exit;
    //     $yo = 1;
    // }
    // if (isset($query['task']) && $query['task'] == 'show_rss_categories'){ob_clean();print_r($query);exit;}
    $array_MediaLibraryBuildRoute = $query;
    $segments = array();
    $db = JFactory::getDBO();
    $app = JFactory::getApplication();
    $menu = $app->getMenu();
    
    if (isset($query['Itemid'])){
          if (!isset($query['view']) && 
             (@$menu->getItem($query['Itemid'])->component == 'com_medialibrary') && 
             !isset($query['task']))
    {
        if (version_compare(JVERSION, "1.6.0", "lt"))
        {
            $query['view'] = $menu->getItem($query['Itemid'])->query['view'];
        } else if (version_compare(JVERSION, "1.6.0", "ge"))
        {
          $query['view'] = $menu->getItem($query['Itemid'])->query['view'];
        }
        else
        {
          $query['view'] = $menu->getItem($query['Itemid'])->query['view'];
        }
      }
    }
    if (isset($query['option']) && $query['option'] == 'com_medialibrary'){ //check component
        $segments[0] = (isset($query['Itemid'])) && ($query['Itemid']!=0) ? $query['Itemid'] : '0';
        if ((isset($query['view'])) && (!isset($query['task']))){
            $query['task'] = $query['view'];
        }
        if (isset($query['task'])){
            switch($query['task']){
                case 'view':
                    $segments[1] = 'view';
                    break; 
                case 'allvideo':
                    $segments[1] = 'allvideo';
                    break; 
                case 'search':
                    // ob_clean();print_r($query);exit;
                    return $segments;
                    $segments[1] = 'search';
                    break; 
                case 'new_url':
                    $segments[1] = 'buy_now';
                    break;
                case 'all_authors':
                    $segments[1] = 'all_people';
                    break;
                case 'view_author':
                    $segments[1] = 'view_people';
                    break;
                // case 'new_url_for_vm':
                //     $segments[1] = 'buy_now_for_vm';
                //     break;
                default:
                    $segments[1] = $query['task'];
                    break;
            }
        }
        unset($query['task']);
        unset($query['view']);
    
        if (!empty($query['lang'])){
            unset($query['lang']);
        }
        // if (isset($query['Itemid'])){
        //     unset($query['Itemid']);
        // }
        // if (!empty($query['Itemid'])){
        //     $query['Itemid'] = "";
        //     unset($query['Itemid']);
        // }

        if (isset($query['name'])){
            $segments[] = JFilterOutput::stringURLSafe($query['name']);
            unset($query['name']);
        }

        if (isset($query['user'])){
            $segments[] = $query['user'];
            unset($query['user']);
        }

        if (isset($query['catid'])){
            if ($query['catid'] > 0){
                $sql_query = "SELECT cc.id, cc.name, mc.catid, cc.parent_id ".
                            " FROM #__medialibrary_main_categories AS cc".
                            " LEFT JOIN #__medialibrary_categories AS mc ON mc.catid=cc.id ".
                            " LEFT JOIN #__medialibrary AS a ON mc.mediaid = a.id ".
                            " WHERE cc.section= 'com_medialibrary' AND cc.id = ".intval($query['catid']);
                $db->setQuery($sql_query);
                $row = null;
                $row = $db->loadObject();
                if (isset($row)){
                    $cattitle = array();
                    $segments[] = JFilterOutput::stringURLSafe($row->name);
                    unset($query['catid']);
                    $catid_was = 1; 
                }
            } else{
                $temp = $query['catid']; //is catid set??
                unset($query['catid']);
                $catid_was = 1;
            }
        }

        if (isset($query['id'])){
            $sql_query = "SELECT mc.catid,other_table.title as title FROM #__medialibrary AS m"
                     ."\n LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid=m.id"
                     ."\n LEFT JOIN #__medialibrary_main_categories AS cc ON cc.id=mc.catid"
                     ."\n JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game "
                     ."\n UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video"
                     ."\n UNION all SELECT  id,title, 'music' as type FROM #__medialibrary_music"
                     ."\n UNION all SELECT id, title, 'book' as type 
                        FROM #__medialibrary_book) AS other_table"
                     ."\n WHERE m.id = ".intval($query['id'])." AND  m.media_type = other_table.type AND 
                        m.media_id = other_table.id";
            $db->setQuery($sql_query);
            $row = null;
            $row = $db->loadObject();
            if (isset($row)){
                $temp_title = JFilterOutput::stringURLSafe($row->title);
                if (isset($temp)){
                    $sql_query = "SELECT name FROM #__medialibrary_main_categories AS cc 
                        WHERE cc.id = ".$row->catid;
                    $db->setQuery($sql_query);
                    $row = $db->loadObject();
                    if (isset($row)){
                        $segments[] = JFilterOutput::stringURLSafe($row->name);
                    }
                }
                $segments[] = $query['id']; //for back up in parseroute
                $segments[] = JFilterOutput::stringURLSafe($temp_title);
                unset($query['id']);
            }
        } else if (isset($query['pid'])) {
            $sql_query = "SELECT people_name FROM #__medialibrary_people"
                     ."\n WHERE id = ".intval($query['pid']);
            $db->setQuery($sql_query);
            $row = null;
            $row = $db->loadObject();
            if (isset($row)){
                $temp_name = JFilterOutput::stringURLSafe($row->people_name);
                $segments[] = $query['pid']; //for back up in parseroute
                $segments[] = JFilterOutput::stringURLSafe($temp_name);
                unset($query['pid']);
            }
        } else if (isset($query['other_uid'])) {
            $sql_query = "SELECT username FROM #__users"
                     ."\n WHERE id = ".intval($query['other_uid']);
            $db->setQuery($sql_query);
            $row = null;
            $row = $db->loadObject();
            if (isset($row)){
                $username = JFilterOutput::stringURLSafe($row->username);
                $segments[] = $query['other_uid']; //for back up in parseroute
                $segments[] = JFilterOutput::stringURLSafe($username);
                unset($query['other_uid']);
            }
        }

        if (isset($query['start'])){
            $segments[] = $query['start'];

            if (isset($query['limitstart'])){
                $segments[] = $query['limitstart'];
                unset($query['limitstart']);
            } else{
                $segments[] = $query['start'];
            }
            unset($query['start']);
        } else if (isset($query['limitstart'])){
            $segments[] = $query['limitstart'];
            unset($query['limitstart']);
        }

        if (isset($query['viewtype'])){
            $segments[] = 'viewtype'.":".$query['viewtype'];
            unset($query['viewtype']);
        }

        if (isset($query['searchtext'])){
            $segments[] = $query['searchtext'];
            unset($query['searchtext']);
        }

        if (isset($query['searchtype'])){
            $segments[] = $query['searchtype'];
            unset($query['searchtype']);
        }
    }
    if (isset($query['tab'])){
        unset($query['tab']);
    }
    if (isset($query['is_show_data'])){
        unset($query['is_show_data']);
    }
    if (isset($segments[1]) && $segments[1] == 'view'){
        if (isset($query['playId'])){
            $segments[] = $query['playId'];
            unset($query['playId']);
        }
        if (isset($query['playVideo'])){
            $segments[] = $query['playVideo'];
            unset($query['playVideo']);
        }
        if (isset($query['currTime'])){
            $segments[] = $query['currTime'];
            unset($query['currTime']);
        }
        if (isset($query['lenSub'])){
            $segments[] = $query['lenSub'];
            unset($query['lenSub']);
        }
    }
    if (isset($segments[1]) && $segments[1] == 'allvideo'){
        if (isset($catid_was)){
            $segments[] = 0;
        }
        if (isset($query['playId'])){
            $segments[] = $query['playId'];
            unset($query['playId']);
        }
        if (isset($query['playVideo'])){
            $segments[] = $query['playVideo'];
            unset($query['playVideo']);
        }
        if (isset($query['currTime'])){
            $segments[] = $query['currTime'];
            unset($query['currTime']);
        }
        if (isset($query['lenSub'])){
            $segments[] = $query['lenSub'];
            unset($query['lenSub']);
        }
    }
    
    if (isset($query['limit'])){
        unset($query['limit']);
    }

    if ($yo){
        print_r($segments);exit;
    }
    // if ($segments[1] == 'search'){
    //     ob_clean();print_r($segments);exit;
    // }
 // print_r("end MediaLibraryBuildRoute");
 // print_r($segments);
    
    return $segments;
}


/**
* Parse the segments of a URL.
**/

function MedialibraryParseRoute($segments){ //where send
  // print_r("start MedialibraryParseRoute");
  // print_r($segments);

    $db = JFactory::getDBO();
    
    $vars = array();
    $count = count($segments);
    $vars['option'] = 'com_medialibrary';
    $app = JFactory::getApplication();
    $menu = $app->getMenu();
    @$menu->setActive($segments[0]);
    if (is_numeric($segments[0]))
        $vars['Itemid'] = $segments[0];
    else $vars['task'] = $segments[0];
    // if (version_compare(JVERSION, '2.6', 'lt')) {
    //     array_unshift($segments,'com_medialibrary');
    // }
    //if ($count > 1){
    if (isset($segments[1])){
        if (@$segments[1] == "alonecategory" || @$segments[0] == "alonecategory"){
            $vars['task'] = "alonecategory";
            $i = 2;
            if (@$menu->getItem($segments[0])->query['view'] != "alonecategory" 
                && (isset($segments[2]) || isset($segments[1]))){
                if (isset($segments[2])) $segments_22 = $segments[2];
                else $segments_22 = $segments[1];
                $segments_2 = str_replace(":", " ", $segments_22);
                $sql_query = "SELECT m.id FROM #__medialibrary_main_categories m 
                    WHERE m.name='".$segments_2."'";
                $db->setQuery($sql_query);
                $row = null;
                $row = $db->loadObject();
                if (empty($row)){
                    $segments_2 = str_replace("-", " ", $segments_2);
                    $sql_query = "SELECT m.id FROM #__medialibrary_main_categories m 
                        WHERE m.name='".$segments_2."'";
                    $db->setQuery($sql_query);
                    $row = null;
                    $row = $db->loadObject();
                }
                $vars['catid'] = $row->id;
                $i = 3;
            }
            if (isset($segments[$i])){
                $viewtype = explode(':', $segments[$i]);
                if ($viewtype[0] == "viewtype"){
                    $vars['viewtype'] = (int) $viewtype[1];
                }
            }

            if (isset($segments[$i]) && !isset($vars['viewtype']) && !isset($segments[$i+1])){
                $vars['start'] = $segments[$i];
            } else{
                unset($vars['start']);
            }

            if (isset($segments[$i+1]) && !isset($vars['viewtype'])){
                $vars['limitstart'] = $segments[$i+1];
            } else{
                unset($vars['limistart']);
            }

            if (isset($segments[$i+2])){
                $viewtype = explode(':', $segments[$i+2]);
                if ($viewtype[0] == "viewtype"){
                    $vars['viewtype'] = (int) $viewtype[1];
                }
            }
        } elseif (@$segments[1] == "view_people"){
            $vars['task'] = "view_author";
            if (isset($segments[2])){
                $vars['pid'] = $segments[2];
            }
        } elseif (@$segments[1] == "view_author"){
            $vars['task'] = "view_author";
            if (isset($segments[2])){
                $vars['pid'] = $segments[2];
            }
        } elseif (@$segments[1] == "mymedias" || @$segments[0] == "mymedias"){
            $vars['view'] = "mymedias";
            if (isset($segments[2])){$vars['limitstart'] = $segments[2];};
        } elseif (@$segments[1] == "mdownload" ){
            $vars['view'] = "mdownload";
            if (isset($segments[2])){$vars['id'] = $segments[2];};
        } elseif (@$segments[1] == "ownermedias" || @$segments[0] == "ownermedias" ){
            $vars['task'] = "ownermedias";
            if (isset($segments[2])){
                $vars['other_uid'] = $segments[2];
            }
            if (isset($segments[3])){
                $vars['limitstart'] = $segments[3];
            }
        } elseif (@$segments[0] == "view" && isset($segments[3])){
            $vars['task'] = "view";
            $vars['id'] = $segments[2];
            if (isset($segments[5]) && $segments[5] == 1){
                $vars['playId'] = $segments[4];
                $vars['playVideo'] = $segments[5];
                $vars['currTime'] = $segments[6];
                $vars['lenSub'] = $segments[7];
            }
        } elseif (@$segments[0] == "view" && !isset($segments[3])){
            $vars['task'] = "view";
            $vars['id'] = $segments[1];
        } elseif (@$segments[1] == "view" && isset($segments[4])){
            $vars['task'] = "view";
            $vars['id'] = $segments[3];
            if (isset($segments[6]) && $segments[6] == 1){
                $vars['playId'] = $segments[5];
                $vars['playVideo'] = $segments[6];
                $vars['currTime'] = $segments[7];
                $vars['lenSub'] = $segments[8];
            }
        } elseif (@$segments[1] == "view" && !isset($segments[4])){
            $vars['task'] = "view";
            $vars['id'] = $segments[2];
        } elseif (@$segments[1] == "Search"){
            $vars['task'] = "search";
            if (isset($segments[4])){
                $vars['searchtext'] = $segments[4];
            }
            if (isset($segments[5])){
                $vars['searchtype'] = $segments[5];
            }
            if(isset($segments[2])){
                $vars['start'] = $segments[2];
            } else{
                unset($vars['start']);
            }
            if (isset($segments[3])){
                $vars['limitstart'] = $segments[3];
            } else{
                unset($vars['limistart']);
            }
        } elseif (@$segments[1] == "show_search"){
            $vars['task'] = "show_search";
            if (isset($segments[4])){
                $vars['searchtext'] = $segments[4];
            }
            if (isset($segments[5])){
                $vars['searchtype'] = $segments[5];
            }
            if (isset($segments[2])){
                $vars['start'] = $segments[2];
            } else{
                unset($vars['start']);
            }
            if (isset($segments[3])){
                $vars['limitstart'] = $segments[3];
            } else{
                unset($vars['limistart']);
            }
        } elseif (isset($segments[1]) && $segments[1] == "search"){
            $vars['task'] = "search";
            if (isset($segments[4])){
                $vars['searchtext'] = $segments[4];
            }
            if (isset($segments[5])){
                $vars['searchtype'] = $segments[5];
            }
            if (isset($segments[2])){
                $vars['start'] = $segments[2];
            } else{
                unset($vars['start']);
            }
            if (isset($segments[3])){
                $vars['limitstart'] = $segments[3];
            } else{
                unset($vars['limistart']);
            }
        } elseif (isset($segments[1]) && $segments[1] == "show_search_media" && isset($segments[2])){
//            $vars['task'] = "show_search_media";
            $vars['task'] = "search";
            if (isset($segments[4])){
                $vars['searchtext'] = $segments[4];
            }
            if (isset($segments[5])){
                $vars['searchtype'] = $segments[5];
            }
            if (isset($segments[2])){
                $vars['start'] = $segments[2];
            } else{
                unset($vars['start']);
            }
            if (isset($segments[3])){
                $vars['limitstart'] = $segments[3];
            } else{
                unset($vars['limistart']);
            }
        } elseif (@$segments[1] == "show_rss_categories"){
            $vars['task'] = "show_rss_categories";
            if (isset($segments[2])) $vars['catid'] = $segments[2];
        } elseif (@$segments[1] == "buy_now"){
            $vars['task'] = "new_url";
            if (isset($segments[2])){
                $vars['id'] = $segments[2];
            }
        } elseif (@$segments[1] == "new_url_for_vm"){
            $vars['task'] = "new_url_for_vm";
            if (isset($segments[2])){
                $vars['id'] = $segments[2];
            }
        } elseif (@$segments[0] == "buy_now"){
            $vars['task'] = "new_url";
            if (isset($segments[1])){
                $vars['id'] = $segments[1];
            }
                $vars['id'] = $segments[1];
        } elseif (@$segments[1] == "lend_history"){
            $vars['task'] = "lend_history";
            $vars['name'] = $segments[2];
            $vars['user'] = $segments[3];
       /* } elseif (@$segments[1] == "ownermedias"){
        $vars['task'] = "ownermedias";
      if (isset($segments[2]) && (!isset($segments[3]))){
                $vars['start'] = $segments[2];
            } else{
                unset($vars['start']);
            }
            if (isset($segments[3])){
                $vars['limitstart'] = $segments[3];
            } else{
                unset($vars['limistart']);
            }    */
      //$vars["id"] = $segments[2];

    } elseif (@$segments[0] == "edit_media"){
        $vars['task'] = "edit_media";
      $vars["id"] = $segments[1];
      $vars["options"] = $segments[2];

    } elseif (@$segments[1] == "edit_media"){
        $vars['task'] = "edit_media";
      $vars["id"] = $segments[2];
      $vars["options"] = $segments[3];


    } elseif (@$segments[1] == "lend_requests"){
            $vars['task'] = "lend_requests";
            if (isset($segments[2])){
                $vars['start'] = $segments[2];
            } else{
                unset($vars['start']);
            }
            if (isset($segments[3])){
                $vars['limitstart'] = $segments[3];
            } else{
                unset($vars['limistart']);
            }
    } elseif (@$segments[1] == "lend_request"){
            $vars['task'] = "lend_request";
    }
    elseif (@$segments[1] == "allgame"){
            $vars['task'] = "allgame";
            if (isset($segments[2]) && (!isset($segments[3]))){
                $vars['start'] = $segments[2];
            } else{
                unset($vars['start']);
            }
            if (isset($segments[3])){
                $vars['limitstart'] = $segments[3];
            } else{
                unset($vars['limistart']);
            }
    }elseif (@$segments[1] == "allbook"){
      $vars['task'] = "allbook";
      if (isset($segments[2]) && (!isset($segments[3]))){
          $vars['start'] = $segments[2];
      } else{
          unset($vars['start']);
      }
      if (isset($segments[3])){
          $vars['limitstart'] = $segments[3];
      } else{
          unset($vars['limistart']);
      }
    }elseif (@$segments[1] == "allvideo"){
      $vars['task'] = "allvideo";
      if (isset($segments[2]) && (!isset($segments[3]))){
          $vars['start'] = $segments[2];
      } else{
          unset($vars['start']);
      }
      

      if (isset($segments[6]) && $segments[6] == 'play'){
        $vars['limitstart'] = $segments[3];
        $vars['playId'] = $segments[5];
        $vars['playVideo'] = $segments[6];
        $vars['currTime'] = $segments[7];
        $vars['lenSub'] = $segments[8];
      } else if (isset($segments[5]) && $segments[5] == 'play'){
        $vars['limitstart'] = $segments[3];
        $vars['playId'] = $segments[4];
        $vars['playVideo'] = $segments[5];
        $vars['currTime'] = $segments[6];
        $vars['lenSub'] = $segments[7];
      } else if (isset($segments[4]) && $segments[4] == 'play'){
        $vars['playId'] = $segments[3];
        $vars['playVideo'] = $segments[4];
        $vars['currTime'] = $segments[5];
        $vars['lenSub'] = $segments[6];
      } else if (isset($segments[3])){
          $vars['limitstart'] = $segments[3];
      } else{
          unset($vars['limistart']);
      }
    }elseif (@$segments[1] == "allmedia"){
      $vars['task'] = "allmedia";
      if (isset($segments[2]) && (!isset($segments[3]))){
          $vars['start'] = $segments[2];
      } else{
          unset($vars['start']);
      }
      if (isset($segments[3])){
          $vars['limitstart'] = $segments[3];
      } else{
          unset($vars['limistart']);
      }
    }elseif (@$segments[1] == "allmusic"){
      $vars['task'] = "allmusic";
      if (isset($segments[2]) && (!isset($segments[3]))){
          $vars['start'] = $segments[2];
      } else{
          unset($vars['start']);
      }
      if (isset($segments[3])){
          $vars['limitstart'] = $segments[3];
      } else{
          unset($vars['limistart']);
      }
    }elseif (@$segments[1] == "all_people" || @$segments[1] == "allpeople"){
      $vars['task'] = "all_authors";
      if (isset($segments[2]) && (!isset($segments[3]))){
          $vars['start'] = $segments[2];
      } else{
          unset($vars['start']);
      }
      if (isset($segments[3])){
          $vars['limitstart'] = $segments[3];
      } else{
          unset($vars['limistart']);
      }
    }elseif (@$segments[1] == "all_authors"){
      $vars['task'] = "all_authors";
      if (isset($segments[2]) && (!isset($segments[3]))){
          $vars['start'] = $segments[2];
      } else{
          unset($vars['start']);
      }
      if (isset($segments[3])){
          $vars['limitstart'] = $segments[3];
      } else{
          unset($vars['limistart']);
      }
    }elseif (@$segments[1] == "ownerslist"){
        $vars['task'] = "ownerslist";
        if (isset($segments[2])){
            $vars['other_uid'] = $segments[2];
        }
    }
    else{
        //  for joomla 2.5 begin
        if (version_compare(JVERSION, '2.6', 'lt') && is_numeric($segments[0])) {
            if ($segments[1] == 'review'){
                $vars['task'] = 'review';
            } else if ($segments[1] == 'secret_image'){
                $vars['task'] = 'secret_image';
            } else if ($segments[1] == 'resultsearch'){
                $vars['task'] = 'resultsearch';
            } else if ($segments[1] == 'mymedias'){
                $vars['task'] = 'mymedias';
            } else if ($segments[1] == 'show_add_media'){
                $vars['task'] = 'show_add_media';
            } else {
                $query = "SELECT link FROM #__menu WHERE id = '".intval($segments[0])."'";
                $db->setQuery($query);
                $link = $db->loadResult();
                if (strpos($link, 'view=show_search_media') !== false){
                    $vars['task'] = 'show_search_media';
                    if (isset($segments[1])){
                        $vars['start'] = $segments[1];
                    }
                    if (isset($segments[2])){
                        $vars['limitstart'] = $segments[2];
                    } 
                }
            }
            if (isset($link) && strpos($link, 'view=mymedias') !== false && $segments[1] == 'lend'){
                $vars['task'] = 'lend';
            }
        } else {
        //  for joomla 2.5 end
          $i=2;
            $vars['task'] = @$segments[1];
            if (isset($segments[$i])){
              $viewtype = explode(':', $segments[$i]);
              if ($viewtype[0] == "viewtype"){
                  $vars['viewtype'] = (int) $viewtype[1];
              }
            }
        }
    }
}
    //} else{
        //$vars['task'] = $segments[1];
    //}

  // print_r("end MedialibraryParseRoute");
  // print_r($vars);
    return $vars;
}
