Example #1
0
function resizeImageCond($imagem, $maxw = 500, $maxh = 500, $watermarkArray = array(), $bg = "FFFFFF", $forceJPG = false)
{
    $ih = @getimagesize($imagem);
    if ($ih) {
        $ow = $ih[0];
        // original
        $oh = $ih[1];
        if (count($watermarkArray) > 0 && !is_array($watermarkArray[0]) && $watermarkArray[0][0] == "C" && $ow > $maxw && $oh >= $maxh) {
            // will crop, so $w and $h are the max (if original image is larger or equal to the thumb)
            $w = $maxw;
            $h = $maxh;
        } else {
            // either NOT crop, or crop but the image is smaller
            $w = $ow;
            $h = $oh;
            if ($maxw > 0) {
                // width surpassed, limit it
                if ($w > $maxw) {
                    $w = $maxw;
                    $h = floor($oh / $ow * $w);
                }
            }
            if ($maxh > 0) {
                // heiht surpassed, limit it
                if ($h > $maxh) {
                    $h = $maxh;
                    $w = floor($ow / $oh * $h);
                }
            }
        }
        if ($w != $ow || $h != $oh || count($watermarkArray) > 0) {
            // if reduce OR watermark present, proceed
            $imagemtmp = $imagem . "tmp";
            if (resizeImage($imagem, $imagemtmp, $w, $h, CONS_JPGQUALITY, $watermarkArray, $bg, $forceJPG)) {
                @unlink($imagem);
                locateFile($imagemtmp, $ext);
                // the resizeImage added .jpg or .png as per required
                if (!@copy($imagemtmp, $imagem)) {
                    @unlink($imagemtmp);
                    return 2;
                    // error copying temporary file to destination file
                }
                // save ok
                $temp = umask(0);
                chmod($imagem, 0775);
                umask($temp);
                @unlink($imagemtmp);
                return 1;
                // ok!
            } else {
                return 2;
            }
            // error
        }
    } else {
        return 2;
    }
    return 0;
    // no change required
}
function hacknrollify($picfilename)
{
    $logofilename = "logo.png";
    $logoPicPath = "logopics/" . $logofilename;
    $originalPicPath = "originalpics/" . $picfilename;
    $editedfilename = "hnr_" . $picfilename;
    $editedPicPath = "editedpics/" . $editedfilename;
    // read the original image from file
    $profilepic = imagecreatefromjpeg($originalPicPath);
    $profilepicWidth = imagesx($profilepic);
    $profilepicHeight = imagesy($profilepic);
    // create the black image overlay
    $blackoverlay = imagecreate($profilepicWidth, $profilepicHeight);
    imagecolorallocate($blackoverlay, 0, 0, 0);
    // then merge the black and profilepic
    imagecopymerge($profilepic, $blackoverlay, 0, 0, 0, 0, $profilepicWidth, $profilepicHeight, 50);
    imagedestroy($blackoverlay);
    // merge the resized logo
    $logo = resizeImage($logoPicPath, $profilepicWidth - 80, 999999);
    imageAlphaBlending($logo, false);
    imageSaveAlpha($logo, true);
    $logoWidth = imagesx($logo);
    $logoHeight = imagesy($logo);
    $verticalOffset = $profilepicHeight / 2 - $logoHeight / 2;
    $horizontalOffset = 40;
    imagecopyresampled($profilepic, $logo, $horizontalOffset, $verticalOffset, 0, 0, $logoWidth, $logoHeight, $logoWidth, $logoHeight);
    $mergeSuccess = imagejpeg($profilepic, $editedPicPath);
    if (!$mergeSuccess) {
        echo "Image merge failed!";
    }
    imagedestroy($profilepic);
    imagedestroy($logo);
    return $editedPicPath;
}
/**
 * Insert image data to database (recoreded_data and thumbnail).
 * First generate an unique image id, then insert image to recoreded_data and resized image to thubnail along with 
 *   other given data
 */
function uploadImage($conn, $sensor_id, $date_created, $description)
{
    $image_id = generateId($conn, "images");
    if ($image_id == 0) {
        return;
    }
    $image2 = file_get_contents($_FILES['file_image']['tmp_name']);
    $image2tmp = resizeImage($_FILES['file_image']);
    $image2Thumbnail = file_get_contents($image2tmp['tmp_name']);
    // encode the stream
    $image = base64_encode($image2);
    $imageThumbnail = base64_encode($image2Thumbnail);
    $sql = "INSERT INTO images (image_id, sensor_id, date_created, description, thumbnail, recoreded_data)\n                      VALUES(" . $image_id . ", " . $sensor_id . ", TO_DATE('" . $date_created . "', 'DD/MM/YYYY hh24:mi:ss'), '" . $description . "', empty_blob(), empty_blob())\n                       RETURNING thumbnail, recoreded_data INTO :thumbnail, :recoreded_data";
    $result = oci_parse($conn, $sql);
    $recoreded_dataBlob = oci_new_descriptor($conn, OCI_D_LOB);
    $thumbnailBlob = oci_new_descriptor($conn, OCI_D_LOB);
    oci_bind_by_name($result, ":recoreded_data", $recoreded_dataBlob, -1, OCI_B_BLOB);
    oci_bind_by_name($result, ":thumbnail", $thumbnailBlob, -1, OCI_B_BLOB);
    $res = oci_execute($result, OCI_DEFAULT) or die("Unable to execute query");
    if ($recoreded_dataBlob->save($image) && $thumbnailBlob->save($imageThumbnail)) {
        oci_commit($conn);
    } else {
        oci_rollback($conn);
    }
    oci_free_statement($result);
    $recoreded_dataBlob->free();
    $thumbnailBlob->free();
    echo "New image is added with image_id ->" . $image_id . "<br>";
}
Example #4
0
 public function index()
 {
     if ($_SESSION['access'] > $this->access['rr']) {
         die('Access denied');
     }
     if (isset($_POST['action']) && $_POST['action'] == 'save') {
         $this->updateSlider();
     }
     if (isset($_SESSION['msg']) && $_SESSION['msg'] == 'success') {
         $this->data['text_message'] = $this->language['changes_applied'];
         $this->data['class_message'] = 'success';
         unset($_SESSION['msg']);
     }
     if (isset($_SESSION['msg']) && $_SESSION['msg'] == 'denied') {
         $this->data['text_message'] = $this->language['access_denied'];
         $this->data['class_message'] = 'error';
         unset($_SESSION['msg']);
     }
     $this->engine->document->addScript('template/js/qfinder/qfinder.js');
     $slides = isset($this->params['slides']) ? $this->params['slides'] : array();
     $this->data['slides'] = $slides;
     resizeImage(ROOT_DIR . 'upload/images/no-image.jpg', 90, 80, false);
     foreach ($slides as $id => $slide) {
         $this->data['slides'][$id] = array('src' => $slide['src'], 'thumb' => resizeImage($slide['src'], 90, 80, false), 'link' => $slide['link']);
     }
     $this->data['breadcrumbs'][] = array('caption' => $this->language['home'], 'link' => ADM_PATH);
     $this->data['breadcrumbs'][] = array('caption' => $this->language['modules'], 'link' => 'index.php?page=modules');
     $this->data['breadcrumb_cur'] = $this->language['slider'];
     $this->template = 'template/slider.tpl';
 }
 function process()
 {
     global $DB, $CFG, $MOBILE_LANGS, $DEFAULT_LANG, $MEDIA;
     $cm = get_coursemodule_from_id('url', $this->id);
     $this->url = $DB->get_record('url', array('id' => $cm->instance), '*', MUST_EXIST);
     $context = context_module::instance($cm->id);
     $this->md5 = md5($this->url->externalurl) . $this->id;
     $eiffilename = extractImageFile($this->url->intro, 'mod_url', 'intro', '0', $context->id, $this->courseroot, $cm->id);
     if ($eiffilename) {
         $this->resource_image = "/images/" . resizeImage($this->courseroot . "/" . $eiffilename, $this->courseroot . "/images/" . $cm->id, $CFG->block_oppia_mobile_export_thumb_width, $CFG->block_oppia_mobile_export_thumb_height);
         //delete original image
         unlink($this->courseroot . "/" . $eiffilename) or die(get_string('error_file_delete', 'block_oppia_mobile_export'));
     }
     unset($eiffilename);
 }
