The code is heavily commented and generates no warnings/errors/notices when PHP's error reporting level is set to E_ALL. With this library you can rescale, flip, rotate and crop images. It supports loading and saving images in the GIF, JPEG and PNG formats and preserves transparency for GIF, PNG and PNG24. The cool thing about it is that it can resize images to exact given width and height and still maintain aspect ratio. Visit {@link http://stefangabos.ro/php-libraries/zebra-image/} for more information. For more resources visit {@link http://stefangabos.ro/}
Example #1
0
 static function thumb($name, $filename, $new_w, $new_h)
 {
     # create a new instance of the class
     $image = new Zebra_Image();
     # indicate a source image (a GIF, PNG or JPEG file)
     $image->source_path = $name;
     # indicate a target image
     # note that there's no extra property to set in order to specify the target
     # image's type -simply by writing '.jpg' as extension will instruct the script
     # to create a 'jpg' file
     $image->target_path = $filename;
     # since in this example we're going to have a jpeg file, let's set the output
     # image's quality (95% has no visible effect but saves some bytes)
     $image->jpeg_quality = 95;
     # some additional properties that can be set
     # read about them in the documentation
     $image->preserve_aspect_ratio = true;
     $image->enlarge_smaller_images = false;
     $image->preserve_time = true;
     # resize the image to at best 100x100 pixels by using the "not boxed" method
     # (read more in the overview section or in the documentation)
     # and if there is an error, check what the error is about
     if (!$image->resize($new_w, $new_h, ZEBRA_IMAGE_NOT_BOXED, -1)) {
         # only admins will see these errors
         if (JFactory::getUser()->authorise('core.manage')) {
             # if there was an error, let's see what the error is about
             switch ($image->error) {
                 case 1:
                     echo 'Source file could not be found!';
                     break;
                 case 2:
                     echo 'Source file is not readable!';
                     break;
                 case 3:
                     echo 'Could not write target file!';
                     break;
                 case 4:
                     echo 'Unsupported source file format!';
                     break;
                 case 5:
                     echo 'Unsupported target file format!';
                     break;
                 case 6:
                     echo 'GD library version does not support target file format!';
                     break;
                 case 7:
                     echo 'GD library is not installed!';
                     break;
             }
         }
         # if no errors
     } else {
         echo '';
     }
 }
