/** * Override this method to take certain actions before the data is saved * * @uses System::mkdir * @uses Upload::save * @uses Debug::path * @uses File::getUnique */ protected function before_save() { if (isset($_FILES['image']['name']) and !empty($_FILES['image']['name'])) { // create directory if not System::mkdir($this->_image_path); // delete previous image if exists, to cleanup stale images $this->_delete_image(); // generate a unique filename to avoid conflicts $filename = File::getUnique($_FILES['image']['name']); if ($file = Upload::save($_FILES['image'], $filename, $this->_image_path)) { $this->image = $filename; } } }
/** * Picture validation for image upload * * @param array $file $_FILES item * @param string $upload_dir Relative upload dir [Optional] * * Example: * ~~~ * $filepath = Upload::uploadImage($_FILES); * ~~~ * * @since 1.2.0 * * @return NULL|string NULL when filed, otherwise file path * * @uses System::mkdir * @uses Message::error * @uses Log::error * @uses Upload::valid * @uses Upload::save * @uses Config::get * @uses File::getUnique */ public static function uploadImage($file, $upload_dir = NULL) { if (is_null($upload_dir)) { $upload_dir = Config::get('media.upload_dir', 'media/pictures'); } $picture_path = APPPATH . $upload_dir; $valid_formats = Config::get('media.supported_image_formats', array('jpg', 'gif', 'png')); $save = TRUE; if (!is_dir($picture_path)) { if (!System::mkdir($picture_path)) { Message::error(__('Failed to create directory %dir for uploading picture.')); Log::error('Failed to create directory :dir for uploading picture.', array(':dir' => $picture_path)); $save = FALSE; } } // Check if there is an uploaded file and valid type if ($save and self::valid($file) and self::type($file, $valid_formats) and self::size($file, self::getUploadMaxFilesize())) { $filename = File::getUnique($file['name']) . '.' . pathinfo($file['name'], PATHINFO_EXTENSION); $path = self::save($file, $filename, $picture_path); if ($path) { return $upload_dir . DS . $filename; } } return NULL; }