Location: PHPKode > projects > injooosm > administrator/components/com_injooosm/models/files.php
<?php
/**
 * Joomla! 1.5 component injooosm
 *
 * @version $Id: files.php 2010-02-08 23:13:00$
 * @author Christian Knorr
 * @package injooosm
 * @subpackage backend
 * @license GNU/GPL
 * @filesource
 *
 *
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

// Import Joomla! libraries
jimport('joomla.application.component.model');
/**
 * Model Class Files
 */
class injooosmModelFiles extends JModel {

	/**
	 * Category data array
	 *
	 * @var array
	 */
	var $_data = null;

	/**
	 * Category total
	 *
	 * @var integer
	 */
	var $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	var $_pagination = null;

function imageupload($images,$id,$path) {
	$cfg = injooosmHelper::getConfig();
	$types = explode(',',$cfg->type); // jpg,png,gif f.e.
	if(count($images) > 0 )  {
		$img_dir = JPATH_SITE.DS.'images'.DS.'injooosm'.DS.$id;
		JFolder::create($img_dir,0777);
		foreach($images['name'] as $key => $value)  {
			$ext = explode('.',$images['name'][$key]);
			$ext = count($ext)-1;
			$filename = str_replace(".".$ext,"",$images['name'][$key]);
			if(in_array(strtolower($ext), $types)) {
				$path = $img_dir.$images['name'][$key];
				$this->createImage($images['tmp_name'][$key], $ext, $path);
			}
		}
	}
}

    /**
     *
     * @param int
     * @return random string with given (int) lengh
     * http://www.php.net/manual/de/function.mt-rand.php#92711
     */
function alphanumericPass($length) {
    $p ="";
    for ($i=0;$i<$length;$i++)
    {
        $c = mt_rand(1,4);
        switch ($c)
        {
            case ($c<=2):
                // Add a number
                $p .= mt_rand(0,9);
            break;
            case ($c<=4):
                // Add a lowercase letter
                $p .= chr(mt_rand(97,122));
            break;
        }
    }
    return $p;
}

    /**
     *
     * @global array $mainframe
     * @global string $option
     */
    function __construct() {
		parent::__construct();
		global $mainframe, $option;

		// Get the pagination request variables
		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( $option.'.limitstart', 'limitstart', 0, 'int' );

		// In case limit has been changed, adjust limitstart accordingly
//		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
        $limitstart = JRequest::getVar('limitstart',0);

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);

