Ejemplo n.º 1
2
 /**
  * Method to attach a JForm object to the field.
  *  Catch upload files when form setup.
  *
  * @param   object  &$element  The JXmlElement object representing the <field /> tag for the form field object.
  * @param   mixed   $value     The form field value to validate.
  * @param   string  $group     The field name group control value. This acts as as an array container for the field.
  *                              For example if the field has name="foo" and the group value is set to "bar" then the
  *                              full field name would end up being "bar[foo]".
  *
  * @return  boolean  True on success.
  */
 public function setup(SimpleXMLElement $element, $value, $group = null)
 {
     parent::setup($element, $value, $group);
     if (JRequest::getVar($this->element['name'] . '_delete') == 1) {
         $this->value = '';
     } else {
         // Upload Image
         // ===============================================
         if (isset($_FILES['jform']['name']['profile'])) {
             foreach ($_FILES['jform']['name']['profile'] as $key => $var) {
                 if (!$var) {
                     continue;
                 }
                 // Get Field Attr
                 $width = $this->element['save_width'] ? $this->element['save_width'] : 800;
                 $height = $this->element['save_height'] ? $this->element['save_height'] : 800;
                 // Build File name
                 $src = $_FILES['jform']['tmp_name']['profile'][$key];
                 $var = explode('.', $var);
                 $date = JFactory::getDate('now', JFactory::getConfig()->get('offset'));
                 $name = md5((string) $date . $width . $height . $src) . '.' . array_pop($var);
                 $url = "images/cck/{$date->year}/{$date->month}/{$date->day}/" . $name;
                 // A Event for extend.
                 JFactory::getApplication()->triggerEvent('onCCKEngineUploadImage', array(&$url, &$this, &$this->element));
                 $dest = JPATH_ROOT . '/' . $url;
                 // Upload First
                 JFile::upload($src, $dest);
                 // Resize image
                 $img = new JImage();
                 $img->loadFile(JPATH_ROOT . '/' . $url);
                 $img = $img->resize($width, $height);
                 switch (array_pop($var)) {
                     case 'gif':
                         $type = IMAGETYPE_GIF;
                         break;
                     case 'png':
                         $type = IMAGETYPE_PNG;
                         break;
                     default:
                         $type = IMAGETYPE_JPEG;
                         break;
                 }
                 // save
                 $img->toFile($dest, $type, array('quality' => 85));
                 // Set in Value
                 $this->value = $url;
             }
         }
     }
     return true;
 }
Ejemplo n.º 2
0
 public function renderFeature()
 {
     //Retina Image
     if ($this->helix3->getParam('logo_type') == 'image') {
         jimport('joomla.image.image');
         if ($this->helix3->getParam('logo_image')) {
             $path = JPATH_ROOT . '/' . $this->helix3->getParam('logo_image');
         } else {
             $path = JPATH_ROOT . '/templates/' . $this->helix3->getTemplate() . '/images/presets/' . $this->helix3->Preset() . '/logo.png';
         }
         if (file_exists($path)) {
             $image = new JImage($path);
             $width = $image->getWidth();
             $height = $image->getHeight();
         } else {
             $width = '';
             $height = '';
         }
     }
     $html = '';
     $custom_logo_class = '';
     $sitename = JFactory::getApplication()->get('sitename');
     if ($this->helix3->getParam('mobile_logo')) {
         $custom_logo_class = ' hidden-xs';
     }
     $html .= '<a class="logo" href="' . JURI::base(true) . '/">';
     if ($this->helix3->getParam('logo_type') == 'image') {
         if ($this->helix3->getParam('logo_image')) {
             $html .= '<div>';
             $html .= '<img class="sp-default-logo' . $custom_logo_class . '" src="' . $this->helix3->getParam('logo_image') . '" alt="' . $sitename . '">';
             if ($this->helix3->getParam('logo_image_2x')) {
                 $html .= '<img class="sp-retina-logo' . $custom_logo_class . '" src="' . $this->helix3->getParam('logo_image_2x') . '" alt="' . $sitename . '" width="' . $width . '" height="' . $height . '">';
             }
             if ($this->helix3->getParam('mobile_logo')) {
                 $html .= '<img class="sp-default-logo visible-xs" src="' . $this->helix3->getParam('mobile_logo') . '" alt="' . $sitename . '">';
             }
             $html .= '</div>';
         } else {
             $html .= '<div>';
             $html .= '<img class="sp-default-logo' . $custom_logo_class . '" src="' . $this->helix3->getTemplateUri() . '/images/presets/' . $this->helix3->Preset() . '/logo.png" alt="' . $sitename . '">';
             $html .= '<img class="sp-retina-logo' . $custom_logo_class . '" src="' . $this->helix3->getTemplateUri() . '/images/presets/' . $this->helix3->Preset() . '/logo@2x.png" alt="' . $sitename . '" width="' . $width . '" height="' . $height . '">';
             if ($this->helix3->getParam('mobile_logo')) {
                 $html .= '<img class="sp-default-logo visible-xs" src="' . $this->helix3->getParam('mobile_logo') . '" alt="' . $sitename . '">';
             }
             $html .= '</div>';
         }
     } else {
         if ($this->helix3->getParam('logo_text')) {
             $html .= '<div>' . $this->helix3->divtParam('logo_text') . '</div>';
         } else {
             $html .= '<div>' . $sitename . '</div>';
         }
         if ($this->helix3->getParam('logo_slogan')) {
             $html .= '<p class="logo-slogan">' . $this->helix3->getParam('logo_slogan') . '</p>';
         }
     }
     $html .= '<div class="site-name">' . $sitename . '</div>';
     $html .= '</a>';
     return $html;
 }
Ejemplo n.º 3
0
 public static function createThumb($path, $width = 100, $height = 100, $crop = 2)
 {
     $myImage = new JImage();
     $myImage->loadFile(JPATH_SITE . DS . $path);
     if ($myImage->isLoaded()) {
         // $filename = end(explode('/', $path));
         $filename = JFile::getName($path);
         $filefolder = substr(md5(self::getFolderPath($path)), 1, 10);
         $newfilename = $width . 'x' . $height . '_' . $filefolder . '_' . JFile::makeSafe($filename);
         $fileExists = JFile::exists(JPATH_CACHE . '/' . $newfilename);
         if (!$fileExists) {
             $resizedImage = $myImage->resize($width, $height, true, $crop);
             $properties = $myImage->getImageFileProperties($path);
             $mime = $properties->mime;
             if ($mime == 'image/jpeg') {
                 $type = IMAGETYPE_JPEG;
             } elseif ($mime = 'image/png') {
                 $type = IMAGETYPE_PNG;
             } elseif ($mime = 'image/gif') {
                 $type = IMAGETYPE_GIF;
             }
             $resizedImage->toFile(JPATH_CACHE . '/' . $newfilename, $type);
         }
         return $newfilename;
     } else {
         return "My file is not loaded";
     }
 }
Ejemplo n.º 4
0
 public function resetThumbs()
 {
     $items = self::getItems();
     //Get Params
     $params = JComponentHelper::getParams('com_spsimpleportfolio');
     $square = strtolower($params->get('square', '600x600'));
     $rectangle = strtolower($params->get('rectangle', '600x400'));
     $tower = strtolower($params->get('tower', '600x800'));
     $cropratio = $params->get('cropratio', 4);
     if (count($items)) {
         //Removing old thumbs
         foreach ($items as $item) {
             $folder = JPATH_ROOT . '/images/spsimpleportfolio/' . $item->alias;
             if (JFolder::exists($folder)) {
                 JFolder::delete($folder);
             }
         }
         //Creating Thumbs
         foreach ($items as $item) {
             $image = JPATH_ROOT . '/' . $item->image;
             $path = JPATH_ROOT . '/images/spsimpleportfolio/' . $item->alias;
             if (!file_exists($path)) {
                 JFolder::create($path, 0755);
             }
             $sizes = array($square, $rectangle, $tower);
             $image = new JImage($image);
             $image->createThumbs($sizes, $cropratio, $path);
         }
     }
     $this->setRedirect('index.php?option=com_config&view=component&component=com_spsimpleportfolio&path=&return=' . base64_encode('index.php?option=com_spsimpleportfolio'), 'Thumbnails generated.');
 }
