Your IP : 216.73.216.240


Current Path : /home/j/u/v/juvelize/www/modules/mod_simple_unite_gallery/
Upload File :
Current File : /home/j/u/v/juvelize/www/modules/mod_simple_unite_gallery/helper.php

<?php
/**
* Simple Unit Gallery - Joomla Module 
* Version			: 1.2.8 
* Package			: Joomla 3.6.x
* copyright 		: Copyright (C) 2016 ConseilGouz. All rights reserved.
* license    		: http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
* From              : Unit Gallery, https://github.com/vvvmax/unitegallery
* Updated on        : December, 2016
*/
// no direct access
defined('_JEXEC') or die;
$com_path = JPATH_SITE . '/components/com_content/';
require_once $com_path . 'router.php';
require_once $com_path . 'helpers/route.php';

// Joomla doesn't autoload JFile and JFolder
JLoader::register('JFile', JPATH_LIBRARIES . '/joomla/filesystem/file.php');
JLoader::register('JFolder', JPATH_LIBRARIES . '/joomla/filesystem/folder.php');

class modSimpleUniteGalleryHelper
{
private $errorMsg = "";

	public static function getFolder($dir)
	{
		$input = JFactory::getApplication()->input;
		$catid = 0;
		$articleid = 0;
		$artalias = '';
		$catalias = '';
		if ($input->getString('view') == 'category') {
			$catid = $input->getInt('id');
			$catalias = self::getCatAlias($catid)->alias;
		}
		if ($input->getString('view') == 'article') { // on est sur l'affichage d'un article
			$catid = $input->getInt('catid');
			$articleid = $input->getInt('id');
			$res = self::getArticleInfos($articleid);
			$articlealias = $res->alias;
			$catid = $res->catid;
			$catalias = self::getCatAlias($catid)->alias;
		}
		$root = $dir;
		$pattern = array('/\$catid/','/\$catalias/', '/\$articleid/', '/\$articlealias/');
		$replace = array($catid, $catalias, $articleid,$articlealias);
		$root = preg_replace($pattern, $replace, $root);
		if (strpos($root,'$') !== false) { // r�pertoire incorrect: il reste des zones 
			return false;
		}
		if(!JFolder::exists($root) ) { // le r�pertoire n'existe pas : on cr�e
			JFolder::create($root,755);
		}
		return $root; 
	}
	static function getArticleInfos($id) {
		$db = JFactory::getDbo();
		$query = $db->getQuery(true)
			->select('alias,catid')
			->from('#__content')
			->where(' id = ' .$id);
		$db->setQuery($query);
		return $db->loadObject();
	}
	static function getCatAlias($id) {
		$db = JFactory::getDbo();
		$query = $db->getQuery(true)
			->select('alias')
			->from('#__categories')
			->where(' id = ' .$id);
		$db->setQuery($query);
		return $db->loadObject();
	}
	static function getArticle(&$item, $params) {
		// Access filter
		$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
		$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
		// Get an instance of the generic articles model
		$articles = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
		// Set application parameters in model
		$app = JFactory::getApplication();
		$appParams = $app->getParams();
		$articles->setState('params', $appParams);
		$articles->setState('filter.published', 1);
		$articles->setState('filter.article_id', $item->slidearticleid);
		$items2 = $articles->getItems();
		$item->article = $items2[0];
		$item->article->text = JHTML::_('content.prepare', $item->article->introtext);
		$item->article->text = self::truncate($item->article->text, $params->get('ug_text_lgth', '100'), true, false);
		// $item->article->text = JHTML::_('string.truncate',$item->article->introtext,'150');
		// set the item link to the article depending on the user rights
		if ($access || in_array($item->article->access, $authorised)) {
			// We know that user has the privilege to view the article
			$item->slug = $item->article->id . ':' . $item->article->alias;
			$item->catslug = $item->article->catid ? $item->article->catid . ':' . $item->article->category_alias : $item->article->catid;
			$link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
		} else {
			$app = JFactory::getApplication();
			$menu = $app->getMenu();
			$menuitems = $menu->getItems('link', 'index.php?option=com_users&view=login');
			if (isset($menuitems[0])) {
				$Itemid = $menuitems[0]->id;
			} elseif (JRequest::getInt('Itemid') > 0) {
				$Itemid = JRequest::getInt('Itemid');
			}
			$link = JRoute::_('index.php?option=com_users&view=login&Itemid=' . $Itemid);
		}
		return $link;
	}
	/**
	 * Truncates text blocks over the specified character limit and closes
	 */
	public static function truncate($text, $length = 0, $noSplit = true, $allowHtml = true) {
		// Check if HTML tags are allowed.
		if (!$allowHtml) {
			// Deal with spacing issues in the input.
			$text = str_replace('>', '> ', $text);
			$text = str_replace(array('&nbsp;', '&#160;'), ' ', $text);
			$text = JString::trim(preg_replace('#\s+#mui', ' ', $text));
	
			// Strip the tags from the input and decode entities.
			$text = strip_tags($text);
			$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
	
			// Remove remaining extra spaces.
			$text = str_replace('&nbsp;', ' ', $text);
			$text = JString::trim(preg_replace('#\s+#mui', ' ', $text));
		}
	
		// Truncate the item text if it is too long.
		if ($length > 0 && JString::strlen($text) > $length) {
			// Find the first space within the allowed length.
			$tmp = JString::substr($text, 0, $length);
	
			if ($noSplit) {
				$offset = JString::strrpos($tmp, ' ');
				if (JString::strrpos($tmp, '<') > JString::strrpos($tmp, '>')) {
					$offset = JString::strrpos($tmp, '<');
				}
				$tmp = JString::substr($tmp, 0, $offset);
	
				// If we don't have 3 characters of room, go to the second space within the limit.
				if (JString::strlen($tmp) > $length - 3) {
					$tmp = JString::substr($tmp, 0, JString::strrpos($tmp, ' '));
				}
			}
	
		if ($allowHtml) {
			// Put all opened tags into an array
			preg_match_all("#<([a-z][a-z0-9]*)\b.*?(?!/)>#i", $tmp, $result);
			$openedTags = $result[1];
			$openedTags = array_diff($openedTags, array("img", "hr", "br"));
			$openedTags = array_values($openedTags);
			// Put all closed tags into an array
			preg_match_all("#</([a-z]+)>#iU", $tmp, $result);
			$closedTags = $result[1];
			$numOpened = count($openedTags);
			// All tags are closed
			if (count($closedTags) == $numOpened) {
				return $tmp . '...';
			}
			$tmp .= '...';
			$openedTags = array_reverse($openedTags);
			// Close tags
			for ($i = 0; $i < $numOpened; $i++) {
				if (!in_array($openedTags[$i], $closedTags)) {
					$tmp .= "</" . $openedTags[$i] . ">";
				} else {
					unset($closedTags[array_search($openedTags[$i], $closedTags)]);
				}
			}
		}
	
		$text = $tmp;
	}
	
	return $text;
	}
	public static function thumbnailFromDir($dir,$compression) {
		$files = JFolder::files($dir,null,null ,null ,null , array('desc.txt','index.html','.htaccess'));
		$_dir = $dir;
		$nb = 0;
		if (count($files) > 0) {
			foreach ($files as $file) {
				$imgthumb = $file;
				$pos = strrpos($imgthumb,'/');
				$len = strlen($imgthumb);
				$imgthumb = $_dir.'/th/'.substr($imgthumb,$pos,$len);
				if (!JFile::exists($imgthumb)) { // fichier existe d�j� : on sort
					if (self::createThumbNail(JURI::root().$_dir.'/'.$file,$imgthumb,$compression)) {
					   $nb = $nb+1;
					} else {
					    JFactory::getApplication()->enqueueMessage(JText::_($this->errorMsg), 'notice');
					}
				}
	
			}
			if ($nb > 0) {
				JFactory::getApplication()->enqueueMessage($nb.JText::_('SAG_THUMBCREATION') );
			}
	
		}
	}
	static function createThumbNail($fileIn,$fileOut,$compression) {
		list($w, $h, $type) = getimagesize($fileIn);
		$width = $w;
		$height = $h;
		$scale = (($width / $w) > ($height / $h)) ? ($width / $w) : ($height / $h); // greater rate
		$newW = $width/$scale;    // check the size of in file
		$newH = $height/$scale;
		$this->errorMsg ='ok';
		// which side is larger (rounding error)
		if (($w - $newW) > ($h - $newH)) {
			$src = array(floor(($w - $newW)/2), 0, floor($newW), $h);
		} else {
			$src = array(0, floor(($h - $newH)/2), $w, floor($newH));
		}
		$dst = array(0,0, floor($width), floor($height));
		switch($type) {
			case IMAGETYPE_JPEG:
				if (!function_exists('imagecreatefromjpeg')) {
					$this->errorMsg = 'ErrorNoJPGFunction';
					return false;
				}
				try {
					$image1 = imagecreatefromjpeg($fileIn);
				} catch(\Exception $exception) {
					$this->errorMsg = 'ErrorJPGFunction';
					return false;
				}
				break;
			case IMAGETYPE_PNG :
				if (!function_exists('ImageCreateFromPNG')) {
					$this->errorMsg = 'ErrorNoPNGFunction';
					return false;
				}
				try {
					$image1 = ImageCreateFromPNG($fileIn);
				} catch(\Exception $exception) {
					$this->errorMsg = 'ErrorPNGFunction';
					return false;
				}
				break;
			case IMAGETYPE_GIF :
				if (!function_exists('ImageCreateFromGIF')) {
					$this->errorMsg = 'ErrorNoGIFFunction';
					return false;
				}
				try {
					$image1 = ImageCreateFromGIF($fileIn);
				} catch(\Exception $exception) {
					$this->errorMsg = 'ErrorGIFFunction';
					return false;
				}
				break;
			case IMAGETYPE_WBMP:
				if (!function_exists('ImageCreateFromWBMP')) {
					$this->errorMsg = 'ErrorNoWBMPFunction';
					return false;
				}
				try {
					$image1 = ImageCreateFromWBMP($fileIn);
				} catch(\Exception $exception) {
					$this->errorMsg = 'ErrorWBMPFunction';
					return false;
				}
				break;
			Default:
				$this->errorMsg = 'ErrorNotSupportedImage';
				return false;
				break;
		}
		if ($image1) {
	
			$image2 = @ImageCreateTruecolor($dst[2], $dst[3]);
			if (!$image2) {
				$this->errorMsg = 'ErrorNoImageCreateTruecolor';
				return false;
			}
	
			ImageCopyResampled($image2, $image1, $dst[0],$dst[1], $src[0],$src[1], $dst[2],$dst[3], $src[2],$src[3]);
	
			// Create the file
			$typeOut = ($type == IMAGETYPE_WBMP) ? IMAGETYPE_PNG : $type;
			header("Content-type: ". image_type_to_mime_type($typeOut));
	
			switch($typeOut) {
				case IMAGETYPE_JPEG:
					if (!function_exists('ImageJPEG')) {
						$this->errorMsg = 'ErrorNoJPGFunction';
						return false;
					}
					ob_start();
	
					if (!imagejpeg($image2,NULL,$compression)) {
						$this->errorMsg = 'ErrorWriteFile';
						ob_end_clean();
						return false;
					}
					$imgJPEGToWrite = ob_get_contents();
					ob_end_clean();
					if(!JFile::write($fileOut, $imgJPEGToWrite)) {
						$this->errorMsg = 'ErrorWriteFile';
						return false;
					}
					break;
	
				case IMAGETYPE_PNG :
					if (!function_exists('ImagePNG')) {
						$this->errorMsg = 'ErrorNoPNGFunction';
						return false;
					}
	
					if (!@ImagePNG($image2, NULL,$compression)) {
						$this->errorMsg = 'ErrorWriteFile';
						return false;
					}
					$imgGIFToWrite = ob_get_contents();
					ob_end_clean();
					if(!JFile::write('../'.$fileOut, $imgGIFToWrite)) {
						$this->errorMsg = 'ErrorWriteFile';
						return false;
					}
	
					break;
	
				case IMAGETYPE_GIF :
					if (!function_exists('ImageGIF')) {
						$this->errorMsg = 'ErrorNoGIFFunction';
						return false;
					}
	
					if ($jfile_thumbs == 1) {
						ob_start();
						if (!@ImageGIF($image2, NULL,$compression)) {
							ob_end_clean();
							$this->errorMsg = 'ErrorWriteFile';
							return false;
						}
						$imgGIFToWrite = ob_get_contents();
						ob_end_clean();
							
						if(!JFile::write('../'.$fileOut, $imgGIFToWrite)) {
							$this->errorMsg = 'ErrorWriteFile';
							return false;
						}
					} else {
						if (!@ImageGIF($image2, $fileOut)) {
							$this->errorMsg = 'ErrorWriteFile';
							return false;
						}
					}
					break;
	
				Default:
					$this->errorMsg = 'ErrorNotSupportedImage';
					return false;
					break;
			}
			// free memory
			ImageDestroy($image1);
			ImageDestroy($image2);
	
		}
		return true;
	}
	/* 
		fichier desc.txt
		<nom image>|<description>|<url>
		si nom image = * => description/url par d�faut
	*/
	static public function getDesc($dir) {
		$filename = 'desc';
		$contents = self::getLabelsFileContents($dir,$filename);
		if ($contents === false) {
			return array();
		}
		if (!strcmp("\xEF\xBB\xBF", substr($contents,0,3))) {  // file starts with UTF-8 BOM
			$contents = substr($contents, 3);  // remove UTF-8 BOM
		}
		$contents = str_replace("\r", "\n", $contents);  // normalize line endings
		$contents = strtr($contents, '������������������������', 'aaaaaaceeeeiiiinooooouuuuyy');
		// split into lines
		$matches = array();
		preg_match_all('/^([^|\n]+)(?:[|]([^|\n]*)(?:[|]([^\n]*))?)?$/mu', $contents, $matches, PREG_SET_ORDER);

		// parse individual entries
		$labels = array();
		foreach ($matches as $match) {
			$imagefile = $match[1];
			$description = count($match) > 2 ? $match[2] : false;
			$link = count($match) > 3 ? $match[3] : false;
			$arr = array();
			$arr['imagefile'] = $imagefile;
			$arr['description'] = $description;
			$arr['link'] = $link;
			$labels[$imagefile] = $arr; 
		}
		return $labels;		
	}
private static function getLabelsFileContents($imagedirectory, $labelsfilename) {
		$file = self::getLabelsFilePath($imagedirectory, $labelsfilename);
		return $file ? file_get_contents($file) : false;
	}

private static function getLabelsFilePath($imagedirectory, $labelsfilename) {

		if (is_file($imagedirectory)) {  // a file, not a directory
			return false;
		}

		// default to language-neutral labels file
		$file = $imagedirectory.DIRECTORY_SEPARATOR.$labelsfilename.'.txt';  // filesystem path to labels file
		if (is_file($file)) {
			return $file;
		}
		return false;
	}
}