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

//error_reporting(E_ALL ^E_NOTICE);
session_start();

class jcText extends JText
{
    function _($text)
    {
        return parent::_($text);
    }
}

$GLOBALS['database'] = & JFactory::getDBO();
$db =& $database;

require_once( JPATH_ADMINISTRATOR.DS.'components/com_jxplorer/joomlaequipment.config.php' );
require_once( JPATH_ADMINISTRATOR.DS.'components/com_jxplorer/jxplorer.functions.php' );
require_once( JPATH_ADMINISTRATOR.DS.'components/com_jxplorer/jxplorer.helpers.php' );
require_once( JPATH_ROOT.DS.'components/com_jxplorer/jxplorer.xajax.php' );

$document =& JFactory::getDocument();
$document->addScript(JURI::root(true).'/media/system/js/mootools.js');
$document->addScript(JURI::root(true).'/components/com_jxplorer/tmpl/jxplorer.js');



jimport('joomla.template.template');

$tmpl = JTemplate::getInstance();
$tmpl->setRoot(JPATH_BASE.DS.'components/com_jxplorer/tmpl');
$tmpl->readTemplatesFromFile('main.tmpl.html');

$cid        = JRequest::getVar('cid');
$task       = JRequest::getVar('task', '');

$offline = JEConfig::get('general.offline');
if($offline)
{
    $tmpl->addVar('message', 'MESSAGE', JEConfig::get('general.offline_msg'));
    $tmpl->displayParsedTemplate('message');
    $task = 'exit';
}

$access = JEConfig::get('general.access_group');
if(($access !== 'Public') && !$my->id)
{
    $tmpl->addVar('message', 'MESSAGE', JText::_('You do not have access to this component. Please, register or authorize.'));
    $tmpl->displayParsedTemplate('message');
    $task = 'exit';
}

if(!jxTestThumbPath())
{
    $tmpl->addVar('message', 'MESSAGE', JText::_('The Tumbnails directory either not exists or not writable.'));
    $tmpl->displayParsedTemplate('message');
    $task = 'exit';
}
if(!jxTestUploadDir())
{
    $tmpl->addVar('message', 'MESSAGE', JText::_('The Upload directory either not exists or not writable.'));
    $tmpl->displayParsedTemplate('message');
    $task = 'exit';
}