		$array = JRequest::getVar('cid', array(0), '', 'array');
		$edit	= JRequest::getVar('edit',true);
		if($edit)
			$this->setId((int)$array[0]);
    }

    /**
     *
     * @return array
     */
	function getData()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}

		return $this->_data;
	}
    /**
     *
     * @return array $pagination
     */
 	function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}

    /**
     *
     * @return string
     */
    function getTotal()  {

		// Lets load the content if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
    }

    /**
     *
     * @global array $mainframe
     * @return string
     */
    function _fetchJPTfiles()  {
	global $mainframe;
	$db =& JFactory::getDBO();
	$query = "SELECT * FROM #__gps_tracks";
	if($db->setQuery($query)) return false;
	$rows = $db->loadAssocList();
	return $rows;
    }

    /**
     *
     * @global array $mainframe
     * @return string
     */
    function _buildQuery()  {
        global $mainframe;

	$orderby	= $this->_buildContentOrderBy();
        $where      = $this->_buildContentWhere();

        $db =& JFactory::getDBO();

        $query = "SELECT a.*, b.title AS cat FROM"
                . "\n #__osm_files AS a"
                . "\n LEFT JOIN #__osm_cats AS b"
                . "\n ON a.catid=b.id"
                . $where
                . $orderby
                ;

        return $query;
    }

    /**
     *
     * @global object $mainframe
     * @global string $option
     * @return string
     */
 	function _buildContentOrderBy()
	{
		global $mainframe, $option;

		$filter_order		= $mainframe->getUserStateFromRequest
			( $option.'filter_order','filter_order','ordering','cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest
			( $option.'filter_order_Dir','filter_order_Dir','','word' );

		if ($filter_order == 'ordering'){
			$orderby 	= ' ORDER BY ordering '.$filter_order_Dir;
		} else {
			$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.' , id ';
		}

		return $orderby;
	}

    /**
     *
     * @global object $mainframe
     * @global string $option
     * @return string
     */
    function _buildContentWhere()  {

        global $mainframe, $option;

        $search =& JRequest::getVar('search');
        $where = array();
        $db =& JFactory::getDBO();

        if($search)  {
            $where[] = 'LOWER(a.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
            $where[] = 'LOWER(b.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
            $where[] = 'LOWER(a.date) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
        }
        $where = ( count( $where ) ? ' WHERE ' . implode( ' OR ', $where ) : '' );
        
        return $where;
    }

    /**
     *
     * @global object $mainframe
     * @param string $id
     * @return object
     */
    function getFile($id)  {
        global $mainframe;

        $db =& JFactory::getDBO();

        $query = "SELECT * FROM #__osm_files"
                . "\n WHERE id='" . $id . "'";

        $db->setQuery($query);
        $result = $db->loadObject();

        if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}

        return $result;
    }

    /**
     *
     * @param string $id
     */
	function setId($id)
	{
		// Set weblink id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
	}


    /**
     *
     * @param array $cid
     * @param string $publish
     * @return bool
     */
	function publish($cid = array(), $publish = 1)
	{
		$user 	=& JFactory::getUser();

		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__osm_files'
				. ' SET published = '.(int) $publish
				. ' WHERE id IN ( '.$cids.' )'
				. ' AND ( checked_out = 0 OR ( checked_out = '.(int) $user->get('id').' ) )'
			;
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}

    /**
     *
     * @param array $cid
     * @param string $access
     * @return bool
     */
	function access($cid = array(), $access = 1)
	{
		$user 	=& JFactory::getUser();

		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__osm_files'
				. ' SET access = '.(int) $access
				. ' WHERE id IN ( '.$cids.' )'
				. ' AND ( checked_out = 0 OR ( checked_out = '.(int) $user->get('id').' ) )'
			;
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}

    /**
     *
     * @param array $cid
     * @return boolean
     */
	function delete($cid = array())
	{
        jimport('joomla.filesystem.file');

		$result = false;

		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
            // delete the images
            $query = 'SELECT * FROM #__osm_files WHERE id IN ( '.$cids.' )';
            $this->_db->setQuery($query);
            $rows = $this->_db->loadObjectList();

            if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
            foreach($rows as $row)  {
// Bildlöschung
		$filename = JPATH_SITE.DS."images".DS."injooosm".DS."cats".DS.$row->image;
		if (is_file($filename))
			JFile::delete($filename);
// Dateilöschung
		$filename = JPATH_SITE.DS."components".DS."com_injooosm".DS."uploads".DS.$row->file;
		if (is_file($filename)) {
			JFile::delete($filename);
		}

// Bilderlöschung
	$imagedir = JPATH_SITE.DS."images".DS."injooosm".DS.$row->id;
	if (is_file($imagedir)) {
		$imagefiles = JFolder::files($imagedir);
		if (count($imagefiles)) {
			foreach ( $imagefiles AS $imagetodelete ) {
			if (is_file($imagedir.DS.$imagetodelete))
				JFile::delete($imagedir.DS.$imagetodelete);
			}
		}
	}
            }

            //delete from DB
			$query = 'DELETE FROM #__osm_files WHERE id IN ( '.$cids.' )';
			$this->_db->setQuery( $query );
			if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}

        /**
         *
         * @global object $mainframe
         * @return array
         */