function laborator_img($url, $width = 0, $height = 0, $crop = FALSE)
{
    $upload_dir = wp_upload_dir();
    $post_thumbnail_url = '';
    $wpurl = site_url();
    $baseurl = $upload_dir['baseurl'];
    # Get Predefined Image Size
    if (is_string($width)) {
        $image_size = LaboratorImageSizes::get_img_size($width);
        extract($image_size);
    }
    # Get from post ID
    if (is_numeric($url)) {
        $post_thumbnail_id = get_post_thumbnail_id($url);
        if ($post_thumbnail_id) {
            $post_thumbnail_url = wp_get_attachment_url($post_thumbnail_id);
        } else {
            return '';
        }
    } else {
        $post_thumbnail_url = $url;
    }
    # Verify if its on this server
    if (strpos($post_thumbnail_url, $wpurl) != -1) {
        $relative_path = str_replace($wpurl, '', $post_thumbnail_url);
        $relative_path = ltrim($relative_path, '/');
        $absolute_path = ABSPATH . $relative_path;
        $basename = basename($absolute_path);
        # New Image Name
        $thumbnail_name = 'labimg_' . ($width ? "{$width}_" : '') . ($height ? "{$height}_" : '') . ($crop ? "1_" : '') . $basename;
        $thumbnail_path = dirname($absolute_path) . '/' . $thumbnail_name;
        $thumbnail_url = dirname($post_thumbnail_url) . '/' . $thumbnail_name;
        # Check if cached
        if (file_exists($thumbnail_path)) {
            return $thumbnail_url;
        }
        # Create File
        if (file_exists($absolute_path)) {
            # Generate Img
            $img = new Zebra_Image();
            $img->source_path = $absolute_path;
            $img->target_path = $thumbnail_path;
            $img->enlarge_smaller_images = TRUE;
            $img->preserve_aspect_ratio = TRUE;
            if ($crop) {
                $img->resize($width, $height, ZEBRA_IMAGE_CROP_CENTER, '#FFF');
            } else {
                $img->resize($width, $height, ZEBRA_IMAGE_NOT_BOXED, '#FFF');
            }
            return $thumbnail_url;
        }
    }
    return '';
}
Example #3
0
 private function _uploadImage($sName)
 {
     if (isset($_FILES[$sName]) && $_FILES[$sName]['error'] == 0) {
         require_once ROOT . '/lib/Zebra_Image.php';
         $oZebra = new \Zebra_Image();
         $sImage = $this->config->templates->path . '/img/u/' . $_FILES[$sName]['name'];
         $oZebra->preserve_aspect_ratio = false;
         $oZebra->source_path = $_FILES[$sName]['tmp_name'];
         $oZebra->target_path = ROOT . $sImage;
         $oZebra->resize($this->config->image->width, $this->config->image->height, ZEBRA_IMAGE_BOXED);
         return $sImage;
     } else {
         return false;
     }
 }
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate($id)
 {
     Yii::import('application.libs.Zebra_Image.Zebra_Image');
     $model = $this->loadModel($id);
     if (isset($_POST['Residents'])) {
         $oldProfilePic = $model->profile_picture;
         $model->attributes = $_POST['Residents'];
         $model->scenario = "update";
         if (!empty($model->profile_picture) && strpos($model->profile_picture, ":image")) {
             /*process profile picture*/
             $foto = str_replace('data:image/png;base64,', '', $model->profile_picture);
             $foto = str_replace(' ', '+', $foto);
             $data_foto = base64_decode($foto);
             $currentUserFileName = sprintf("%s_%s_%s_%s", $model->firstname, $model->middle_name, $model->lastname, uniqid());
             $filename = $currentUserFileName . '.png';
             $filepath = YiiBase::getPathOfAlias("webroot.themes.abound.uploads") . '/' . $filename;
             $writeToDisk = file_put_contents($filepath, $data_foto);
             //remove extra space
             //
             $image = new Zebra_Image();
             $image->source_path = $filepath;
             $image->target_path = $filepath;
             $image->jpeg_quality = 100;
             $image->preserve_aspect_ratio = true;
             $image->enlarge_smaller_images = true;
             $image->preserve_time = true;
             $image->resize(300, 300, ZEBRA_IMAGE_CROP_TOPLEFT);
             //
             //
             $model->profile_picture = basename($filepath);
         } else {
             $model->profile_picture = $oldProfilePic;
         }
         /*proceed saving*/
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         } else {
             Yii::app()->user->setFlash("error", CHtml::errorSummary($model));
             $this->redirect(array('update', 'id' => $model->id));
         }
     }
     $this->render('update', array('residentRecord' => $model));
 }
Example #5
0
 public function imageResize($source, $destination, $width, $height, $boxedType)
 {
     $image = new Zebra_Image();
     $image->source_path = $source;
     $image->target_path = $destination;
     $image->jpeg_quality = 90;
     $image->preserve_aspect_ratio = true;
     $image->enlarge_smaller_images = true;
     $image->preserve_time = true;
     if (!isset($boxedType)) {
         $boxedType = ZEBRA_IMAGE_NOT_BOXED;
     }
     if (!$image->resize($width, $height, $boxedType, '#FFFFFF')) {
         // if there was an error, let's see what the error is about
         switch ($image->error) {
             case 1:
                 echo 'Source file could not be found!';
                 break;
             case 2:
                 echo 'Source file is not readable!';
                 break;
             case 3:
                 echo 'Could not write target file!';
                 break;
             case 4:
                 echo 'Unsupported source file format!';
                 break;
             case 5:
                 echo 'Unsupported target file format!';
                 break;
             case 6:
                 echo 'GD library version does not support target file format!';
                 break;
             case 7:
                 echo 'GD library is not installed!';
                 break;
         }
         // if no errors
     } else {
         echo 'Success!';
     }
 }
 public function actionIndex()
 {
     Yii::import('application.libs.Zebra_Image.Zebra_Image');
     $residentRecord = new Residents("createNewRecord");
     if (Yii::app()->request->isPostRequest && $_POST['Residents']) {
         $oldProfilePic = $residentRecord->profile_picture;
         $residentRecord->attributes = $_POST['Residents'];
         if ($residentRecord->validate()) {
             //Decode with base64
             if (isset($residentRecord->profile_picture) && !empty($residentRecord->profile_picture) && !is_null($residentRecord->profile_picture)) {
                 $foto = str_replace('data:image/png;base64,', '', $residentRecord->profile_picture);
                 $foto = str_replace(' ', '+', $foto);
                 $data_foto = base64_decode($foto);
                 //Set photo filename
                 $currentUserFileName = sprintf("%s_%s_%s_%s", $residentRecord->firstname, $residentRecord->middle_name, $residentRecord->lastname, uniqid());
                 $filename = $currentUserFileName . '.png';
                 $filepath = YiiBase::getPathOfAlias("webroot.themes.abound.uploads") . '/' . $filename;
                 $writeToDisk = file_put_contents($filepath, $data_foto);
                 //remove extra space
                 $image = new Zebra_Image();
                 $image->source_path = $filepath;
                 $image->target_path = $filepath;
                 $image->jpeg_quality = 100;
                 $image->preserve_aspect_ratio = true;
                 $image->enlarge_smaller_images = true;
                 $image->preserve_time = true;
                 $image->resize(300, 300, ZEBRA_IMAGE_CROP_TOPLEFT);
                 $residentRecord->profile_picture = $filepath;
             }
             if ($residentRecord->save()) {
                 Yii::app()->user->setFlash("success", "<strong>Record Saved ! </strong>New Resident Record Created");
                 $this->redirect(array('/register'));
             }
         } else {
             Yii::app()->user->setFlash("error", CHtml::errorSummary($residentRecord));
         }
     }
     $this->render('index', compact('residentRecord'));
 }