Example #6
0
function getUploadedImage($width = null, $height = null)
{
    $ret = false;
    $img_taille = 0;
    $img_nom = '';
    $taille_max = 20000000;
    $ret = is_uploaded_file($_FILES['Filedata']['tmp_name']);
    if (!$ret) {
        error_log('Problème de transfert (Erreur php : ' . $_FILES['Filedata'] . ')');
        return false;
    } else {
        // Le fichier a bien été reçu
        $img_taille = $_FILES['Filedata']['size'];
        if ($img_taille > $taille_max) {
            error_log("Trop gros !");
            return false;
        }
        $img_nom = $_FILES['Filedata']['name'];
    }
    // Redimensionnement de l'image
    // Hauteur image destination
    $source_file = $_FILES['Filedata']['tmp_name'];
    // Fichier d'origine
    // Cacul des nouvelles dimensions
    $fileParts = pathinfo($_FILES['Filedata']['name']);
    if (substr_count(strtolower($fileParts['extension']), "jpg") > 0 || substr_count($fileParts['extension'], "jpeg") > 0) {
        $source_image = imagecreatefromjpeg($source_file);
    } else {
        if (substr_count(strtolower($fileParts['extension']), "png") > 0) {
            $source_image = imagecreatefrompng($source_file);
        } else {
            if (substr_count(strtolower($fileParts['extension']), "gif") > 0) {
                $source_image = imagecreatefromgif($source_file);
            } else {
                return false;
            }
        }
    }
    if ($width == null && $height == null) {
        ob_start();
        imagejpeg($source_image);
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    } else {
        return resizeImage($source_image, $width, $height);
    }
}
Example #7
0
function resize()
{
    $image = $_GET['image'];
    $height = $_GET['height'];
    $width = $_GET['width'];
    $file = md5($image . $height . $width);
    $image = strstr($image, '?', true) ?: $image;
    $ext = parse_url($image);
    $ext = pathinfo($ext['path'], PATHINFO_EXTENSION);
    if (!file_exists(dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . $file . "." . $ext)) {
        $output = resizeImage(dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . $file . "." . $ext, file_get_contents($image), $width, $height, 1, 'file');
    }
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: " . BASE_URL . "cache/" . $file . "." . $ext . "\r\n");
    exit;
}
Example #8
0
function changeAvatar()
{
    $post = isset($_POST) ? $_POST : array();
    $max_width = "500";
    $userId = isset($post['hdn-profile-id']) ? intval($post['hdn-profile-id']) : 0;
    $path = 'images/tmp';
    $valid_formats = array("jpg", "png", "gif", "bmp", "jpeg");
    $name = $_FILES['photoimg']['name'];
    $size = $_FILES['photoimg']['size'];
    if (strlen($name)) {
        list($txt, $ext) = explode(".", $name);
        if (in_array($ext, $valid_formats)) {
            if ($size < 1024 * 1024) {
                $actual_image_name = 'avatar' . '_' . $userId . '.' . $ext;
                $filePath = $path . '/' . $actual_image_name;
                $tmp = $_FILES['photoimg']['tmp_name'];
                if (move_uploaded_file($tmp, $filePath)) {
                    $width = getWidth($filePath);
                    $height = getHeight($filePath);
                    //Scale the image if it is greater than the width set above
                    if ($width > $max_width) {
                        $scale = $max_width / $width;
                        $uploaded = resizeImage($filePath, $width, $height, $scale);
                    } else {
                        $scale = 1;
                        $uploaded = resizeImage($filePath, $width, $height, $scale);
                    }
                    /*$res = saveAvatar(array(
                      'userId' => isset($userId) ? intval($userId) : 0,
                                              'avatar' => isset($actual_image_name) ? $actual_image_name : '',
                      ));*/
                    //mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
                    echo "<img id='photo' file-name='" . $actual_image_name . "' class='' src='" . $filePath . '?' . time() . "' class='preview'/>";
                } else {
                    echo "failed";
                }
            } else {
                echo "Image file size max 1 MB";
            }
        } else {
            echo "Invalid file format..";
        }
    } else {
        echo "Please select image..!";
    }
    exit;
}
function getData()
{
    $tmpName = $_FILES['file']['tmp_name'];
    assertNotEmpty($tmpName, "missing file");
    $imageWidth = getParameter("imageWidth");
    $imageHeight = getParameter("imageHeight");
    $contentType = getContentType();
    debug($contentType);
    if (($contentType == "image/jpeg" || $contentType == "image/x-png" || $contentType == "image/png" || $contentType == "image/gif") && !empty($imageWidth) && !empty($imageHeight)) {
        resizeImage($tmpName, $imageWidth, $imageHeight);
    }
    $fp = fopen($tmpName, 'r');
    $length = filesize($tmpName);
    debug("File size: {$length}");
    $content = fread($fp, $length);
    fclose($fp);
    return $content;
}
Example #10
0
 private function fillCategory($category_id)
 {
     $limit = $this->params['count_per_page'];
     $start = ($this->engine->url->page_n - 1) * $limit;
     $q = $this->engine->db->query("SELECT id, parent_id, caption_" . $_SESSION['lang'] . " as caption, description_" . $_SESSION['lang'] . " as description, text_" . $_SESSION['lang'] . " as `text`, title_" . $_SESSION['lang'] . " as title, kw_" . $_SESSION['lang'] . " as kw, descr_" . $_SESSION['lang'] . " as descr FROM " . DB_PREF . "materials WHERE id='" . (int) $category_id . "' AND is_category=1 AND enabled=1 ORDER BY date_added DESC");
     if (empty($q->row)) {
         $this->engine->ERROR_404 = true;
         return false;
     } else {
         $category = $q->row;
         $breadcrumbs = array();
         $this->buildBreadcrumbs($category['id'], $breadcrumbs);
         $this->data['breadcrumbs'][0] = array('caption' => '<i class="glyphicon glyphicon-home"></i>', 'link' => $this->engine->url->link('route=home'));
         foreach ($breadcrumbs as $breadcrumb) {
             $this->data['breadcrumbs'][] = array('caption' => $breadcrumb['caption_' . $_SESSION['lang']], 'link' => $this->engine->url->link('route=materials&material_id=' . $breadcrumb['id']));
         }
         $this->data['category'] = array('caption' => $category['caption'], 'description' => $category['description'], 'text' => $category['text']);
         if ($category['title'] != '') {
             $this->engine->document->setTitle($category['title']);
         }
         if ($category['kw'] != '') {
             $this->engine->document->setKeywords($category['kw']);
         }
         if ($category['descr'] != '') {
             $this->engine->document->setDescription($category['descr']);
         }
         $categories = $this->engine->db->query("SELECT id, caption_" . $_SESSION['lang'] . " as caption, description_" . $_SESSION['lang'] . " as description, text_" . $_SESSION['lang'] . " as text, preview FROM " . DB_PREF . "materials WHERE parent_id=" . (int) $category_id . " AND enabled=1 AND is_category = 1 ORDER BY  date_added DESC")->rows;
         $this->data['categories'] = array();
         foreach ($categories as $category) {
             $this->data['categories'][$category['id']] = array('link' => $this->engine->url->link('route=materials&material_id=' . $category['id']), 'caption' => $category['caption'], 'preview' => resizeImage($category['preview'], 100, 100), 'description' => $category['description'], 'text' => $category['text']);
         }
         $materials = $this->engine->db->query("SELECT id, caption_" . $_SESSION['lang'] . " as caption, description_" . $_SESSION['lang'] . " as description, preview, date_added FROM " . DB_PREF . "materials WHERE parent_id=" . (int) $category_id . " AND enabled = 1 AND is_category = 0 ORDER BY date_added DESC LIMIT " . $start . ", " . $limit)->rows;
         $this->data['materials'] = array();
         foreach ($materials as $material) {
             $this->data['materials'][$material['id']] = array('link' => $this->engine->url->link('route=materials&material_id=' . $material['id']), 'caption' => $material['caption'], 'preview' => resizeImage($material['preview'], 150, 150), 'date_added' => $material['date_added'], 'description' => $material['description']);
         }
         $this->data['details_caption'] = $this->params['details_' . $_SESSION['lang']];
         $page_count = $this->getPageCount((int) $category_id, (int) $this->params['count_per_page']);
         $this->data['pagination'] = printPagination($page_count, $this->engine->uri);
         $this->mode = 1;
         $this->engine->ERROR_404 = false;
         return true;
     }
 }