Ejemplo n.º 5
0
 /**
  * Create a thumbnail from an image file.
  *
  * <code>
  * $myFile   = "/tmp/myfile.jpg";
  *
  * $options = array(
  *     "destination" => "image/mypic.jpg",
  *     "width" => 200,
  *     "height" => 200,
  *     "scale" => JImage::SCALE_INSIDE
  * );
  *
  * $file = new PrismFileImage($myFile);
  * $file->createThumbnail($options);
  *
  * </code>
  *
  * @param  array $options Some options used in the process of generating thumbnail.
  *
  * @throws \InvalidArgumentException
  * @throws \RuntimeException
  *
  * @return string A location to the new file.
  */
 public function createThumbnail($options)
 {
     $width = ArrayHelper::getValue($options, "width", 100);
     $height = ArrayHelper::getValue($options, "height", 100);
     $scale = ArrayHelper::getValue($options, "scale", \JImage::SCALE_INSIDE);
     $destination = ArrayHelper::getValue($options, "destination");
     if (!$destination) {
         throw new \InvalidArgumentException(\JText::_("LIB_PRISM_ERROR_INVALID_FILE_DESTINATION"));
     }
     // Generate thumbnail.
     $image = new \JImage();
     $image->loadFile($this->file);
     if (!$image->isLoaded()) {
         throw new \RuntimeException(\JText::sprintf('LIB_PRISM_ERROR_FILE_NOT_FOUND', $this->file));
     }
     // Resize the file as a new object
     $thumb = $image->resize($width, $height, true, $scale);
     $fileName = basename($this->file);
     $ext = \JString::strtolower(\JFile::getExt(\JFile::makeSafe($fileName)));
     switch ($ext) {
         case "gif":
             $type = IMAGETYPE_GIF;
             break;
         case "png":
             $type = IMAGETYPE_PNG;
             break;
         case IMAGETYPE_JPEG:
         default:
             $type = IMAGETYPE_JPEG;
     }
     $thumb->toFile($destination, $type);
     return $destination;
 }
Ejemplo n.º 6
0
 /**
  * Resize an image, auto catch it from remote host and generate a new thumb in cache dir.
  *
  * @param   string  $url       Image URL, recommend a absolute URL.
  * @param   integer $width     Image width, do not include 'px'.
  * @param   integer $height    Image height, do not include 'px'.
  * @param   int     $method    Crop or not.
  * @param   integer $q         Image quality
  * @param   string  $file_type File type.
  *
  * @return  string  The cached thumb URL.
  */
 public function resize($url = null, $width = 100, $height = 100, $method = \JImage::SCALE_INSIDE, $q = 85, $file_type = 'jpg')
 {
     if (!$url) {
         return $this->getDefaultImage($width, $height, $method, $q, $file_type);
     }
     $path = $this->getImagePath($url);
     try {
         $img = new \JImage();
         if (\JFile::exists($path)) {
             $img->loadFile($path);
         } else {
             return $this->getDefaultImage($width, $height, $method, $q, $file_type);
         }
         // If file type not png or gif, use jpg as default.
         if ($file_type != 'png' && $file_type != 'gif') {
             $file_type = 'jpg';
         }
         // Using md5 hash
         $handler = $this->hashHandler;
         $file_name = $handler($url . $width . $height . $method . $q) . '.' . $file_type;
         $file_path = $this->config['path.cache'] . '/' . $file_name;
         $file_url = trim($this->config['url.cache'], '/') . '/' . $file_name;
         // Img exists?
         if (\JFile::exists($file_path)) {
             return $file_url;
         }
         // Crop
         if ($method === true) {
             $method = \JImage::CROP_RESIZE;
         } elseif ($method === false) {
             $method = \JImage::SCALE_INSIDE;
         }
         $img = $img->generateThumbs($width . 'x' . $height, $method);
         // Save
         switch ($file_type) {
             case 'gif':
                 $type = IMAGETYPE_GIF;
                 break;
             case 'png':
                 $type = IMAGETYPE_PNG;
                 break;
             default:
                 $type = IMAGETYPE_JPEG;
                 break;
         }
         // Create folder
         if (!is_dir(dirname($file_path))) {
             \JFolder::create(dirname($file_path));
         }
         $img[0]->toFile($file_path, $type, array('quality' => $q));
         return $file_url;
     } catch (\Exception $e) {
         if (JDEBUG) {
             echo $e->getMessage();
         }
         return $this->getDefaultImage($width, $height, $method, $q, $file_type);
     }
 }
Ejemplo n.º 7
0
 public function check()
 {
     $result = true;
     //Alias
     if (empty($this->alias)) {
         // Auto-fetch a alias
         $this->alias = JFilterOutput::stringURLSafe($this->title);
     } else {
         // Make sure nobody adds crap characters to the alias
         $this->alias = JFilterOutput::stringURLSafe($this->alias);
     }
     $existingAlias = FOFModel::getTmpInstance('Items', 'SpsimpleportfolioModel')->alias($this->alias)->getList(true);
     if (!empty($existingAlias)) {
         $count = 0;
         $k = $this->getKeyName();
         foreach ($existingAlias as $item) {
             if ($item->{$k} != $this->{$k}) {
                 $count++;
             }
         }
         if ($count) {
             $this->setError(JText::_('COM_SPSIMPLEPORTFOLIO_ALIAS_ERR_SLUGUNIQUE'));
             $result = false;
         }
     }
     //Tags
     if (is_array($this->spsimpleportfolio_tag_id)) {
         if (!empty($this->spsimpleportfolio_tag_id)) {
             $this->spsimpleportfolio_tag_id = json_encode($this->spsimpleportfolio_tag_id);
         }
     }
     if (is_null($this->spsimpleportfolio_tag_id) || empty($this->spsimpleportfolio_tag_id)) {
         $this->spsimpleportfolio_tag_id = '';
     }
     //Generate Thumbnails
     if ($result) {
         $params = JComponentHelper::getParams('com_spsimpleportfolio');
         $square = strtolower($params->get('square', '600x600'));
         $rectangle = strtolower($params->get('rectangle', '600x400'));
         $tower = strtolower($params->get('tower', '600x800'));
         $cropratio = $params->get('cropratio', 4);
         if (!is_null($this->image)) {
             jimport('joomla.filesystem.file');
             jimport('joomla.filesystem.folder');
             jimport('joomla.image.image');
             $image = JPATH_ROOT . '/' . $this->image;
             $path = JPATH_ROOT . '/images/spsimpleportfolio/' . $this->alias;
             if (!file_exists($path)) {
                 JFolder::create($path, 0755);
             }
             $sizes = array($square, $rectangle, $tower);
             $image = new JImage($image);
             $image->createThumbs($sizes, $cropratio, $path);
         }
     }
     return $result;
 }
Ejemplo n.º 8
0
 public static function getProportion($path)
 {
     $myImage = new JImage();
     $imgPath = JPATH_SITE . DS . $path;
     $myImage->loadFile($imgPath);
     if ($myImage->isLoaded()) {
         $properties = $myImage->getImageFileProperties($imgPath);
         return $properties->height / $properties->width * 100;
     } else {
         return;
     }
 }
Ejemplo n.º 9
0
 public function create()
 {
     $output = '';
     $size = JRequest::getCmd('size', '');
     if (!in_array($size, array('min', 'medium'))) {
         throw new Exception('The image size is not recognized', 500);
     }
     $image = JRequest::getVar('image', '');
     $id = JRequest::getInt('id', 0);
     $imagePath = JPATH_ROOT . DS . 'images' . DS . 'com_jea' . DS . 'images' . DS . $id . DS . $image;
     $thumbDir = JPATH_ROOT . DS . 'images' . DS . 'com_jea' . DS . 'thumb-' . $size;
     $thumbPath = $thumbDir . DS . $id . '-' . $image;
     if (file_exists($thumbPath)) {
         $output = readfile($thumbPath);
     } elseif (file_exists($imagePath)) {
         if (!JFolder::exists($thumbPath)) {
             JFolder::create($thumbDir);
         }
         $params = JComponentHelper::getParams('com_jea');
         if ($size == 'medium') {
             $width = $params->get('thumb_medium_width', 400);
             $height = $params->get('thumb_medium_height', 300);
         } else {
             $width = $params->get('thumb_min_width', 120);
             $height = $params->get('thumb_min_height', 90);
         }
         $quality = (int) $params->get('jpg_quality', 90);
         $cropThumbnails = (bool) $params->get('crop_thumbnails', 0);
         $JImage = new JImage($imagePath);
         if ($cropThumbnails) {
             $thumb = $JImage->resize($width, $height, true, JImage::SCALE_OUTSIDE);
             $left = $thumb->getWidth() > $width ? intval(($thumb->getWidth() - $width) / 2) : 0;
             $top = $thumb->getHeight() > $height ? intval(($thumb->getHeight() - $height) / 2) : 0;
             $thumb->crop($width, $height, $left, $top, false);
         } else {
             $thumb = $JImage->resize($width, $height);
         }
         $thumb->toFile($thumbPath, IMAGETYPE_JPEG, array('quality' => $quality));
         $output = readfile($thumbPath);
     } else {
         throw new Exception('The image ' . $image . ' was not found', 500);
     }
     JResponse::setHeader('Content-Type', 'image/jpeg', true);
     JResponse::setHeader('Content-Transfer-Encoding', 'binary');
     JResponse::allowCache(false);
     JResponse::setBody($output);
     echo JResponse::toString();
     exit;
 }