function getLevel($selected=0)  {
	$return = "\n";
	for($i=0;$i<6;$i++){
		$return .= ("<input type=\"radio\" name=\"level\" id=\"level".$i."\" value=\"".$i."\"");
		if ($i==$selected)
		$return .= (" checked=\"checked\"");
		$return .= (" /><label for=\"level".$i."\">");
		if ($i==0)
			$return .= JText::_('OSM_SELECT')."<br />";
		else
			$return .= $i;
		$return .= ("</label>\n");
	}
	return $return;
}
        /**
         *
         * @global object $mainframe
         * @return array
         */
        function getCats()  {
	global $mainframe;
	$db =& JFactory::getDBO();

// 	$query = "SELECT * FROM #__osm_cats ORDER BY title ASC";
	$query = "SELECT * FROM #__osm_cats ORDER BY id ASC";
// 	$query = "SELECT * FROM #__osm_cats";
// 	$query = "SELECT * FROM #__osm_cats ORDER BY parent,id ASC";

	$db->setQuery($query);
	$rows = $db->loadObjectList();
	$children = array();
	foreach ($rows as $v ) {
		$pt	= $v->parent;
		$list	= @$children[$pt] ? $children[$pt] : array();
		array_push( $list, $v );
		$children[$pt] = $list;
	}
        $levellimit = 50;

	$rows = JHTML::_('menu.treerecurse', 0, '', array(), $children, max( 0, $levellimit-1 ) );

	$return = array(array(
		id=>0,
		parent=>0,
		title=>JText::_('OSM_SELECT'),
		description=>"",
		image=>"",
		ordering=>0,
		published=>0,
		checked_out=>0
	));
	$i = 0;
	foreach($rows AS $value){
// 		$value->title = "(".$value->id."-".$value->parent.") ".$value->title;
		$id[$i] = ((int)$value->id);
		$parent[$i] = ((int)$value->parent);
		$title[$id[$i]] = ($value->title);
		if ($parent[$i] != 0) {
// 			$value->title = $title[$i]." - ".$value->title;
			$value->title = "&nbsp;&nbsp;&nbsp;|_&nbsp;&nbsp;&nbsp;".$value->title;
		}
		$return[] = $value;
		$i++;
	}
	return $return;
}

        /**
         *
         * @global object $mainframe
         * @return array
         */
        function getTerrain()  {
            global $mainframe;

            $db =& JFactory::getDBO();

            $query = "SELECT * FROM #__osm_terrain ORDER BY title ASC";

            $db->setQuery($query);
            $rows = $db->loadObjectList();
            return $rows;
        }

    function saveFiles() {
        global $mainframe;
        jimport('joomla.filesystem.file');
        require_once("..".DS."components".DS."com_injooosm".DS."helpers".DS."gpsClass.php");
	$fileokay = true;
        $db =& JFactory::getDBO();
        $user =& JFactory::getUser();
	$targetdir = JPATH_SITE.DS."components".DS."com_injooosm".DS."uploads".DS;	
	$found =& JRequest::getInt('found');
	for($i=0;$i<$found;$i++) {
		$existingfiles = JFolder::files($targetdir);
		$import =& JRequest::getVar('import_'.$i);
		if ( $import == "on" ) {
			$catid =& JRequest::getInt('catid_'.$i);
			$level =& JRequest::getInt('level_'.$i);
			$title =& JRequest::getVar('title_'.$i);
			$terrain =& JRequest::getVar('terrain_'.$i);
			$desc =& JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW);
			$file =& JRequest::getVar('file_'.$i);
			$file_tmp = explode(DS,$file);
			$file_tmp = str_replace(' ','_',strtolower($file_tmp[(count($file_tmp)-1)]));
			$file_tmp = explode('.',$file_tmp);
			$extension = $file_tmp[(count($file_tmp)-1)];
			unset($file_tmp[(count($file_tmp)-1)]);
			$file_tmp = trim(implode('.',$file_tmp));
			$file_tmp = str_replace('#','',$file_tmp);
			$file_tmp = str_replace('\&amp;','',$file_tmp);
			$file_tmp = str_replace('\&','',$file_tmp);
			$target = $file_tmp.".".$extension;
			$target = JFile::makeSafe($target);
			if ( in_array($target,$existingfiles) ) {
				$randnumber = (50-strlen($target));
				$fncount = 0;
				while (true) {
					$randname = $this->alphanumericPass($randnumber);
					$target = $file_tmp.$randname.".".$extension;
					if (!in_array($target,$existingfiles) )
						break;
// Man weiß ja nie ;)
					if ( $fncount > 100 ) {
						$randname = $this->alphanumericPass(45);
						$target = $randname.".".$extension;
					}
					if ( $fncount > 10000 )
						die("<html>Booah! No free Filename available!<br>\"<i>".$file."</i>\"</html>");
					$fncount++;
				}
			} elseif (strlen($target) > 50) { // Wenn Dateiname über 50 Zeichen hat...
					for($j=0;$j<100;$j++) { // ... unternehme 100 Versuche...
						$file_tmp = $this->alphanumericPass(45);
						if ( !in_array($file_tmp.".".$extension,$existingfiles) ) {
							// ... einen neuen Namen zu finden, ...
							$target = $file_tmp.".".$extension;
							$j=105; // ... und beende, andernfalls ...
						}
						if ( $j == 99 ) // ... breche ab.
							die("<html>Filename<br>\"<i>".$file."</i>\"<br>too long to proceed, please short manually</html>");
					}
			}

			$uid =& JRequest::getVar('uid_'.$i);
			$date =& JRequest::getVar('date_'.$i);
//			$images =& JRequest::getVar('images_'.$i, null, 'files', 'array');
			$access =& JRequest::getInt('access_'.$i);
// 	get the start coordinates $target
			$gps = new gpsClass();
			$gps->gpsFile = $file;
			$isTrack = $gps->isTrack();
			if ($isTrack !== false) $isTrack = "1"; else $isTrack = "0";
			$isWaypoint = $gps->isWaypoint();
			if ($isWaypoint !== false) $isWaypoint = "1"; else $isWaypoint = "0";
			$isRoute = "0";
			if($start = $gps->getStartCoordinates())  {
				$fileokay = true;
			} else {
				echo "<script type='text/javascript'>alert('".JText::_('OSM_NO_SUPPORT').": ".$target."');window.history.back(-1);</script>";
// 				exit;
			}
			if ($fileokay == true) {
	
	// upload the file
// 				$upload_dir = JPATH_SITE.DS."components".DS."com_injooosm".DS."uploads".DS;
// 				$filename = explode(DS,$file);
// 				$filename = $filename[(count($filename)-1)];
// 				$filename = JFile::makeSafe($filename);
				if (!JFile::copy($file, $targetdir.$target)) {
					echo "Upload failed (file: \"".$file."\") !\n";
				} else {
					chmod($targetdir.$target, 0664);
				}
				if (!JFile::delete($file))
					echo "Erasing failed (file: \"".$file."\") !\n";
	
				$start_n = $start[1];
				$start_e = $start[0];
				$coords = $gps->getCoords($targetdir.$target);
				$distance = $gps->getDistance($coords);
	// call the elevation function
				$ele = $gps->getElevation($coords);
	// images upload part

				$query = "INSERT INTO #__osm_files SET"
					. "\n uid='".$uid."',"
					. "\n catid='".$catid."',"
					. "\n title='".$title."',"
					. "\n file='".$target."',"
					. "\n terrain='".$terrain."',"
					. "\n description='".$desc."',"
					. "\n date='".$date."',"
					. "\n start_n='".$start_n."',"
					. "\n start_e='".$start_e."',"
					. "\n distance='".$distance."',"
					. "\n ele_asc='".$ele[0]."',"
					. "\n ele_desc='".$ele[1]."',"
					. "\n level='".$level."',"
					. "\n access='".$access."',"
					. "\n istrack='".$isTrack."',"
					. "\n iswp='".$isWaypoint."',"
					. "\n isroute='".$isRoute."'";

				$db->setQuery($query);
				$db->query();
				if ($db->getErrorNum()) {
					echo $db->stderr();
					return false;
				}
			}
		}
	}
    return true;
    }

    function importFromJPT($track) {
        global $mainframe;
        jimport('joomla.filesystem.file');
        require_once("..".DS."components".DS."com_injooosm".DS."helpers".DS."gpsClass.php");
        $db =& JFactory::getDBO();
	$fileokay = false;
	$targetdir = JPATH_SITE.DS."components".DS."com_injooosm".DS."uploads".DS;
	$sourcedir = JPATH_SITE.DS."components".DS."com_joomgpstracks".DS."uploads".DS;
	$existingfiles = JFolder::files($targetdir);
	$file = $sourcedir.$track['file'];
		$file_tmp = explode(DS,$file);
		$file_tmp = str_replace(' ','_',strtolower($file_tmp[(count($file_tmp)-1)]));
		$file_tmp = explode('.',$file_tmp);
		$extension = $file_tmp[(count($file_tmp)-1)];
		unset($file_tmp[(count($file_tmp)-1)]);
		$file_tmp = trim(implode('.',$file_tmp));
		$file_tmp = str_replace('#','',$file_tmp);
		$file_tmp = str_replace('\&amp;','',$file_tmp);
		$file_tmp = str_replace('\&','',$file_tmp);
	$target = $file_tmp.".".$extension;
	$target = JFile::makeSafe($target);
	if ( in_array($target,$existingfiles) ) {
		$randnumber = (50-strlen($target));
		$fncount = 0;
		while (true) {
			$randname = $this->alphanumericPass($randnumber);
			$target = $file_tmp.$randname.".".$extension;
			if (!in_array($target,$existingfiles) )
				break;
// Man weiß ja nie ;)
			if ( $fncount > 100 ) {
				$randname = $this->alphanumericPass(45);
				$target = $randname.".".$extension;
			}
			if ( $fncount > 10000 )
				die("<html>Booah! No free Filename available!<br>\"<i>".$file."</i>\"</html>");
			$fncount++;
		}
	} elseif (strlen($target) > 50) { // Wenn Dateiname über 50 Zeichen hat...
		for($j=0;$j<100;$j++) { // ... unternehme 100 Versuche...
			$file_tmp = $this->alphanumericPass(45);
			if ( !in_array($file_tmp.".".$extension,$existingfiles) ) {
				// ... einen neuen Namen zu finden, ...
				$target = $file_tmp.".".$extension;
				$j=105; // ... und beende, andernfalls ...
			}
			if ( $j == 99 ) // ... breche ab.
				die("<html>Filename<br>\"<i>".$file."</i>\"<br>too long to proceed, please short manually</html>");
		}
	}
// 	get the start coordinates $target
	$gps = new gpsClass();
	$gps->gpsFile = $file;
	$isTrack = $gps->isTrack();
	if ($isTrack !== false) $isTrack = "1"; else $isTrack = "0";
	$isWaypoint = $gps->isWaypoint();
	if ($isWaypoint !== false) $isWaypoint = "1"; else $isWaypoint = "0";
	$isRoute = "0";
	if($start = $gps->getStartCoordinates())  {
		$fileokay = true;
	} else {
		echo "<script type='text/javascript'>alert('".JText::_('OSM_NO_SUPPORT').": ".$target."');window.history.back(-1);</script>";
// 				exit;
	}
	if ($fileokay == true) {
		if (!JFile::copy($file, $targetdir.$target)) {
			echo "Upload failed (file: \"".$file."\") !\n";
		} else {
			chmod($targetdir.$target, 0664);
		}
		$cfg = injooosmHelper::getConfig();
		$types = explode(',',$cfg->type);
		$query = "INSERT INTO #__osm_files SET"
			. "\n uid='".$track['uid']."',"
			. "\n catid='0',"
			. "\n title='".$track['title']."',"
//			. "\n file='".$track['file']."',"
			. "\n file='".$target."',"
			. "\n description='".$track['description']."',"
			. "\n date='".$track['date']."',"
			. "\n start_n='".$track['start_n']."',"
			. "\n start_e='".$track['start_e']."',"
			. "\n distance='".$track['distance']."',"
			. "\n ele_asc='".$track['ele_asc']."',"
			. "\n ele_desc='".$track['ele_desc']."',"
			. "\n level='".$track['level']."',"
			. "\n access='".$track['access']."',"
			. "\n istrack='".$isTrack."',"
			. "\n iswp='".$isWaypoint."',"
			. "\n isroute='".$isRoute."'";
		$db->setQuery($query);
		$db->query();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		} else {
// start picture import
	$query = "SELECT id FROM #__osm_files WHERE file='" . $target . "'";
	$db->setQuery($query);
	$result = $db->loadObject();
        if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
	$imagedirsource = JPATH_SITE.DS."images".DS."joomgpstracks".DS.md5($track['title']).DS;
	$imagedirsourcedir = JFolder::files($imagedirsource);
	$imagedirdestination = JPATH_SITE.DS."images".DS."injooosm".DS.$result->id.DS;
	if((!JFolder::exists($imagedirdestination)) AND (count($imagedirsourcedir) > 0) )
		JFolder::create($imagedirdestination,0777);
	foreach ( $imagedirsourcedir AS $imagetocopy ) {
		if (!JFile::copy($imagedirsource.$imagetocopy, $imagedirdestination.$imagetocopy)) {
			echo "Upload failed:<pre>\"".$imagedirsource.$imagetocopy."\"</pre> to <pre>\"".$imagedirdestination.$imagetocopy."\"</pre>\n";
			return false;
		}
	}
// end picture import
}
	}
    return true;
    }

    function saveFile()  {
        global $mainframe;
        jimport('joomla.filesystem.file');
        require_once("..".DS."components".DS."com_injooosm".DS."helpers".DS."gpsClass.php");

        $db =& JFactory::getDBO();
        $user =& JFactory::getUser();
        // get the post data
        $catid =& JRequest::getInt('catid');
        $level =& JRequest::getInt('level');
        $title =& JRequest::getVar('title');
        $terrain =& JRequest::getVar('terrain');
if ($terrain)
        $terrain = implode(',', $terrain);
else
$terrain = "";
        $desc =& JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW);
        $file =& JRequest::getVar('file', null, 'files', 'array');
        $uid =& JRequest::getVar('uid');
        $date = date("Y-m-d");