function fileUpload($imgFile)
{
    $file_path = $_SESSION['rootDir'] . '/images/gallery/' . basename($imgFile["name"]);
    if (fileExists($file_path)) {
        if (move_uploaded_file($imgFile["tmp_name"], $file_path)) {
            resizeImage($file_path);
            return 'images/gallery/' . basename($imgFile["name"]);
        } else {
            $_SESSION['status'] = 'error';
            $_SESSION['flashData'] = 'File can not be uploaded';
            header('location:' . baseUrl . 'admin/gallery/');
            exit;
        }
    } else {
        $_SESSION['status'] = 'error';
        $_SESSION['flashData'] = 'Same file cannot be uploaded twice';
        header('location:' . baseUrl . 'admin/gallery/');
    }
}
Example #12
0
function thumbsize($file, $size)
{
    if (!preg_match("/(\\.gif|\\.jpeg|.\\jpg|\\.png|\\.bmp)/i", $file)) {
        return $url;
    }
    if ($size) {
        if (!is_dir(THUMB_DIR . "/" . $size)) {
            mkdir(THUMB_DIR . "/" . $size, 777);
        }
        $path = explode("/", $file);
        $fullfile = array_pop($path);
        $second = array_pop($path);
        if (!is_dir(THUMB_DIR . "/" . $size . "/" . $second)) {
            mkdir(THUMB_DIR . "/" . $size . "/" . $second, 777);
        }
        $wh = explode("_", $size);
        if (count($wh) != 2) {
            return $file;
        }
        $width = intval($wh[0]);
        $height = intval($wh[1]);
        if ($width == 0 || $height == 0) {
            return $file;
        }
        $ext = substr($fullfile, strrpos($fullfile, '.') + 1);
        $noext = substr($fullfile, 0, strrpos($fullfile, '.'));
        $thumbfile = THUMB_DIR . "/" . $size . "/{$second}/" . "{$noext}" . "_{$width}" . "_{$height}" . "." . $ext;
        if (file_exists($thumbfile)) {
            return MPIC_1 . $thumbfile;
        } else {
            if (resizeImage($file, $width, $height, $thumbfile)) {
                return MPIC_1 . $thumbfile;
            }
        }
    } else {
        return $url;
    }
}
Example #13
0
 public function index()
 {
     if (!$this->engine->url->is_category) {
         $this->engine->ERROR_404 = false;
         $this->engine->document->setTitle($this->params['title_' . $_SESSION['lang']]);
         $this->engine->document->setKeywords($this->params['kw_' . $_SESSION['lang']]);
         $this->engine->document->setDescription($this->params['descr_' . $_SESSION['lang']]);
         $this->data['leave_review_btn'] = $this->params['leave_review_btn_' . $_SESSION['lang']];
         $this->data['form_caption'] = $this->params['form_caption_' . $_SESSION['lang']];
         $this->data['name_placeholder'] = $this->params['name_placeholder_' . $_SESSION['lang']];
         $this->data['email_placeholder'] = $this->params['email_placeholder_' . $_SESSION['lang']];
         $this->data['review_placeholder'] = $this->params['review_placeholder_' . $_SESSION['lang']];
         $this->data['post_btn'] = $this->params['post_btn_' . $_SESSION['lang']];
         $this->data['cancel_btn'] = $this->params['cancel_btn_' . $_SESSION['lang']];
         $this->data['error_name'] = $this->params['error_name_' . $_SESSION['lang']];
         $this->data['error_text'] = $this->params['error_text_' . $_SESSION['lang']];
         $reviews = $this->getReviews(0, 50);
         foreach ($reviews as $review) {
             $this->data['reviews'][] = array('name' => $review['name'], 'post' => $review['post'], 'rating' => $review['rating'], 'photo' => resizeImage($review['photo'], 150, 150));
         }
         $this->template = TEMPLATE . 'template/modules/site_reviews.tpl';
     }
 }
Example #14
0
 private function findPhoto($start = 1, $limit = 20)
 {
     $dir = dirname(dirname(__FILE__)) . ROOT_DIR . 'upload/images/photos/';
     $photos = array();
     $i = 0;
     foreach (glob($dir . "*.*") as $filename) {
         $i++;
         if ($i > $limit + $start - 1) {
             break;
         }
         $filepath = $filename;
         $filepath = str_replace('\\', '/', $filepath);
         $path_parts = pathinfo($filepath);
         $photos[$i]['src'] = ROOT_DIR . 'upload/images/photos/' . $path_parts['basename'];
         $photos[$i]['thumb'] = resizeImage(ROOT_DIR . 'upload/images/photos/' . $path_parts['basename'], 150, 150);
     }
     if ($start > 1) {
         for ($i = 1; $i < $start; $i++) {
             unset($photos[$i]);
         }
     }
     return $photos;
 }
Example #15
0
 /**
  * 保存缩略图图片到本地
  *
  * @param string 图片原url
  * @return string 图片保存名
  */
 function save_image($image_source_url, $image_new_name)
 {
     //包含gd库,处理图片
     include "fn_gd.php";
     if (preg_match("/jpg/i", $image_source_url)) {
         $src_im = imagecreatefromjpeg($image_source_url);
         if (!$src_im) {
             throw new Exception("载入jpeg图片错误!");
         }
         return resizeImage($src_im, 230, 230, 'images/', $image_new_name, '.jpg');
     } else {
         if (preg_match("/png/i", $image_source_url)) {
             $src_im = imagecreatefrompng($image_source_url);
             if (!$src_im) {
                 throw new Exception("载入png图片错误!");
             }
             return resizeImage($src_im, 230, 230, 'images/', $image_new_name, '.png');
         } else {
             if (preg_match("/gif/i", $image_source_url)) {
                 $src_im = imagecreatefromgif($image_source_url);
                 if (!$src_im) {
                     throw new Exception("载入gif图片错误!");
                 }
                 return resizeImage($src_im, 230, 230, 'images/', $image_new_name, '.gif');
             }
         }
     }
     throw new Exception("无法识别的图片类型!");
 }