Ejemplo n.º 10
0
 public function onMediaEditorProcess($filePath)
 {
     jimport('joomla.filesystem.file');
     $image = new JImage($filePath);
     if ($image->isLoaded() == false) {
         throw new LogicException('Failed to load image');
     }
     $image->rotate(180, 0, false);
     $extension = JFile::getExt($filePath);
     if (in_array($extension, array('png', 'gif'))) {
         $imageType = $extension;
     } else {
         $imageType = 'jpg';
     }
     $image->toFile($filePath, $imageType);
 }
Ejemplo n.º 11
0
 /**
  * Method to load the images from the relative source
  * 
  * @param  JRegistry $params The module params object
  * 
  * @return object[]          An array of image objects
  *
  * @since  1.0
  */
 public static function getImages($params)
 {
     // Create the folder path
     $folder = JPath::clean(JPATH_BASE . DIRECTORY_SEPARATOR . $params->get('image_folder'));
     $cacheFolder = JPath::clean(JPATH_BASE . '/cache/mod_qluegallery/thumbs/' . $params->get('image_folder'));
     // Make sure the folder we are trying to load actually exists
     if (!JFolder::exists($folder)) {
         JError::raiseWarning(500, JText::_('MOD_QLUEGALLERY_NO_FOLDER_EXISTS'));
         return null;
     }
     // Load all images from the folder
     $images = JFolder::files($folder, '\\.(?:gif|jpg|png|jpeg)$');
     // Limit our found images
     $images = array_slice($images, 0, (int) $params->get('limit', 1));
     // Loop through each image and apply the image path
     foreach ($images as $key => $image) {
         // Path to the file
         $file = JPath::clean($folder . '/' . $image);
         $dimensions = $params->get('thumbnail_width', 150) . 'x' . $params->get('thumbnail_height', 150);
         $thumbnail = pathinfo($image, PATHINFO_FILENAME);
         $thumbExt = pathinfo($image, PATHINFO_EXTENSION);
         $thumbnail .= '_' . $dimensions . '.' . $thumbExt;
         // Create our image object
         $img = new stdClass();
         $img->file = $image;
         $img->full_path = JUri::root(true) . str_replace(JPATH_BASE, '', $file);
         $img->properties = JImage::getImageFileProperties($file);
         $img->thumbnail = str_replace(JPATH_BASE, '', $cacheFolder . '/' . $thumbnail);
         // If the thumbnail does not exist, create it
         if (!file_exists($cacheFolder . DIRECTORY_SEPARATOR . $thumbnail)) {
             // Get the image source
             $gd = new JImage($file);
             // Create the thumb folder if it does not exist
             if (!JFolder::exists($cacheFolder)) {
                 JFolder::create($cacheFolder);
             }
             // Create the thumbnails
             $gd->createThumbs($dimensions, JImage::CROP_RESIZE, $cacheFolder);
         }
         // Make sure the file paths are safe to use
         $img->full_path = str_replace('\\', '/', $img->full_path);
         $img->thumbnail = str_replace('\\', '/', $img->thumbnail);
         $images[$key] = $img;
     }
     return $images;
 }
Ejemplo n.º 12
0
 /**
  * Allows public access to protected method.
  *
  * @param   string  $type  The image filter type to get.
  *
  * @return  JImageFilter
  *
  * @since   11.3
  * @throws  RuntimeException
  */
 public function getFilterInstance($type)
 {
     if ($this->mockFilter) {
         return $this->mockFilter;
     } else {
         return parent::getFilterInstance($type);
     }
 }
Ejemplo n.º 13
0
 public function resize($type, $width, $height, $crop = false)
 {
     if ($type == 'thumbnail') {
         $path = $this->gallery->getThumbnailsPath();
         $filePath =& $this->thumbnailFilepath;
         $scale = 3;
         // SCALE_OUTSIDE
         $options = array('quality' => 75);
         // TODO as param
     } else {
         if ($type == 'resized') {
             $path = $this->gallery->getResizedPath();
             $filePath =& $this->resizedFilepath;
             $scale = 2;
             // SCALE_INSIDE
             $options = array('quality' => 85);
             // TODO as param
         } else {
             return;
         }
     }
     // define file paths
     $newPhotoFilepath = $path . DS . $this->folder->getFolderPath() . DS . $this->filename;
     $photoFilepath = $this->gallery->getPhotosPath() . DS . $this->folder->getFolderPath() . DS . $this->filename;
     // check if thumbnail already exists and create it if not
     if (!JFile::exists($newPhotoFilepath)) {
         // TODO add check if file size (width and height) is correct
         // resize image
         $photo = new JImage($photoFilepath);
         $newPhoto = $photo->resize($width, $height, true, $scale);
         // crop image
         if ($crop) {
             $offsetLeft = ($newPhoto->getWidth() - $width) / 2;
             $offsetTop = ($newPhoto->getHeight() - $height) / 2;
             $newPhoto->crop($width, $height, $offsetLeft, $offsetTop, false);
         }
         // create folders (recursive) and write file
         if (JFolder::create($path . DS . $this->folder->getFolderPath())) {
             $newPhoto->toFile($newPhotoFilepath, IMAGETYPE_JPEG, $options);
         }
     }
     $filePath = str_replace($this->gallery->getCachePath(), '', $newPhotoFilepath);
 }
Ejemplo n.º 14
0
 /**
  * Class constructor.
  *
  * @param   mixed  $source  Either a file path for a source image or a GD resource handler for an image.
  *
  * @since   11.3
  * @throws  RuntimeException
  */
 public function __construct($source = null)
 {
     // Determine which image types are supported by GD, but only once.
     if (!isset(self::$formats[IMAGETYPE_JPEG])) {
         $info = gd_info();
         self::$formats[IMAGETYPE_JPEG] = $info['JPEG Support'] ? true : $info['JPG Support'] ? true : false;
         self::$formats[IMAGETYPE_PNG] = $info['PNG Support'] ? true : false;
         self::$formats[IMAGETYPE_GIF] = $info['GIF Read Support'] ? true : false;
     }
     parent::__construct($source);
 }
Ejemplo n.º 15
0
 /**
  * Resize an image, auto catch it from remote host and generate a new thumb in cache dir.
  *
  * @param   string  $url       Image URL, recommend a absolute URL.
  * @param   integer $width     Image width, do not include 'px'.
  * @param   integer $height    Image height, do not include 'px'.
  * @param   boolean $zc        Crop or not.
  * @param   integer $q         Image quality
  * @param   string  $file_type File type.
  *
  * @return  string  The cached thumb URL.
  */
 public static function resize($url = null, $width = 100, $height = 100, $zc = 0, $q = 85, $file_type = 'jpg')
 {
     if (!$url) {
         return self::getDefaultImage($width, $height, $zc, $q, $file_type);
     }
     $path = self::getImagePath($url);
     try {
         $img = new JImage();
         if (JFile::exists($path)) {
             $img->loadFile($path);
         } else {
             return self::getDefaultImage($width, $height, $zc, $q, $file_type);
         }
         // get Width Height
         $imgdata = JImage::getImageFileProperties($path);
         // set save data
         if ($file_type != 'png' && $file_type != 'gif') {
             $file_type = 'jpg';
         }
         $file_name = md5($url . $width . $height . $zc . $q . implode('', (array) $imgdata)) . '.' . $file_type;
         $file_path = self::$cache_path . DS . $file_name;
         $file_url = trim(self::$cache_url, '/') . '/' . $file_name;
         // img exists?
         if (JFile::exists($file_path)) {
             return $file_url;
         }
         // crop
         if ($zc) {
             $img = self::crop($img, $width, $height, $imgdata);
         }
         // resize
         $img = $img->resize($width, $height);
         // save
         switch ($file_type) {
             case 'gif':
                 $type = IMAGETYPE_GIF;
                 break;
             case 'png':
                 $type = IMAGETYPE_PNG;
                 break;
             default:
                 $type = IMAGETYPE_JPEG;
                 break;
         }
         JFolder::create(self::$cache_path);
         $img->toFile($file_path, $type, array('quality' => $q));
         return $file_url;
     } catch (Exception $e) {
         if (JDEBUG) {
             echo $e->getMessage();
         }
         return self::getDefaultImage($width, $height, $zc, $q, $file_type);
     }
 }