//        $images =& JRequest::getVar('images', null, 'files', 'array');
        $access =& JRequest::getInt('access');



            // upload the file
            $upload_dir = JPATH_SITE.DS."components".DS."com_injooosm".DS."uploads".DS;
            $filename = JFile::makeSafe($file['name']);
            if (!JFile::upload($file['tmp_name'], $upload_dir.strtolower($filename))) {
                echo "Upload failed!";
            } else {
                chmod($upload_dir.strtolower($filename), 0664);
            }

            // get the start coordinates
            $gps = new gpsClass();
	$isTrack = $gps->isTrack(simplexml_load_file($upload_dir.strtolower($filename)));
// die(var_dump($isTrack));
	if ($isTrack !== false) $isTrack = "1"; else $isTrack = "0";
	$isWaypoint = $gps->isWaypoint(simplexml_load_file($upload_dir.strtolower($filename)));
	if ($isWaypoint !== false) $isWaypoint = "1"; else $isWaypoint = "0";
	$isRoute = "0";
            $gps->gpsFile = "..".DS."components".DS."com_injooosm".DS."uploads".DS.strtolower($filename);
            if($gps->getStartCoordinates())  {
                $start = $gps->getStartCoordinates();
            } else {
                echo "<script type='text/javascript'>alert('".JText::_('OSM_NO_SUPPORT')."');window.history.back(-1);</script>";
//                 exit;
            }

            $file = "..".DS."components".DS."com_injooosm".DS."uploads".DS.strtolower($filename);
            $start_n = $start[1];
            $start_e = $start[0];
            $coords = $gps->getCoords($file);
            $distance = $gps->getDistance($coords);