Example #16
0
function resizeImageFile($source, $destination, $max_width, $max_height, $preferred_format = 0)
{
    global $sourcedir;
    // Nothing to do without GD
    if (!checkGD()) {
        return false;
    }
    static $default_formats = array('1' => 'gif', '2' => 'jpeg', '3' => 'png', '6' => 'bmp', '15' => 'wbmp');
    require_once $sourcedir . '/Subs-Package.php';
    @ini_set('memory_limit', '90M');
    $success = false;
    // Get the image file, we have to work with something after all
    $fp_destination = fopen($destination, 'wb');
    if ($fp_destination && substr($source, 0, 7) == 'http://') {
        $fileContents = fetch_web_data($source);
        fwrite($fp_destination, $fileContents);
        fclose($fp_destination);
        $sizes = @getimagesize($destination);
    } elseif ($fp_destination) {
        $sizes = @getimagesize($source);
        $fp_source = fopen($source, 'rb');
        if ($fp_source !== false) {
            while (!feof($fp_source)) {
                fwrite($fp_destination, fread($fp_source, 8192));
            }
            fclose($fp_source);
        } else {
            $sizes = array(-1, -1, -1);
        }
        fclose($fp_destination);
    } else {
        $sizes = array(-1, -1, -1);
    }
    // Gif? That might mean trouble if gif support is not available.
    if ($sizes[2] == 1 && !function_exists('imagecreatefromgif') && function_exists('imagecreatefrompng')) {
        // Download it to the temporary file... use the special gif library... and save as png.
        if ($img = @gif_loadFile($destination) && gif_outputAsPng($img, $destination)) {
            $sizes[2] = 3;
        }
    }
    // A known and supported format?
    if (isset($default_formats[$sizes[2]]) && function_exists('imagecreatefrom' . $default_formats[$sizes[2]])) {
        $imagecreatefrom = 'imagecreatefrom' . $default_formats[$sizes[2]];
        if ($src_img = @$imagecreatefrom($destination)) {
            resizeImage($src_img, $destination, imagesx($src_img), imagesy($src_img), $max_width === null ? imagesx($src_img) : $max_width, $max_height === null ? imagesy($src_img) : $max_height, true, $preferred_format);
            $success = true;
        }
    }
    return $success;
}
Example #17
0
         $processImage = false;
         //image format is not supported!
 }
 //get Image Size
 list($CurWidth, $CurHeight) = getimagesize($TempSrc[$i]);
 //Get file extension from Image name, this will be re-added after random name
 $ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
 $ImageExt = str_replace('.', '', $ImageExt);
 //Construct a new image name (with random number added) for our new image.
 $NewImageName = $RandomNumber . '.' . $ImageExt;
 //Set the Destination Image path with Random Name
 //$thumb_DestRandImageName 	= $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
 $DestRandImageName = $DestinationDirectory . "/" . $NewImageName;
 //Name for Big Image
 //Resize image to our Specified Size by calling resizeImage function.
 if ($processImage && resizeImage($CurWidth, $CurHeight, $BigImageMaxSize, $DestRandImageName, $CreatedImage, $Quality, $ImageType[$i])) {
     //Create a square Thumbnail right after, this time we are using cropImage() function
     //if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
     //{
     //echo 'Error Creating thumbnail';
     //}
     /*
      At this point we have succesfully resized and created thumbnail image
      We can render image to user's browser or store information in the database
      For demo, we are going to output results on browser.
     */
     //Get New Image Size
     list($ResizedWidth, $ResizedHeight) = getimagesize($DestRandImageName);
     echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
     echo '<tr>';
     //echo '<td align="center"><img src="uploads/'.$ThumbPrefix.$NewImageName.'" alt="Thumbnail" height="'.$ThumbSquareSize.'" width="'.$ThumbSquareSize.'"></td>';
Example #18
0
function genThumbnail()
{
    // Make sure the parameters in the URL were generated by us.
    $sign = hash_hmac('sha256', $_GET['url'], $GLOBALS['salt']);
    if ($sign != $_GET['hmac']) {
        die('Naughty boy!');
    }
    // Let's see if we don't already have the image for this URL in the cache.
    $thumbname = hash('sha1', $_GET['url']) . '.jpg';
    if (is_file($GLOBALS['config']['CACHEDIR'] . '/' . $thumbname)) {
        // We have the thumbnail, just serve it:
        header('Content-Type: image/jpeg');
        echo file_get_contents($GLOBALS['config']['CACHEDIR'] . '/' . $thumbname);
        return;
    }
    // We may also serve a blank image (if service did not respond)
    $blankname = hash('sha1', $_GET['url']) . '.gif';
    if (is_file($GLOBALS['config']['CACHEDIR'] . '/' . $blankname)) {
        header('Content-Type: image/gif');
        echo file_get_contents($GLOBALS['config']['CACHEDIR'] . '/' . $blankname);
        return;
    }
    // Otherwise, generate the thumbnail.
    $url = $_GET['url'];
    $domain = parse_url($url, PHP_URL_HOST);
    if ($domain == 'flickr.com' || endsWith($domain, '.flickr.com')) {
        // Crude replacement to handle new flickr domain policy (They prefer www. now)
        $url = str_replace('http://flickr.com/', 'http://www.flickr.com/', $url);
        // Is this a link to an image, or to a flickr page ?
        $imageurl = '';
        if (endswith(parse_url($url, PHP_URL_PATH), '.jpg')) {
            // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
            preg_match('!(http://farm\\d+\\.staticflickr\\.com/\\d+/\\d+_\\w+_)\\w.jpg!', $url, $matches);
            if (!empty($matches[1])) {
                $imageurl = $matches[1] . 'm.jpg';
            }
        } else {
            // Get the flickr html page.
            list($headers, $content) = get_http_response($url, 20);
            if (strpos($headers[0], '200 OK') !== false) {
                // flickr now nicely provides the URL of the thumbnail in each flickr page.
                preg_match('!<link rel=\\"image_src\\" href=\\"(.+?)\\"!', $content, $matches);
                if (!empty($matches[1])) {
                    $imageurl = $matches[1];
                }
                // In albums (and some other pages), the link rel="image_src" is not provided,
                // but flickr provides:
                // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
                if ($imageurl == '') {
                    preg_match('!<meta property=\\"og:image\\" content=\\"(.+?)\\"!', $content, $matches);
                    if (!empty($matches[1])) {
                        $imageurl = $matches[1];
                    }
                }
            }
        }
        if ($imageurl != '') {
            // Let's download the image.
            // Image is 240x120, so 10 seconds to download should be enough.
            list($headers, $content) = get_http_response($imageurl, 10);
            if (strpos($headers[0], '200 OK') !== false) {
                // Save image to cache.
                file_put_contents($GLOBALS['config']['CACHEDIR'] . '/' . $thumbname, $content);
                header('Content-Type: image/jpeg');
                echo $content;
                return;
            }
        }
    } elseif ($domain == 'vimeo.com') {
        // This is more complex: we have to perform a HTTP request, then parse the result.
        // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
        $vid = substr(parse_url($url, PHP_URL_PATH), 1);
        list($headers, $content) = get_http_response('https://vimeo.com/api/v2/video/' . escape($vid) . '.php', 5);
        if (strpos($headers[0], '200 OK') !== false) {
            $t = unserialize($content);
            $imageurl = $t[0]['thumbnail_medium'];
            // Then we download the image and serve it to our client.
            list($headers, $content) = get_http_response($imageurl, 10);
            if (strpos($headers[0], '200 OK') !== false) {
                // Save image to cache.
                file_put_contents($GLOBALS['config']['CACHEDIR'] . '/' . $thumbname, $content);
                header('Content-Type: image/jpeg');
                echo $content;
                return;
            }
        }
    } elseif ($domain == 'ted.com' || endsWith($domain, '.ted.com')) {
        // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
        // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
        // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
        list($headers, $content) = get_http_response($url, 5);
        if (strpos($headers[0], '200 OK') !== false) {
            // Extract the link to the thumbnail
            preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\\d+x\\d+\\.jpg)"!', $content, $matches);
            if (!empty($matches[1])) {
                // Let's download the image.
                $imageurl = $matches[1];
                // No control on image size, so wait long enough
                list($headers, $content) = get_http_response($imageurl, 20);
                if (strpos($headers[0], '200 OK') !== false) {
                    $filepath = $GLOBALS['config']['CACHEDIR'] . '/' . $thumbname;
                    file_put_contents($filepath, $content);
                    // Save image to cache.
                    if (resizeImage($filepath)) {
                        header('Content-Type: image/jpeg');
                        echo file_get_contents($filepath);
                        return;
                    }
                }
            }
        }
    } elseif ($domain == 'xkcd.com' || endsWith($domain, '.xkcd.com')) {
        // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
        // http://xkcd.com/327/
        // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
        list($headers, $content) = get_http_response($url, 5);
        if (strpos($headers[0], '200 OK') !== false) {
            // Extract the link to the thumbnail
            preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!', $content, $matches);
            if (!empty($matches[1])) {
                // Let's download the image.
                $imageurl = $matches[1];
                // No control on image size, so wait long enough
                list($headers, $content) = get_http_response($imageurl, 20);
                if (strpos($headers[0], '200 OK') !== false) {
                    $filepath = $GLOBALS['config']['CACHEDIR'] . '/' . $thumbname;
                    // Save image to cache.
                    file_put_contents($filepath, $content);
                    if (resizeImage($filepath)) {
                        header('Content-Type: image/jpeg');
                        echo file_get_contents($filepath);
                        return;
                    }
                }
            }
        }
    } else {
        // For all other domains, we try to download the image and make a thumbnail.
        // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
        list($headers, $content) = get_http_response($url, 30);
        if (strpos($headers[0], '200 OK') !== false) {
            $filepath = $GLOBALS['config']['CACHEDIR'] . '/' . $thumbname;
            // Save image to cache.
            file_put_contents($filepath, $content);
            if (resizeImage($filepath)) {
                header('Content-Type: image/jpeg');
                echo file_get_contents($filepath);
                return;
            }
        }
    }
    // Otherwise, return an empty image (8x8 transparent gif)
    $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
    file_put_contents($GLOBALS['config']['CACHEDIR'] . '/' . $blankname, $blankgif);
    // Also put something in cache so that this URL is not requested twice.
    header('Content-Type: image/gif');
    echo $blankgif;
}
Example #19
0
 public function add_slider()
 {
     if (isset($_POST['edit_slider_btn'])) {
         $data_post = $this->input->post();
         $this->load->helper('Validation');
         $this->load->helper('HTMLPurifier');
         $config = HTMLPurifier_Config::createDefault();
         $purifier = new HTMLPurifier($config);
         //====================== Validate START ======================
         $error = array();
         $link_slider = array();
         for ($i = 0; $i < count($_FILES['image_slider']['name']); $i++) {
             $data_insert['link_slider'][$i] = '';
             if ($_FILES['image_slider']['name'][$i] != '') {
                 $tmp = new SplFileInfo($_FILES['image_slider']['name'][$i]);
                 $type = $tmp->getExtension();
                 if (strtolower($type) != 'jpg' && strtolower($type) != 'gif' && strtolower($type) != 'png') {
                     $error[] = "Không đúng định dạng ảnh cho phép!";
                 } elseif (!isImage($_FILES['image_slider']['tmp_name'][$i])) {
                     $error[] = "Không phải là file ảnh!";
                 } elseif ($_FILES['image_slider']['size'][$i] > 2048000) {
                     $error[] = "Ảnh lớn hơn 2MB";
                 } else {
                     $data_insert['link_slider'][$i] = $i . microtime() . '.' . $type;
                     $tmp_name_image_slider[$i] = $_FILES['image_slider']['tmp_name'][$i];
                 }
             } else {
                 $error[] = "Bắt buộc phải upload 1 ảnh cho 1 slide.";
             }
         }
         for ($i = 0; $i < count($data_post['des_slider']); $i++) {
             if ($data_post['des_slider'][$i] !== '') {
                 $data_insert['des_slider'][$i] = $purifier->purify($data_post['des_slider'][$i]);
             } else {
                 $data_insert['des_slider'][$i] = '';
             }
         }
         //====================== Validate END ======================
         if (count($error) > 0) {
             $alert_time = 15000;
             set_notice('status', FAILED_STATUS, $error, $alert_time);
             $redata['re_des_slider'] = $data_post['des_slider'];
             $data['subView'] = '/manage_site/slider/add_slider_layout';
             $data['title'] = "Thêm hình ảnh vào slider";
             $data['subData'] = $redata;
             $this->load->view('/main/main_layout', $data);
         } else {
             $tmp_insert = array();
             for ($i = 0; $i < count($data_post['des_slider']); $i++) {
                 // $this->Slider->insert($data_insert[]);
                 $tmp_insert['link_slider'] = $data_insert['link_slider'][$i];
                 $tmp_insert['des_slider'] = $data_insert['des_slider'][$i];
                 $tmp_rs = $this->Slider->insert($tmp_insert);
             }
             // ============= Upload anh image_slider ===================
             for ($i = 0; $i < count($_FILES['image_slider']['name']); $i++) {
                 if (!empty($_FILES['image_slider']['name'][$i])) {
                     $path = "public/img/slider/";
                     if (move_uploaded_file($tmp_name_image_slider[$i], $path . $data_insert['link_slider'][$i])) {
                         resizeImage($path . $data_insert['link_slider'][$i], $path . $data_insert['link_slider'][$i], 400, 400);
                     }
                 }
             }
             // ============= Upload anh image_slider ===================
             $content = 'Thêm mới slide thành công.';
             set_notice('status', SUCCESS_STATUS, $content);
             header('location:' . base_url() . 'index.php/_admin/manage_site/slider/show_slider');
         }
     } else {
         $data['subView'] = '/manage_site/slider/add_slider_layout';
         $data['title'] = "Thêm hình ảnh vào slider";
         $data['subData'] = $data;
         $this->load->view('/main/main_layout', $data);
     }
 }