Example #7
0
 /**
  * Resize and/or crop an image
  *
  * @param $path
  * @param int $width
  * @param int $height
  * @param null $action
  * @return mixed
  * @throws InternalErrorException
  */
 public function resizeCrop($path, $width = 0, $height = 0, $action = null)
 {
     ini_set("memory_limit", "10000M");
     App::import('Vendor', 'Gallery.Zebra_Image', array('file' => 'ZebraImage.class.php'));
     # Flag
     $delete_png = false;
     $image = new Zebra_Image();
     # Load image
     $image->source_path = $path;
     # The target will be the same image
     $target = $path;
     # Get File Extension
     $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
     # Convert PNG files to JPG if configured on bootstrap.php
     if (Configure::read('GalleryOptions.Pictures.png2jpg') && $ext == "png") {
         # Flag to check must delete the png file
         $delete_png = true;
         # Store PNG file path to delete later
         $png_file = $target;
         # Update target path with JPG extension
         $target = str_replace(array('.png', '.PNG'), '.jpg', $path);
     }
     # The target will be the same image
     $image->target_path = $target;
     # JPG quality
     $image->jpeg_quality = Configure::read('GalleryOptions.Pictures.jpg_quality');
     # Extra configs
     $image->preserve_aspect_ratio = true;
     $image->enlarge_smaller_images = true;
     $image->preserve_time = true;
     if ($action == "crop") {
         $action = ZEBRA_IMAGE_CROP_CENTER;
     }
     if (!$image->resize($width, $height, $action)) {
         // if there was an error, let's see what the error is about
         switch ($image->error) {
             case 1:
                 throw new InternalErrorException('Source file could not be found!');
                 break;
             case 2:
                 throw new InternalErrorException('Source file is not readable!');
                 break;
             case 3:
                 throw new InternalErrorException('Could not write target file!');
                 break;
             case 4:
                 throw new InternalErrorException('Unsupported source file format!');
                 break;
             case 5:
                 throw new InternalErrorException('Unsupported target file format!');
                 break;
             case 6:
                 throw new InternalErrorException('GD library version does not support target file format!');
                 break;
             case 7:
                 throw new InternalErrorException('GD library is not installed!');
                 break;
             case 8:
                 throw new InternalErrorException('"chmod" command is disabled via configuration!');
                 break;
         }
     } else {
         # Delete PNG file if needed
         if ($delete_png) {
             unlink($png_file);
         }
         return $target;
     }
 }
Example #8
0
<?php