switch($task)
{
    case 'exit':
    break;

    case 'download':
    
        $download = JEConfig::get('general.download');
        if(!$download){
            @ob_end_clean();
         
            jxDownload($cid, JEConfig::get('general.temp_dir'));
            ob_start(false);
        }else{
            $tmpl->addVar('filelist', 'msg', JText::_('The Download Function Is disabled'));
        }
        jxListFiles($tmpl,$task);
    break;
    
    case 'upload':
    default:
      	jxListFiles($tmpl, $task);
}
function jxUppload($files)
{
    $user	 = & JFactory::getUser();
    $db = JFactory::getDBO();
    
    if(JEConfig::get('general.upload_rule') == 'Upload to Current Folder')
    {
        $path = jxGetDestinationById(JRequest::getVar('directory', JEConfig::get('general.upload_dir')));
    }
    else
    {
        $path  = JEConfig::get('general.upload_dir');
        $path  = ereg_replace("/$", "", $path).DS;
        $path .= $user->get('id') ? str_replace(" ", "_", $user->get('name')) : 'pub';
        $path .= DS;
    }
    $path = str_replace(array('/', '//', '\\', '\\\\'), DS, $path);
    
    $ext = explode(", ", strtolower(JEConfig::get('general.upload_type')));
    
    jimport('joomla.filesystem.folder');
    jimport('joomla.filesystem.file');
    foreach($files as $file)
    {
        if(!$file['tmp_name']) continue;
        
        if(!is_dir($path))
        {
            if(JFolder::create($path))
            {
                //JError::raiseNotice(1204, jcText::_('Created Succesful'));
            }
            else
            {
                JError::raiseWarning(1204, jcText::_('Could not create directory!!!'));
                return;
            }
        }
        
        if(file_exists($path.$file['name']))
        {
            JError::raiseWarning(1207, jcText::_('File Exists!')." <B>{$file[name]}</B>");
            continue;
        }
        $fext = strtolower(str_replace(".","", strrchr($file['name'], ".")));
        if(!in_array($fext, $ext))
        {
            JError::raiseWarning(1208, jcText::_('Unsupported Extension!!!')." <B>{$file[name]}</B>");
            continue;
        }
        if(JFile::upload($file['tmp_name'], $path.$file['name']))
        {
            JError::raiseNotice(1204, jcText::_('Upload Succesful')." <B>{$file[name]}</B>");
        }
        else
        {
            JError::raiseWarning(1203, jcText::_('Could not Upload file !!!'));
            return;
        }
    }
    
    $_SESSION['upload_user'] = $user->get('id');
    
    $path = str_replace(DS, "/", $path);
    jxIndexDirectory($path, false);
    
    $descr = JRequest::getVar('descr', array(), 'array');
    foreach($files as $dig => $file)
    {
        $sql = "SELECT id FROM #__jx_index WHERE dir = '{$path}' AND name = '{$file[name]}'";
        $db->setQuery($sql);
        $id = $db->loadResult();
        if($id)
        {
            $int =  substr($dig, -1);
            $desc = $descr[$int];
            $sql = "UPDATE #__jx_index SET description = '{$desc}' WHERE id = $id";
            $db->setQuery($sql);
            $db->query();
        }
    }
    return;
}
function jxListFiles($tmpl, $task)
{
    global $mainframe;
    if($task == 'upload') jxUppload($_FILES);
    
    $db = JFactory::getDBO();
    $my	= & JFactory::getUser();
    $user	= & JFactory::getUser();
    
    $option     = $db->getEscaped(JRequest::getVar('option', 'com_jxlporer'));
    $task       = $db->getEscaped(JRequest::getVar('task'));
    $itemid     = intval(JRequest::getVar('Itemid'));
    $sort       = $db->getEscaped(JRequest::getVar('sort', 'type DESC'));
    $directory  = intval(JRequest::getVar('directory', 0));
    $limitstart = intval(JRequest::getVar('limitstart', 0));
    $cid        = JRequest::getVar('cid');
  
    
    if(!is_array($cid)) $cid = array(0);
    
    $limit      = JEConfig::get('view.num_files');
    $view       = JRequest::getVar('view', JEConfig::get('view.list_view'));
    
    $tmpl->addVar('search-field', 'show_search',  (boolean)JEConfig::get('view.show_search'));
    $tmpl->addVar('toolbar',      'show_toolbar', (boolean)JEConfig::get('view.show_toolbar'));
    $tmpl->addVar('copyright',    'show_rights',  (boolean)JEConfig::get('view.show_rights'));
    $tmpl->addVar('upload',    'show_upload',  (boolean)JEConfig::get('general.uploads'));
    $tmpl->addVar('favorite',    'show_favor',  (boolean)(JEConfig::get('general.favorite') && $user->get('id')));
    $tmpl->addVar('filelist', 'option',     $option);
    $tmpl->addVar('filelist', 'task',       $task);
    $tmpl->addVar('filelist', 'itemid',     $itemid);
    $tmpl->addVar('filelist', 'sort',       $sort);
    $tmpl->addVar('filelist', 'directory',  $directory);
    $tmpl->addVar('filelist', 'view',       $view);

    
    $tmpl->addVar('list_type', 'view', $view);
    $tmpl->addVar('list_type', 'checkbox', $limit);
    
    $sql = "
        SELECT j.*, ROUND((j.rate_total / j.rate_times) / 5 * 100) AS rate FROM #__jx_index AS j 
     LEFT JOIN #__jx_favorites AS f ON f.file_id = j.id 
         WHERE j.published = 1  
           AND j.`trash` = 0 "; 
    
    $sqlf = "
        SELECT f.file_id FROM #__jx_index AS j  
     LEFT JOIN #__jx_favorites AS f ON f.file_id = j.id 
         WHERE j.published = 1  
           AND j.`trash` = 0  
           AND f.user_id = ".$user->get('id')." "; 
    
    if(($task == 'chdir' || $task == 'upload'|| $task == 'download') && $directory)
    {
        $dir = jxGetDestinationById($directory);
        //echo $sql;
        $sql  .= " AND j.dir = '{$dir}' " ;
        $sqlf .= " AND j.dir = '{$dir}' " ;
    }
    else
    {
        if($task == 'favorite')
        {
            $sql .= " AND f.user_id = ".$user->get('id');
        }
        elseif ($task == 'search')
        {
        	
        }
        else 
        {
            $sql  .= " AND j.publish_home = 1";
            $sqlf .= " AND j.publish_home = 1";
        }
    }
    $tmpl->addVar('search-field', 'q',  '');
    if($task == 'search')
    {
        $q = JRequest::getVar('q');
        $search = explode(' ', $q);
        
        $rep = array('~', '`', '!', '@', '#', '$', '%', '^', 
        '&', '(', ')', '+', '=', '\\', '/', '[', ']', '{', '}', 
        '?', ',', '"', '\'', ':', ';');
        
        $clean = str_replace($rep, "" , $search[0]);
        
        $tmpl->addVar('search-field', 'q',  $clean);
        
        if(strstr($clean, "*") && (strlen($clean) > 1))
        {
            $search = str_replace('*', '%', $db->getEscaped($clean));
        }
        else
        {
            if($clean)
              $search = '%'.$db->getEscaped($clean).'%';
        }
        if($search)
        {
            $sql  .= " AND j.name LIKE '{$search}' "; 
            $sqlf .= " AND j.name LIKE '{$search}' "; 
        }
        else
        {
            $limitstart = 0;
            $limit = 0;
        }
        
    }

    if(!(boolean)JEConfig::get('view.show_all') && !$my->get('id'))
    {
        $sql .= " AND `access` = 0 ";
        $sqlf .= " AND `access` = 0 ";
    }
    
    /*if($total == 0)
    {
        $tmpl->addVar('filelist', 'view', 'none');
    }*/

    $sql .= " ORDER BY $sort";
    
    if(JEConfig::get('view.show_pagenav'))
    {
        $db->setQuery($sql);
        $tlist = $db->loadObjectList();
        $total = count($tlist);

        $db->setQuery($sql, $limitstart, $limit);
        $list = $db->loadObjectList();
        jimport('joomla.html.pagination');
        $pageNav = new JPagination( $total, $limitstart, $limit);
    
        $db->setQuery($sqlf, $limitstart, $limit);
        $favor = $db->loadResultArray();
    }
    else
    {
        $db->setQuery($sql);
        $list = $db->loadObjectList();
    
        $db->setQuery($sqlf);
        $favor = $db->loadResultArray();
    }    
    $ts = JEConfig::get('view.tumb_size');
    $tmpl->addVar('filelist', 'width',  ($ts+5));
    $tmpl->addVar('filelist', 'height', ($ts+130));
    $allow_rate = (boolean)JEConfig::get('general.rating');
    $allow_comm = (boolean)JEConfig::get('general.comments');
    foreach($list AS $i => $file)
    {
        if(strtolower($file->type) == "dir")
        {
            $list[$i]->link = sprintf(
                '<a href="javascript:void(0);" onclick="javascript:'.
                'document.adminForm.directory.value=\'%s\';'.
                'submitbutton(\'chdir\'); return false;" title="%s">%s</a>', 
                $file->id, $file->name, $file->name
            );
            $list[$i]->check = '';
        }
        else
        {
            $list[$i]->link = sprintf(
                '<a href="javascript:void(0);" onclick="return listItemTask(\'cb%d\',\'download\')" title="%s">%s</a>', 
                $i, $file->name, $file->name
            );
            $list[$i]->check = '<input type="checkbox" id="cid'.$i.'" name="cid[]" value="'.$file->id.'" onchange="isChecked(this.checked);">';
            //$list[$i]->check = mosCommonHTML::CheckedOutProcessing( $file, $i );
        }
        
        $list[$i]->ctime = date(JEConfig::get('view.date_format'), $file->ctime);
        if($allow_rate) $list[$i]->rating = jxHtml::jxRating($file->rate);
        if($allow_comm)
        {
            $text = jcText::_('Comments').' ('.(int)$file->commetnum.')';
            $list[$i]->comment = JHTML::link('', $text);
        }
        //$list[$i]->rating = 'test';
        $iopt = array('border'=>'0','align'=>'absmiddle');
        $img = "administrator/components/com_jxplorer/images/icons/16/".jxIconCrystal($file->icon, $file->type);
        if($view == 'Icons')
        {
            $img = "administrator/components/com_jxplorer/images/icons/48/".jxIconCrystal($file->icon, $file->type);
        }
        $list[$i]->size = jxFormatSize($file->size);
        $ext = strtolower(str_replace(".", "", $file->type));
        if($view == 'Tumbnails')
        {
            
            $list[$i]->height = $ts + 5;
            $list[$i]->width = $ts + 5;
            
            if(($ext == 'png') || ($ext == 'jpeg') || ($ext == 'jpg') || ($ext == 'gif'))
            {
                $list[$i]->icon = jxMakeTumbnail($file->dir.$file->name, $ts, $ts, JEConfig::get('view.tumb_quality'));
            }
            else
            {
                $img = "administrator/components/com_jxplorer/images/icons/68/".jxIconCrystal($file->icon, $file->type);
            }
        }
     
        $list[$i]->icon = '<img src="'.$img.'" alt="'.$file->name.' '.$iopt.'" />';
        
        $list[$i]->id = $file->id;
        if(JEConfig::get('general.favorite') && $user->get('id'))
        {
            $opt = array(
              'id' => 'favor_'.$file->id,
              'style' => 'cursor:pointer',
              'align'=>'absmiddle',
              'onclick'=>"xajax_jxProcessFavorit($file->id)"
            );
            if(in_array($file->id, $favor))
            {
                $img = 'favor.png';
            }
            else
            {
                $img = 'favor0.png';
            }
            $icon = JHTML::image("/components/com_jxplorer/tmpl/images/".$img, jcText::_('Add To Favorites'), $opt);
            $list[$i]->favor = $icon;
          
            
        }
    }
    
    $link_info = array(
        'option'     => $option,
        'task'       => $task,
        'sort'       => $sort,
        'sort_order' => $sort_order,
        'view'       => $view,
        'directory'  => $directory,
        'Itemid'     => $itemid,
        'q'          => $clean
    );
    if(JEConfig::get('view.show_pagenav')) 
        $tmpl->addVar('pagination',   'page_nav',     
            $pageNav->getPagesLinks("index.php?".jxMakeUrl($link_info)));
    $tmpl->addVar('pagination',   'show_nav',     JEConfig::get('view.show_pagenav'));
    
    $link_info['limit'] = $limit;
    $link_info['limitstart'] = $limitstart;
    $tmpl->addVar('filelist', 'urlplus',    jxMakeUrl($link_info));
    if(JEConfig::get('view.show_address'))
    {
        $tmpl->addVar('address', 'path',       jxAddressLineFront($directory, $link_info, $task));
    }
    if(count($list) > 0) $tmpl->addObject('list_'.strtolower($view), $list, 'list_' ); 
    else $tmpl->addVar('list_type', 'view', 'none');   
    
    $tmpl->displayParsedTemplate('filelist');
}