//             if($distance == NULL)  {
//                 echo "<script type='text/javascript'>alert('".JText::_('OSM_DISTANCE')." = 0');window.history.back(-1);</script>";
//                 exit; // Warum stop?
//             }

            // call the elevation function
            $ele = $gps->getElevation($coords);


            // images upload part
            $cfg = injooosmHelper::getConfig();
            $types = explode(',',$cfg->type);
/*
            if(count($images) > 0 )  {
                JFolder::create(JPATH_SITE.DS.'images'.DS.'injooosm'.DS.md5($title),0664);
                $img_dir = JPATH_SITE.DS.'images'.DS.'injooosm'.DS.md5($title);
                foreach($images['name'] as $key => $value)  {
                    $ext = explode('.',$images['name'][$key]);
                    if(in_array($ext[1], $types)) {
                        $path = $img_dir.DS.strtolower($images['name'][$key]);
                        $this->createImage($images['tmp_name'][$key], $ext[1], $path);
                    }
                }
            }
*/


            $query = "INSERT INTO #__osm_files SET"
                    . "\n uid='".$uid."',"
                    . "\n catid='".$catid."',"
                    . "\n title='".$title."',"
                    . "\n file='".strtolower($filename)."',"
                    . "\n terrain='".$terrain."',"
                    . "\n description='".$desc."',"
                    . "\n date='".$date."',"
                    . "\n start_n='".$start_n."',"
                    . "\n start_e='".$start_e."',"
                    . "\n distance='".$distance."',"
                    . "\n ele_asc='".$ele[0]."',"
                    . "\n ele_desc='".$ele[1]."',"
                    . "\n level='".$level."',"
                    . "\n access='".$access."',"
		. "\n istrack='".$isTrack."',"
		. "\n iswp='".$isWaypoint."',"
		. "\n isroute='".$isRoute."'"
                    ;

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

            if ($db->getErrorNum()) {
		JFile::delete($file);
		return false;
                } else {
                    return true;
                }

    }
	/*
	 * description: Import tracks from JoomGPSTracks
	 *
	 * @param string $id
	 */
    function importJPTtracks()  {
/* under construction */
	$importfiles = $this->_fetchJPTfiles;
        global $mainframe;
        jimport('joomla.filesystem.file');
        require_once("..".DS."components".DS."com_injooosm".DS."helpers".DS."gpsClass.php");
	$fileokay = true;
        $db =& JFactory::getDBO();
        $user =& JFactory::getUser();
	$targetdir = JPATH_SITE.DS."components".DS."com_injooosm".DS."uploads".DS;	
//	$found =& JRequest::getInt('found');
	for($i=0;$i<count($importfiles);$i++) {
		$importfile = $importfiles[$i];
		$existingfiles = JFolder::files($targetdir);
//		$import =& JRequest::getVar('import_'.$i);
//		if ( $import == "on" ) {
			$catid = $importfile['catid'];
			$level = $importfile['level'];
			$title = $importfile['title'];
			$terrain = $importfile['terrain'];
			$desc = $importfile['desc'];
			$file = $importfile['file'];
			$source = $file;
				$file_tmp = explode(DS,$file);
//				$file_tmp = str_replace(' ','_',strtolower($file_tmp[(count($file_tmp)-1)]));
				$file_tmp = explode('.',$file_tmp);
				$extension = $file_tmp[(count($file_tmp)-1)];
				unset($file_tmp[(count($file_tmp)-1)]);
				$file_tmp = trim(implode('.',$file_tmp));
				$file_tmp = str_replace('#','',$file_tmp);
				$file_tmp = str_replace('\&amp;','',$file_tmp);
				$file_tmp = str_replace('\&','',$file_tmp);
			$target = $file_tmp.".".$extension;
			$target = JFile::makeSafe($target);
			if ( in_array($target,$existingfiles) ) {
				$randnumber = (50-strlen($target));
				$fncount = 0;
				while (true) {
					$randname = $this->alphanumericPass($randnumber);
					$target = $file_tmp.$randname.".".$extension;
					if (!in_array($target,$existingfiles) )
						break;
// Man weiß ja nie ;)
					if ( $fncount > 100 ) {
						$randname = $this->alphanumericPass(45);
						$target = $randname.".".$extension;
					}
					if ( $fncount > 10000 )
						die("<html>Booah! No free Filename available!<br>\"<i>".$file."</i>\"</html>");
					$fncount++;
				}
			} elseif (strlen($target) > 50) { // Wenn Dateiname über 50 Zeichen hat...
					for($j=0;$j<100;$j++) { // ... unternehme 100 Versuche...
						$file_tmp = $this->alphanumericPass(45);
						if ( !in_array($file_tmp.".".$extension,$existingfiles) ) {
							// ... einen neuen Namen zu finden, ...
							$target = $file_tmp.".".$extension;
							$j=105; // ... und beende, andernfalls ...
						}
						if ( $j == 99 ) // ... breche ab.
							die("<html>Filename<br>\"<i>".$file."</i>\"<br>too long to proceed, please short manually</html>");
					}
			}

			$uid = $importfile['uid'];
			$date = $importfile['date'];
			$access = $importfile['access'];
// 	get the start coordinates $target
			$gps = new gpsClass();
			$gps->gpsFile = $file;
			$isTrack = $gps->isTrack();
			if ($isTrack !== false) $isTrack = "1"; else $isTrack = "0";
			$isWaypoint = $gps->isWaypoint();
			if ($isWaypoint !== false) $isWaypoint = "1"; else $isWaypoint = "0";
			$isRoute = "0";
			$start_n = $importfile['start_n'];
			$start_e = $importfile['start_e'];
/*			if($start = $gps->getStartCoordinates())  {
				$fileokay = true;
			} else {
				echo "<script type='text/javascript'>alert('".JText::_('OSM_NO_SUPPORT').": ".$target."');window.history.back(-1);</script>";
// 				exit;
			}
*/
//			if ($fileokay == true) {
	
	// upload the file
// 				$upload_dir = JPATH_SITE.DS."components".DS."com_injooosm".DS."uploads".DS;
// 				$filename = explode(DS,$file);
// 				$filename = $filename[(count($filename)-1)];
// 				$filename = JFile::makeSafe($filename);
				if (!JFile::copy($file, $targetdir.$target)) {
					echo "Upload failed (file: \"".$file."\") !\n";
				} else {
					chmod($targetdir.$target, 0664);
				}
//				if (!JFile::delete($file))
//					echo "Erasing failed (file: \"".$file."\") !\n";
	
//				$start_n = $start[1];
//				$start_e = $start[0];
//				$coords = $gps->getCoords($targetdir.$target);
//				$distance = $gps->getDistance($coords);
				$distance = $importfile['distance'];

	// call the elevation function
//				$ele = $gps->getElevation($coords);
				$ele[0] = $importfile['ele_asc'];
				$ele[1] = $importfile['ele_desc'];

	// images upload part
				$cfg = injooosmHelper::getConfig();
				$types = explode(',',$cfg->type);

				$query = "INSERT INTO #__osm_files SET"
					. "\n uid='".$uid."',"
					. "\n catid='".$catid."',"
					. "\n title='".$title."',"
					. "\n file='".$target."',"
					. "\n terrain='".$terrain."',"
					. "\n description='".$desc."',"
					. "\n date='".$date."',"
					. "\n start_n='".$start_n."',"
					. "\n start_e='".$start_e."',"
					. "\n distance='".$distance."',"
					. "\n ele_asc='".$ele[0]."',"
					. "\n ele_desc='".$ele[1]."',"
					. "\n level='".$level."',"
					. "\n access='".$access."',"
					. "\n istrack='".$isTrack."',"
					. "\n iswp='".$isWaypoint."',"
					. "\n isroute='".$isRoute."'";

				$db->setQuery($query);
				$db->query();
				if ($db->getErrorNum()) {
					echo $db->stderr();
					return false;
				} else {

// Fehlt noch ...
					$id = 0;
					$images = 0;
// Fehlt noch ...

					$sourcePath = JPATH_SITE.DS.'images'.DS.'joomgpstracks'.DS.md5($title);
					$destPath = JPATH_SITE.DS.'images'.DS.'injooosm'.DS.$id;
					if(count($images) > 0 )  {
						JFolder::create($destPath,0777);
//						$img_dir = JPATH_SITE.DS.'images'.DS.'injooosm'.DS.md5($title);
						foreach($images['name'] as $key => $value)  {
							$ext = explode('.',$images['name'][$key]);
							if(in_array($ext[1], $types)) {
								$path = $destPath.DS.strtolower($images['name'][$key]);
								$this->createImage($images['tmp_name'][$key], $ext[1], $path);
							}
						}
					}
				}
			}
//		}
//	}
// */
    return false;
    }

        /**
         * creates the images
         *
         * @param string $file_tmp_name
         * @param string $ext
         * @param string $filepath
         */
        function createImage($file_tmp_name, $ext, $filepath)  {

               switch (strtolower($ext))
               {
                  case 'jpeg':
                  case 'pjpeg':
                  case 'jpg':
                     $src = ImageCreateFromJpeg($file_tmp_name);
                     break;

                  case 'png':
                     $src = ImageCreateFromPng($file_tmp_name);
                     break;

                  case 'gif':
                     $src = ImageCreateFromGif($file_tmp_name);
                     break;

               }

                list($width,$height)=getimagesize($file_tmp_name);
                $newwidth=460;//set file width to 460
                $newheight=($height/$width)*460;//the height are set according to ratio
                $tmp=imagecreatetruecolor($newwidth,$newheight);
                imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);//resample the image

                switch (strtolower($ext))
               {
                case 'jpeg':
                case 'pjpeg':
                case 'jpg':
                  $statusupload = imagejpeg($tmp,$filepath,100);//upload the image
                  break;

                case 'png':
                  $statusupload =  imagepng($tmp,$filepath,100);//upload the image
                  break;

                 case 'gif':
                  $statusupload = imagegif($tmp,$filepath,100);//upload the image
                  break;

               }
        }

    function updateFile()  {
        global $mainframe;
        jimport('joomla.filesystem.file');
        require_once('../components/com_injooosm/helpers/gpsClass.php');

        $db =& JFactory::getDBO();
        $user =& JFactory::getUser();

        // get the post data
        $id =& JRequest::getInt('id');
        $catid =& JRequest::getInt('catid');
        $level =& JRequest::getInt('level');
        $title =& JRequest::getVar('title');
        $date =& JRequest::getVar('date');
        $terrain =& JRequest::getVar('terrain');
// ToDo: empty Terrain = bad
        if ($terrain != "")
		$terrain = implode(',', $terrain);
        $desc =& JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW);
