Location: PHPKode > projects > injooosm > components/com_injooosm/models/files.php
<?php
/**
 * Joomla! 1.5 component injooosm
 *
 * @version $Id: files.php 2010-02-16 12:28:00$
 * @author Christian Knorr
 * @package injooosm
 * @subpackage frontend
 * @license GNU/GPL
 * @filesource
 *
 */
 
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

class injooosmModelFiles extends JModel  {
	/**
	 * files data array
	 *
	 * @var array
	 */
	var $_data = null;

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

	
	/**
	 * Constructor
	 */
	function __construct() {
		
		parent::__construct();
	}

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

		return $this->_data;
	}


	/**
	 *
	 * @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 _buildQuery()  {
		global $mainframe;
		$user		=& JFactory::getUser();
		$orderby	= $this->_buildContentOrderBy();
		$where		= $this->_buildContentWhere();
		$userwhere	= "";

		if(JRequest::getVar('layout') == 'user' && !$where)  {
			$userwhere = " WHERE uid='".$user->get('id')."'";
		} else if(JRequest::getVar('layout') == 'user' && $where)  {
			$userwhere = " AND uid='".$user->get('id')."'";
		}

		$db =& JFactory::getDBO();

		$query = "SELECT a.*, b.title AS cat, b.image AS image, c.username AS user"
				. "\n FROM #__osm_files AS a"
				. "\n LEFT JOIN #__osm_cats AS b ON a.catid=b.id"
				. "\n LEFT JOIN #__users AS c ON a.uid=c.id"
				. $where
				. $userwhere
				. $orderby
				;

		return $query;
	}

	/**
	 *
	 * @global array $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 array $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(c.username) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
		}
		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' OR ', $where ) : '' );

		return $where;
	}

	/**
	 *
	 * @global <type> $mainframe
	 * @return <type> 
	 */
	function getCats()  {
		global $mainframe;

		$db =& JFactory::getDBO();

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

		$db->setQuery($query);
		$rows = $db->loadObjectList();
		$limit = count($rows);
		$children = array();
		foreach ($rows as $v ) {
			$pt 	= $v->parent;
			$list 	= @$children[$pt] ? $children[$pt] : array();
			array_push( $list, $v );
			$children[$pt] = $list;
		}
		$list = JHTML::_('menu.treerecurse', 0, '', array(), $children );
		$list = array_slice($list,0,$limit);
		$cats = array();
		foreach($list as $cat) {
			if($cat->treename == NULL) {
				$title = $cat->title;
			} else {
				$title = "&bull; ".$cat->title;
			}
			array_push($cats,array('id' => $cat->id, 'title' => $title));
		}
		return $cats;
	}

	/**
	 *
	 * @global object $mainframe
	 * @return boolean
	 */
	function saveFile()  {
		global $mainframe;

		jimport('joomla.filesystem.file');

		$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 != NULL)
			$terrain = implode(',', $terrain);
		else
			$terrain = "";
		$desc =& JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW);
		$file =& JRequest::getVar('file', null, 'files', 'array');
		$uid = $user->get('id');
		$date = date("Y-m-d");
		$images =& JRequest::getVar('images', null, 'files', 'array');
		$access =& JRequest::getInt('access', 0);


		// 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), 0777);
		}

		// get the start coordinates
		$gps = new gpsClass();
		$gps->gpsFile = "./components/com_injooosm/uploads/".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 = './components/com_injooosm/uploads/'.strtolower($filename);
		$start_n = $start[1];
		$start_e = $start[0];
		$coords = $gps->getCoords($file);
		$distance = $gps->getDistance($coords);