function jxMakeUrl($param)
{
    foreach($param AS $k => $v)
    {
        $out[] = "$k=$v";
    }
    return implode('&amp;', $out );
}
function jxAddressLineFront($directory, $options, $task)
{
    global $mainframe;

    $pathway =& $mainframe->getPathWay();
    
    if(JEConfig::get('view.joom_path'))
    {
        $options['directory'] = 0;
        $options['task'] = NULL;
        $pathway =& $mainframe->getPathWay();
        $pathway->addItem( JText::_('My Files'), 'index.php?'.jxMakeUrl($options) );
    }
        
    $dir  = jxGetDestinationById($directory);
    $root = jxInitialDirectory();
    
    $dirs = ereg_replace('^'.$root, '', $dir);
    $dirs = ereg_replace('^/','',$dirs);
    $dirs = ereg_replace('/$','',$dirs);
    
    
    if($task == 'search')
    {
        if(JEConfig::get('view.joom_path'))
        {
            $options['directory'] = 0;
            $pathway->addItem( JText::_('Search Result'), 'index.php?'.jxMakeUrl($options) );
        }
        $address .= ' / '.JText::_('Search Result');
        return $address;
    }

    $patern = ' <a href="javascript:void(0);" onclick="javascript:document.adminForm.directory.value=\'%d\';submitbutton(\'chdir\'); return false;">%s</a>';
    
    $address = sprintf($patern, 0, JText::_('ROOT'));
    
    if($dirs)
    {
        $dirs = explode('/', $dirs);
    }
    else
    {
        return $address;
    }
    
    foreach($dirs AS $dir)
    {
        $root .= $dir.'/';
        if(!jxIsPublished($root)) continue;
        $id = jxGetDirectoryId($root);
        if(JEConfig::get('view.joom_path'))
        {
            $options['directory'] = $id;
            $pathway->addItem( $dir, 'index.php?'.jxMakeUrl($options) );
        }
        $address .= ' / ';
        $address .= sprintf($patern, $id, $dir);
        
    }
    return $address;
}