Example #20
0
     //if(move_uploaded_file($tempFile, $targetFile))
     //generate thumbnails after the main file is uploaded
     if ($_POST["dimThumbs"] != "" && in_array($extensionFile, $imagesExtentions)) {
         $l_dimThumbs = explode(",", $_POST["dimThumbs"]);
         if ($_POST["foldThumbs"] != "") {
             $l_foldThumbs = explode(",", $_POST["foldThumbs"]);
         }
         if ($_POST["cropThumbs"] != "") {
             $l_cropThumbs = explode(",", $_POST["cropThumbs"]);
         }
         $result["dimThumbs"] = array();
         $imageFile = $targetFile;
         for ($i = 0; $i < count($l_dimThumbs); $i++) {
             $dimensions = explode("x", trim($l_dimThumbs[$i]));
             $destinationFile = (trim($l_foldThumbs[$i]) != "" ? trim($l_foldThumbs[$i]) : $uploadDir) . $fileName . $_POST["svig"] . $i . "." . $extensionFile;
             resizeImage($dimensions[0], $dimensions[1], $imageFile, $destinationFile, array(), array(), $_POST["cropThumbs"]);
             // $l_cropThumbs[$i]
             $result["dimThumbs"][] = $fileName . $_POST["svig"] . $i . "." . $extensionFile;
         }
         //for($i=0; $i<count($l_dimThumbs); $i++)
     }
     // if($_POST["dimThumbs"]!="")
 }
 // $idResultat==0
 // affichage résultats
 $texte = "";
 switch ($idResultat) {
     case 0:
         $texte = "";
         break;
     case 1:
Example #21
0
}
/**
* Create alternate image sizes.
*/
$resize_msg = '';
if ($disp_size['0'] == TRUE && ($cnvrt_alt['indiv'] == FALSE || $upr_nav['sizer'] == TRUE || $lwr_nav['sizer'] == TRUE || $reqd_img_size == $cnvrt_size['0']['label'])) {
    $resize_msg .= resizeImage($cnvrt_size['0']);
}
if ($disp_size['1'] == TRUE && ($cnvrt_alt['indiv'] == FALSE || $upr_nav['sizer'] == TRUE || $lwr_nav['sizer'] == TRUE || $reqd_img_size == $cnvrt_size['1']['label'])) {
    $resize_msg .= resizeImage($cnvrt_size['1']);
}
if ($disp_size['2'] == TRUE && ($cnvrt_alt['indiv'] == FALSE || $upr_nav['sizer'] == TRUE || $lwr_nav['sizer'] == TRUE || $reqd_img_size == $cnvrt_size['2']['label'])) {
    $resize_msg .= resizeImage($cnvrt_size['2']);
}
if ($disp_size['3'] == TRUE && ($cnvrt_alt['indiv'] == FALSE || $upr_nav['sizer'] == TRUE || $lwr_nav['sizer'] == TRUE || $reqd_img_size == $cnvrt_size['3']['label'])) {
    $resize_msg .= resizeImage($cnvrt_size['3']);
}
/**
* Finish creating diagnostic messages.
*/
if ($diag_messages == TRUE) {
    $server_sw = $server_vars['SERVER_SOFTWARE'];
    if (eregi('/Fedora/', $server_sw)) {
        $server_sw .= "<br />\nFedora Core 3 or later may require \n<a href='http://qdig.sourceforge.net/Support/FedoraSELinux'>adjusting the SELinux policy</a> for Apache.";
    }
    if (@file_exists($qdig_files) && @is_dir($qdig_files)) {
        $qdig_files_exists = TRUE;
        $qdig_files_perms = decoct(fileperms($qdig_files)) % 10000;
    } else {
        $qdig_files_exists = FALSE;
    }
Example #22
0
    if (!$quality) {
        $quality = bu::config('rc/quality');
    }
    $width = $maxWidth;
    $height = $maxHeight;
    list($width_orig, $height_orig) = getimagesize($origName);
    $ratio_orig = $width_orig / $height_orig;
    if ($width_orig < $width and $height_orig < $height) {
        $width = $width_orig;
        $height = $height_orig;
    } elseif ($width / $height > $ratio_orig) {
        $width = $height * $ratio_orig;
    } else {
        $height = $width / $ratio_orig;
    }
    bu::lib('opt/smart_resize_image/smart_resize_image.function');
    smart_resize_image($origName, $width, $height, false, $destName, false);
}
$name = getUniqueName($fileType);
$finalDir = bu::config('rc/uploadPath') . '/' . getDirForString($name);
$finalSmallDir = bu::config('rc/smallImgPath') . '/' . getDirForString($name);
if (!file_exists($finalDir)) {
    mkdir($finalDir, 0775, true);
    mkdir($finalSmallDir, 0775, true);
}
$finalPath = bu::config('rc/uploadPath') . '/' . makePathForString($name, $fileType);
$finalSmallPath = bu::config('rc/smallImgPath') . '/' . makePathForString($name, $fileType);
move_uploaded_file($tmpName, $finalPath);
resizeImage($finalPath, $finalSmallPath);
bu::redirect('/links.php?img=' . getUrlForString($name, $fileType));
#$path = makePathForString($name, $fileType);
 private function saveImageWithResize()
 {
     if (isset($_REQUEST['image_deleted'])) {
         if ("1" == $_REQUEST['image_deleted']) {
             // setting all image fields empty to indicate the product has no image anymore
             // the previous version of the product will still reference the image
             $this->bean->image_mime_type = $this->bean->image_filename = $this->bean->image_unique_filename = '';
             // setting to empty string instead of setting to null. because setting to null does not set the db entry to null.
         }
     }
     // this assumes that edit view form has enctype="multipart/form-data" set
     $file = $_FILES['select_image_filename'];
     if (empty($file['name']) && empty($file['type']) && empty($file['tmp_name'])) {
         // don't do anything. we assume the old product image is still valid and keep everything as is.
         $GLOBALS['log']->warn("oqc_ProductController::saveImage() name, type, tmp_name of image are empty. Will not upload any file.");
         return;
     } else {
         if ($file['error'] != 0) {
             // TODO handle different error codes
             // TODO what do they mean??
             $GLOBALS['log']->warn("oqc_ProductController::saveImage() Could not upload any files because error {$file['error']} is reported.");
             return;
         } else {
             // note: perhaps there was previous image for this product and the user uploaded a new one.
             // we must not delete the old picture because a new version of the product will automatically created.
             // the older version of the product still displays the previous image.
             // 2.1 Use standard config.php settings for upload dir and max file size. It fileUploadDir key exist in document.properties, then use values from openqc configuration file. By default openqc values are disabled.
             global $sugar_config;
             require_once 'include/oqc/common/Configuration.php';
             $conf = Configuration::getInstance();
             $oqc_uploadDir = $conf->get('fileUploadDir');
             $oqc_maxFileSize = $conf->get('maximumUploadFileSize');
             $uploadDir = $oqc_uploadDir ? $oqc_uploadDir : $sugar_config['upload_dir'];
             $maxFileSize = $oqc_maxFileSize ? $oqc_maxFileSize : $sugar_config['upload_maxsize'];
             if ($file['size'] > $maxFileSize) {
                 $GLOBALS['log']->warn("oqc_ProductController::saveImage() Image size (" . $file['size'] . ") exceeds maximumUploadFileSize (" . $maxFileSize . "). Please check configuration.");
             } else {
                 // TODO how browser/server (?) finds out mime type (can we trust it?)
                 if (!$this->bean->isMimeTypeAllowed($file['type'])) {
                     $GLOBALS['log']->warn("oqc_ProductController::saveImage() Image has a invalid mime type " . $file['type']);
                 } else {
                     $this->bean->image_mime_type = $file['type'];
                     $this->bean->image_filename = basename($file['name']);
                     $id = str_replace('.', '', uniqid('i', true));
                     // we have to remove the dots from the generated id because latex can only determine the filetype properly if the only dot in the filename is in front of the file extension.
                     $fileExtension = substr($this->bean->image_filename, strrpos($this->bean->image_filename, '.') + 1);
                     $this->bean->image_unique_filename = $id . "." . $fileExtension;
                     // we have to add the original file extension to make sure latex can later determine the filetype when generating the pdf.
                     $from = $file['tmp_name'];
                     $to = $uploadDir . $this->bean->image_unique_filename;
                     $thumbname = $uploadDir . 'th' . $this->bean->image_unique_filename;
                     if (!move_uploaded_file($from, $to)) {
                         $GLOBALS['log']->warn("oqc_ProductController::saveImage() could not move file from {$from} to {$to}. Please check configuration file and permissions");
                         return;
                     } else {
                         if (!resizeImage($to, $thumbname, 700)) {
                             $GLOBALS['log']->debug("oqc_ProductController::saveImage() image could not be resized");
                         }
                     }
                 }
             }
         }
     }
 }
 function export2print()
 {
     global $DB, $CFG, $MOBILE_LANGS, $DEFAULT_LANG, $MEDIA;
     $cm = get_coursemodule_from_id('page', $this->id);
     $page = $DB->get_record('page', array('id' => $cm->instance), '*', MUST_EXIST);
     $context = context_module::instance($cm->id);
     $content = $this->extractFiles($page->content, 'mod_page', 'content', 0, $context->id, $this->courseroot);
     $langs = extractLangs($content);
     // get the image from the intro section
     $eiffilename = extractImageFile($page->intro, 'mod_page', 'intro', 0, $context->id, $this->courseroot, $cm->id);
     if ($eiffilename) {
         $this->page_image = $eiffilename;
         $this->page_image = "/images/" . resizeImage($this->courseroot . "/" . $this->page_image, $this->courseroot . "/images/" . $cm->id, $CFG->block_oppia_mobile_export_thumb_width, $CFG->block_oppia_mobile_export_thumb_height);
         //delete original image
         unlink($this->courseroot . "/" . $eiffilename) or die(get_string('error_file_delete', 'block_oppia_mobile_export'));
     }
     unset($eiffilename);
     $return_content = "";
     if (is_array($langs) && count($langs) > 0) {
         foreach ($langs as $l => $t) {
             $pre_content = $t;
             $t = $this->extractMedia($t);
             // if page has media and no special icon for page, extract the image for first video
             if (count($this->page_media) > 0 && $this->page_image == null) {
                 if ($this->extractMediaImage($pre_content, 'mod_page', 'content', 0, $context->id)) {
                     $this->page_image = "/images/" . resizeImage($this->courseroot . "/" . $this->page_image, $this->courseroot . "/images/" . $cm->id, $CFG->block_oppia_mobile_export_thumb_width, $CFG->block_oppia_mobile_export_thumb_height);
                 }
             }
             $return_content .= $t;
         }
     } else {
         $pre_content = $content;
         $content = $this->extractMedia($content);
         // if page has media and no special icon for page, extract the image for first video
         if (count($this->page_media) > 0 && $this->page_image == null) {
             if ($this->extractMediaImage($pre_content, 'mod_page', 'content', 0, $context->id)) {
                 $this->page_image = "/images/" . resizeImage($this->courseroot . "/" . $this->page_image, $this->courseroot . "/images/" . $cm->id, $CFG->block_oppia_mobile_export_thumb_width, $CFG->block_oppia_mobile_export_thumb_height);
             }
         } else {
             if ($this->page_image == null) {
                 $piffilename = extractImageFile($page->content, 'mod_page', 'content', 0, $context->id, $this->courseroot, $cm->id);
                 if ($piffilename) {
                     $this->page_image = $piffilename;
                     $this->page_image = "/images/" . resizeImage($this->courseroot . "/" . $this->page_image, $this->courseroot . "/images/" . $cm->id, $CFG->block_oppia_mobile_export_thumb_width, $CFG->block_oppia_mobile_export_thumb_height);
                     unlink($this->courseroot . "/" . $piffilename) or die(get_string('error_file_delete', 'block_oppia_mobile_export'));
                 }
             }
         }
         $return_content = $content;
     }
     return $return_content;
 }
