public static function uploadPicture() { $user_id = Input::get('object_id'); $type = Input::get('object_type'); $user_id = Input::get('user_id'); $uploader = new Utils_Uploader(array('jpeg', 'jpg', 'png')); $path = DOCROOT . 'assets/uploads' . DS; if (!file_exists($path)) { mkdir($path, 0777, true); } $typeName = Model_Upload_Type::find($type)->types; $pic_name = $typeName . "_" . time(); $original = $path . $pic_name; $output = $uploader->handleUploadRename($path, $pic_name); if (isset($output['success'])) { $original = $path . $output['full_filename']; $uploadAll = Model_Upload::forge(); $uploadAll->user_id = $user_id; $uploadAll->type_id = $type; $uploadAll->name = $output['full_filename']; $uploadAll->original_name = $output['full_filename']; $uploadAll->path = $original; $uploadAll->save(); $output['upload_id'] = $uploadAll->id; Image::load($original)->preset($typeName)->save($original); $localFileName = $path . $output['full_filename']; $remoteFileName = DOCROOT . 'assets/uploads/' . DS . $output['full_filename']; $output['uri'] = Uri::create('upload/get_image/' . $output['full_filename'] . '/' . $output['upload_id']); } return $output; }
public function process(Version $version) { $fr = $version->getFileResource(); $image = \Image::load($fr->read()); $fr = $version->getFileResource(); $width = $this->getMaxWidth(); $height = $this->getMaxHeight(); $mode = $this->getConstraintMode(); $thumbnail = $image->thumbnail(new Box($width, $height), $mode); $mimetype = $fr->getMimeType(); $thumbnailOptions = array(); switch ($mimetype) { case 'image/jpeg': $thumbnailType = 'jpeg'; $thumbnailOptions = array('jpeg_quality' => \Config::get('concrete.misc.default_jpeg_image_compression')); break; case 'image/png': $thumbnailType = 'png'; break; case 'image/gif': $thumbnailType = 'gif'; break; case 'image/xbm': $thumbnailType = 'xbm'; break; case 'image/vnd.wap.wbmp': $thumbnailType = 'wbmp'; break; default: $thumbnailType = 'png'; break; } $version->updateContents($thumbnail->get($thumbnailType, $thumbnailOptions)); }
public function cropCoverPhoto($Croppath, $upload_id) { $uploader = new Utils_Uploader(array('jpeg', 'jpg', 'png')); $uploads = self::find($upload_id); $oldpath = $uploads->path; $oldname = $uploads->name; $uploadTypeModel = Model_Upload_Type::find($uploads->type_id); $typeName = $uploadTypeModel->types; if (file_exists($oldpath . $oldname)) { File::delete($oldpath . $oldname); } $img = $Croppath; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); $data = base64_decode($img); $file = $oldpath . "crop_image_" . $upload_id . ".png"; $original = $oldpath . $oldname; //$thumbnail = $path . 'min_' . $newFile; $success = file_put_contents($file, $data); //Image::load($file)->preset('coverimage')->save($thumbnail); //360 width Image::load($file)->preset($typeName)->save($original); //1260 width File::delete($file); return $oldname; }
protected function _processMedia($requestData, $mediaFile, $mediaInfo) { list($type, $id, $size, $filename) = $requestData; App::uses('Image', 'Media.Vendor'); $image = new Image(); $aSize = $this->PHMedia->getSizeInfo($size); $method = $this->PHMedia->getResizeMethod($size); $origImg = $this->PHMedia->getFileName($type, $id, null, $mediaInfo['fname'] . '.' . $mediaInfo['orig_ext']); if ($method == 'thumb') { $thumb = $this->PHMedia->getFileName($type, $id, null, 'thumb.png'); if (file_exists($thumb)) { $origImg = $thumb; } } if (!file_exists($origImg)) { $origImg = ROOT . DS . Configure::read('App.webroot') . DS . 'img' . DS . 'no-photo.jpg'; } $image->load($origImg); if ($aSize) { $method = $this->PHMedia->getResizeMethod($size); $image->{$method}($aSize['w'], $aSize['h']); } $folder = new Folder(dirname($mediaFile), true, 0755); if ($mediaInfo['ext'] == 'jpg') { $image->outputJpg($mediaFile); } elseif ($mediaInfo['ext'] == 'png') { $image->outputPng($mediaFile); } else { $image->outputGif($mediaFile); } }
public function action_index() { $is_chenged = false; if ($this->user->bank == null) { $this->user->bank = Model_Bank::forge(); $this->user->bank->user_id = $this->user->id; $this->user->bank->save(); } if (Input::post("firstname", null) != null and Security::check_token()) { $email = Input::post("email", null); if ($email != $this->user->email) { $check_user = Model_User::find("first", ["where" => [["email" => $email]]]); if ($check_user == null) { $this->email = $email; } else { $data["error"] = "This email is already in use."; } } $config = ["path" => DOCROOT . "assets/img/pictures/", 'randomize' => true, 'auto_rename' => true, 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png')]; Upload::process($config); if (Upload::is_valid()) { Upload::save(); $saved_result = Upload::get_files(); $file_name = $saved_result[0]['saved_as']; $image = Image::load($config["path"] . $file_name); $image->crop_resize(200, 200)->save($config["path"] . "m_" . $file_name); $image->crop_resize(86, 86)->save($config["path"] . "s_" . $file_name); $this->user->img_path = $file_name; } else { $error = Upload::get_errors(); } if (!isset($data["error"])) { $this->user->firstname = Input::post("firstname", ""); $this->user->middlename = Input::post("middlename", ""); $this->user->lastname = Input::post("lastname", ""); $this->user->google_account = Input::post("google_account", ""); $this->user->pr = Input::post("pr", ""); $this->user->educational_background = Input::post("educational_background", ""); $this->user->enchantJS = Input::post("enchantJS", 0); $this->user->trial = Input::post("trial", 0); $this->user->save(); $this->user->bank->name = Input::post("bank_name", ""); $this->user->bank->branch = Input::post("bank_branch", ""); $this->user->bank->account = Input::post("bank_account", ""); $this->user->bank->number = Input::post("bank_number", ""); $this->user->bank->etc = Input::post("bank_etc", ""); $this->user->bank->type = Input::post("bank_type", 0); $this->user->bank->save(); $is_chenged = true; } } $data["user"] = $this->user; $data["is_chenged"] = $is_chenged; $view = View::forge("teachers/profile", $data); $this->template->content = $view; }
public function update_item($post_data) { $upload_type = $this->def('upload_type', 'image'); $upload_dir = \Config::get($upload_type . '_dir', 'files'); $files = \Upload::get_files(); $clean_class = str_replace('\\', '', $this->class); foreach ($files as $key => $params) { if ($params['field'] == $clean_class . '-' . ($this->item->id ? $this->item->id : 'new') . "-{$this->field}") { $idx = $key; break; } } if (isset($idx)) { \Upload::save(array($idx), $this->def('secure') ? realpath(\Config::get('secure_dir', 'secure') . $upload_dir) : DOCROOT . $upload_dir); $errors = \Upload::get_errors(); if (!isset($errors[$idx])) { $files = \Upload::get_files(); $name = $files[$idx]['saved_as']; $path = $files[$idx]['saved_to']; if ($upload_type == 'image') { if ($dimensions = $this->def('dimension')) { // resize image $image = \Image::load($path . $name); foreach ($dimensions as $dim) { if (preg_match("/^(?P<width>[0-9]+)x(?P<height>[0-9]+)\$/i", $dim, $matches)) { $image->resize($matches['width'], $matches['height'])->save_pa(null, strtolower("_{$dim}")); } } } } elseif ($upload_type == 'audio') { if ($lengths = $this->def('truncate')) { if ($ffmpeg = \Config::get('ffmpeg')) { foreach ($lengths as $len) { // truncate audio track $sample = preg_replace("/^(.+)\\.([^\\.]+)\$/", '$1_sample_' . $len . '.$2', $name); // TODO: make an ffmpeg wrapper class shell_exec("{$ffmpeg} -i " . escapeshellarg($path . $name) . " -t {$length} -acodec copy " . escapeshellarg(DOCROOT . $upload_dir . DS . $sample)); } } else { error_log("could not truncate audio: ffmpeg not configured."); } } } $this->item->{$this->field} = $name; } else { error_log(print_r($errors, true)); return array('upload_error' => $this->def('desc') . ' failed to save. Error No. ' . $errors[$idx]['error']); } } return true; }
public function save_thumb() { $this->view(); $profile = $this->get('profile'); if (!is_object($profile) || $profile->getUserID() < 1) { return false; } if (isset($_POST['thumbnail']) && strlen($_POST['thumbnail'])) { $thumb = base64_decode($_POST['thumbnail']); $image = \Image::load($thumb); $profile->updateUserAvatar($image); } $this->redirect('/account/avatar', 'saved'); }
public function index($type, $id, $size, $filename) { App::uses('MediaPath', 'Media.Vendor'); $this->PHMedia = new MediaPath(); $fname = $this->PHMedia->getFileName($type, $id, $size, $filename); $aFName = $this->PHMedia->getFileInfo($filename); $this->response->header("Cache-Control", "max-age=2592000, must-revalidate"); $this->response->header("Expires", gmdate("D, d M Y H:i:s", time() + MONTH) . " GMT"); $this->response->header("Pragma", "cache"); if (file_exists($fname)) { $this->response->type($aFName['ext']); $this->response->file($fname); return $this->response; } App::uses('Image', 'Media.Vendor'); $image = new Image(); $aSize = $this->PHMedia->getSizeInfo($size); $method = $this->PHMedia->getResizeMethod($size); $origImg = $this->PHMedia->getFileName($type, $id, null, $aFName['fname'] . '.' . $aFName['orig_ext']); if ($method == 'thumb') { $thumb = $this->PHMedia->getFileName($type, $id, null, 'thumb.png'); if (file_exists($thumb)) { $origImg = $thumb; } } if (!file_exists($origImg)) { $origImg = ROOT . DS . Configure::read('App.webroot') . DS . 'img' . DS . 'no-photo.jpg'; } $image->load($origImg); if ($aSize) { $method = $this->PHMedia->getResizeMethod($size); $image->{$method}($aSize['w'], $aSize['h']); } //debug($fname); if ($aFName['ext'] == 'jpg') { $image->outputJpg($fname); $image->outputJpg(); } elseif ($aFName['ext'] == 'png') { $image->outputPng($fname); $image->outputPng(); } else { $image->outputGif($fname); $image->outputGif(); } exit; }
public function process(Version $version) { switch ($this->getFormat()) { case self::FORMAT_JPEG: $extension = 'jpg'; default: $extension = 'jpg'; break; } if ($extension) { $fr = $version->getFileResource(); $image = \Image::load($fr->read()); $filename = $version->getFileName(); $service = \Core::make('helper/file'); $newFilename = $service->replaceExtension($filename, $extension); $version->updateContents($image->get($extension)); $version->rename($newFilename); } }
/** * Resizes an Image to a given maximum width and height. * * @param string $file - absolute image path * @param integer $width - desired width of the image * @param integer $height - desired height of the image * @param string $mimetype - image type * * @return boolean - true if success, false otherwise */ public static function resize($file, $width, $height, $mimetype) { $jit_status = ExtensionManager::fetchStatus(array('handle' => 'jit_image_manipulation')); // process image using JIT mode 1 if ($jit_status[0] === EXTENSION_ENABLED) { require_once EXTENSIONS . '/jit_image_manipulation/lib/class.image.php'; try { $image = Image::load($file); // if not and Image, stick with original version if (!$image instanceof Image) { return false; } } catch (Exception $e) { return false; } $image->applyFilter('resize', array($width, $height)); $image->save($file, 85, null, $mimetype); } return true; }
public function action_index() { $is_chenged = false; if (Input::post("firstname", null) != null and Security::check_token()) { $email = Input::post("email", null); if ($email != $this->user->email) { $check_user = Model_User::find("first", ["where" => [["email" => $email]]]); if ($check_user == null) { $this->email = $email; } else { $data["error"] = "This email is already in use."; } } $config = ["path" => DOCROOT . "assets/img/pictures/", 'randomize' => true, 'auto_rename' => true, 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png')]; Upload::process($config); if (Upload::is_valid()) { Upload::save(); $saved_result = Upload::get_files(); $file_name = $saved_result[0]['saved_as']; $image = Image::load($config["path"] . $file_name); $image->crop_resize(200, 200)->save($config["path"] . "m_" . $file_name); $image->crop_resize(86, 86)->save($config["path"] . "s_" . $file_name); $this->user->img_path = $file_name; } else { $error = Upload::get_errors(); } if (!isset($data["error"])) { $this->user->firstname = Input::post("firstname", ""); $this->user->middlename = Input::post("middlename", ""); $this->user->lastname = Input::post("lastname", ""); $this->user->save(); $is_chenged = true; } } $data['pasts'] = Model_Lessontime::find("all", ["where" => [["student_id", $this->user->id], ["status", 2], ["language", Input::get("course", 0)], ["deleted_at", 0]]]); $data["donetrial"] = Model_Lessontime::find("all", ["where" => [["student_id", $this->user->id], ["status", 2], ["language", Input::get("course", -1)], ["deleted_at", 0]]]); $data["user"] = $this->user; $data["is_chenged"] = $is_chenged; $view = View::forge("students/profile", $data); $this->template->content = $view; }
public function index($type, $id, $size, $filename) { App::uses('MediaPath', 'Media.Vendor'); $this->PHMedia = new MediaPath(); $fname = $this->PHMedia->getFileName($type, $id, $size, $filename); $aFName = $this->PHMedia->getFileInfo($filename); if (file_exists($fname)) { header('Content-type: image/' . $aFName['ext']); echo file_get_contents($fname); exit; } App::uses('Image', 'Media.Vendor'); $image = new Image(); $aSize = $this->PHMedia->getSizeInfo($size); $method = $this->PHMedia->getResizeMethod($size); $origImg = $this->PHMedia->getFileName($type, $id, null, $aFName['fname'] . '.' . $aFName['orig_ext']); if ($method == 'thumb') { $thumb = $this->PHMedia->getFileName($type, $id, null, 'thumb.png'); if (file_exists($thumb)) { $origImg = $thumb; } } $image->load($origImg); if ($aSize) { $method = $this->PHMedia->getResizeMethod($size); $image->{$method}($aSize['w'], $aSize['h']); } if ($aFName['ext'] == 'jpg') { $image->outputJpg($fname); $image->outputJpg(); } elseif ($aFName['ext'] == 'png') { $image->outputPng($fname); $image->outputPng(); } else { $image->outputGif($fname); $image->outputGif(); } exit; }
/** * Действие для редактирования фотографии * * @param int $id */ public function action_edit($id = null) { is_null($id) and \Response::redirect('admin/media/photos/categories'); if (!($photo = \Model_Media_Photo::find($id, array('related' => 'category')))) { \Session::set_flash('error', 'Фотография не найдена.'); \Response::redirect('admin/media/photos/categories'); } $val = \Model_Media_Photo::validate('edit'); if ($val->run()) { // Загружаем файл $config = array('path' => DOCROOT . 'assets/img/gallery', 'randomize' => true, 'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png')); \Upload::process($config); if (\Upload::is_valid()) { // Сохраняем файл на диск \Upload::save(); // Меняем размер изображения на 1024px * 768px $files = \Upload::get_files(); $path = $files[0]['saved_to'] . $files[0]['saved_as']; \Image::load($path)->resize(1024, 768, true)->save($path); // Создаём thumbnail $thumb_path = $files[0]['saved_to'] . 'thumbnails/' . $files[0]['saved_as']; \Image::load($path)->resize(400, 300, true)->save($thumb_path); // Удаляем старые файлы unlink(DOCROOT . 'assets/img/gallery/' . $photo->image_path); unlink(DOCROOT . 'assets/img/gallery/thumbnails/' . $photo->image_path); // Пишем инфу в БД $photo->image_path = $files[0]['saved_as']; if ($photo->save()) { \Session::set_flash('success', 'Фотография обновлена.'); \Response::redirect('admin/media/photos/list/index/' . $photo->category->id); } else { \Session::set_flash('error', 'Could not update Media_Photo #' . $id); } } } else { if (\Input::method() == 'POST') { \Session::set_flash('error', $val->error()); } $this->template->set_global('photo', $photo, false); } $this->template->title = 'Фотогалерея "' . $photo->category->title . '"'; $this->template->content = \View::forge('media/photos/list/edit'); }
if (!isset($_JPOST->backgroundColor) || $_JPOST->backgroundColor == '') { $_JPOST->backgroundColor = new stdClass(); $_JPOST->backgroundColor->red = 255; $_JPOST->backgroundColor->green = 255; $_JPOST->backgroundColor->blue = 255; $_JPOST->backgroundColor->alpha = 1; } imagefill($img->image, 0, 0, imagecolorallocatealpha($img->image, $_JPOST->backgroundColor->red, $_JPOST->backgroundColor->green, $_JPOST->backgroundColor->blue, $_JPOST->backgroundColor->alpha * 127.0)); $img->image_type = IMAGETYPE_PNG; # Adding our images for ($i = 0, $icount = count($_JPOST->images); $i < $icount; $i++) { # Storing our image $img_details = $_JPOST->images[$i]; # Getting our image $tmpimg = new Image(); $tmpimg->load($img_details->src); # Our dimentions $x = (int) $img_details->x; $y = (int) $img_details->y; $width = (int) $img_details->width; $height = (int) $img_details->height; $rotate = (double) $img_details->rotate; switch ($img_details->size) { case 'contain': # Calaulating our actual widths/heights $px = $width / $tmpimg->getWidth(); $py = $height / $tmpimg->getHeight(); # Getting our percentages if ($px >= $py) { $py /= $px; $px = 1.0;
/** * Save thumbnail * * params int $id Article-ID * params boolean $is_upthumb Upload thumbnail or not * * @author Nguyen Van Hiep * @author Dao Anh Minh * @access public * * @version 1.0 * @since 1.0 */ protected function save_thumb($id, $is_upthumb) { if (!$is_upthumb) { return; } Upload::save(); $info = Upload::get_files(0); $filepath = $info['saved_to'] . $info['saved_as']; $name = 'a' . $id . '_' . str_replace('-', '_', $info['saved_as']); $image = Image::load($filepath); $image->save($this->dir . $name); File::delete($filepath); Model_Article::save_thumb($id, $name); }
/** * Returns a path to the specified item, resized and/or cropped to meet max width and height. $obj can either be * a string (path) or a file object. * Returns an object with the following properties: src, width, height * @param mixed $obj * @param int $maxWidth * @param int $maxHeight * @param bool $crop */ public function getThumbnail($obj, $maxWidth, $maxHeight, $crop = false) { $fID = false; $fh = Loader::helper('file'); if ($obj instanceof File) { try { $fr = $obj->getFileResource(); $fID = $obj->getFileID(); $filename = md5(implode(':', array($fID, $maxWidth, $maxHeight, $crop, $fr->getTimestamp()))) . '.' . $fh->getExtension($fr->getPath()); } catch (\Exception $e) { $filename = ''; } } else { $filename = md5(implode(':', array($obj, $maxWidth, $maxHeight, $crop, filemtime($obj)))) . '.' . $fh->getExtension($obj); } if (!file_exists(Config::get('concrete.cache.directory') . '/' . $filename)) { if ($obj instanceof File) { $image = \Image::load($fr->read()); } else { $image = \Image::open($obj); } // create image there $this->create($image, Config::get('concrete.cache.directory') . '/' . $filename, $maxWidth, $maxHeight, $crop); } $src = REL_DIR_FILES_CACHE . '/' . $filename; $abspath = Config::get('concrete.cache.directory') . '/' . $filename; $thumb = new \stdClass(); if (isset($abspath) && file_exists($abspath)) { $thumb->src = $src; $dimensions = getimagesize($abspath); $thumb->width = $dimensions[0]; $thumb->height = $dimensions[1]; return $thumb; } }
/** * Add a post */ public function iframe_add() { $this->setView('iframe_add.php'); @set_time_limit(0); $uploaded_files = array(); try { if (!isset(User_Model::$auth_data)) { throw new Exception(__('POST_ADD_ERROR_SESSION_EXPIRED')); } $is_student = isset(User_Model::$auth_data['student_number']); // Message $message = isset($_POST['message']) ? trim($_POST['message']) : ''; if ($message == '' || $message == __('PUBLISH_DEFAULT_MESSAGE')) { throw new Exception(__('POST_ADD_ERROR_NO_MESSAGE')); } $message = preg_replace('#\\n{2,}#', "\n\n", $message); // Category if (!isset($_POST['category']) || !ctype_digit($_POST['category'])) { throw new Exception(__('POST_ADD_ERROR_NO_CATEGORY')); } $category = (int) $_POST['category']; // Official post (in a group) $official = isset($_POST['official']); // Group $group = isset($_POST['group']) && ctype_digit($_POST['group']) ? (int) $_POST['group'] : 0; if ($group == 0) { $group = null; $official = false; } else { $groups_auth = Group_Model::getAuth(); if (isset($groups_auth[$group])) { if ($official && !$groups_auth[$group]['admin']) { throw new Exception(__('POST_ADD_ERROR_OFFICIAL')); } } else { throw new Exception(__('POST_ADD_ERROR_GROUP_NOT_FOUND')); } } // Private message $private = isset($_POST['private']); if ($private && !$is_student) { throw new Exception(__('POST_ADD_ERROR_PRIVATE')); } $attachments = array(); // Photos if (isset($_FILES['attachment_photo']) && is_array($_FILES['attachment_photo']['name'])) { foreach ($_FILES['attachment_photo']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_PHOTO) { throw new Exception(__('POST_ADD_ERROR_PHOTO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_PHOTO)))); } } if ($filepaths = File::upload('attachment_photo')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { $name = isset($_FILES['attachment_photo']['name'][$i]) ? $_FILES['attachment_photo']['name'][$i] : ''; try { $img = new Image(); $img->load($filepath); $type = $img->getType(); if ($type == IMAGETYPE_JPEG) { $ext = 'jpg'; } else { if ($type == IMAGETYPE_GIF) { $ext = 'gif'; } else { if ($type == IMAGETYPE_PNG) { $ext = 'png'; } else { throw new Exception(); } } } if ($img->getWidth() > 800) { $img->setWidth(800, true); } $img->save($filepath); // Thumb $thumbpath = $filepath . '.thumb'; $img->thumb(Config::$THUMBS_SIZES[0], Config::$THUMBS_SIZES[1]); $img->setType(IMAGETYPE_JPEG); $img->save($thumbpath); unset($img); $attachments[] = array($filepath, $name, $thumbpath); $uploaded_files[] = $thumbpath; } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_PHOTO_FORMAT')); } } } } // Vidéos /* @uses PHPVideoToolkit : http://code.google.com/p/phpvideotoolkit/ * @requires ffmpeg, php5-ffmpeg */ if (isset($_FILES['attachment_video']) && is_array($_FILES['attachment_video']['name'])) { foreach ($_FILES['attachment_video']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_VIDEO) { throw new Exception(__('POST_ADD_ERROR_VIDEO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_VIDEO)))); } } if ($filepaths = File::upload('attachment_video')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { $name = isset($_FILES['attachment_video']['name'][$i]) ? $_FILES['attachment_video']['name'][$i] : ''; try { $video = new ffmpeg_movie($filepath, false); if (!$video->hasVideo()) { throw new Exception('No video stream found in the file'); } if (!$video->hasAudio()) { throw new Exception('No audio stream found in the file'); } } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_VIDEO_FORMAT')); } // Video conversion try { $video_current_width = $video->getFrameWidth(); $video_width = min($video_current_width, Config::VIDEO_MAX_WIDTH); if ($video_width % 2 == 1) { // Even number required $video_width--; } $video_height = $video_width * $video->getFrameHeight() / $video_current_width; if ($video_height % 2 == 1) { // Even number required $video_height--; } // Extract thumb $video_thumb = $video->getFrame(round($video->getFrameCount() * 0.2)); unset($video); $video_thumb = $video_thumb->toGDImage(); $thumbpath = DATA_DIR . Config::DIR_DATA_TMP . File::getName($filepath) . '.thumb'; imagejpeg($video_thumb, $thumbpath, 95); unset($video_thumb); $img = new Image(); $img->load($thumbpath); $img->setWidth($video_width, true); $img->setType(IMAGETYPE_JPEG); $img->save($thumbpath); $uploaded_files[] = $thumbpath; unset($img); // Convert to FLV if (!preg_match('#\\.flv$#i', $filepath)) { $toolkit = new PHPVideoToolkit(); $toolkit->on_error_die = true; // Will throw exception on error $toolkit->setInputFile($filepath); $toolkit->setVideoOutputDimensions($video_width, $video_height); $toolkit->setFormatToFLV(Config::VIDEO_SAMPLING_RATE, Config::VIDEO_AUDIO_BIT_RATE); $toolkit->setOutput(DATA_DIR . Config::DIR_DATA_TMP, File::getName($filepath) . '.flv', PHPVideoToolkit::OVERWRITE_EXISTING); $toolkit->execute(false, false); // Multipass: false, Log: false File::delete($filepath); $filepath = $toolkit->getLastOutput(); $filepath = $filepath[0]; unset($toolkit); } $attachments[] = array($filepath, $name, $thumbpath); $uploaded_files[] = $filepath; } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_VIDEO_CONVERT') . $e->getMessage()); } } } } // Audios if (isset($_FILES['attachment_audio']) && is_array($_FILES['attachment_audio']['name'])) { foreach ($_FILES['attachment_audio']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_AUDIO) { throw new Exception(__('POST_ADD_ERROR_AUDIO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_AUDIO)))); } } if ($filepaths = File::upload('attachment_audio')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { if (!preg_match('#\\.mp3$#', $filepath)) { throw new Exception(__('POST_ADD_ERROR_AUDIO_FORMAT')); } $name = isset($_FILES['attachment_audio']['name'][$i]) ? $_FILES['attachment_audio']['name'][$i] : ''; $attachments[] = array($filepath, $name); } } } // Files if (isset($_FILES['attachment_file']) && is_array($_FILES['attachment_file']['name'])) { foreach ($_FILES['attachment_file']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_FILE) { throw new Exception(__('POST_ADD_ERROR_FILE_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_FILE)))); } } if ($filepaths = File::upload('attachment_file')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { if (!preg_match('#\\.[a-z0-9]{2,4}$#i', $filepath)) { throw new Exception(__('POST_ADD_ERROR_FILE_FORMAT')); } if (preg_match('#\\.(jpg|png|gif|mp3|flv)$#i', $filepath)) { throw new Exception(__('POST_ADD_ERROR_FILE_FORMAT2')); } $name = isset($_FILES['attachment_file']['name'][$i]) ? $_FILES['attachment_file']['name'][$i] : ''; $attachments[] = array($filepath, $name); } } } // Event if (isset($_POST['event_title']) && isset($_POST['event_start']) && isset($_POST['event_end'])) { // Title $event_title = trim($_POST['event_title']); if ($event_title == '') { throw new Exception(__('POST_ADD_ERROR_EVENT_NO_TITLE')); } // Dates if (!($event_start = strptime($_POST['event_start'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE')); } if (!($event_end = strptime($_POST['event_end'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE')); } $event_start = mktime($event_start['tm_hour'], $event_start['tm_min'], 0, $event_start['tm_mon'] + 1, $event_start['tm_mday'], $event_start['tm_year'] + 1900); $event_end = mktime($event_end['tm_hour'], $event_end['tm_min'], 0, $event_end['tm_mon'] + 1, $event_end['tm_mday'], $event_end['tm_year'] + 1900); if ($event_start > $event_end) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE_ORDER')); } $event = array($event_title, $event_start, $event_end); } else { $event = null; } // Survey if (isset($_POST['survey_question']) && isset($_POST['survey_end']) && isset($_POST['survey_answer']) && is_array($_POST['survey_answer'])) { // Question $survey_question = trim($_POST['survey_question']); if ($survey_question == '') { throw new Exception(__('POST_ADD_ERROR_SURVEY_NO_QUESTION')); } // Date if (!($survey_end = strptime($_POST['survey_end'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_SURVEY_DATE')); } $survey_end = mktime($survey_end['tm_hour'], $survey_end['tm_min'], 0, $survey_end['tm_mon'] + 1, $survey_end['tm_mday'], $survey_end['tm_year'] + 1900); // Multiple answers $survey_multiple = isset($_POST['survey_multiple']); // Answers $survey_answers = array(); foreach ($_POST['survey_answer'] as $survey_answer) { $survey_answer = trim($survey_answer); if ($survey_answer != '') { $survey_answers[] = $survey_answer; } } if (count($survey_answers) < 2) { throw new Exception(__('POST_ADD_ERROR_SURVEY_ANSWERS')); } $survey = array($survey_question, $survey_end, $survey_multiple, $survey_answers); } else { $survey = null; } // Creation of the post $id = $this->model->addPost((int) User_Model::$auth_data['id'], $message, $category, $group, $official, $private); // Attach files foreach ($attachments as $attachment) { $this->model->attachFile($id, $attachment[0], $attachment[1], isset($attachment[2]) ? $attachment[2] : null); } // Event if (isset($event)) { $this->model->attachEvent($id, $event[0], $event[1], $event[2]); } // Survey if (isset($survey)) { $this->model->attachSurvey($id, $survey[0], $survey[1], $survey[2], $survey[3]); } $this->addJSCode(' parent.location = "' . Config::URL_ROOT . Routes::getPage('home') . '"; '); } catch (Exception $e) { // Delete all uploading files in tmp foreach ($uploaded_files as $uploaded_file) { File::delete($uploaded_file); } $this->addJSCode(' with(parent){ Post.errorForm(' . json_encode($e->getMessage()) . '); } '); } }
/** * Proccess Image * Generate a image the first time is requested to be served by apache later * To take advantage of this service, you should use Apache Header module width Header set Cache-Control * @return void */ public static function ProcessImage() { $id = Util::getvalue('id'); $args = Util::getvalue('params'); $ext = Util::getvalue('ext'); $options = array('id' => $id, 'width' => false, 'height' => false, 'quality' => false, 'type' => 'resize'); // Parametro Ancho if (preg_match('/w([0-9]+)/i', $args, $outputWidth)) { $options['width'] = $outputWidth[1]; } // Parametro Alto if (preg_match('/h([0-9]+)/i', $args, $outputHeight)) { $options['height'] = $outputHeight[1]; } // Parametro calidad if (preg_match('/q(100|\\d{1,2})/i', $args, $outputHeight)) { $options['quality'] = $outputHeight[1]; } // Type Crop / Resize $arr = explode('.', $args); if (strpos($arr[0], 'c') !== false) { $options['type'] = 'crop'; } // Extension del archivo solicitado $fileType = $ext ? strtolower($ext) : 'jpg'; $fileType = substr($fileType, 0, 3); $fileType = $fileType == 'jpe' ? 'jpg' : $fileType; $fileType = '.' . $fileType; // Ruta del a imagen origina en disco $sourceOpt = array('module' => 'image', 'folderoption' => 'target'); $sourceDir = PathManager::GetContentTargetPath($sourceOpt); $sourcePath = PathManager::GetDirectoryFromId($sourceDir, $id); $source = $sourcePath . '/' . $id . $fileType; $imageDir = PathManager::GetApplicationPath() . Configuration::Query('/configuration/images_bucket')->item(0)->nodeValue; if (!is_dir($imageDir)) { mkdir($imageDir, 0777); } $imagePath = PathManager::GetDirectoryFromId($imageDir, $id); $image = $imagePath . '/' . $id; // El nombre del archivo contendrá los parametros para ser servida de manera estatica if ($options['width']) { $image .= 'w' . $options['width']; } if ($options['height']) { $image .= 'h' . $options['height']; } if ($options['quality'] !== false) { $image .= 'q' . $options['quality']; } if ($options['type'] == 'crop') { $image .= 'c'; } if (!file_exists($source)) { $source = PathManager::GetApplicationPath() . '/content/not-found' . $fileType; } list($sourceWidth, $sourceHeight) = getimagesize($source); /* Si no esta definido el ancho o el alto debemos asignar limites por defecto para la generación de la imagen */ $options['width'] = $options['width'] ? $options['width'] : $sourceWidth; $options['height'] = $options['height'] ? $options['height'] : $sourceHeight; // Generar la imagen $img = new Image(); $img->load($source); $img->{$options}['type']($options['width'], $options['height']); /* Guardar la imagen en disco el próximo pedido será servido estáticamente por apache */ $quality = $options['quality'] !== false ? $options['quality'] : '80'; $img->save($image, $quality); /* Mostrar la imagen */ $img->display(); }
/** * Returns a path to the specified item, resized and/or cropped to meet max width and height. $obj can either be * a string (path) or a file object. * Returns an object with the following properties: src, width, height * * @param File|string $obj * @param int $maxWidth * @param int $maxHeight * @param bool $crop * @return \stdClass Object that has the following properties: src, width, height */ public function getThumbnail($obj, $maxWidth, $maxHeight, $crop = false) { $storage = $this->getStorageLocation(); $filesystem = $storage->getFileSystemObject(); $configuration = $storage->getConfigurationObject(); $fh = \Core::make('helper/file'); if ($obj instanceof File) { try { $fr = $obj->getFileResource(); $fID = $obj->getFileID(); $filename = md5(implode(':', array($fID, $maxWidth, $maxHeight, $crop, $fr->getTimestamp()))) . '.' . $fh->getExtension($fr->getPath()); } catch (\Exception $e) { $filename = ''; } } else { $filename = md5(implode(':', array($obj, $maxWidth, $maxHeight, $crop, filemtime($obj)))) . '.' . $fh->getExtension($obj); } $abspath = '/cache/' . $filename; if (!$filesystem->has($abspath)) { if ($obj instanceof File && $fr->exists()) { $image = \Image::load($fr->read()); } else { $image = \Image::open($obj); } // create image there $this->create($image, $abspath, $maxWidth, $maxHeight, $crop); } $src = $configuration->getPublicURLToFile($abspath); $thumb = new \stdClass(); $thumb->src = $src; //this is terrible try { //try and get it locally, otherwise use http $dimensions = getimagesize($abspath); } catch (\Exception $e) { //$dimensions = getimagesize($src); } $thumb->width = $dimensions[0]; $thumb->height = $dimensions[1]; return $thumb; }
curl_setopt($ch, CURLOPT_URL, $_JPOST->src); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $results = split("\n", trim(curl_exec($ch))); foreach ($results as $line) { if (strtok($line, ':') == 'Content-Type') { $parts = explode(":", $line); if (substr(trim($parts[1]), 0, 6) != 'image/') { exit_fail(NQ_ERROR_INVALID_VALUE, LANG_INVALID_IMAGE . $line); } } } # Getting our image $img = new Image(); $img->load($_JPOST->src); # Checking our image if ((int) $img->getWidth() < 1 || (int) $img->getHeight() < 1) { exit_fail(NQ_ERROR_INVALID_VALUE, LANG_INVALID_IMAGE); } # Making sure we have our open directories $G_PATH_DATA = parse_path($_JPOST->dir, $_ENDPOINT, $G_TOKEN_SESSION_DATA); $G_DIRECTORY_DATA = directory_hierarchy($G_STORAGE_CONTROLLER_DBLINK, $G_APP_DATA['id'], $G_APP_ENVIRONMENT, $G_PATH_DATA->absolute, $G_APP_DATA['img_auto_makedir'] == 1); # If we aren't allowed we exit check_directory_blacklisted($G_CONTROLLER_DBLINK, $G_TOKEN_DATA['id'], $G_TOKEN_SESSION_DATA, $G_DIRECTORY_DATA['path'] . $G_DIRECTORY_DATA['name']); # Getting our server where we are going to store the images $query = "\tSELECT\n\t\t\t\t*\n\t\t\tFROM\n\t\t\t\t" . NQ_SERVERS_TABLE . "\n\t\t\tWHERE\n\t\t\t\t`server_type`\t='image' AND\n\t\t\t\t`environment`\t='" . mysqli_escape_string($G_CONTROLLER_DBLINK, $G_APP_ENVIRONMENT) . "'\n\t\t\tORDER BY\n\t\t\t\t`tier` ASC,\n\t\t\t\t`available_space` DESC\n\t\t\tLIMIT 1"; $G_SERVER_DATA = mysqli_single_result_query($G_CONTROLLER_DBLINK, $query); # Combining our host properties into our path $G_SERVER_HOST = NQ_FILE_STORAGE_PROTOCOL . $G_SERVER_DATA['username'] . NQ_FILE_STORAGE_CRED_SEPARATOR . $G_SERVER_DATA['password'] . NQ_FILE_STORAGE_HOST_SEPARATOR . $G_SERVER_DATA['host'] . $G_SERVER_DATA['path']; # Getting our metadata
check_directory_blacklisted($G_CONTROLLER_DBLINK, $tid, $G_TOKEN_SESSION_DATA, $G_DIRECTORY_DATA['path'] . $G_DIRECTORY_DATA['name'], true); # Getting our live file $query = "\tSELECT\n\t\t\t\t*\n\t\t\tFROM\n\t\t\t\t" . NQ_FILE_TABLE . "\n\t\t\tWHERE \n\t\t\t\t`app_id`\t=" . (int) $G_APP_DATA['id'] . " AND\n\t\t\t\t`environment`\t='" . mysqli_escape_string($G_STORAGE_CONTROLLER_DBLINK, $G_APP_ENVIRONMENT) . "' AND\n\t\t\t\t`directory_id`\t=" . (int) $G_DIRECTORY_DATA['id'] . " AND\n\t\t\t\t`name`\t\t='" . mysqli_escape_string($G_STORAGE_CONTROLLER_DBLINK, $_JPOST->name) . "'\n\t\t\tLIMIT 1"; $current_file_data = mysqli_single_result_query($G_STORAGE_CONTROLLER_DBLINK, $query); # Invalid file to modify if (!isset($current_file_data['id'])) { exit_fail(NQ_ERROR_INVALID_VALUE, LANG_INVALID_FILE); } # Getting our server where we the image is stored $query = "\tSELECT\n\t\t\t\t*\n\t\t\tFROM\n\t\t\t\t" . NQ_SERVERS_TABLE . "\n\t\t\tWHERE\n\t\t\t\t`id`=" . (int) $current_file_data['host_id'] . "\n\t\t\tLIMIT 1"; $G_SERVER_DATA = mysqli_single_result_query($G_CONTROLLER_DBLINK, $query); # Combining our host properties into our path $G_SERVER_HOST = NQ_FILE_STORAGE_PROTOCOL . $G_SERVER_DATA['username'] . NQ_FILE_STORAGE_CRED_SEPARATOR . $G_SERVER_DATA['password'] . NQ_FILE_STORAGE_HOST_SEPARATOR . $G_SERVER_DATA['host'] . $G_SERVER_DATA['path']; # Loading the image $img = new Image(); $img->load($G_SERVER_HOST . $current_file_data['filepath']); # Applying our actions foreach ($_JPOST->actions as $action => $value) { switch ($action) { case 'flip': $img->flip($value); break; } } # Moving our file version $query = "\tINSERT INTO\n\t\t\t\t" . NQ_FILE_VERSION_TABLE . "\n\t\t\t\t(\n\t\t\t\t\tSELECT\n\t\t\t\t\t\t*\n\t\t\t\t\tFROM\n\t\t\t\t\t\t" . NQ_FILE_TABLE . "\n\t\t\t\t\tWHERE\n\t\t\t\t\t\t`id`=" . (int) $current_file_data['id'] . "\n\t\t\t\t)"; mysqli_sub_query($G_STORAGE_CONTROLLER_DBLINK, $query); # Deleting our file $query = "\tDELETE FROM\n\t\t\t\t" . NQ_FILE_TABLE . "\n\t\t\tWHERE\n\t\t\t\t`id`=" . (int) $current_file_data['id'] . "\n\t\t\tLIMIT 1"; mysqli_sub_query($G_STORAGE_CONTROLLER_DBLINK, $query); # Getting our server where we are going to store the images
/** * Add a group */ public function add($params) { $this->setView('add.php'); $this->setTitle(__('GROUP_ADD_TITLE')); $is_logged = isset(User_Model::$auth_data); $is_admin = $is_logged && User_Model::$auth_data['admin'] == '1'; // Authorization if (!$is_admin) { throw new ActionException('Page', 'error404'); } $group = array(); // Saving data if (isset($_POST['name']) && isset($_POST['creation_date']) && isset($_POST['mail']) && isset($_POST['description'])) { $uploaded_files = array(); try { // Members $members = array(); if (isset($_POST['members_ids']) && is_array($_POST['members_ids'])) { foreach ($_POST['members_ids'] as $id) { if (ctype_digit($id)) { $id = (int) $id; $members[$id] = array('title' => isset($_POST['member_title_' . $id]) ? $_POST['member_title_' . $id] : '', 'admin' => isset($_POST['member_admin_' . $id])); } } } // Other info $data = array('name' => $_POST['name'], 'creation_date' => $_POST['creation_date'], 'mail' => $_POST['mail'], 'description' => $_POST['description'], 'members' => $members); // Avatar if (isset($_FILES['avatar']) && !is_array($_FILES['avatar']['name'])) { if ($_FILES['avatar']['size'] > Config::UPLOAD_MAX_SIZE_PHOTO) { throw new FormException('avatar'); } if ($avatarpath = File::upload('avatar')) { $uploaded_files[] = $avatarpath; try { $img = new Image(); $img->load($avatarpath); $type = $img->getType(); if ($type == IMAGETYPE_JPEG) { $ext = 'jpg'; } else { if ($type == IMAGETYPE_GIF) { $ext = 'gif'; } else { if ($type == IMAGETYPE_PNG) { $ext = 'png'; } else { throw new Exception(); } } } if ($img->getWidth() > 800) { $img->setWidth(800, true); } $img->setType(IMAGETYPE_JPEG); $img->save($avatarpath); // Thumb $avatarthumbpath = $avatarpath . '.thumb'; $img->thumb(Config::$AVATARS_THUMBS_SIZES[0], Config::$AVATARS_THUMBS_SIZES[1]); $img->setType(IMAGETYPE_JPEG); $img->save($avatarthumbpath); unset($img); $uploaded_files[] = $avatarthumbpath; $data['avatar_path'] = $avatarthumbpath; $data['avatar_big_path'] = $avatarpath; } catch (Exception $e) { throw new FormException('avatar'); } } } $url_name = $this->model->create($data); Routes::redirect('group', array('group' => $url_name)); } catch (FormException $e) { foreach ($uploaded_files as $uploaded_file) { File::delete($uploaded_file); } foreach ($data as $key => $value) { $group[$key] = $value; } $group['members'] = Student_Model::getInfoByUsersIds(array_keys($members)); foreach ($group['members'] as &$member) { if (isset($members[(int) $member['user_id']])) { $member['title'] = $members[(int) $member['user_id']]['title']; $member['admin'] = $members[(int) $member['user_id']]['admin'] ? '1' : '0'; } } $this->set('form_error', $e->getError()); } } $this->set('group', $group); $this->addJSCode('Group.initEdit();'); }
public function rescanThumbnails() { $types = Type::getVersionList(); foreach ($types as $type) { $fr = $this->getFileResource(); // delete the file if it exists $this->deleteThumbnail($type); if ($this->getAttribute('width') <= $type->getWidth()) { continue; } $image = \Image::load($fr->read()); $filesystem = $this->getFile()->getFileStorageLocationObject()->getFileSystemObject(); $height = $type->getHeight(); $thumbnailMode = ImageInterface::THUMBNAIL_OUTBOUND; if (!$height) { $height = $type->getWidth(); $thumbnailMode = ImageInterface::THUMBNAIL_INSET; } $thumbnail = $image->thumbnail(new \Imagine\Image\Box($type->getWidth(), $height), $thumbnailMode); $thumbnailPath = $type->getFilePath($this); $o = new \stdClass(); $o->visibility = AdapterInterface::VISIBILITY_PUBLIC; $o->mimetype = 'image/jpeg'; $filesystem->write($thumbnailPath, $thumbnail->get('jpg', array('jpeg_quality' => 60)), array('visibility' => AdapterInterface::VISIBILITY_PUBLIC, 'mimetype' => 'image/jpeg')); if ($type->getHandle() == \Config::get('concrete.icons.file_manager_listing.handle')) { $this->fvHasListingThumbnail = true; } if ($type->getHandle() == \Config::get('concrete.icons.file_manager_detail.handle')) { $this->fvHasDetailThumbnail = true; } } }
public function rescanThumbnails() { if ($this->fvType != \Concrete\Core\File\Type\Type::T_IMAGE) { return false; } $types = Type::getVersionList(); $fr = $this->getFileResource(); try { $image = \Image::load($fr->read()); $mimetype = $fr->getMimeType(); foreach ($types as $type) { // delete the file if it exists $this->deleteThumbnail($type); if ($this->getAttribute('width') <= $type->getWidth()) { continue; } $filesystem = $this->getFile()->getFileStorageLocationObject()->getFileSystemObject(); $height = $type->getHeight(); $thumbnailMode = ImageInterface::THUMBNAIL_OUTBOUND; if (!$height) { $height = $type->getWidth(); $thumbnailMode = ImageInterface::THUMBNAIL_INSET; } $thumbnail = $image->thumbnail(new \Imagine\Image\Box($type->getWidth(), $height), $thumbnailMode); $thumbnailPath = $type->getFilePath($this); $thumbnailOptions = array(); switch ($mimetype) { case 'image/jpeg': $thumbnailType = 'jpeg'; $thumbnailOptions = array('jpeg_quality' => \Config::get('concrete.misc.default_jpeg_image_compression')); break; case 'image/png': $thumbnailType = 'png'; break; case 'image/gif': $thumbnailType = 'gif'; break; case 'image/xbm': $thumbnailType = 'xbm'; break; case 'image/vnd.wap.wbmp': $thumbnailType = 'wbmp'; break; default: $thumbnailType = 'png'; break; } $filesystem->write($thumbnailPath, $thumbnail->get($thumbnailType, $thumbnailOptions), array('visibility' => AdapterInterface::VISIBILITY_PUBLIC, 'mimetype' => $mimetype)); if ($type->getHandle() == \Config::get('concrete.icons.file_manager_listing.handle')) { $this->fvHasListingThumbnail = true; } if ($type->getHandle() == \Config::get('concrete.icons.file_manager_detail.handle')) { $this->fvHasDetailThumbnail = true; } unset($thumbnail); unset($filesystem); } } catch (ImagineInvalidArgumentException $e) { return false; } }
/** * Edit a user */ public function edit($params) { $this->setView('edit.php'); $is_logged = isset(User_Model::$auth_data); $is_admin = $is_logged && User_Model::$auth_data['admin'] == '1'; // Authorization if (!$is_admin) { throw new ActionException('Page', 'error404'); } try { $student = $this->model->getInfo($params['username']); } catch (Exception $e) { throw new ActionException('Page', 'error404'); } $this->setTitle(__('STUDENT_EDIT_TITLE', array('username' => $student['username']))); // Birthday $student['birthday'] = date(__('USER_EDIT_FORM_BIRTHDAY_FORMAT'), strtotime($student['birthday'])); // Saving data if (isset($_POST['mail']) && isset($_POST['msn']) && isset($_POST['jabber']) && isset($_POST['address']) && isset($_POST['zipcode']) && isset($_POST['city']) && isset($_POST['cellphone']) && isset($_POST['phone']) && isset($_POST['birthday']) && isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['student_number']) && isset($_POST['promo'])) { $uploaded_files = array(); try { // Other info $user_data = array('mail' => $_POST['mail'], 'msn' => $_POST['msn'], 'jabber' => $_POST['jabber'], 'address' => $_POST['address'], 'zipcode' => $_POST['zipcode'], 'city' => $_POST['city'], 'cellphone' => $_POST['cellphone'], 'phone' => $_POST['phone'], 'birthday' => $_POST['birthday']); $student_data = array('firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname'], 'student_number' => $_POST['student_number'], 'promo' => $_POST['promo'], 'cesure' => isset($_POST['cesure'])); // Avatar if (isset($_FILES['avatar']) && !is_array($_FILES['avatar']['name'])) { if ($_FILES['avatar']['size'] > Config::UPLOAD_MAX_SIZE_PHOTO) { throw new FormException('avatar'); } if ($avatarpath = File::upload('avatar')) { $uploaded_files[] = $avatarpath; try { $img = new Image(); $img->load($avatarpath); $type = $img->getType(); if ($type == IMAGETYPE_JPEG) { $ext = 'jpg'; } else { if ($type == IMAGETYPE_GIF) { $ext = 'gif'; } else { if ($type == IMAGETYPE_PNG) { $ext = 'png'; } else { throw new Exception(); } } } if ($img->getWidth() > 800) { $img->setWidth(800, true); } $img->setType(IMAGETYPE_JPEG); $img->save($avatarpath); // Thumb $avatarthumbpath = $avatarpath . '.thumb'; $img->thumb(Config::$AVATARS_THUMBS_SIZES[0], Config::$AVATARS_THUMBS_SIZES[1]); $img->setType(IMAGETYPE_JPEG); $img->save($avatarthumbpath); unset($img); $uploaded_files[] = $avatarthumbpath; $student_data['avatar_path'] = $avatarthumbpath; $student_data['avatar_big_path'] = $avatarpath; } catch (Exception $e) { throw new FormException('avatar'); } } } $user_model = new User_Model(); $user_model->save((int) $student['id'], $user_data); $this->model->save($student['username'], $student_data); Routes::redirect('student', array('username' => $params['username'])); } catch (FormException $e) { foreach ($uploaded_files as $uploaded_file) { File::delete($uploaded_file); } foreach ($student_data as $key => $value) { $student[$key] = $value; } foreach ($user_data as $key => $value) { $student[$key] = $value; } $this->set('form_error', $e->getError()); } } $this->set('student', $student); $this->addJSCode('User.initEdit();'); }
function check_directory_blacklisted($dblink, $token_id, $session, $path, $image = false) { # Adding a slash to our path $path .= substr($path, -1, 1) == '/' ? '' : '/'; $blacklisted = false; # If we have blacklist enabled if (NQ_BLACKLIST_ENABLED) { # Checking our blackist table $query = "\tSELECT\n\t\t\t\t\t\t\t`path`\n\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t" . NQ_BLACKLIST_PATH_TABLE . "\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t`token_id`\t=" . (int) $token_id . " AND\n\t\t\t\t\t\t\t`path` \t\t=LEFT('" . mysqli_escape_string($dblink, $path) . "',LENGTH(`path`)) \n\t\t\t\t\t\tLIMIT 1"; $blackist_data = mysqli_single_result_query($dblink, $query); # Failing if we have a blacklisted path $blacklisted = isset($blackist_data['path']); # Checking our sessions blacklist if (!$blacklisted && isset($session->{NQ_SESSION_GROUP}->blacklist)) { # Matching any that start with our path foreach ($session->{NQ_SESSION_GROUP}->blacklist as $blacklist) { if ($blacklist == substr($path, 0, strlen($blacklist))) { $blacklisted = true; break; } } } # If we are enabling a whitelist if (NQ_WHITELIST_ENABLED) { # Checking our sessions whitelist if ($blacklisted && isset($session->{NQ_SESSION_GROUP}->whitelist)) { # Matching any that start with our path foreach ($session->{NQ_SESSION_GROUP}->whitelist as $whitelist) { if ($whitelist == substr($path, 0, strlen($whitelist))) { $blacklisted = false; break; } } } # Checking for whitelist if ($blacklisted) { # Checking our whitelist table $query = "\tSELECT\n\t\t\t\t\t\t\t\t\t`path`\n\t\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\t\t" . NQ_WHITELIST_PATH_TABLE . "\n\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t`token_id`\t=" . (int) $token_id . " AND\n\t\t\t\t\t\t\t\t\t`path`\t\t=LEFT('" . mysqli_escape_string($dblink, $path) . "',LENGTH(`path`)) \n\t\t\t\t\t\t\t\tLIMIT 1"; $whitelist_data = mysqli_single_result_query($dblink, $query); # Failing if we have a blacklisted path $blacklisted = !isset($whitelist_data['path']); } # Leaving if we are bad if ($blacklisted) { # We are blacklisting an image if ($image) { # Loading our blacklist image $img = new Image(); $img->load(NQ_BLACKLIST_IMAGE_FILE); # Sending our image $img->headerOutput(); $img->output(); exit; } # Non-image exit exit_fail(NQ_ERROR_INVALID_VALUE, str_replace('%path%', $path, LANG_BLACKLIST_PATH_DENIED)); } } } }
/** * use for remove exif. */ public static function resave($file_path) { return Image::load($file_path)->save($file_path); }
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * @author [creator, or "Original Author"] * @license http://bit.ly/aVWqRV PayAsYouGo License * @copyright Copyright (c) 2010 Broadband Mechanics * @package PeopleAggregator */ $login_required = FALSE; $use_theme = 'Beta'; //TODO : Remove this when new UI is completely implemented. include_once "web/includes/page.php"; require_once "api/Image/Image.php"; // Now we are trying to get the data from the given id if (!empty($_GET['img_id'])) { $data_array = explode('_', $_GET['img_id']); $show_media = new Image(); $show_media->load($data_array[1]); if (strstr($show_media->file_name, 'http://')) { $image_val['url'] = $show_media->file_name; } else { if (!empty($show_media->file_name)) { // Now we fatching all the data related to the image and display it $image_val = uihelper_resize_img($show_media->file_name, 220, 200, PA::$theme_rel . "/images/no_preview.gif", 'alt="Media gallery"'); } else { // handling the SB image $var = $show_media->body; $start = strpos($var, '<image>') + 7; $end = strpos($var, '</image>'); $image_val['url'] = substr($var, $start, $end - $start); $show_media->body = $show_media->title; } }
public static function uploadPicture() { $join_id = Input::get('object_id'); $type = Input::get('object_type'); $user_id = Input::get('user_id'); $join_type = self::JOINTYPE_UPLOAD; $uploader = new Utils_Uploader(array('jpeg', 'jpg', 'png')); $path = DOCROOT . 'assets/uploads' . DS; if (!file_exists($path)) { mkdir($path, 0777, true); } $uploadTypeModel = Model_Upload_Type::find($type); $typeName = $uploadTypeModel->types; $pic_name = $typeName . "_" . time(); $original = $path . $pic_name; $output = $uploader->handleUploadRename($path, $pic_name); if (isset($output['success'])) { $original = $path . $output['full_filename']; $uploadAll = Model_Upload::forge(); $uploadAll->user_id = $user_id; $uploadAll->type_id = $type; $uploadAll->join_id = $join_id; $uploadAll->join_type = $join_type; $uploadAll->name = $output['full_filename']; $uploadAll->original_name = $output['full_filename']; #You can change this name to article name $uploadAll->path = $path; $uploadAll->save(); $output['upload_id'] = $uploadAll->id; if ($uploadTypeModel->crop == 0) { #If not set crop then preset other preset after crop Image::load($original)->preset($typeName)->save($original); } else { // Image::load($original)->preset('banner')->save($original); #check if height and width do not match } if (filesize($original) < 102400) { //Do nothing } else { if (filesize($original) < 524288) { self::compress($original, $original, 90); } elseif (filesize($original) < 1048576) { //1MB self::compress($original, $original, 75); } elseif (filesize($original) < 3145728) { //3MB self::compress($original, $original, 60); } elseif (filesize($original) < 6291456) { //6MB self::compress($original, $original, 40); } else { self::compress($original, $original, 30); } } $localFileName = $path . $output['full_filename']; $remoteFileName = DOCROOT . 'assets/uploads/' . DS . $output['full_filename']; $output['uri'] = Uri::create('upload/get_image/' . $output['full_filename'] . '/' . $output['upload_id']); } return $output; }
public function save($value) { $flag = $this->module->flag; $path = File::formatDir($this->path); $destPath = static::storagePath() . File::formatDir($this->path); File::mkdir($destPath); if (!is_writable($destPath)) { Response::code(500); return Response::json(array("error" => true, "error_description" => "Directory '" . $destPath . "' is not writtable.")); } $files = json_decode(Session::get($this->sessionKey), true); if ($flag == "U" || $flag == "D") { $oldFiles = $this->module->orm->field($this->name); if (!is_array(@json_decode($oldFiles, true))) { $oldFiles = json_encode(array()); } $oldFiles = json_decode($oldFiles, true); if ($flag == "U") { //Delete files that are on our table but not on our session list foreach ($oldFiles as $oldFile) { $found = false; foreach ($files as $file) { if (!array_key_exists("_tmpName", $file) && current($oldFile) == current($file)) { $found = true; break; } } if (!$found) { foreach ($oldFile as $sample) { File::delete(static::storagePath() . $sample); } } } } else { if ($flag == "D") { //Delete all files foreach ($oldFiles as $oldFile) { foreach ($oldFile as $sample) { File::delete(static::storagePath() . $sample); } } if (count(File::lsdir($destPath)) == 0) { File::rmdir($destPath); } } } } if ($flag == "C" || $flag == "U") { //Copy tmp files to it's target place and save foreach ($files as $k => $file) { if (array_key_exists("_tmpName", $file)) { $samples = array(); $im = new Image(); $i = 0; $tmpPath = static::tmpPath() . $file["_tmpName"]; foreach ($this->samples as $k2 => $sample) { //if ($k2 == 0) //{ $im->load($tmpPath); //} if (!array_key_exists("width", $sample)) { $sample["width"] = 0; } if (!array_key_exists("height", $sample)) { $sample["height"] = 0; } if ($sample["width"] != 0 || $sample["height"] != 0) { $im->resize($sample["width"], $sample["height"], $sample["resizeMethod"], $sample["background"]); } if ($this->customFilters) { foreach ($this->customFilters as $filter) { call_user_func($filter, $im); } } $fileName = $file["_name"]; if ($sample["key"] != "original") { $fileName = File::removeExtension($file["_name"]) . "-" . $sample["key"] . "." . File::extension($file["_name"]); } $unique = static::unique($destPath . $fileName); $im->save($unique); $samples[$sample["key"]] = $path . File::fileName($unique); $samples["caption"] = array_key_exists('caption', $file) ? $file['caption'] : ""; $i++; } File::delete($tmpPath); $files[$k] = $samples; } } $this->module->orm->setField($this->name, json_encode($files)); } }