function jxMakeTumbnail($imagem, $max_width, $max_height, $quality){ 
    
    $p = JEConfig::get('view.tumb_path');
    $p = str_replace(array('/', '\\'), DS, $p);
    $p = ereg_replace(DS."$", '', $p);
    jimport( 'joomla.filesystem.path' );
    $tbpath = JPath::clean($p);
   
    $file = basename($imagem);
    
    $tumbfile = $tbpath.substr(md5($file),0,5).'_'.$file;
    
    if(file_exists($tumbfile))
    {
        $img = JHTML::image("/".str_replace("\\", "/", $tumbfile), '', array('border'=> 0));
        return $img;
    }

    if(!file_exists($imagem))
    {
        return $imgenotfound."image not found";
    }

    $size = getimagesize ($imagem);    
    if($size[0] > $max_width)
    {
        $width  = $max_width;
        $k = $size[0] / $max_width;
        $height = ($size[1] / $k); 
    }
    else
    {
        $width  = $size[0];
        $height = $size[1];
    }
    
    // if height is bigger than allowed resize it
    if($height > $max_height)
    {
        $height = $max_height; 
        $k = $height / $max_height;
        $width = ($width / $k); 
    }

    $width  = ceil($width);
    $height = ceil($height);
    
    switch(strtolower(strrchr($imagem, '.')))
    {
        case ".gif":
            $img = imagecreatefromgif($imagem);
            break;
        case ".png":
            $img = imagecreatefrompng($imagem);
            break;
        case ".jpg":
        case ".jpeg":
            $img = imagecreatefromjpeg($imagem);
            break;
    }

    //echo $width .'--'. $height;
    $mini  = imagecreatetruecolor($width, $height);
    $white = imagecolorallocate  ($mini,255,255,255);
    
    imagefilledrectangle($mini,0,0,$width,$height,$white); 
    imagecopyresampled  ($mini,$img,0,0,0,0,$width,$height,$size[0],$size[1]);
    
    imagejpeg($mini, $tumbfile, $quality);
    
    imagedestroy($mini); 
    imagedestroy($img);
    
    $img = JHTML::image("/".str_replace("\\", "/", $tumbfile), '', array('border'=> 0));
    return $img; 
}

?>