// 	  Na und was ist mit Wegpunkten?
//		 if($distance == NULL)  {
//			 echo "<script type='text/javascript'>alert('".$distance."');window.history.back(-1);</script>";
//			 exit;
//		 }

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

		$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."'"
				;

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

		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		} else {
			$query = "SELECT id FROM #__osm_files WHERE file='".strtolower($filename)."'";

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

			// images upload part
			$cfg = injooosmHelper::getConfig();
			$types = explode(',',$cfg->type);
			if(count($images) > 0 )  {
				$img_dir = JPATH_SITE.DS.'images'.DS.'injooosm'.DS.$rows->id;
				JFolder::create($img_dir,0777);
				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]);
						(createImage($images['tmp_name'][$key], $ext[1], $path));
					}
				}
			}

		return true;
		}
	}

	/**
	 *
	 * @global <type> $mainframe
	 * @return <type> 
	 */
	function hit()
	{
		global $mainframe;

		$id =& JRequest::getInt('id');

		if ($id)
		{
			$tracks = & $this->getTable('osm_files');
			$tracks->hit($id);
			return true;
		}
		return false;
	}

	/**
	 *
	 * @global <type> $mainframe
	 * @param <type> $id
	 * @return <type>
	 */
	function getFile($id)  {
		global $mainframe;

		$db =& JFactory::getDBO();

		$query = "SELECT a.*, b.title AS cat, b.image AS image, c.username AS user"
				. "\n FROM #__osm_files AS a"
				. "\n LEFT JOIN #__osm_cats AS b ON a.catid=b.id"
				. "\n LEFT JOIN #__users AS c ON a.uid=c.id"
				. "\n WHERE a.id='" .$id. "'";

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

		return $track;
	}

	/**
	 *
	 * @global <type> $mainframe
	 * @param <type> $id
	 * @param <type> $rate
	 * @return <type> 
	 */
	function vote($id, $rate)  {
		global $mainframe;

		$db =& JFactory::getDBO();

		$query = "INSERT INTO #__osm_votes SET"
				. "\n trackid='" .$id."',"
				. "\n rating='" .$rate."'"
				;

		if($id && $rate):
			$db->setQuery($query);
			$db->query();
			return true;
		endif;

		return false;
	}

	/**
	 *
	 * @global <type> $mainframe
	 * @param <type> $id
	 * @return <type> 
	 */
	function getVotes($id)  {
		global $mainframe;

		$class = array('nostar', 'onestar', 'twostar', 'threestar', 'fourstar', 'fivestar',
		'sixstar', 'sevenstar', 'eightstar', 'ninestar', 'tenstar');
		
		$db =& JFactory::getDBO();
		// count votings
		$query = "SELECT COUNT(*) FROM #__osm_votes"
				. "\n WHERE trackid='" .$id. "'";

		$db->setQuery($query);
		$count = $db->loadResult();
		// sum rating
		$query = "SELECT SUM(rating) FROM #__osm_votes"
				. "\n WHERE trackid='" .$id. "'";

		$db->setQuery($query);
		$rating = $db->loadResult();
		if($count > 0)  {
			$rate = round(($rating/$count), 0);
		} else {
			$rate = 0;
		}



		$object = array("count" => $count,
						"rate"  => $rate,
						"class" => $class[$rate]);

		return $object;
	}

	function deleteFile($id)  {
		global $mainframe;

		$db = JFactory::getDBO();

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

		$db->setQuery($query);
		if($db->query())  {
			return true;
		} else {
			return false;
		}
	}
	function updateFile($id)  {
		global $mainframe;

		jimport('joomla.filesystem.file');

		$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);
		$images =& JRequest::getVar('images', null, 'files', 'array');
		$access =& JRequest::getInt('access', 0);
	if($images["tmp_name"][0] == "") return false;

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


			$query = "UPDATE #__osm_files SET"
					. "\n catid='".$catid."',"
					. "\n title='".$title."',"
					. "\n terrain='".$terrain."',"
					. "\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;
				}
	}

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

		$db = JFactory::getDBO();

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

		$db->setQuery($query);
		$row = $db->loadObjectList();

		return $row;
	}

	/**
	 *
	 * @global object $mainframe
	 * @param int $id
	 * @param string $order
	 * @return array
	 */
	function getComments($id, $order)  {
		global $mainframe;

		$db = JFactory::getDBO();
		$query = "SELECT * FROM #__osm_comments WHERE"
				. "\n tid='".$id."'"
				. "\n AND published='1'"
				. "\n ORDER BY date ".$order
				;
		$db->setQuery($query);
		$result = $db->loadObjectList();

		return $result;
	}

	/**
	 *
	 * @param object $cfg
	 */
	function addcomment($cfg)  {
		JHTML::_('behavior.formvalidation');
		$editor =& JFactory::getEditor('tinymce');
		$editor_params = array('theme' => 'simple');
		$user =& JFactory::getUser();
		$id = JRequest::getInt('id');
		?>
		<script language="javascript">
		function myValidate(f) {
				if (document.formvalidator.isValid(f)) {
						f.check.value='<?php echo JUtility::getToken(); ?>';//send token
						return true;
				}
				else {
						alert('<?php echo JText::_('OSM_FILLOUT'); ?>');
				}
				return false;
		}
		</script>

		<form class='form-validate' id='adminform' name='adminform' action='index.php?option=com_injooosm' method='post' onSubmit='return myValidate(this);'>
					<table class='comment-form'>
					<thead>
						<tr><th colspan='2'><b><?php echo JText::_('OSM_WRITE_COMMENT'); ?></b></th></tr>
					</thead>
					<tbody>
						<tr>
						<td><label for='name'><?php echo JText::_('Name'); ?>*</label></td><td><input type='text' name='name' id='name' size='20' value='<?php echo $user->get('name'); ?>' class='required' maxlength='50' /></td>
						</tr><tr>
						<td><label for='email'><?php echo JText::_('e-mail'); ?>*</label></td><td><input type='text' name='email' id='email' size='30' value='<?php echo $user->get('email'); ?>' class='required validate-email' maxlength='50' /></td>
						</tr><tr>
						<td><label for='title'><?php echo JText::_('OSM_TITLE'); ?>*</label></td><td><input type='text' name='title' id='title' size='40' value='' class='required' maxlength='80' /></td>
						</tr><tr>
						<td><label for='text'><?php echo JText::_('OSM_TEXT'); ?>*</label></td><td><?php echo $editor->display('text', '', '400', '100', '10', '10', false, $editor_params); ?></td>
						</tr>
						<?php if($cfg->captcha == 1): ?>
						<tr><td><img src='index.php?option=com_injooosm&task=displayimg' ></td><td><input type="text" name="word" value="" size="10" class="required" /> <?php echo JText::_('OSM_CAPTCHA_INFO'); ?></td></tr>
						<?php endif; ?>
						<tr><td colspan='2' align='right'><input type='submit' value='senden' name='submit' class='button' /></td></tr>
					</tbody>
					</table>
					<?php echo JHTML::_( 'form.token' ) . "\n"; ?>
					<input type='hidden' name='controller' value='files' />
					<input type='hidden' name='task' value='savecomment' />
					<input type='hidden' name='id' value='<?php echo $id; ?>' />
				</form>
				<?php
	   }

	   /**
		*
		* @global object $mainframe
		* @param int $id
		* @return boolean
		*/
	   function savecomment($id, $cfg)  {
		   global $mainframe;

		   $name =& JRequest::getVar('name');
		   $email =& JRequest::getVar('email');
		   $title =& JRequest::getVar('title');
		   $text =& JRequest::getVar( 'text', '', 'post', 'string', JREQUEST_ALLOWRAW);

		   $db =& JFactory::getDBO();
		   $query = "INSERT INTO #__osm_comments SET"
					. "\n tid='".$id."',"
					. "\n user='".$name."',"
					. "\n email='".$email."',"
					. "\n title='".$title."',"
					. "\n text='".$text."',"
					. "\n published='1'"
					;

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

		   // send autor email if set
		   if($cfg->inform_autor == 1)  {
			   $jcfg = JFactory::getConfig();
			   $user = $this->getAutorData($id);
			   $email = $autor->email;
			   $from = $jcfg->mailfrom;
			   $sender = $jcfg->fromname;
			   $link = JURI::base()."index.php?option=com_injooosm&view=files&layout=file&id=".$id;
			   $msg = JText::_('OSM_CMAIL_MSG');
			   $body = sprintf($msg, $link);
			   $subject = JText::_('OSM_CMAIL_SUBJECT');

			   // clean the email data
			   $subject = JMailHelper::cleanSubject($subject);
			   $body = JMailHelper::cleanBody($body);
			   $sender = JMailHelper::cleanAdress($sender);

			   JUtility::sendMail($from, $sender,$email,$subject,$body);
		   }
	   }

	   function getAutorData($id)  {
		   global $mainframe;

		   $db = JFactory::getDBO();
		   $query = "SELECT a.uid, b.name, b.email FROM #__osm_files AS a"
					. "\n LEFT JOIN #__users AS b ON a.uid=b.id"
					. "\n WHERE a.id='".$id.'"'
					;

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

		   return $user;

	   }

/**
 * Gives back lat/lon from start (if given) and endpoint to make an approachlink
 * Homepage: http://openrouteservice.org/
 * WIKI: http://wiki.openstreetmap.org/wiki/OpenRouteService
 * 
 * @param lat
 * @param lon
 * @return array
 **/
function approach($to_lat,$to_lon)  {
	$user = JFactory::getUser();
	$latlon = injooosmHelper::getLatLon($user->id);
	$link = "http://data.giub.uni-bonn.de/openrouteservice/index.php?";
	if ($latlon[0]->osmlat) $from_lat = $latlon[0]->osmlat;
	if ($latlon[0]->osmlon) $from_lon = $latlon[0]->osmlon;
	if ($from_lon && $from_lat){
		$middle_lon = ((float)$to_lon + (float)$from_lon) / 2;
		$middle_lat = ((float)$to_lat + (float)$from_lat) / 2;
		$link .= "start=".$from_lon.",".$from_lat."&amp;end=".$to_lon.",".$to_lat."&amp;lat=".$middle_lat."&amp;lon=".$middle_lon;
	} else
		$link .= "end=".$to_lon.",".$to_lat;
	return $link;
}

}
Return current item: injooosm