Current File : /home/pacjaorg/public_html/kmm/administrator/components/com_djclassifieds/lib/djimage.php
<?php
/**
 * @package DJ-Classifieds
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

defined('_JEXEC') or die('Restricted access');

require_once(JPATH_ROOT.'/administrator/components/com_djclassifieds/lib/djtheme.php');

class DJClassifiedsImage
{
	public static function makeThumb($path, $newpath, $nw = 0, $nh = 0, $keep_ratio = false, $enlarge = true, $add_watermark=-1)
	{
		$params = JComponentHelper::getParams('com_djclassifieds');
		if($add_watermark<0){
			$add_watermark = $params->get('watermark', '0');
		}
		
		if($params->get('image_resize', '0')){
			$keep_ratio = true;
		}
		if (!$path || !$newpath)
		return false;
		if (! list ($w, $h, $type, $attr) = getimagesize($path)) {
			return false;
		}

		$OldImage = null;

		switch($type)
		{
			case 1:
				$OldImage = imagecreatefromgif($path);
				break;
			case 2:
				$OldImage = imagecreatefromjpeg($path);
				break;
			case 3:
				$OldImage = imagecreatefrompng($path);
				break;
			default:
				return  false;
				break;
		}
		
		if ($nw == 0 && $nh == 0) {
			$nw = 75;
			$nh = (int)(round(($nw * $h) / $w));
		}
		elseif ($nw == 0) {
			$nw = (int)(round(($nh * $w) / $h));
		}
		elseif ($nh == 0) {
			$nh = (int)(round(($nw * $h) / $w));
		}
		if ($keep_ratio) {
			$x_ratio = $nw / $w;
			$y_ratio = $nh / $h;

			if (($x_ratio * $h) < $nh){
				$nh = ceil($x_ratio * $h);
			}else{
				$nw = ceil($y_ratio * $w);
			}
		}
		
		if ( ($nw > $w || $nh > $h) && !$enlarge) {
			$nw = $w;
			$nh = $h;
		}

		// check if ratios match
		$_ratio=array($w/$h, $nw/$nh);
		if (($_ratio[0] != $_ratio[1]) && $params->get('image_resize', '0') == '0') { // crop image

			// find the right scale to use
			$_scale=min((float)($w/$nw),(float)($h/$nh));

			// coords to crop
			$cropX=(float)($w-($_scale*$nw));
			$cropY=(float)($h-($_scale*$nh));

			// cropped image size
			$cropW=(int)($w-$cropX);
			$cropH=(int)($h-$cropY);

			$crop=ImageCreateTrueColor($cropW,$cropH);
			if ($type == 3) {
				imagecolortransparent($crop, imagecolorallocate($crop, 0, 0, 0));
				imagealphablending($crop, false);
				imagesavealpha($crop, true);
			}
			
			$cropCoeffsX = array('l' => 0, 'm' => 0.5, 'r' => 1);
			$cropCoeffsY = array('t' => 0, 'm' => 0.5, 'b' => 1);
			
			$cropAlignmentX = $params->get('crop_alignment_h', 'm');
			$cropAlignmentY = $params->get('crop_alignment_v', 'm');
			
			if (!array_key_exists($cropAlignmentX, $cropCoeffsX)) {
				$cropAlignmentX = 'm';
			}
			
			if (!array_key_exists($cropAlignmentY, $cropCoeffsY)) {
				$cropAlignmentY = 'm';
			}
			
			ImageCopy(
			$crop,
			$OldImage,
			0,
			0,
			(int)($cropX * $cropCoeffsX[$cropAlignmentX]),
			(int)($cropY * $cropCoeffsY[$cropAlignmentY]),
			$cropW,
			$cropH
			);
		}

		// do the thumbnail
		$NewThumb=ImageCreateTrueColor($nw,$nh);
		if ($type == 3) {
			$bg = imagecolortransparent($NewThumb, imagecolorallocatealpha($NewThumb, 0, 0, 0,127));
			imagealphablending($NewThumb, false);
			imagefill($NewThumb, 0, 0, $bg);
			imagesavealpha($NewThumb, true);
		}
		if (isset($crop)) { // been cropped
			ImageCopyResampled(
			$NewThumb,
			$crop,
			0,
			0,
			0,
			0,
			$nw,
			$nh,
			$cropW,
			$cropH
			);
			ImageDestroy($crop);
		} else { // ratio match, regular resize
			ImageCopyResampled(
			$NewThumb,
			$OldImage,
			0,
			0,
			0,
			0,
			$nw,
			$nh,
			$w,
			$h
			);
		}
		
		$watermark_path = JPATH_ROOT.'/'.($params->get('watermark_image','') ? self::decodeMediaPath($params->get('watermark_image')) : DJClassifiedsTheme::getImgAssetPath('djcf_watermark.png'));
		
		if($add_watermark>0 && JFile::exists($watermark_path)){		
			if (list ($w_w, $w_h, $w_type, $w_attr) = getimagesize($watermark_path)) {	
				$w_size = $params->get('watermark_size', '20');
			
				$nw_w = round($nw*$w_size/100);
				$nw_ratio = $nw_w/$w_w;
				$nw_h= round($w_h*$nw_ratio);
		
				if($nw_w>$w_w || $nw_h>$w_h ){
					$nw_w=$w_w;		
					$nw_h=$w_h;		
				}				
				
				imagealphablending($NewThumb, true);
				imagesavealpha($NewThumb, true);
		
				$OldWatermark = imagecreatefrompng($watermark_path);	
				//imagealphablending($OldWatermark, true);
				//imagesavealpha($OldWatermark, true);				
				
				$NewWatermark=ImageCreateTrueColor($nw_w,$nw_h);		
				$bg = imagecolortransparent($NewWatermark, imagecolorallocatealpha($NewWatermark, 0, 0, 0,127));		
				imagealphablending($NewWatermark, true);		
				imagefill($NewWatermark, 0, 0, $bg);
				imagesavealpha($NewWatermark, true);
	
				ImageCopyResampled($NewWatermark,$OldWatermark,0,0,0,0,$nw_w,$nw_h,$w_w,$w_h);
				
				$im = $NewThumb;				
		
				// Set the margins for the stamp and get the height/width of the stamp image		
				$margin_v = 10;		
				$margin_h = 10;		
				$sx = imagesx($NewWatermark);		
				$sy = imagesy($NewWatermark);		
				
				if($params->get('watermark_alignment_h', 'l')=='r'){		
					$pos_l = $nw - $nw_w - $margin_v;		
				}else if($params->get('watermark_alignment_h', 'l')=='m'){		
					$pos_l = round($nw/2) - round($nw_w/2);		
				}else{//left		
					$pos_l = $margin_v;		
				}		
				
				if($params->get('watermark_alignment_v', 'b')=='t'){		
					$pos_t = $margin_h;		
				}else if($params->get('watermark_alignment_v', 'b')=='m'){		
					$pos_t = round($nh/2) - round($nw_h/2);		
				}else{//bottom		
					$pos_t = $nh - $nw_h - $margin_h;		
				}				
		
				//$pos_l = $nw - $nw_w - $marge_right;		
				//$pos_t = $nh - $nw_h - $marge_bottom;		
				
				ImageCopy($NewThumb, $NewWatermark, $pos_l , $pos_t , 0, 0, $nw_w, $nw_h);		
				
				//header('Content-Type: image/png');imagepng($NewThumb);die();
						
				ImageDestroy($OldWatermark);		
				ImageDestroy($NewWatermark);		
			}		
		}				

		$thumb_path = $newpath;
		if (is_file($thumb_path))
		unlink($thumb_path);
		switch($type)
		{
			case 1:
				imagegif($NewThumb, $thumb_path);
				break;
			case 2:
				imagejpeg($NewThumb, $thumb_path, $params->get('image_quality', '100'));
				break;
			case 3:
				imagepng($NewThumb, $thumb_path);
				break;
		}
		//imagejpeg($NewThumb, $thumb_path, 85);

		ImageDestroy($NewThumb);
		ImageDestroy($OldImage);

		return true;
	}	
	
	static function _getImagesRaw($item_ids, $type = 'item')
	{
		$app = JFactory::getApplication();
		$db	= JFactory::getDBO();

		$plugins_img = $app->triggerEvent('onDJClassifiedsGetAdsImages', array($item_ids, $type));
		foreach($plugins_img as $plugin_img){
			return $plugin_img;
		}

		$query = "SELECT img.* "
				."FROM #__djcf_images img "
				."WHERE img.item_id IN (".$item_ids.") AND img.type='".$type."' "
				."ORDER BY img.item_id, img.ordering";
		$db->setQuery($query);
		$items_img = $db->loadObjectList();

		return $items_img; 
	}

	public static function getAdsImages($item_ids, $indexed = false)
	{
		$items_img = self::_getImagesRaw($item_ids, 'item');
		$img_indexed = array();

		foreach($items_img as $img){
			$img->thumb_s = $img->path.$img->name.'_ths.'.$img->ext;
			$img->thumb_m = $img->path.$img->name.'_thm.'.$img->ext;
			$img->thumb_b = $img->path.$img->name.'_thb.'.$img->ext;
			self::getImgThumbs($img);

			if(!isset($img_indexed[$img->item_id])){
				$img_indexed[$img->item_id] = array();
			}
			$img_indexed[$img->item_id][] = $img;
		}

		return $indexed ? $img_indexed : $items_img;
	}

	public static function getAdsImagesIndexed($item_ids) // backward compatibility
	{
		return self::getAdsImages($item_ids, true);
	}

	public static function getProfilesImages($item_ids, $indexed = false)
	{
		$items_img = self::_getImagesRaw($item_ids, 'profile');
		$img_indexed = array();

		foreach($items_img as $img){
			$img->thumb = $img->path.$img->name.'_th.'.$img->ext;
			$img->thumb_s = $img->path.$img->name.'_ths.'.$img->ext;

			if(!isset($img_indexed[$img->item_id])){
				$img_indexed[$img->item_id] = array();
			}
			$img_indexed[$img->item_id][] = $img;
		}

		return $indexed ? $img_indexed : $items_img;
	}
	
	private static $_categories_images = null;

	public static function getCatImage($cat_id)
	{
		if(!self::$_categories_images){
			$db	= JFactory::getDBO();
			$query = "SELECT img.* FROM #__djcf_images img "
					."WHERE img.type='category' "
					."ORDER BY img.item_id, img.ordering";
			$db->setQuery($query);
			self::$_categories_images = $db->loadObjectList('item_id');
		}
		
		$img_src = '';
		if(isset(self::$_categories_images[$cat_id])){
			$cat = self::$_categories_images[$cat_id];
			$thumb_path = $cat->path.$cat->name.'_ths.'.$cat->ext;
			$thumb_path = file_exists(JPATH_ROOT.$thumb_path) ? $thumb_path : $cat->path.$cat->name.'.'.$cat->ext;
			$img_src = JUri::root(true).$thumb_path;
		}else{
			$img_src = JUri::root().DJClassifiedsTheme::getImgAssetPath('no-image.svg');
		}
		
		return $img_src;
	}

	public static function getCatImages($cat_ids = null)
	{
		$db = JFactory::getDBO();
		$query = "SELECT * FROM #__djcf_images WHERE type='category'";
		if($cat_ids){
			$query .= " AND item_id IN (".$cat_ids.")";
		}
		$db->setQuery($query);
		$cats_img = $db->loadObjectList('item_id');

		foreach($cats_img as $key => $cat_img){
			$thumb_path = $cat_img->path.$cat_img->name.'_ths.'.$cat_img->ext;
			$cats_img[$key]->image_path = file_exists(JPATH_ROOT.$thumb_path) ? $thumb_path : $cat_img->path.$cat_img->name.'.'.$cat_img->ext;
		}

		return $cats_img;
	}
	
	public static function resmushitThumbnails($filepath) // Losslessly compressing with resmush.it
	{
		if (function_exists('curl_file_create')) { // php 5.6+
			$file = curl_file_create($filepath, '', '');
		} else { //
			$file = '@' . realpath($filepath);
		}
		$post = array('files'=> $file);
	
		$url = 'http://api.resmush.it/ws.php';
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		$data = curl_exec($ch);
		curl_close($ch);
		$json = json_decode($data);
	
		// download and write file only if image size is smaller
		if(!empty($json->src_size) && $json->src_size > $json->dest_size) {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $json->dest);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			$image = curl_exec($ch);
			curl_close($ch);
	
			JFile::write($filepath, $image);
	
			echo round(100 * ($json->src_size - $json->dest_size) / $json->src_size) .'% reduction of <code>'.$filepath.'</code><br/>';
		}

		return true;
	}
	
	public static function generatePath($path, $id)
	{
		$folder_name = ($id - ($id%1000))/1000; 
		$path .= $folder_name.'/';
		if(!JFolder::exists(JPATH_SITE.$path)){
			JFolder::create(JPATH_SITE.$path);
		}	
		return $path;
	}

	static $_th_types = array(
		'table' => 1,
		'smart_table' => 2,
		'blog' => 3,
		'item_thumb' => 3,
		'item_main'=> 5,
		'item_popup'=> 6,
		'user_items' => 7,
		'tooltip' => 8,
		'feed' => 9,
		'og' => 10,
		'amp_items' => 11,
		'amp_item' => 12,
		'orders' => 13,
		'sales' => 14,
		'offers_rec' => 15,
		'offers_sub' => 16,
		'email' => 17,
		'bids' => 18
	);

	static function getThumbType($itemtype)
	{
		$par = JComponentHelper::getParams( 'com_djclassifieds' );

		$mediumth_use_in = $par->get('mediumth_use_in', array(3,9));
		$bigth_use_in = $par->get('bigth_use_in', array(5,6,10,11,12));

		$thumb_id = self::$_th_types[$itemtype];

		if(in_array($thumb_id, $bigth_use_in)){
			return 'thb';
		}elseif(in_array($thumb_id, $mediumth_use_in)){
			return 'thm';
		}else{
			return 'ths';
		}
	}
	
	public static function getImgThumbs($img)
	{
		foreach(self::$_th_types as $itemtype => $id){
			$img->{'thumb_'.$itemtype} = $img->path.$img->name.'_'.self::getThumbType($itemtype).'.'.$img->ext;
		}	
	}

	public static function rotate($filename, $rotate_times)
	{
		if (! list ($w, $h, $type, $attr) = getimagesize($filename)) {
			return false;
		}

		switch($type)
		{
			case 1:
				$source = imagecreatefromgif($filename);
				break;
			case 2:
				$source = imagecreatefromjpeg($filename);
				break;
			case 3:
				$source = imagecreatefrompng($filename);
				break;
			default:
				return  false;
				break;
		}

		$degrees = -90 * $rotate_times;

		$rotate = imagerotate($source, $degrees, 0);
		imagealphablending($rotate, false);
		imagesavealpha($rotate, true);

		switch($type)
		{
			case 1:
				imagegif($rotate, $filename);
				break;
			case 2:
				imagejpeg($rotate, $filename, '100');
				break;
			case 3:
				imagepng($rotate, $filename);
				break;
		}

		imagedestroy($source);
		imagedestroy($rotate);
	}

	static function rename($img, $new_name)
	{
		$db = JFactory::getDBO();

		if(rename(JPATH_ROOT.$img->path.$img->name.'.'.$img->ext, JPATH_ROOT.$img->path.$new_name.'.'.$img->ext)){
			$query = "UPDATE #__djcf_images SET name=".$db->quote($new_name)." WHERE id=".$img->id;
			$db->setQuery($query);
			$db->execute();

			$img->name = $new_name;
		}

		return $img;
	}

	static function saveItemImages($item, $is_new, $par = null)
	{
		$app = JFactory::getApplication();
		$par = $par ? $par : JComponentHelper::getParams('com_djclassifieds');
		$lang = JFactory::getLanguage();
		$db = JFactory::getDBO();

		if($app->input->get('task') == 'save2copy' && $app->input->getInt('id')){
    		$query = "SELECT * FROM #__djcf_images WHERE item_id=".$app->input->getInt('id')." AND type='item'";
    		$db->setQuery($query);
    		$base_item_images = $db->loadObjectList('id');
    		if($base_item_images){
    			$query_img = "INSERT INTO #__djcf_images(`item_id`,`type`,`name`,`ext`,`path`,`caption`,`ordering`,`optimized`) VALUES ";    			    		
    			$new_img_path_rel = DJClassifiedsImage::generatePath($par->get('advert_img_path','/components/com_djclassifieds/images/item/'), $item->id);    			
    			foreach($base_item_images as $item_img){
    				$path_from_copy = JPATH_ROOT.$item_img->path.$item_img->name;
    				$new_img_name = str_ireplace($item_img->item_id.'_', $item->id.'_', $item_img->name);
    				$path_to_copy = JPATH_SITE.$new_img_path_rel.$new_img_name;
    				if (JFile::exists($path_from_copy.'.'.$item_img->ext)){
    					JFile::copy($path_from_copy.'.'.$item_img->ext,$path_to_copy.'.'.$item_img->ext);
    				}
    				if (JFile::exists($path_from_copy.'_ths.'.$item_img->ext)){
    					JFile::copy($path_from_copy.'_ths.'.$item_img->ext,$path_to_copy.'_ths.'.$item_img->ext);
    				}
    				if (JFile::exists($path_from_copy.'_thm.'.$item_img->ext)){
    					JFile::copy($path_from_copy.'_thm.'.$item_img->ext,$path_to_copy.'_thm.'.$item_img->ext);
    				}
    				if (JFile::exists($path_from_copy.'_thb.'.$item_img->ext)){
    					JFile::copy($path_from_copy.'_thb.'.$item_img->ext,$path_to_copy.'_thb.'.$item_img->ext);
    				}
    				$query_img .= "('".$item->id."','item','".$new_img_name."','".$item_img->ext."','".$new_img_path_rel."','".$db->escape($item_img->caption)."','".$item_img->ordering."',0), ";
    			}
    			$query_img = substr($query_img, 0, -2).';';
    			$db->setQuery($query_img);
    			$db->execute();
    		}
    	}

    	$item_images = array();
    	$images_c = 0;
		if(!$is_new || $app->input->get('task') == 'save2copy'){
			$item_id = $item->id;
    		if($app->input->get('task') == 'save2copy'){
    			$item_id = $app->input->getInt('id');
    		}
    		$query = "SELECT * FROM #__djcf_images WHERE item_id=".$item_id." AND type='item'";
    		$db->setQuery($query);
    		$item_images = $db->loadObjectList('id');
			$images_c = count($item_images);
    	}
    	
    	$img_ids = $app->input->getVar('img_id',array());
    	$img_captions = $app->input->getVar('img_caption',array());
    	$img_images = $app->input->getVar('img_image',array());
    	$img_rotate = $app->input->getVar('img_rotate',array());
    	 
    	$img_id_to_del = '';
    	
    	if($item_images){
	    	foreach($item_images as $item_img){
	    		$img_to_del = 1;
	    		foreach($img_ids as $img_id){
	    			if($item_img->id==$img_id){
	    				$img_to_del = 0;    				
	    				break;
	    			}
	    		}
	    		if($img_to_del){
	    			$images_c--;
	    			$path_to_delete = JPATH_ROOT.$item_img->path.$item_img->name;
	    			if (JFile::exists($path_to_delete.'.'.$item_img->ext)){
	    				JFile::delete($path_to_delete.'.'.$item_img->ext);
	    			}
	    			if (JFile::exists($path_to_delete.'_ths.'.$item_img->ext)){
	    				JFile::delete($path_to_delete.'_ths.'.$item_img->ext);
	    			}
	    			if (JFile::exists($path_to_delete.'_thm.'.$item_img->ext)){
	    				JFile::delete($path_to_delete.'_thm.'.$item_img->ext);
	    			}
	    			if (JFile::exists($path_to_delete.'_thb.'.$item_img->ext)){
	    				JFile::delete($path_to_delete.'_thb.'.$item_img->ext);
	    			}
	    			$img_id_to_del .= $item_img->id.',';
	    		}
	    	}
	    	if($img_id_to_del){
	    		$query = "DELETE FROM #__djcf_images WHERE item_id=".$item->id." AND type='item' AND ID IN (".substr($img_id_to_del, 0, -1).") ";
	    		$db->setQuery($query);
	    		$db->execute();
	    	}
    	}

    	$last_id = $item->id;

    	$imglimit = $par->get('img_limit','3');
    	$nws = (int)$par->get('smallth_width','56');
    	$nhs = (int)$par->get('smallth_height','32');
    	$nwm = (int)$par->get('middleth_width','150');
    	$nhm = (int)$par->get('middleth_height','110');
    	$nwb = (int)$par->get('bigth_width','600');
    	$nhb = (int)$par->get('bigth_height','0');
    	 
    	$img_ord = 1;
    	$img_to_insert = 0;
    	$query_img = "INSERT INTO #__djcf_images(`item_id`,`type`,`name`,`ext`,`path`,`caption`,`ordering`) VALUES ";
    	$new_img_path_rel = DJClassifiedsImage::generatePath($par->get('advert_img_path','/components/com_djclassifieds/images/item/'),$last_id) ;
    	$new_img_path = JPATH_SITE.$new_img_path_rel;
    	
    	for($im = 0;$im<count($img_ids);$im++){
    		if($img_ids[$im]){
    			if($img_rotate[$im]%4>0){
    				$img_rot = $item_images[$img_ids[$im]];

    				if($par->get('leave_small_th','0')==0){
	    				if (JFile::exists($new_img_path.$img_rot->name.'_ths.'.$img_rot->ext)){
	    					JFile::delete($new_img_path.$img_rot->name.'_ths.'.$img_rot->ext);
	    						
	    				}
    				}
    				if (JFile::exists($new_img_path.$img_rot->name.'_thm.'.$img_rot->ext)){
    					JFile::delete($new_img_path.$img_rot->name.'_thm.'.$img_rot->ext);
    				}
    				if (JFile::exists($new_img_path.$img_rot->name.'_thb.'.$img_rot->ext)){
    					JFile::delete($new_img_path.$img_rot->name.'_thb.'.$img_rot->ext);
    				}
						
					DJClassifiedsImage::rotate($new_img_path.$img_rot->name.'.'.$img_rot->ext, $img_rotate[$im]);
					$img_rot = DJClassifiedsImage::rename($img_rot, preg_replace('/_r(?:.(?!_r))+$/', '', $img_rot->name).'_r'.rand());

    				DJClassifiedsImage::makeThumb($new_img_path.$img_rot->name.'.'.$img_rot->ext,$new_img_path.$img_rot->name.'_ths.'.$img_rot->ext, $nws, $nhs);
    				DJClassifiedsImage::makeThumb($new_img_path.$img_rot->name.'.'.$img_rot->ext,$new_img_path.$img_rot->name.'_thm.'.$img_rot->ext, $nwm, $nhm);
    				DJClassifiedsImage::makeThumb($new_img_path.$img_rot->name.'.'.$img_rot->ext,$new_img_path.$img_rot->name.'_thb.'.$img_rot->ext, $nwb, $nhb);
    			}
    			    			
    			if($item_images[$img_ids[$im]]->ordering!=$img_ord || $item_images[$img_ids[$im]]->caption!=$img_captions[$im]){
    				$query = "UPDATE #__djcf_images SET ordering='".$img_ord."', caption='".$db->escape($img_captions[$im])."' WHERE item_id=".$item->id." AND type='item' AND id=".$img_ids[$im]." ";
    				$db->setQuery($query);
    				$db->execute();
    			}
    		}else{
    			if($app->isClient('site') && $images_c >= $imglimit){
    				break;
    			}
    			$new_img_name = explode(';',$img_images[$im]);
    			if(is_array($new_img_name)){
    				$new_img_name_u = JPATH_ROOT.DJClassifiedsTheme::getImgUploadPath().'/'.$new_img_name[0];
    				if (JFile::exists($new_img_name_u)){
    					if(getimagesize($new_img_name_u)){
    						$new_img_n = $last_id.'_'.str_ireplace(' ', '_',$new_img_name[1]);
    						$new_img_n = $lang->transliterate($new_img_n);
    						$new_img_n = strtolower($new_img_n);
    						$new_img_n = JFile::makeSafe($new_img_n);
    							    						
							$nimg= 0;
							$name_parts = pathinfo($new_img_n);
							$img_name = $name_parts['filename'];
							$img_ext = $name_parts['extension'];
							$new_path_check = $new_img_path.$new_img_n;
							$new_path_check = str_ireplace('.'.$img_ext, '_thm.'.$img_ext, $new_path_check);
    						
    						while(JFile::exists($new_path_check)){
    							$nimg++;
    							$new_img_n = $last_id.'_'.$nimg.'_'.str_ireplace(' ', '_',$new_img_name[1]);
    							$new_img_n = $lang->transliterate($new_img_n);
    							$new_img_n = strtolower($new_img_n);
    							$new_img_n = JFile::makeSafe($new_img_n);
    							$new_path_check = $new_img_path.$new_img_n;
    						
    							$new_path_check = str_ireplace('.'.$img_ext, '_thm.'.$img_ext, $new_path_check);
    						}
    						    							
    						rename($new_img_name_u, $new_img_path.$new_img_n);
    						$name_parts = pathinfo($new_img_n);
    						$img_name = $name_parts['filename'];
    						$img_ext = $name_parts['extension'];
    						
    						DJClassifiedsImage::makeThumb($new_img_path.$new_img_n,$new_img_path.$img_name.'_ths.'.$img_ext, $nws, $nhs);
    						DJClassifiedsImage::makeThumb($new_img_path.$new_img_n,$new_img_path.$img_name.'_thm.'.$img_ext, $nwm, $nhm);
    						DJClassifiedsImage::makeThumb($new_img_path.$new_img_n,$new_img_path.$img_name.'_thb.'.$img_ext, $nwb, $nhb);
    						$query_img .= "('".$item->id."','item','".$img_name."','".$img_ext."','".$new_img_path_rel."','".$db->escape($img_captions[$im])."','".$img_ord."'), ";
    						$img_to_insert++;
    						if($par->get('store_org_img','1')==0){
    							JFile::delete($new_img_path.$new_img_n);
    						}
    					}
    				}
    			}
    			$images_c++;
    		}
    		$img_ord++;    		 	
    	}
    	
    	if($img_to_insert){
    		$query_img = substr($query_img, 0, -2).';';
    		$db->setQuery($query_img);
    		$db->execute();
    	}    	

		return $images_c;
	}

	static function saveImage($type, $item_id, $store_path, $new_icon, $del_icon = false, $thumbs = array(), $img_maxsize = 0, $watermark = 0)
	{
		$app = JFactory::getApplication();
		$db = JFactory::getDBO();
		$lang = JFactory::getLanguage();

		$img_maxsize = $img_maxsize ? $img_maxsize * 1024 * 1024 : $img_maxsize;

		if($img_maxsize && $new_icon['size'] > $img_maxsize){
			$app->enqueueMessage(JText::_('COM_DJCLASSIFIEDS_TO_BIG_IMAGE').': "'.$new_icon['name'].'"', 'error');
			return false;
		}else{
			if($new_icon['size'] || $del_icon){
				$query = "SELECT * FROM #__djcf_images WHERE type='".$type."' AND item_id=".$item_id." ORDER BY ordering LIMIT 1";
				$db->setQuery($query);
				$old_icon = $db->loadObject();

				if($old_icon){
					if(JFile::exists(JPATH_SITE.$old_icon->path.$old_icon->name.'.'.$old_icon->ext)){
						JFile::delete(JPATH_SITE.$old_icon->path.$old_icon->name.'.'.$old_icon->ext);
					}

					foreach($thumbs as $thumb_name => $thumb){
						if(JFile::exists(JPATH_SITE.$old_icon->path.$old_icon->name.'_'.$thumb_name.'.'.$old_icon->ext)){
							JFile::delete(JPATH_SITE.$old_icon->path.$old_icon->name.'_'.$thumb_name.'.'.$old_icon->ext);
						}
					}
							
					$query = "DELETE FROM #__djcf_images WHERE type='".$type."' AND item_id=".$item_id." AND id=".$old_icon->id;
					$db->setQuery($query);
					$db->execute();
				}
			}

			if(substr($new_icon['type'], 0, 5) == 'image'){
				$icon_name = str_ireplace(' ', '_',$new_icon['name']);
				$icon_name = $lang->transliterate($icon_name);
				$icon_name = strtolower($icon_name);
				$icon_name = JFile::makeSafe($icon_name);
				$icon_name = $item_id.'_'.$icon_name;

				$path_rel = DJClassifiedsImage::generatePath($store_path, $item_id);
				$path = JPATH_SITE.$path_rel.$icon_name;
				
				move_uploaded_file($new_icon['tmp_name'], $path);
			
				$name_parts = pathinfo($path);
				$img_name = $name_parts['filename'];
				$img_ext = $name_parts['extension'];
				$new_path = JPATH_SITE.$path_rel;

				foreach($thumbs as $thumb_name => $thumb){
					DJClassifiedsImage::makeThumb($path, $new_path.$img_name.'_'.$thumb_name.'.'.$img_ext, $thumb['w'], $thumb['h'], false, true, $watermark);
				}
					
				$query = "INSERT INTO #__djcf_images(`item_id`,`type`,`name`,`ext`,`path`,`caption`,`ordering`) VALUES ";
				$query .= "(".$item_id.",'".$type."','".$img_name."','".$img_ext."','".$path_rel."','','1'); ";
				$db->setQuery($query);
				$db->execute();
			}

			return true;
		}
	}

	static function includeDJImageAssets() // backward compatibility
	{
		DJClassifiedsTheme::includeDJImageAssets();
	}

	static function getThumbStyle($th, $par)
	{
		if($th == 'ths'){
			$w = $par->get('smallth_width',56);
			$h = $par->get('smallth_height',32);
		}elseif($th == 'thm'){
			$w = $par->get('middleth_width',150);
			$h = $par->get('middleth_height',110);
		}elseif($th == 'thb'){
			$w = $par->get('bigth_width',600);
			$h = $par->get('bigth_height',0);
		}elseif($th == 'p_th'){
			$w = $par->get('profth_width',120);
			$h = $par->get('profth_height',120);
		}elseif($th == 'p_ths'){
			$w = $par->get('prof_smallth_width',50);
			$h = $par->get('prof_smallth_height',50);
		}elseif($th == 'c_th'){
			$w = $par->get('catth_width',68);
			$h = $par->get('catth_height',50);
		}

		return ($w ? 'width:'.$w.'px;' : '').($h ? 'max-height:'.$h.'px;' : '');
	}

	static function decodeMediaPath($path)
	{
		return urldecode(JUri::getInstance($path)->getPath());
	}

	static function getVideoLinks($video_value, $par)
	{
		$video_links = array();
		foreach(preg_split('/\r\n|[\r\n]/', $video_value) as $key => $item_video){
			if($key && $par->get('video_allow_multiple','0')=='0'){
				break;
			}

			$video_host = '';
			$video = '';
			$video_parts = explode('/',$item_video);
			if(isset($video_parts[2])){
				if($video_parts[2]=='www.youtube.com' || $video_parts[2]=='youtube.com'){
					$video_host = $par->get('youtube_nocookie','0') ? '//www.youtube-nocookie.com/embed/' : '//www.youtube.com/embed/';
					if($video_parts[3]=='embed' && isset($video_parts[4])){
						$video = $video_parts[4];
					}else{
						$video = array_pop($video_parts);
						preg_match('/v=([\w\d\-]+)/', $video, $video_matches);
						$video = ($video_matches ? $video_matches[1] : $video).'?rel=0';
					}
				}else if($video_parts[2]=='youtu.be' && isset($video_parts[3])){
					$video_host = $par->get('youtube_nocookie','0') ? '//www.youtube-nocookie.com/embed/' : '//www.youtube.com/embed/';
					$video = $video_parts[3];
				}else if($video_parts[2]=='vimeo.com'){	
					$video_host = '//player.vimeo.com/video/';
					$video = array_pop($video_parts).'?portrait=0&color=333';
				}
			}

			if(!$video){
				$video_parts = explode('|', $item_video);
				if(file_exists($_SERVER['DOCUMENT_ROOT'].$video_parts[0])){
					$secs = 0;
					if(!empty($video_parts[1])){
						$time_parts = explode(':', $video_parts[1]);
						if(count($time_parts) > 1){
							foreach(array_reverse($time_parts) as $key => $time){
								$secs += ($key ? ($key * 60) : 1) * $time;
							}
						}
					}
					$video = $video_parts[0].($secs ? '#t='.$secs : '');
				}
			}

			if($video){
				$video_links[] = $video_host.$video;
			}
		}

		return $video_links;
	}
}
Site is undergoing maintenance

PACJA Events

Maintenance mode is on

Site will be available soon. Thank you for your patience!