Ejemplo n.º 16
0
 public static function createThumb($path, $width = 100, $height = 100, $crop = 2, $cachefolder = 'hgimages', $external = 0)
 {
     $myImage = new JImage();
     if (!$external) {
         $myImage->loadFile(JPATH_SITE . DS . $path);
     } else {
         $myImage->loadFile($path);
     }
     if ($myImage->isLoaded()) {
         // $filename = end(explode('/', $path));
         $filename = JFile::getName($path);
         $filefolder = substr(md5(self::getFolderPath($path)), 1, 10);
         $newfilename = $width . 'x' . $height . 'x' . $crop . '_' . $filefolder . '_' . JFile::makeSafe($filename);
         $hgimages = JPATH_CACHE . '/' . $cachefolder . '/';
         if (!JFolder::exists($hgimages)) {
             JFolder::create($hgimages);
         }
         $fileExists = JFile::exists($hgimages . $newfilename);
         if (!$fileExists) {
             switch ($crop) {
                 // Case for self::CROP
                 case 4:
                     $resizedImage = $myImage->crop($width, $height, null, null, true);
                     break;
                     // Case for self::CROP_RESIZE
                 // Case for self::CROP_RESIZE
                 case 5:
                     $resizedImage = $myImage->cropResize($width, $height, true);
                     break;
                 default:
                     $resizedImage = $myImage->resize($width, $height, true, $crop);
                     break;
             }
             $properties = $myImage->getImageFileProperties($path);
             $mime = $properties->mime;
             if ($mime == 'image/jpeg') {
                 $type = IMAGETYPE_JPEG;
             } elseif ($mime = 'image/png') {
                 $type = IMAGETYPE_PNG;
             } elseif ($mime = 'image/gif') {
                 $type = IMAGETYPE_GIF;
             }
             $resizedImage->toFile($hgimages . $newfilename, $type);
         }
         return $newfilename;
     } else {
         return "My file is not loaded";
     }
 }
Ejemplo n.º 17
0
 /**
  * Plugin that manipulate uploaded images
  *
  * @param   string   $context       The context of the content being passed to the plugin.
  * @param   object   &$object_file  The file object.
  *
  * @return  object  The file object.
  */
 public function onContentAfterSave($context, &$object_file)
 {
     // Are we in the right context?
     if ($context != 'com_media.file') {
         return;
     }
     $file = pathinfo($object_file->filepath);
     // Skip if the pass through keyword is set
     if (preg_match('/' . $this->params->get('passthrough') . '_/', $file['filename'])) {
         return;
     }
     $image = new JImage();
     // Load the file
     $image->loadFile($object_file->filepath);
     // Get the properties
     $properties = $image->getImageFileProperties($object_file->filepath);
     // Skip if the width is less or equal to the required
     if ($properties->width <= $this->params->get('maxwidth')) {
         return;
     }
     // Get the image type
     if (preg_match('/jp(e)g/', mb_strtolower($properties->mime))) {
         $imageType = 'IMAGETYPE_JPEG';
     }
     if (preg_match('/gif/', mb_strtolower($properties->mime))) {
         $imageType = 'IMAGETYPE_GIF';
     }
     if (preg_match('/png/', mb_strtolower($properties->mime))) {
         $imageType = 'IMAGETYPE_PNG';
     }
     // Resize the image
     $image->resize($this->params->get('maxwidth'), '', false);
     // Overwrite the file
     $image->toFile($object_file->filepath, $imageType, array('quality' => $this->params->get('quality')));
     return $object_file;
 }