Example #25
0
    case 'et':
        $EpisodeInfo = $XBMC->GetEpisodeInformation($_GET['id']);
        $path = $EpisodeInfo['filePath'];
        $searchpath = $XBMC->XBMCUserDataPath . "Thumbnails/";
        break;
    case 'sb':
        $ShowInfo = $XBMC->RetrieveShowInfo($_GET['id']);
        $path = $ShowInfo['folder'];
        $searchpath = $XBMC->XBMCUserDataPath . "Thumbnails/";
        break;
    case 'sf':
        $ShowInfo = $XBMC->RetrieveShowInfo($_GET['id']);
        $path = $ShowInfo['folder'];
        $searchpath = $XBMC->XBMCUserDataPath . "Thumbnails/Video/Fanart/";
}
$filename = _get_hash($path) . ".tbn";
$filename2 = _get_hash($path) . ".jpg";
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($searchpath)) as $file => $cur) {
    if ($cur->getFilename() == $filename) {
        if ($_GET['ri'] == "1") {
            echo resizeImage($file, $_GET['w'], $_GET['h']);
        } else {
            echo file_get_contents($file);
        }
        break;
    }
    if ($cur->getFilename() == $filename2) {
        echo file_get_contents($file);
        break;
    }
}
Example #26
0
         if (!empty($_FILES[$profile_image]['name'])) {
             $allowed = array('jpg', 'jpeg', 'gif', 'png');
             $image_name = $_FILES[$profile_image]['name'];
             $explode = explode('.', $image_name);
             $image_extn = strtolower(end($explode));
             $image_temp = $_FILES[$profile_image]['tmp_name'];
             if (in_array($image_extn, $allowed)) {
                 $sql = $db->Query('SELECT profile_image FROM {users} WHERE user_id = ?', array(Post::val('user_id')));
                 $avatar_oldname = $db->FetchRow($sql);
                 if (is_file(BASEDIR . '/avatars/' . $avatar_oldname['profile_image'])) {
                     unlink(BASEDIR . '/avatars/' . $avatar_oldname['profile_image']);
                 }
                 $avatar_name = substr(md5(time()), 0, 10) . '.' . $image_extn;
                 $image_path = BASEDIR . '/avatars/' . $avatar_name;
                 move_uploaded_file($image_temp, $image_path);
                 resizeImage($avatar_name, $fs->prefs['max_avatar_size'], $fs->prefs['max_avatar_size']);
                 $db->Query('UPDATE {users} SET profile_image = ? WHERE user_id = ?', array($avatar_name, Post::num('user_id')));
             } else {
                 Flyspray::show_error(L('incorrectfiletype'));
                 break;
             }
         }
     }
 }
 // end only admin or user himself can change
 if ($user->perms('is_admin')) {
     if ($user->id == (int) Post::val('user_id')) {
         if (Post::val('account_enabled', 0) <= 0 || Post::val('old_global_id') != 1) {
             Flyspray::show_error(L('nosuicide'));
             break;
         }
Example #27
0
			<td class="td_center"><?php 
        echo $k + 1 + $start;
        ?>
</td>
			<td class="td_no_padd"><input type="checkbox" class="custom_chk" id="item<?php 
        echo $i;
        ?>
" onclick="selectItem(<?php 
        echo $i;
        ?>
)" value="<?php 
        echo $v->id;
        ?>
" /></td>
			<td class="td_center"><img class="img_block" alt="" src="<?php 
        echo resizeImage(PATH_URL . DIR_UPLOAD_SLIDER . $v->image, 150);
        ?>
" /></td>
			<td class="th_left"><a href="<?php 
        echo PATH_URL . 'admincp/' . $module . '/update/' . $v->id;
        ?>
"><?php 
        echo $v->name;
        ?>
</a></td>
			<td class="td_center" id="loadActiveID_<?php 
        echo $v->id;
        ?>
"><a href="javascript:void(0)" onclick="updateActive(<?php 
        echo $v->id;
        ?>
Example #28
0
             //this file could now has an unknown file extension (we hope it's one of the ones set above!)
             $large_image_location = $large_image_location . "." . $file_ext;
             $thumb_image_location = $thumb_image_location . "." . $file_ext;
             //put the file ext in the session so we know what file to look for once its uploaded
             $_SESSION['user_file_ext'] = "." . $file_ext;
             move_uploaded_file($userfile_tmp, $large_image_location);
             chmod($large_image_location, 0777);
             $width = getWidth($large_image_location);
             $height = getHeight($large_image_location);
             //Scale the image if it is greater than the width set above
             if ($width > $max_width) {
                 $scale = $max_width / $width;
                 $uploaded = resizeImage($large_image_location, $width, $height, $scale);
             } else {
                 $scale = 1;
                 $uploaded = resizeImage($large_image_location, $width, $height, $scale);
             }
             //Delete the thumbnail file so the user can create a new one
             if (file_exists($thumb_image_location)) {
                 unlink($thumb_image_location);
             }
         }
         //Refresh the page to show the new uploaded image
         header("location:" . $_SERVER["PHP_SELF"]);
         exit;
     }
 }
 if (isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists) > 0) {
     //Get the new coordinates to crop the image.
     $x1 = $_POST["x1"];
     $y1 = $_POST["y1"];
Example #29
0
 function prepareUpload($name, $kA, &$data)
 {
     # Returns the same errCode from storefile, plus 8 (unable to create thumbails), 9 (near time limit), 10 (quota exceeded)
     # file format should be [field][ids_]#_thumbid (or 1 for no thumb)
     if (!isset($_FILES[$name])) {
         return 4;
     } else {
         if ($_FILES[$name]['error'] < 5 && $_FILES[$name]['error'] != 0) {
             return $_FILES[$name]['error'];
         } else {
             if (!is_file($_FILES[$name]['tmp_name'])) {
                 return 3;
                 // file not found
             }
         }
     }
     $isImg = isset($this->fields[$name][CONS_XML_TWEAKIMAGES]) || isset($this->fields[$name][CONS_XML_THUMBNAILS]);
     if ($isImg) {
         # prepare thumbnail handling variables, as well conditional thumbs
         if (isset($this->fields[$name][CONS_XML_CONDTHUMBNAILS])) {
             //    />    'a'       'b'
             //   /    t1  t2     t1   t2
             // field:[   |   ;][   |    ;]
             preg_match("@ENUM \\(([^)]*)\\).*@", $this->fields[$this->fields[$name][CONS_XML_CONDTHUMBNAILS][0]][CONS_XML_SQL], $regs);
             $thumbsettings = explode(";", $this->fields[$name][CONS_XML_CONDTHUMBNAILS][1]);
             $enums = explode(",", $regs[1]);
             $c = 0;
             $found = false;
             foreach ($enums as $reg) {
                 if ($data[$this->fields[$name][CONS_XML_CONDTHUMBNAILS][0]] == str_replace("'", "", $reg)) {
                     $thumbsettings = explode("|", $thumbsettings[$c]);
                     $found = true;
                     break;
                 }
                 $c++;
             }
             if (!$found) {
                 $thumbsettings = isset($this->fields[$name][CONS_XML_THUMBNAILS]) ? $this->fields[$name][CONS_XML_THUMBNAILS] : explode("|", $thumbsettings[0]);
             }
         } else {
             $thumbsettings = isset($this->fields[$name][CONS_XML_THUMBNAILS]) ? $this->fields[$name][CONS_XML_THUMBNAILS] : array(array(0, 0));
         }
     }
     # quota test
     $this->parent->loadDimconfig(true);
     if (isset($this->parent->dimconfig['_usedquota']) && isset($this->parent->dimconfig['quota']) && $this->parent->dimconfig['quota'] > 0) {
         if ($this->parent->dimconfig['_usedquota'] > $this->parent->dimconfig['quota']) {
             return 10;
         }
         # quota exceeded
     }
     # prepares path
     $path = CONS_FMANAGER . $this->name . "/";
     if (!is_dir($path)) {
         makeDirs($path);
     }
     if (isset($this->fields[$name][CONS_XML_FILEPATH])) {
         # custom path
         $path .= $this->fields[$name][CONS_XML_FILEPATH];
         if ($path[strlen($path) - 1] != "/") {
             $path .= "/";
         }
         if (!is_dir($path)) {
             safe_mkdir($path);
         }
     }
     # prepares filename with item keys
     $filename = $name . "_";
     foreach ($kA as $id => $value) {
         $filename .= $value . "_";
     }
     # prepares filetype filter
     if (isset($this->fields[$name][CONS_XML_FILETYPES])) {
         $ftypes = "udef:" . $this->fields[$name][CONS_XML_FILETYPES];
     } else {
         $ftypes = "";
     }
     # prepares watermark and/or crop (for images)
     $WM_TODO = array();
     if (isset($this->fields[$name][CONS_XML_TWEAKIMAGES])) {
         foreach ($this->fields[$name][CONS_XML_TWEAKIMAGES] as $c => $WM) {
             # stamp:over(filename@x,y)[r] # [r] not implemented yet
             # stamp:under(filename@x,y)[r]
             # croptofit:top bottom left right
             # might have multiple with + separator
             $TODO = array();
             $WM = explode("+", $WM);
             foreach ($WM as $thisWM) {
                 $concept = explode(":", $thisWM);
                 if ($concept[0] == "stamp") {
                     $thisTODO = array();
                     $stamptype = explode("(", $concept[1]);
                     // ...(...@x,y)R
                     $parameters = explode(")", $stamptype[1]);
                     // ...@x,y)R
                     $stamptype = $stamptype[0];
                     $thisTODO['isBack'] = $stamptype == "under";
                     $resample = isset($parameters[1]) && $parameters[1] == "r";
                     $parameters = $parameters[0];
                     $parameters = explode("@", $parameters);
                     // ...@x,y
                     $parameters[1] = explode(",", $parameters[1]);
                     // x,y
                     $thisTODO['position'] = $parameters[1];
                     $thisTODO['filename'] = CONS_PATH_PAGES . $_SESSION['CODE'] . "/files/" . $parameters[0];
                     if ($resample) {
                         $thisTODO['resample'] = explode(",", $thumbsettings[$c]);
                     }
                     $TODO[] = $thisTODO;
                 } else {
                     if ($concept[0] == "croptofit") {
                         $TODO[] = "C" . (isset($concept[1]) ? $concept[1] : '');
                     }
                 }
             }
             $WM_TODO[$c] = $TODO;
         }
     }
     # perform upload and possible thumbnails if the file was uploaded
     $errCode = 4;
     # supose no upload
     if (isset($_FILES[$name])) {
         # initial size check (no need to even try if it's bigger)
         $mfs = isset($this->fields[$name][CONS_XML_FILEMAXSIZE]) ? $this->fields[$name][CONS_XML_FILEMAXSIZE] : 0;
         if ($mfs > 0 && !$isImg) {
             if (filesize($_FILES[$name]['tmp_name']) > $mfs) {
                 if (!isset($_FILES[$name]['virtual'])) {
                     @unlink($_FILES[$name]['tmp_name']);
                 }
                 return 2;
                 # file larger than allowed by field and is not an image (thus, we cannot reduce)
             }
         }
         # perform upload
         $thisFilename = $path . $filename . "1";
         $errCode = storeFile($_FILES[$name], $thisFilename, $ftypes);
         # <----------------- upload happens here
         //$errCode = storeFile($_FILES[$name],$thisFilename,$ftypes,true); # <----------------- use this (note the true) for full debug
         $arquivo = explode(".", $thisFilename);
         $ext = strtolower(array_pop($arquivo));
         # <-- ext for the file
         $arquivo = implode(".", $arquivo);
         # if ok and is an image, check thumbnails
         if ($errCode == 0 && $isImg) {
             # delete other images (could have uploaded a different image type than before on edit)
             $exts = array("jpg", "gif", "swf", "png", "jpeg", "ico", "bmp");
             foreach ($exts as $x => $sext) {
                 if ($sext != $ext && is_file($arquivo . "." . $sext)) {
                     @unlink($arquivo . "." . $sext);
                 }
             }
             # if this is not an JPG image, and it's larger then mfs, won't work at all. Abort
             if ($mfs > 0 && filesize($thisFilename) > $mfs && $ext != 'jpg') {
                 if (!isset($_FILES[$name]['virtual'])) {
                     @unlink($thisFilename);
                 }
                 return 2;
                 # file larger than allowed by field and is not a resizable image
             }
             if ($ext == "swf") {
                 // might have tweakimages (isImg) but accept flash
                 #check if the dimensions of the flash are too big
                 $dim = explode(",", $thumbsettings[0]);
                 $h = getimagesize($thisFilename);
                 if ($h[2] != IMAGETYPE_SWF && $h[2] != IMAGETYPE_SWC) {
                     die;
                     return 7;
                     // swf but not a swf!?
                 } else {
                     if ($h[0] > $dim[0] || $h[1] > $dim[1]) {
                         return 12;
                         // too big
                     }
                 }
             } else {
                 # $thisFilename has the image untreated.
                 # Create all thumbnails, then treat the main image:
                 $thumbVersions = count($thumbsettings);
                 if ($thumbVersions > 1) {
                     # has other versions/thumbnails, work these first
                     if (!is_dir($path . "t/")) {
                         makeDirs($path . "t/");
                     }
                     for ($tb = 1; $tb < $thumbVersions; $tb++) {
                         # for all thumbs ...
                         if ($this->parent->nearTimeLimit()) {
                             return 9;
                         }
                         $dim = explode(",", $thumbsettings[$tb]);
                         # remember, the array start at 0, not 1
                         $thisFilenameT = $path . "t/" . $filename . ($tb + 1);
                         if (!resizeImage($thisFilename, $thisFilenameT, $dim[0], isset($dim[1]) ? $dim[1] : 0, 0, isset($WM_TODO[$tb]) ? $WM_TODO[$tb] : array()) == 2) {
                             # error!
                             @unlink($thisFilename);
                             return 8;
                             // whoever called this function should also perform cleanup
                         }
                     }
                     #for each thumb
                 }
                 # done, process main image
                 $dim = explode(",", $thumbsettings[0]);
                 if (resizeImageCond($thisFilename, $dim[0], isset($dim[1]) ? $dim[1] : 0, isset($WM_TODO[0]) ? $WM_TODO[0] : array()) == 2) {
                     @unlink($thisFilename);
                     return 8;
                     // whoever called this function should also perform cleanup
                 }
                 # check mfs
                 clearstatcache();
                 # resize could have changed file size
                 if ($mfs > 0 && filesize($thisFilename) > $mfs) {
                     if ($ext == 'jpg') {
                         $miniatura_id = imagecreatefromjpeg($thisFilename);
                         imagejpeg($miniatura_id, $thisFilename, 50);
                         // reduce step2
                         imagedestroy($miniatura_id);
                         clearstatcache();
                         if (filesize($thisFilename) > $mfs) {
                             unlink($thisFilename);
                             return 2;
                             // unable to reduce more
                         }
                     } else {
                         # can't reduce quality on non-jpg
                         unlink($thisFilename);
                         return 2;
                         // unable to reduce more
                     }
                 }
             }
         }
     }
     # upload + image handling ok?
     if ($errCode == 0) {
         $this->parent->dimconfig['_usedquota'] += filesize($thisFilename);
         # simple quota controler, note this is not counting thumbs
         $this->parent->saveConfig();
     }
     return $errCode;
 }
Example #30
0
 function asset_add($asset_id)
 {
     if (!preg_match('/^[0-9]+$/', $asset_id)) {
         return 'Sorry No Related Content Available.';
     }
     $this->load->model('assets_m');
     $form = new HTMLQuickForm2('assets', 'POST', 'action="' . site_url('admin/assets/add/' . $asset_id) . '"');
     $form->setAttribute('enctype', 'multipart/form-data');
     if ($asset_id) {
         $assets = $this->assets_m->detailAsset($asset_id);
         $form->addDataSource(new HTML_QuickForm2_DataSource_Array(array('asset_id' => $assets['asset_id'], 'asset_name' => $assets['asset_name'], 'asset_type' => $assets['asset_type'], 'asset_platform' => $assets['asset_platform'], 'asset_bgcolor' => $assets['asset_bgcolor'])));
         if (!$assets) {
             return 'Sorry No Related Content Available.';
         }
     }
     $form->addElement('hidden', 'asset_id');
     $form->addElement('static', '', '', array('content' => '<b>Asset Name ?</b>'));
     $asset_name = $form->addElement('text', 'asset_name', array('style' => ''));
     $asset_name->addRule('required', 'Required', null, HTML_QuickForm2_Rule::SERVER);
     $form->addElement('static', '', '', array('content' => '<b>Asset Platform ?</b>'));
     $asset_platform = $form->addElement('select', 'asset_platform', '', array('options' => array('facebook' => 'On Facebook', 'mobile' => 'On Mobile Web')));
     $asset_platform->addRule('required', 'Required', null, HTML_QuickForm2_Rule::SERVER);
     $form->addElement('static', '', '', array('content' => '<b>Asset Type ?</b>'));
     $asset_type = $form->addElement('select', 'asset_type', '', array('options' => array('banner_header' => 'Banner Header', 'banner_main' => 'Banner Main', 'banner_footer' => 'Banner Footer', 'logo_main' => 'Campaign Main Logo', 'background_norepeat' => 'Background No Repeat', 'background_repeat' => 'Background Repeat')));
     $asset_type->addRule('required', 'Required', null, HTML_QuickForm2_Rule::SERVER);
     $form->addElement('static', '', '', array('content' => '<b>Default Background Color ? ex: #090909 </b>'));
     $asset_bgcolor = $form->addElement('text', 'asset_bgcolor', array('style' => 'width:100px;font-size:20;', 'size' => 7, 'maxlength' => 7));
     $asset_bgcolor->addRule('regex', 'Wrong Color Format', '/^#[a-zA-Z0-9]{6}$/');
     if ($asset_id) {
         $form->addElement('static', '', '', array('content' => '<img src="' . $assets['asset_url'] . '" />'));
     } else {
         $asset_uploadedtext = $form->addElement('static', '', '', array('content' => '<b>Upload Assets ? (GIF,JPG,PNG)</b>'));
         $asset_uploadedfile = $form->addElement('file', 'uploadedfile', 'size="80"');
         $asset_uploadedfile->addRule('mimetype', 'Asset is not a valid file type', array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png'), HTML_QuickForm2_Rule::SERVER);
         //$asset_file->addRule('maxfilesize', 'Asset filesize is exceeded ', $allowed_maxfilesize,HTML_QuickForm2_Rule::SERVER);
         $form->addElement('static', '', '', array('content' => '<b>Set Width Size? (Height resized by width Ratio)</b>'));
         $asset_resizeto = $form->addElement('select', 'asset_resizeto', '', array('options' => array('' => 'No Resizing', '90' => '90px', '100' => '100px', '120' => '120px', '200' => '220px', '320' => '320px', '400' => '400px', '520' => '520px', '760' => '760px', '810' => '810px')));
     }
     $button = $form->addElement('submit', '', 'value="Submit Asset"');
     if ($form->validate()) {
         $data = $form->getValue();
         unset($data['submit'], $data['_qf__assets']);
         if (isset($data['uploadedfile']['error']) && $data['uploadedfile']['error'] == UPLOAD_ERR_OK) {
             $asset_resizeto = $data['asset_resizeto'];
             unset($data['asset_resizeto']);
             $tmp_name = $data['uploadedfile']["tmp_name"];
             $time = md5(uniqid(rand(), true) . time());
             $filename = CAMPAIGN_IMAGE_DIR . "/" . $time . ".jpg";
             //Thumb Creation
             $thm = resizeImage($tmp_name, CAMPAIGN_IMAGE_DIR . "/thumb_" . $time . ".jpg", 100, null, true);
             if ($asset_resizeto) {
                 $img = resizeImage($tmp_name, $filename, $asset_resizeto, 'width');
             } else {
                 move_uploaded_file($tmp_name, $filename);
                 $img = $filename;
             }
             $info_img = getimagesize($img);
             $data['asset_basename'] = $time . ".jpg";
             $data['asset_width'] = isset($info_img[0]) ? $info_img[0] : '';
             $data['asset_height'] = isset($info_img[1]) ? $info_img[1] : '';
             $data['asset_mimetype'] = isset($info_img['mime']) ? $info_img['mime'] : '';
             //$data['asset_url'] = site_url('image/campaign').'?src='.$data['asset_basename'];
             //$data['asset_thumb_url'] = site_url('image/campaign').'?src=thumb_'.$data['asset_basename'];
             $data['asset_url'] = site_url('image/campaign/' . $data['asset_basename']);
             $data['asset_thumb_url'] = site_url('image/campaign/thumb_' . $data['asset_basename']);
             unset($data['uploadedfile']);
             $form->addElement('static', '', '', array('content' => '<div style="margin-top:10px;">Uploaded Asset :</div><div><img src="' . $data['asset_url'] . '" /></div>'));
         }
         if (isset($data['uploadedfile'])) {
             unset($data['uploadedfile']);
         }
         $ok = false;
         if ($asset_id) {
             if ($ok = $this->assets_m->updateAssets($data)) {
                 $this->notify->set_message('success', 'Data has been successfuly updated.');
             } else {
                 $this->notify->set_message('error', 'Data has failed to be updated.');
             }
         } else {
             unset($data['asset_id']);
             if ($ok = $this->assets_m->addAssets($data)) {
                 $this->notify->set_message('success', 'Data has been successfuly submitted.');
             } else {
                 $this->notify->set_message('error', 'Data has failed to be submitted.');
             }
         }
         if ($ok) {
             if (isset($asset_uploadedtext)) {
                 $form->removeChild($asset_uploadedtext);
             }
             if (isset($asset_uploadedfile)) {
                 $form->removeChild($asset_uploadedfile);
             }
             $form->removeChild($button);
             $form->toggleFrozen(true);
         }
     }
     $renderer = HTML_QuickForm2_Renderer::factory('default');
     $form_layout = $form->render($renderer);
     return $form_layout;
 }