//         $uid = $user->get('id');
        $uid =& JRequest::getVar('uid');
        if ( $date == "" )
	        $date = date("Y-m-d");
        $images =& JRequest::getVar('images', null, 'files', 'array');
        $access =& JRequest::getInt('access');


            // images upload part
            $cfg = injooosmHelper::getConfig();
            $types = explode(',',$cfg->type);
            if(count($images) > 0 )  {
                JFolder::create(JPATH_SITE.DS.'images'.DS.'injooosm'.DS.$id,0777);
                $img_dir = JPATH_SITE.DS.'images'.DS.'injooosm'.DS.$id;
                foreach($images['name'] as $key => $value)  {
                    $ext = explode('.',$images['name'][$key]);
                    if(in_array($ext[1], $types)) {
                        $path = $img_dir.DS.strtolower($images['name'][$key]);
                        $this->createImage($images['tmp_name'][$key], $ext[1], $path);
                    }
                }
            }



            $query = "UPDATE #__osm_files SET"
                    . "\n uid='".$uid."',"
                    . "\n catid='".$catid."',"
                    . "\n title='".$title."',"
                    . "\n terrain='".$terrain."',"
                    . "\n date='".$date."',"
                    . "\n description='".$desc."',"
                    . "\n level='".$level."',"
                    . "\n access='".$access."'"
                    . "\n WHERE id='".$id."'"
                    ;

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

            if ($db->getErrorNum()) {
                echo $db->stderr();
                    return false;
                } else {
                    return true;
                }

    }
}
Return current item: injooosm