Ejemplo n.º 18
0
 /**
  * Save user profile data.
  *
  * @param   array    $data    Entered user data
  * @param   boolean  $isNew   True if this is a new user
  * @param   boolean  $result  True if saving the user worked
  * @param   string   $error   Error message
  *
  * @return  boolean
  */
 public function onUserAfterSave($data, $isNew, $result, $error)
 {
     // Only run in front-end.
     if (!JFactory::getApplication()->isSite()) {
         return true;
     }
     $userId = JArrayHelper::getValue($data, 'id', 0, 'int');
     $folder = $this->params->get('folder', '');
     $avatarFolder = JPATH_ROOT . '/' . $folder;
     // If the avatar folder doesn't exist, we don't do anything.
     if (!JFolder::exists($avatarFolder)) {
         return false;
     }
     $jinput = JFactory::getApplication()->input;
     $delete = $jinput->get('delete-avatar', '', 'word');
     if ($delete == 'yes') {
         $this->deleteAvatar($userId);
         return true;
     }
     if ($result && $userId > 0) {
         $files = $jinput->files->get('jform', array(), 'array');
         if (!isset($files['cmavatar']['cmavatar'])) {
             return false;
         }
         $file = $files['cmavatar']['cmavatar'];
         if (empty($file['name'])) {
             return true;
         }
         $fileTypes = explode('.', $file['name']);
         if (count($fileTypes) < 2) {
             // There seems to be no extension.
             throw new RuntimeException(JText::_('PLG_USER_CMAVATAR_ERROR_FILE_TYPE'));
             return false;
         }
         array_shift($fileTypes);
         // Check if the file has an executable extension.
         $executable = array('php', 'js', 'exe', 'phtml', 'java', 'perl', 'py', 'asp', 'dll', 'go', 'ade', 'adp', 'bat', 'chm', 'cmd', 'com', 'cpl', 'hta', 'ins', 'isp', 'jse', 'lib', 'mde', 'msc', 'msp', 'mst', 'pif', 'scr', 'sct', 'shb', 'sys', 'vb', 'vbe', 'vbs', 'vxd', 'wsc', 'wsf', 'wsh');
         $check = array_intersect($fileTypes, $executable);
         if (!empty($check)) {
             throw new RuntimeException(JText::_('PLG_USER_CMAVATAR_ERROR_FILE_TYPE'));
             return false;
         }
         $fileType = array_pop($fileTypes);
         $allowable = array_map('trim', explode(',', $this->params->get('allowed_extensions')));
         if ($fileType == '' || $fileType == false || !in_array($fileType, $allowable)) {
             throw new RuntimeException(JText::_('PLG_USER_CMAVATAR_ERROR_FILE_TYPE'));
             return false;
         }
         $uploadMaxSize = $this->params->get('max_size', 0) * 1024 * 1024;
         $uploadMaxFileSize = $this->toBytes(ini_get('upload_max_filesize'));
         if ($file['error'] == 1 || $uploadMaxSize > 0 && $file['size'] > $uploadMaxSize || $uploadMaxFileSize > 0 && $file['size'] > $uploadMaxFileSize) {
             throw new RuntimeException(JText::_('PLG_USER_CMAVATAR_ERROR_FILE_TOO_LARGE'));
             return false;
         }
         // Make the file name unique.
         $md5String = $userId . $file['name'] . JFactory::getDate();
         $avatarFileName = JFile::makeSafe(md5($md5String));
         if (empty($avatarFileName)) {
             // No file name after the name was cleaned by JFile::makeSafe.
             throw new RuntimeException(JText::_('PLG_USER_CMAVATAR_ERROR_NO_FILENAME'));
             return false;
         }
         $avatarPath = JPath::clean($avatarFolder . '/' . $avatarFileName . '.' . $this->extension);
         if (JFile::exists($avatarPath)) {
             // A file with this name already exists. It is almost impossible.
             throw new RuntimeException(JText::_('PLG_USER_CMAVATAR_ERROR_FILE_EXISTS'));
             return false;
         }
         // Start resizing the file.
         $avatar = new JImage($file['tmp_name']);
         $originalWidth = $avatar->getWidth();
         $originalHeight = $avatar->getHeight();
         $ratio = $originalWidth / $originalHeight;
         $maxWidth = (int) $this->params->get('width', 100);
         $maxHeight = (int) $this->params->get('height', 100);
         // Invalid value in the plugin configuration. Set avatar width to 100.
         if ($maxWidth <= 0) {
             $maxWidth = 100;
         }
         if ($maxHeight <= 0) {
             $maxHeight = 100;
         }
         if ($originalWidth > $maxWidth) {
             $ratio = $originalWidth / $originalHeight;
             $newWidth = $maxWidth;
             $newHeight = $newWidth / $ratio;
             if ($newHeight > $maxHeight) {
                 $ratio = $newWidth / $newHeight;
                 $newHeight = $maxHeight;
                 $newWidth = $newHeight * $ratio;
             }
         } elseif ($originalHeight > $maxHeight) {
             $ratio = $originalWidth / $originalHeight;
             $newHeight = $maxHeight;
             $newWidth = $newHeight * $ratio;
             if ($newWidth > $maxWidth) {
                 $ratio = $newWidth / $newHeight;
                 $newWidth = $maxWidth;
                 $newHeight = $newWidth / $ratio;
             }
         } else {
             $newWidth = $originalWidth;
             $newHeight = $originalHeight;
         }
         $resizedAvatar = $avatar->resize($newWidth, $newHeight, true);
         $resizedAvatar->toFile($avatarPath);
         // Delete current avatar if exists.
         $this->deleteAvatar($userId);
         $db = JFactory::getDbo();
         $query = $db->getQuery(true);
         // Save avatar's file name to database.
         if (!empty($currentAvatar)) {
             $query->update($db->qn('#__user_profiles'))->set($db->qn('profile_value') . ' = ' . $db->q($avatarFileName))->where($db->qn('user_id') . ' = ' . $db->q($userId))->where($db->qn('profile_key') . ' = ' . $db->quote($this->profileKey));
         } else {
             $query->insert($db->qn('#__user_profiles'))->columns($db->qn(array('user_id', 'profile_key', 'profile_value', 'ordering')))->values($db->q($userId) . ', ' . $db->q($this->profileKey) . ', ' . $db->q($avatarFileName) . ', ' . $db->q('1'));
         }
         $db->setQuery($query)->execute();
         // Check for a database error.
         if ($error = $db->getErrorMsg()) {
             throw new RuntimeException($error);
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 19
0
 /**
  * Resize an image.
  *
  * @param   string  $file    The name and location of the file
  * @param   string  $width   The new width of the image.
  * @param   string  $height  The new height of the image.
  *
  * @return   boolean  true if image resize successful, false otherwise.
  *
  * @since   3.2
  */
 public function resizeImage($file, $width, $height)
 {
     if ($template = $this->getTemplate()) {
         $app = JFactory::getApplication();
         $client = JApplicationHelper::getClientInfo($template->client_id);
         $relPath = base64_decode($file);
         $path = JPath::clean($client->path . '/templates/' . $template->element . '/' . $relPath);
         $JImage = new JImage($path);
         try {
             $image = $JImage->resize($width, $height, true, 1);
             $image->toFile($path);
             return true;
         } catch (Exception $e) {
             $app->enqueueMessage($e->getMessage(), 'error');
         }
     }
 }
Ejemplo n.º 20
0
 /**
  * Validate image type and extension.
  *
  * <code>
  * $myFile     = "/tmp/myfile.jpg";
  * $fileName   = "myfile.jpg";
  *
  * $validator = new Prism\File\Validator\Image($myFile, $fileName);
  *
  * if (!$validator->isValid()) {
  *     echo $validator->getMessage();
  * }
  * </code>
  *
  * @return bool
  */
 public function isValid()
 {
     if (!\JFile::exists($this->file)) {
         $this->message = \JText::sprintf('LIB_PRISM_ERROR_FILE_DOES_NOT_EXISTS', $this->file);
         return false;
     }
     $imageProperties = \JImage::getImageFileProperties($this->file);
     // Check mime type of the file
     if (false === array_search($imageProperties->mime, $this->mimeTypes)) {
         $this->message = \JText::_('LIB_PRISM_ERROR_FILE_TYPE');
         return false;
     }
     // Check file extension
     $ext = \JString::strtolower(\JFile::getExt($this->fileName));
     if (false === array_search($ext, $this->imageExtensions)) {
         $this->message = \JText::sprintf('LIB_PRISM_ERROR_FILE_EXTENSIONS', $ext);
         return false;
     }
     return true;
 }
Ejemplo n.º 21
0
 function onUserAfterSave($data, $isNew, $result, $error)
 {
     $userId = JArrayHelper::getValue($data, 'id', 0, 'int');
     $files = JRequest::getVar('jform', null, 'files');
     $post = JRequest::getVar('jform', null);
     $savedNewProfileCover = false;
     // Save original cover, resized covers and save them
     if ($files['error']['profilecover']['file'] == 0 && !empty($files['tmp_name']['profilecover']['file'])) {
         // Throw new exception if the uploaded file exceed the maximum allowed file size.
         if ($this->doesExceedFileSizeLimit($files['size']['profilecover']['file'])) {
             throw new Exception(JText::sprintf('PLG_USER_PROFILECOVER_ERROR_FILE_SIZE_TOO_BIG', $this->maxUploadSizeInBytes() / 1000));
         }
         $profilecover = new JImage($files['tmp_name']['profilecover']['file']);
         $sourceWidth = $profilecover->getWidth();
         $sourceHeight = $profilecover->getHeight();
         if ($sourceWidth < PROFILECOVER_SIZE_200 || $sourceHeight < PROFILECOVER_SIZE_200) {
             throw new Exception(JText::_('PLG_USER_PROFILECOVER_ERROR_TOO_SMALL'));
         }
         $pp_filename = sha1($userId . uniqid()) . '.' . plgUserProfileCover::FILE_EXTENSION;
         foreach ($this->sizes as $size) {
             if ($size == PROFILECOVER_SIZE_ORIGINAL) {
                 $profilecover->toFile(PROFILECOVER_PATH_ORIGINAL . $pp_filename);
                 $savedNewProfileCover = true;
             } else {
                 $ratio = max($sourceWidth, $sourceHeight) / $size;
                 $ratio = max($ratio, 1.0);
                 $resizedWidth = (int) ($sourceWidth / $ratio);
                 $resizedHeight = (int) ($sourceHeight / $ratio);
                 $left = 0;
                 $top = 0;
                 if ($this->square && $sourceWidth > $size && $sourceHeight > $size) {
                     if ($sourceWidth > $sourceHeight) {
                         $left = (int) ($sourceWidth - $sourceHeight) / 2;
                         $top = 0;
                         $croppedWidth = $sourceHeight;
                         $croppedHeight = $sourceHeight;
                         $resizedHeight = $resizedWidth;
                     } elseif ($sourceHeight >= $sourceWidth) {
                         $left = 0;
                         $top = (int) (($sourceHeight - $sourceWidth) / 2);
                         $croppedWidth = $sourceWidth;
                         $croppedHeight = $sourceWidth;
                         $resizedWidth = $resizedHeight;
                     }
                     $cropped = $profilecover->crop($croppedWidth, $croppedHeight, $left, $top, true);
                     $resized = $cropped->resize($resizedWidth, $resizedHeight, true, JImage::SCALE_OUTSIDE);
                     $resized->toFile(constant('PROFILECOVER_PATH_' . $size) . $pp_filename);
                     $savedNewProfileCover = true;
                 } else {
                     $resized = $profilecover->resize($size, $size, true, JImage::SCALE_INSIDE);
                     $resized->toFile(constant('PROFILECOVER_PATH_' . $size) . $pp_filename);
                     $savedNewProfileCover = true;
                 }
             }
         }
     }
     // Remove profile cover if an existing profile cover is
     // checked for removal or a new cover has been uploaded
     // replacing the existing cover.
     if (isset($userId) && (!empty($post['profilecover']['file']['remove']) || $savedNewProfileCover)) {
         $this->removeProfileCover($userId);
     }
     if ($userId && $savedNewProfileCover) {
         try {
             $db = JFactory::getDbo();
             $query = $db->getQuery(true);
             $query = $db->getQuery(true);
             $query->insert('#__user_profiles')->columns('user_id, profile_key, profile_value, ordering')->values($userId . ', ' . $db->quote(plgUserProfileCover::PROFILE_KEY) . ', ' . $db->quote($pp_filename) . ', ' . ' 1');
             $db->setQuery($query);
             if (!$db->query()) {
                 throw new Exception($db->getErrorMsg());
             }
         } catch (JException $e) {
             $this->_subject->setError($e->getMessage());
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 22
0
 function onUserAfterSave($data, $isNew, $result, $error)
 {
     $userId = JArrayHelper::getValue($data, 'id', 0, 'int');
     $files = JRequest::getVar('jform', null, 'files');
     $post = JRequest::getVar('jform', null);
     /*var_dump($_GET["task"]);
     		var_dump($_POST["task"]);
     		die;*/
     if ($_GET["task"] != "registration.register" && $_POST["task"] != "register") {
         $savedNewProfilePicture = false;
         // Save original picture, resized pictures and save them
         if ($files['error']['profilepicture']['file'] == 0) {
             $profilepicture = new JImage($files['tmp_name']['profilepicture']['file']);
             $sourceWidth = $profilepicture->getWidth();
             $sourceHeight = $profilepicture->getHeight();
             if ($sourceWidth < PROFILEPICTURE_SIZE_200 || $sourceHeight < PROFILEPICTURE_SIZE_200) {
                 throw new Exception(JText::_('PLG_USER_PROFILEPICTURE_ERROR_TOO_SMALL'));
             }
             $pp_filename = sha1($userId . uniqid()) . '.' . plgUserProfilePicture::FILE_EXTENSION;
             foreach ($this->sizes as $size) {
                 if ($size == PROFILEPICTURE_SIZE_ORIGINAL) {
                     $profilepicture->toFile(PROFILEPICTURE_PATH_ORIGINAL . $pp_filename);
                     $savedNewProfilePicture = true;
                 } else {
                     $ratio = max($sourceWidth, $sourceHeight) / $size;
                     $ratio = max($ratio, 1.0);
                     $resizedWidth = (int) ($sourceWidth / $ratio);
                     $resizedHeight = (int) ($sourceHeight / $ratio);
                     $left = 0;
                     $top = 0;
                     if ($this->square && $sourceWidth > $size && $sourceHeight > $size) {
                         if ($sourceWidth > $sourceHeight) {
                             $left = (int) ($sourceWidth - $sourceHeight) / 2;
                             $top = 0;
                             $croppedWidth = $sourceHeight;
                             $croppedHeight = $sourceHeight;
                             $resizedHeight = $resizedWidth;
                         } elseif ($sourceHeight > $sourceWidth) {
                             $left = 0;
                             $top = (int) (($sourceHeight - $sourceWidth) / 2);
                             $croppedWidth = $sourceWidth;
                             $croppedHeight = $sourceWidth;
                             $resizedWidth = $resizedHeight;
                         }
                         $cropped = $profilepicture->crop($croppedWidth, $croppedHeight, $left, $top, true);
                         $resized = $cropped->resize($resizedWidth, $resizedHeight, true, JImage::SCALE_OUTSIDE);
                         $resized->toFile(constant('PROFILEPICTURE_PATH_' . $size) . $pp_filename);
                         $savedNewProfilePicture = true;
                     } else {
                         $resized = $profilepicture->resize($size, $size, true, JImage::SCALE_INSIDE);
                         $resized->toFile(constant('PROFILEPICTURE_PATH_' . $size) . $pp_filename);
                         $savedNewProfilePicture = true;
                     }
                 }
             }
         }
         // Remove profile picture if an existing profile picture is
         // checked for removal or a new picture has been uploaded
         // replacing the existing picture.
         if (isset($userId) && (!empty($post['profilepicture']['file']['remove']) || $savedNewProfilePicture)) {
             $this->removeProfilePicture($userId);
         }
         if ($userId && $savedNewProfilePicture) {
             try {
                 $db = JFactory::getDbo();
                 $query = $db->getQuery(true);
                 $query = $db->getQuery(true);
                 $query->insert('#__user_profiles')->columns('user_id, profile_key, profile_value, ordering')->values($userId . ', ' . $db->quote(plgUserProfilePicture::PROFILE_KEY) . ', ' . $db->quote($pp_filename) . ', ' . ' 1');
                 $db->setQuery($query);
                 if (!$db->query()) {
                     throw new Exception($db->getErrorMsg());
                 }
             } catch (JException $e) {
                 $this->_subject->setError($e->getMessage());
                 return false;
             }
         }
         return true;
     } else {
         return true;
     }
 }
Ejemplo n.º 23
0
 /**
  * Crop the image and generates smaller ones.
  *
  * @param string $file
  * @param array $options
  *
  * @throws Exception
  *
  * @return array
  */
 public function cropImage($file, $options)
 {
     // Resize image
     $image = new JImage();
     $image->loadFile($file);
     if (!$image->isLoaded()) {
         throw new Exception(JText::sprintf('COM_CROWDFUNDING_ERROR_FILE_NOT_FOUND', $file));
     }
     $destinationFolder = Joomla\Utilities\ArrayHelper::getValue($options, "destination");
     // Generate temporary file name
     $generatedName = new Prism\String();
     $generatedName->generateRandomString(32);
     $imageName = $generatedName . "_image.png";
     $smallName = $generatedName . "_small.png";
     $squareName = $generatedName . "_square.png";
     $imageFile = $destinationFolder . DIRECTORY_SEPARATOR . $imageName;
     $smallFile = $destinationFolder . DIRECTORY_SEPARATOR . $smallName;
     $squareFile = $destinationFolder . DIRECTORY_SEPARATOR . $squareName;
     // Create main image
     $width = Joomla\Utilities\ArrayHelper::getValue($options, "width", 200);
     $width = $width < 25 ? 50 : $width;
     $height = Joomla\Utilities\ArrayHelper::getValue($options, "height", 200);
     $height = $height < 25 ? 50 : $height;
     $left = Joomla\Utilities\ArrayHelper::getValue($options, "x", 0);
     $top = Joomla\Utilities\ArrayHelper::getValue($options, "y", 0);
     $image->crop($width, $height, $left, $top, false);
     // Resize to general size.
     $width = Joomla\Utilities\ArrayHelper::getValue($options, "resize_width", 200);
     $width = $width < 25 ? 50 : $width;
     $height = Joomla\Utilities\ArrayHelper::getValue($options, "resize_height", 200);
     $height = $height < 25 ? 50 : $height;
     $image->resize($width, $height, false);
     // Store to file.
     $image->toFile($imageFile, IMAGETYPE_PNG);
     // Load parameters.
     $params = JComponentHelper::getParams($this->option);
     /** @var  $params Joomla\Registry\Registry */
     // Create small image
     $width = $params->get("image_small_width", 100);
     $height = $params->get("image_small_height", 100);
     $image->resize($width, $height, false);
     $image->toFile($smallFile, IMAGETYPE_PNG);
     // Create square image
     $width = $params->get("image_square_width", 50);
     $height = $params->get("image_square_height", 50);
     $image->resize($width, $height, false);
     $image->toFile($squareFile, IMAGETYPE_PNG);
     $names = array("image" => $imageName, "image_small" => $smallName, "image_square" => $squareName);
     // Remove the temporary file.
     if (is_file($file)) {
         JFile::delete($file);
     }
     return $names;
 }
Ejemplo n.º 24
0
 /**
  * Test the JImage::filter method without a loaded image.
  *
  * @return  void
  *
  * @expectedException  LogicException
  * @since   11.3
  */
 public function testFilterWithoutLoadedImage()
 {
     // Create a new JImage object without loading an image.
     $image = new JImage();
     $image->filter('negate');
 }
Ejemplo n.º 25
0
 /**
  * Upload a pitch image.
  *
  * @param  array $image
  *
  * @throws Exception
  *
  * @return array
  */
 public function uploadPitchImage($image)
 {
     $app = JFactory::getApplication();
     /** @var $app JApplicationSite */
     $uploadedFile = JArrayHelper::getValue($image, 'tmp_name');
     $uploadedName = JArrayHelper::getValue($image, 'name');
     $errorCode = JArrayHelper::getValue($image, 'error');
     // Load parameters.
     $params = JComponentHelper::getParams($this->option);
     /** @var  $params Joomla\Registry\Registry */
     $destFolder = JPath::clean(JPATH_ROOT . DIRECTORY_SEPARATOR . $params->get("images_directory", "images/crowdfunding"));
     $tmpFolder = $app->get("tmp_path");
     // Joomla! media extension parameters
     $mediaParams = JComponentHelper::getParams("com_media");
     /** @var  $mediaParams Joomla\Registry\Registry */
     jimport("itprism.file");
     jimport("itprism.file.uploader.local");
     jimport("itprism.file.validator.size");
     jimport("itprism.file.validator.image");
     jimport("itprism.file.validator.server");
     $file = new ITPrismFile();
     // Prepare size validator.
     $KB = 1024 * 1024;
     $fileSize = (int) $app->input->server->get('CONTENT_LENGTH');
     $uploadMaxSize = $mediaParams->get("upload_maxsize") * $KB;
     $sizeValidator = new ITPrismFileValidatorSize($fileSize, $uploadMaxSize);
     // Prepare server validator.
     $serverValidator = new ITPrismFileValidatorServer($errorCode, array(UPLOAD_ERR_NO_FILE));
     // Prepare image validator.
     $imageValidator = new ITPrismFileValidatorImage($uploadedFile, $uploadedName);
     // Get allowed mime types from media manager options
     $mimeTypes = explode(",", $mediaParams->get("upload_mime"));
     $imageValidator->setMimeTypes($mimeTypes);
     // Get allowed image extensions from media manager options
     $imageExtensions = explode(",", $mediaParams->get("image_extensions"));
     $imageValidator->setImageExtensions($imageExtensions);
     $file->addValidator($sizeValidator)->addValidator($imageValidator)->addValidator($serverValidator);
     // Validate the file
     if (!$file->isValid()) {
         throw new RuntimeException($file->getError());
     }
     // Generate temporary file name
     $ext = JString::strtolower(JFile::makeSafe(JFile::getExt($image['name'])));
     jimport("itprism.string");
     $generatedName = new ITPrismString();
     $generatedName->generateRandomString(32);
     $tmpDestFile = $tmpFolder . DIRECTORY_SEPARATOR . $generatedName . "." . $ext;
     // Prepare uploader object.
     $uploader = new ITPrismFileUploaderLocal($uploadedFile);
     $uploader->setDestination($tmpDestFile);
     // Upload temporary file
     $file->setUploader($uploader);
     $file->upload();
     // Get file
     $tmpDestFile = $file->getFile();
     if (!is_file($tmpDestFile)) {
         throw new Exception('COM_CROWDFUNDING_ERROR_FILE_CANT_BE_UPLOADED');
     }
     // Resize image
     $image = new JImage();
     $image->loadFile($tmpDestFile);
     if (!$image->isLoaded()) {
         throw new Exception(JText::sprintf('COM_CROWDFUNDING_ERROR_FILE_NOT_FOUND', $tmpDestFile));
     }
     $imageName = $generatedName . "_pimage.png";
     $imageFile = JPath::clean($destFolder . DIRECTORY_SEPARATOR . $imageName);
     // Create main image
     $width = $params->get("pitch_image_width", 600);
     $height = $params->get("pitch_image_height", 400);
     $image->resize($width, $height, false);
     $image->toFile($imageFile, IMAGETYPE_PNG);
     // Remove the temporary
     if (is_file($tmpDestFile)) {
         JFile::delete($tmpDestFile);
     }
     return $imageName;
 }
Ejemplo n.º 26
0
	/**
	 * Allows public access to protected method.
	 *
	 * @param   mixed  $width   The input width value to sanitize.
	 * @param   mixed  $height  The input height value for reference.
	 *
	 * @return  integer
	 *
	 * @since   11.3
	 */
	public function sanitizeWidth($width, $height)
	{
		return parent::sanitizeWidth($width, $height);
	}
Ejemplo n.º 27
0
 /**
  * Generate the file preview. U
  */
 private function _generatePreview()
 {
     // Create thumbnail (for jpeg) if there is none
     $supportedImageMine = array('image/png', 'image/jpeg');
     if (in_array($this->mimetype, $supportedImageMine)) {
         jimport('joomla.image');
         require_once JPATH_ROOT . DS . 'libraries' . DS . 'joomla' . DS . 'image' . DS . 'filters' . DS . 'sharpen.php';
         $image = new JImage(JPATH_ROOT . DS . $this->path);
         if (!$image->isLoaded()) {
             return false;
         }
         $pathinfo = pathinfo($this->path);
         $width = $image->getWidth();
         $height = $image->getHeight();
         // Generate preview
         if ($width > 640) {
             $height = 640 / $width * $height;
             $width = 640;
         }
         if ($height > 640) {
             $width = 640 / $height * $width;
             $height = 640;
         }
         // Resize for preview
         $image = $image->resize($width, $height);
         $previewPath = JPATH_ROOT . DS . $pathinfo['dirname'] . DS . $pathinfo['filename'] . '_preview.jpg';
         $image->filter('sharpen');
         $image->toFile($previewPath, IMAGETYPE_JPEG, array('quality' => 90));
         // crop them to predefined aspect ratio if necessary
         // and the resize them
         if ($width / $height > 1.3) {
             $image = $image->crop($height * 1.3, $height, ($width - $height * 1.3) / 2, 0);
             $image = $image->resize(StreamTableFile::PHOTO_THUMB_WIDTH, StreamTableFile::PHOTO_THUMB_HEIGHT);
         } elseif ($height / $width > 1.3) {
             $image = $image->crop($width, $width * 1.3, 0, $height - $width * 1.3);
             $image = $image->resize(StreamTableFile::PHOTO_THUMB_HEIGHT, StreamTableFile::PHOTO_THUMB_WIDTH);
         } else {
             $image = $image->resize(StreamTableFile::PHOTO_THUMB_WIDTH, StreamTableFile::PHOTO_THUMB_WIDTH);
         }
         $thumbPath = JPATH_ROOT . DS . $pathinfo['dirname'] . DS . $pathinfo['filename'] . '_thumb.jpg';
         $image->toFile($thumbPath, IMAGETYPE_JPEG, array('quality' => 100));
         if (JFile::exists($thumbPath)) {
             $this->setParam('has_preview', true);
             $this->setParam('thumb_path', $pathinfo['dirname'] . DS . $pathinfo['filename'] . '_thumb.jpg');
             $this->setParam('preview_path', $pathinfo['dirname'] . DS . $pathinfo['filename'] . '_preview.jpg');
             $this->setParam('width', $width);
             $this->setParam('height', $height);
         }
     } else {
         $this->setParam('has_preview', false);
         $this->setParam('thumb_path', '');
         $this->setParam('preview_path', '');
         $this->setParam('width', '');
         $this->setParam('height', '');
     }
 }
Ejemplo n.º 28
0
 /**
  * Метод для генерации изображения
  * @param string $url    УРЛ изображения
  * @param string $file_output    Название изображения для сохранения
  * @param int $w_o, $h_o    Максимальные ширина и высота генерируемого изображения
  * @return string    Результат выполнения false - изображения нет, up - успешно записали и нужно обновиться, ok - изображение существует и не требует модификации
  */
 private function createAvatar($file_input, $file_output, $width, $height)
 {
     //Если источник не указан
     if (!$file_input) {
         return false;
     }
     //папка для работы с изображением и качество сжатия
     $rootfolder = $this->params->get('rootfolder', 'images/avatar');
     $img_quality = $this->params->get('img_quality', 80);
     //если папка для складирования аватаров не существует создаем ее
     if (!JFolder::exists(JPATH_ROOT . '/' . $rootfolder)) {
         JFolder::create(JPATH_ROOT . '/' . $rootfolder);
         file_put_contents(JPATH_ROOT . '/' . $rootfolder . '/index.html', '');
     }
     // Генерируем имя tmp-изображения
     $tmp_name = JPATH_ROOT . '/tmp/' . $file_output;
     $output_path = JPATH_ROOT . '/' . $rootfolder . '/';
     $output_name = $output_path . $file_output;
     //заузка файла
     $uploaded = $this->upload($file_input, $tmp_name);
     if ($uploaded) {
         $image = new JImage($tmp_name);
         $image->resize($width, $height, false, JImage::SCALE_INSIDE);
         $image->toFile($output_name, IMAGETYPE_JPEG, array('quality' => $img_quality));
         unlink($tmp_name);
     }
     $ret = JFile::exists($output_name) ? true : false;
     return $ret;
 }
Ejemplo n.º 29
0
 function uploadImages($file, $currentImage = null)
 {
     if ($file) {
         $maxSize = 2 * 1024 * 1024;
         $arr = array('image/jpeg', 'image/jpg', 'image/bmp', 'image/gif', 'image/png', 'image/ico');
         // Create folder
         $tzFolder = 'tz_portfolio';
         $tzUserFolder = 'users';
         $tzFolderPath = JPATH_ROOT . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . $tzFolder;
         $tzUserFolderPath = $tzFolderPath . DIRECTORY_SEPARATOR . $tzUserFolder;
         if (!JFolder::exists($tzFolderPath)) {
             JFolder::create($tzFolderPath);
             if (!JFile::exists($tzFolderPath . DIRECTORY_SEPARATOR . 'index.html')) {
                 JFile::write($tzFolderPath . DIRECTORY_SEPARATOR . 'index.html', htmlspecialchars_decode('<!DOCTYPE html><title></title>'));
             }
         }
         if (JFolder::exists($tzFolderPath)) {
             if (!JFolder::exists($tzUserFolderPath)) {
                 JFolder::create($tzUserFolderPath);
                 if (!JFile::exists($tzUserFolderPath . DIRECTORY_SEPARATOR . 'index.html')) {
                     JFile::write($tzUserFolderPath . DIRECTORY_SEPARATOR . 'index.html', htmlspecialchars_decode('<!DOCTYPE html><title></title>'));
                 }
             }
         }
         if (is_array($file)) {
             foreach ($file as $key => $val) {
                 if (is_array($val)) {
                     foreach ($val as $key2 => $val2) {
                         $file[$key] = $val2;
                     }
                 }
             }
             //Upload image
             if (in_array($file['type'], $arr)) {
                 if ($file['size'] <= $maxSize) {
                     $desFileName = 'user_' . time() . uniqid() . '.' . JFile::getExt($file['name']);
                     $desPath = $tzUserFolderPath . DIRECTORY_SEPARATOR . $desFileName;
                     if (JFile::exists($file['tmp_name'])) {
                         if (!JFile::copy($file['tmp_name'], $desPath)) {
                             JError::raiseNotice(300, JText::_('COM_TZ_PORTFOLIO_CAN_NOT_UPLOAD_FILE'));
                         }
                         $image = new JImage();
                         $image->loadFile($desPath);
                         $params = JComponentHelper::getParams('com_tz_portfolio');
                         if ($params->get('tz_user_image_width', 100)) {
                             $width = $params->get('tz_user_image_width', 100);
                         }
                         $height = ceil($image->getHeight() * $width / $image->getWidth());
                         $image = $image->resize($width, $height);
                         $type = $this->_getImageType($file['name']);
                         $image->toFile($desPath, $type);
                         $this->deleteImages($currentImage);
                         return 'media/' . $tzFolder . '/' . $tzUserFolder . '/' . $desFileName;
                     }
                 } else {
                     JError::raiseNotice(300, JText::_('COM_TZ_PORTFOLIO_IMAGE_SIZE_TOO_LARGE'));
                 }
             } else {
                 JError::raiseNotice(300, JText::_('COM_TZ_PORTFOLIO_IMAGE_FILE_NOT_SUPPORTED'));
             }
         } else {
             tzportfolioimport('HTTPFetcher');
             tzportfolioimport('readfile');
             $image = new Services_Yadis_PlainHTTPFetcher();
             $image = $image->get($file);
             if (in_array($image->headers['Content-Type'], $arr)) {
                 if ($image->headers['Content-Length'] > $maxSize) {
                     $this->deleteImages($currentImage);
                     $desFileName = 'user_' . time() . uniqid() . '.' . str_replace('image/', '', $image->headers['Content-Type']);
                     $desPath = $tzUserFolderPath . DIRECTORY_SEPARATOR . $desFileName;
                     if (JFolder::exists($tzFolderPath)) {
                         if (!JFile::write($desPath, $image->body)) {
                             $this->setError(JText::_('COM_TZ_PORTFOLIO_CAN_NOT_UPLOAD_FILE'));
                             return false;
                         }
                         return 'media/' . $tzFolder . '/' . $tzUserFolder . '/' . $desFileName;
                     }
                 } else {
                     JError::raiseNotice(300, JText::_('COM_TZ_PORTFOLIO_IMAGE_SIZE_TOO_LARGE'));
                 }
             } else {
                 JError::raiseNotice(300, JText::_('COM_TZ_PORTFOLIO_IMAGE_FILE_NOT_SUPPORTED'));
             }
         }
     }
     if ($currentImage) {
         return $currentImage;
     }
     return '';
 }
Ejemplo n.º 30
0
 function uploadImages($file)
 {
     if ($file) {
         $maxSize = 2 * 1024 * 1024;
         $arr = array('image/jpeg', 'image/jpg', 'image/bmp', 'image/gif', 'image/png', 'image/ico');
         // Create folder
         $tzFolder = 'tz_pinboard';
         $tzUserFolder = 'users';
         $tzFolderPath = JPATH_ROOT . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . $tzFolder;
         $tzUserFolderPath = $tzFolderPath . DIRECTORY_SEPARATOR . $tzUserFolder;
         if (!JFolder::exists($tzFolderPath)) {
             JFolder::create($tzFolderPath);
             if (!JFile::exists($tzFolderPath . DIRECTORY_SEPARATOR . 'index.html')) {
                 JFile::write($tzFolderPath . DIRECTORY_SEPARATOR . 'index.html', htmlspecialchars_decode('<!DOCTYPE html><title></title>'));
             }
         }
         if (JFolder::exists($tzFolderPath)) {
             if (!JFolder::exists($tzUserFolderPath)) {
                 JFolder::create($tzUserFolderPath);
                 if (!JFile::exists($tzUserFolderPath . DIRECTORY_SEPARATOR . 'index.html')) {
                     JFile::write($tzUserFolderPath . DIRECTORY_SEPARATOR . 'index.html', htmlspecialchars_decode('<!DOCTYPE html><title></title>'));
                 }
             }
         }
         if (is_array($file)) {
             foreach ($file as $key => $val) {
                 if (is_array($val)) {
                     foreach ($val as $key2 => $val2) {
                         $file[$key] = $val2;
                     }
                 }
             }
             //Upload image
             if (!in_array($file['type'], $arr)) {
                 $this->setError(JText::_('Invalid file type'));
                 return false;
             }
             if ($file['size'] > $maxSize) {
                 $this->setError(JText::_('This file size too large'));
                 return false;
             }
             $desFileName = 'user_' . time() . uniqid() . '.' . JFile::getExt($file['name']);
             $desPath = $tzUserFolderPath . DIRECTORY_SEPARATOR . $desFileName;
             if (JFile::exists($file['tmp_name'])) {
                 if (!JFile::copy($file['tmp_name'], $desPath)) {
                     $this->setError(JText::_('Can not upload file'));
                     return false;
                 }
                 $image = new JImage();
                 $image->loadFile($desPath);
                 $params = JComponentHelper::getParams('com_tz_pinboard');
                 if ($params->get('tz_user_image_width', 100)) {
                     $width = $params->get('tz_user_image_width', 100);
                 }
                 $height = ceil($image->getHeight() * $width / $image->getWidth());
                 $image = $image->resize($width, $height);
                 $type = $this->_getImageType($file['name']);
                 $image->toFile($desPath, $type);
                 return 'media/' . $tzFolder . '/' . $tzUserFolder . '/' . $desFileName;
             }
         } else {
             require_once JPATH_COMPONENT . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'HTTPFetcher.php';
             require_once JPATH_COMPONENT . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'readfile.php';
             $image = new Services_Yadis_PlainHTTPFetcher();
             $image = $image->get($file);
             if (!in_array($image->headers['Content-Type'], $arr)) {
                 $this->setError(JText::_('Invalid file'));
                 return false;
             }
             if ($image->headers['Content-Length'] > $maxSize) {
                 $this->setError(JText::_('This file size too large'));
                 return false;
             }
             $desFileName = 'user_' . time() . uniqid() . '.' . str_replace('image/', '', $image->headers['Content-Type']);
             $desPath = $tzUserFolderPath . DIRECTORY_SEPARATOR . $desFileName;
             if (JFolder::exists($tzFolderPath)) {
                 if (!JFile::write($desPath, $image->body)) {
                     $this->setError(JText::_('Can not upload file'));
                     return false;
                 }
                 return 'media/' . $tzFolder . '/' . $tzUserFolder . '/' . $desFileName;
             }
         }
     }
     return true;
 }