$imgCrop = new Zebra_Image();
$imgCrop->source_path = "../upload/temporal_{$_REQUEST['imagen']}";
$imgCrop->target_path = "../upload/temporal_{$_REQUEST['imagen']}";
$imgCrop->jpeg_quality = 100;
$imgCrop->preserve_aspect_ratio = true;
$imgCrop->enlarge_smaller_images = true;
$imgCrop->preserve_time = true;
//SI EL CROP SE REALIZO CORRECTAMENTE RENOMBRAMOS LA IMAGEN
if ($imgCrop->crop(intval($_REQUEST[jrac_crop_x]), intval($_REQUEST[jrac_crop_y]), intval($_REQUEST[jrac_crop_width]) + intval($_REQUEST[jrac_crop_x]), intval($_REQUEST[jrac_crop_height]))) {
    if (rename("../upload/temporal_{$_REQUEST['imagen']}", "../upload/{$_REQUEST['imagen']}")) {
        $tiempoRedir = 5;
        ?>
        <html>
            <head>
                <title>Redimencion de imagen</title>
                <meta http-equiv="refresh" content="<?php 
        echo $tiempoRedir;
        ?>
; url=<?php 
        echo "../index.php?module=EDITA_EDITAR_IMAGEN&action=index&imagen={$_REQUEST['imagen']}&resultado=ok";
        ?>
" />
                <link href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css' rel='stylesheet'  type='text/css'/>
                <script src="https://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
                <script>
                    $(document).ready(function () {
                        var count = <?php 
        echo $tiempoRedir;
        ?>
 public function upload_image($files_instance)
 {
     if (!function_exists('wp_handle_upload')) {
         include_once ABSPATH . 'wp-admin/includes/file.php';
     }
     # Do Some Tricks...
     $_POST['action'] = 'simplead_handle_upload';
     $override['test_form'] = false;
     $override['action'] = 'simplead_handle_upload';
     $image_path = wp_handle_upload($files_instance, $override);
     $original_image = $image_path['file'];
     $images = array();
     if ($original_image) {
         // Generate Sizes
         foreach ($this->ad_sizes as $prefix => $size) {
             $w = $size[0];
             $h = $size[1];
             $new_file = dirname($file) . "/{$prefix}_" . basename($file);
             #$thumb = image_resize($original_image, $w, $h, true);
             $thumb = dirname($original_image) . "/{$prefix}_" . basename($original_image);
             # Zebra Image Ressize
             $img = new Zebra_Image();
             $img->enlarge_smaller_images = FALSE;
             $img->source_path = $original_image;
             $img->target_path = $thumb;
             $img->resize($w, $h, ZEBRA_IMAGE_CROP_CENTER, '#FFF');
             $images[$prefix] = _wp_relative_upload_path($thumb);
         }
         $images['original'] = _wp_relative_upload_path($original_image);
     }
     return $images;
 }
Example #10
0
function cropImage(&$image, $request)
{
    if (!$image['result']) {
        return;
    }
    $cropWidthCount = array_key_exists('cropWidthCount', $request) ? $request['cropWidthCount'] : false;
    $cropHeightCount = array_key_exists('cropHeightCount', $request) ? $request['cropHeightCount'] : false;
    if ($cropWidthCount === false && $cropHeightCount === false) {
        return;
    }
    list($width, $height) = getimagesize($image['url']);
    for ($h = 0; $h < $cropHeightCount; ++$h) {
        for ($w = 0; $w < $cropWidthCount; ++$w) {
            $zebraImage = new Zebra_Image();
            $zebraImage->source_path = $image['url'];
            $zebraImage->target_path = dirname($image['url']) . DIRECTORY_SEPARATOR . basename($image['url'], '.' . pathinfo($image['url'], PATHINFO_EXTENSION)) . "_{$w}_{$h}" . '.' . pathinfo($image['url'], PATHINFO_EXTENSION);
            $zebraImage->jpeg_quality = 100;
            $image['result'] = $zebraImage->crop(($w + 0) * $width / $cropWidthCount, ($h + 0) * $height / $cropHeightCount, ($w + 1) * $width / $cropWidthCount, ($h + 1) * $height / $cropHeightCount);
            $image['status'] = extractZebraError($zebraImage);
            if (!array_key_exists('crop', $image)) {
                $image['crop'] = array();
            }
            if (!array_key_exists($h, $image['crop'])) {
                $image['crop'][$h] = array();
            }
            $image['crop'][$h][$w] = array('url' => $zebraImage->target_path);
        }
    }
}
Example #11
0
             break;
         case 6:
             echo 'GD library version does not support target file format!';
             break;
         case 7:
             echo 'GD library is not installed!';
             break;
         case 8:
             echo '"chmod" command is disabled via configuration!';
             break;
     }
 }
 // include the class
 require '../Zebra_Image.php';
 // create a new instance of the class
 $image = new Zebra_Image();
 // set this to TRUE if you work on images uploaded by users
 // (see http://stefangabos.ro/wp-content/docs/Zebra_Image/Zebra_Image/Zebra_Image.html#var$auto_handle_exif_orientation)
 //$auto_handle_exif_orientation = true;
 // indicate a source image
 $image->source_path = 'images/transparent-png24.png';
 /**
  *
  *  THERE'S NO NEED TO EDIT BEYOUND THIS POINT
  *
  */
 $ext = substr($image->source_path, strrpos($image->source_path, '.') + 1);
 // indicate a target image
 $image->target_path = 'results/resize.' . $ext;
 // resize
 // and if there is an error, show the error message
Example #12
0
<?php

//SI EL ROTAR ES MAYOR A 0 SE ROTA DE LO CONTRARIO BRINCAMOS A HACER CROP
if ($_REQUEST[rotar] > 0) {
    $imgRotate = new Zebra_Image();
    $imgRotate->source_path = "../upload/temporal_{$_REQUEST['imagen']}";
    $imgRotate->target_path = "../upload/temporal_{$_REQUEST['imagen']}";
    $imgRotate->jpeg_quality = 100;
    $imgRotate->preserve_aspect_ratio = true;
    $imgRotate->enlarge_smaller_images = true;
    $imgRotate->preserve_time = true;
    if ($imgRotate->rotate(intval($_REQUEST[rotar]))) {
        require_once './crop.php';
    } else {
        switch ($imgRotate->error) {
            case 1:
                echo 'Source file could not be found!';
                break;
            case 2:
                echo 'Source file is not readable!';
                break;
            case 3:
                echo 'Could not write target file!';
                break;
            case 4:
                echo 'Unsupported source file format!';
                break;
            case 5:
                echo 'Unsupported target file format!';
                break;
            case 6:
 public function generate_thumbnails($image_path, $image_sizes)
 {
     $files = array();
     # Checking if Image exists
     if (!file_exists($image_path)) {
     }
     #return array();
     $files['original'] = str_replace(ABSPATH, '', $image_path);
     $image_dir = dirname($image_path) . '/';
     $image_name = basename($image_path);
     $image_size = getimagesize($image_path);
     # Create Thumbnails
     foreach ($image_sizes as $prefix => $size) {
         $thumbnail_name = $prefix . $image_name;
         $thumbnail_path = $image_dir . $thumbnail_name;
         $width = $size[0];
         $height = $size[1];
         $crop = isset($size[2]);
         $boxed = isset($size[3]) ? $size[3] : 0;
         # Boxed to width and height
         # Resize only one dimension
         if ($width <= 0 || $height <= 0) {
             if ($height <= 0) {
                 # Resize by Width
                 $ratio = $width / $image_size[0];
                 $new_width = $width;
                 $new_height = $image_size[1] * $ratio;
             } else {
                 # Resize by Height
                 $ratio = $height / $image_size[1];
                 $new_width = $image_size[0] * $ratio;
                 $new_height = $height;
             }
             $width = $new_width;
             $height = $new_height;
         }
         # Rresize Image
         /* 
         	DEPRECATED METHOD
         	$thumbnail_path = image_resize($image_path, $width, $height, $crop, '', $thumbnail_path);
         */
         # Resize Image Using Zebra_Image Library
         $img = new Zebra_Image();
         $thumbnail_path = dirname($image_path) . "/{$prefix}_" . basename($image_path);
         $img->source_path = $image_path;
         $img->target_path = $thumbnail_path;
         if ($crop) {
             switch ($boxed) {
                 // Do not enlarge Smaller Images
                 case 2:
                     $img->enlarge_smaller_images = FALSE;
                     $img->resize($width, $height, ZEBRA_IMAGE_BOXED, '#FFF');
                     break;
                     // Fit images to box size
                 // Fit images to box size
                 case 1:
                 case TRUE:
                     $img->resize($width, $height, ZEBRA_IMAGE_BOXED, '#FFF');
                     break;
                     // Crop in the center
                 // Crop in the center
                 default:
                     $img->resize($width, $height, ZEBRA_IMAGE_CROP_CENTER, '#FFF');
             }
         } else {
             $img->preserve_aspect_ratio = TRUE;
             $img->resize($width, $height, ZEBRA_IMAGE_NOT_BOXED, '#FFF');
         }
         $thumbnail_path_relative = str_replace(ABSPATH, '', $thumbnail_path);
         # Remove prefix last character which is _ or -
         $arr_index = preg_replace('/(_|-)$/', '', $prefix);
         $files[$arr_index] = $thumbnail_path_relative;
     }
     return $files;
 }
Example #14
0
<?php

ini_set('display_errors', 'Off');
require_once '../class/Zebra_Image.php';
//SI LA IMAGEN SII SE LE REALIZO RESIZE ENTRA A ESTA FUNCION
if ($_REQUEST[hecerResize] == "1") {
    $img = new Zebra_Image();
    $img->source_path = "../upload/{$_REQUEST['imagen']}";
    $img->target_path = "../upload/temporal_{$_REQUEST['imagen']}";
    $img->sharpen_images = true;
    $img->jpeg_quality = 100;
    $img->preserve_aspect_ratio = true;
    $img->enlarge_smaller_images = true;
    $img->preserve_time = true;
    if ($img->resize(intval($_REQUEST[jrac_image_width]), intval($_REQUEST[jrac_image_height]), ZEBRA_IMAGE_CROP_CENTER)) {
        //PASAMOS A ROTAR LA IMAGEN
        require_once './rotate.php';
    } else {
        switch ($img->error) {
            case 1:
                echo 'Source file could not be found!';
                break;
            case 2:
                echo 'Source file is not readable!';
                break;
            case 3:
                echo 'Could not write target file!';
                break;
            case 4:
                echo 'Unsupported source file format!';
                break;
Example #15
0
$xoops = Xoops::getInstance();
$xoops->logger()->quiet();
$imgPath = Request::getString('img', '');
$imgWidth = Request::getInt('w', 0);
$imgHeight = Request::getInt('h', 0);
if ($imgWidth == 0 && $imgHeight == 0) {
    $configs = $xoops->getModuleConfigs('thumbs');
    $imgWidth = $configs['thumbs_width'];
    $imgHeight = $configs['thumbs_height'];
}
$helper = $xoops->getModuleHelper('thumbs');
$thumbPath = $helper->buildThumbPath($imgPath, $imgWidth, $imgHeight);
$oldUmask = umask(022);
mkdir(dirname($xoops->path($thumbPath)), 0755, true);
umask($oldUmask);
$image = new Zebra_Image();
$image->source_path = $xoops->path($imgPath);
$image->target_path = $xoops->path($thumbPath);
$image->preserve_aspect_ratio = true;
$image->enlarge_smaller_images = false;
$image->preserve_time = true;
if ($image->resize($imgWidth, $imgHeight, ZEBRA_IMAGE_NOT_BOXED, -1)) {
    header("HTTP/1.1 301 Moved Permanently");
    header('Location: ' . $xoops->url($thumbPath));
} else {
    header("HTTP/1.0 404 Not Found");
    // http_response_code(400);
    // exit("Parameter error");
    switch ($image->error) {
        case 1:
            echo 'Source file could not be found!';
Example #16
0
 /**
  * Method to upload a file from client side, storing and making thumbnail for images
  *
  * TODO add token check for file uploading
  *
  * @return JSON
  */
 public function upload()
 {
     // Check for request forgeries
     if (!JSession::checkToken('request')) {
         die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "' . JText::_('JINVALID_TOKEN') . '"}, "id" : "id"}');
     }
     $user = JFactory::getUser();
     $srMedia = SRFactory::get('solidres.media.media');
     $date = JFactory::getDate();
     $model = $this->getModel('media');
     $err = NULL;
     $targetDir = SRPATH_MEDIA_IMAGE_SYSTEM;
     $targetThumbDir = SRPATH_MEDIA_IMAGE_SYSTEM . '/thumbnails';
     static $log;
     if ($log == null) {
         $options['format'] = '{DATE}\\t{TIME}\\t{LEVEL}\\t{CODE}\\t{MESSAGE}';
         $options['text_file'] = 'media.php';
         $log = JLog::addLogger($options);
     }
     JLog::add('Start uploading', JLog::DEBUG);
     if (!$user->authorise('core.create', 'com_solidres')) {
         JError::raiseWarning(403, JText::_('SR_ERROR_CREATE_NOT_PERMITTED'));
         return;
     }
     // HTTP headers for no cache etc
     header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
     header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
     header("Cache-Control: no-store, no-cache, must-revalidate");
     header("Cache-Control: post-check=0, pre-check=0", false);
     header("Pragma: no-cache");
     // 5 minutes execution time
     @set_time_limit(5 * 60);
     // Uncomment this one to fake upload time
     // usleep(5000);
     // Get parameters
     $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
     $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
     $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
     JLog::add('Original file name ' . $fileName, JLog::DEBUG);
     // Clean the fileName for security reasons
     $_FILES['file']['name'] = JFile::makeSafe($_FILES['file']['name']);
     $fileName = $_FILES['file']['name'];
     JLog::add('Cleaned file name ' . $_FILES['file']['name'], JLog::DEBUG);
     // Look for the content type header
     if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
         $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
     }
     if (isset($_SERVER["CONTENT_TYPE"])) {
         $contentType = $_SERVER["CONTENT_TYPE"];
     }
     // Check the target file against our rules to see if it is allow to be uploaded
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     // Do not check the chunk since it is not valid
     if (strpos($contentType, "multipart") !== false && $chunks == 0) {
         if (!SRMediaHelper::canUpload($_FILES['file'], $err)) {
             die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "' . JText::_($err) . '"}, "id" : "id"}');
             //return;
         }
     }
     // Make sure the fileName is unique but only if chunking is disabled
     if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
         $ext = strrpos($fileName, '.');
         $fileName_a = substr($fileName, 0, $ext);
         $fileName_b = substr($fileName, $ext);
         $count = 1;
         while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b)) {
             $count++;
         }
         $fileName = $fileName_a . '_' . $count . $fileName_b;
     }
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     if (strpos($contentType, "multipart") !== false) {
         if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
             // Open temp file
             $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
             if ($out) {
                 // Read binary input stream and append it to temp file
                 $in = fopen($_FILES['file']['tmp_name'], "rb");
                 if ($in) {
                     while ($buff = fread($in, 4096)) {
                         fwrite($out, $buff);
                     }
                 } else {
                     die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                 }
                 fclose($in);
                 fclose($out);
                 @unlink($_FILES['file']['tmp_name']);
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
             }
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
         }
     } else {
         // Open temp file
         $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
         if ($out) {
             // Read binary input stream and append it to temp file
             $in = fopen("php://input", "rb");
             if ($in) {
                 while ($buff = fread($in, 4096)) {
                     fwrite($out, $buff);
                 }
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
             }
             fclose($in);
             fclose($out);
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
         }
     }
     // ONLY PERFORM THESE LAST OPERATIONS WHEN THE FILE IS TOTALLY UPLOADED (NOT PARTLY UPLOADED)
     if ($chunks == 0 || $chunk == $chunks - 1) {
         $uploadedFilePath = $targetDir . '/' . $fileName;
         // Prepare some data for db storing
         $data = array('type' => 'IMAGE', 'value' => $fileName, 'name' => $fileName, 'created_date' => $date->toSql(), 'created_by' => $user->get('id'), 'mime_type' => $srMedia->getMime($uploadedFilePath), 'size' => filesize($uploadedFilePath));
         // Attempt to save the data.
         if (!$model->save($data)) {
             JLog::add('Can not save this file to db: ' . $fileName, JLog::DEBUG);
             die('{"jsonrpc" : "2.0", "error" : {"code": 105, "message": "' . JText::_('SR_ERROR_CAN_NOT_SAVE_DB') . '"}, "id" : "id"}');
         }
         // If media is image, create thumbnail for it
         if (SRMediaHelper::isImage($uploadedFilePath)) {
             $media = new Zebra_Image();
             $media->source_path = $uploadedFilePath;
             $media->target_path = $targetThumbDir . '/1/' . $fileName;
             $media->resize(300, 250);
             $media->target_path = $targetThumbDir . '/2/' . $fileName;
             $media->resize(75, 75);
         }
     }
     die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
 }